Merges xwork packages into struts

This commit is contained in:
Lukasz Lenart
2015-06-17 23:08:29 +02:00
parent 31af5842e0
commit 82cb1286cd
190 changed files with 8921 additions and 0 deletions
@@ -0,0 +1,44 @@
/*
* 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 com.opensymphony.xwork2.config.entities;
import com.opensymphony.xwork2.XWorkTestCase;
import com.opensymphony.xwork2.util.location.LocationImpl;
/**
* ActionConfigTest
*/
public class ActionConfigTest extends XWorkTestCase {
public void testToString() {
ActionConfig cfg = new ActionConfig.Builder("", "bob", "foo.Bar")
.methodName("execute")
.location(new LocationImpl(null, "foo/xwork.xml", 10, 12))
.build();
assertTrue("Wrong toString(): "+cfg.toString(),
"{ActionConfig bob (foo.Bar.execute()) - foo/xwork.xml:10:12}".equals(cfg.toString()));
}
public void testToStringWithNoMethod() {
ActionConfig cfg = new ActionConfig.Builder("", "bob", "foo.Bar")
.location(new LocationImpl(null, "foo/xwork.xml", 10, 12))
.build();
assertTrue("Wrong toString(): "+cfg.toString(),
"{ActionConfig bob (foo.Bar) - foo/xwork.xml:10:12}".equals(cfg.toString()));
}
}
@@ -0,0 +1,34 @@
/*
* 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 com.opensymphony.xwork2.config.entities;
import com.opensymphony.xwork2.XWorkTestCase;
public class PackageConfigTest extends XWorkTestCase {
public void testFullDefaultInterceptorRef() {
PackageConfig cfg1 = new PackageConfig.Builder("pkg1")
.defaultInterceptorRef("ref1").build();
PackageConfig cfg2 = new PackageConfig.Builder("pkg2").defaultInterceptorRef("ref2").build();
PackageConfig cfg = new PackageConfig.Builder("pkg")
.addParent(cfg1)
.addParent(cfg2)
.build();
assertEquals("ref2", cfg.getFullDefaultInterceptorRef());
}
}
@@ -0,0 +1,164 @@
/*
* $Id$
*
* Copyright 1999-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 com.opensymphony.xwork2.config.impl;
import com.opensymphony.xwork2.XWorkTestCase;
import com.opensymphony.xwork2.config.entities.ActionConfig;
import com.opensymphony.xwork2.config.entities.ExceptionMappingConfig;
import com.opensymphony.xwork2.config.entities.InterceptorMapping;
import com.opensymphony.xwork2.config.entities.ResultConfig;
import java.util.HashMap;
import java.util.Map;
public class ActionConfigMatcherTest extends XWorkTestCase {
// ----------------------------------------------------- Instance Variables
private Map<String,ActionConfig> configMap;
private ActionConfigMatcher matcher;
// ----------------------------------------------------- Setup and Teardown
@Override public void setUp() throws Exception {
super.setUp();
configMap = buildActionConfigMap();
matcher = new ActionConfigMatcher(configMap);
}
@Override public void tearDown() throws Exception {
super.tearDown();
}
// ------------------------------------------------------- Individual Tests
// ---------------------------------------------------------- match()
public void testNoMatch() {
assertNull("ActionConfig shouldn't be matched", matcher.match("test"));
}
public void testNoWildcardMatch() {
assertNull("ActionConfig shouldn't be matched", matcher.match("noWildcard"));
}
public void testShouldMatch() {
ActionConfig matched = matcher.match("foo/class/method");
assertNotNull("ActionConfig should be matched", matched);
assertTrue("ActionConfig should have properties, had " +
matched.getParams().size(), matched.getParams().size() == 2);
assertTrue("ActionConfig should have interceptors",
matched.getInterceptors().size() == 1);
assertTrue("ActionConfig should have ex mappings",
matched.getExceptionMappings().size() == 1);
assertTrue("ActionConfig should have external refs",
matched.getExceptionMappings().size() == 1);
assertTrue("ActionConfig should have results",
matched.getResults().size() == 1);
}
public void testCheckSubstitutionsMatch() {
ActionConfig m = matcher.match("foo/class/method");
assertTrue("Class hasn't been replaced", "foo.bar.classAction".equals(m.getClassName()));
assertTrue("Method hasn't been replaced", "domethod".equals(m.getMethodName()));
assertTrue("Package isn't correct", "package-class".equals(m.getPackageName()));
assertTrue("First param isn't correct", "class".equals(m.getParams().get("first")));
assertTrue("Second param isn't correct", "method".equals(m.getParams().get("second")));
ExceptionMappingConfig ex = m.getExceptionMappings().get(0);
assertTrue("Wrong name, was "+ex.getName(), "fooclass".equals(ex.getName()));
assertTrue("Wrong result", "successclass".equals(ex.getResult()));
assertTrue("Wrong exception",
"java.lang.methodException".equals(ex.getExceptionClassName()));
assertTrue("First param isn't correct", "class".equals(ex.getParams().get("first")));
assertTrue("Second param isn't correct", "method".equals(ex.getParams().get("second")));
ResultConfig result = m.getResults().get("successclass");
assertTrue("Wrong name, was "+result.getName(), "successclass".equals(result.getName()));
assertTrue("Wrong classname", "foo.method".equals(result.getClassName()));
assertTrue("First param isn't correct", "class".equals(result.getParams().get("first")));
assertTrue("Second param isn't correct", "method".equals(result.getParams().get("second")));
}
public void testCheckMultipleSubstitutions() {
ActionConfig m = matcher.match("bar/class/method/more");
assertTrue("Method hasn't been replaced correctly: " + m.getMethodName(),
"doclass_class".equals(m.getMethodName()));
}
public void testLooseMatch() {
configMap.put("*!*", configMap.get("bar/*/**"));
ActionConfigMatcher matcher = new ActionConfigMatcher(configMap, true);
// exact match
ActionConfig m = matcher.match("foo/class/method");
assertNotNull("ActionConfig should be matched", m);
assertTrue("Class hasn't been replaced "+m.getClassName(), "foo.bar.classAction".equals(m.getClassName()));
assertTrue("Method hasn't been replaced", "domethod".equals(m.getMethodName()));
// Missing last wildcard
m = matcher.match("foo/class");
assertNotNull("ActionConfig should be matched", m);
assertTrue("Class hasn't been replaced", "foo.bar.classAction".equals(m.getClassName()));
assertTrue("Method hasn't been replaced, "+m.getMethodName(), "do".equals(m.getMethodName()));
// Simple mapping
m = matcher.match("class!method");
assertNotNull("ActionConfig should be matched", m);
assertTrue("Class hasn't been replaced, "+m.getPackageName(), "package-class".equals(m.getPackageName()));
assertTrue("Method hasn't been replaced", "method".equals(m.getParams().get("first")));
// Simple mapping
m = matcher.match("class");
assertNotNull("ActionConfig should be matched", m);
assertTrue("Class hasn't been replaced", "package-class".equals(m.getPackageName()));
assertTrue("Method hasn't been replaced", "".equals(m.getParams().get("first")));
}
private Map<String,ActionConfig> buildActionConfigMap() {
Map<String, ActionConfig> map = new HashMap<>();
HashMap<String, String> params = new HashMap<>();
params.put("first", "{1}");
params.put("second", "{2}");
ActionConfig config = new ActionConfig.Builder("package-{1}", "foo/*/*", "foo.bar.{1}Action")
.methodName("do{2}")
.addParams(params)
.addExceptionMapping(new ExceptionMappingConfig.Builder("foo{1}", "java.lang.{2}Exception", "success{1}")
.addParams(new HashMap<>(params))
.build())
.addInterceptor(new InterceptorMapping(null, null))
.addResultConfig(new ResultConfig.Builder("success{1}", "foo.{2}").addParams(params).build())
.build();
map.put("foo/*/*", config);
config = new ActionConfig.Builder("package-{1}", "bar/*/**", "bar")
.methodName("do{1}_{1}")
.addParam("first", "{2}")
.build();
map.put("bar/*/**", config);
map.put("noWildcard", new ActionConfig.Builder("", "", "").build());
return map;
}
}
@@ -0,0 +1,41 @@
/*
* 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 com.opensymphony.xwork2.config.impl;
import com.opensymphony.xwork2.util.WildcardHelper;
import junit.framework.TestCase;
import java.util.HashSet;
import java.util.Set;
public class NamespaceMatcherTest extends TestCase {
public void testMatch() {
Set<String> names = new HashSet<>();
names.add("/bar");
names.add("/foo/*/bar");
names.add("/foo/*");
names.add("/foo/*/jim/*");
NamespaceMatcher matcher = new NamespaceMatcher(new WildcardHelper(), names);
assertEquals(3, matcher.compiledPatterns.size());
assertNull(matcher.match("/asd"));
assertEquals("/foo/*", matcher.match("/foo/23").getPattern());
assertEquals("/foo/*/bar", matcher.match("/foo/23/bar").getPattern());
assertEquals("/foo/*/jim/*", matcher.match("/foo/23/jim/42").getPattern());
assertNull(matcher.match("/foo/23/asd"));
}
}
@@ -0,0 +1,45 @@
/*
* 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 com.opensymphony.xwork2.config.providers;
import com.opensymphony.xwork2.FileManagerFactory;
import com.opensymphony.xwork2.ObjectFactory;
import com.opensymphony.xwork2.XWorkTestCase;
import com.opensymphony.xwork2.config.ConfigurationProvider;
import com.opensymphony.xwork2.config.impl.MockConfiguration;
/**
* ConfigurationTestBase
*
* @author Jason Carreira
* Created Jun 9, 2003 7:42:12 AM
*/
public abstract class ConfigurationTestBase extends XWorkTestCase {
protected ConfigurationProvider buildConfigurationProvider(final String filename) {
configuration = new MockConfiguration();
((MockConfiguration)configuration).selfRegister();
container = configuration.getContainer();
XmlConfigurationProvider prov = new XmlConfigurationProvider(filename, true);
prov.setObjectFactory(container.getInstance(ObjectFactory.class));
prov.setFileManagerFactory(container.getInstance(FileManagerFactory.class));
prov.init(configuration);
prov.loadPackages();
return prov;
}
}
@@ -0,0 +1,274 @@
package com.opensymphony.xwork2.config.providers;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ObjectFactory;
import com.opensymphony.xwork2.XWorkTestCase;
import com.opensymphony.xwork2.config.entities.InterceptorConfig;
import com.opensymphony.xwork2.config.entities.InterceptorMapping;
import com.opensymphony.xwork2.config.entities.InterceptorStackConfig;
import com.opensymphony.xwork2.config.entities.PackageConfig;
import com.opensymphony.xwork2.interceptor.Interceptor;
import java.util.LinkedHashMap;
import java.util.List;
/**
* <code>InterceptorBuilderTest</code>
*
* @author <a href="mailto:hermanns@aixcept.de">Rainer Hermanns</a>
* @version $Id$
*/
public class InterceptorBuilderTest extends XWorkTestCase {
ObjectFactory objectFactory;
@Override
public void setUp() throws Exception {
super.setUp();
objectFactory = container.getInstance(ObjectFactory.class);
}
/**
* Try to test this
* <interceptor-ref name="interceptorStack1">
* <param name="interceptor1.param1">interceptor1_value1</param>
* <param name="interceptor1.param2">interceptor1_value2</param>
* <param name="interceptor2.param1">interceptor2_value1</param>
* <param name="interceptor2.param2">interceptor2_value2</param>
* </interceptor-ref>
*
* @throws Exception
*/
public void testBuildInterceptor_1() throws Exception {
InterceptorStackConfig interceptorStackConfig1 = new InterceptorStackConfig.Builder("interceptorStack1").build();
InterceptorConfig interceptorConfig1 = new InterceptorConfig.Builder("interceptor1", "com.opensymphony.xwork2.config.providers.InterceptorBuilderTest$MockInterceptor1").build();
InterceptorConfig interceptorConfig2 = new InterceptorConfig.Builder("interceptor2", "com.opensymphony.xwork2.config.providers.InterceptorBuilderTest$MockInterceptor2").build();
PackageConfig packageConfig = new PackageConfig.Builder("package1").namespace("/namespace").addInterceptorConfig(interceptorConfig1).addInterceptorConfig(interceptorConfig2).addInterceptorStackConfig(interceptorStackConfig1).build();
List
interceptorMappings =
InterceptorBuilder.constructInterceptorReference(packageConfig, "interceptorStack1",
new LinkedHashMap<String, String>() {
private static final long serialVersionUID = -1358620486812957895L;
{
put("interceptor1.param1", "interceptor1_value1");
put("interceptor1.param2", "interceptor1_value2");
put("interceptor2.param1", "interceptor2_value1");
put("interceptor2.param2", "interceptor2_value2");
}
},null, objectFactory);
assertEquals(interceptorMappings.size(), 2);
assertEquals(((InterceptorMapping) interceptorMappings.get(0)).getName(), "interceptor1");
assertNotNull(((InterceptorMapping) interceptorMappings.get(0)).getInterceptor());
assertEquals(((InterceptorMapping) interceptorMappings.get(0)).getInterceptor().getClass(), MockInterceptor1.class);
assertEquals(((MockInterceptor1) ((InterceptorMapping) interceptorMappings.get(0)).getInterceptor()).getParam1(), "interceptor1_value1");
assertEquals(((MockInterceptor1) ((InterceptorMapping) interceptorMappings.get(0)).getInterceptor()).getParam2(), "interceptor1_value2");
assertEquals(((InterceptorMapping) interceptorMappings.get(1)).getName(), "interceptor2");
assertNotNull(((InterceptorMapping) interceptorMappings.get(1)).getInterceptor());
assertEquals(((InterceptorMapping) interceptorMappings.get(1)).getInterceptor().getClass(), MockInterceptor2.class);
assertEquals(((MockInterceptor2) ((InterceptorMapping) interceptorMappings.get(1)).getInterceptor()).getParam1(), "interceptor2_value1");
assertEquals(((MockInterceptor2) ((InterceptorMapping) interceptorMappings.get(1)).getInterceptor()).getParam2(), "interceptor2_value2");
}
/**
* Try to test this
* <interceptor-ref name="interceptorStack1">
* <param name="interceptorStack2.interceptor1.param1">interceptor1_value1</param>
* <param name="interceptorStack2.interceptor1.param2">interceptor1_value2</param>
* <param name="interceptorStack3.interceptor2.param1">interceptor2_value1</param>
* <param name="interceptorStack3.interceptor2.param2">interceptor2_value2</param>
* </interceptor-ref>
*
* @throws Exception
*/
public void testBuildInterceptor_2() throws Exception {
InterceptorStackConfig interceptorStackConfig1 = new InterceptorStackConfig.Builder("interceptorStack1").build();
InterceptorStackConfig interceptorStackConfig2 = new InterceptorStackConfig.Builder("interceptorStack2").build();
InterceptorStackConfig interceptorStackConfig3 = new InterceptorStackConfig.Builder("interceptorStack3").build();
InterceptorConfig interceptorConfig1 = new InterceptorConfig.Builder("interceptor1", "com.opensymphony.xwork2.config.providers.InterceptorBuilderTest$MockInterceptor1").build();
InterceptorConfig interceptorConfig2 = new InterceptorConfig.Builder("interceptor2", "com.opensymphony.xwork2.config.providers.InterceptorBuilderTest$MockInterceptor2").build();
PackageConfig packageConfig = new PackageConfig.Builder("package1").namespace("/namspace").
addInterceptorConfig(interceptorConfig1).
addInterceptorConfig(interceptorConfig2).
addInterceptorStackConfig(interceptorStackConfig1).
addInterceptorStackConfig(interceptorStackConfig2).
addInterceptorStackConfig(interceptorStackConfig3).build();
List interceptorMappings = InterceptorBuilder.constructInterceptorReference(packageConfig, "interceptorStack1",
new LinkedHashMap<String, String>() {
private static final long serialVersionUID = -5819935102242042570L;
{
put("interceptorStack2.interceptor1.param1", "interceptor1_value1");
put("interceptorStack2.interceptor1.param2", "interceptor1_value2");
put("interceptorStack3.interceptor2.param1", "interceptor2_value1");
put("interceptorStack3.interceptor2.param2", "interceptor2_value2");
}
}, null, objectFactory);
assertEquals(interceptorMappings.size(), 2);
assertEquals(((InterceptorMapping) interceptorMappings.get(0)).getName(), "interceptor1");
assertNotNull(((InterceptorMapping) interceptorMappings.get(0)).getInterceptor());
assertEquals(((InterceptorMapping) interceptorMappings.get(0)).getInterceptor().getClass(), MockInterceptor1.class);
assertEquals(((MockInterceptor1) ((InterceptorMapping) interceptorMappings.get(0)).getInterceptor()).getParam1(), "interceptor1_value1");
assertEquals(((MockInterceptor1) ((InterceptorMapping) interceptorMappings.get(0)).getInterceptor()).getParam2(), "interceptor1_value2");
assertEquals(((InterceptorMapping) interceptorMappings.get(1)).getName(), "interceptor2");
assertNotNull(((InterceptorMapping) interceptorMappings.get(1)).getInterceptor());
assertEquals(((InterceptorMapping) interceptorMappings.get(1)).getInterceptor().getClass(), MockInterceptor2.class);
assertEquals(((MockInterceptor2) ((InterceptorMapping) interceptorMappings.get(1)).getInterceptor()).getParam1(), "interceptor2_value1");
assertEquals(((MockInterceptor2) ((InterceptorMapping) interceptorMappings.get(1)).getInterceptor()).getParam2(), "interceptor2_value2");
}
/**
* Try to test this
* <interceptor-ref name="interceptorStack1">
* <param name="interceptorStack2.interceptorStack3.interceptorStack4.interceptor1.param1">interceptor1_value1</param>
* <param name="interceptorStack2.interceptorStack3.interceptorStack4.interceptor1.param2">interceptor1_value2</param>
* <param name="interceptorStack5.interceptor2.param1">interceptor2_value1</param>
* <param name="interceptorStack5.interceptor2.param2">interceptor2_value2</param>
* </interceptor-ref>
*
* @throws Exception
*/
public void testBuildInterceptor_3() throws Exception {
InterceptorConfig interceptorConfig1 = new InterceptorConfig.Builder("interceptor1", "com.opensymphony.xwork2.config.providers.InterceptorBuilderTest$MockInterceptor1").build();
InterceptorConfig interceptorConfig2 = new InterceptorConfig.Builder("interceptor2", "com.opensymphony.xwork2.config.providers.InterceptorBuilderTest$MockInterceptor2").build();
InterceptorStackConfig interceptorStackConfig1 = new InterceptorStackConfig.Builder("interceptorStack1").build();
InterceptorStackConfig interceptorStackConfig2 = new InterceptorStackConfig.Builder("interceptorStack2").build();
InterceptorStackConfig interceptorStackConfig3 = new InterceptorStackConfig.Builder("interceptorStack3").build();
InterceptorStackConfig interceptorStackConfig4 = new InterceptorStackConfig.Builder("interceptorStack4").build();
InterceptorStackConfig interceptorStackConfig5 = new InterceptorStackConfig.Builder("interceptorStack5").build();
PackageConfig packageConfig = new PackageConfig.Builder("package1").
addInterceptorConfig(interceptorConfig1).
addInterceptorConfig(interceptorConfig2).
addInterceptorStackConfig(interceptorStackConfig1).
addInterceptorStackConfig(interceptorStackConfig2).
addInterceptorStackConfig(interceptorStackConfig3).
addInterceptorStackConfig(interceptorStackConfig4).
addInterceptorStackConfig(interceptorStackConfig5).build();
List interceptorMappings = InterceptorBuilder.constructInterceptorReference(
packageConfig, "interceptorStack1",
new LinkedHashMap<String, String>() {
private static final long serialVersionUID = 4675809753780875525L;
{
put("interceptorStack2.interceptorStack3.interceptorStack4.interceptor1.param1", "interceptor1_value1");
put("interceptorStack2.interceptorStack3.interceptorStack4.interceptor1.param2", "interceptor1_value2");
put("interceptorStack5.interceptor2.param1", "interceptor2_value1");
put("interceptorStack5.interceptor2.param2", "interceptor2_value2");
}
}, null, objectFactory);
assertEquals(interceptorMappings.size(), 2);
assertEquals(((InterceptorMapping) interceptorMappings.get(0)).getName(), "interceptor1");
assertNotNull(((InterceptorMapping) interceptorMappings.get(0)).getInterceptor());
assertEquals(((InterceptorMapping) interceptorMappings.get(0)).getInterceptor().getClass(), MockInterceptor1.class);
assertEquals(((MockInterceptor1) ((InterceptorMapping) interceptorMappings.get(0)).getInterceptor()).getParam1(), "interceptor1_value1");
assertEquals(((MockInterceptor1) ((InterceptorMapping) interceptorMappings.get(0)).getInterceptor()).getParam2(), "interceptor1_value2");
assertEquals(((InterceptorMapping) interceptorMappings.get(1)).getName(), "interceptor2");
assertNotNull(((InterceptorMapping) interceptorMappings.get(1)).getInterceptor());
assertEquals(((InterceptorMapping) interceptorMappings.get(1)).getInterceptor().getClass(), MockInterceptor2.class);
assertEquals(((MockInterceptor2) ((InterceptorMapping) interceptorMappings.get(1)).getInterceptor()).getParam1(), "interceptor2_value1");
assertEquals(((MockInterceptor2) ((InterceptorMapping) interceptorMappings.get(1)).getInterceptor()).getParam2(), "interceptor2_value2");
}
public static class MockInterceptor1 implements Interceptor {
private static final long serialVersionUID = 2939902550126175874L;
private String param1;
private String param2;
public void setParam1(String param1) {
this.param1 = param1;
}
public String getParam1() {
return this.param1;
}
public void setParam2(String param2) {
this.param2 = param2;
}
public String getParam2() {
return this.param2;
}
public void destroy() {
}
public void init() {
}
public String intercept(ActionInvocation invocation) throws Exception {
return invocation.invoke();
}
}
public static class MockInterceptor2 implements Interceptor {
private static final long serialVersionUID = 267427973306989618L;
private String param1;
private String param2;
public void setParam1(String param1) {
this.param1 = param1;
}
public String getParam1() {
return this.param1;
}
public void setParam2(String param2) {
this.param2 = param2;
}
public String getParam2() {
return this.param2;
}
public void destroy() {
}
public void init() {
}
public String intercept(ActionInvocation invocation) throws Exception {
return invocation.invoke();
}
}
}
@@ -0,0 +1,47 @@
/*
* 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 com.opensymphony.xwork2.config.providers;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
/**
*
* @author tm_jee
* @version $Date$ $Id$
*/
public class InterceptorForTestPurpose implements Interceptor {
private String paramOne;
private String paramTwo;
public String getParamOne() { return paramOne; }
public void setParamOne(String paramOne) { this.paramOne = paramOne; }
public String getParamTwo() { return paramTwo; }
public void setParamTwo(String paramTwo) { this.paramTwo = paramTwo; }
public void destroy() {
}
public void init() {
}
public String intercept(ActionInvocation invocation) throws Exception {
return invocation.invoke();
}
}
@@ -0,0 +1,194 @@
/*
* 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 com.opensymphony.xwork2.config.providers;
import com.opensymphony.xwork2.*;
import com.opensymphony.xwork2.config.Configuration;
import com.opensymphony.xwork2.config.ConfigurationException;
import com.opensymphony.xwork2.config.ConfigurationProvider;
import com.opensymphony.xwork2.config.entities.*;
import com.opensymphony.xwork2.inject.ContainerBuilder;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor;
import com.opensymphony.xwork2.interceptor.ParametersInterceptor;
import com.opensymphony.xwork2.interceptor.StaticParametersInterceptor;
import com.opensymphony.xwork2.mock.MockResult;
import com.opensymphony.xwork2.util.location.LocatableProperties;
import com.opensymphony.xwork2.validator.ValidationInterceptor;
import java.util.*;
/**
* MockConfigurationProvider provides a simple configuration class without the need for xml files, etc. for simple testing.
*
* @author $author$
* @version $Revision$
*/
public class MockConfigurationProvider implements ConfigurationProvider {
public static final String FOO_ACTION_NAME = "foo";
public static final String MODEL_DRIVEN_PARAM_TEST = "modelParamTest";
public static final String MODEL_DRIVEN_PARAM_FILTER_TEST = "modelParamFilterTest";
public static final String PARAM_INTERCEPTOR_ACTION_NAME = "parametersInterceptorTest";
public static final String VALIDATION_ACTION_NAME = "validationInterceptorTest";
public static final String VALIDATION_ALIAS_NAME = "validationAlias";
public static final String VALIDATION_SUBPROPERTY_NAME = "subproperty";
public static final String EXPRESSION_VALIDATION_ACTION = "expressionValidationAction";
private static final Map<String,String> EMPTY_STRING_MAP = Collections.emptyMap();
private Configuration configuration;
private Map<String,String> params;
private ObjectFactory objectFactory;
public MockConfigurationProvider() {}
public MockConfigurationProvider(Map<String,String> params) {
this.params = params;
}
/**
* Allows the configuration to clean up any resources used
*/
public void destroy() {
}
public void init(Configuration config) {
this.configuration = config;
}
@Inject
public void setObjectFactory(ObjectFactory fac) {
this.objectFactory = fac;
}
public void loadPackages() {
PackageConfig.Builder defaultPackageContext = new PackageConfig.Builder("defaultPackage");
Map<String, String> params = new HashMap<>();
params.put("bar", "5");
Map<String, ResultConfig> results = new HashMap<>();
Map<String, String> successParams = new HashMap<>();
successParams.put("actionName", "bar");
results.put("success", new ResultConfig.Builder("success", ActionChainResult.class.getName()).addParams(successParams).build());
ActionConfig fooActionConfig = new ActionConfig.Builder("defaultPackage", FOO_ACTION_NAME, SimpleAction.class.getName())
.addResultConfig(new ResultConfig.Builder(Action.ERROR, MockResult.class.getName()).build())
.build();
defaultPackageContext.addActionConfig(FOO_ACTION_NAME, fooActionConfig);
results = new HashMap<>();
successParams = new HashMap<>();
successParams.put("actionName", "bar");
results.put("success", new ResultConfig.Builder("success", ActionChainResult.class.getName()).addParams(successParams).build());
List<InterceptorMapping> interceptors = new ArrayList<>();
interceptors.add(new InterceptorMapping("params", new ParametersInterceptor()));
ActionConfig paramInterceptorActionConfig = new ActionConfig.Builder("defaultPackage", PARAM_INTERCEPTOR_ACTION_NAME, SimpleAction.class.getName())
.addResultConfig(new ResultConfig.Builder(Action.ERROR, MockResult.class.getName()).build())
.addInterceptors(interceptors)
.build();
defaultPackageContext.addActionConfig(PARAM_INTERCEPTOR_ACTION_NAME, paramInterceptorActionConfig);
interceptors = new ArrayList<>();
interceptors.add(new InterceptorMapping("model",
objectFactory.buildInterceptor(new InterceptorConfig.Builder("model", ModelDrivenInterceptor.class.getName()).build(), EMPTY_STRING_MAP)));
interceptors.add(new InterceptorMapping("params",
objectFactory.buildInterceptor(new InterceptorConfig.Builder("model", ParametersInterceptor.class.getName()).build(), EMPTY_STRING_MAP)));
ActionConfig modelParamActionConfig = new ActionConfig.Builder("defaultPackage", MODEL_DRIVEN_PARAM_TEST, ModelDrivenAction.class.getName())
.addInterceptors(interceptors)
.addResultConfig(new ResultConfig.Builder(Action.SUCCESS, MockResult.class.getName()).build())
.build();
defaultPackageContext.addActionConfig(MODEL_DRIVEN_PARAM_TEST, modelParamActionConfig);
//List paramFilterInterceptor=new ArrayList();
//paramFilterInterceptor.add(new ParameterFilterInterC)
//ActionConfig modelParamFilterActionConfig = new ActionConfig(null, ModelDrivenAction.class, null, null, interceptors);
results = new HashMap<>();
successParams = new HashMap<>();
successParams.put("actionName", "bar");
results.put("success", new ResultConfig.Builder("success", ActionChainResult.class.getName()).addParams(successParams).build());
results.put(Action.ERROR, new ResultConfig.Builder(Action.ERROR, MockResult.class.getName()).build());
interceptors = new ArrayList<>();
interceptors.add(new InterceptorMapping("staticParams",
objectFactory.buildInterceptor(new InterceptorConfig.Builder("model", StaticParametersInterceptor.class.getName()).build(), EMPTY_STRING_MAP)));
interceptors.add(new InterceptorMapping("model",
objectFactory.buildInterceptor(new InterceptorConfig.Builder("model", ModelDrivenInterceptor.class.getName()).build(), EMPTY_STRING_MAP)));
interceptors.add(new InterceptorMapping("params",
objectFactory.buildInterceptor(new InterceptorConfig.Builder("model", ParametersInterceptor.class.getName()).build(), EMPTY_STRING_MAP)));
interceptors.add(new InterceptorMapping("validation",
objectFactory.buildInterceptor(new InterceptorConfig.Builder("model", ValidationInterceptor.class.getName()).build(), EMPTY_STRING_MAP)));
//Explicitly set an out-of-range date for DateRangeValidatorTest
params = new HashMap<>();
ActionConfig validationActionConfig = new ActionConfig.Builder("defaultPackage", VALIDATION_ACTION_NAME, SimpleAction.class.getName())
.addInterceptors(interceptors)
.addParams(params)
.addResultConfigs(results)
.build();
defaultPackageContext.addActionConfig(VALIDATION_ACTION_NAME, validationActionConfig);
defaultPackageContext.addActionConfig(VALIDATION_ALIAS_NAME,
new ActionConfig.Builder(validationActionConfig).name(VALIDATION_ALIAS_NAME).build());
defaultPackageContext.addActionConfig(VALIDATION_SUBPROPERTY_NAME,
new ActionConfig.Builder(validationActionConfig).name(VALIDATION_SUBPROPERTY_NAME).build());
params = new HashMap<>();
ActionConfig percentageActionConfig = new ActionConfig.Builder("defaultPackage", "percentage", SimpleAction.class.getName())
.addParams(params)
.addResultConfigs(results)
.addInterceptors(interceptors)
.build();
defaultPackageContext.addActionConfig(percentageActionConfig.getName(), percentageActionConfig);
// We need this actionconfig to be the final destination for action chaining
ActionConfig barActionConfig = new ActionConfig.Builder("defaultPackage", "bar", SimpleAction.class.getName())
.addResultConfig(new ResultConfig.Builder(Action.ERROR, MockResult.class.getName()).build())
.build();
defaultPackageContext.addActionConfig(barActionConfig.getName(), barActionConfig);
ActionConfig expressionValidationActionConfig = new ActionConfig.Builder("defaultPackage", EXPRESSION_VALIDATION_ACTION, SimpleAction.class.getName())
.addInterceptors(interceptors)
.addResultConfigs(results)
.build();
defaultPackageContext.addActionConfig(EXPRESSION_VALIDATION_ACTION, expressionValidationActionConfig);
configuration.addPackageConfig("defaultPackage", defaultPackageContext.build());
}
/**
* Tells whether the ConfigurationProvider should reload its configuration
*
* @return false
*/
public boolean needsReload() {
return false;
}
public void register(ContainerBuilder builder, LocatableProperties props) throws ConfigurationException {
if (params != null) {
for (String key : params.keySet()) {
props.setProperty(key, params.get(key));
}
}
}
}
@@ -0,0 +1,24 @@
package com.opensymphony.xwork2.config.providers;
import com.opensymphony.xwork2.Action;
/**
* Action with no public constructor taking no args.
* <p/>
* Used for unit test of {@link com.opensymphony.xwork2.config.providers.XmlConfigurationProvider}.
*
* @author Claus Ibsen
*/
public class NoNoArgsConstructorAction implements Action {
private int foo;
public NoNoArgsConstructorAction(int foo) {
this.foo = foo;
}
public String execute() throws Exception {
return SUCCESS;
}
}
@@ -0,0 +1,43 @@
/*
* 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 com.opensymphony.xwork2.config.providers;
import com.opensymphony.xwork2.Action;
/**
* Action with nu public constructor.
* <p/>
* Used for unit test of {@link XmlConfigurationProvider}.
*
* @author Claus Ibsen
*/
public class PrivateConstructorAction implements Action {
private int foo;
private PrivateConstructorAction() {
// should be private, no constructor
}
public String execute() throws Exception {
return SUCCESS;
}
public void setFoo(int foo) {
this.foo = foo;
}
}
@@ -0,0 +1,48 @@
/*
* 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 com.opensymphony.xwork2.config.providers;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.Result;
import com.opensymphony.xwork2.UnknownHandler;
import com.opensymphony.xwork2.XWorkException;
import com.opensymphony.xwork2.config.entities.ActionConfig;
public class SomeUnknownHandler implements UnknownHandler{
private ActionConfig actionConfig;
private String actionMethodResult;
public ActionConfig handleUnknownAction(String namespace, String actionName) throws XWorkException {
return actionConfig;
}
public Object handleUnknownActionMethod(Object action, String methodName) throws NoSuchMethodException {
return actionMethodResult;
}
public Result handleUnknownResult(ActionContext actionContext, String actionName, ActionConfig actionConfig,
String resultCode) throws XWorkException {
return null;
}
public void setActionConfig(ActionConfig actionConfig) {
this.actionConfig = actionConfig;
}
public void setActionMethodResult(String actionMethodResult) {
this.actionMethodResult = actionMethodResult;
}
}
@@ -0,0 +1,214 @@
/*
* 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 com.opensymphony.xwork2.config.providers;
import com.opensymphony.xwork2.ObjectFactory;
import com.opensymphony.xwork2.SimpleAction;
import com.opensymphony.xwork2.config.ConfigurationException;
import com.opensymphony.xwork2.config.ConfigurationProvider;
import com.opensymphony.xwork2.config.entities.*;
import com.opensymphony.xwork2.interceptor.TimerInterceptor;
import com.opensymphony.xwork2.mock.MockInterceptor;
import com.opensymphony.xwork2.mock.MockResult;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Mike
* @author Rainer Hermanns
*/
public class XmlConfigurationProviderActionsTest extends ConfigurationTestBase {
private List<InterceptorMapping> interceptors;
private List<ExceptionMappingConfig> exceptionMappings;
private Map<String, String> params;
private Map<String, ResultConfig> results;
private ObjectFactory objectFactory;
public void testActions() throws Exception {
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-actions.xml";
ConfigurationProvider provider = buildConfigurationProvider(filename);
// setup expectations
// bar action is very simple, just two params
params.put("foo", "17");
params.put("bar", "23");
params.put("testXW412", "foo.jspa?fooID=${fooID}&something=bar");
params.put("testXW412Again", "something");
ActionConfig barAction = new ActionConfig.Builder("", "Bar", SimpleAction.class.getName())
.addParams(params).build();
// foo action is a little more complex, two params, a result and an interceptor stack
results = new HashMap<>();
params = new HashMap<>();
params.put("foo", "18");
params.put("bar", "24");
results.put("success", new ResultConfig.Builder("success", MockResult.class.getName()).build());
InterceptorConfig timerInterceptorConfig = new InterceptorConfig.Builder("timer", TimerInterceptor.class.getName()).build();
interceptors.add(new InterceptorMapping("timer", objectFactory.buildInterceptor(timerInterceptorConfig, new HashMap<String, String>())));
ActionConfig fooAction = new ActionConfig.Builder("", "Foo", SimpleAction.class.getName())
.addParams(params)
.addResultConfigs(results)
.addInterceptors(interceptors)
.build();
// wildcard action is simple wildcard example
results = new HashMap<>();
results.put("*", new ResultConfig.Builder("*", MockResult.class.getName()).build());
ActionConfig wildcardAction = new ActionConfig.Builder("", "WildCard", SimpleAction.class.getName())
.addResultConfigs(results)
.addInterceptors(interceptors)
.build();
// fooBar action is a little more complex, two params, a result and an interceptor stack
params = new HashMap<String, String>();
params.put("foo", "18");
params.put("bar", "24");
results = new HashMap<>();
results.put("success", new ResultConfig.Builder("success", MockResult.class.getName()).build());
ExceptionMappingConfig exceptionConfig = new ExceptionMappingConfig.Builder("runtime", "java.lang.RuntimeException", "exception")
.build();
exceptionMappings.add(exceptionConfig);
ActionConfig fooBarAction = new ActionConfig.Builder("", "FooBar", SimpleAction.class.getName())
.addParams(params)
.addResultConfigs(results)
.addInterceptors(interceptors)
.addExceptionMappings(exceptionMappings)
.build();
// TestInterceptorParam action tests that an interceptor worked
HashMap<String, String> interceptorParams = new HashMap<>();
interceptorParams.put("expectedFoo", "expectedFooValue");
interceptorParams.put("foo", MockInterceptor.DEFAULT_FOO_VALUE);
InterceptorConfig mockInterceptorConfig = new InterceptorConfig.Builder("test", MockInterceptor.class.getName()).build();
interceptors = new ArrayList<>();
interceptors.add(new InterceptorMapping("test", objectFactory.buildInterceptor(mockInterceptorConfig, interceptorParams)));
ActionConfig intAction = new ActionConfig.Builder("", "TestInterceptorParam", SimpleAction.class.getName())
.addInterceptors(interceptors)
.build();
// TestInterceptorParamOverride action tests that an interceptor with a param override worked
interceptorParams = new HashMap<>();
interceptorParams.put("expectedFoo", "expectedFooValue");
interceptorParams.put("foo", "foo123");
interceptors = new ArrayList<>();
interceptors.add(new InterceptorMapping("test", objectFactory.buildInterceptor(mockInterceptorConfig, interceptorParams)));
ActionConfig intOverAction = new ActionConfig.Builder("", "TestInterceptorParamOverride", SimpleAction.class.getName())
.addInterceptors(interceptors)
.build();
// execute the configuration
provider.init(configuration);
provider.loadPackages();
PackageConfig pkg = configuration.getPackageConfig("default");
Map actionConfigs = pkg.getActionConfigs();
// assertions
assertEquals(7, actionConfigs.size());
assertEquals(barAction, actionConfigs.get("Bar"));
assertEquals(fooAction, actionConfigs.get("Foo"));
assertEquals(wildcardAction, actionConfigs.get("WildCard"));
assertEquals(fooBarAction, actionConfigs.get("FooBar"));
assertEquals(intAction, actionConfigs.get("TestInterceptorParam"));
assertEquals(intOverAction, actionConfigs.get("TestInterceptorParamOverride"));
}
public void testInvalidActions() throws Exception {
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-action-invalid.xml";
try {
ConfigurationProvider provider = buildConfigurationProvider(filename);
fail("Should have thrown an exception");
} catch (ConfigurationException ex) {
// it worked correctly
}
}
public void testPackageDefaultClassRef() throws Exception {
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-actions-packagedefaultclassref.xml";
final String testDefaultClassName = "com.opensymphony.xwork2.UserSpecifiedDefaultAction";
ConfigurationProvider provider = buildConfigurationProvider(filename);
// setup expectations
params.put("foo", "17");
params.put("bar", "23");
ActionConfig barWithPackageDefaultClassRefConfig =
new ActionConfig.Builder("", "Bar", "").addParams(params).build();
// execute the configuration
provider.init(configuration);
PackageConfig pkg = configuration.getPackageConfig("default");
Map actionConfigs = pkg.getActionConfigs();
// assertions
assertEquals(1, actionConfigs.size());
assertEquals(barWithPackageDefaultClassRefConfig, actionConfigs.get("Bar"));
}
public void testDefaultActionClass() throws Exception {
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-actions.xml";
final String testDefaultClassName = "com.opensymphony.xwork2.ActionSupport";
ConfigurationProvider provider = buildConfigurationProvider(filename);
// setup expectations
params.put("foo", "17");
params.put("bar", "23");
ActionConfig barWithoutClassNameConfig =
new ActionConfig.Builder("", "BarWithoutClassName", "").addParams(params).build();
// execute the configuration
provider.init(configuration);
PackageConfig pkg = configuration.getPackageConfig("default");
Map actionConfigs = pkg.getActionConfigs();
// assertions
assertEquals(7, actionConfigs.size());
assertEquals(barWithoutClassNameConfig, actionConfigs.get("BarWithoutClassName"));
}
@Override
protected void setUp() throws Exception {
super.setUp();
params = new HashMap<>();
results = new HashMap<>();
interceptors = new ArrayList<>();
exceptionMappings = new ArrayList<>();
this.objectFactory = container.getInstance(ObjectFactory.class);
}
}
@@ -0,0 +1,125 @@
package com.opensymphony.xwork2.config.providers;
import com.opensymphony.xwork2.config.ConfigurationException;
import com.opensymphony.xwork2.config.ConfigurationProvider;
import com.opensymphony.xwork2.config.entities.ActionConfig;
import com.opensymphony.xwork2.config.entities.PackageConfig;
import java.util.Map;
/**
* @author John Lindal
*/
public class XmlConfigurationProviderAllowedMethodsTest extends ConfigurationTestBase {
public void testDefaultAllowedMethods() throws ConfigurationException {
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-allowed-methods.xml";
ConfigurationProvider provider = buildConfigurationProvider(filename);
// execute the configuration
provider.init(configuration);
provider.loadPackages();
PackageConfig pkg = configuration.getPackageConfig("default");
Map actionConfigs = pkg.getActionConfigs();
// assertions
assertEquals(5, actionConfigs.size());
ActionConfig action = (ActionConfig) actionConfigs.get("Default");
assertEquals(1, action.getAllowedMethods().size());
assertTrue(action.isAllowedMethod("execute"));
assertTrue(action.isAllowedMethod("foo"));
assertTrue(action.isAllowedMethod("bar"));
assertTrue(action.isAllowedMethod("baz"));
assertTrue(action.isAllowedMethod("xyz"));
action = (ActionConfig) actionConfigs.get("Boring");
assertEquals(0, action.getAllowedMethods().size());
assertTrue(action.isAllowedMethod("execute"));
assertFalse(action.isAllowedMethod("foo"));
assertFalse(action.isAllowedMethod("bar"));
assertFalse(action.isAllowedMethod("baz"));
assertFalse(action.isAllowedMethod("xyz"));
action = (ActionConfig) actionConfigs.get("Foo");
assertEquals(1, action.getAllowedMethods().size());
assertTrue(action.isAllowedMethod("execute"));
assertTrue(action.isAllowedMethod("foo"));
assertFalse(action.isAllowedMethod("bar"));
assertFalse(action.isAllowedMethod("baz"));
assertFalse(action.isAllowedMethod("xyz"));
action = (ActionConfig) actionConfigs.get("Bar");
assertEquals(2, action.getAllowedMethods().size());
assertTrue(action.isAllowedMethod("execute"));
assertTrue(action.isAllowedMethod("foo"));
assertTrue(action.isAllowedMethod("bar"));
assertFalse(action.isAllowedMethod("baz"));
assertFalse(action.isAllowedMethod("xyz"));
action = (ActionConfig) actionConfigs.get("Baz");
assertEquals(2, action.getAllowedMethods().size());
assertFalse(action.isAllowedMethod("execute"));
assertTrue(action.isAllowedMethod("foo"));
assertTrue(action.isAllowedMethod("bar"));
assertTrue(action.isAllowedMethod("baz"));
assertFalse(action.isAllowedMethod("xyz"));
}
public void testStrictAllowedMethods() throws ConfigurationException {
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-allowed-methods.xml";
ConfigurationProvider provider = buildConfigurationProvider(filename);
// execute the configuration
provider.init(configuration);
provider.loadPackages();
PackageConfig pkg = configuration.getPackageConfig("strict");
Map actionConfigs = pkg.getActionConfigs();
// assertions
assertEquals(5, actionConfigs.size());
ActionConfig action = (ActionConfig) actionConfigs.get("Default");
assertEquals(0, action.getAllowedMethods().size());
assertTrue(action.isAllowedMethod("execute"));
assertFalse(action.isAllowedMethod("foo"));
assertFalse(action.isAllowedMethod("bar"));
assertFalse(action.isAllowedMethod("baz"));
assertFalse(action.isAllowedMethod("xyz"));
action = (ActionConfig) actionConfigs.get("Boring");
assertEquals(0, action.getAllowedMethods().size());
assertTrue(action.isAllowedMethod("execute"));
assertFalse(action.isAllowedMethod("foo"));
assertFalse(action.isAllowedMethod("bar"));
assertFalse(action.isAllowedMethod("baz"));
assertFalse(action.isAllowedMethod("xyz"));
action = (ActionConfig) actionConfigs.get("Foo");
assertEquals(1, action.getAllowedMethods().size());
assertTrue(action.isAllowedMethod("execute"));
assertTrue(action.isAllowedMethod("foo"));
assertFalse(action.isAllowedMethod("bar"));
assertFalse(action.isAllowedMethod("baz"));
assertFalse(action.isAllowedMethod("xyz"));
action = (ActionConfig) actionConfigs.get("Bar");
assertEquals(2, action.getAllowedMethods().size());
assertTrue(action.isAllowedMethod("execute"));
assertTrue(action.isAllowedMethod("foo"));
assertTrue(action.isAllowedMethod("bar"));
assertFalse(action.isAllowedMethod("baz"));
assertFalse(action.isAllowedMethod("xyz"));
action = (ActionConfig) actionConfigs.get("Baz");
assertEquals(2, action.getAllowedMethods().size());
assertFalse(action.isAllowedMethod("execute"));
assertTrue(action.isAllowedMethod("foo"));
assertTrue(action.isAllowedMethod("bar"));
assertTrue(action.isAllowedMethod("baz"));
assertFalse(action.isAllowedMethod("xyz"));
}
}
@@ -0,0 +1,65 @@
package com.opensymphony.xwork2.config.providers;
import com.opensymphony.xwork2.ActionChainResult;
import com.opensymphony.xwork2.SimpleAction;
import com.opensymphony.xwork2.config.ConfigurationException;
import com.opensymphony.xwork2.config.ConfigurationProvider;
import com.opensymphony.xwork2.config.entities.ActionConfig;
import com.opensymphony.xwork2.config.entities.ExceptionMappingConfig;
import com.opensymphony.xwork2.config.entities.PackageConfig;
import com.opensymphony.xwork2.config.entities.ResultConfig;
import com.opensymphony.xwork2.mock.MockResult;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* User: Matthew E. Porter (matthew dot porter at metissian dot com)
* Date: Aug 15, 2005
* Time: 2:05:36 PM
*/
public class XmlConfigurationProviderExceptionMappingsTest extends ConfigurationTestBase {
public void testActions() throws ConfigurationException {
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-exception-mappings.xml";
ConfigurationProvider provider = buildConfigurationProvider(filename);
List<ExceptionMappingConfig> exceptionMappings = new ArrayList<>();
HashMap<String, String> parameters = new HashMap<>();
HashMap<String, ResultConfig> results = new HashMap<>();
exceptionMappings.add(
new ExceptionMappingConfig.Builder("spooky-result", "com.opensymphony.xwork2.SpookyException", "spooky-result")
.build());
results.put("spooky-result", new ResultConfig.Builder("spooky-result", MockResult.class.getName()).build());
Map<String, String> resultParams = new HashMap<>();
resultParams.put("actionName", "bar.vm");
results.put("specificLocationResult",
new ResultConfig.Builder("specificLocationResult", ActionChainResult.class.getName())
.addParams(resultParams)
.build());
ActionConfig expectedAction = new ActionConfig.Builder("default", "Bar", SimpleAction.class.getName())
.addParams(parameters)
.addResultConfigs(results)
.addExceptionMappings(exceptionMappings)
.build();
// execute the configuration
provider.init(configuration);
provider.loadPackages();
PackageConfig pkg = configuration.getPackageConfig("default");
Map actionConfigs = pkg.getActionConfigs();
// assertions
assertEquals(1, actionConfigs.size());
ActionConfig action = (ActionConfig) actionConfigs.get("Bar");
assertEquals(expectedAction, action);
}
}
@@ -0,0 +1,53 @@
package com.opensymphony.xwork2.config.providers;
import com.opensymphony.xwork2.config.Configuration;
import com.opensymphony.xwork2.config.ConfigurationManager;
import com.opensymphony.xwork2.config.ConfigurationProvider;
import com.opensymphony.xwork2.config.entities.ActionConfig;
import com.opensymphony.xwork2.config.entities.ResultConfig;
/**
* <code>XmlConfigurationProviderGlobalResultInheritenceTest</code>
*
* @author <a href="mailto:hermanns@aixcept.de">Rainer Hermanns</a>
* @author tm_jee
* @version $Id$
*/
public class XmlConfigurationProviderGlobalResultInheritenceTest extends ConfigurationTestBase {
public void testGlobalResultInheritenceTest() throws Exception {
ConfigurationProvider provider = buildConfigurationProvider("com/opensymphony/xwork2/config/providers/xwork-test-global-result-inheritence.xml");
ConfigurationManager configurationManager = new ConfigurationManager();
configurationManager.addContainerProvider(new XWorkConfigurationProvider());
configurationManager.addContainerProvider(provider);
Configuration configuration = configurationManager.getConfiguration();
ActionConfig parentActionConfig = configuration.getRuntimeConfiguration().getActionConfig("/base", "parentAction");
ActionConfig anotherActionConfig = configuration.getRuntimeConfiguration().getActionConfig("/base", "anotherAction");
ActionConfig childActionConfig = configuration.getRuntimeConfiguration().getActionConfig("/base", "childAction");
ResultConfig parentResultConfig1 = parentActionConfig.getResults().get("mockResult1");
ResultConfig parentResultConfig2 = parentActionConfig.getResults().get("mockResult2");
ResultConfig anotherResultConfig1 = anotherActionConfig.getResults().get("mockResult1");
ResultConfig anotherResultConfig2 = anotherActionConfig.getResults().get("mockResult2");
ResultConfig childResultConfig1 = childActionConfig.getResults().get("mockResult1");
ResultConfig childResultConfig2 = childActionConfig.getResults().get("mockResult2");
System.out.println(parentResultConfig1.getParams().get("identity"));
System.out.println(parentResultConfig2.getParams().get("identity"));
System.out.println(anotherResultConfig1.getParams().get("identity"));
System.out.println(anotherResultConfig2.getParams().get("identity"));
System.out.println(childResultConfig1.getParams().get("identity"));
System.out.println(childResultConfig2.getParams().get("identity"));
assertFalse(parentResultConfig1 == anotherResultConfig1);
assertFalse(parentResultConfig2 == anotherResultConfig2);
assertFalse(parentResultConfig1 == childResultConfig1);
assertTrue(parentResultConfig2 == childResultConfig2);
}
}
@@ -0,0 +1,101 @@
/*
* 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 com.opensymphony.xwork2.config.providers;
import com.opensymphony.xwork2.XWorkTestCase;
import com.opensymphony.xwork2.config.ConfigurationProvider;
import com.opensymphony.xwork2.config.RuntimeConfiguration;
import com.opensymphony.xwork2.config.entities.ActionConfig;
import com.opensymphony.xwork2.config.entities.InterceptorMapping;
import com.opensymphony.xwork2.config.impl.DefaultConfiguration;
import com.opensymphony.xwork2.util.fs.DefaultFileManager;
import com.opensymphony.xwork2.util.fs.DefaultFileManagerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* @author tm_jee
* @version $Date$ $Id$
*/
public class XmlConfigurationProviderInterceptorParamOverridingTest extends XWorkTestCase {
public void testInterceptorParamOveriding() throws Exception {
DefaultConfiguration conf = new DefaultConfiguration();
final XmlConfigurationProvider p = new XmlConfigurationProvider("com/opensymphony/xwork2/config/providers/xwork-test-interceptor-param-overriding.xml");
DefaultFileManagerFactory factory = new DefaultFileManagerFactory();
factory.setContainer(container);
factory.setFileManager(new DefaultFileManager());
p.setFileManagerFactory(factory);
conf.reload(new ArrayList<ConfigurationProvider>() {
{
add(new XWorkConfigurationProvider());
add(p);
}
});
RuntimeConfiguration rtConf = conf.getRuntimeConfiguration();
ActionConfig actionOne = rtConf.getActionConfig("", "actionOne");
ActionConfig actionTwo = rtConf.getActionConfig("", "actionTwo");
List<InterceptorMapping> actionOneInterceptors = actionOne.getInterceptors();
List<InterceptorMapping> actionTwoInterceptors = actionTwo.getInterceptors();
assertNotNull(actionOne);
assertNotNull(actionTwo);
assertNotNull(actionOneInterceptors);
assertNotNull(actionTwoInterceptors);
assertEquals(actionOneInterceptors.size(), 3);
assertEquals(actionTwoInterceptors.size(), 3);
InterceptorMapping actionOneInterceptorMapping1 = actionOneInterceptors.get(0);
InterceptorMapping actionOneInterceptorMapping2 = actionOneInterceptors.get(1);
InterceptorMapping actionOneInterceptorMapping3 = actionOneInterceptors.get(2);
InterceptorMapping actionTwoInterceptorMapping1 = actionTwoInterceptors.get(0);
InterceptorMapping actionTwoInterceptorMapping2 = actionTwoInterceptors.get(1);
InterceptorMapping actionTwoInterceptorMapping3 = actionTwoInterceptors.get(2);
assertNotNull(actionOneInterceptorMapping1);
assertNotNull(actionOneInterceptorMapping2);
assertNotNull(actionOneInterceptorMapping3);
assertNotNull(actionTwoInterceptorMapping1);
assertNotNull(actionTwoInterceptorMapping2);
assertNotNull(actionTwoInterceptorMapping3);
assertEquals(((InterceptorForTestPurpose) actionOneInterceptorMapping1.getInterceptor()).getParamOne(), "i1p1");
assertEquals(((InterceptorForTestPurpose) actionOneInterceptorMapping1.getInterceptor()).getParamTwo(), "i1p2");
assertEquals(((InterceptorForTestPurpose) actionOneInterceptorMapping2.getInterceptor()).getParamOne(), "i2p1");
assertEquals(((InterceptorForTestPurpose) actionOneInterceptorMapping2.getInterceptor()).getParamTwo(), null);
assertEquals(((InterceptorForTestPurpose) actionOneInterceptorMapping3.getInterceptor()).getParamOne(), null);
assertEquals(((InterceptorForTestPurpose) actionOneInterceptorMapping3.getInterceptor()).getParamTwo(), null);
assertEquals(((InterceptorForTestPurpose) actionTwoInterceptorMapping1.getInterceptor()).getParamOne(), null);
assertEquals(((InterceptorForTestPurpose) actionTwoInterceptorMapping1.getInterceptor()).getParamTwo(), null);
assertEquals(((InterceptorForTestPurpose) actionTwoInterceptorMapping2.getInterceptor()).getParamOne(), null);
assertEquals(((InterceptorForTestPurpose) actionTwoInterceptorMapping2.getInterceptor()).getParamTwo(), "i2p2");
assertEquals(((InterceptorForTestPurpose) actionTwoInterceptorMapping3.getInterceptor()).getParamOne(), "i3p1");
assertEquals(((InterceptorForTestPurpose) actionTwoInterceptorMapping3.getInterceptor()).getParamTwo(), "i3p2");
}
@Override
protected void tearDown() throws Exception {
configurationManager.clearContainerProviders();
}
}
@@ -0,0 +1,89 @@
package com.opensymphony.xwork2.config.providers;
import com.opensymphony.xwork2.XWorkTestCase;
import com.opensymphony.xwork2.config.ConfigurationProvider;
import com.opensymphony.xwork2.config.RuntimeConfiguration;
import com.opensymphony.xwork2.config.entities.ActionConfig;
import com.opensymphony.xwork2.config.entities.InterceptorMapping;
import com.opensymphony.xwork2.config.impl.DefaultConfiguration;
import com.opensymphony.xwork2.util.fs.DefaultFileManager;
import com.opensymphony.xwork2.util.fs.DefaultFileManagerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* <code>XmlConfigurationProviderInterceptorStackParamOverridingTest</code>
*
* @author <a href="mailto:hermanns@aixcept.de">Rainer Hermanns</a>
* @version $Id$
*/
public class XmlConfigurationProviderInterceptorStackParamOverridingTest extends XWorkTestCase {
public void testInterceptorStackParamOveriding() throws Exception {
DefaultConfiguration conf = new DefaultConfiguration();
final XmlConfigurationProvider p = new XmlConfigurationProvider("com/opensymphony/xwork2/config/providers/xwork-test-interceptor-stack-param-overriding.xml");
DefaultFileManagerFactory factory = new DefaultFileManagerFactory();
factory.setContainer(container);
factory.setFileManager(new DefaultFileManager());
p.setFileManagerFactory(factory);
configurationManager.addContainerProvider(p);
conf.reload(new ArrayList<ConfigurationProvider>(){
{
add(new XWorkConfigurationProvider());
add(p);
}
});
RuntimeConfiguration rtConf = conf.getRuntimeConfiguration();
ActionConfig actionOne = rtConf.getActionConfig("", "actionOne");
ActionConfig actionTwo = rtConf.getActionConfig("", "actionTwo");
List actionOneInterceptors = actionOne.getInterceptors();
List actionTwoInterceptors = actionTwo.getInterceptors();
assertNotNull(actionOne);
assertNotNull(actionTwo);
assertNotNull(actionOneInterceptors);
assertNotNull(actionTwoInterceptors);
assertEquals(actionOneInterceptors.size(), 3);
assertEquals(actionTwoInterceptors.size(), 3);
InterceptorMapping actionOneInterceptorMapping1 = (InterceptorMapping) actionOneInterceptors.get(0);
InterceptorMapping actionOneInterceptorMapping2 = (InterceptorMapping) actionOneInterceptors.get(1);
InterceptorMapping actionOneInterceptorMapping3 = (InterceptorMapping) actionOneInterceptors.get(2);
InterceptorMapping actionTwoInterceptorMapping1 = (InterceptorMapping) actionTwoInterceptors.get(0);
InterceptorMapping actionTwoInterceptorMapping2 = (InterceptorMapping) actionTwoInterceptors.get(1);
InterceptorMapping actionTwoInterceptorMapping3 = (InterceptorMapping) actionTwoInterceptors.get(2);
assertNotNull(actionOneInterceptorMapping1);
assertNotNull(actionOneInterceptorMapping2);
assertNotNull(actionOneInterceptorMapping3);
assertNotNull(actionTwoInterceptorMapping1);
assertNotNull(actionTwoInterceptorMapping2);
assertNotNull(actionTwoInterceptorMapping3);
assertEquals(((InterceptorForTestPurpose)actionOneInterceptorMapping1.getInterceptor()).getParamOne(), "i1p1");
assertEquals(((InterceptorForTestPurpose)actionOneInterceptorMapping1.getInterceptor()).getParamTwo(), "i1p2");
assertEquals(((InterceptorForTestPurpose)actionOneInterceptorMapping2.getInterceptor()).getParamOne(), "i2p1");
assertEquals(((InterceptorForTestPurpose)actionOneInterceptorMapping2.getInterceptor()).getParamTwo(), null);
assertEquals(((InterceptorForTestPurpose)actionOneInterceptorMapping3.getInterceptor()).getParamOne(), null);
assertEquals(((InterceptorForTestPurpose)actionOneInterceptorMapping3.getInterceptor()).getParamTwo(), null);
assertEquals(((InterceptorForTestPurpose)actionTwoInterceptorMapping1.getInterceptor()).getParamOne(), null);
assertEquals(((InterceptorForTestPurpose)actionTwoInterceptorMapping1.getInterceptor()).getParamTwo(), null);
assertEquals(((InterceptorForTestPurpose)actionTwoInterceptorMapping2.getInterceptor()).getParamOne(), null);
assertEquals(((InterceptorForTestPurpose)actionTwoInterceptorMapping2.getInterceptor()).getParamTwo(), "i2p2");
assertEquals(((InterceptorForTestPurpose)actionTwoInterceptorMapping3.getInterceptor()).getParamOne(), "i3p1");
assertEquals(((InterceptorForTestPurpose)actionTwoInterceptorMapping3.getInterceptor()).getParamTwo(), "i3p2");
}
@Override
protected void tearDown() throws Exception {
configurationManager.clearContainerProviders();
}
}
@@ -0,0 +1,80 @@
/*
* 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 com.opensymphony.xwork2.config.providers;
import com.opensymphony.xwork2.ObjectFactory;
import com.opensymphony.xwork2.config.ConfigurationException;
import com.opensymphony.xwork2.config.ConfigurationProvider;
import com.opensymphony.xwork2.config.entities.InterceptorConfig;
import com.opensymphony.xwork2.config.entities.PackageConfig;
import com.opensymphony.xwork2.interceptor.TimerInterceptor;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.context.support.StaticApplicationContext;
import java.util.Map;
/**
* Created by IntelliJ IDEA.
* User: Mike
* Date: May 6, 2003
* Time: 3:10:16 PM
* To change this template use Options | File Templates.
*/
public class XmlConfigurationProviderInterceptorsSpringTest extends ConfigurationTestBase {
InterceptorConfig timerInterceptor = new InterceptorConfig.Builder("timer", TimerInterceptor.class.getName()).build();
ObjectFactory objectFactory;
StaticApplicationContext sac;
public void testInterceptorsLoadedFromSpringApplicationContext() throws ConfigurationException {
sac.registerSingleton("timer-interceptor", TimerInterceptor.class, new MutablePropertyValues());
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-interceptors-spring.xml";
// Expect a ConfigurationException to be thrown if the interceptor reference
// cannot be resolved
ConfigurationProvider provider = buildConfigurationProvider(filename);
// execute the configuration
provider.init(configuration);
provider.loadPackages();
PackageConfig pkg = configuration.getPackageConfig("default");
Map interceptorConfigs = pkg.getInterceptorConfigs();
// assertions for size
assertEquals(1, interceptorConfigs.size());
// assertions for interceptors
InterceptorConfig seen = (InterceptorConfig) interceptorConfigs.get("timer");
assertEquals("timer-interceptor", seen.getClassName());
}
@Override
protected void setUp() throws Exception {
super.setUp();
sac = new StaticApplicationContext();
//SpringObjectFactory objFactory = new SpringObjectFactory();
//objFactory.setApplicationContext(sac);
//ObjectFactory.setObjectFactory(objFactory);
objectFactory = container.getInstance(ObjectFactory.class);
}
}
@@ -0,0 +1,226 @@
/*
* 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 com.opensymphony.xwork2.config.providers;
import com.opensymphony.xwork2.ObjectFactory;
import com.opensymphony.xwork2.SimpleAction;
import com.opensymphony.xwork2.config.ConfigurationException;
import com.opensymphony.xwork2.config.ConfigurationProvider;
import com.opensymphony.xwork2.config.RuntimeConfiguration;
import com.opensymphony.xwork2.config.entities.*;
import com.opensymphony.xwork2.interceptor.LoggingInterceptor;
import com.opensymphony.xwork2.interceptor.TimerInterceptor;
import com.opensymphony.xwork2.mock.MockInterceptor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Created by IntelliJ IDEA.
* User: Mike
* Date: May 6, 2003
* Time: 3:10:16 PM
* To change this template use Options | File Templates.
*/
public class XmlConfigurationProviderInterceptorsTest extends ConfigurationTestBase {
InterceptorConfig loggingInterceptor = new InterceptorConfig.Builder("logging", LoggingInterceptor.class.getName()).build();
InterceptorConfig mockInterceptor = new InterceptorConfig.Builder("mock", MockInterceptor.class.getName()).build();
InterceptorConfig timerInterceptor = new InterceptorConfig.Builder("timer", TimerInterceptor.class.getName()).build();
ObjectFactory objectFactory;
@Override
public void setUp() throws Exception {
super.setUp();
objectFactory = container.getInstance(ObjectFactory.class);
}
public void testBasicInterceptors() throws ConfigurationException {
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-interceptors-basic.xml";
ConfigurationProvider provider = buildConfigurationProvider(filename);
// setup expectations
// the test interceptor with a parameter
Map<String, String> params = new HashMap<>();
params.put("foo", "expectedFoo");
InterceptorConfig paramsInterceptor = new InterceptorConfig.Builder("test", MockInterceptor.class.getName())
.addParams(params).build();
// the default interceptor stack
InterceptorStackConfig defaultStack = new InterceptorStackConfig.Builder("defaultStack")
.addInterceptor(new InterceptorMapping("timer", objectFactory.buildInterceptor(timerInterceptor, new HashMap<String, String>())))
.addInterceptor(new InterceptorMapping("test", objectFactory.buildInterceptor(mockInterceptor, params)))
.build();
// the derivative interceptor stack
InterceptorStackConfig derivativeStack = new InterceptorStackConfig.Builder("derivativeStack")
.addInterceptor(new InterceptorMapping("timer", objectFactory.buildInterceptor(timerInterceptor, new HashMap<String, String>())))
.addInterceptor(new InterceptorMapping("test", objectFactory.buildInterceptor(mockInterceptor, params)))
.addInterceptor(new InterceptorMapping("logging", objectFactory.buildInterceptor(loggingInterceptor, new HashMap<String, String>())))
.build();
// execute the configuration
provider.init(configuration);
provider.loadPackages();
PackageConfig pkg = configuration.getPackageConfig("default");
Map interceptorConfigs = pkg.getInterceptorConfigs();
// assertions for size
assertEquals(5, interceptorConfigs.size());
// assertions for interceptors
assertEquals(timerInterceptor, interceptorConfigs.get("timer"));
assertEquals(loggingInterceptor, interceptorConfigs.get("logging"));
assertEquals(paramsInterceptor, interceptorConfigs.get("test"));
// assertions for interceptor stacks
assertEquals(defaultStack, interceptorConfigs.get("defaultStack"));
assertEquals(derivativeStack, interceptorConfigs.get("derivativeStack"));
}
public void testInterceptorDefaultRefs() throws ConfigurationException {
XmlConfigurationProvider provider = new XmlConfigurationProvider("com/opensymphony/xwork2/config/providers/xwork-test-interceptor-defaultref.xml");
container.inject(provider);
loadConfigurationProviders(provider);
// expectations - the inherited interceptor stack
// default package
ArrayList<InterceptorMapping> interceptors = new ArrayList<>();
interceptors.add(new InterceptorMapping("logging", objectFactory.buildInterceptor(loggingInterceptor, new HashMap<String, String>())));
ActionConfig actionWithOwnRef = new ActionConfig.Builder("", "ActionWithOwnRef", SimpleAction.class.getName())
.addInterceptors(interceptors)
.build();
ActionConfig actionWithDefaultRef = new ActionConfig.Builder("", "ActionWithDefaultRef", SimpleAction.class.getName())
.addInterceptor(new InterceptorMapping("timer", objectFactory.buildInterceptor(timerInterceptor, new HashMap<String, String>())))
.build();
// sub package
// this should inherit
ActionConfig actionWithNoRef = new ActionConfig.Builder("", "ActionWithNoRef", SimpleAction.class.getName())
.addInterceptor(new InterceptorMapping("timer", objectFactory.buildInterceptor(timerInterceptor, new HashMap<String, String>())))
.build();
interceptors = new ArrayList<>();
interceptors.add(new InterceptorMapping("logging", objectFactory.buildInterceptor(loggingInterceptor, new HashMap<String, String>())));
ActionConfig anotherActionWithOwnRef = new ActionConfig.Builder("", "AnotherActionWithOwnRef", SimpleAction.class.getName())
.addInterceptor(new InterceptorMapping("logging", objectFactory.buildInterceptor(loggingInterceptor, new HashMap<String, String>())))
.build();
RuntimeConfiguration runtimeConfig = configurationManager.getConfiguration().getRuntimeConfiguration();
// assertions
assertEquals(actionWithOwnRef, runtimeConfig.getActionConfig("", "ActionWithOwnRef"));
assertEquals(actionWithDefaultRef, runtimeConfig.getActionConfig("", "ActionWithDefaultRef"));
assertEquals(actionWithNoRef, runtimeConfig.getActionConfig("", "ActionWithNoRef"));
assertEquals(anotherActionWithOwnRef, runtimeConfig.getActionConfig("", "AnotherActionWithOwnRef"));
}
public void testInterceptorInheritance() throws ConfigurationException {
// expectations - the inherited interceptor stack
InterceptorStackConfig inheritedStack = new InterceptorStackConfig.Builder("subDefaultStack")
.addInterceptor(new InterceptorMapping("timer", objectFactory.buildInterceptor(timerInterceptor, new HashMap<String, String>())))
.build();
ConfigurationProvider provider = buildConfigurationProvider("com/opensymphony/xwork2/config/providers/xwork-test-interceptor-inheritance.xml");
// assertions
PackageConfig defaultPkg = configuration.getPackageConfig("default");
assertEquals(2, defaultPkg.getInterceptorConfigs().size());
PackageConfig subPkg = configuration.getPackageConfig("subPackage");
assertEquals(1, subPkg.getInterceptorConfigs().size());
assertEquals(3, subPkg.getAllInterceptorConfigs().size());
assertEquals(inheritedStack, subPkg.getInterceptorConfigs().get("subDefaultStack"));
// expectations - the inherited interceptor stack
inheritedStack = new InterceptorStackConfig.Builder("subSubDefaultStack")
.addInterceptor(new InterceptorMapping("timer", objectFactory.buildInterceptor(timerInterceptor, new HashMap<String, String>())))
.addInterceptor(new InterceptorMapping("timer", objectFactory.buildInterceptor(timerInterceptor, new HashMap<String, String>())))
.build();
PackageConfig subSubPkg = configuration.getPackageConfig("subSubPackage");
assertEquals(1, subSubPkg.getInterceptorConfigs().size());
assertEquals(4, subSubPkg.getAllInterceptorConfigs().size());
assertEquals(inheritedStack, subSubPkg.getInterceptorConfigs().get("subSubDefaultStack"));
}
public void testInterceptorParamOverriding() throws Exception {
Map<String, String> params = new HashMap<>();
params.put("foo", "expectedFoo");
params.put("expectedFoo", "expectedFooValue");
InterceptorStackConfig defaultStack = new InterceptorStackConfig.Builder("defaultStack")
.addInterceptor(new InterceptorMapping("timer", objectFactory.buildInterceptor(timerInterceptor, new HashMap<String, String>())))
.addInterceptor(new InterceptorMapping("test", objectFactory.buildInterceptor(mockInterceptor, params)))
.build();
ArrayList<InterceptorMapping> interceptors = new ArrayList<>();
interceptors.addAll(defaultStack.getInterceptors());
ActionConfig intAction = new ActionConfig.Builder("", "TestInterceptorParam", SimpleAction.class.getName())
.addInterceptors(interceptors)
.build();
// TestInterceptorParamOverride action tests that an interceptor with a param override worked
HashMap<String, String> interceptorParams = new HashMap<>();
interceptorParams.put("expectedFoo", "expectedFooValue2");
interceptorParams.put("foo", "foo123");
InterceptorStackConfig defaultStack2 = new InterceptorStackConfig.Builder("defaultStack")
.addInterceptor(new InterceptorMapping("timer", objectFactory.buildInterceptor(timerInterceptor, new HashMap<String, String>())))
.addInterceptor(new InterceptorMapping("test", objectFactory.buildInterceptor(mockInterceptor, interceptorParams)))
.build();
interceptors = new ArrayList<>();
interceptors.addAll(defaultStack2.getInterceptors());
ActionConfig intOverAction = new ActionConfig.Builder("", "TestInterceptorParamOverride", SimpleAction.class.getName())
.addInterceptors(interceptors)
.build();
ConfigurationProvider provider = buildConfigurationProvider("com/opensymphony/xwork2/config/providers/xwork-test-interceptor-params.xml");
PackageConfig pkg = configuration.getPackageConfig("default");
Map actionConfigs = pkg.getActionConfigs();
// assertions
assertEquals(2, actionConfigs.size());
assertEquals(intAction, actionConfigs.get("TestInterceptorParam"));
assertEquals(intOverAction, actionConfigs.get("TestInterceptorParamOverride"));
ActionConfig ac = (ActionConfig) actionConfigs.get("TestInterceptorParamOverride");
assertEquals(defaultStack.getInterceptors(), ac.getInterceptors());
ActionConfig ac2 = (ActionConfig) actionConfigs.get("TestInterceptorParam");
assertEquals(defaultStack2.getInterceptors(), ac2.getInterceptors());
}
}
@@ -0,0 +1,40 @@
/*
* 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 com.opensymphony.xwork2.config.providers;
import com.opensymphony.xwork2.config.ConfigurationException;
import com.opensymphony.xwork2.config.ConfigurationProvider;
/**
* XmlConfigurationProviderInvalidFileTest
*
* @author Jason Carreira
* Created Sep 6, 2003 2:36:10 PM
*/
public class XmlConfigurationProviderInvalidFileTest extends ConfigurationTestBase {
public void testInvalidFileThrowsException() {
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-invalid-file.xml";
try {
ConfigurationProvider provider = buildConfigurationProvider(filename);
fail();
} catch (ConfigurationException e) {
// this is what we expect
}
}
}
@@ -0,0 +1,70 @@
/*
* 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 com.opensymphony.xwork2.config.providers;
import com.opensymphony.xwork2.ActionChainResult;
import com.opensymphony.xwork2.config.ConfigurationProvider;
import com.opensymphony.xwork2.config.entities.ActionConfig;
import com.opensymphony.xwork2.config.entities.InterceptorMapping;
import com.opensymphony.xwork2.config.entities.PackageConfig;
import com.opensymphony.xwork2.config.entities.ResultConfig;
import com.opensymphony.xwork2.interceptor.ParametersInterceptor;
import junit.framework.Assert;
/**
* Verify that Interceptor inheritance is happy for multi-level package derivations
*
* @author $Author$
* @version $Revision$
*/
public class XmlConfigurationProviderMultilevelTest extends ConfigurationTestBase {
/**
* attempt to load an xwork.xml file that has multilevel levels of inheritance and verify that the interceptors are
* correctly propagated through.
*
* @throws Exception
*/
public void testMultiLevelInheritance() throws Exception {
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-multilevel.xml";
ConfigurationProvider provider = buildConfigurationProvider(filename);
provider.init(configuration);
provider.loadPackages();
/**
* for this test, we expect the action named, action3, in the namespace, namespace3, to have a single
* ParameterInterceptor. The ParameterInterceptor, param, has been defined far up namespace3's parentage ...
* namespace3 -> namespace2 -> namespace1 -> default
*/
PackageConfig packageConfig = configuration.getPackageConfig("namespace3");
Assert.assertNotNull(packageConfig);
assertEquals(2, packageConfig.getAllInterceptorConfigs().size());
ActionConfig actionConfig = packageConfig.getActionConfigs().get("action3");
assertNotNull(actionConfig);
assertNotNull(actionConfig.getInterceptors());
assertEquals(2, actionConfig.getInterceptors().size());
assertEquals(ParametersInterceptor.class, ((InterceptorMapping) actionConfig.getInterceptors().get(0)).getInterceptor().getClass());
assertNotNull(actionConfig.getResults());
assertEquals(1, actionConfig.getResults().size());
assertTrue(actionConfig.getResults().containsKey("success"));
ResultConfig resultConfig = (ResultConfig) actionConfig.getResults().get("success");
assertEquals(ActionChainResult.class.getName(), resultConfig.getClassName());
}
}
@@ -0,0 +1,157 @@
/*
* 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 com.opensymphony.xwork2.config.providers;
import com.opensymphony.xwork2.config.ConfigurationException;
import com.opensymphony.xwork2.config.ConfigurationProvider;
import com.opensymphony.xwork2.config.RuntimeConfiguration;
import com.opensymphony.xwork2.config.entities.PackageConfig;
import java.util.List;
/**
* Created by IntelliJ IDEA.
* User: Mike
* Date: May 6, 2003
* Time: 3:10:16 PM
* To change this template use Options | File Templates.
*/
public class XmlConfigurationProviderPackagesTest extends ConfigurationTestBase {
public void testBadInheritance() throws ConfigurationException {
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-bad-inheritance.xml";
ConfigurationProvider provider = null;
try {
provider = buildConfigurationProvider(filename);
fail("Should have thrown a ConfigurationException");
provider.init(configuration);
provider.loadPackages();
} catch (ConfigurationException e) {
// Expected
}
}
public void testBasicPackages() throws ConfigurationException {
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-basic-packages.xml";
ConfigurationProvider provider = buildConfigurationProvider(filename);
provider.init(configuration);
provider.loadPackages();
// setup our expectations
PackageConfig expectedNamespacePackage = new PackageConfig.Builder("namespacepkg")
.namespace("/namespace/set")
.isAbstract(false)
.build();
PackageConfig expectedAbstractPackage = new PackageConfig.Builder("abstractpkg")
.isAbstract(true)
.build();
// test expectations
assertEquals(3, configuration.getPackageConfigs().size());
assertEquals(expectedNamespacePackage, configuration.getPackageConfig("namespacepkg"));
assertEquals(expectedAbstractPackage, configuration.getPackageConfig("abstractpkg"));
}
public void testDefaultPackage() throws ConfigurationException {
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-default-package.xml";
ConfigurationProvider provider = buildConfigurationProvider(filename);
provider.init(configuration);
provider.loadPackages();
// setup our expectations
PackageConfig expectedPackageConfig = new PackageConfig.Builder("default").build();
// test expectations
assertEquals(1, configuration.getPackageConfigs().size());
assertEquals(expectedPackageConfig, configuration.getPackageConfig("default"));
}
public void testPackageInheritance() throws ConfigurationException {
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-package-inheritance.xml";
ConfigurationProvider provider = buildConfigurationProvider(filename);
provider.init(configuration);
provider.loadPackages();
// test expectations
assertEquals(5, configuration.getPackageConfigs().size());
PackageConfig defaultPackage = configuration.getPackageConfig("default");
assertNotNull(defaultPackage);
assertEquals("default", defaultPackage.getName());
PackageConfig abstractPackage = configuration.getPackageConfig("abstractPackage");
assertNotNull(abstractPackage);
assertEquals("abstractPackage", abstractPackage.getName());
PackageConfig singlePackage = configuration.getPackageConfig("singleInheritance");
assertNotNull(singlePackage);
assertEquals("singleInheritance", singlePackage.getName());
assertEquals(1, singlePackage.getParents().size());
assertEquals(defaultPackage, singlePackage.getParents().get(0));
PackageConfig multiplePackage = configuration.getPackageConfig("multipleInheritance");
assertNotNull(multiplePackage);
assertEquals("multipleInheritance", multiplePackage.getName());
assertEquals(3, multiplePackage.getParents().size());
List<PackageConfig> multipleParents = multiplePackage.getParents();
assertTrue(multipleParents.contains(defaultPackage));
assertTrue(multipleParents.contains(abstractPackage));
assertTrue(multipleParents.contains(singlePackage));
PackageConfig parentBelow = configuration.getPackageConfig("testParentBelow");
assertEquals(1, parentBelow.getParents().size());
List<PackageConfig> parentBelowParents = parentBelow.getParents();
assertTrue(parentBelowParents.contains(multiplePackage));
configurationManager.addContainerProvider(provider);
configurationManager.reload();
RuntimeConfiguration runtimeConfiguration = configurationManager.getConfiguration().getRuntimeConfiguration();
assertNotNull(runtimeConfiguration.getActionConfig("/multiple", "default"));
assertNotNull(runtimeConfiguration.getActionConfig("/multiple", "abstract"));
assertNotNull(runtimeConfiguration.getActionConfig("/multiple", "single"));
assertNotNull(runtimeConfiguration.getActionConfig("/multiple", "multiple"));
assertNotNull(runtimeConfiguration.getActionConfig("/single", "default"));
assertNull(runtimeConfiguration.getActionConfig("/single", "abstract"));
assertNotNull(runtimeConfiguration.getActionConfig("/single", "single"));
assertNull(runtimeConfiguration.getActionConfig("/single", "multiple"));
assertNotNull(runtimeConfiguration.getActionConfig("/parentBelow", "default"));
assertNotNull(runtimeConfiguration.getActionConfig("/parentBelow", "abstract"));
assertNotNull(runtimeConfiguration.getActionConfig("/parentBelow", "single"));
assertNotNull(runtimeConfiguration.getActionConfig("/parentBelow", "multiple"));
assertNotNull(runtimeConfiguration.getActionConfig("/parentBelow", "testParentBelowAction"));
}
public void testDefaultClassRef() throws ConfigurationException {
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-defaultclassref-package.xml";
final String hasDefaultClassRefPkgName = "hasDefaultClassRef";
final String noDefaultClassRefPkgName = "noDefaultClassRef";
final String testDefaultClassRef = "com.opensymphony.xwork2.ActionSupport";
ConfigurationProvider provider = buildConfigurationProvider(filename);
provider.init(configuration);
// setup our expectations
PackageConfig expectedDefaultClassRefPackage = new PackageConfig.Builder(hasDefaultClassRefPkgName).defaultClassRef(testDefaultClassRef).build();
PackageConfig expectedNoDefaultClassRefPackage = new PackageConfig.Builder(noDefaultClassRefPkgName).build();
// test expectations
assertEquals(2, configuration.getPackageConfigs().size());
assertEquals(expectedDefaultClassRefPackage, configuration.getPackageConfig(hasDefaultClassRefPkgName));
assertEquals(expectedNoDefaultClassRefPackage, configuration.getPackageConfig(noDefaultClassRefPkgName));
}
}
@@ -0,0 +1,119 @@
/*
* 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 com.opensymphony.xwork2.config.providers;
import com.opensymphony.xwork2.config.ConfigurationProvider;
import com.opensymphony.xwork2.config.entities.ActionConfig;
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.mock.MockResult;
import java.util.Map;
/**
* Test XmlConfigurationProvider's <result-types> ... </result-types>
*
* @author tm_jee
* @version $Date$ $Id$
*/
public class XmlConfigurationProviderResultTypesTest extends ConfigurationTestBase {
public void testPlainResultTypesParams() throws Exception {
ConfigurationProvider configurationProvider = buildConfigurationProvider("com/opensymphony/xwork2/config/providers/xwork-test-result-types.xml");
PackageConfig packageConfig = configuration.getPackageConfig("xworkResultTypesTestPackage1");
Map resultTypesConfigMap = packageConfig.getResultTypeConfigs();
assertEquals(resultTypesConfigMap.size(), 2);
assertTrue(resultTypesConfigMap.containsKey("result1"));
assertTrue(resultTypesConfigMap.containsKey("result2"));
assertFalse(resultTypesConfigMap.containsKey("result3"));
ResultTypeConfig result1ResultTypeConfig = (ResultTypeConfig) resultTypesConfigMap.get("result1");
Map result1ParamsMap = result1ResultTypeConfig.getParams();
ResultTypeConfig result2ResultTypeConfig = (ResultTypeConfig) resultTypesConfigMap.get("result2");
Map result2ParamsMap = result2ResultTypeConfig.getParams();
assertEquals(result1ResultTypeConfig.getName(), "result1");
assertEquals(result1ResultTypeConfig.getClazz(), MockResult.class.getName());
assertEquals(result2ResultTypeConfig.getName(), "result2");
assertEquals(result2ResultTypeConfig.getClazz(), MockResult.class.getName());
assertEquals(result1ParamsMap.size(), 3);
assertEquals(result2ParamsMap.size(), 2);
assertTrue(result1ParamsMap.containsKey("param1"));
assertTrue(result1ParamsMap.containsKey("param2"));
assertTrue(result1ParamsMap.containsKey("param3"));
assertFalse(result1ParamsMap.containsKey("param4"));
assertTrue(result2ParamsMap.containsKey("paramA"));
assertTrue(result2ParamsMap.containsKey("paramB"));
assertFalse(result2ParamsMap.containsKey("paramC"));
assertEquals(result1ParamsMap.get("param1"), "value1");
assertEquals(result1ParamsMap.get("param2"), "value2");
assertEquals(result1ParamsMap.get("param3"), "value3");
assertEquals(result2ParamsMap.get("paramA"), "valueA");
assertEquals(result2ParamsMap.get("paramB"), "valueB");
}
public void testInheritedResultTypesParams() throws Exception {
ConfigurationProvider configurationProvider = buildConfigurationProvider("com/opensymphony/xwork2/config/providers/xwork-test-result-types.xml");
PackageConfig packageConfig = configuration.getPackageConfig("xworkResultTypesTestPackage2");
Map actionConfigMap = packageConfig.getActionConfigs();
ActionConfig action1ActionConfig = (ActionConfig) actionConfigMap.get("action1");
ActionConfig action2ActionConfig = (ActionConfig) actionConfigMap.get("action2");
ResultConfig action1Result = (ResultConfig) action1ActionConfig.getResults().get("success");
ResultConfig action2Result = (ResultConfig) action2ActionConfig.getResults().get("success");
assertEquals(action1Result.getName(), "success");
assertEquals(action1Result.getClassName(), "com.opensymphony.xwork2.mock.MockResult");
assertEquals(action1Result.getName(), "success");
assertEquals(action1Result.getClassName(), "com.opensymphony.xwork2.mock.MockResult");
Map action1ResultMap = action1Result.getParams();
Map action2ResultMap = action2Result.getParams();
assertEquals(action1ResultMap.size(), 5);
assertTrue(action1ResultMap.containsKey("param1"));
assertTrue(action1ResultMap.containsKey("param2"));
assertTrue(action1ResultMap.containsKey("param3"));
assertTrue(action1ResultMap.containsKey("param10"));
assertTrue(action1ResultMap.containsKey("param11"));
assertFalse(action1ResultMap.containsKey("param12"));
assertEquals(action1ResultMap.get("param1"), "newValue1");
assertEquals(action1ResultMap.get("param2"), "value2");
assertEquals(action1ResultMap.get("param3"), "newValue3");
assertEquals(action1ResultMap.get("param10"), "value10");
assertEquals(action1ResultMap.get("param11"), "value11");
assertEquals(action2ResultMap.size(), 3);
assertTrue(action2ResultMap.containsKey("paramA"));
assertTrue(action2ResultMap.containsKey("paramB"));
assertTrue(action2ResultMap.containsKey("paramZ"));
assertFalse(action2ResultMap.containsKey("paramY"));
assertEquals(action2ResultMap.get("paramA"), "valueA");
assertEquals(action2ResultMap.get("paramB"), "newValueB");
assertEquals(action2ResultMap.get("paramZ"), "valueZ");
}
}
@@ -0,0 +1,121 @@
/*
* 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 com.opensymphony.xwork2.config.providers;
import com.opensymphony.xwork2.ActionChainResult;
import com.opensymphony.xwork2.SimpleAction;
import com.opensymphony.xwork2.config.ConfigurationException;
import com.opensymphony.xwork2.config.ConfigurationProvider;
import com.opensymphony.xwork2.config.entities.ActionConfig;
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.mock.MockResult;
import java.util.HashMap;
import java.util.Map;
/**
* Created by IntelliJ IDEA.
* User: Mike
* Date: May 6, 2003
* Time: 3:10:16 PM
* To change this template use Options | File Templates.
*/
public class XmlConfigurationProviderResultsTest extends ConfigurationTestBase {
public void testActions() throws ConfigurationException {
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-results.xml";
ConfigurationProvider provider = buildConfigurationProvider(filename);
HashMap<String, String> parameters = new HashMap<>();
HashMap<String, ResultConfig> results = new HashMap<>();
results.put("chainDefaultTypedResult", new ResultConfig.Builder("chainDefaultTypedResult", ActionChainResult.class.getName()).build());
results.put("mockTypedResult", new ResultConfig.Builder("mockTypedResult", MockResult.class.getName()).build());
Map<String, String> resultParams = new HashMap<>();
resultParams.put("actionName", "bar.vm");
results.put("specificLocationResult", new ResultConfig.Builder("specificLocationResult", ActionChainResult.class.getName())
.addParams(resultParams).build());
resultParams = new HashMap<>();
resultParams.put("actionName", "foo.vm");
results.put("defaultLocationResult", new ResultConfig.Builder("defaultLocationResult", ActionChainResult.class.getName())
.addParams(resultParams).build());
resultParams = new HashMap<>();
resultParams.put("foo", "bar");
results.put("noDefaultLocationResult", new ResultConfig.Builder("noDefaultLocationResult", ActionChainResult.class.getName())
.addParams(resultParams).build());
ActionConfig expectedAction = new ActionConfig.Builder("default", "Bar", SimpleAction.class.getName())
.addParams(parameters)
.addResultConfigs(results)
.build();
// execute the configuration
provider.init(configuration);
provider.loadPackages();
PackageConfig pkg = configuration.getPackageConfig("default");
Map<String, ActionConfig> actionConfigs = pkg.getActionConfigs();
// assertions
assertEquals(1, actionConfigs.size());
ActionConfig action = actionConfigs.get("Bar");
assertEquals(expectedAction, action);
}
public void testResultInheritance() throws ConfigurationException {
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-result-inheritance.xml";
ConfigurationProvider provider = buildConfigurationProvider(filename);
// expectations
provider.init(configuration);
provider.loadPackages();
// assertions
PackageConfig subPkg = configuration.getPackageConfig("subPackage");
assertEquals(1, subPkg.getResultTypeConfigs().size());
assertEquals(3, subPkg.getAllResultTypeConfigs().size());
}
public void testResultTypes() throws ConfigurationException {
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-results.xml";
ConfigurationProvider provider = buildConfigurationProvider(filename);
// setup expectations
ResultTypeConfig chainResult = new ResultTypeConfig.Builder("chain", ActionChainResult.class.getName()).build();
ResultTypeConfig mockResult = new ResultTypeConfig.Builder("mock", MockResult.class.getName()).build();
// execute the configuration
provider.init(configuration);
provider.loadPackages();
PackageConfig pkg = configuration.getPackageConfig("default");
Map resultTypes = pkg.getResultTypeConfigs();
// assertions
assertEquals(2, resultTypes.size());
assertEquals("chain", pkg.getDefaultResultType());
assertEquals(chainResult, resultTypes.get("chain"));
assertEquals(mockResult, resultTypes.get("mock"));
}
}
@@ -0,0 +1,201 @@
/*
* 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 com.opensymphony.xwork2.config.providers;
import com.opensymphony.xwork2.FileManagerFactory;
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.impl.MockConfiguration;
import com.opensymphony.xwork2.util.ClassLoaderUtil;
import org.w3c.dom.Document;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class XmlConfigurationProviderTest extends ConfigurationTestBase {
public void testLoadOrder() throws Exception {
configuration = new MockConfiguration();
((MockConfiguration) configuration).selfRegister();
container = configuration.getContainer();
XmlConfigurationProvider prov = new XmlConfigurationProvider("xwork-test-load-order.xml", true) {
@Override
protected Iterator<URL> getConfigurationUrls(String fileName) throws IOException {
List<URL> urls = new ArrayList<>();
urls.add(ClassLoaderUtil.getResource("com/opensymphony/xwork2/config/providers/loadorder1/xwork-test-load-order.xml", XmlConfigurationProvider.class));
urls.add(ClassLoaderUtil.getResource("com/opensymphony/xwork2/config/providers/loadorder2/xwork-test-load-order.xml", XmlConfigurationProvider.class));
urls.add(ClassLoaderUtil.getResource("com/opensymphony/xwork2/config/providers/loadorder3/xwork-test-load-order.xml", XmlConfigurationProvider.class));
return urls.iterator();
}
};
prov.setObjectFactory(container.getInstance(ObjectFactory.class));
prov.setFileManagerFactory(container.getInstance(FileManagerFactory.class));
prov.init(configuration);
List<Document> docs = prov.getDocuments();
assertEquals(3, docs.size());
assertEquals(1, XmlHelper.getLoadOrder(docs.get(0)).intValue());
assertEquals(2, XmlHelper.getLoadOrder(docs.get(1)).intValue());
assertEquals(3, XmlHelper.getLoadOrder(docs.get(2)).intValue());
}
public static final long FILE_TS_WAIT_IN_MS = 3600000;
private static void changeFileTime(File f) throws Exception {
final long orig = f.lastModified();
final long maxwait = orig + FILE_TS_WAIT_IN_MS;
long curr;
while (!f.setLastModified(curr = System.currentTimeMillis()) || orig == f.lastModified()) {
Thread.sleep(500);
assertTrue("Waited more than " + FILE_TS_WAIT_IN_MS + " ms to update timestamp on file: " + f, maxwait > curr);
}
}
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");
assertTrue(!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);
assertTrue(provider.needsReload());
}
public void testInheritence() throws Exception {
final String filename = "com/opensymphony/xwork2/config/providers/xwork-include-parent.xml";
ConfigurationProvider provider = buildConfigurationProvider(filename);
provider.init(configuration);
provider.loadPackages();
// test expectations
assertEquals(6, configuration.getPackageConfigs().size());
PackageConfig defaultPackage = configuration.getPackageConfig("default");
assertNotNull(defaultPackage);
assertEquals("default", defaultPackage.getName());
PackageConfig namespace1 = configuration.getPackageConfig("namespace1");
assertNotNull(namespace1);
assertEquals("namespace1", namespace1.getName());
assertEquals(defaultPackage, namespace1.getParents().get(0));
PackageConfig namespace2 = configuration.getPackageConfig("namespace2");
assertNotNull(namespace2);
assertEquals("namespace2", namespace2.getName());
assertEquals(1, namespace2.getParents().size());
assertEquals(namespace1, namespace2.getParents().get(0));
PackageConfig namespace4 = configuration.getPackageConfig("namespace4");
assertNotNull(namespace4);
assertEquals("namespace4", namespace4.getName());
assertEquals(1, namespace4.getParents().size());
assertEquals(namespace1, namespace4.getParents().get(0));
PackageConfig namespace5 = configuration.getPackageConfig("namespace5");
assertNotNull(namespace5);
assertEquals("namespace5", namespace5.getName());
assertEquals(1, namespace5.getParents().size());
assertEquals(namespace4, namespace5.getParents().get(0));
configurationManager.addContainerProvider(provider);
configurationManager.reload();
RuntimeConfiguration runtimeConfiguration = configurationManager.getConfiguration().getRuntimeConfiguration();
assertNotNull(runtimeConfiguration.getActionConfig("/namespace1", "action1"));
assertNotNull(runtimeConfiguration.getActionConfig("/namespace2", "action2"));
assertNotNull(runtimeConfiguration.getActionConfig("/namespace4", "action4"));
assertNotNull(runtimeConfiguration.getActionConfig("/namespace5", "action5"));
}
public void testGuessResultType() {
XmlConfigurationProvider prov = new XmlConfigurationProvider();
assertEquals(null, prov.guessResultType(null));
assertEquals("foo", prov.guessResultType("foo"));
assertEquals("foo", prov.guessResultType("foo-"));
assertEquals("fooBar", prov.guessResultType("foo-bar"));
assertEquals("fooBarBaz", prov.guessResultType("foo-bar-baz"));
}
public void testEmptySpaces() throws Exception {
final String filename = "com/opensymphony/xwork2/config/providers/xwork- test.xml";
container.getInstance(FileManagerFactory.class).getFileManager().setReloadingConfigs(true);
ConfigurationProvider provider = buildConfigurationProvider(filename);
assertTrue(!provider.needsReload());
URI uri = ClassLoaderUtil.getResource(filename, ConfigurationProvider.class).toURI();
File file = new File(uri);
assertTrue(file.exists());
changeFileTime(file);
assertTrue(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");
testProvider("xwork - zip.xml");
testProvider("xwork-jar2.xml");
testProvider("xwork-zip2.xml");
testProvider("xwork - jar2.xml");
testProvider("xwork - zip2.xml");
}
private void testProvider(String configFile) throws Exception {
ConfigurationProvider provider = buildConfigurationProvider(configFile);
assertTrue(!provider.needsReload());
String fullPath = ClassLoaderUtil.getResource(configFile, ConfigurationProvider.class).toString();
int startIndex = fullPath.indexOf(":file:/");
int endIndex = fullPath.indexOf("!/");
String jar = fullPath.substring(startIndex + (":file:/".length() - 1), endIndex).replaceAll("%20", " ");
File file = new File(jar);
assertTrue("File [" + file + "] doesn't exist!", file.exists());
file.setLastModified(System.currentTimeMillis());
assertTrue(!provider.needsReload());
}
}
@@ -0,0 +1,40 @@
package com.opensymphony.xwork2.config.providers;
import com.opensymphony.xwork2.UnknownHandlerManager;
import com.opensymphony.xwork2.config.ConfigurationException;
import com.opensymphony.xwork2.config.ConfigurationProvider;
import com.opensymphony.xwork2.config.entities.UnknownHandlerConfig;
import com.opensymphony.xwork2.DefaultUnknownHandlerManager;
import java.util.List;
public class XmlConfigurationProviderUnknownHandlerStackTest extends ConfigurationTestBase {
public void testStackWithElements() throws ConfigurationException {
final String filename = "com/opensymphony/xwork2/config/providers/xwork-unknownhandler-stack.xml";
ConfigurationProvider provider = buildConfigurationProvider(filename);
loadConfigurationProviders(provider);
configurationManager.reload();
List<UnknownHandlerConfig> unknownHandlerStack = configuration.getUnknownHandlerStack();
assertNotNull(unknownHandlerStack);
assertEquals(2, unknownHandlerStack.size());
assertEquals("uh1", unknownHandlerStack.get(0).getName());
assertEquals("uh2", unknownHandlerStack.get(1).getName());
UnknownHandlerManager unknownHandlerManager = new DefaultUnknownHandlerManager();
container.inject(unknownHandlerManager);
assertTrue(unknownHandlerManager.hasUnknownHandlers());
}
public void testEmptyStack() throws ConfigurationException {
final String filename = "com/opensymphony/xwork2/config/providers/xwork-unknownhandler-stack-empty.xml";
ConfigurationProvider provider = buildConfigurationProvider(filename);
loadConfigurationProviders(provider);
configurationManager.reload();
List<UnknownHandlerConfig> unknownHandlerStack = configuration.getUnknownHandlerStack();
assertNull(unknownHandlerStack);
}
}
@@ -0,0 +1,48 @@
/*
* 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 com.opensymphony.xwork2.config.providers;
import com.opensymphony.xwork2.config.ConfigurationProvider;
import com.opensymphony.xwork2.config.entities.PackageConfig;
public class XmlConfigurationProviderWildCardIncludeTest extends ConfigurationTestBase {
public void testWildCardInclude() throws Exception {
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-wildcard-include.xml";
ConfigurationProvider provider = buildConfigurationProvider(filename);
provider.init(configuration);
provider.loadPackages();
PackageConfig defaultWildcardPackage = configuration.getPackageConfig("default-wildcard");
assertNotNull(defaultWildcardPackage);
assertEquals("default-wildcard", defaultWildcardPackage.getName());
PackageConfig defaultOnePackage = configuration.getPackageConfig("default-1");
assertNotNull(defaultOnePackage);
assertEquals("default-1", defaultOnePackage.getName());
PackageConfig defaultTwoPackage = configuration.getPackageConfig("default-2");
assertNotNull(defaultTwoPackage);
assertEquals("default-2", defaultTwoPackage.getName());
configurationManager.addContainerProvider(provider);
configurationManager.reload();
}
}
@@ -0,0 +1,255 @@
package com.opensymphony.xwork2.config.providers;
import com.opensymphony.xwork2.XWorkTestCase;
import org.easymock.MockControl;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.Map;
/**
* <code>XmlHelperTest</code>
*
* @author <a href="mailto:hermanns@aixcept.de">Rainer Hermanns</a>
* @version $Id$
*/
public class XmlHelperTest extends XWorkTestCase {
public void testGetContent1() throws Exception {
// set up Node
MockControl nodeControl = MockControl.createControl(Node.class);
Node mockNode = (Node) nodeControl.getMock();
nodeControl.expectAndDefaultReturn(mockNode.getNodeValue(), "testing testing 123");
nodeControl.expectAndDefaultReturn(mockNode.getNodeType(), Node.TEXT_NODE);
// set up NodeList
MockControl nodeListControl = MockControl.createControl(NodeList.class);
NodeList mockNodeList = (NodeList) nodeListControl.getMock();
nodeListControl.expectAndDefaultReturn(mockNodeList.getLength(), 1);
nodeListControl.expectAndDefaultReturn(mockNodeList.item(0), mockNode);
// set up Element
MockControl elementControl = MockControl.createControl(Element.class);
Element mockElement = (Element) elementControl.getMock();
elementControl.expectAndDefaultReturn(mockElement.getChildNodes(), mockNodeList);
nodeControl.replay();
nodeListControl.replay();
elementControl.replay();
String result = XmlHelper.getContent(mockElement);
nodeControl.verify();
nodeListControl.verify();
elementControl.verify();
assertEquals(result, "testing testing 123");
}
public void testGetContent2() throws Exception {
// set up Node
MockControl nodeControl1 = MockControl.createControl(Node.class);
Node mockNode1 = (Node) nodeControl1.getMock();
nodeControl1.expectAndDefaultReturn(mockNode1.getNodeValue(), "testing testing 123");
nodeControl1.expectAndDefaultReturn(mockNode1.getNodeType(), Node.TEXT_NODE);
MockControl nodeControl2 = MockControl.createControl(Node.class);
Node mockNode2 = (Node) nodeControl2.getMock();
nodeControl2.expectAndDefaultReturn(mockNode2.getNodeValue(), "comment 1");
nodeControl2.expectAndDefaultReturn(mockNode2.getNodeType(), Node.COMMENT_NODE);
MockControl nodeControl3 = MockControl.createControl(Node.class);
Node mockNode3 = (Node) nodeControl3.getMock();
nodeControl3.expectAndDefaultReturn(mockNode3.getNodeValue(), " tmjee ");
nodeControl3.expectAndDefaultReturn(mockNode3.getNodeType(), Node.TEXT_NODE);
MockControl nodeControl4 = MockControl.createControl(Node.class);
Node mockNode4 = (Node) nodeControl4.getMock();
nodeControl4.expectAndDefaultReturn(mockNode4.getNodeValue(), " phil ");
nodeControl4.expectAndDefaultReturn(mockNode4.getNodeType(), Node.TEXT_NODE);
MockControl nodeControl5 = MockControl.createControl(Node.class);
Node mockNode5 = (Node) nodeControl5.getMock();
nodeControl5.expectAndDefaultReturn(mockNode5.getNodeValue(), "comment 2");
nodeControl5.expectAndDefaultReturn(mockNode5.getNodeType(), Node.COMMENT_NODE);
MockControl nodeControl6 = MockControl.createControl(Node.class);
Node mockNode6 = (Node) nodeControl6.getMock();
nodeControl6.expectAndDefaultReturn(mockNode6.getNodeValue(), "comment 3");
nodeControl6.expectAndDefaultReturn(mockNode6.getNodeType(), Node.COMMENT_NODE);
// set up NodeList
MockControl nodeListControl = MockControl.createControl(NodeList.class);
NodeList mockNodeList = (NodeList) nodeListControl.getMock();
nodeListControl.expectAndDefaultReturn(mockNodeList.getLength(), 6);
mockNodeList.item(0);
nodeListControl.setReturnValue(mockNode1);
mockNodeList.item(1);
nodeListControl.setReturnValue(mockNode2);
mockNodeList.item(2);
nodeListControl.setDefaultReturnValue(mockNode3);
mockNodeList.item(3);
nodeListControl.setReturnValue(mockNode4);
mockNodeList.item(4);
nodeListControl.setReturnValue(mockNode5);
mockNodeList.item(5);
nodeListControl.setReturnValue(mockNode6);
// set up Element
MockControl elementControl = MockControl.createControl(Element.class);
Element mockElement = (Element) elementControl.getMock();
elementControl.expectAndDefaultReturn(mockElement.getChildNodes(), mockNodeList);
nodeControl1.replay();
nodeControl2.replay();
nodeControl3.replay();
nodeControl4.replay();
nodeControl5.replay();
nodeControl6.replay();
nodeListControl.replay();
elementControl.replay();
String result = XmlHelper.getContent(mockElement);
nodeControl1.verify();
nodeControl2.verify();
nodeControl3.verify();
nodeControl4.verify();
nodeControl5.verify();
nodeControl6.verify();
nodeListControl.verify();
elementControl.verify();
assertEquals(result, "testing testing 123tmjeephil");
}
public void testGetParams() throws Exception {
// <param name="param1">value1</param>
MockControl nodeControl1 = MockControl.createControl(Node.class);
Node mockNode1 = (Node) nodeControl1.getMock();
nodeControl1.expectAndDefaultReturn(mockNode1.getNodeValue(), "value1");
nodeControl1.expectAndDefaultReturn(mockNode1.getNodeType(), Node.TEXT_NODE);
MockControl nodeListControl1 = MockControl.createControl(NodeList.class);
NodeList mockNodeList1 = (NodeList) nodeListControl1.getMock();
nodeListControl1.expectAndDefaultReturn(mockNodeList1.getLength(), 1);
nodeListControl1.expectAndDefaultReturn(mockNodeList1.item(0), mockNode1);
MockControl paramControl1 = MockControl.createControl(Element.class);
Element mockParamElement1 = (Element) paramControl1.getMock();
mockParamElement1.getNodeName();
paramControl1.setReturnValue("param");
mockParamElement1.getNodeType();
paramControl1.setReturnValue(Node.ELEMENT_NODE);
mockParamElement1.getAttribute("name");
paramControl1.setReturnValue("param1");
mockParamElement1.getChildNodes();
paramControl1.setReturnValue(mockNodeList1);
nodeControl1.replay();
nodeListControl1.replay();
paramControl1.replay();
// <param name="param2">value2</param>
MockControl nodeControl2 = MockControl.createControl(Node.class);
Node mockNode2 = (Node) nodeControl2.getMock();
nodeControl2.expectAndDefaultReturn(mockNode2.getNodeValue(), "value2");
nodeControl2.expectAndDefaultReturn(mockNode2.getNodeType(), Node.TEXT_NODE);
MockControl nodeListControl2 = MockControl.createControl(NodeList.class);
NodeList mockNodeList2 = (NodeList) nodeListControl2.getMock();
nodeListControl2.expectAndDefaultReturn(mockNodeList2.getLength(), 1);
nodeListControl2.expectAndDefaultReturn(mockNodeList2.item(0), mockNode2);
MockControl paramControl2 = MockControl.createControl(Element.class);
Element mockParamElement2 = (Element) paramControl2.getMock();
mockParamElement2.getNodeName();
paramControl2.setReturnValue("param");
mockParamElement2.getNodeType();
paramControl2.setReturnValue(Node.ELEMENT_NODE);
mockParamElement2.getAttribute("name");
paramControl2.setReturnValue("param2");
mockParamElement2.getChildNodes();
paramControl2.setReturnValue(mockNodeList2);
nodeControl2.replay();
nodeListControl2.replay();
paramControl2.replay();
// <some_element>
// ...
// </some_element>
MockControl elementNodeListControl = MockControl.createControl(NodeList.class);
NodeList mockElementNodeList = (NodeList) elementNodeListControl.getMock();
elementNodeListControl.expectAndDefaultReturn(mockElementNodeList.getLength(), 2);
mockElementNodeList.item(0);
elementNodeListControl.setReturnValue(mockParamElement2);
mockElementNodeList.item(1);
elementNodeListControl.setReturnValue(mockParamElement1);
MockControl elementControl = MockControl.createControl(Element.class);
Element element = (Element) elementControl.getMock();
elementControl.expectAndDefaultReturn(element.getChildNodes(), mockElementNodeList);
elementNodeListControl.replay();
elementControl.replay();
Map params = XmlHelper.getParams(element);
nodeControl1.verify();
nodeListControl1.verify();
paramControl1.verify();
nodeControl2.verify();
nodeListControl2.verify();
paramControl2.verify();
elementNodeListControl.verify();
elementControl.verify();
assertNotNull(params);
assertEquals(params.size(), 2);
assertEquals(params.get("param1"), "value1");
assertEquals(params.get("param2"), "value2");
}
}
@@ -0,0 +1,469 @@
/*
* 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 com.opensymphony.xwork2.conversion.impl;
import com.opensymphony.xwork2.*;
import com.opensymphony.xwork2.test.AnnotationUser;
import com.opensymphony.xwork2.test.ModelDrivenAnnotationAction2;
import com.opensymphony.xwork2.util.Bar;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.reflection.ReflectionContextState;
import ognl.OgnlException;
import ognl.OgnlRuntime;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @author $Author$
* @author Rainer Hermanns
* @version $Revision$
*/
public class AnnotationXWorkConverterTest extends XWorkTestCase {
ActionContext ac;
Map<String, Object> context;
XWorkConverter converter;
// public void testConversionToSetKeepsOriginalSetAndReplacesContents() {
// ValueStack stack = ValueStackFactory.getFactory().createValueStack();
//
// Map stackContext = stack.getContext();
// stackContext.put(InstantiatingNullHandler.CREATE_NULL_OBJECTS, Boolean.TRUE);
// stackContext.put(XWorkMethodAccessor.DENY_METHOD_EXECUTION, Boolean.TRUE);
// stackContext.put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE);
//
// String[] param = new String[] {"abc", "def", "ghi"};
// List paramList = Arrays.asList(param);
//
// List originalList = new ArrayList();
// originalList.add("jkl");
// originalList.add("mno");
//
// AnnotationUser user = new AnnotationUser();
// user.setList(originalList);
// stack.push(user);
//
// stack.setValue("list", param);
//
// List userList = user.getList();
// assertEquals(3,userList.size());
// assertEquals(paramList,userList);
// assertSame(originalList,userList);
// }
public void testArrayToNumberConversion() {
String[] value = new String[]{"12345"};
assertEquals(new Integer(12345), converter.convertValue(context, null, null, null, value, Integer.class));
assertEquals(new Long(12345), converter.convertValue(context, null, null, null, value, Long.class));
value[0] = "123.45";
assertEquals(new Float(123.45), converter.convertValue(context, null, null, null, value, Float.class));
assertEquals(new Double(123.45), converter.convertValue(context, null, null, null, value, Double.class));
value[0] = "1234567890123456789012345678901234567890";
assertEquals(new BigInteger(value[0]), converter.convertValue(context, null, null, null, value, BigInteger.class));
value[0] = "1234567890123456789.012345678901234567890";
assertEquals(new BigDecimal(value[0]), converter.convertValue(context, null, null, null, value, BigDecimal.class));
}
public void testDateConversion() throws ParseException {
java.sql.Date sqlDate = new java.sql.Date(System.currentTimeMillis());
assertEquals(sqlDate, converter.convertValue(context, null, null, null, sqlDate, Date.class));
SimpleDateFormat format = new SimpleDateFormat("mm/dd/yyyy hh:mm:ss");
Date date = format.parse("01/10/2001 00:00:00");
String dateStr = (String) converter.convertValue(context, null, null, null, date, String.class);
Date date2 = (Date) converter.convertValue(context, null, null, null, dateStr, Date.class);
assertEquals(date, date2);
}
public void testFieldErrorMessageAddedForComplexProperty() {
SimpleAnnotationAction action = new SimpleAnnotationAction();
action.setBean(new AnnotatedTestBean());
ValueStack stack = ActionContext.getContext().getValueStack();
stack.push(action);
Map<String, Object> ognlStackContext = stack.getContext();
ognlStackContext.put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE);
ognlStackContext.put(XWorkConverter.CONVERSION_PROPERTY_FULLNAME, "bean.birth");
String[] value = new String[]{"invalid date"};
assertEquals("Conversion should have failed.", OgnlRuntime.NoConversionPossible, converter.convertValue(ognlStackContext, action.getBean(), null, "birth", value, Date.class));
stack.pop();
Map conversionErrors = (Map) stack.getContext().get(ActionContext.CONVERSION_ERRORS);
assertNotNull(conversionErrors);
assertTrue(conversionErrors.size() == 1);
assertEquals(value, conversionErrors.get("bean.birth"));
}
public void testFieldErrorMessageAddedWhenConversionFails() {
SimpleAnnotationAction action = new SimpleAnnotationAction();
action.setDate(null);
ValueStack stack = ActionContext.getContext().getValueStack();
stack.push(action);
Map<String, Object> ognlStackContext = stack.getContext();
ognlStackContext.put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE);
String[] value = new String[]{"invalid date"};
assertEquals("Conversion should have failed.", OgnlRuntime.NoConversionPossible, converter.convertValue(ognlStackContext, action, null, "date", value, Date.class));
stack.pop();
Map conversionErrors = (Map) ognlStackContext.get(ActionContext.CONVERSION_ERRORS);
assertNotNull(conversionErrors);
assertEquals(1, conversionErrors.size());
assertNotNull(conversionErrors.get("date"));
assertEquals(value, conversionErrors.get("date"));
}
public void testFieldErrorMessageAddedWhenConversionFailsOnModelDriven() {
ModelDrivenAnnotationAction action = new ModelDrivenAnnotationAction();
ValueStack stack = ActionContext.getContext().getValueStack();
stack.push(action);
stack.push(action.getModel());
Map<String, Object> ognlStackContext = stack.getContext();
ognlStackContext.put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE);
String[] value = new String[]{"invalid date"};
assertEquals("Conversion should have failed.", OgnlRuntime.NoConversionPossible, converter.convertValue(ognlStackContext, action, null, "birth", value, Date.class));
stack.pop();
stack.pop();
Map conversionErrors = (Map) ognlStackContext.get(ActionContext.CONVERSION_ERRORS);
assertNotNull(conversionErrors);
assertEquals(1, conversionErrors.size());
assertNotNull(conversionErrors.get("birth"));
assertEquals(value, conversionErrors.get("birth"));
}
public void testFindConversionErrorMessage() {
ModelDrivenAnnotationAction action = new ModelDrivenAnnotationAction();
ValueStack stack = ActionContext.getContext().getValueStack();
stack.push(action);
stack.push(action.getModel());
String message = XWorkConverter.getConversionErrorMessage("birth", stack);
assertNotNull(message);
assertEquals("Invalid date for birth.", message);
message = XWorkConverter.getConversionErrorMessage("foo", stack);
assertNotNull(message);
assertEquals("Invalid field value for field \"foo\".", message);
}
public void testFindConversionMappingForInterface() {
ModelDrivenAnnotationAction2 action = new ModelDrivenAnnotationAction2();
ValueStack stack = ActionContext.getContext().getValueStack();
stack.push(action);
stack.push(action.getModel());
Map<String, Object> ognlStackContext = stack.getContext();
ognlStackContext.put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE);
String value = "asdf:123";
Object o = converter.convertValue(ognlStackContext, action.getModel(), null, "barObj", value, Bar.class);
assertNotNull(o);
assertTrue("class is: " + o.getClass(), o instanceof Bar);
Bar b = (Bar) o;
assertEquals(value, b.getTitle() + ":" + b.getSomethingElse());
}
public void testLocalizedDateConversion() throws Exception {
Date date = new Date(System.currentTimeMillis());
Locale locale = Locale.GERMANY;
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
String dateString = df.format(date);
context.put(ActionContext.LOCALE, locale);
assertEquals(dateString, converter.convertValue(context, null, null, null, date, String.class));
}
public void testStringArrayToCollection() {
List<String> list = new ArrayList<>();
list.add("foo");
list.add("bar");
list.add("baz");
assertEquals(list, converter.convertValue(context, null, null, null, new String[]{
"foo", "bar", "baz"
}, Collection.class));
}
public void testStringArrayToList() {
List<String> list = new ArrayList<String>();
list.add("foo");
list.add("bar");
list.add("baz");
assertEquals(list, converter.convertValue(context, null, null, null, new String[]{
"foo", "bar", "baz"
}, List.class));
}
public void testStringArrayToPrimitiveWrappers() {
Long[] longs = (Long[]) converter.convertValue(context, null, null, null, new String[]{
"123", "456"
}, Long[].class);
assertNotNull(longs);
assertTrue(Arrays.equals(new Long[]{123L, 456L}, longs));
Integer[] ints = (Integer[]) converter.convertValue(context, null, null, null, new String[]{
"123", "456"
}, Integer[].class);
assertNotNull(ints);
assertTrue(Arrays.equals(new Integer[]{123, 456}, ints));
Double[] doubles = (Double[]) converter.convertValue(context, null, null, null, new String[]{
"123", "456"
}, Double[].class);
assertNotNull(doubles);
assertTrue(Arrays.equals(new Double[]{123D, 456D}, doubles));
Float[] floats = (Float[]) converter.convertValue(context, null, null, null, new String[]{
"123", "456"
}, Float[].class);
assertNotNull(floats);
assertTrue(Arrays.equals(new Float[]{123F, 456F}, floats));
Boolean[] booleans = (Boolean[]) converter.convertValue(context, null, null, null, new String[]{
"true", "false"
}, Boolean[].class);
assertNotNull(booleans);
assertTrue(Arrays.equals(new Boolean[]{Boolean.TRUE, Boolean.FALSE}, booleans));
}
public void testStringArrayToPrimitives() throws OgnlException {
long[] longs = (long[]) converter.convertValue(context, null, null, null, new String[]{
"123", "456"
}, long[].class);
assertNotNull(longs);
assertTrue(Arrays.equals(new long[]{123, 456}, longs));
int[] ints = (int[]) converter.convertValue(context, null, null, null, new String[]{
"123", "456"
}, int[].class);
assertNotNull(ints);
assertTrue(Arrays.equals(new int[]{123, 456}, ints));
double[] doubles = (double[]) converter.convertValue(context, null, null, null, new String[]{
"123", "456"
}, double[].class);
assertNotNull(doubles);
assertTrue(Arrays.equals(new double[]{123, 456}, doubles));
float[] floats = (float[]) converter.convertValue(context, null, null, null, new String[]{
"123", "456"
}, float[].class);
assertNotNull(floats);
assertTrue(Arrays.equals(new float[]{123, 456}, floats));
boolean[] booleans = (boolean[]) converter.convertValue(context, null, null, null, new String[]{
"true", "false"
}, boolean[].class);
assertNotNull(booleans);
assertTrue(Arrays.equals(new boolean[]{true, false}, booleans));
}
public void testStringArrayToSet() {
Set<String> list = new HashSet<>();
list.add("foo");
list.add("bar");
list.add("baz");
assertEquals(list, converter.convertValue(context, null, null, null, new String[]{
"foo", "bar", "bar", "baz"
}, Set.class));
}
// TODO: Fixme... This test does not work with GenericsObjectDeterminer!
public void testStringToCollectionConversion() {
ValueStack stack = ActionContext.getContext().getValueStack();
Map<String, Object> stackContext = stack.getContext();
stackContext.put(ReflectionContextState.CREATE_NULL_OBJECTS, Boolean.TRUE);
stackContext.put(ReflectionContextState.DENY_METHOD_EXECUTION, Boolean.TRUE);
stackContext.put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE);
AnnotationUser user = new AnnotationUser();
stack.push(user);
stack.setValue("list", "asdf");
assertNotNull(user.getList());
assertEquals(1, user.getList().size());
assertEquals(String.class, user.getList().get(0).getClass());
assertEquals("asdf", user.getList().get(0));
}
public void testStringToCustomTypeUsingCustomConverter() {
// the converter needs to be registered as the Bar.class converter
// it won't be detected from the Foo-conversion.properties
// because the Foo-conversion.properties file is only used when converting a property of Foo
converter.registerConverter(Bar.class.getName(), new FooBarConverter());
Bar bar = (Bar) converter.convertValue(null, null, null, null, "blah:123", Bar.class);
assertNotNull("conversion failed", bar);
assertEquals(123, bar.getSomethingElse());
assertEquals("blah", bar.getTitle());
}
public void testStringToPrimitiveWrappers() {
assertEquals(new Long(123), converter.convertValue(context, null, null, null, "123", Long.class));
assertEquals(new Integer(123), converter.convertValue(context, null, null, null, "123", Integer.class));
assertEquals(new Double(123.5), converter.convertValue(context, null, null, null, "123.5", Double.class));
assertEquals(new Float(123.5), converter.convertValue(context, null, null, null, "123.5", float.class));
assertEquals(false, converter.convertValue(context, null, null, null, "false", Boolean.class));
assertEquals(true, converter.convertValue(context, null, null, null, "true", Boolean.class));
}
public void testStringToPrimitives() {
assertEquals(new Long(123), converter.convertValue(context, null, null, null, "123", long.class));
assertEquals(new Integer(123), converter.convertValue(context, null, null, null, "123", int.class));
assertEquals(new Double(123.5), converter.convertValue(context, null, null, null, "123.5", double.class));
assertEquals(new Float(123.5), converter.convertValue(context, null, null, null, "123.5", float.class));
assertEquals(false, converter.convertValue(context, null, null, null, "false", boolean.class));
assertEquals(true, converter.convertValue(context, null, null, null, "true", boolean.class));
assertEquals(new BigDecimal(123.5), converter.convertValue(context, null, null, null, "123.5", BigDecimal.class));
assertEquals(new BigInteger("123"), converter.convertValue(context, null, null, null, "123", BigInteger.class));
}
public void testValueStackWithTypeParameter() {
ValueStack stack = ActionContext.getContext().getValueStack();
stack.push(new Foo1());
Bar1 bar = (Bar1) stack.findValue("bar", Bar1.class);
assertNotNull(bar);
}
public void testGenericProperties() {
GenericsBean gb = new GenericsBean();
ValueStack stack = ac.getValueStack();
stack.push(gb);
String[] value = new String[] {"123.12", "123.45"};
stack.setValue("doubles", value);
assertEquals(2, gb.getDoubles().size());
assertEquals(Double.class, gb.getDoubles().get(0).getClass());
assertEquals(new Double(123.12), gb.getDoubles().get(0));
assertEquals(new Double(123.45), gb.getDoubles().get(1));
}
public void testGenericPropertiesFromField() {
GenericsBean gb = new GenericsBean();
ValueStack stack = ac.getValueStack();
stack.push(gb);
stack.setValue("genericMap[123.12]", "66");
stack.setValue("genericMap[456.12]", "42");
assertEquals(2, gb.getGenericMap().size());
assertEquals("66", stack.findValue("genericMap.get(123.12).toString()"));
assertEquals("42", stack.findValue("genericMap.get(456.12).toString()"));
assertEquals(66, stack.findValue("genericMap.get(123.12)"));
assertEquals(42, stack.findValue("genericMap.get(456.12)"));
assertEquals(true, stack.findValue("genericMap.containsValue(66)"));
assertEquals(true, stack.findValue("genericMap.containsValue(42)"));
assertEquals(true, stack.findValue("genericMap.containsKey(123.12)"));
assertEquals(true, stack.findValue("genericMap.containsKey(456.12)"));
}
public void testGenericPropertiesFromSetter() {
GenericsBean gb = new GenericsBean();
ValueStack stack = ac.getValueStack();
stack.push(gb);
stack.setValue("genericMap[123.12]", "66");
stack.setValue("genericMap[456.12]", "42");
assertEquals(2, gb.getGenericMap().size());
assertEquals("66", stack.findValue("genericMap.get(123.12).toString()"));
assertEquals("42", stack.findValue("genericMap.get(456.12).toString()"));
assertEquals(66, stack.findValue("genericMap.get(123.12)"));
assertEquals(42, stack.findValue("genericMap.get(456.12)"));
assertEquals(true, stack.findValue("genericMap.containsValue(66)"));
assertEquals(true, stack.findValue("genericMap.containsValue(42)"));
assertEquals(true, stack.findValue("genericMap.containsKey(123.12)"));
assertEquals(true, stack.findValue("genericMap.containsKey(456.12)"));
}
public void testGenericPropertiesFromGetter() {
GenericsBean gb = new GenericsBean();
ValueStack stack = ac.getValueStack();
stack.push(gb);
assertEquals(1, gb.getGetterList().size());
assertEquals("42.42", stack.findValue("getterList.get(0).toString()"));
assertEquals(new Double(42.42), stack.findValue("getterList.get(0)"));
assertEquals(new Double(42.42), gb.getGetterList().get(0));
}
// FIXME: Implement nested Generics such as: List of Generics List, Map of Generic keys/values, etc...
public void no_testGenericPropertiesWithNestedGenerics() {
GenericsBean gb = new GenericsBean();
ValueStack stack = ac.getValueStack();
stack.push(gb);
stack.setValue("extendedMap[123.12]", new String[] {"1", "2", "3", "4"});
stack.setValue("extendedMap[456.12]", new String[] {"5", "6", "7", "8", "9"});
System.out.println("gb.getExtendedMap(): " + gb.getExtendedMap());
assertEquals(2, gb.getExtendedMap().size());
System.out.println(stack.findValue("extendedMap"));
assertEquals(4, stack.findValue("extendedMap.get(123.12).size"));
assertEquals(5, stack.findValue("extendedMap.get(456.12).size"));
assertEquals("1", stack.findValue("extendedMap.get(123.12).get(0)"));
assertEquals("5", stack.findValue("extendedMap.get(456.12).get(0)"));
assertEquals(Integer.class, stack.findValue("extendedMap.get(123.12).get(0).class"));
assertEquals(Integer.class, stack.findValue("extendedMap.get(456.12).get(0).class"));
assertEquals(List.class, stack.findValue("extendedMap.get(123.12).class"));
assertEquals(List.class, stack.findValue("extendedMap.get(456.12).class"));
}
public static class Foo1 {
public Bar1 getBar() {
return new Bar1Impl();
}
}
public interface Bar1 {
}
public static class Bar1Impl implements Bar1 {
}
@Override
protected void setUp() throws Exception {
super.setUp();
converter = container.getInstance(XWorkConverter.class);
ac = ActionContext.getContext();
ac.setLocale(Locale.US);
context = ac.getContextMap();
}
@Override
protected void tearDown() throws Exception {
ActionContext.setContext(null);
}
}
@@ -0,0 +1,72 @@
/*
* 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 com.opensymphony.xwork2.conversion.impl;
import com.opensymphony.xwork2.util.AnnotatedCat;
import com.opensymphony.xwork2.util.Bar;
import com.opensymphony.xwork2.util.Cat;
import java.lang.reflect.Member;
import java.util.Map;
/**
* @author <a href="mailto:plightbo@cisco.com">Pat Lightbody</a>
* @author $Author$
* @version $Revision$
*/
public class FooBarConverter extends DefaultTypeConverter {
@Override
public Object convertValue(Map<String, Object> context, Object value, Class toType) {
if (toType == String.class) {
Bar bar = (Bar) value;
return bar.getTitle() + ":" + bar.getSomethingElse();
} else if (toType == Bar.class) {
String valueStr = (String) value;
int loc = valueStr.indexOf(":");
String title = valueStr.substring(0, loc);
String rest = valueStr.substring(loc + 1);
Bar bar = new Bar();
bar.setTitle(title);
bar.setSomethingElse(Integer.parseInt(rest));
return bar;
} else if (toType == Cat.class) {
Cat cat = new Cat();
cat.setName((String) value);
return cat;
} else if (toType == AnnotatedCat.class) {
AnnotatedCat cat = new AnnotatedCat();
cat.setName((String) value);
return cat;
} else {
System.out.println("Don't know how to convert between " + value.getClass().getName() +
" and " + toType.getName());
}
return null;
}
@Override
public Object convertValue(Map<String, Object> context, Object source, Member member, String property, Object value, Class toClass) {
return convertValue(context, value, toClass);
}
}
@@ -0,0 +1,18 @@
package com.opensymphony.xwork2.conversion.impl;
import java.util.Map;
public class FooNumberConverter extends DefaultTypeConverter {
@Override
public Object convertValue(Map<String, Object> map, Object object, Class aClass) {
String s = (String) object;
int length = s.length();
StringBuilder r = new StringBuilder();
for (int i = length; i > 0; i--) {
r.append(s.charAt(i - 1));
}
return super.convertValue(map, r.toString(), aClass);
}
}
@@ -0,0 +1,54 @@
/*
* 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 com.opensymphony.xwork2.conversion.impl;
import junit.framework.TestCase;
/**
* DOCUMENT ME!
*
* @author $author$
* @version $Revision$
*/
public class InstantiatingNullHandlerTest extends TestCase {
public void testBlank() {
}
/*public void testInheritance() {
Tiger t = new Tiger();
CompoundRoot root = new CompoundRoot();
root.add(t);
Map context = new OgnlContext();
context.put(InstantiatingNullHandler.CREATE_NULL_OBJECTS, Boolean.TRUE);
InstantiatingNullHandler nh = new InstantiatingNullHandler();
Object dogList = nh.nullPropertyValue(context, root, "dogs");
Class clazz = nh.getCollectionType(Tiger.class, "dogs");
assertEquals(Dog.class, clazz);
assertNotNull(dogList);
assertTrue(dogList instanceof List);
Object kittenList = nh.nullPropertyValue(context, root, "kittens");
clazz = nh.getCollectionType(Tiger.class, "kittens");
assertEquals(Cat.class, clazz);
assertNotNull(kittenList);
assertTrue(kittenList instanceof List);
}*/
}
@@ -0,0 +1,42 @@
package com.opensymphony.xwork2.conversion.impl;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.SimpleFooAction;
import com.opensymphony.xwork2.XWorkTestCase;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
public class NumberConverterTest extends XWorkTestCase {
public void testStringToNumberConversionPL() throws Exception {
// given
NumberConverter converter = new NumberConverter();
Map<String, Object> context = new HashMap<>();
context.put(ActionContext.LOCALE, new Locale("pl", "PL"));
SimpleFooAction foo = new SimpleFooAction();
// when
Object value = converter.convertValue(context, foo, null, "id", "1234", Integer.class);
// then
assertEquals(1234, value);
}
public void testStringToNumberConversionUS() throws Exception {
// given
NumberConverter converter = new NumberConverter();
Map<String, Object> context = new HashMap<>();
context.put(ActionContext.LOCALE, new Locale("en", "US"));
SimpleFooAction foo = new SimpleFooAction();
// when
Object value = converter.convertValue(context, foo, null, "id", ",1234", Integer.class);
// then
assertEquals(1234, value);
}
}
@@ -0,0 +1,27 @@
package com.opensymphony.xwork2.conversion.impl;
/**
* <code>ParentClass</code>
*
* @author <a href="mailto:hermanns@aixcept.de">Rainer Hermanns</a>
* @version $Id$
*/
public class ParentClass {
public enum NestedEnum {
TEST,
TEST2,
TEST3
}
private NestedEnum value;
public void setValue(NestedEnum value) {
this.value = value;
}
public NestedEnum getValue() {
return value;
}
}
@@ -0,0 +1,260 @@
/*
* Copyright 2002-2007,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 com.opensymphony.xwork2.conversion.impl;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.XWorkException;
import com.opensymphony.xwork2.XWorkTestCase;
import com.opensymphony.xwork2.test.annotations.Person;
import java.text.DateFormat;
import java.util.*;
/**
* Test case for XWorkBasicConverter
*
* @author tm_jee
* @version $Date$ $Id$
*/
public class XWorkBasicConverterTest extends XWorkTestCase {
private XWorkBasicConverter basicConverter;
// TODO: test for every possible conversion
// take into account of empty string
// primitive -> conversion error when empty string is passed
// object -> return null when empty string is passed
public void testDateConversionWithEmptyValue() {
Object convertedObject = basicConverter.convertValue(new HashMap<String, Object>(), null, null, null, "", Date.class);
// we must not get XWorkException as that will caused a conversion error
assertNull(convertedObject);
}
public void testDateConversionWithInvalidValue() throws Exception {
try {
Object convertedObject = basicConverter.convertValue(new HashMap<String, Object>(), null, null, null, "asdsd", Date.class);
fail("XWorkException expected - conversion error occurred");
} catch (XWorkException e) {
// we MUST get this exception as this is a conversion error
}
}
public void testDateWithLocalePoland() throws Exception {
Map<String, Object> map = new HashMap<>();
Locale locale = new Locale("pl", "PL");
map.put(ActionContext.LOCALE, locale);
String reference = "2009-01-09";
Object convertedObject = basicConverter.convertValue(map, null, null, null, reference, Date.class);
assertNotNull(convertedObject);
compareDates(locale, convertedObject);
}
public void testDateWithLocaleFrance() throws Exception {
Map<String, Object> map = new HashMap<>();
Locale locale = new Locale("fr", "FR");
map.put(ActionContext.LOCALE, locale);
String reference = "09/01/2009";
Object convertedObject = basicConverter.convertValue(map, null, null, null, reference, Date.class);
assertNotNull(convertedObject);
compareDates(locale, convertedObject);
}
public void testDateWithLocaleUK() throws Exception {
Map<String, Object> map = new HashMap<>();
Locale locale = new Locale("en", "US");
map.put(ActionContext.LOCALE, locale);
String reference = "01/09/2009";
Object convertedObject = basicConverter.convertValue(map, null, null, null, reference, Date.class);
assertNotNull(convertedObject);
compareDates(locale, convertedObject);
}
private void compareDates(Locale locale, Object convertedObject) {
Calendar cal = Calendar.getInstance(locale);
cal.set(Calendar.YEAR, 2009);
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.DATE, 9);
Calendar cal1 = Calendar.getInstance(locale);
cal1.setTime((Date) convertedObject);
assertEquals(cal.get(Calendar.YEAR), cal1.get(Calendar.YEAR));
assertEquals(cal.get(Calendar.MONTH), cal1.get(Calendar.MONTH));
assertEquals(cal.get(Calendar.DATE), cal1.get(Calendar.DATE));
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
assertEquals(df.format(cal.getTime()), df.format(convertedObject));
}
public void testEmptyArrayConversion() throws Exception {
Object convertedObject = basicConverter.convertValue(new HashMap<String, Object>(), null, null, null, new Object[]{}, Object[].class);
// we must not get XWorkException as that will caused a conversion error
assertEquals(Object[].class, convertedObject.getClass());
Object[] obj = (Object[]) convertedObject;
assertEquals(0, obj.length);
}
public void testNullArrayConversion() throws Exception {
Object convertedObject = basicConverter.convertValue(new HashMap<String, Object>(), null, null, null, null, Object[].class);
// we must not get XWorkException as that will caused a conversion error
assertNull(convertedObject);
}
/* the code below has been disabled as it causes sideffects in Strtus2 (XW-512)
public void testXW490ConvertStringToDouble() throws Exception {
Locale locale = new Locale("DA"); // let's use a not common locale such as Denmark
Map ctx = new HashMap();
ctx.put(ActionContext.LOCALE, locale);
XWorkBasicConverter conv = new XWorkBasicConverter();
// decimal seperator is , in Denmark so we should write 123,99 as input
Double value = (Double) conv.convertValue(ctx, null, null, null, "123,99", Double.class);
assertNotNull(value);
// output is as expected a real double value converted using Denmark as locale
assertEquals(123.99d, value.doubleValue(), 0.001d);
}
public void testXW49ConvertDoubleToString() throws Exception {
Locale locale = new Locale("DA"); // let's use a not common locale such as Denmark
Map ctx = new HashMap();
ctx.put(ActionContext.LOCALE, locale);
XWorkBasicConverter conv = new XWorkBasicConverter();
// decimal seperator is , in Denmark so we should write 123,99 as input
String value = (String) conv.convertValue(ctx, null, null, null, new Double("123.99"), String.class);
assertNotNull(value);
// output should be formatted according to Danish locale using , as decimal seperator
assertEquals("123,99", value);
}
*/
public void testDoubleValues() {
NumberConverter numberConverter = new NumberConverter();
assertTrue(numberConverter.isInRange(-1.2, "-1.2", Double.class));
assertTrue(numberConverter.isInRange(1.5, "1.5", Double.class));
Object value = basicConverter.convertValue("-1.3", double.class);
assertNotNull(value);
assertEquals(-1.3, value);
value = basicConverter.convertValue("1.8", double.class);
assertNotNull(value);
assertEquals(1.8, value);
value = basicConverter.convertValue("-1.9", double.class);
assertNotNull(value);
assertEquals(-1.9, value);
value = basicConverter.convertValue("1.7", Double.class);
assertNotNull(value);
assertEquals(1.7, value);
value = basicConverter.convertValue("0.0", Double.class);
assertNotNull(value);
assertEquals(0.0, value);
value = basicConverter.convertValue("0.0", double.class);
assertNotNull(value);
assertEquals(0.0, value);
}
public void testFloatValues() {
NumberConverter numberConverter = new NumberConverter();
assertTrue(numberConverter.isInRange(-1.65, "-1.65", Float.class));
assertTrue(numberConverter.isInRange(1.9876, "1.9876", float.class));
Float value = (Float) basicConverter.convertValue("-1.444401", Float.class);
assertNotNull(value);
assertEquals(Float.valueOf("-1.444401"), value);
value = (Float) basicConverter.convertValue("1.46464989", Float.class);
assertNotNull(value);
assertEquals(Float.valueOf(1.46464989f), value);
}
public void testNegativeFloatValue() throws Exception {
Object convertedObject = basicConverter.convertValue("-94.1231233", Float.class);
assertTrue(convertedObject instanceof Float);
assertEquals(-94.1231233f, ((Float) convertedObject).floatValue(), 0.0001);
}
public void testPositiveFloatValue() throws Exception {
Object convertedObject = basicConverter.convertValue("94.1231233", Float.class);
assertTrue(convertedObject instanceof Float);
assertEquals(94.1231233f, ((Float) convertedObject).floatValue(), 0.0001);
}
public void testNegativeDoubleValue() throws Exception {
Object convertedObject = basicConverter.convertValue("-94.1231233", Double.class);
assertTrue(convertedObject instanceof Double);
assertEquals(-94.1231233d, ((Double) convertedObject).doubleValue(), 0.0001);
}
public void testPositiveDoubleValue() throws Exception {
Object convertedObject = basicConverter.convertValue("94.1231233", Double.class);
assertTrue(convertedObject instanceof Double);
assertEquals(94.1231233d, ((Double) convertedObject).doubleValue(), 0.0001);
}
public void testNestedEnumValue() throws Exception {
Object convertedObject = basicConverter.convertValue(ParentClass.NestedEnum.TEST.name(), ParentClass.NestedEnum.class);
assertTrue(convertedObject instanceof ParentClass.NestedEnum);
assertEquals(ParentClass.NestedEnum.TEST, convertedObject);
}
public void testConvert() {
Map<String, Object> context = new HashMap<>();
Person o = new Person();
String s = "names";
Object value = new Person[0];
Class toType = String.class;
basicConverter.convertValue(context, value, null, s, value, toType);
}
@Override
protected void setUp() throws Exception {
super.setUp();
basicConverter = container.getInstance(XWorkBasicConverter.class);
}
@Override
protected void tearDown() throws Exception {
ActionContext.setContext(null);
}
}
@@ -0,0 +1,715 @@
/*
* 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 com.opensymphony.xwork2.conversion.impl;
import com.opensymphony.xwork2.*;
import com.opensymphony.xwork2.ognl.OgnlValueStack;
import com.opensymphony.xwork2.test.ModelDrivenAction2;
import com.opensymphony.xwork2.test.User;
import com.opensymphony.xwork2.util.Bar;
import com.opensymphony.xwork2.util.Cat;
import com.opensymphony.xwork2.util.Foo;
import com.opensymphony.xwork2.util.FurColor;
import com.opensymphony.xwork2.util.reflection.ReflectionContextState;
import ognl.OgnlException;
import ognl.OgnlRuntime;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URL;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @author $Author$
* @version $Revision$
*/
public class XWorkConverterTest extends XWorkTestCase {
Map<String, Object> context;
XWorkConverter converter;
OgnlValueStack stack;
// public void testConversionToSetKeepsOriginalSetAndReplacesContents() {
// ValueStack stack = ValueStackFactory.getFactory().createValueStack();
//
// Map stackContext = stack.getContext();
// stackContext.put(InstantiatingNullHandler.CREATE_NULL_OBJECTS, Boolean.TRUE);
// stackContext.put(XWorkMethodAccessor.DENY_METHOD_EXECUTION, Boolean.TRUE);
// stackContext.put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE);
//
// String[] param = new String[] {"abc", "def", "ghi"};
// List paramList = Arrays.asList(param);
//
// List originalList = new ArrayList();
// originalList.add("jkl");
// originalList.add("mno");
//
// User user = new User();
// user.setList(originalList);
// stack.push(user);
//
// stack.setValue("list", param);
//
// List userList = user.getList();
// assertEquals(3,userList.size());
// assertEquals(paramList,userList);
// assertSame(originalList,userList);
// }
public void testArrayToNumberConversion() {
String[] value = new String[]{"12345"};
assertEquals(new Integer(12345), converter.convertValue(context, null, null, null, value, Integer.class));
assertEquals(new Long(12345), converter.convertValue(context, null, null, null, value, Long.class));
value[0] = "123.45";
assertEquals(new Float(123.45), converter.convertValue(context, null, null, null, value, Float.class));
assertEquals(new Double(123.45), converter.convertValue(context, null, null, null, value, Double.class));
value[0] = "1234567890123456789012345678901234567890";
assertEquals(new BigInteger(value[0]), converter.convertValue(context, null, null, null, value, BigInteger.class));
value[0] = "1234567890123456789.012345678901234567890";
assertEquals(new BigDecimal(value[0]), converter.convertValue(context, null, null, null, value, BigDecimal.class));
}
public void testDateConversion() throws ParseException {
java.sql.Date sqlDate = new java.sql.Date(System.currentTimeMillis());
assertEquals(sqlDate, converter.convertValue(context, null, null, null, sqlDate, Date.class));
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
Date date = format.parse("01/10/2001 00:00:00");
SimpleDateFormat formatt = new SimpleDateFormat("hh:mm:ss");
java.sql.Time datet = new java.sql.Time(formatt.parse("10:11:12").getTime());
String dateStr = (String) converter.convertValue(context, null, null, null, date, String.class);
String datetStr = (String) converter.convertValue(context, null, null, null, datet, String.class);
Date date2 = (Date) converter.convertValue(context, null, null, null, dateStr, Date.class);
assertEquals(date, date2);
java.sql.Date date3 = (java.sql.Date) converter.convertValue(context, null, null, null, dateStr, java.sql.Date.class);
assertEquals(date, date3);
java.sql.Timestamp ts = (java.sql.Timestamp) converter.convertValue(context, null, null, null, dateStr, java.sql.Timestamp.class);
assertEquals(date, ts);
java.sql.Time time1 = (java.sql.Time) converter.convertValue(context, null, null, null, datetStr, java.sql.Time.class);
assertEquals(datet, time1);
}
public void testFieldErrorMessageAddedForComplexProperty() {
SimpleAction action = new SimpleAction();
action.setBean(new TestBean());
stack.push(action);
Map<String, Object> ognlStackContext = stack.getContext();
ognlStackContext.put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE);
ognlStackContext.put(XWorkConverter.CONVERSION_PROPERTY_FULLNAME, "bean.birth");
String[] value = new String[]{"invalid date"};
assertEquals("Conversion should have failed.", OgnlRuntime.NoConversionPossible, converter.convertValue(ognlStackContext, action.getBean(), null, "birth", value, Date.class));
stack.pop();
Map conversionErrors = (Map) stack.getContext().get(ActionContext.CONVERSION_ERRORS);
assertNotNull(conversionErrors);
assertTrue(conversionErrors.size() == 1);
assertEquals(value, conversionErrors.get("bean.birth"));
}
public void testFieldErrorMessageAddedWhenConversionFails() {
SimpleAction action = new SimpleAction();
action.setDate(null);
stack.push(action);
Map<String, Object> ognlStackContext = stack.getContext();
ognlStackContext.put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE);
String[] value = new String[]{"invalid date"};
assertEquals("Conversion should have failed.", OgnlRuntime.NoConversionPossible, converter.convertValue(ognlStackContext, action, null, "date", value, Date.class));
stack.pop();
Map conversionErrors = (Map) ognlStackContext.get(ActionContext.CONVERSION_ERRORS);
assertNotNull(conversionErrors);
assertEquals(1, conversionErrors.size());
assertNotNull(conversionErrors.get("date"));
assertEquals(value, conversionErrors.get("date"));
}
public void testFieldErrorMessageAddedWhenConversionFailsOnModelDriven() {
ModelDrivenAction action = new ModelDrivenAction();
stack.push(action);
stack.push(action.getModel());
Map<String, Object> ognlStackContext = stack.getContext();
ognlStackContext.put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE);
String[] value = new String[]{"invalid date"};
assertEquals("Conversion should have failed.", OgnlRuntime.NoConversionPossible, converter.convertValue(ognlStackContext, action, null, "birth", value, Date.class));
stack.pop();
stack.pop();
Map conversionErrors = (Map) ognlStackContext.get(ActionContext.CONVERSION_ERRORS);
assertNotNull(conversionErrors);
assertEquals(1, conversionErrors.size());
assertNotNull(conversionErrors.get("birth"));
assertEquals(value, conversionErrors.get("birth"));
}
public void testDateStrictConversion() throws Exception {
// see XW-341
String dateStr = "13/01/2005"; // us date format is used in context
Object res = converter.convertValue(context, null, null, null, dateStr, Date.class);
assertEquals(res, OgnlRuntime.NoConversionPossible);
dateStr = "02/30/2005"; // us date format is used in context
res = converter.convertValue(context, null, null, null, dateStr, Date.class);
assertEquals(res, OgnlRuntime.NoConversionPossible);
// and test a date that is passable
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
dateStr = "12/31/2005"; // us date format
res = converter.convertValue(context, null, null, null, dateStr, Date.class);
Date date = format.parse(dateStr);
assertNotSame(res, OgnlRuntime.NoConversionPossible);
assertEquals(date, res);
}
public void testFindConversionErrorMessage() {
ModelDrivenAction action = new ModelDrivenAction();
stack.push(action);
stack.push(action.getModel());
String message = XWorkConverter.getConversionErrorMessage("birth", stack);
assertNotNull(message);
assertEquals("Invalid date for birth.", message);
message = XWorkConverter.getConversionErrorMessage("foo", stack);
assertNotNull(message);
assertEquals("Invalid field value for field \"foo\".", message);
}
public void testFindConversionMappingForInterface() {
ModelDrivenAction2 action = new ModelDrivenAction2();
stack.push(action);
stack.push(action.getModel());
Map<String, Object> ognlStackContext = stack.getContext();
ognlStackContext.put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE);
String value = "asdf:123";
Object o = converter.convertValue(ognlStackContext, action.getModel(), null, "barObj", value, Bar.class);
assertNotNull(o);
assertTrue(o instanceof Bar);
Bar b = (Bar) o;
assertEquals(value, b.getTitle() + ":" + b.getSomethingElse());
}
public void testLocalizedDateConversion() throws Exception {
Date date = new Date(System.currentTimeMillis());
Locale locale = Locale.GERMANY;
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
String dateString = df.format(date);
context.put(ActionContext.LOCALE, locale);
assertEquals(dateString, converter.convertValue(context, null, null, null, date, String.class));
}
public void testStringToIntConversions() {
SimpleAction action = new SimpleAction();
action.setBean(new TestBean());
stack.push(action);
Map<String, Object> ognlStackContext = stack.getContext();
ognlStackContext.put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE);
assertEquals("Conversion should have failed.", OgnlRuntime.NoConversionPossible, converter.convertValue(ognlStackContext, action.getBean(), null, "count", "111.1", int.class));
stack.pop();
Map conversionErrors = (Map) stack.getContext().get(ActionContext.CONVERSION_ERRORS);
assertNotNull(conversionErrors);
assertTrue(conversionErrors.size() == 1);
}
public void testStringArrayToCollection() {
List<String> list = new ArrayList<>();
list.add("foo");
list.add("bar");
list.add("baz");
assertEquals(list, converter.convertValue(context, null, null, null, new String[]{
"foo", "bar", "baz"
}, Collection.class));
}
public void testStringArrayToList() {
List<String> list = new ArrayList<>();
list.add("foo");
list.add("bar");
list.add("baz");
assertEquals(list, converter.convertValue(context, null, null, null, new String[]{
"foo", "bar", "baz"
}, List.class));
}
public void testStringArrayToPrimitiveWrappers() {
Long[] longs = (Long[]) converter.convertValue(context, null, null, null, new String[]{
"123", "456"
}, Long[].class);
assertNotNull(longs);
assertTrue(Arrays.equals(new Long[]{123L, 456L}, longs));
Integer[] ints = (Integer[]) converter.convertValue(context, null, null, null, new String[]{
"123", "456"
}, Integer[].class);
assertNotNull(ints);
assertTrue(Arrays.equals(new Integer[]{123, 456}, ints));
Double[] doubles = (Double[]) converter.convertValue(context, null, null, null, new String[]{
"123", "456"
}, Double[].class);
assertNotNull(doubles);
assertTrue(Arrays.equals(new Double[]{123D, 456D}, doubles));
Float[] floats = (Float[]) converter.convertValue(context, null, null, null, new String[]{
"123", "456"
}, Float[].class);
assertNotNull(floats);
assertTrue(Arrays.equals(new Float[]{123F, 456F}, floats));
Boolean[] booleans = (Boolean[]) converter.convertValue(context, null, null, null, new String[]{
"true", "false"
}, Boolean[].class);
assertNotNull(booleans);
assertTrue(Arrays.equals(new Boolean[]{Boolean.TRUE, Boolean.FALSE}, booleans));
}
public void testStringArrayToPrimitives() throws OgnlException {
long[] longs = (long[]) converter.convertValue(context, null, null, null, new String[]{
"123", "456"
}, long[].class);
assertNotNull(longs);
assertTrue(Arrays.equals(new long[]{123, 456}, longs));
int[] ints = (int[]) converter.convertValue(context, null, null, null, new String[]{
"123", "456"
}, int[].class);
assertNotNull(ints);
assertTrue(Arrays.equals(new int[]{123, 456}, ints));
double[] doubles = (double[]) converter.convertValue(context, null, null, null, new String[]{
"123", "456"
}, double[].class);
assertNotNull(doubles);
assertTrue(Arrays.equals(new double[]{123, 456}, doubles));
float[] floats = (float[]) converter.convertValue(context, null, null, null, new String[]{
"123", "456"
}, float[].class);
assertNotNull(floats);
assertTrue(Arrays.equals(new float[]{123, 456}, floats));
boolean[] booleans = (boolean[]) converter.convertValue(context, null, null, null, new String[]{
"true", "false"
}, boolean[].class);
assertNotNull(booleans);
assertTrue(Arrays.equals(new boolean[]{true, false}, booleans));
}
public void testStringArrayToSet() {
Set<String> list = new HashSet<>();
list.add("foo");
list.add("bar");
list.add("baz");
assertEquals(list, converter.convertValue(context, null, null, null, new String[]{
"foo", "bar", "bar", "baz"
}, Set.class));
}
public void testStringToCollectionConversion() {
Map<String, Object> stackContext = stack.getContext();
stackContext.put(ReflectionContextState.CREATE_NULL_OBJECTS, Boolean.TRUE);
stackContext.put(ReflectionContextState.DENY_METHOD_EXECUTION, Boolean.TRUE);
stackContext.put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE);
User user = new User();
stack.push(user);
stack.setValue("list", "asdf");
assertNotNull(user.getList());
assertEquals(1, user.getList().size());
assertEquals(String.class, user.getList().get(0).getClass());
assertEquals("asdf", user.getList().get(0));
}
public void testStringToCustomTypeUsingCustomConverter() {
// the converter needs to be registered as the Bar.class converter
// it won't be detected from the Foo-conversion.properties
// because the Foo-conversion.properties file is only used when converting a property of Foo
converter.registerConverter(Bar.class.getName(), new FooBarConverter());
Bar bar = (Bar) converter.convertValue(null, null, null, null, "blah:123", Bar.class);
assertNotNull("conversion failed", bar);
assertEquals(123, bar.getSomethingElse());
assertEquals("blah", bar.getTitle());
}
public void testStringToCustomTypeUsingCustomConverterFromProperties() throws Exception {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(new ClassLoader(cl) {
@Override
public Enumeration<URL> getResources(String name) throws IOException {
if ("xwork-conversion.properties".equals(name)) {
return new Enumeration<URL>() {
boolean done = false;
public boolean hasMoreElements() {
return !done;
}
public URL nextElement() {
if (done) {
throw new RuntimeException("Conversion configuration loading " +
"failed because it asked the enumeration for the next URL " +
"too many times");
}
done = true;
return getClass().getResource("/com/opensymphony/xwork2/conversion/impl/test-xwork-conversion.properties");
}
};
} else {
return super.getResources(name);
}
}
});
setUp();
} finally {
Thread.currentThread().setContextClassLoader(cl);
}
Bar bar = (Bar) converter.convertValue(null, null, null, null, "blah:123", Bar.class);
assertNotNull("conversion failed", bar);
assertEquals(123, bar.getSomethingElse());
assertEquals("blah", bar.getTitle());
}
public void testStringToPrimitiveWrappers() {
assertEquals(new Long(123), converter.convertValue(context, null, null, null, "123", Long.class));
assertEquals(new Integer(123), converter.convertValue(context, null, null, null, "123", Integer.class));
assertEquals(new Double(123.5), converter.convertValue(context, null, null, null, "123.5", Double.class));
assertEquals(new Float(123.5), converter.convertValue(context, null, null, null, "123.5", float.class));
assertEquals(false, converter.convertValue(context, null, null, null, "false", Boolean.class));
assertEquals(true, converter.convertValue(context, null, null, null, "true", Boolean.class));
}
public void testStringToPrimitives() {
assertEquals(new Long(123), converter.convertValue(context, null, null, null, "123", long.class));
assertEquals(new Double(123.5), converter.convertValue(context, null, null, null, "123.5", double.class));
assertEquals(new Float(123.5), converter.convertValue(context, null, null, null, "123.5", float.class));
assertEquals(false, converter.convertValue(context, null, null, null, "false", boolean.class));
assertEquals(true, converter.convertValue(context, null, null, null, "true", boolean.class));
assertEquals(new BigDecimal(123.5), converter.convertValue(context, null, null, null, "123.5", BigDecimal.class));
assertEquals(new BigInteger("123"), converter.convertValue(context, null, null, null, "123", BigInteger.class));
}
public void testOverflows() {
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, Double.MAX_VALUE + "1", double.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, Double.MIN_VALUE + "-1", double.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, Double.MAX_VALUE + "1", Double.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, Double.MIN_VALUE + "-1", Double.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, Float.MAX_VALUE + "1", float.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, Float.MIN_VALUE + "-1", float.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, Float.MAX_VALUE + "1", Float.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, Float.MIN_VALUE + "-1", Float.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, Integer.MAX_VALUE + "1", int.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, Integer.MIN_VALUE + "-1", int.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, Integer.MAX_VALUE + "1", Integer.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, Integer.MIN_VALUE + "-1", Integer.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, Byte.MAX_VALUE + "1", byte.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, Byte.MIN_VALUE + "-1", byte.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, Byte.MAX_VALUE + "1", Byte.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, Byte.MIN_VALUE + "-1", Byte.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, Short.MAX_VALUE + "1", short.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, Short.MIN_VALUE + "-1", short.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, Short.MAX_VALUE + "1", Short.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, Short.MIN_VALUE + "-1", Short.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, Long.MAX_VALUE + "1", long.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, Long.MIN_VALUE + "-1", long.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, Long.MAX_VALUE + "1", Long.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, Long.MIN_VALUE + "-1", Long.class));
}
public void testStringToInt() {
assertEquals(new Integer(123), converter.convertValue(context, null, null, null, "123", int.class));
context.put(ActionContext.LOCALE, Locale.US);
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "123.12", int.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "123aa", int.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "aa123", int.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "1,234", int.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "1,23", int.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "1,234.12", int.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "1.234", int.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "1.234,12", int.class));
context.put(ActionContext.LOCALE, Locale.GERMANY);
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "123.12", int.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "123aa", int.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "aa123", int.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "1,234", int.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "1,23", int.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "1,234.12", int.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "1.234", int.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "1.234,12", int.class));
}
public void testStringToInteger() {
assertEquals(new Integer(123), converter.convertValue(context, null, null, null, "123", Integer.class));
context.put(ActionContext.LOCALE, Locale.US);
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "123.12", Integer.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "123aa", Integer.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "aa123", Integer.class));
assertEquals(new Integer(1234), converter.convertValue(context, null, null, null, "1,234", Integer.class));
// WRONG: locale separator is wrongly placed
assertEquals(new Integer(123), converter.convertValue(context, null, null, null, "1,23", Integer.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "1,234.12", Integer.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "1.234", Integer.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "1.234,12", Integer.class));
context.put(ActionContext.LOCALE, Locale.GERMANY);
// WRONG: locale separator is wrongly placed
assertEquals(new Integer(12312), converter.convertValue(context, null, null, null, "123.12", Integer.class));
assertEquals(new Integer(1234), converter.convertValue(context, null, null, null, "1.234", Integer.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "123aa", Integer.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "aa123", Integer.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "1,234", Integer.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "1,234.12", Integer.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "1,23", Integer.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "1.234,12", Integer.class));
}
public void testStringToPrimitiveDouble() {
assertEquals(new Double(123), converter.convertValue(context, null, null, null, "123", double.class));
context.put(ActionContext.LOCALE, Locale.US);
assertEquals(new Double(123.12), converter.convertValue(context, null, null, null, "123.12", double.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "123aa", double.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "aa123", double.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "1,234", double.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "1,234.12", double.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "1,23", double.class));
assertEquals(new Double(1.234), converter.convertValue(context, null, null, null, "1.234", double.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "1.234,12", double.class));
context.put(ActionContext.LOCALE, Locale.GERMANY);
assertEquals(new Double(123.12), converter.convertValue(context, null, null, null, "123.12", double.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "123aa", double.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "aa123", double.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "1,234", double.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "1,234.12", double.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "1,23", double.class));
assertEquals(new Double(1.234), converter.convertValue(context, null, null, null, "1.234", double.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "1.234,12", double.class));
}
public void testStringToDouble() {
assertEquals(new Double(123), converter.convertValue(context, null, null, null, "123", Double.class));
context.put(ActionContext.LOCALE, Locale.US);
assertEquals(new Double(123.12), converter.convertValue(context, null, null, null, "123.12", Double.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "123aa", Double.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "aa123", Double.class));
assertEquals(new Double(1234), converter.convertValue(context, null, null, null, "1,234", Double.class));
assertEquals(new Double(1234.12), converter.convertValue(context, null, null, null, "1,234.12", Double.class));
// WRONG: locale separator is wrongly placed
assertEquals(new Double(123), converter.convertValue(context, null, null, null, "1,23", Double.class));
assertEquals(new Double(1.234), converter.convertValue(context, null, null, null, "1.234", Double.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "1.234,12", Double.class));
context.put(ActionContext.LOCALE, Locale.GERMANY);
// WRONG: locale separator is wrongly placed
assertEquals(new Double(12312), converter.convertValue(context, null, null, null, "123.12", Double.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "123aa", Double.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "aa123", Double.class));
assertEquals(new Double(1.234), converter.convertValue(context, null, null, null, "1,234", Double.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "1,234.12", Double.class));
assertEquals(new Double(1.23), converter.convertValue(context, null, null, null, "1,23", Double.class));
assertEquals(new Double(1234), converter.convertValue(context, null, null, null, "1.234", Double.class));
assertEquals(new Double(1234.12), converter.convertValue(context, null, null, null, "1.234,12", Double.class));
}
public void testStringToEnum() {
assertEquals(FurColor.BLACK, converter.convertValue(context, null, null, null, "BLACK", FurColor.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "black", FurColor.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, null, null, null, "red", FurColor.class));
}
// Testing for null result on non-primitive Number types supplied as empty String or
public void testNotPrimitiveDefaultsToNull() {
assertEquals(null, converter.convertValue(context, null, null, null, null, Double.class));
assertEquals(null, converter.convertValue(context, null, null, null, "", Double.class));
assertEquals(null, converter.convertValue(context, null, null, null, null, Integer.class));
assertEquals(null, converter.convertValue(context, null, null, null, "", Integer.class));
assertEquals(null, converter.convertValue(context, null, null, null, null, Float.class));
assertEquals(null, converter.convertValue(context, null, null, null, "", Float.class));
assertEquals(null, converter.convertValue(context, null, null, null, null, Character.class));
assertEquals(null, converter.convertValue(context, null, null, null, "", Character.class));
assertEquals(null, converter.convertValue(context, null, null, null, null, Long.class));
assertEquals(null, converter.convertValue(context, null, null, null, "", Long.class));
assertEquals(null, converter.convertValue(context, null, null, null, null, Short.class));
assertEquals(null, converter.convertValue(context, null, null, null, "", Short.class));
}
public void testConvertChar() {
assertEquals(new Character('A'), converter.convertValue(context, "A", char.class));
assertEquals(new Character('Z'), converter.convertValue(context, "Z", char.class));
assertEquals(new Character('A'), converter.convertValue(context, "A", Character.class));
assertEquals(new Character('Z'), converter.convertValue(context, "Z", Character.class));
assertEquals(new Character('A'), converter.convertValue(context, new Character('A'), char.class));
assertEquals(new Character('Z'), converter.convertValue(context, new Character('Z'), char.class));
assertEquals(new Character('A'), converter.convertValue(context, new Character('A'), Character.class));
assertEquals(new Character('Z'), converter.convertValue(context, new Character('Z'), Character.class));
assertEquals(new Character('D'), converter.convertValue(context, "DEF", char.class));
assertEquals(new Character('X'), converter.convertValue(context, "XYZ", Character.class));
assertEquals(new Character(' '), converter.convertValue(context, " ", Character.class));
assertEquals(new Character(' '), converter.convertValue(context, " ", char.class));
assertEquals(null, converter.convertValue(context, "", char.class));
}
public void testConvertClass() {
Class clazz = (Class) converter.convertValue(context, "java.util.Date", Class.class);
assertEquals(Date.class.getName(), clazz.getName());
Class clazz2 = (Class) converter.convertValue(context, "com.opensymphony.xwork2.util.Bar", Class.class);
assertEquals(Bar.class.getName(), clazz2.getName());
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, "com.opensymphony.xwork2.util.IDoNotExist", Class.class));
assertEquals(OgnlRuntime.NoConversionPossible, converter.convertValue(context, new Bar(), Class.class)); // only supports string values
}
public void testConvertBoolean() {
assertEquals(Boolean.TRUE, converter.convertValue(context, "true", Boolean.class));
assertEquals(Boolean.FALSE, converter.convertValue(context, "false", Boolean.class));
assertEquals(Boolean.TRUE, converter.convertValue(context, Boolean.TRUE, Boolean.class));
assertEquals(Boolean.FALSE, converter.convertValue(context, Boolean.FALSE, Boolean.class));
assertEquals(null, converter.convertValue(context, null, Boolean.class));
assertEquals(Boolean.TRUE, converter.convertValue(context, new Bar(), Boolean.class)); // Ognl converter will default to true
}
public void testConvertPrimitiveArraysToString() {
assertEquals("2, 3, 1", converter.convertValue(context, new int[]{2, 3, 1}, String.class));
assertEquals("100, 200, 300", converter.convertValue(context, new long[]{100, 200, 300}, String.class));
assertEquals("1.5, 2.5, 3.5", converter.convertValue(context, new double[]{1.5, 2.5, 3.5}, String.class));
assertEquals("true, false, true", converter.convertValue(context, new boolean[]{true, false, true}, String.class));
}
public void testConvertSameCollectionToCollection() {
Collection<String> names = new ArrayList<>();
names.add("XWork");
names.add("Struts");
Collection col = (Collection) converter.convertValue(context, names, Collection.class);
assertSame(names, col);
}
public void testConvertSqlTimestamp() {
assertNotNull(converter.convertValue(context, new Timestamp(new Date().getTime()), String.class));
assertNotNull(converter.convertValue(null, new Timestamp(new Date().getTime()), String.class));
}
public void testValueStackWithTypeParameter() {
stack.push(new Foo1());
Bar1 bar = (Bar1) stack.findValue("bar", Bar1.class);
assertNotNull(bar);
}
public void testNestedConverters() {
Cat cat = new Cat();
cat.setFoo(new Foo());
stack.push(cat);
stack.setValue("foo.number", "123");
assertEquals(321, cat.getFoo().getNumber());
}
public void testCollectionConversion() throws Exception {
// given
String[] col1 = new String[]{"1", "2", "ble", "3"};
// when
Object converted = converter.convertValue(context, new ListAction(), null, "ints", col1, List.class);
// then
assertEquals(converted, Arrays.asList(1, 2, 3));
}
public static class Foo1 {
public Bar1 getBar() {
return new Bar1Impl();
}
}
public interface Bar1 {
}
public static class Bar1Impl implements Bar1 {
}
@Override
protected void setUp() throws Exception {
super.setUp();
converter = container.getInstance(XWorkConverter.class);
ActionContext ac = ActionContext.getContext();
ac.setLocale(Locale.US);
context = ac.getContextMap();
stack = (OgnlValueStack) ac.getValueStack();
}
}
class ListAction {
private List<Integer> ints = new ArrayList<>();
public List<Integer> getInts() {
return ints;
}
public void setInts(List<Integer> ints) {
this.ints = ints;
}
}
@@ -0,0 +1,23 @@
package com.opensymphony.xwork2.interceptor.annotations;
import com.opensymphony.xwork2.ActionSupport;
/**
* @author martin.gilday
*
*/
public class AllowingByDefaultAction extends ActionSupport {
@Blocked
private String name;
private String job;
public void setName(String name) {
this.name = name;
}
public void setJob(String job) {
this.job = job;
}
}
@@ -0,0 +1,22 @@
package com.opensymphony.xwork2.interceptor.annotations;
/**
* @author jafl
*
*/
public class AllowingByDefaultModel {
@Blocked
private String m1;
private String m2;
public void setM1(String s) {
m1 = s;
}
public void setM2(String s) {
m2 = s;
}
}
@@ -0,0 +1,46 @@
/*
* 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 com.opensymphony.xwork2.interceptor.annotations;
import com.opensymphony.xwork2.Action;
/**
* @author Zsolt Szasz, zsolt at lorecraft dot com
* @author Rainer Hermanns
*/
public class AnnotatedAction extends BaseAnnotatedAction {
@Before(priority=5)
public String before() {
log = log + "before";
return null;
}
public String execute() {
log = log + "-execute";
return Action.SUCCESS;
}
@BeforeResult
public void beforeResult() throws Exception {
log = log +"-beforeResult";
}
@After(priority=5)
public void after() {
log = log + "-after";
}
}
@@ -0,0 +1,173 @@
package com.opensymphony.xwork2.interceptor.annotations;
import com.mockobjects.dynamic.Mock;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.StubValueStack;
import com.opensymphony.xwork2.util.ValueStack;
import junit.framework.TestCase;
import java.util.HashMap;
import java.util.Map;
/**
* @author martin.gilday
* @author jafl
*
*/
public class AnnotationParameterFilterUnitTest extends TestCase {
ValueStack stack;
@Override
protected void setUp() throws Exception {
super.setUp();
stack = new StubValueStack();
}
/**
* Only "name" should remain in the parameter map. All others
* should be removed
* @throws Exception
*/
public void testBlockingByDefault() throws Exception {
Map<String, Object> contextMap = new HashMap<>();
Map<String, Object> parameterMap = new HashMap<>();
parameterMap.put("job", "Baker");
parameterMap.put("name", "Martin");
contextMap.put(ActionContext.PARAMETERS, parameterMap);
Action action = new BlockingByDefaultAction();
stack.push(action);
Mock mockInvocation = new Mock(ActionInvocation.class);
mockInvocation.expectAndReturn("getInvocationContext", new ActionContext(contextMap));
mockInvocation.matchAndReturn("getAction", action);
mockInvocation.matchAndReturn("getStack", stack);
mockInvocation.expectAndReturn("invoke", Action.SUCCESS);
ActionInvocation invocation = (ActionInvocation) mockInvocation.proxy();
AnnotationParameterFilterIntereptor intereptor = new AnnotationParameterFilterIntereptor();
intereptor.intercept(invocation);
assertEquals("Parameter map should contain one entry", 1, parameterMap.size());
assertNull(parameterMap.get("job"));
assertNotNull(parameterMap.get("name"));
}
/**
* "name" should be removed from the map, as it is blocked.
* All other parameters should remain
* @throws Exception
*/
public void testAllowingByDefault() throws Exception {
Map<String, Object> contextMap = new HashMap<>();
Map<String, Object> parameterMap = new HashMap<>();
parameterMap.put("job", "Baker");
parameterMap.put("name", "Martin");
contextMap.put(ActionContext.PARAMETERS, parameterMap);
Action action = new AllowingByDefaultAction();
stack.push(action);
Mock mockInvocation = new Mock(ActionInvocation.class);
mockInvocation.expectAndReturn("getInvocationContext", new ActionContext(contextMap));
mockInvocation.matchAndReturn("getAction", action);
mockInvocation.matchAndReturn("getStack", stack);
mockInvocation.expectAndReturn("invoke", Action.SUCCESS);
ActionInvocation invocation = (ActionInvocation) mockInvocation.proxy();
AnnotationParameterFilterIntereptor intereptor = new AnnotationParameterFilterIntereptor();
intereptor.intercept(invocation);
assertEquals("Paramter map should contain one entry", 1, parameterMap.size());
assertNotNull(parameterMap.get("job"));
assertNull(parameterMap.get("name"));
}
/**
* Only "name" should remain in the parameter map. All others
* should be removed
* @throws Exception
*/
public void testBlockingByDefaultWithModel() throws Exception {
Map<String, Object> contextMap = new HashMap<>();
Map<String, Object> parameterMap = new HashMap<>();
parameterMap.put("job", "Baker");
parameterMap.put("name", "Martin");
parameterMap.put("m1", "s1");
parameterMap.put("m2", "s2");
contextMap.put(ActionContext.PARAMETERS, parameterMap);
stack.push(new BlockingByDefaultModel());
Mock mockInvocation = new Mock(ActionInvocation.class);
mockInvocation.expectAndReturn("getInvocationContext", new ActionContext(contextMap));
mockInvocation.matchAndReturn("getAction", new BlockingByDefaultAction());
mockInvocation.matchAndReturn("getStack", stack);
mockInvocation.expectAndReturn("invoke", Action.SUCCESS);
ActionInvocation invocation = (ActionInvocation) mockInvocation.proxy();
AnnotationParameterFilterIntereptor intereptor = new AnnotationParameterFilterIntereptor();
intereptor.intercept(invocation);
assertEquals("Paramter map should contain two entries", 2, parameterMap.size());
assertNull(parameterMap.get("job"));
assertNotNull(parameterMap.get("name"));
assertNotNull(parameterMap.get("m1"));
assertNull(parameterMap.get("m2"));
}
/**
* "name" should be removed from the map, as it is blocked.
* All other parameters should remain
* @throws Exception
*/
public void testAllowingByDefaultWithModel() throws Exception {
Map<String, Object> contextMap = new HashMap<>();
Map<String, Object> parameterMap = new HashMap<>();
parameterMap.put("job", "Baker");
parameterMap.put("name", "Martin");
parameterMap.put("m1", "s1");
parameterMap.put("m2", "s2");
contextMap.put(ActionContext.PARAMETERS, parameterMap);
stack.push(new AllowingByDefaultModel());
Mock mockInvocation = new Mock(ActionInvocation.class);
mockInvocation.expectAndReturn("getInvocationContext", new ActionContext(contextMap));
mockInvocation.matchAndReturn("getAction", new AllowingByDefaultAction());
mockInvocation.matchAndReturn("getStack", stack);
mockInvocation.expectAndReturn("invoke", Action.SUCCESS);
ActionInvocation invocation = (ActionInvocation) mockInvocation.proxy();
AnnotationParameterFilterIntereptor intereptor = new AnnotationParameterFilterIntereptor();
intereptor.intercept(invocation);
assertEquals("Paramter map should contain two entries", 2, parameterMap.size());
assertNotNull(parameterMap.get("job"));
assertNull(parameterMap.get("name"));
assertNull(parameterMap.get("m1"));
assertNotNull(parameterMap.get("m2"));
}
}
@@ -0,0 +1,102 @@
/*
* 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 com.opensymphony.xwork2.interceptor.annotations;
import com.opensymphony.xwork2.*;
import com.opensymphony.xwork2.config.Configuration;
import com.opensymphony.xwork2.config.ConfigurationException;
import com.opensymphony.xwork2.config.ConfigurationProvider;
import com.opensymphony.xwork2.config.entities.ActionConfig;
import com.opensymphony.xwork2.config.entities.InterceptorMapping;
import com.opensymphony.xwork2.config.entities.PackageConfig;
import com.opensymphony.xwork2.config.entities.ResultConfig;
import com.opensymphony.xwork2.config.providers.XmlConfigurationProvider;
import com.opensymphony.xwork2.inject.ContainerBuilder;
import com.opensymphony.xwork2.mock.MockResult;
import com.opensymphony.xwork2.util.location.LocatableProperties;
import java.util.Collections;
/**
* @author Zsolt Szasz, zsolt at lorecraft dot com
* @author Rainer Hermanns
*/
public class AnnotationWorkflowInterceptorTest extends XWorkTestCase {
private static final String ANNOTATED_ACTION = "annotatedAction";
private static final String SHORTCIRCUITED_ACTION = "shortCircuitedAction";
private final AnnotationWorkflowInterceptor annotationWorkflow = new AnnotationWorkflowInterceptor();
@Override
public void setUp() throws Exception{
super.setUp();
XmlConfigurationProvider provider = new XmlConfigurationProvider("xwork-default.xml");
container.inject(provider);
loadConfigurationProviders(provider, new MockConfigurationProvider());
}
public void testInterceptsBeforeAndAfter() throws Exception {
ActionProxy proxy = actionProxyFactory.createActionProxy("", ANNOTATED_ACTION, null);
assertEquals(Action.SUCCESS, proxy.execute());
AnnotatedAction action = (AnnotatedAction)proxy.getInvocation().getAction();
assertEquals("baseBefore-before-execute-beforeResult-after", action.log);
}
public void testInterceptsShortcircuitedAction() throws Exception {
ActionProxy proxy = actionProxyFactory.createActionProxy("", SHORTCIRCUITED_ACTION, null);
assertEquals("shortcircuit", proxy.execute());
ShortcircuitedAction action = (ShortcircuitedAction)proxy.getInvocation().getAction();
assertEquals("baseBefore-before", action.log);
}
private class MockConfigurationProvider implements ConfigurationProvider {
private Configuration config;
public void init(Configuration configuration) throws ConfigurationException {
this.config = configuration;
}
public boolean needsReload() {
return false;
}
public void destroy() { }
public void register(ContainerBuilder builder, LocatableProperties props) throws ConfigurationException {
if (!builder.contains(ObjectFactory.class)) {
builder.factory(ObjectFactory.class);
}
if (!builder.contains(ActionProxyFactory.class)) {
builder.factory(ActionProxyFactory.class, DefaultActionProxyFactory.class);
}
}
public void loadPackages() throws ConfigurationException {
PackageConfig packageConfig = new PackageConfig.Builder("default")
.addActionConfig(ANNOTATED_ACTION, new ActionConfig.Builder("defaultPackage", ANNOTATED_ACTION, AnnotatedAction.class.getName())
.addInterceptors(Collections.singletonList(new InterceptorMapping("annotationWorkflow", annotationWorkflow)))
.addResultConfig(new ResultConfig.Builder("success", MockResult.class.getName()).build())
.build())
.addActionConfig(SHORTCIRCUITED_ACTION, new ActionConfig.Builder("defaultPackage", SHORTCIRCUITED_ACTION, ShortcircuitedAction.class.getName())
.addInterceptors(Collections.singletonList(new InterceptorMapping("annotationWorkflow", annotationWorkflow)))
.addResultConfig(new ResultConfig.Builder("shortcircuit", MockResult.class.getName()).build())
.build())
.build();
config.addPackageConfig("defaultPackage", packageConfig);
config.addPackageConfig("default", new PackageConfig.Builder(packageConfig).name("default").build());
}
}
}
@@ -0,0 +1,32 @@
/*
* 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 com.opensymphony.xwork2.interceptor.annotations;
/**
* @author Zsolt Szasz, zsolt at lorecraft dot com
* @author Rainer Hermanns
*/
public class BaseAnnotatedAction {
protected String log = "";
@Before
public String baseBefore() {
log = log + "baseBefore-";
return null;
}
}
@@ -0,0 +1,24 @@
package com.opensymphony.xwork2.interceptor.annotations;
import com.opensymphony.xwork2.ActionSupport;
/**
* @author martin.gilday
*
*/
@BlockByDefault
public class BlockingByDefaultAction extends ActionSupport {
@Allowed
private String name;
private String job;
public void setName(String name) {
this.name = name;
}
public void setJob(String job) {
this.job = job;
}
}
@@ -0,0 +1,22 @@
package com.opensymphony.xwork2.interceptor.annotations;
/**
* @author jafl
*
*/
@BlockByDefault
public class BlockingByDefaultModel {
@Allowed
private String m1;
private String m2;
public void setM1(String s) {
m1 = s;
}
public void setM2(String s) {
m2 = s;
}
}
@@ -0,0 +1,35 @@
/*
* 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 com.opensymphony.xwork2.interceptor.annotations;
import com.opensymphony.xwork2.Action;
/**
* @author Zsolt Szasz, zsolt at lorecraft dot com
* @author Rainer Hermanns
*/
public class ShortcircuitedAction extends BaseAnnotatedAction {
@Before(priority=5)
public String before() {
log = log + "before";
return "shortcircuit";
}
public String execute() {
log = log + "-execute-";
return Action.SUCCESS;
}
}
@@ -0,0 +1,53 @@
/*
* Copyright (c) 2005 Opensymphony. All Rights Reserved.
*/
package com.opensymphony.xwork2.ognl.accessor;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.XWorkTestCase;
import com.opensymphony.xwork2.util.ListHolder;
import com.opensymphony.xwork2.util.ValueStack;
import java.util.ArrayList;
import java.util.List;
/**
* XWorkListPropertyAccessorTest
* <p/>
* Created : Nov 7, 2005 3:54:44 PM
*
* @author Jason Carreira <jcarreira@eplus.com>
*/
public class XWorkListPropertyAccessorTest extends XWorkTestCase {
public void testContains() {
ValueStack vs = ActionContext.getContext().getValueStack();
ListHolder listHolder = new ListHolder();
vs.push(listHolder);
vs.setValue("longs", new String[] {"1", "2", "3"});
assertNotNull(listHolder.getLongs());
assertEquals(3, listHolder.getLongs().size());
assertEquals(new Long(1), (Long) listHolder.getLongs().get(0));
assertEquals(new Long(2), (Long) listHolder.getLongs().get(1));
assertEquals(new Long(3), (Long) listHolder.getLongs().get(2));
assertTrue(((Boolean) vs.findValue("longs.contains(1)")).booleanValue());
}
public void testCanAccessListSizeProperty() {
ValueStack vs = ActionContext.getContext().getValueStack();
List myList = new ArrayList();
myList.add("a");
myList.add("b");
ListHolder listHolder = new ListHolder();
listHolder.setStrings(myList);
vs.push(listHolder);
assertEquals(new Integer(myList.size()), vs.findValue("strings.size()"));
assertEquals(new Integer(myList.size()), vs.findValue("strings.size"));
}
}
@@ -0,0 +1,112 @@
/*
* Created on 6/11/2004
*/
package com.opensymphony.xwork2.spring.interceptor;
import com.opensymphony.xwork2.*;
import com.opensymphony.xwork2.config.providers.XmlConfigurationProvider;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.StaticWebApplicationContext;
import java.util.HashMap;
import java.util.Map;
/**
* @author Simon Stewart
*/
public class ActionAutowiringInterceptorTest extends XWorkTestCase {
public void testShouldAutowireAction() throws Exception {
StaticWebApplicationContext context = new StaticWebApplicationContext();
context.getBeanFactory().registerSingleton("bean", new TestBean());
TestBean bean = (TestBean) context.getBean("bean");
loadSpringApplicationContextIntoApplication(context);
SimpleAction action = new SimpleAction();
ActionInvocation invocation = new TestActionInvocation(action);
ActionAutowiringInterceptor interceptor = new ActionAutowiringInterceptor();
interceptor.setApplicationContext(context);
interceptor.init();
interceptor.intercept(invocation);
assertEquals(bean, action.getBean());
}
public void testSetAutowireType() throws Exception {
XmlConfigurationProvider prov = new XmlConfigurationProvider("xwork-default.xml");
container.inject(prov);
prov.setThrowExceptionOnDuplicateBeans(false);
XmlConfigurationProvider c = new XmlConfigurationProvider("com/opensymphony/xwork2/spring/xwork-autowire.xml");
container.inject(c);
loadConfigurationProviders(c, prov);
StaticWebApplicationContext appContext = new StaticWebApplicationContext();
loadSpringApplicationContextIntoApplication(appContext);
ActionAutowiringInterceptor interceptor = new ActionAutowiringInterceptor();
interceptor.init();
SimpleAction action = new SimpleAction();
ActionInvocation invocation = new TestActionInvocation(action);
interceptor.intercept(invocation);
ApplicationContext loadedContext = interceptor.getApplicationContext();
assertEquals(appContext, loadedContext);
}
protected void loadSpringApplicationContextIntoApplication(ApplicationContext appContext) {
Map<Object, Object> application = new HashMap<>();
application.put(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appContext);
Map<String, Object> context = new HashMap<>();
context.put(ActionContext.APPLICATION, application);
ActionContext actionContext = new ActionContext(context);
ActionContext.setContext(actionContext);
}
public void testLoadsApplicationContextUsingWebApplicationContextUtils() throws Exception {
StaticWebApplicationContext appContext = new StaticWebApplicationContext();
loadSpringApplicationContextIntoApplication(appContext);
ActionAutowiringInterceptor interceptor = new ActionAutowiringInterceptor();
interceptor.init();
SimpleAction action = new SimpleAction();
ActionInvocation invocation = new TestActionInvocation(action);
interceptor.intercept(invocation);
ApplicationContext loadedContext = interceptor.getApplicationContext();
assertEquals(appContext, loadedContext);
}
public void testIfApplicationContextIsNullThenBeanWillNotBeWiredUp() throws Exception {
Map<String, Object> context = new HashMap<>();
context.put(ActionContext.APPLICATION, new HashMap());
ActionContext actionContext = new ActionContext(context);
ActionContext.setContext(actionContext);
ActionAutowiringInterceptor interceptor = new ActionAutowiringInterceptor();
interceptor.init();
SimpleAction action = new SimpleAction();
ActionInvocation invocation = new TestActionInvocation(action);
TestBean bean = action.getBean();
// If an exception is thrown here, things are going to go wrong in
// production
interceptor.intercept(invocation);
assertEquals(bean, action.getBean());
}
}
@@ -0,0 +1,82 @@
/*
* Created on 6/11/2004
*/
package com.opensymphony.xwork2.spring.interceptor;
import com.opensymphony.xwork2.*;
import com.opensymphony.xwork2.interceptor.PreResultListener;
import com.opensymphony.xwork2.util.ValueStack;
import java.lang.reflect.Method;
/**
* @author Simon Stewart
*/
public class TestActionInvocation implements ActionInvocation {
private Object action;
private boolean executed;
public TestActionInvocation(Object wrappedAction) {
this.action = wrappedAction;
}
public Object getAction() {
return action;
}
public boolean isExecuted() {
return executed;
}
public ActionContext getInvocationContext() {
return null;
}
public ActionProxy getProxy() {
return null;
}
public Result getResult() throws Exception {
return null;
}
public String getResultCode() {
return null;
}
public void setResultCode(String resultCode) {
}
public ValueStack getStack() {
return null;
}
public void addPreResultListener(PreResultListener listener) {
}
public String invoke() throws Exception {
return invokeActionOnly();
}
public String invokeActionOnly() throws Exception {
executed = true;
Method method = action.getClass().getMethod("execute", new Class[0]);
return (String) method.invoke(action, new Object[0]);
}
public void setActionEventListener(ActionEventListener listener) {
}
public void init(ActionProxy proxy) {
}
public ActionInvocation serialize() {
return this;
}
public ActionInvocation deserialize(ActionContext actionContext) {
return this;
}
}
@@ -0,0 +1,40 @@
package com.opensymphony.xwork2.test.annotations;
public class Address {
private String line1;
private String line2;
private String city;
private String country;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getLine1() {
return line1;
}
public void setLine1(String line1) {
this.line1 = line1;
}
public String getLine2() {
return line2;
}
public void setLine2(String line2) {
this.line2 = line2;
}
}
@@ -0,0 +1,29 @@
package com.opensymphony.xwork2.test.annotations;
import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;
import java.util.Map;
public class AddressTypeConverter extends DefaultTypeConverter {
@Override public Object convertValue(Map<String, Object> context, Object value, Class toType) {
if(value instanceof String) {
return decodeAddress((String)value);
} else if(value instanceof String && value.getClass().isArray()) {
return decodeAddress(((String[])value)[0]);
} else {
Address address = (Address)value;
return address.getLine1() + ":" + address.getLine2() + ":" +
address.getCity() + ":" + address.getCountry();
}
}
private Address decodeAddress(String encodedAddress) {
String[] parts = ((String)encodedAddress).split(":");
Address address = new Address();
address.setLine1(parts[0]);
address.setLine2(parts[1]);
address.setCity(parts[2]);
address.setCountry(parts[3]);
return address;
}
}
@@ -0,0 +1,22 @@
package com.opensymphony.xwork2.test.annotations;
public class Person {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
@@ -0,0 +1,47 @@
package com.opensymphony.xwork2.test.annotations;
import com.opensymphony.xwork2.conversion.annotations.Conversion;
import com.opensymphony.xwork2.conversion.annotations.ConversionType;
import com.opensymphony.xwork2.conversion.annotations.TypeConversion;
import com.opensymphony.xwork2.util.Element;
import java.util.List;
@Conversion(
conversions={
@TypeConversion(type=ConversionType.APPLICATION,
key="com.opensymphony.xwork2.test.annotations.Address",
converter="com.opensymphony.xwork2.test.annotations.AddressTypeConverter"),
@TypeConversion(type=ConversionType.APPLICATION,
key="com.opensymphony.xwork2.test.annotations.Person",
converter="com.opensymphony.xwork2.test.annotations.PersonTypeConverter")})
public class PersonAction {
List<Person> users;
private List<Address> address;
@Element(com.opensymphony.xwork2.test.annotations.Address.class)
private List addressesNoGenericElementAnnotation;
public List<Person> getUsers() {
return users;
}
public void setUsers(List<Person> users) {
this.users = users;
}
public void setAddress(List<Address> address) {
this.address = address;
}
public List<Address> getAddress() {
return address;
}
public void setAddressesNoGenericElementAnnotation(List addressesNoGenericElementAnnotation) {
this.addressesNoGenericElementAnnotation = addressesNoGenericElementAnnotation;
}
public List getAddressesNoGenericElementAnnotation() {
return addressesNoGenericElementAnnotation;
}
}
@@ -0,0 +1,87 @@
package com.opensymphony.xwork2.test.annotations;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.XWorkTestCase;
import com.opensymphony.xwork2.conversion.impl.XWorkConverter;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.reflection.ReflectionContextState;
import java.util.Map;
public class PersonActionTest extends XWorkTestCase {
public void testAddPerson() {
ValueStack stack = ActionContext.getContext().getValueStack();
Map<String, Object> stackContext = stack.getContext();
stackContext.put(ReflectionContextState.CREATE_NULL_OBJECTS, Boolean.TRUE);
stackContext.put(ReflectionContextState.DENY_METHOD_EXECUTION, Boolean.TRUE);
stackContext.put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE);
PersonAction action = new PersonAction();
stack.push(action);
stack.setValue("users", "jonathan:gerrish");
assertNotNull(action.getUsers());
assertEquals(1, action.getUsers().size());
for(Object person : action.getUsers()) {
System.out.println("Person: " + person);
}
assertEquals(Person.class, action.getUsers().get(0).getClass());
assertEquals("jonathan", action.getUsers().get(0).getFirstName());
assertEquals("gerrish", action.getUsers().get(0).getLastName());
}
public void testAddAddress() {
ValueStack stack = ActionContext.getContext().getValueStack();
Map<String, Object> stackContext = stack.getContext();
stackContext.put(ReflectionContextState.CREATE_NULL_OBJECTS, Boolean.TRUE);
stackContext.put(ReflectionContextState.DENY_METHOD_EXECUTION, Boolean.TRUE);
stackContext.put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE);
PersonAction action = new PersonAction();
stack.push(action);
stack.setValue("address", "2 Chandos Court:61 Haverstock Hill:London:England");
assertNotNull(action.getAddress());
assertEquals(1, action.getAddress().size());
for(Object address : action.getAddress()) {
System.out.println("Address: " + address);
}
assertEquals(Address.class, action.getAddress().get(0).getClass());
assertEquals("2 Chandos Court", action.getAddress().get(0).getLine1());
assertEquals("61 Haverstock Hill", action.getAddress().get(0).getLine2());
assertEquals("London", action.getAddress().get(0).getCity());
assertEquals("England", action.getAddress().get(0).getCountry());
}
public void testAddAddressesNoGenericElementAnnotation() {
ValueStack stack = ActionContext.getContext().getValueStack();
Map<String, Object> stackContext = stack.getContext();
stackContext.put(ReflectionContextState.CREATE_NULL_OBJECTS, Boolean.TRUE);
stackContext.put(ReflectionContextState.DENY_METHOD_EXECUTION, Boolean.TRUE);
stackContext.put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE);
PersonAction action = new PersonAction();
stack.push(action);
stack.setValue("addressesNoGenericElementAnnotation", "2 Chandos Court:61 Haverstock Hill:London:England");
assertNotNull(action.getAddressesNoGenericElementAnnotation());
assertEquals(1, action.getAddressesNoGenericElementAnnotation().size());
for(Object address : action.getAddressesNoGenericElementAnnotation()) {
System.out.println("Address: " + address);
}
assertEquals(Address.class, action.getAddressesNoGenericElementAnnotation().get(0).getClass());
assertEquals("2 Chandos Court", ((Address)action.getAddressesNoGenericElementAnnotation().get(0)).getLine1());
assertEquals("61 Haverstock Hill", ((Address)action.getAddressesNoGenericElementAnnotation().get(0)).getLine2());
assertEquals("London", ((Address)action.getAddressesNoGenericElementAnnotation().get(0)).getCity());
assertEquals("England", ((Address)action.getAddressesNoGenericElementAnnotation().get(0)).getCountry());
}
}
@@ -0,0 +1,27 @@
package com.opensymphony.xwork2.test.annotations;
import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;
import java.util.Map;
public class PersonTypeConverter extends DefaultTypeConverter {
@Override
public Object convertValue(Map<String, Object> context, Object value, Class toType) {
if(value instanceof String) {
return decodePerson((String)value);
} else if(value instanceof String && value.getClass().isArray()) {
return decodePerson(((String[])value)[0]);
} else {
Person person = (Person)value;
return person.getFirstName() + ":" + person.getLastName();
}
}
private Person decodePerson(String encodedPerson) {
String[] parts = ((String)encodedPerson).split(":");
Person person = new Person();
person.setFirstName(parts[0]);
person.setLastName(parts[1]);
return person;
}
}
@@ -0,0 +1,55 @@
package com.opensymphony.xwork2.test.annotations;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.ExpressionValidator;
import com.opensymphony.xwork2.validator.annotations.Validation;
/**
* <code>ValidateAnnotatedMethodOnlyAction</code>
*
* @author <a href="mailto:hermanns@aixcept.de">Rainer Hermanns</a>
* @version $Id$
*/
@Validation
public class ValidateAnnotatedMethodOnlyAction extends ActionSupport {
String param1;
String param2;
public String getParam1() {
return param1;
}
public void setParam1(String param1) {
this.param1 = param1;
}
public String getParam2() {
return param2;
}
public void setParam2(String param2) {
this.param2 = param2;
}
@ExpressionValidator(expression = "(param1 != null) || (param2 != null)",
message = "Need param1 or param2.")
public String annotatedMethod() {
try {
// do search
} catch (Exception e) {
return INPUT;
}
return SUCCESS;
}
public String notAnnotatedMethod() {
try {
// do different search
} catch (Exception e) {
return INPUT;
}
return SUCCESS;
}
}
@@ -0,0 +1,19 @@
package com.opensymphony.xwork2.test.subtest;
import com.opensymphony.xwork2.ModelDrivenAction;
/**
* Extends ModelDrivenAction to return a null model.
*
* @author Mark Woon
*/
public class NullModelDrivenAction extends ModelDrivenAction {
/**
* @return the model to be pushed onto the ValueStack instead of the Action itself
*/
@Override
public Object getModel() {
return null;
}
}
@@ -0,0 +1,9 @@
package com.opensymphony.xwork2.util.annotation;
public class Dummy2Class {
@MyAnnotation("class-test")
public void methodWithAnnotation() {
}
}
@@ -0,0 +1,13 @@
package com.opensymphony.xwork2.util.annotation;
@MyAnnotation("class-test")
public class DummyClass {
public DummyClass() {
}
@MyAnnotation("method-test")
public void methodWithAnnotation() {
}
}
@@ -0,0 +1,9 @@
package com.opensymphony.xwork2.util.annotation;
public final class DummyClassExt extends DummyClass {
@MyAnnotation2
public void anotherAnnotatedMethod() {
}
}
@@ -0,0 +1,11 @@
package com.opensymphony.xwork2.util.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value();
}
@@ -0,0 +1,8 @@
package com.opensymphony.xwork2.util.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation2 {
}
@@ -0,0 +1,22 @@
/*
* $Id: package-info.java 655902 2008-05-13 15:15:12Z bpontarelli $
*
* 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.
*/
@MyAnnotation("package-test")
package com.opensymphony.xwork2.util.annotation;
@@ -0,0 +1,135 @@
package com.opensymphony.xwork2.util.fs;
import com.opensymphony.xwork2.FileManager;
import com.opensymphony.xwork2.XWorkTestCase;
import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.inject.Scope;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class DefaultFileManagerFactoryTest extends XWorkTestCase {
static FileManager fileManager;
public void testCreateDefaultFileManager() throws Exception {
// given
fileManager = null;
DefaultFileManagerFactory factory = new DefaultFileManagerFactory();
factory.setFileManager(new DefaultFileManager());
factory.setContainer(new DummyContainer());
// when
FileManager fm = factory.getFileManager();
// then
assertTrue(fm instanceof DefaultFileManager);
}
public void testCreateDummyFileManager() throws Exception {
// given
fileManager = new DummyFileManager();
DefaultFileManagerFactory factory = new DefaultFileManagerFactory();
factory.setFileManager(new DefaultFileManager());
factory.setContainer(new DummyContainer());
// when
FileManager fm = factory.getFileManager();
// then
assertTrue(fm instanceof DummyFileManager);
}
public void testFileManagerFactoryWithRealConfig() throws Exception {
// given
DefaultFileManagerFactory factory = new DefaultFileManagerFactory();
container.inject(factory);
// when
FileManager fm = factory.getFileManager();
// then
assertTrue(fm instanceof DefaultFileManager);
}
}
class DummyContainer implements Container {
public void inject(Object o) {
}
public <T> T inject(Class<T> implementation) {
return null;
}
public <T> T getInstance(Class<T> type, String name) {
if ("dummy".equals(name)) {
return (T) DefaultFileManagerFactoryTest.fileManager;
}
return null;
}
public <T> T getInstance(Class<T> type) {
return null;
}
public Set<String> getInstanceNames(Class<?> type) {
if (DefaultFileManagerFactoryTest.fileManager != null) {
return new HashSet<String>() {
{
add("dummy");
}
};
}
return Collections.emptySet();
}
public void setScopeStrategy(Scope.Strategy scopeStrategy) {
}
public void removeScopeStrategy() {
}
}
class DummyFileManager implements FileManager {
public void setReloadingConfigs(boolean reloadingConfigs) {
}
public boolean fileNeedsReloading(String fileName) {
return false;
}
public boolean fileNeedsReloading(URL fileUrl) {
return false;
}
public InputStream loadFile(URL fileUrl) {
return null;
}
public void monitorFile(URL fileUrl) {
}
public URL normalizeToFileProtocol(URL url) {
return null;
}
public boolean support() {
return true;
}
public boolean internal() {
return true;
}
public Collection<? extends URL> getAllPhysicalUrls(URL url) throws IOException {
return null;
}
}
@@ -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 com.opensymphony.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));
}
}
@@ -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 com.opensymphony.xwork2.util.location;
import com.opensymphony.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("com/opensymphony/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("com/opensymphony/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)));
}
}
@@ -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 com.opensymphony.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(),
"com/opensymphony/xwork2/util/location/LocationUtilsTest.java"
.equals(loc.getURI()));
}
}
@@ -0,0 +1,24 @@
package com.opensymphony.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("foo (bob/ally)", LoggerUtils.format("foo (#0/#1)", "bob", "ally"));
assertEquals("foo (bobally)", LoggerUtils.format("foo (#0#1)", "bob", "ally"));
assertEquals(null, LoggerUtils.format(null));
assertEquals("", LoggerUtils.format(""));
}
}
@@ -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 com.opensymphony.xwork2.util.profiling;
import junit.framework.TestCase;
/**
*
* @author tm_jee
* @version $Date$ $Id$
*/
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);
}
}
@@ -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 com.opensymphony.xwork2.util.profiling;
import junit.framework.TestCase;
/**
* @author tmjee
* @version $Date$ $Id$
*/
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;
}
}
@@ -0,0 +1,47 @@
package com.opensymphony.xwork2.validator.validators;
import java.util.List;
import java.util.Map;
import com.opensymphony.xwork2.XWorkTestCase;
import com.opensymphony.xwork2.validator.DelegatingValidatorContext;
import com.opensymphony.xwork2.validator.ValidatorContext;
import com.opensymphony.xwork2.validator.VisitorValidatorTestAction;
import com.opensymphony.xwork2.validator.validators.VisitorFieldValidator.AppendingValidatorContext;
public class AppendingValidatorContextTest extends XWorkTestCase {
private static final String FIRST_NAME = "first";
private static final String SECOND_NAME = "second";
private static final String FIELD_NAME = "fieldName";
private static final String FULL_FIELD_NAME = FIRST_NAME + "." + SECOND_NAME + "." + FIELD_NAME;
private VisitorValidatorTestAction action;
private VisitorFieldValidator.AppendingValidatorContext validatorContext;
@Override
protected void setUp() throws Exception {
super.setUp();
action = new VisitorValidatorTestAction();
ValidatorContext vc1 = new DelegatingValidatorContext(action);
VisitorFieldValidator.AppendingValidatorContext vc2 = new AppendingValidatorContext(
vc1, "value", FIRST_NAME, "");
validatorContext = new AppendingValidatorContext(vc2, "value", SECOND_NAME, "");
}
public void testGetFullFieldName() throws Exception {
String fullFieldName = validatorContext.getFullFieldName(FIELD_NAME);
assertEquals(FULL_FIELD_NAME, fullFieldName);
}
public void testAddFieldError() throws Exception {
validatorContext.addFieldError(FIELD_NAME, "fieldError");
assertTrue(action.hasFieldErrors());
Map<String, List<String>> fieldErrors = action.getFieldErrors();
assertEquals(1, fieldErrors.size());
assertTrue(fieldErrors.containsKey(FULL_FIELD_NAME));
}
}
@@ -0,0 +1,93 @@
package com.opensymphony.xwork2.validator.validators;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.XWorkTestCase;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.ValueStackFactory;
import com.opensymphony.xwork2.validator.GenericValidatorContext;
import com.opensymphony.xwork2.validator.ValidatorContext;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class DateRangeFieldValidatorTest extends XWorkTestCase {
public void testPassValidation() throws Exception {
// given
ValidationAction action = prepareAction(createDate(2013, 6, 6));
ValidatorContext context = new GenericValidatorContext(action);
DateRangeFieldValidator validator = prepareValidator(action, context);
// when
validator.validate(action);
// then
assertTrue(context.getFieldErrors().size() == 0);
}
public void testMinValidation() throws Exception {
// given
ValidationAction action = prepareAction(createDate(2012, Calendar.MARCH, 3));
ValidatorContext context = new GenericValidatorContext(action);
DateRangeFieldValidator validator = prepareValidator(action, context);
// when
validator.validate(action);
// then
assertTrue(context.getFieldErrors().size() == 1);
assertEquals("Max is 12.12.13, min is 01.01.13 but value is 03.03.12", context.getFieldErrors().get("dateRange").get(0));
}
public void testMaxValidation() throws Exception {
// given
ValidationAction action = prepareAction(createDate(2014, Calendar.APRIL, 4));
ValidatorContext context = new GenericValidatorContext(action);
DateRangeFieldValidator validator = prepareValidator(action, context);
// when
validator.validate(action);
// then
assertTrue(context.getFieldErrors().size() == 1);
assertEquals("Max is 12.12.13, min is 01.01.13 but value is 04.04.14", context.getFieldErrors().get("dateRange").get(0));
}
private ValidationAction prepareAction(Date range) {
ValidationAction action = new ValidationAction();
action.setDateMinValue(createDate(2013, Calendar.JANUARY, 1));
action.setDateMaxValue(createDate(2013, Calendar.DECEMBER, 12));
action.setDateRange(range);
return action;
}
private Date createDate(int year, int month, int day) {
Calendar cal = Calendar.getInstance();
cal.set(year, month, day);
return cal.getTime();
}
private DateRangeFieldValidator prepareValidator(ValidationAction action, ValidatorContext context) {
ValueStack valueStack = container.getInstance(ValueStackFactory.class).createValueStack();
valueStack.push(action);
DateRangeFieldValidator validator = new DateRangeFieldValidator();
validator.setValueStack(valueStack);
validator.setMaxExpression("${dateMaxValue}");
validator.setMinExpression("${dateMinValue}");
validator.setValidatorContext(context);
validator.setFieldName("dateRange");
validator.setDefaultMessage("Max is ${dateMaxValue}, min is ${dateMinValue} but value is ${dateRange}");
return validator;
}
@Override
public void setUp() throws Exception {
super.setUp();
ActionContext.getContext().setLocale(new Locale("DE"));
}
}
@@ -0,0 +1,76 @@
package com.opensymphony.xwork2.validator.validators;
import com.opensymphony.xwork2.XWorkTestCase;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.ValueStackFactory;
import com.opensymphony.xwork2.validator.GenericValidatorContext;
import com.opensymphony.xwork2.validator.ValidatorContext;
public class IntRangeFieldValidatorTest extends XWorkTestCase {
public void testPassValidation() throws Exception {
// given
ValidationAction action = prepareAction(100);
ValidatorContext context = new GenericValidatorContext(action);
IntRangeFieldValidator validator = prepareValidator(action, context);
// when
validator.validate(action);
// then
assertTrue(context.getFieldErrors().size() == 0);
}
public void testMinValidation() throws Exception {
// given
ValidationAction action = prepareAction(98);
ValidatorContext context = new GenericValidatorContext(action);
IntRangeFieldValidator validator = prepareValidator(action, context);
// when
validator.validate(action);
// then
assertTrue(context.getFieldErrors().size() == 1);
assertEquals("Max is 101, min is 99 but value is 98", context.getFieldErrors().get("intRange").get(0));
}
public void testMaxValidation() throws Exception {
// given
ValidationAction action = prepareAction(102);
ValidatorContext context = new GenericValidatorContext(action);
IntRangeFieldValidator validator = prepareValidator(action, context);
// when
validator.validate(action);
// then
assertTrue(context.getFieldErrors().size() == 1);
assertEquals("Max is 101, min is 99 but value is 102", context.getFieldErrors().get("intRange").get(0));
}
private ValidationAction prepareAction(int intRange) {
ValidationAction action = new ValidationAction();
action.setIntMaxValue(101);
action.setIntMinValue(99);
action.setIntRange(intRange);
return action;
}
private IntRangeFieldValidator prepareValidator(ValidationAction action, ValidatorContext context) {
ValueStack valueStack = container.getInstance(ValueStackFactory.class).createValueStack();
valueStack.push(action);
IntRangeFieldValidator validator = new IntRangeFieldValidator();
validator.setValueStack(valueStack);
validator.setMaxExpression("${intMaxValue}");
validator.setMinExpression("${intMinValue}");
validator.setValidatorContext(context);
validator.setFieldName("intRange");
validator.setDefaultMessage("Max is ${intMaxValue}, min is ${intMinValue} but value is ${intRange}");
return validator;
}
}
@@ -0,0 +1,76 @@
package com.opensymphony.xwork2.validator.validators;
import com.opensymphony.xwork2.XWorkTestCase;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.ValueStackFactory;
import com.opensymphony.xwork2.validator.GenericValidatorContext;
import com.opensymphony.xwork2.validator.ValidatorContext;
public class LongRangeFieldValidatorTest extends XWorkTestCase {
public void testPassValidation() throws Exception {
// given
ValidationAction action = prepareAction(100);
ValidatorContext context = new GenericValidatorContext(action);
LongRangeFieldValidator validator = prepareValidator(action, context);
// when
validator.validate(action);
// then
assertTrue(context.getFieldErrors().size() == 0);
}
public void testMinValidation() throws Exception {
// given
ValidationAction action = prepareAction(98);
ValidatorContext context = new GenericValidatorContext(action);
LongRangeFieldValidator validator = prepareValidator(action, context);
// when
validator.validate(action);
// then
assertTrue(context.getFieldErrors().size() == 1);
assertEquals("Max is 101, min is 99 but value is 98", context.getFieldErrors().get("longRange").get(0));
}
public void testMaxValidation() throws Exception {
// given
ValidationAction action = prepareAction(102);
ValidatorContext context = new GenericValidatorContext(action);
LongRangeFieldValidator validator = prepareValidator(action, context);
// when
validator.validate(action);
// then
assertTrue(context.getFieldErrors().size() == 1);
assertEquals("Max is 101, min is 99 but value is 102", context.getFieldErrors().get("longRange").get(0));
}
private ValidationAction prepareAction(long longRange) {
ValidationAction action = new ValidationAction();
action.setLongMaxValue(101L);
action.setLongMinValue(99L);
action.setLongRange(longRange);
return action;
}
private LongRangeFieldValidator prepareValidator(ValidationAction action, ValidatorContext context) {
ValueStack valueStack = container.getInstance(ValueStackFactory.class).createValueStack();
valueStack.push(action);
LongRangeFieldValidator validator = new LongRangeFieldValidator();
validator.setValueStack(valueStack);
validator.setMaxExpression("${longMaxValue}");
validator.setMinExpression("${longMinValue}");
validator.setValidatorContext(context);
validator.setFieldName("longRange");
validator.setDefaultMessage("Max is ${longMaxValue}, min is ${longMinValue} but value is ${longRange}");
return validator;
}
}
@@ -0,0 +1,79 @@
package com.opensymphony.xwork2.validator.validators;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.XWorkTestCase;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.validator.GenericValidatorContext;
import com.opensymphony.xwork2.validator.ValidatorContext;
public class RequiredStringValidatorTest extends XWorkTestCase {
public void testRequiredStringPass() throws Exception {
// given
ValueStack valueStack = ActionContext.getContext().getValueStack();
ValidationAction action = new ValidationAction();
action.setStringValue("a string");
valueStack.push(action);
ValidatorContext context = new GenericValidatorContext(action);
RequiredStringValidator validator = new RequiredStringValidator();
validator.setValidatorContext(context);
validator.setFieldName("stringValue");
validator.setValueStack(valueStack);
// when
validator.validate(action);
// then
assertTrue(context.getFieldErrors().size() == 0);
}
public void testRequiredStringFails() throws Exception {
// given
ValueStack valueStack = ActionContext.getContext().getValueStack();
ValidationAction action = new ValidationAction();
valueStack.push(action);
ValidatorContext context = new GenericValidatorContext(action);
RequiredStringValidator validator = new RequiredStringValidator();
validator.setValidatorContext(context);
validator.setFieldName("stringValue");
validator.setValueStack(valueStack);
validator.setDefaultMessage("Field ${fieldName} is required");
// when
validator.validate(action);
// then
assertTrue(context.getFieldErrors().size() == 1);
assertEquals(context.getFieldErrors().get("stringValue").get(0), "Field stringValue is required");
}
public void testTrimAsExpression() throws Exception {
// given
ValueStack valueStack = ActionContext.getContext().getValueStack();
ActionSupport action = new ActionSupport() {
public boolean getTrimValue() {
return false;
}
};
valueStack.push(action);
RequiredStringValidator validator = new RequiredStringValidator();
validator.setValueStack(valueStack);
assertTrue(validator.isTrim());
// when
validator.setTrimExpression("${trimValue}");
// then
assertFalse(validator.isTrim());
}
}
@@ -0,0 +1,76 @@
package com.opensymphony.xwork2.validator.validators;
import com.opensymphony.xwork2.XWorkTestCase;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.ValueStackFactory;
import com.opensymphony.xwork2.validator.GenericValidatorContext;
import com.opensymphony.xwork2.validator.ValidatorContext;
public class ShortRangeFieldValidatorTest extends XWorkTestCase {
public void testPassValidation() throws Exception {
// given
ValidationAction action = prepareAction((short) 5);
ValidatorContext context = new GenericValidatorContext(action);
ShortRangeFieldValidator validator = prepareValidator(action, context);
// when
validator.validate(action);
// then
assertTrue(context.getFieldErrors().size() == 0);
}
public void testMinValidation() throws Exception {
// given
ValidationAction action = prepareAction((short) 1);
ValidatorContext context = new GenericValidatorContext(action);
ShortRangeFieldValidator validator = prepareValidator(action, context);
// when
validator.validate(action);
// then
assertTrue(context.getFieldErrors().size() == 1);
assertEquals("Max is 10, min is 2 but value is 1", context.getFieldErrors().get("shortRange").get(0));
}
public void testMaxValidation() throws Exception {
// given
ValidationAction action = prepareAction((short) 11);
ValidatorContext context = new GenericValidatorContext(action);
ShortRangeFieldValidator validator = prepareValidator(action, context);
// when
validator.validate(action);
// then
assertTrue(context.getFieldErrors().size() == 1);
assertEquals("Max is 10, min is 2 but value is 11", context.getFieldErrors().get("shortRange").get(0));
}
private ValidationAction prepareAction(short range) {
ValidationAction action = new ValidationAction();
action.setShortMaxValue((short) 10);
action.setShortMinValue((short) 2);
action.setShortRange(range);
return action;
}
private ShortRangeFieldValidator prepareValidator(ValidationAction action, ValidatorContext context) {
ValueStack valueStack = container.getInstance(ValueStackFactory.class).createValueStack();
valueStack.push(action);
ShortRangeFieldValidator validator = new ShortRangeFieldValidator();
validator.setValueStack(valueStack);
validator.setMaxExpression("${shortMaxValue}");
validator.setMinExpression("${shortMinValue}");
validator.setValidatorContext(context);
validator.setFieldName("shortRange");
validator.setDefaultMessage("Max is ${shortMaxValue}, min is ${shortMinValue} but value is ${shortRange}");
return validator;
}
}
@@ -0,0 +1,136 @@
package com.opensymphony.xwork2.validator.validators;
import java.util.Date;
public class ValidationAction {
private Integer intRange;
private Integer intMinValue;
private Integer intMaxValue;
private Short shortRange;
private Short shortMinValue;
private Short shortMaxValue;
private Long longRange;
private Long longMinValue;
private Long longMaxValue;
private Date dateRange;
private Date dateMinValue;
private Date dateMaxValue;
private String dateFormat;
private String stringValue;
public Integer getIntRange() {
return intRange;
}
public void setIntRange(Integer intRange) {
this.intRange = intRange;
}
public Integer getIntMinValue() {
return intMinValue;
}
public void setIntMinValue(Integer intMinValue) {
this.intMinValue = intMinValue;
}
public Integer getIntMaxValue() {
return intMaxValue;
}
public void setIntMaxValue(Integer intMaxValue) {
this.intMaxValue = intMaxValue;
}
public Short getShortRange() {
return shortRange;
}
public void setShortRange(Short shortRange) {
this.shortRange = shortRange;
}
public Short getShortMinValue() {
return shortMinValue;
}
public void setShortMinValue(Short shortMinValue) {
this.shortMinValue = shortMinValue;
}
public Short getShortMaxValue() {
return shortMaxValue;
}
public void setShortMaxValue(Short shortMaxValue) {
this.shortMaxValue = shortMaxValue;
}
public Long getLongRange() {
return longRange;
}
public void setLongRange(Long longRange) {
this.longRange = longRange;
}
public Long getLongMinValue() {
return longMinValue;
}
public void setLongMinValue(Long longMinValue) {
this.longMinValue = longMinValue;
}
public Long getLongMaxValue() {
return longMaxValue;
}
public void setLongMaxValue(Long longMaxValue) {
this.longMaxValue = longMaxValue;
}
public Date getDateRange() {
return dateRange;
}
public void setDateRange(Date dateRange) {
this.dateRange = dateRange;
}
public Date getDateMinValue() {
return dateMinValue;
}
public void setDateMinValue(Date dateMinValue) {
this.dateMinValue = dateMinValue;
}
public Date getDateMaxValue() {
return dateMaxValue;
}
public void setDateMaxValue(Date dateMaxValue) {
this.dateMaxValue = dateMaxValue;
}
public String getDateFormat() {
return dateFormat;
}
public void setDateFormat(String dateFormat) {
this.dateFormat = dateFormat;
}
public void setStringValue(String stringValue) {
this.stringValue = stringValue;
}
public String getStringValue() {
return stringValue;
}
}
@@ -0,0 +1,53 @@
/*
* 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 com.opensymphony.xwork2.validator.validators;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.XWorkTestCase;
import com.opensymphony.xwork2.ognl.OgnlValueStack;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.ValueStackFactory;
import com.opensymphony.xwork2.validator.ValidationException;
/**
* @author tmjee
* @version $Date$ $Id$
*/
public class ValidatorSupportTest extends XWorkTestCase {
public void testConditionalParseExpression() throws Exception {
ValueStack oldStack = ActionContext.getContext().getValueStack();
try {
OgnlValueStack stack = (OgnlValueStack) container.getInstance(ValueStackFactory.class).createValueStack();
stack.getContext().put(ActionContext.CONTAINER, container);
stack.getContext().put("something", "somevalue");
ActionContext.getContext().setValueStack(stack);
ValidatorSupport validator = new ValidatorSupport() {
public void validate(Object object) throws ValidationException {
}
};
validator.setValueStack(ActionContext.getContext().getValueStack());
String result1 = validator.parse("${#something}", String.class).toString();
assertEquals(result1, "somevalue");
}
finally {
ActionContext.getContext().setValueStack(oldStack);
}
}
}
@@ -0,0 +1,10 @@
#
# Copyright (c) 2002-2006 by OpenSymphony
# All rights reserved.
#
hello=Hello World
hello.0=Hello World {0}
hello.1=Hello World. This is {0} speaking {1}
format.number = {0,number,#0.0##}
@@ -0,0 +1 @@
invalid.count=Count must be between ${min} and ${max}, current value is ${count}.
@@ -0,0 +1,8 @@
#
# Copyright (c) 2002-2006 by OpenSymphony
# All rights reserved.
#
hello=Hello World
hello.0=Hello World {0}
hello.1=Hello World. This is {0} speaking {1}
@@ -0,0 +1,13 @@
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.dtd">
<validators>
<field name="count">
<field-validator type="required">
<message>You must enter a value for count.</message>
</field-validator>
<field-validator type="int">
<param name="min">1</param>
<param name="max">10</param>
<message>count must be between ${min} and ${max}, current value is ${count}.</message>
</field-validator>
</field>
</validators>
@@ -0,0 +1 @@
invalid.fieldvalue.birth=Invalid date for birth.
@@ -0,0 +1,6 @@
#
# Copyright (c) 2002-2006 by OpenSymphony
# All rights reserved.
#
invalid.fieldvalue.birth=Invalid date for birth.
@@ -0,0 +1,13 @@
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.dtd">
<validators>
<field name="baz">
<field-validator type="required">
<message>You must enter a value for baz.</message>
</field-validator>
<field-validator type="int">
<param name="min">2</param>
<param name="max">4</param>
<message>baz out of range.</message>
</field-validator>
</field>
</validators>
@@ -0,0 +1,18 @@
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.dtd">
<validators>
<field name="bean.name">
<field-validator type="required">
<message>You must enter a name for the bean.</message>
</field-validator>
</field>
<field name="bean.count">
<field-validator type="required">
<message>You must have a count for the bean.</message>
</field-validator>
<field-validator type="int">
<param name="min">0</param>
<param name="max">10</param>
<message>bean.count out of range.</message>
</field-validator>
</field>
</validators>
@@ -0,0 +1,58 @@
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.dtd">
<validators>
<field name="bar">
<field-validator type="required">
<message>You must enter a value for bar.</message>
</field-validator>
<field-validator type="int">
<param name="min">6</param>
<param name="max">10</param>
<message>bar must be between ${min} and ${max}, current value is ${bar}.</message>
</field-validator>
</field>
<field name="percentage">
<field-validator type="double">
<param name="minExclusive">0.1</param>
<param name="maxExclusive">10.1</param>
<message>percentage must be between ${minExclusive} and ${maxExclusive}, current value is ${percentage}.</message>
</field-validator>
</field>
<field name="date">
<field-validator type="date">
<param name="min">12/22/2002</param>
<param name="max">12/25/2002</param>
<message>The date must be between 12-22-2002 and 12-25-2002.</message>
</field-validator>
</field>
<field name="foo">
<field-validator type="int">
<param name="min">0</param>
<param name="max">100</param>
<message key="foo.range">Could not find foo.range!</message>
</field-validator>
</field>
<field name="baz">
<field-validator type="int">
<param name="min">0</param>
<message key="baz.range">Could not find baz.range!</message>
</field-validator>
</field>
<field name="longFoo">
<field-validator type="long">
<param name="min">0</param>
<param name="max">100</param>
<message key="foo.range">Could not find foo.range!</message>
</field-validator>
</field>
<field name="shortFoo">
<field-validator type="short">
<param name="min">0</param>
<param name="max">100</param>
<message key="foo.range">Could not find foo.range!</message>
</field-validator>
</field>
<validator type="expression">
<param name="expression">foo > bar</param>
<message>Foo must be greater than Bar. Foo = ${foo}, Bar = ${bar}.</message>
</validator>
</validators>
@@ -0,0 +1,13 @@
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.dtd">
<validators>
<field name="baz">
<field-validator type="required">
<message>You must enter a value for baz.</message>
</field-validator>
<field-validator type="int">
<param name="min">2</param>
<param name="max">4</param>
<message>baz out of range.</message>
</field-validator>
</field>
</validators>
@@ -0,0 +1,3 @@
foo.range=Foo Range Message
baz.range=${getText(fieldName)} must be greater than ${min}
baz=Baz Field
@@ -0,0 +1 @@
foo.range=I don''t know German
@@ -0,0 +1,8 @@
#
# Copyright (c) 2002-2006 by OpenSymphony
# All rights reserved.
#
foo.range=Foo Range Message
baz.range=${getText(fieldName)} must be greater than ${min}
baz=Baz Field
@@ -0,0 +1,6 @@
#
# Copyright (c) 2002-2006 by OpenSymphony
# All rights reserved.
#
foo.range=I don''t know German
@@ -0,0 +1,5 @@
#
# Copyright (c) 2002-2006 by OpenSymphony
# All rights reserved.
#
@@ -0,0 +1,10 @@
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.dtd">
<validators>
<field name="count">
<field-validator type="int">
<param name="min">1</param>
<param name="max">100</param>
<message>Count must be between ${min} and ${max}, current value is ${count}.</message>
</field-validator>
</field>
</validators>
@@ -0,0 +1,8 @@
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.dtd">
<validators>
<field name="name">
<field-validator type="requiredstring" foo="bar">
<message>You must enter a name.</message>
</field-validator>
</field>
</validators>
@@ -0,0 +1,15 @@
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">
<validators>
<field name="count">
<field-validator type="int" short-circuit="true">
<param name="min">1</param>
<param name="max">100</param>
<message key="invalid.count">Invalid count value, must be between ${min} and ${max}, current value ${count}!</message>
</field-validator>
<field-validator type="int">
<param name="min">20</param>
<param name="max">80</param>
<message key="invalid.count.bad">Smaller Invalid Count: ${count}</message>
</field-validator>
</field>
</validators>
@@ -0,0 +1,9 @@
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.dtd">
<validators>
<field name="name">
<field-validator type="fieldexpression">
<param name="expression">name.length() > 5</param>
<message>Name must be greater than 5 characters, it is currently '${name}'</message>
</field-validator>
</field>
</validators>
@@ -0,0 +1,8 @@
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.dtd">
<validators>
<field name="name">
<field-validator type="requiredstring">
<message>You must enter a name.</message>
</field-validator>
</field>
</validators>
@@ -0,0 +1,14 @@
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.dtd">
<validators>
<field name="birth">
<field-validator type="date">
<param name="min">01/01/1970</param>
<message>You must have been born after 1970.</message>
</field-validator>
</field>
<field name="child">
<field-validator type="visitor">
<message>child bean: </message>
</field-validator>
</field>
</validators>
@@ -0,0 +1,9 @@
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.dtd">
<validators>
<field name="birth">
<field-validator type="date">
<param name="min">01/01/1970</param>
<message>You must have been born after 1970.</message>
</field-validator>
</field>
</validators>

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