Consistent formatting

This commit is contained in:
Juergen Hoeller 2016-03-24 19:22:49 +01:00
parent 2cdb0cf690
commit 517ebd1d3e
101 changed files with 681 additions and 509 deletions

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2015 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -101,7 +101,7 @@ public class AspectJAfterReturningAdvice extends AbstractAspectJAdvice
else if (Object.class == type && void.class == method.getReturnType()) { else if (Object.class == type && void.class == method.getReturnType()) {
return true; return true;
} }
else{ else {
return ClassUtils.isAssignable(type, method.getReturnType()); return ClassUtils.isAssignable(type, method.getReturnType());
} }
} }

View File

@ -307,7 +307,8 @@ public class AspectJAdviceParameterNameDiscovererTests {
try { try {
discoverer.getParameterNames(m); discoverer.getParameterNames(m);
fail("Expecting " + exceptionType.getName() + " with message '" + message + "'"); fail("Expecting " + exceptionType.getName() + " with message '" + message + "'");
} catch (RuntimeException expected) { }
catch (RuntimeException expected) {
assertEquals("Expecting exception of type " + exceptionType.getName(), assertEquals("Expecting exception of type " + exceptionType.getName(),
exceptionType, expected.getClass()); exceptionType, expected.getClass());
assertEquals("Exception message does not match expected", message, expected.getMessage()); assertEquals("Exception message does not match expected", message, expected.getMessage());

View File

@ -215,7 +215,8 @@ public final class MethodInvocationProceedingJoinPointTests {
itb.setSpouse(new TestBean()); itb.setSpouse(new TestBean());
try { try {
itb.unreliableFileOperation(); itb.unreliableFileOperation();
} catch (IOException ex) { }
catch (IOException ex) {
// we don't realy care... // we don't realy care...
} }
} }

View File

@ -1,3 +1,19 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj; package org.springframework.aop.aspectj;
import java.lang.annotation.Documented; import java.lang.annotation.Documented;
@ -97,12 +113,14 @@ public class TrickyAspectJPointcutExpressionTests {
try { try {
bean.sayHello(); bean.sayHello();
fail("Expected exception"); fail("Expected exception");
} catch (TestException e) { }
assertEquals(message, e.getMessage()); catch (TestException ex) {
assertEquals(message, ex.getMessage());
} }
assertEquals(1, logAdvice.getCountThrows()); assertEquals(1, logAdvice.getCountThrows());
} }
public static class SimpleThrowawayClassLoader extends OverridingClassLoader { public static class SimpleThrowawayClassLoader extends OverridingClassLoader {
/** /**
@ -115,15 +133,16 @@ public class TrickyAspectJPointcutExpressionTests {
} }
@SuppressWarnings("serial") @SuppressWarnings("serial")
public static class TestException extends RuntimeException { public static class TestException extends RuntimeException {
public TestException(String string) { public TestException(String string) {
super(string); super(string);
} }
} }
@Target({ ElementType.METHOD, ElementType.TYPE }) @Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Documented @Documented
@ -131,18 +150,23 @@ public class TrickyAspectJPointcutExpressionTests {
public static @interface Log { public static @interface Log {
} }
public static interface TestService { public static interface TestService {
public String sayHello(); public String sayHello();
} }
@Log @Log
public static class TestServiceImpl implements TestService { public static class TestServiceImpl implements TestService {
@Override @Override
public String sayHello() { public String sayHello() {
throw new TestException("TestServiceImpl"); throw new TestException("TestServiceImpl");
} }
} }
public class LogUserAdvice implements MethodBeforeAdvice, ThrowsAdvice { public class LogUserAdvice implements MethodBeforeAdvice, ThrowsAdvice {
private int countBefore = 0; private int countBefore = 0;
@ -154,9 +178,9 @@ public class TrickyAspectJPointcutExpressionTests {
countBefore++; countBefore++;
} }
public void afterThrowing(Exception e) throws Throwable { public void afterThrowing(Exception ex) throws Throwable {
countThrows++; countThrows++;
throw e; throw ex;
} }
public int getCountBefore() { public int getCountBefore() {
@ -171,7 +195,6 @@ public class TrickyAspectJPointcutExpressionTests {
countThrows = 0; countThrows = 0;
countBefore = 0; countBefore = 0;
} }
} }
} }

View File

@ -61,7 +61,8 @@ public final class DebugInterceptorTests {
try { try {
interceptor.invoke(methodInvocation); interceptor.invoke(methodInvocation);
fail("Must have propagated the IllegalArgumentException."); fail("Must have propagated the IllegalArgumentException.");
} catch (IllegalArgumentException expected) { }
catch (IllegalArgumentException expected) {
} }
checkCallCountTotal(interceptor); checkCallCountTotal(interceptor);

View File

@ -60,7 +60,8 @@ public final class SimpleTraceInterceptorTests {
try { try {
interceptor.invokeUnderTrace(mi, log); interceptor.invokeUnderTrace(mi, log);
fail("Must have propagated the IllegalArgumentException."); fail("Must have propagated the IllegalArgumentException.");
} catch (IllegalArgumentException expected) { }
catch (IllegalArgumentException expected) {
} }
verify(log).trace(anyString()); verify(log).trace(anyString());

View File

@ -154,7 +154,8 @@ public class ThreadLocalTargetSourceTests {
// try second time // try second time
try { try {
source.getTarget(); source.getTarget();
} catch(NullPointerException ex) { }
catch (NullPointerException ex) {
fail("Should not throw NPE"); fail("Should not throw NPE");
} }
} }

View File

@ -210,7 +210,8 @@ public class AnnotationAsyncExecutionAspectTests {
public synchronized void waitForCompletion() { public synchronized void waitForCompletion() {
try { try {
wait(WAIT_TIME); wait(WAIT_TIME);
} catch (InterruptedException e) { }
catch (InterruptedException ex) {
fail("Didn't finish the async job in " + WAIT_TIME + " milliseconds"); fail("Didn't finish the async job in " + WAIT_TIME + " milliseconds");
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2012 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -204,7 +204,7 @@ public class FieldRetrievingFactoryBean
// instance field // instance field
return this.fieldObject.get(this.targetObject); return this.fieldObject.get(this.targetObject);
} }
else{ else {
// class field // class field
return this.fieldObject.get(null); return this.fieldObject.get(null);
} }

View File

@ -81,19 +81,22 @@ public final class ServiceLocatorFactoryBeanTests {
TestServiceLocator factory = (TestServiceLocator) bf.getBean("factory"); TestServiceLocator factory = (TestServiceLocator) bf.getBean("factory");
factory.getTestService(); factory.getTestService();
fail("Must fail on more than one matching type"); fail("Must fail on more than one matching type");
} catch (NoSuchBeanDefinitionException ex) { /* expected */ } }
catch (NoSuchBeanDefinitionException ex) { /* expected */ }
try { try {
TestServiceLocator2 factory = (TestServiceLocator2) bf.getBean("factory2"); TestServiceLocator2 factory = (TestServiceLocator2) bf.getBean("factory2");
factory.getTestService(null); factory.getTestService(null);
fail("Must fail on more than one matching type"); fail("Must fail on more than one matching type");
} catch (NoSuchBeanDefinitionException ex) { /* expected */ } }
catch (NoSuchBeanDefinitionException ex) { /* expected */ }
try { try {
TestService2Locator factory = (TestService2Locator) bf.getBean("factory3"); TestService2Locator factory = (TestService2Locator) bf.getBean("factory3");
factory.getTestService(); factory.getTestService();
fail("Must fail on no matching types"); fail("Must fail on no matching types");
} catch (NoSuchBeanDefinitionException ex) { /* expected */ } }
catch (NoSuchBeanDefinitionException ex) { /* expected */ }
} }
@Test @Test
@ -138,7 +141,8 @@ public final class ServiceLocatorFactoryBeanTests {
TestService2Locator factory3 = (TestService2Locator) bf.getBean("factory3"); TestService2Locator factory3 = (TestService2Locator) bf.getBean("factory3");
factory3.getTestService(); factory3.getTestService();
fail("Must fail on no matching type"); fail("Must fail on no matching type");
} catch (CustomServiceLocatorException3 ex) { /* expected */ } }
catch (CustomServiceLocatorException3 ex) { /* expected */ }
} }
@Test @Test
@ -160,7 +164,8 @@ public final class ServiceLocatorFactoryBeanTests {
try { try {
factory.getTestService("bogusTestService"); factory.getTestService("bogusTestService");
fail("Illegal operation allowed"); fail("Illegal operation allowed");
} catch (NoSuchBeanDefinitionException ex) { /* expected */ } }
catch (NoSuchBeanDefinitionException ex) { /* expected */ }
} }
@Ignore @Test // worked when using an ApplicationContext (see commented), fails when using BeanFactory @Ignore @Test // worked when using an ApplicationContext (see commented), fails when using BeanFactory
@ -275,7 +280,8 @@ public final class ServiceLocatorFactoryBeanTests {
try { try {
ServiceLocatorFactoryBean factory = new ServiceLocatorFactoryBean(); ServiceLocatorFactoryBean factory = new ServiceLocatorFactoryBean();
factory.setBeanFactory(beanFactory); factory.setBeanFactory(beanFactory);
} catch (FatalBeanException ex) { }
catch (FatalBeanException ex) {
// expected // expected
} }
} }

View File

@ -324,7 +324,8 @@ public class CallbacksSecurityTests {
try { try {
acc.checkPermission(new PropertyPermission("*", "read")); acc.checkPermission(new PropertyPermission("*", "read"));
fail("Acc should not have any permissions"); fail("Acc should not have any permissions");
} catch (SecurityException se) { }
catch (SecurityException se) {
// expected // expected
} }
@ -342,7 +343,8 @@ public class CallbacksSecurityTests {
} }
}, acc); }, acc);
fail("expected security exception"); fail("expected security exception");
} catch (Exception ex) { }
catch (Exception ex) {
} }
final Class<ConstructorBean> cl = ConstructorBean.class; final Class<ConstructorBean> cl = ConstructorBean.class;
@ -356,7 +358,8 @@ public class CallbacksSecurityTests {
} }
}, acc); }, acc);
fail("expected security exception"); fail("expected security exception");
} catch (Exception ex) { }
catch (Exception ex) {
} }
} }
@ -365,7 +368,8 @@ public class CallbacksSecurityTests {
try { try {
beanFactory.getBean("spring-init"); beanFactory.getBean("spring-init");
fail("expected security exception"); fail("expected security exception");
} catch (BeanCreationException ex) { }
catch (BeanCreationException ex) {
assertTrue(ex.getCause() instanceof SecurityException); assertTrue(ex.getCause() instanceof SecurityException);
} }
} }
@ -375,7 +379,8 @@ public class CallbacksSecurityTests {
try { try {
beanFactory.getBean("custom-init"); beanFactory.getBean("custom-init");
fail("expected security exception"); fail("expected security exception");
} catch (BeanCreationException ex) { }
catch (BeanCreationException ex) {
assertTrue(ex.getCause() instanceof SecurityException); assertTrue(ex.getCause() instanceof SecurityException);
} }
} }
@ -399,7 +404,8 @@ public class CallbacksSecurityTests {
try { try {
beanFactory.getBean("spring-factory"); beanFactory.getBean("spring-factory");
fail("expected security exception"); fail("expected security exception");
} catch (BeanCreationException ex) { }
catch (BeanCreationException ex) {
assertTrue(ex.getCause() instanceof SecurityException); assertTrue(ex.getCause() instanceof SecurityException);
} }
@ -416,7 +422,8 @@ public class CallbacksSecurityTests {
try { try {
beanFactory.getBean("custom-static-factory-method"); beanFactory.getBean("custom-static-factory-method");
fail("expected security exception"); fail("expected security exception");
} catch (BeanCreationException ex) { }
catch (BeanCreationException ex) {
assertTrue(ex.getMostSpecificCause() instanceof SecurityException); assertTrue(ex.getMostSpecificCause() instanceof SecurityException);
} }
} }
@ -426,7 +433,8 @@ public class CallbacksSecurityTests {
try { try {
beanFactory.getBean("custom-factory-method"); beanFactory.getBean("custom-factory-method");
fail("expected security exception"); fail("expected security exception");
} catch (BeanCreationException ex) { }
catch (BeanCreationException ex) {
assertTrue(ex.getMostSpecificCause() instanceof SecurityException); assertTrue(ex.getMostSpecificCause() instanceof SecurityException);
} }
} }
@ -436,7 +444,8 @@ public class CallbacksSecurityTests {
try { try {
beanFactory.getBean("privileged-static-factory-method"); beanFactory.getBean("privileged-static-factory-method");
fail("expected security exception"); fail("expected security exception");
} catch (BeanCreationException ex) { }
catch (BeanCreationException ex) {
assertTrue(ex.getMostSpecificCause() instanceof SecurityException); assertTrue(ex.getMostSpecificCause() instanceof SecurityException);
} }
} }
@ -446,7 +455,8 @@ public class CallbacksSecurityTests {
try { try {
beanFactory.getBean("constructor"); beanFactory.getBean("constructor");
fail("expected security exception"); fail("expected security exception");
} catch (BeanCreationException ex) { }
catch (BeanCreationException ex) {
// expected // expected
assertTrue(ex.getMostSpecificCause() instanceof SecurityException); assertTrue(ex.getMostSpecificCause() instanceof SecurityException);
} }
@ -472,7 +482,8 @@ public class CallbacksSecurityTests {
try { try {
beanFactory.getBean("property-injection"); beanFactory.getBean("property-injection");
fail("expected security exception"); fail("expected security exception");
} catch (BeanCreationException ex) { }
catch (BeanCreationException ex) {
assertTrue(ex.getMessage().contains("security")); assertTrue(ex.getMessage().contains("security"));
} }

View File

@ -48,7 +48,8 @@ public class DuplicateBeanIdTests {
try { try {
reader.loadBeanDefinitions(new ClassPathResource("DuplicateBeanIdTests-sameLevel-context.xml", this.getClass())); reader.loadBeanDefinitions(new ClassPathResource("DuplicateBeanIdTests-sameLevel-context.xml", this.getClass()));
fail("expected parsing exception due to duplicate ids in same nesting level"); fail("expected parsing exception due to duplicate ids in same nesting level");
} catch (Exception ex) { }
catch (Exception ex) {
// expected // expected
} }
} }

View File

@ -485,7 +485,8 @@ public class CustomEditorTests {
CustomNumberEditor editor = new CustomNumberEditor(Short.class, true); CustomNumberEditor editor = new CustomNumberEditor(Short.class, true);
editor.setAsText(String.valueOf(Short.MAX_VALUE + 1)); editor.setAsText(String.valueOf(Short.MAX_VALUE + 1));
fail(Short.MAX_VALUE + 1 + " is greater than max value"); fail(Short.MAX_VALUE + 1 + " is greater than max value");
} catch (NumberFormatException ex) { }
catch (NumberFormatException ex) {
// expected // expected
} }
} }

View File

@ -70,7 +70,7 @@ public class CollectingReaderEventListener implements ReaderEventListener {
@Override @Override
public void aliasRegistered(AliasDefinition aliasDefinition) { public void aliasRegistered(AliasDefinition aliasDefinition) {
List aliases = (List) this.aliasMap.get(aliasDefinition.getBeanName()); List aliases = (List) this.aliasMap.get(aliasDefinition.getBeanName());
if(aliases == null) { if (aliases == null) {
aliases = new ArrayList(); aliases = new ArrayList();
this.aliasMap.put(aliasDefinition.getBeanName(), aliases); this.aliasMap.put(aliasDefinition.getBeanName(), aliases);
} }

View File

@ -186,7 +186,9 @@ class PrecedenceTestAspect implements BeanNameAware, Ordered {
try { try {
ret = ((Integer)pjp.proceed()).intValue(); ret = ((Integer)pjp.proceed()).intValue();
} }
catch(Throwable t) { throw new RuntimeException(t); } catch (Throwable t) {
throw new RuntimeException(t);
}
this.collaborator.aroundAdviceOne(this.name); this.collaborator.aroundAdviceOne(this.name);
return ret; return ret;
} }
@ -197,7 +199,9 @@ class PrecedenceTestAspect implements BeanNameAware, Ordered {
try { try {
ret = ((Integer)pjp.proceed()).intValue(); ret = ((Integer)pjp.proceed()).intValue();
} }
catch(Throwable t) {throw new RuntimeException(t);} catch (Throwable t) {
throw new RuntimeException(t);
}
this.collaborator.aroundAdviceTwo(this.name); this.collaborator.aroundAdviceTwo(this.name);
return ret; return ret;
} }

View File

@ -513,11 +513,13 @@ class RetryAspect {
try { try {
o = jp.proceed(); o = jp.proceed();
this.commitCalls++; this.commitCalls++;
} catch (RetryableException e) {
this.rollbackCalls++;
throw e;
} }
} catch (RetryableException re) { catch (RetryableException re) {
this.rollbackCalls++;
throw re;
}
}
catch (RetryableException re) {
retry = true; retry = true;
} }
} }

View File

@ -1,5 +1,5 @@
/** /**
* Copyright 2002-2012 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.aop.aspectj.autoproxy.spr3064; package org.springframework.aop.aspectj.autoproxy.spr3064;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
@ -35,6 +36,7 @@ public final class SPR3064Tests {
private Service service; private Service service;
@Test @Test
public void testServiceIsAdvised() { public void testServiceIsAdvised() {
ClassPathXmlApplicationContext ctx = ClassPathXmlApplicationContext ctx =
@ -46,7 +48,7 @@ public final class SPR3064Tests {
this.service.serveMe(); this.service.serveMe();
fail("service operation has not been advised by transaction interceptor"); fail("service operation has not been advised by transaction interceptor");
} }
catch(RuntimeException ex) { catch (RuntimeException ex) {
assertEquals("advice invoked",ex.getMessage()); assertEquals("advice invoked",ex.getMessage());
} }
} }
@ -56,7 +58,6 @@ public final class SPR3064Tests {
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@interface Transaction { @interface Transaction {
} }
@ -68,14 +69,12 @@ class TransactionInterceptor {
throw new RuntimeException("advice invoked"); throw new RuntimeException("advice invoked");
//return pjp.proceed(); //return pjp.proceed();
} }
} }
interface Service { interface Service {
void serveMe(); void serveMe();
} }
@ -85,5 +84,4 @@ class ServiceImpl implements Service {
@Transaction @Transaction
public void serveMe() { public void serveMe() {
} }
} }

View File

@ -400,7 +400,8 @@ public abstract class AbstractAopProxyTests {
public Object invoke(MethodInvocation invocation) throws Throwable { public Object invoke(MethodInvocation invocation) throws Throwable {
if (!context) { if (!context) {
assertNoInvocationContext(); assertNoInvocationContext();
} else { }
else {
assertNotNull("have context", ExposeInvocationInterceptor.currentInvocation()); assertNotNull("have context", ExposeInvocationInterceptor.currentInvocation());
} }
return s; return s;

View File

@ -354,7 +354,8 @@ public abstract class AbstractCacheAnnotationTests {
try { try {
service.throwCheckedSync(arg); service.throwCheckedSync(arg);
fail("Excepted exception"); fail("Excepted exception");
} catch (Exception ex) { }
catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
assertEquals("Wrong exception type", IOException.class, ex.getClass()); assertEquals("Wrong exception type", IOException.class, ex.getClass());
assertEquals(arg, ex.getMessage()); assertEquals(arg, ex.getMessage());
@ -365,7 +366,8 @@ public abstract class AbstractCacheAnnotationTests {
try { try {
service.throwUncheckedSync(Long.valueOf(1)); service.throwUncheckedSync(Long.valueOf(1));
fail("Excepted exception"); fail("Excepted exception");
} catch (RuntimeException ex) { }
catch (RuntimeException ex) {
assertEquals("Wrong exception type", UnsupportedOperationException.class, ex.getClass()); assertEquals("Wrong exception type", UnsupportedOperationException.class, ex.getClass());
assertEquals("1", ex.getMessage()); assertEquals("1", ex.getMessage());
} }

View File

@ -35,7 +35,10 @@ public class CacheAdviceParserTests {
try { try {
new GenericXmlApplicationContext("/org/springframework/cache/config/cache-advice-invalid.xml"); new GenericXmlApplicationContext("/org/springframework/cache/config/cache-advice-invalid.xml");
fail("Should have failed to load context, one advise define both a key and a key generator"); fail("Should have failed to load context, one advise define both a key and a key generator");
} catch (BeanDefinitionStoreException e) { // TODO better exception handling }
catch (BeanDefinitionStoreException ex) {
// TODO better exception handling
} }
} }
} }

View File

@ -72,7 +72,7 @@ public class PropertySourceAnnotationTests {
do { do {
name = iterator.next().getName(); name = iterator.next().getName();
} }
while(iterator.hasNext()); while (iterator.hasNext());
assertThat(name, is("p1")); assertThat(name, is("p1"));
} }

View File

@ -117,7 +117,7 @@ public class ConfigurationClassProcessingTests {
BeanFactory factory = initBeanFactory(ConfigWithBeanWithAliases.class); BeanFactory factory = initBeanFactory(ConfigWithBeanWithAliases.class);
assertSame(factory.getBean("name1"), ConfigWithBeanWithAliases.testBean); assertSame(factory.getBean("name1"), ConfigWithBeanWithAliases.testBean);
String[] aliases = factory.getAliases("name1"); String[] aliases = factory.getAliases("name1");
for(String alias : aliases) for (String alias : aliases)
assertSame(factory.getBean(alias), ConfigWithBeanWithAliases.testBean); assertSame(factory.getBean(alias), ConfigWithBeanWithAliases.testBean);
// method name should not be registered // method name should not be registered

View File

@ -37,7 +37,7 @@ public class Spr10546Tests {
@After @After
public void closeContext() { public void closeContext() {
if(context != null) { if (context != null) {
context.close(); context.close();
} }
} }

View File

@ -53,7 +53,8 @@ public class FactoryBeanAccessTests {
try { try {
assertEquals(Boat.class.getName(), expr.getValue(context)); assertEquals(Boat.class.getName(), expr.getValue(context));
fail("Expected BeanIsNotAFactoryException"); fail("Expected BeanIsNotAFactoryException");
} catch (BeanIsNotAFactoryException binafe) { }
catch (BeanIsNotAFactoryException binafe) {
// success // success
} }

View File

@ -85,9 +85,11 @@ public class SerializableBeanFactoryMemoryLeakTests {
ctx.refresh(); ctx.refresh();
assertThat(serializableFactoryCount(), equalTo(1)); assertThat(serializableFactoryCount(), equalTo(1));
ctx.close(); ctx.close();
} catch (BeanCreationException ex) { }
catch (BeanCreationException ex) {
// ignore - this is expected on refresh() for failure case tests // ignore - this is expected on refresh() for failure case tests
} finally { }
finally {
assertThat(serializableFactoryCount(), equalTo(0)); assertThat(serializableFactoryCount(), equalTo(0));
} }
} }

View File

@ -196,7 +196,8 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests {
// now start the connector // now start the connector
try { try {
connector.start(); connector.start();
} catch (BindException ex) { }
catch (BindException ex) {
System.out.println("Skipping remainder of JMX LazyConnectionToRemote test because binding to local port [" System.out.println("Skipping remainder of JMX LazyConnectionToRemote test because binding to local port ["
+ port + "] failed: " + ex.getMessage()); + port + "] failed: " + ex.getMessage());
return; return;
@ -206,13 +207,15 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests {
try { try {
assertEquals("Rob Harrop", bean.getName()); assertEquals("Rob Harrop", bean.getName());
assertEquals(100, bean.getAge()); assertEquals(100, bean.getAge());
} finally { }
finally {
connector.stop(); connector.stop();
} }
try { try {
bean.getName(); bean.getName();
} catch (JmxException ex) { }
catch (JmxException ex) {
// expected // expected
} }
@ -223,7 +226,8 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests {
try { try {
assertEquals("Rob Harrop", bean.getName()); assertEquals("Rob Harrop", bean.getName());
assertEquals(100, bean.getAge()); assertEquals(100, bean.getAge());
} finally { }
finally {
connector.stop(); connector.stop();
} }
} }

View File

@ -63,7 +63,8 @@ public class RemoteMBeanClientInterceptorTests extends MBeanClientInterceptorTes
this.connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(getServiceUrl(), null, getServer()); this.connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(getServiceUrl(), null, getServer());
try { try {
this.connectorServer.start(); this.connectorServer.start();
} catch (BindException ex) { }
catch (BindException ex) {
System.out.println("Skipping remote JMX tests because binding to local port [" System.out.println("Skipping remote JMX tests because binding to local port ["
+ SERVICE_PORT + "] failed: " + ex.getMessage()); + SERVICE_PORT + "] failed: " + ex.getMessage());
runTests = false; runTests = false;

View File

@ -172,7 +172,8 @@ public class NotificationListenerTests extends AbstractMBeanServerTests {
if (notification instanceof AttributeChangeNotification) { if (notification instanceof AttributeChangeNotification) {
AttributeChangeNotification changeNotification = (AttributeChangeNotification) notification; AttributeChangeNotification changeNotification = (AttributeChangeNotification) notification;
return "Name".equals(changeNotification.getAttributeName()); return "Name".equals(changeNotification.getAttributeName());
} else { }
else {
return false; return false;
} }
} }
@ -200,7 +201,8 @@ public class NotificationListenerTests extends AbstractMBeanServerTests {
try { try {
new NotificationListenerBean().afterPropertiesSet(); new NotificationListenerBean().afterPropertiesSet();
fail("Must have thrown an IllegalArgumentException (no NotificationListener supplied)"); fail("Must have thrown an IllegalArgumentException (no NotificationListener supplied)");
} catch (IllegalArgumentException expected) { }
catch (IllegalArgumentException expected) {
} }
} }
@ -463,7 +465,8 @@ public class NotificationListenerTests extends AbstractMBeanServerTests {
if (currentCount != null) { if (currentCount != null) {
int count = currentCount.intValue() + 1; int count = currentCount.intValue() + 1;
this.attributeCounts.put(attributeName, new Integer(count)); this.attributeCounts.put(attributeName, new Integer(count));
} else { }
else {
this.attributeCounts.put(attributeName, new Integer(1)); this.attributeCounts.put(attributeName, new Integer(1));
} }

View File

@ -67,7 +67,8 @@ public class ConnectorServerFactoryBeanTests extends AbstractMBeanServerTests {
try { try {
checkServerConnection(getServer()); checkServerConnection(getServer());
} finally { }
finally {
bean.destroy(); bean.destroy();
} }
} }
@ -84,7 +85,8 @@ public class ConnectorServerFactoryBeanTests extends AbstractMBeanServerTests {
try { try {
checkServerConnection(getServer()); checkServerConnection(getServer());
} finally { }
finally {
bean.destroy(); bean.destroy();
} }
} }
@ -102,7 +104,8 @@ public class ConnectorServerFactoryBeanTests extends AbstractMBeanServerTests {
// Try to get the connector bean. // Try to get the connector bean.
ObjectInstance instance = getServer().getObjectInstance(ObjectName.getInstance(OBJECT_NAME)); ObjectInstance instance = getServer().getObjectInstance(ObjectName.getInstance(OBJECT_NAME));
assertNotNull("ObjectInstance should not be null", instance); assertNotNull("ObjectInstance should not be null", instance);
} finally { }
finally {
bean.destroy(); bean.destroy();
} }
} }
@ -116,9 +119,11 @@ public class ConnectorServerFactoryBeanTests extends AbstractMBeanServerTests {
// Try to get the connector bean. // Try to get the connector bean.
getServer().getObjectInstance(ObjectName.getInstance(OBJECT_NAME)); getServer().getObjectInstance(ObjectName.getInstance(OBJECT_NAME));
fail("Instance should not be found"); fail("Instance should not be found");
} catch (InstanceNotFoundException ex) { }
catch (InstanceNotFoundException ex) {
// expected // expected
} finally { }
finally {
bean.destroy(); bean.destroy();
} }
} }

View File

@ -74,10 +74,12 @@ public class MBeanServerConnectionFactoryBeanTests extends AbstractMBeanServerTe
// perform simple MBean count test // perform simple MBean count test
assertEquals("MBean count should be the same", getServer().getMBeanCount(), connection.getMBeanCount()); assertEquals("MBean count should be the same", getServer().getMBeanCount(), connection.getMBeanCount());
} finally { }
finally {
bean.destroy(); bean.destroy();
} }
} finally { }
finally {
connectorServer.stop(); connectorServer.stop();
} }
} }
@ -104,7 +106,8 @@ public class MBeanServerConnectionFactoryBeanTests extends AbstractMBeanServerTe
connector = getConnectorServer(); connector = getConnectorServer();
connector.start(); connector.start();
assertEquals("Incorrect MBean count", getServer().getMBeanCount(), connection.getMBeanCount()); assertEquals("Incorrect MBean count", getServer().getMBeanCount(), connection.getMBeanCount());
} finally { }
finally {
bean.destroy(); bean.destroy();
if (connector != null) { if (connector != null) {
connector.stop(); connector.stop();

View File

@ -30,7 +30,6 @@ import java.rmi.UnknownHostException;
import java.rmi.UnmarshalException; import java.rmi.UnmarshalException;
import org.aopalliance.intercept.MethodInvocation; import org.aopalliance.intercept.MethodInvocation;
import org.junit.Test; import org.junit.Test;
import org.springframework.remoting.RemoteAccessException; import org.springframework.remoting.RemoteAccessException;
@ -342,7 +341,7 @@ public class RmiSupportTests {
client.afterPropertiesSet(); client.afterPropertiesSet();
fail("url isn't set, expected IllegalArgumentException"); fail("url isn't set, expected IllegalArgumentException");
} }
catch(IllegalArgumentException e){ catch (IllegalArgumentException ex){
// expected // expected
} }
} }

View File

@ -41,15 +41,19 @@ public class LazyScheduledTasksBeanDefinitionParserTests {
while (!task.executed) { while (!task.executed) {
try { try {
Thread.sleep(10); Thread.sleep(10);
} catch (Exception e) { /* Do Nothing */ } }
catch (Exception ex) { /* Do Nothing */ }
} }
} }
static class Task { static class Task {
volatile boolean executed = false; volatile boolean executed = false;
public void doWork() { public void doWork() {
executed = true; executed = true;
} }
} }
} }

View File

@ -58,7 +58,8 @@ public final class AdvisedJRubyScriptFactoryTests {
assertEquals(0, advice.getCalls()); assertEquals(0, advice.getCalls());
bean.getMessage(); bean.getMessage();
assertEquals(1, advice.getCalls()); assertEquals(1, advice.getCalls());
} finally { }
finally {
ctx.close(); ctx.close();
} }
} }
@ -76,7 +77,8 @@ public final class AdvisedJRubyScriptFactoryTests {
assertEquals(0, advice.getCalls()); assertEquals(0, advice.getCalls());
bean.getMessage(); bean.getMessage();
assertEquals(1, advice.getCalls()); assertEquals(1, advice.getCalls());
} finally { }
finally {
ctx.close(); ctx.close();
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2015 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -127,7 +127,7 @@ public abstract class DigestUtils {
((UpdateMessageDigestInputStream) inputStream).updateMessageDigest(messageDigest); ((UpdateMessageDigestInputStream) inputStream).updateMessageDigest(messageDigest);
return messageDigest.digest(); return messageDigest.digest();
} }
else{ else {
return messageDigest.digest(StreamUtils.copyToByteArray(inputStream)); return messageDigest.digest(StreamUtils.copyToByteArray(inputStream));
} }
} }

View File

@ -198,7 +198,7 @@ public class MimeType implements Comparable<MimeType>, Serializable {
* @see <a href="http://tools.ietf.org/html/rfc2616#section-2.2">HTTP 1.1, section 2.2</a> * @see <a href="http://tools.ietf.org/html/rfc2616#section-2.2">HTTP 1.1, section 2.2</a>
*/ */
private void checkToken(String token) { private void checkToken(String token) {
for (int i=0; i < token.length(); i++ ) { for (int i = 0; i < token.length(); i++ ) {
char ch = token.charAt(i); char ch = token.charAt(i);
if (!TOKEN.get(ch)) { if (!TOKEN.get(ch)) {
throw new IllegalArgumentException("Invalid token character '" + ch + "' in token \"" + token + "\""); throw new IllegalArgumentException("Invalid token character '" + ch + "' in token \"" + token + "\"");

View File

@ -130,7 +130,7 @@ public class GenericTypeResolverTests {
Type t = null; Type t = null;
Type x = null; Type x = null;
for (Map.Entry<TypeVariable, Type> entry : map.entrySet()) { for (Map.Entry<TypeVariable, Type> entry : map.entrySet()) {
if(entry.getKey().toString().equals("T")) { if (entry.getKey().toString().equals("T")) {
t = entry.getValue(); t = entry.getValue();
} }
else { else {

View File

@ -111,7 +111,8 @@ public class PropertySourceTests {
equalTo(String.format("%s [name='%s']", equalTo(String.format("%s [name='%s']",
ps.getClass().getSimpleName(), ps.getClass().getSimpleName(),
name))); name)));
} finally { }
finally {
logger.setLevel(original); logger.setLevel(original);
} }
} }

View File

@ -35,7 +35,8 @@ public class ClassMetadataReadingVisitorMemberClassTests
MetadataReader reader = MetadataReader reader =
new SimpleMetadataReaderFactory().getMetadataReader(clazz.getName()); new SimpleMetadataReaderFactory().getMetadataReader(clazz.getName());
return reader.getAnnotationMetadata(); return reader.getAnnotationMetadata();
} catch (IOException ex) { }
catch (IOException ex) {
throw new IllegalStateException(ex); throw new IllegalStateException(ex);
} }
} }

View File

@ -51,7 +51,7 @@ public class Matchers {
@Override @Override
public boolean matches(Object item) { public boolean matches(Object item) {
Throwable cause = null; Throwable cause = null;
if(item != null && item instanceof Throwable) { if (item != null && item instanceof Throwable) {
cause = ((Throwable)item).getCause(); cause = ((Throwable)item).getCause();
} }
return matcher.matches(cause); return matcher.matches(cause);

View File

@ -93,7 +93,8 @@ public enum TestGroup {
for (String group : value.split(",")) { for (String group : value.split(",")) {
try { try {
groups.add(valueOf(group.trim().toUpperCase())); groups.add(valueOf(group.trim().toUpperCase()));
} catch (IllegalArgumentException e) { }
catch (IllegalArgumentException ex) {
throw new IllegalArgumentException(format( throw new IllegalArgumentException(format(
"Unable to find test group '%s' when parsing testGroups value: '%s'. " + "Unable to find test group '%s' when parsing testGroups value: '%s'. " +
"Available groups include: [%s]", group.trim(), value, "Available groups include: [%s]", group.trim(), value,

View File

@ -74,9 +74,9 @@ public class AutoPopulatingListTests {
private void doTestWithElementFactory(AutoPopulatingList<Object> list) { private void doTestWithElementFactory(AutoPopulatingList<Object> list) {
doTestWithClass(list); doTestWithClass(list);
for(int x = 0; x < list.size(); x++) { for (int x = 0; x < list.size(); x++) {
Object element = list.get(x); Object element = list.get(x);
if(element instanceof TestObject) { if (element instanceof TestObject) {
assertEquals(x, ((TestObject) element).getAge()); assertEquals(x, ((TestObject) element).getAge());
} }
} }

View File

@ -179,7 +179,7 @@ public class FastByteArrayOutputStreamTests {
public void updateMessageDigestManyBuffers() throws Exception { public void updateMessageDigestManyBuffers() throws Exception {
StringBuilder builder = new StringBuilder("\"0"); StringBuilder builder = new StringBuilder("\"0");
// filling at least one 256 buffer // filling at least one 256 buffer
for( int i=0; i < 30; i++) { for ( int i = 0; i < 30; i++) {
this.os.write(helloBytes); this.os.write(helloBytes);
} }
InputStream inputStream = this.os.getInputStream(); InputStream inputStream = this.os.getInputStream();

View File

@ -54,7 +54,7 @@ public class ResizableByteArrayOutputStreamTests {
@Test @Test
public void autoGrow() { public void autoGrow() {
assertEquals(INITIAL_CAPACITY, this.baos.capacity()); assertEquals(INITIAL_CAPACITY, this.baos.capacity());
for(int i = 0; i < 129; i++) { for (int i = 0; i < 129; i++) {
this.baos.write(0); this.baos.write(0);
} }
assertEquals(256, this.baos.capacity()); assertEquals(256, this.baos.capacity());

View File

@ -169,7 +169,8 @@ public class SettableListenableFutureTests {
try { try {
Thread.sleep(20L); Thread.sleep(20L);
settableListenableFuture.set(string); settableListenableFuture.set(string);
} catch (InterruptedException ex) { }
catch (InterruptedException ex) {
throw new RuntimeException(ex); throw new RuntimeException(ex);
} }
} }
@ -183,7 +184,8 @@ public class SettableListenableFutureTests {
try { try {
settableListenableFuture.get(1L, TimeUnit.MILLISECONDS); settableListenableFuture.get(1L, TimeUnit.MILLISECONDS);
fail("Expected TimeoutException"); fail("Expected TimeoutException");
} catch (TimeoutException ex) { }
catch (TimeoutException ex) {
// expected // expected
} }
} }
@ -197,7 +199,8 @@ public class SettableListenableFutureTests {
try { try {
Thread.sleep(20L); Thread.sleep(20L);
settableListenableFuture.set(string); settableListenableFuture.set(string);
} catch (InterruptedException ex) { }
catch (InterruptedException ex) {
throw new RuntimeException(ex); throw new RuntimeException(ex);
} }
} }
@ -278,7 +281,8 @@ public class SettableListenableFutureTests {
try { try {
Thread.sleep(20L); Thread.sleep(20L);
settableListenableFuture.cancel(true); settableListenableFuture.cancel(true);
} catch (InterruptedException ex) { }
catch (InterruptedException ex) {
throw new RuntimeException(ex); throw new RuntimeException(ex);
} }
} }
@ -286,7 +290,8 @@ public class SettableListenableFutureTests {
try { try {
settableListenableFuture.get(100L, TimeUnit.MILLISECONDS); settableListenableFuture.get(100L, TimeUnit.MILLISECONDS);
fail("Expected CancellationException"); fail("Expected CancellationException");
} catch (CancellationException ex) { }
catch (CancellationException ex) {
// expected // expected
} }
} }

View File

@ -194,8 +194,8 @@ public abstract class AbstractStaxXMLReaderTestCase {
private static class SkipLocatorArgumentsAdapter implements InvocationArgumentsAdapter { private static class SkipLocatorArgumentsAdapter implements InvocationArgumentsAdapter {
@Override @Override
public Object[] adaptArguments(Object[] arguments) { public Object[] adaptArguments(Object[] arguments) {
for(int i=0; i<arguments.length; i++) { for (int i = 0; i < arguments.length; i++) {
if(arguments[i] instanceof Locator) { if (arguments[i] instanceof Locator) {
arguments[i] = null; arguments[i] = null;
} }
} }
@ -206,7 +206,7 @@ public abstract class AbstractStaxXMLReaderTestCase {
private static class CharArrayToStringAdapter implements InvocationArgumentsAdapter { private static class CharArrayToStringAdapter implements InvocationArgumentsAdapter {
@Override @Override
public Object[] adaptArguments(Object[] arguments) { public Object[] adaptArguments(Object[] arguments) {
if(arguments.length == 3 && arguments[0] instanceof char[] if (arguments.length == 3 && arguments[0] instanceof char[]
&& arguments[1] instanceof Integer && arguments[2] instanceof Integer) { && arguments[1] instanceof Integer && arguments[2] instanceof Integer) {
return new Object[] {new String((char[]) arguments[0], (Integer) arguments[1], (Integer) arguments[2])}; return new Object[] {new String((char[]) arguments[0], (Integer) arguments[1], (Integer) arguments[2])};
} }
@ -218,7 +218,7 @@ public abstract class AbstractStaxXMLReaderTestCase {
@Override @Override
public Object[] adaptArguments(Object[] arguments) { public Object[] adaptArguments(Object[] arguments) {
for (int i = 0; i < arguments.length; i++) { for (int i = 0; i < arguments.length; i++) {
if(arguments[i] instanceof Attributes) { if (arguments[i] instanceof Attributes) {
arguments[i] = new PartialAttributes((Attributes) arguments[i]); arguments[i] = new PartialAttributes((Attributes) arguments[i]);
} }
}; };

View File

@ -918,7 +918,7 @@ public class CodeFlow implements Opcodes {
*/ */
public static boolean isReferenceTypeArray(String arraytype) { public static boolean isReferenceTypeArray(String arraytype) {
int length = arraytype.length(); int length = arraytype.length();
for (int i=0;i<length;i++) { for (int i = 0; i < length; i++) {
char ch = arraytype.charAt(i); char ch = arraytype.charAt(i);
if (ch == '[') continue; if (ch == '[') continue;
return ch=='L'; return ch=='L';

View File

@ -71,7 +71,8 @@ public class EvaluationTests extends AbstractExpressionTests {
try { try {
o = parser.parseExpression("list2[3]").getValue(new StandardEvaluationContext(testClass)); o = parser.parseExpression("list2[3]").getValue(new StandardEvaluationContext(testClass));
fail(); fail();
} catch (EvaluationException ee) { }
catch (EvaluationException ee) {
ee.printStackTrace(); ee.printStackTrace();
// success! // success!
} }
@ -241,7 +242,8 @@ public class EvaluationTests extends AbstractExpressionTests {
try { try {
new SpelExpressionParser().parseExpression("placeOfBirth.foo."); new SpelExpressionParser().parseExpression("placeOfBirth.foo.");
fail("Should have failed to parse"); fail("Should have failed to parse");
} catch (ParseException e) { }
catch (ParseException e) {
assertTrue(e instanceof SpelParseException); assertTrue(e instanceof SpelParseException);
SpelParseException spe = (SpelParseException) e; SpelParseException spe = (SpelParseException) e;
assertEquals(SpelMessage.OOD, spe.getMessageCode()); assertEquals(SpelMessage.OOD, spe.getMessageCode());
@ -265,7 +267,8 @@ public class EvaluationTests extends AbstractExpressionTests {
try { try {
new SpelExpressionParser().parseRaw("placeOfBirth.23"); new SpelExpressionParser().parseRaw("placeOfBirth.23");
fail(); fail();
} catch (SpelParseException spe) { }
catch (SpelParseException spe) {
assertEquals(spe.getMessageCode(), SpelMessage.UNEXPECTED_DATA_AFTER_DOT); assertEquals(spe.getMessageCode(), SpelMessage.UNEXPECTED_DATA_AFTER_DOT);
assertEquals("23", spe.getInserts()[0]); assertEquals("23", spe.getInserts()[0]);
} }
@ -554,7 +557,8 @@ public class EvaluationTests extends AbstractExpressionTests {
try { try {
assertFalse(parser.parseExpression("T(List)!=null").getValue(context, Boolean.class)); assertFalse(parser.parseExpression("T(List)!=null").getValue(context, Boolean.class));
fail("should have failed to find List"); fail("should have failed to find List");
} catch (EvaluationException ee) { }
catch (EvaluationException ee) {
// success - List not found // success - List not found
} }
((StandardTypeLocator) context.getTypeLocator()).registerImport("java.util"); ((StandardTypeLocator) context.getTypeLocator()).registerImport("java.util");
@ -633,7 +637,8 @@ public class EvaluationTests extends AbstractExpressionTests {
try { try {
context.registerMethodFilter(String.class, filter); context.registerMethodFilter(String.class, filter);
fail("should have failed"); fail("should have failed");
} catch (IllegalStateException ise) { }
catch (IllegalStateException ise) {
assertEquals( assertEquals(
"Method filter cannot be set as the reflective method resolver is not in use", "Method filter cannot be set as the reflective method resolver is not in use",
ise.getMessage()); ise.getMessage());
@ -738,7 +743,8 @@ public class EvaluationTests extends AbstractExpressionTests {
try { try {
e.getValue(ctx,String.class); e.getValue(ctx,String.class);
fail(); fail();
} catch (SpelEvaluationException see) { }
catch (SpelEvaluationException see) {
assertEquals(SpelMessage.COLLECTION_INDEX_OUT_OF_BOUNDS,see.getMessageCode()); assertEquals(SpelMessage.COLLECTION_INDEX_OUT_OF_BOUNDS,see.getMessageCode());
} }
} }
@ -754,7 +760,8 @@ public class EvaluationTests extends AbstractExpressionTests {
expression = parser.parseExpression("foo[3]"); expression = parser.parseExpression("foo[3]");
try { try {
expression.setValue(ctx, "3"); expression.setValue(ctx, "3");
} catch(SpelEvaluationException see) { }
catch (SpelEvaluationException see) {
assertEquals(SpelMessage.UNABLE_TO_GROW_COLLECTION, see.getMessageCode()); assertEquals(SpelMessage.UNABLE_TO_GROW_COLLECTION, see.getMessageCode());
assertThat(instance.getFoo().size(), equalTo(3)); assertThat(instance.getFoo().size(), equalTo(3));
} }
@ -771,7 +778,8 @@ public class EvaluationTests extends AbstractExpressionTests {
try { try {
e.getValue(ctx,Integer.class); e.getValue(ctx,Integer.class);
fail(); fail();
} catch (SpelEvaluationException see) { }
catch (SpelEvaluationException see) {
assertEquals(SpelMessage.NOT_ASSIGNABLE,see.getMessageCode()); assertEquals(SpelMessage.NOT_ASSIGNABLE,see.getMessageCode());
} }
} }
@ -894,7 +902,8 @@ public class EvaluationTests extends AbstractExpressionTests {
try { try {
e.getValue(ctx,Double.TYPE); e.getValue(ctx,Double.TYPE);
fail(); fail();
} catch (SpelEvaluationException see) { }
catch (SpelEvaluationException see) {
assertEquals(SpelMessage.OPERAND_NOT_INCREMENTABLE,see.getMessageCode()); assertEquals(SpelMessage.OPERAND_NOT_INCREMENTABLE,see.getMessageCode());
} }
@ -902,7 +911,8 @@ public class EvaluationTests extends AbstractExpressionTests {
try { try {
e.getValue(ctx,Double.TYPE); e.getValue(ctx,Double.TYPE);
fail(); fail();
} catch (SpelEvaluationException see) { }
catch (SpelEvaluationException see) {
assertEquals(SpelMessage.OPERAND_NOT_INCREMENTABLE,see.getMessageCode()); assertEquals(SpelMessage.OPERAND_NOT_INCREMENTABLE,see.getMessageCode());
} }
} }
@ -917,14 +927,16 @@ public class EvaluationTests extends AbstractExpressionTests {
Expression e = parser.parseExpression("++1"); Expression e = parser.parseExpression("++1");
e.getValue(ctx,Integer.class); e.getValue(ctx,Integer.class);
fail(); fail();
} catch (SpelEvaluationException see) { }
catch (SpelEvaluationException see) {
assertEquals(SpelMessage.NOT_ASSIGNABLE,see.getMessageCode()); assertEquals(SpelMessage.NOT_ASSIGNABLE,see.getMessageCode());
} }
try { try {
Expression e = parser.parseExpression("1++"); Expression e = parser.parseExpression("1++");
e.getValue(ctx,Integer.class); e.getValue(ctx,Integer.class);
fail(); fail();
} catch (SpelEvaluationException see) { }
catch (SpelEvaluationException see) {
assertEquals(SpelMessage.NOT_ASSIGNABLE,see.getMessageCode()); assertEquals(SpelMessage.NOT_ASSIGNABLE,see.getMessageCode());
} }
} }
@ -938,7 +950,8 @@ public class EvaluationTests extends AbstractExpressionTests {
try { try {
e.getValue(ctx,Integer.class); e.getValue(ctx,Integer.class);
fail(); fail();
} catch (SpelEvaluationException see) { }
catch (SpelEvaluationException see) {
assertEquals(SpelMessage.NOT_ASSIGNABLE,see.getMessageCode()); assertEquals(SpelMessage.NOT_ASSIGNABLE,see.getMessageCode());
} }
} }
@ -1060,7 +1073,8 @@ public class EvaluationTests extends AbstractExpressionTests {
try { try {
e.getValue(ctx,Double.TYPE); e.getValue(ctx,Double.TYPE);
fail(); fail();
} catch (SpelEvaluationException see) { }
catch (SpelEvaluationException see) {
assertEquals(SpelMessage.OPERAND_NOT_DECREMENTABLE,see.getMessageCode()); assertEquals(SpelMessage.OPERAND_NOT_DECREMENTABLE,see.getMessageCode());
} }
@ -1068,7 +1082,8 @@ public class EvaluationTests extends AbstractExpressionTests {
try { try {
e.getValue(ctx,Double.TYPE); e.getValue(ctx,Double.TYPE);
fail(); fail();
} catch (SpelEvaluationException see) { }
catch (SpelEvaluationException see) {
assertEquals(SpelMessage.OPERAND_NOT_DECREMENTABLE,see.getMessageCode()); assertEquals(SpelMessage.OPERAND_NOT_DECREMENTABLE,see.getMessageCode());
} }
} }
@ -1083,14 +1098,16 @@ public class EvaluationTests extends AbstractExpressionTests {
Expression e = parser.parseExpression("--1"); Expression e = parser.parseExpression("--1");
e.getValue(ctx,Integer.class); e.getValue(ctx,Integer.class);
fail(); fail();
} catch (SpelEvaluationException see) { }
catch (SpelEvaluationException see) {
assertEquals(SpelMessage.NOT_ASSIGNABLE,see.getMessageCode()); assertEquals(SpelMessage.NOT_ASSIGNABLE,see.getMessageCode());
} }
try { try {
Expression e = parser.parseExpression("1--"); Expression e = parser.parseExpression("1--");
e.getValue(ctx,Integer.class); e.getValue(ctx,Integer.class);
fail(); fail();
} catch (SpelEvaluationException see) { }
catch (SpelEvaluationException see) {
assertEquals(SpelMessage.NOT_ASSIGNABLE,see.getMessageCode()); assertEquals(SpelMessage.NOT_ASSIGNABLE,see.getMessageCode());
} }
} }
@ -1123,36 +1140,6 @@ public class EvaluationTests extends AbstractExpressionTests {
} }
private void expectFail(ExpressionParser parser, EvaluationContext eContext, String expressionString, SpelMessage messageCode) {
try {
Expression e = parser.parseExpression(expressionString);
SpelUtilities.printAbstractSyntaxTree(System.out, e);
e.getValue(eContext);
fail();
} catch (SpelEvaluationException see) {
see.printStackTrace();
assertEquals(messageCode,see.getMessageCode());
}
}
private void expectFailNotAssignable(ExpressionParser parser, EvaluationContext eContext, String expressionString) {
expectFail(parser,eContext,expressionString,SpelMessage.NOT_ASSIGNABLE);
}
private void expectFailSetValueNotSupported(ExpressionParser parser, EvaluationContext eContext, String expressionString) {
expectFail(parser,eContext,expressionString,SpelMessage.SETVALUE_NOT_SUPPORTED);
}
private void expectFailNotIncrementable(ExpressionParser parser, EvaluationContext eContext, String expressionString) {
expectFail(parser,eContext,expressionString,SpelMessage.OPERAND_NOT_INCREMENTABLE);
}
private void expectFailNotDecrementable(ExpressionParser parser, EvaluationContext eContext, String expressionString) {
expectFail(parser,eContext,expressionString,SpelMessage.OPERAND_NOT_DECREMENTABLE);
}
// Verify how all the nodes behave with assignment (++, --, =) // Verify how all the nodes behave with assignment (++, --, =)
@Test @Test
public void incrementAllNodeTypes() throws SecurityException, NoSuchMethodException { public void incrementAllNodeTypes() throws SecurityException, NoSuchMethodException {
@ -1456,9 +1443,39 @@ public class EvaluationTests extends AbstractExpressionTests {
r = e.getValue(ctx,Integer.TYPE); r = e.getValue(ctx,Integer.TYPE);
assertEquals(100,r); assertEquals(100,r);
assertEquals(100,helper.iii); assertEquals(100,helper.iii);
} }
private void expectFail(ExpressionParser parser, EvaluationContext eContext, String expressionString, SpelMessage messageCode) {
try {
Expression e = parser.parseExpression(expressionString);
SpelUtilities.printAbstractSyntaxTree(System.out, e);
e.getValue(eContext);
fail();
}
catch (SpelEvaluationException see) {
see.printStackTrace();
assertEquals(messageCode,see.getMessageCode());
}
}
private void expectFailNotAssignable(ExpressionParser parser, EvaluationContext eContext, String expressionString) {
expectFail(parser,eContext,expressionString,SpelMessage.NOT_ASSIGNABLE);
}
private void expectFailSetValueNotSupported(ExpressionParser parser, EvaluationContext eContext, String expressionString) {
expectFail(parser,eContext,expressionString,SpelMessage.SETVALUE_NOT_SUPPORTED);
}
private void expectFailNotIncrementable(ExpressionParser parser, EvaluationContext eContext, String expressionString) {
expectFail(parser,eContext,expressionString,SpelMessage.OPERAND_NOT_INCREMENTABLE);
}
private void expectFailNotDecrementable(ExpressionParser parser, EvaluationContext eContext, String expressionString) {
expectFail(parser,eContext,expressionString,SpelMessage.OPERAND_NOT_DECREMENTABLE);
}
static class MyBeanResolver implements BeanResolver { static class MyBeanResolver implements BeanResolver {
@Override @Override
@ -1472,5 +1489,4 @@ public class EvaluationTests extends AbstractExpressionTests {
} }
} }

View File

@ -79,10 +79,12 @@ public class ExpressionLanguageScenarioTests extends AbstractExpressionTests {
assertEquals("hello world", value); assertEquals("hello world", value);
assertEquals(String.class, value.getClass()); assertEquals(String.class, value.getClass());
} catch (EvaluationException ee) { }
catch (EvaluationException ee) {
ee.printStackTrace(); ee.printStackTrace();
fail("Unexpected Exception: " + ee.getMessage()); fail("Unexpected Exception: " + ee.getMessage());
} catch (ParseException pe) { }
catch (ParseException pe) {
pe.printStackTrace(); pe.printStackTrace();
fail("Unexpected Exception: " + pe.getMessage()); fail("Unexpected Exception: " + pe.getMessage());
} }
@ -186,10 +188,12 @@ public class ExpressionLanguageScenarioTests extends AbstractExpressionTests {
Object value = expr.getValue(ctx); Object value = expr.getValue(ctx);
assertEquals("hellohello", value); assertEquals("hellohello", value);
} catch (EvaluationException ee) { }
catch (EvaluationException ee) {
ee.printStackTrace(); ee.printStackTrace();
fail("Unexpected Exception: " + ee.getMessage()); fail("Unexpected Exception: " + ee.getMessage());
} catch (ParseException pe) { }
catch (ParseException pe) {
pe.printStackTrace(); pe.printStackTrace();
fail("Unexpected Exception: " + pe.getMessage()); fail("Unexpected Exception: " + pe.getMessage());
} }
@ -213,7 +217,8 @@ public class ExpressionLanguageScenarioTests extends AbstractExpressionTests {
try { try {
expr.setValue(ctx, Color.blue); expr.setValue(ctx, Color.blue);
fail("Should not be allowed to set oranges to be blue !"); fail("Should not be allowed to set oranges to be blue !");
} catch (SpelEvaluationException ee) { }
catch (SpelEvaluationException ee) {
assertEquals(ee.getMessageCode(), SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL); assertEquals(ee.getMessageCode(), SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL);
} }
} }

View File

@ -140,7 +140,8 @@ public class ExpressionStateTests extends AbstractExpressionTests {
try { try {
state.popActiveContextObject(); state.popActiveContextObject();
fail("stack should be empty..."); fail("stack should be empty...");
} catch (EmptyStackException ese) { }
catch (EmptyStackException ese) {
// success // success
} }
@ -221,7 +222,8 @@ public class ExpressionStateTests extends AbstractExpressionTests {
try { try {
state.operate(Operation.ADD,1,2); state.operate(Operation.ADD,1,2);
fail("should have failed"); fail("should have failed");
} catch (EvaluationException ee) { }
catch (EvaluationException ee) {
SpelEvaluationException sEx = (SpelEvaluationException)ee; SpelEvaluationException sEx = (SpelEvaluationException)ee;
assertEquals(SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES,sEx.getMessageCode()); assertEquals(SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES,sEx.getMessageCode());
} }
@ -229,7 +231,8 @@ public class ExpressionStateTests extends AbstractExpressionTests {
try { try {
state.operate(Operation.ADD,null,null); state.operate(Operation.ADD,null,null);
fail("should have failed"); fail("should have failed");
} catch (EvaluationException ee) { }
catch (EvaluationException ee) {
SpelEvaluationException sEx = (SpelEvaluationException)ee; SpelEvaluationException sEx = (SpelEvaluationException)ee;
assertEquals(SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES,sEx.getMessageCode()); assertEquals(SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES,sEx.getMessageCode());
} }
@ -249,7 +252,8 @@ public class ExpressionStateTests extends AbstractExpressionTests {
try { try {
state.findType("someMadeUpName"); state.findType("someMadeUpName");
fail("Should have failed to find it"); fail("Should have failed to find it");
} catch (EvaluationException ee) { }
catch (EvaluationException ee) {
SpelEvaluationException sEx = (SpelEvaluationException)ee; SpelEvaluationException sEx = (SpelEvaluationException)ee;
assertEquals(SpelMessage.TYPE_NOT_FOUND,sEx.getMessageCode()); assertEquals(SpelMessage.TYPE_NOT_FOUND,sEx.getMessageCode());
} }

View File

@ -191,8 +191,9 @@ public class IndexingTests {
expression = parser.parseExpression("property[0]"); expression = parser.parseExpression("property[0]");
try { try {
expression.setValue(this, "4"); expression.setValue(this, "4");
} catch (EvaluationException e) { }
assertTrue(e.getMessage().startsWith("EL1053E")); catch (EvaluationException ex) {
assertTrue(ex.getMessage().startsWith("EL1053E"));
} }
} }
@ -251,8 +252,9 @@ public class IndexingTests {
expression = parser.parseExpression("property[0]"); expression = parser.parseExpression("property[0]");
try { try {
assertEquals("bar", expression.getValue(this)); assertEquals("bar", expression.getValue(this));
} catch (EvaluationException e) { }
assertTrue(e.getMessage().startsWith("EL1027E")); catch (EvaluationException ex) {
assertTrue(ex.getMessage().startsWith("EL1027E"));
} }
} }
@ -268,8 +270,9 @@ public class IndexingTests {
expression = parser.parseExpression("property[0]"); expression = parser.parseExpression("property[0]");
try { try {
assertEquals("bar", expression.getValue(this)); assertEquals("bar", expression.getValue(this));
} catch (EvaluationException e) { }
assertTrue(e.getMessage().startsWith("EL1053E")); catch (EvaluationException ex) {
assertTrue(ex.getMessage().startsWith("EL1053E"));
} }
} }
@ -285,8 +288,9 @@ public class IndexingTests {
expression = parser.parseExpression("property2[0]"); expression = parser.parseExpression("property2[0]");
try { try {
assertEquals("bar", expression.getValue(this)); assertEquals("bar", expression.getValue(this));
} catch (EvaluationException e) { }
assertTrue(e.getMessage().startsWith("EL1053E")); catch (EvaluationException ex) {
assertTrue(ex.getMessage().startsWith("EL1053E"));
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2012 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -33,29 +33,6 @@ import static org.junit.Assert.*;
*/ */
public class OperatorOverloaderTests extends AbstractExpressionTests { public class OperatorOverloaderTests extends AbstractExpressionTests {
static class StringAndBooleanAddition implements OperatorOverloader {
@Override
public Object operate(Operation operation, Object leftOperand, Object rightOperand) throws EvaluationException {
if (operation==Operation.ADD) {
return ((String)leftOperand)+((Boolean)rightOperand).toString();
} else {
return leftOperand;
}
}
@Override
public boolean overridesOperation(Operation operation, Object leftOperand, Object rightOperand)
throws EvaluationException {
if (leftOperand instanceof String && rightOperand instanceof Boolean) {
return true;
}
return false;
}
}
@Test @Test
public void testSimpleOperations() throws Exception { public void testSimpleOperations() throws Exception {
// no built in support for this: // no built in support for this:
@ -73,4 +50,28 @@ public class OperatorOverloaderTests extends AbstractExpressionTests {
expr = (SpelExpression)parser.parseExpression("'abc'+null"); expr = (SpelExpression)parser.parseExpression("'abc'+null");
assertEquals("abcnull",expr.getValue(eContext)); assertEquals("abcnull",expr.getValue(eContext));
} }
static class StringAndBooleanAddition implements OperatorOverloader {
@Override
public Object operate(Operation operation, Object leftOperand, Object rightOperand) throws EvaluationException {
if (operation==Operation.ADD) {
return ((String)leftOperand)+((Boolean)rightOperand).toString();
}
else {
return leftOperand;
}
}
@Override
public boolean overridesOperation(Operation operation, Object leftOperand, Object rightOperand) throws EvaluationException {
if (leftOperand instanceof String && rightOperand instanceof Boolean) {
return true;
}
return false;
}
}
} }

View File

@ -462,7 +462,8 @@ public class ParsingTests {
fail("Parsed exception was null"); fail("Parsed exception was null");
} }
assertEquals("String form of AST does not match expected output", expectedStringFormOfAST, e.toStringAST()); assertEquals("String form of AST does not match expected output", expectedStringFormOfAST, e.toStringAST());
} catch (ParseException ee) { }
catch (ParseException ee) {
ee.printStackTrace(); ee.printStackTrace();
fail("Unexpected Exception: " + ee.getMessage()); fail("Unexpected Exception: " + ee.getMessage());
} }

View File

@ -78,15 +78,17 @@ public class PropertyAccessTests extends AbstractExpressionTests {
try { try {
expr.getValue(context); expr.getValue(context);
fail("Should have failed - default property resolver cannot resolve on null"); fail("Should have failed - default property resolver cannot resolve on null");
} catch (Exception e) { }
checkException(e,SpelMessage.PROPERTY_OR_FIELD_NOT_READABLE_ON_NULL); catch (Exception ex) {
checkException(ex, SpelMessage.PROPERTY_OR_FIELD_NOT_READABLE_ON_NULL);
} }
assertFalse(expr.isWritable(context)); assertFalse(expr.isWritable(context));
try { try {
expr.setValue(context,"abc"); expr.setValue(context,"abc");
fail("Should have failed - default property resolver cannot resolve on null"); fail("Should have failed - default property resolver cannot resolve on null");
} catch (Exception e) { }
checkException(e,SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL); catch (Exception ex) {
checkException(ex, SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL);
} }
} }
@ -94,7 +96,8 @@ public class PropertyAccessTests extends AbstractExpressionTests {
if (e instanceof SpelEvaluationException) { if (e instanceof SpelEvaluationException) {
SpelMessage sm = ((SpelEvaluationException)e).getMessageCode(); SpelMessage sm = ((SpelEvaluationException)e).getMessageCode();
assertEquals("Expected exception type did not occur",expectedMessage,sm); assertEquals("Expected exception type did not occur",expectedMessage,sm);
} else { }
else {
fail("Should be a SpelException "+e); fail("Should be a SpelException "+e);
} }
} }
@ -127,7 +130,8 @@ public class PropertyAccessTests extends AbstractExpressionTests {
try { try {
expr.setValue(ctx, "not allowed"); expr.setValue(ctx, "not allowed");
fail("Should not have been allowed"); fail("Should not have been allowed");
} catch (EvaluationException e) { }
catch (EvaluationException ex) {
// success - message will be: EL1063E:(pos 20): A problem occurred whilst attempting to set the property // success - message will be: EL1063E:(pos 20): A problem occurred whilst attempting to set the property
// 'flibbles': 'Cannot set flibbles to an object of type 'class java.lang.String'' // 'flibbles': 'Cannot set flibbles to an object of type 'class java.lang.String''
// System.out.println(e.getMessage()); // System.out.println(e.getMessage());
@ -171,38 +175,42 @@ public class PropertyAccessTests extends AbstractExpressionTests {
@Override @Override
public Class<?>[] getSpecificTargetClasses() { public Class<?>[] getSpecificTargetClasses() {
return new Class[] { String.class }; return new Class[] {String.class};
} }
@Override @Override
public boolean canRead(EvaluationContext context, Object target, String name) throws AccessException { public boolean canRead(EvaluationContext context, Object target, String name) throws AccessException {
if (!(target instanceof String)) if (!(target instanceof String)) {
throw new RuntimeException("Assertion Failed! target should be String"); throw new RuntimeException("Assertion Failed! target should be String");
}
return (name.equals("flibbles")); return (name.equals("flibbles"));
} }
@Override @Override
public boolean canWrite(EvaluationContext context, Object target, String name) throws AccessException { public boolean canWrite(EvaluationContext context, Object target, String name) throws AccessException {
if (!(target instanceof String)) if (!(target instanceof String)) {
throw new RuntimeException("Assertion Failed! target should be String"); throw new RuntimeException("Assertion Failed! target should be String");
}
return (name.equals("flibbles")); return (name.equals("flibbles"));
} }
@Override @Override
public TypedValue read(EvaluationContext context, Object target, String name) throws AccessException { public TypedValue read(EvaluationContext context, Object target, String name) throws AccessException {
if (!name.equals("flibbles")) if (!name.equals("flibbles")) {
throw new RuntimeException("Assertion Failed! name should be flibbles"); throw new RuntimeException("Assertion Failed! name should be flibbles");
}
return new TypedValue(flibbles); return new TypedValue(flibbles);
} }
@Override @Override
public void write(EvaluationContext context, Object target, String name, Object newValue) public void write(EvaluationContext context, Object target, String name, Object newValue) throws AccessException {
throws AccessException { if (!name.equals("flibbles")) {
if (!name.equals("flibbles"))
throw new RuntimeException("Assertion Failed! name should be flibbles"); throw new RuntimeException("Assertion Failed! name should be flibbles");
}
try { try {
flibbles = (Integer) context.getTypeConverter().convertValue(newValue, TypeDescriptor.forObject(newValue), TypeDescriptor.valueOf(Integer.class)); flibbles = (Integer) context.getTypeConverter().convertValue(newValue, TypeDescriptor.forObject(newValue), TypeDescriptor.valueOf(Integer.class));
}catch (EvaluationException e) { }
catch (EvaluationException ex) {
throw new AccessException("Cannot set flibbles to an object of type '" + newValue.getClass() + "'"); throw new AccessException("Cannot set flibbles to an object of type '" + newValue.getClass() + "'");
} }
} }

View File

@ -61,7 +61,8 @@ public class ScenariosForSpringSecurity extends AbstractExpressionTests {
value = expr.getValue(ctx,Boolean.class); value = expr.getValue(ctx,Boolean.class);
assertTrue(value); assertTrue(value);
} catch (EvaluationException ee) { }
catch (EvaluationException ee) {
ee.printStackTrace(); ee.printStackTrace();
fail("Unexpected SpelException: " + ee.getMessage()); fail("Unexpected SpelException: " + ee.getMessage());
} }
@ -160,10 +161,10 @@ public class ScenariosForSpringSecurity extends AbstractExpressionTests {
public String[] getRoles() { return new String[]{"NONE"}; } public String[] getRoles() { return new String[]{"NONE"}; }
public boolean hasAnyRole(String... roles) { public boolean hasAnyRole(String... roles) {
if (roles==null) return true; if (roles == null) return true;
String[] myRoles = getRoles(); String[] myRoles = getRoles();
for (int i=0;i<myRoles.length;i++) { for (int i = 0; i < myRoles.length; i++) {
for (int j=0;j<roles.length;j++) { for (int j = 0; j < roles.length; j++) {
if (myRoles[i].equals(roles[j])) return true; if (myRoles[i].equals(roles[j])) return true;
} }
} }

View File

@ -428,7 +428,8 @@ public class SelectionAndProjectionTests {
for (int i = 0; i < 3; i++) { for (int i = 0; i < 3; i++) {
if (i == 1) { if (i == 1) {
array[i] = new IntegerTestBean(5.9f); array[i] = new IntegerTestBean(5.9f);
} else { }
else {
array[i] = new IntegerTestBean(i + 5); array[i] = new IntegerTestBean(i + 5);
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2014 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -39,6 +39,7 @@ public class SetValueTests extends AbstractExpressionTests {
private final static boolean DEBUG = false; private final static boolean DEBUG = false;
@Test @Test
public void testSetProperty() { public void testSetProperty() {
setValue("wonNobelPrize", true); setValue("wonNobelPrize", true);
@ -90,7 +91,8 @@ public class SetValueTests extends AbstractExpressionTests {
try { try {
assertFalse("Should not be writable!",e.isWritable(lContext)); assertFalse("Should not be writable!",e.isWritable(lContext));
fail("Should have had an error because wibble does not really exist"); fail("Should have had an error because wibble does not really exist");
} catch (SpelEvaluationException see) { }
catch (SpelEvaluationException see) {
// org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 15): Property or field 'wibble' cannot be found on object of type 'org.springframework.expression.spel.testresources.ArrayContainer' - maybe not public? // org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 15): Property or field 'wibble' cannot be found on object of type 'org.springframework.expression.spel.testresources.ArrayContainer' - maybe not public?
// at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:225) // at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:225)
// success! // success!
@ -110,7 +112,8 @@ public class SetValueTests extends AbstractExpressionTests {
try { try {
assertFalse("Should not be writable!",e.isWritable(lContext)); assertFalse("Should not be writable!",e.isWritable(lContext));
fail("Should have had an error because wibble does not really exist"); fail("Should have had an error because wibble does not really exist");
} catch (SpelEvaluationException see) { }
catch (SpelEvaluationException see) {
// success! // success!
} }
@ -119,7 +122,8 @@ public class SetValueTests extends AbstractExpressionTests {
try { try {
assertFalse("Should not be writable!",e.isWritable(lContext)); assertFalse("Should not be writable!",e.isWritable(lContext));
fail("Should have had an error because wibble does not really exist"); fail("Should have had an error because wibble does not really exist");
} catch (SpelEvaluationException see) { }
catch (SpelEvaluationException see) {
// success! // success!
} }
} }
@ -247,10 +251,12 @@ public class SetValueTests extends AbstractExpressionTests {
StandardEvaluationContext lContext = TestScenarioCreator.getTestEvaluationContext(); StandardEvaluationContext lContext = TestScenarioCreator.getTestEvaluationContext();
e.setValue(lContext, value); e.setValue(lContext, value);
fail("expected an error"); fail("expected an error");
} catch (ParseException pe) { }
catch (ParseException pe) {
pe.printStackTrace(); pe.printStackTrace();
fail("Unexpected Exception: " + pe.getMessage()); fail("Unexpected Exception: " + pe.getMessage());
} catch (EvaluationException ee) { }
catch (EvaluationException ee) {
// success! // success!
} }
} }
@ -268,10 +274,12 @@ public class SetValueTests extends AbstractExpressionTests {
assertTrue("Expression is not writeable but should be", e.isWritable(lContext)); assertTrue("Expression is not writeable but should be", e.isWritable(lContext));
e.setValue(lContext, value); e.setValue(lContext, value);
assertEquals("Retrieved value was not equal to set value", value, e.getValue(lContext,value.getClass())); assertEquals("Retrieved value was not equal to set value", value, e.getValue(lContext,value.getClass()));
} catch (EvaluationException ee) { }
catch (EvaluationException ee) {
ee.printStackTrace(); ee.printStackTrace();
fail("Unexpected Exception: " + ee.getMessage()); fail("Unexpected Exception: " + ee.getMessage());
} catch (ParseException pe) { }
catch (ParseException pe) {
pe.printStackTrace(); pe.printStackTrace();
fail("Unexpected Exception: " + pe.getMessage()); fail("Unexpected Exception: " + pe.getMessage());
} }
@ -299,12 +307,15 @@ public class SetValueTests extends AbstractExpressionTests {
fail("Not the same: ["+a+"] type="+a.getClass()+" ["+b+"] type="+b.getClass()); fail("Not the same: ["+a+"] type="+a.getClass()+" ["+b+"] type="+b.getClass());
// assertEquals("Retrieved value was not equal to set value", expectedValue, e.getValue(lContext)); // assertEquals("Retrieved value was not equal to set value", expectedValue, e.getValue(lContext));
} }
} catch (EvaluationException ee) { }
catch (EvaluationException ee) {
ee.printStackTrace(); ee.printStackTrace();
fail("Unexpected Exception: " + ee.getMessage()); fail("Unexpected Exception: " + ee.getMessage());
} catch (ParseException pe) { }
catch (ParseException pe) {
pe.printStackTrace(); pe.printStackTrace();
fail("Unexpected Exception: " + pe.getMessage()); fail("Unexpected Exception: " + pe.getMessage());
} }
} }
} }

View File

@ -4267,7 +4267,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
// // time it interpreted // // time it interpreted
// long stime = System.currentTimeMillis(); // long stime = System.currentTimeMillis();
// for (int i=0;i<100000;i++) { // for (int i = 0;i<100000;i++) {
// v = expression.getValue(ctx,holder); // v = expression.getValue(ctx,holder);
// } // }
// System.out.println((System.currentTimeMillis()-stime)); // System.out.println((System.currentTimeMillis()-stime));
@ -4278,7 +4278,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
// //
// // time it compiled // // time it compiled
// stime = System.currentTimeMillis(); // stime = System.currentTimeMillis();
// for (int i=0;i<100000;i++) { // for (int i = 0;i<100000;i++) {
// v = expression.getValue(ctx,holder); // v = expression.getValue(ctx,holder);
// } // }
// System.out.println((System.currentTimeMillis()-stime)); // System.out.println((System.currentTimeMillis()-stime));
@ -5014,7 +5014,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
public void reset() { public void reset() {
i = 0; i = 0;
_i=0; _i = 0;
s = null; s = null;
_s = null; _s = null;
field = null; field = null;

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2015 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -79,80 +79,80 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests {
assertEquals(2d,o); assertEquals(2d,o);
System.out.println("Performance check for SpEL expression: '(T(Integer).valueOf(payload).doubleValue())/18D'"); System.out.println("Performance check for SpEL expression: '(T(Integer).valueOf(payload).doubleValue())/18D'");
long stime = System.currentTimeMillis(); long stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(nh); o = expression.getValue(nh);
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(nh); o = expression.getValue(nh);
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(nh); o = expression.getValue(nh);
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
compile(expression); compile(expression);
System.out.println("Now compiled:"); System.out.println("Now compiled:");
o = expression.getValue(nh); o = expression.getValue(nh);
assertEquals(2d, o); assertEquals(2d, o);
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(nh); o = expression.getValue(nh);
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(nh); o = expression.getValue(nh);
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(nh); o = expression.getValue(nh);
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
expression = parser.parseExpression("payload/18D"); expression = parser.parseExpression("payload/18D");
o = expression.getValue(nh); o = expression.getValue(nh);
assertEquals(2d,o); assertEquals(2d,o);
System.out.println("Performance check for SpEL expression: 'payload/18D'"); System.out.println("Performance check for SpEL expression: 'payload/18D'");
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(nh); o = expression.getValue(nh);
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(nh); o = expression.getValue(nh);
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(nh); o = expression.getValue(nh);
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
compile(expression); compile(expression);
System.out.println("Now compiled:"); System.out.println("Now compiled:");
o = expression.getValue(nh); o = expression.getValue(nh);
assertEquals(2d, o); assertEquals(2d, o);
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(nh); o = expression.getValue(nh);
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(nh); o = expression.getValue(nh);
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(nh); o = expression.getValue(nh);
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
} }
@Test @Test
@ -162,40 +162,40 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests {
assertEquals("bc",o); assertEquals("bc",o);
System.out.println("Performance check for SpEL expression: '{'abcde','ijklm'}[0].substring({1,3,4}[0],{1,3,4}[1])'"); System.out.println("Performance check for SpEL expression: '{'abcde','ijklm'}[0].substring({1,3,4}[0],{1,3,4}[1])'");
long stime = System.currentTimeMillis(); long stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(); o = expression.getValue();
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(); o = expression.getValue();
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(); o = expression.getValue();
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
compile(expression); compile(expression);
System.out.println("Now compiled:"); System.out.println("Now compiled:");
o = expression.getValue(); o = expression.getValue();
assertEquals("bc", o); assertEquals("bc", o);
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(); o = expression.getValue();
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(); o = expression.getValue();
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(); o = expression.getValue();
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
} }
@Test @Test
@ -205,40 +205,40 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests {
assertEquals("jk",o); assertEquals("jk",o);
System.out.println("Performance check for SpEL expression: '{'abcde','ijklm'}[0].substring({1,3,4}[0],{1,3,4}[1])'"); System.out.println("Performance check for SpEL expression: '{'abcde','ijklm'}[0].substring({1,3,4}[0],{1,3,4}[1])'");
long stime = System.currentTimeMillis(); long stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(); o = expression.getValue();
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(); o = expression.getValue();
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(); o = expression.getValue();
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
compile(expression); compile(expression);
System.out.println("Now compiled:"); System.out.println("Now compiled:");
o = expression.getValue(); o = expression.getValue();
assertEquals("jk", o); assertEquals("jk", o);
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(); o = expression.getValue();
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(); o = expression.getValue();
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(); o = expression.getValue();
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
} }
@ -251,40 +251,40 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests {
System.out.println("Performance check for SpEL expression: 'hello' + getWorld() + ' spring'"); System.out.println("Performance check for SpEL expression: 'hello' + getWorld() + ' spring'");
long stime = System.currentTimeMillis(); long stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(g); o = expression.getValue(g);
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(g); o = expression.getValue(g);
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(g); o = expression.getValue(g);
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
compile(expression); compile(expression);
System.out.println("Now compiled:"); System.out.println("Now compiled:");
o = expression.getValue(g); o = expression.getValue(g);
assertEquals("helloworld spring", o); assertEquals("helloworld spring", o);
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(g); o = expression.getValue(g);
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(g); o = expression.getValue(g);
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<1000000;i++) { for (int i = 0; i < 1000000; i++) {
o = expression.getValue(g); o = expression.getValue(g);
} }
System.out.println("One million iterations: "+(System.currentTimeMillis()-stime)+"ms"); System.out.println("One million iterations: " + (System.currentTimeMillis()-stime) + "ms");
} }
public static class Greeter { public static class Greeter {
@ -301,15 +301,15 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests {
long iTotal = 0,cTotal = 0; long iTotal = 0,cTotal = 0;
// warmup // warmup
for (int i=0;i<count;i++) { for (int i = 0; i < count; i++) {
b = expression.getValue(payload,Boolean.TYPE); b = expression.getValue(payload, Boolean.TYPE);
} }
log("timing interpreted: "); log("timing interpreted: ");
for (int iter=0;iter<iterations;iter++) { for (int i = 0; i < iterations; i++) {
long stime = System.currentTimeMillis(); long stime = System.currentTimeMillis();
for (int i=0;i<count;i++) { for (int j = 0; j < count; j++) {
b = expression.getValue(payload,Boolean.TYPE); b = expression.getValue(payload, Boolean.TYPE);
} }
long etime = System.currentTimeMillis(); long etime = System.currentTimeMillis();
long interpretedSpeed = (etime - stime); long interpretedSpeed = (etime - stime);
@ -320,12 +320,12 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests {
compile(expression); compile(expression);
boolean bc = false; boolean bc = false;
expression.getValue(payload,Boolean.TYPE); expression.getValue(payload, Boolean.TYPE);
log("timing compiled: "); log("timing compiled: ");
for (int iter=0;iter<iterations;iter++) { for (int i = 0; i < iterations; i++) {
long stime = System.currentTimeMillis(); long stime = System.currentTimeMillis();
for (int i=0;i<count;i++) { for (int j = 0; j < count; j++) {
bc = expression.getValue(payload,Boolean.TYPE); bc = expression.getValue(payload, Boolean.TYPE);
} }
long etime = System.currentTimeMillis(); long etime = System.currentTimeMillis();
long compiledSpeed = (etime - stime); long compiledSpeed = (etime - stime);
@ -340,11 +340,11 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests {
assertFalse(b); assertFalse(b);
// Verify the same result for compiled vs interpreted // Verify the same result for compiled vs interpreted
assertEquals(b,bc); assertEquals(b, bc);
// Verify if the input changes, the result changes // Verify if the input changes, the result changes
payload.DR[0].DRFixedSection.duration = 0.04d; payload.DR[0].DRFixedSection.duration = 0.04d;
bc = expression.getValue(payload,Boolean.TYPE); bc = expression.getValue(payload, Boolean.TYPE);
assertTrue(bc); assertTrue(bc);
} }
@ -364,15 +364,15 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests {
Expression expression = parser.parseExpression("hello()"); Expression expression = parser.parseExpression("hello()");
// warmup // warmup
for (int i=0;i<count;i++) { for (int i = 0; i < count; i++) {
interpretedResult = expression.getValue(testdata,String.class); interpretedResult = expression.getValue(testdata, String.class);
} }
log("timing interpreted: "); log("timing interpreted: ");
for (int iter=0;iter<iterations;iter++) { for (int i = 0; i < iterations; i++) {
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<count;i++) { for (int j = 0; j < count; j++) {
interpretedResult = expression.getValue(testdata,String.class); interpretedResult = expression.getValue(testdata, String.class);
} }
etime = System.currentTimeMillis(); etime = System.currentTimeMillis();
long interpretedSpeed = (etime - stime); long interpretedSpeed = (etime - stime);
@ -384,11 +384,11 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests {
compile(expression); compile(expression);
log("timing compiled: "); log("timing compiled: ");
expression.getValue(testdata,String.class); expression.getValue(testdata, String.class);
for (int iter=0;iter<iterations;iter++) { for (int i = 0; i < iterations; i++) {
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<count;i++) { for (int j = 0; j < count; j++) {
compiledResult = expression.getValue(testdata,String.class); compiledResult = expression.getValue(testdata, String.class);
} }
etime = System.currentTimeMillis(); etime = System.currentTimeMillis();
long compiledSpeed = (etime - stime); long compiledSpeed = (etime - stime);
@ -438,15 +438,15 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests {
Expression expression = parser.parseExpression("name"); Expression expression = parser.parseExpression("name");
// warmup // warmup
for (int i=0;i<count;i++) { for (int i = 0; i < count; i++) {
expression.getValue(testdata,String.class); expression.getValue(testdata, String.class);
} }
log("timing interpreted: "); log("timing interpreted: ");
for (int iter=0;iter<iterations;iter++) { for (int i = 0; i < iterations; i++) {
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<count;i++) { for (int j = 0; j < count; j++) {
interpretedResult = expression.getValue(testdata,String.class); interpretedResult = expression.getValue(testdata, String.class);
} }
etime = System.currentTimeMillis(); etime = System.currentTimeMillis();
long interpretedSpeed = (etime - stime); long interpretedSpeed = (etime - stime);
@ -458,11 +458,11 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests {
compile(expression); compile(expression);
log("timing compiled: "); log("timing compiled: ");
expression.getValue(testdata,String.class); expression.getValue(testdata, String.class);
for (int iter=0;iter<iterations;iter++) { for (int i = 0; i < iterations; i++) {
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<count;i++) { for (int j = 0; j < count; j++) {
compiledResult = expression.getValue(testdata,String.class); compiledResult = expression.getValue(testdata, String.class);
} }
etime = System.currentTimeMillis(); etime = System.currentTimeMillis();
long compiledSpeed = (etime - stime); long compiledSpeed = (etime - stime);
@ -485,15 +485,15 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests {
Expression expression = parser.parseExpression("foo.bar.boo"); Expression expression = parser.parseExpression("foo.bar.boo");
// warmup // warmup
for (int i=0;i<count;i++) { for (int i = 0; i < count; i++) {
expression.getValue(testdata,String.class); expression.getValue(testdata, String.class);
} }
log("timing interpreted: "); log("timing interpreted: ");
for (int iter=0;iter<iterations;iter++) { for (int i = 0; i < iterations; i++) {
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<count;i++) { for (int j = 0; j < count; j++) {
interpretedResult = expression.getValue(testdata,String.class); interpretedResult = expression.getValue(testdata, String.class);
} }
etime = System.currentTimeMillis(); etime = System.currentTimeMillis();
long interpretedSpeed = (etime - stime); long interpretedSpeed = (etime - stime);
@ -505,11 +505,11 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests {
compile(expression); compile(expression);
log("timing compiled: "); log("timing compiled: ");
expression.getValue(testdata,String.class); expression.getValue(testdata, String.class);
for (int iter=0;iter<iterations;iter++) { for (int i = 0; i < iterations; i++) {
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<count;i++) { for (int j = 0; j < count; j++) {
compiledResult = expression.getValue(testdata,String.class); compiledResult = expression.getValue(testdata, String.class);
} }
etime = System.currentTimeMillis(); etime = System.currentTimeMillis();
long compiledSpeed = (etime - stime); long compiledSpeed = (etime - stime);
@ -531,14 +531,14 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests {
Expression expression = parser.parseExpression("foo.baz.boo"); Expression expression = parser.parseExpression("foo.baz.boo");
// warmup // warmup
for (int i=0;i<count;i++) { for (int i = 0; i < count; i++) {
expression.getValue(testdata,String.class); expression.getValue(testdata, String.class);
} }
log("timing interpreted: "); log("timing interpreted: ");
for (int iter=0;iter<iterations;iter++) { for (int i = 0; i < iterations; i++) {
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<count;i++) { for (int j = 0; j < count; j++) {
interpretedResult = expression.getValue(testdata,String.class); interpretedResult = expression.getValue(testdata, String.class);
} }
etime = System.currentTimeMillis(); etime = System.currentTimeMillis();
long interpretedSpeed = (etime - stime); long interpretedSpeed = (etime - stime);
@ -550,11 +550,11 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests {
compile(expression); compile(expression);
log("timing compiled: "); log("timing compiled: ");
expression.getValue(testdata,String.class); expression.getValue(testdata, String.class);
for (int iter=0;iter<iterations;iter++) { for (int i = 0; i < iterations; i++) {
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<count;i++) { for (int j = 0; j < count; j++) {
compiledResult = expression.getValue(testdata,String.class); compiledResult = expression.getValue(testdata, String.class);
} }
etime = System.currentTimeMillis(); etime = System.currentTimeMillis();
long compiledSpeed = (etime - stime); long compiledSpeed = (etime - stime);
@ -576,42 +576,42 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests {
Expression expression = parser.parseExpression("foo.bay().boo"); Expression expression = parser.parseExpression("foo.bay().boo");
// warmup // warmup
for (int i=0;i<count;i++) { for (int i = 0; i < count; i++) {
expression.getValue(testdata,String.class); expression.getValue(testdata, String.class);
} }
log("timing interpreted: "); log("timing interpreted: ");
for (int iter=0;iter<iterations;iter++) { for (int i = 0; i < iterations; i++) {
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<count;i++) { for (int j = 0; j < count; j++) {
interpretedResult = expression.getValue(testdata,String.class); interpretedResult = expression.getValue(testdata, String.class);
} }
etime = System.currentTimeMillis(); etime = System.currentTimeMillis();
long interpretedSpeed = (etime - stime); long interpretedSpeed = (etime - stime);
interpretedTotal+=interpretedSpeed; interpretedTotal += interpretedSpeed;
log(interpretedSpeed+"ms "); log(interpretedSpeed + "ms ");
} }
logln(); logln();
compile(expression); compile(expression);
log("timing compiled: "); log("timing compiled: ");
expression.getValue(testdata,String.class); expression.getValue(testdata, String.class);
for (int iter=0;iter<iterations;iter++) { for (int i = 0; i < iterations; i++) {
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<count;i++) { for (int j = 0; j < count; j++) {
compiledResult = expression.getValue(testdata,String.class); compiledResult = expression.getValue(testdata, String.class);
} }
etime = System.currentTimeMillis(); etime = System.currentTimeMillis();
long compiledSpeed = (etime - stime); long compiledSpeed = (etime - stime);
compiledTotal+=compiledSpeed; compiledTotal += compiledSpeed;
log(compiledSpeed+"ms "); log(compiledSpeed + "ms ");
} }
logln(); logln();
assertEquals(interpretedResult,compiledResult); assertEquals(interpretedResult,compiledResult);
reportPerformance("nested reference (mixed field/method)",interpretedTotal, compiledTotal); reportPerformance("nested reference (mixed field/method)", interpretedTotal, compiledTotal);
} }
@Test @Test
@ -623,15 +623,15 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests {
Expression expression = parser.parseExpression("name2"); Expression expression = parser.parseExpression("name2");
// warmup // warmup
for (int i=0;i<count;i++) { for (int i = 0;i < count; i++) {
expression.getValue(testdata,String.class); expression.getValue(testdata, String.class);
} }
log("timing interpreted: "); log("timing interpreted: ");
for (int iter=0;iter<iterations;iter++) { for (int i = 0; i < iterations; i++) {
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<count;i++) { for (int j = 0; j < count; j++) {
interpretedResult = expression.getValue(testdata,String.class); interpretedResult = expression.getValue(testdata, String.class);
} }
etime = System.currentTimeMillis(); etime = System.currentTimeMillis();
long interpretedSpeed = (etime - stime); long interpretedSpeed = (etime - stime);
@ -644,11 +644,11 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests {
compile(expression); compile(expression);
log("timing compiled: "); log("timing compiled: ");
expression.getValue(testdata,String.class); expression.getValue(testdata, String.class);
for (int iter=0;iter<iterations;iter++) { for (int i = 0; i < iterations; i++) {
stime = System.currentTimeMillis(); stime = System.currentTimeMillis();
for (int i=0;i<count;i++) { for (int j = 0; j < count; j++) {
compiledResult = expression.getValue(testdata,String.class); compiledResult = expression.getValue(testdata, String.class);
} }
etime = System.currentTimeMillis(); etime = System.currentTimeMillis();
long compiledSpeed = (etime - stime); long compiledSpeed = (etime - stime);
@ -672,7 +672,7 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests {
double averageInterpreted = interpretedTotal/(iterations); double averageInterpreted = interpretedTotal/(iterations);
double averageCompiled = compiledTotal/(iterations); double averageCompiled = compiledTotal/(iterations);
double ratio = (averageCompiled/averageInterpreted)*100.0d; double ratio = (averageCompiled/averageInterpreted)*100.0d;
logln(">>"+title+": average for "+count+": compiled="+averageCompiled+"ms interpreted="+averageInterpreted+"ms: compiled takes "+((int)ratio)+"% of the interpreted time"); logln(">>"+title+": average for "+count+": compiled="+averageCompiled+"ms interpreted="+averageInterpreted+"ms: compiled takes " + ((int)ratio)+"% of the interpreted time");
if (averageCompiled>averageInterpreted) { if (averageCompiled>averageInterpreted) {
fail("Compiled version took longer than interpreted! CompiledSpeed=~"+averageCompiled+ fail("Compiled version took longer than interpreted! CompiledSpeed=~"+averageCompiled+
"ms InterpretedSpeed="+averageInterpreted+"ms"); "ms InterpretedSpeed="+averageInterpreted+"ms");
@ -690,7 +690,8 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests {
if (noisyTests) { if (noisyTests) {
if (message!=null && message.length>0) { if (message!=null && message.length>0) {
System.out.println(message[0]); System.out.println(message[0]);
} else { }
else {
System.out.println(); System.out.println();
} }
} }

View File

@ -1968,7 +1968,8 @@ public class SpelReproTests extends AbstractExpressionTests {
try { try {
expr = new SpelExpressionParser().parseRaw("&@foo"); expr = new SpelExpressionParser().parseRaw("&@foo");
fail("Illegal syntax, error expected"); fail("Illegal syntax, error expected");
} catch (SpelParseException spe) { }
catch (SpelParseException spe) {
assertEquals(SpelMessage.INVALID_BEAN_REFERENCE,spe.getMessageCode()); assertEquals(SpelMessage.INVALID_BEAN_REFERENCE,spe.getMessageCode());
assertEquals(0,spe.getPosition()); assertEquals(0,spe.getPosition());
} }
@ -1976,7 +1977,8 @@ public class SpelReproTests extends AbstractExpressionTests {
try { try {
expr = new SpelExpressionParser().parseRaw("@&foo"); expr = new SpelExpressionParser().parseRaw("@&foo");
fail("Illegal syntax, error expected"); fail("Illegal syntax, error expected");
} catch (SpelParseException spe) { }
catch (SpelParseException spe) {
assertEquals(SpelMessage.INVALID_BEAN_REFERENCE,spe.getMessageCode()); assertEquals(SpelMessage.INVALID_BEAN_REFERENCE,spe.getMessageCode());
assertEquals(0,spe.getPosition()); assertEquals(0,spe.getPosition());
} }

View File

@ -49,7 +49,8 @@ public class StandardTypeLocatorTests {
try { try {
locator.findType("URL"); locator.findType("URL");
fail("Should have failed"); fail("Should have failed");
} catch (EvaluationException ee) { }
catch (EvaluationException ee) {
SpelEvaluationException sEx = (SpelEvaluationException)ee; SpelEvaluationException sEx = (SpelEvaluationException)ee;
assertEquals(SpelMessage.TYPE_NOT_FOUND,sEx.getMessageCode()); assertEquals(SpelMessage.TYPE_NOT_FOUND,sEx.getMessageCode());
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2012 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -78,7 +78,8 @@ public class VariableAndFunctionTests extends AbstractExpressionTests {
@SuppressWarnings("unused") @SuppressWarnings("unused")
Object v = parser.parseRaw("#notStatic()").getValue(ctx); Object v = parser.parseRaw("#notStatic()").getValue(ctx);
fail("Should have failed with exception - cannot call non static method that way"); fail("Should have failed with exception - cannot call non static method that way");
} catch (SpelEvaluationException se) { }
catch (SpelEvaluationException se) {
if (se.getMessageCode() != SpelMessage.FUNCTION_MUST_BE_STATIC) { if (se.getMessageCode() != SpelMessage.FUNCTION_MUST_BE_STATIC) {
se.printStackTrace(); se.printStackTrace();
fail("Should have failed a message about the function needing to be static, not: " fail("Should have failed a message about the function needing to be static, not: "
@ -86,6 +87,8 @@ public class VariableAndFunctionTests extends AbstractExpressionTests {
} }
} }
} }
// this method is used by the test above // this method is used by the test above
public void nonStatic() { public void nonStatic() {
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2013 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -116,9 +116,10 @@ public class SpelParserTests {
SpelExpressionParser parser = new SpelExpressionParser(); SpelExpressionParser parser = new SpelExpressionParser();
parser.parseRaw("new String"); parser.parseRaw("new String");
fail(); fail();
} catch (ParseException e) { }
assertTrue(e instanceof SpelParseException); catch (ParseException ex) {
SpelParseException spe = (SpelParseException) e; assertTrue(ex instanceof SpelParseException);
SpelParseException spe = (SpelParseException) ex;
assertEquals(SpelMessage.MISSING_CONSTRUCTOR_ARGS, spe.getMessageCode()); assertEquals(SpelMessage.MISSING_CONSTRUCTOR_ARGS, spe.getMessageCode());
assertEquals(10, spe.getPosition()); assertEquals(10, spe.getPosition());
} }
@ -127,9 +128,10 @@ public class SpelParserTests {
SpelExpressionParser parser = new SpelExpressionParser(); SpelExpressionParser parser = new SpelExpressionParser();
parser.parseRaw("new String(3,"); parser.parseRaw("new String(3,");
fail(); fail();
} catch (ParseException e) { }
assertTrue(e instanceof SpelParseException); catch (ParseException ex) {
SpelParseException spe = (SpelParseException) e; assertTrue(ex instanceof SpelParseException);
SpelParseException spe = (SpelParseException) ex;
assertEquals(SpelMessage.RUN_OUT_OF_ARGUMENTS, spe.getMessageCode()); assertEquals(SpelMessage.RUN_OUT_OF_ARGUMENTS, spe.getMessageCode());
assertEquals(10, spe.getPosition()); assertEquals(10, spe.getPosition());
} }
@ -138,9 +140,10 @@ public class SpelParserTests {
SpelExpressionParser parser = new SpelExpressionParser(); SpelExpressionParser parser = new SpelExpressionParser();
parser.parseRaw("new String(3"); parser.parseRaw("new String(3");
fail(); fail();
} catch (ParseException e) { }
assertTrue(e instanceof SpelParseException); catch (ParseException ex) {
SpelParseException spe = (SpelParseException) e; assertTrue(ex instanceof SpelParseException);
SpelParseException spe = (SpelParseException) ex;
assertEquals(SpelMessage.RUN_OUT_OF_ARGUMENTS, spe.getMessageCode()); assertEquals(SpelMessage.RUN_OUT_OF_ARGUMENTS, spe.getMessageCode());
assertEquals(10, spe.getPosition()); assertEquals(10, spe.getPosition());
} }
@ -149,9 +152,10 @@ public class SpelParserTests {
SpelExpressionParser parser = new SpelExpressionParser(); SpelExpressionParser parser = new SpelExpressionParser();
parser.parseRaw("new String("); parser.parseRaw("new String(");
fail(); fail();
} catch (ParseException e) { }
assertTrue(e instanceof SpelParseException); catch (ParseException ex) {
SpelParseException spe = (SpelParseException) e; assertTrue(ex instanceof SpelParseException);
SpelParseException spe = (SpelParseException) ex;
assertEquals(SpelMessage.RUN_OUT_OF_ARGUMENTS, spe.getMessageCode()); assertEquals(SpelMessage.RUN_OUT_OF_ARGUMENTS, spe.getMessageCode());
assertEquals(10, spe.getPosition()); assertEquals(10, spe.getPosition());
} }
@ -160,9 +164,10 @@ public class SpelParserTests {
SpelExpressionParser parser = new SpelExpressionParser(); SpelExpressionParser parser = new SpelExpressionParser();
parser.parseRaw("\"abc"); parser.parseRaw("\"abc");
fail(); fail();
} catch (ParseException e) { }
assertTrue(e instanceof SpelParseException); catch (ParseException ex) {
SpelParseException spe = (SpelParseException) e; assertTrue(ex instanceof SpelParseException);
SpelParseException spe = (SpelParseException) ex;
assertEquals(SpelMessage.NON_TERMINATING_DOUBLE_QUOTED_STRING, spe.getMessageCode()); assertEquals(SpelMessage.NON_TERMINATING_DOUBLE_QUOTED_STRING, spe.getMessageCode());
assertEquals(0, spe.getPosition()); assertEquals(0, spe.getPosition());
} }
@ -171,9 +176,10 @@ public class SpelParserTests {
SpelExpressionParser parser = new SpelExpressionParser(); SpelExpressionParser parser = new SpelExpressionParser();
parser.parseRaw("'abc"); parser.parseRaw("'abc");
fail(); fail();
} catch (ParseException e) { }
assertTrue(e instanceof SpelParseException); catch (ParseException ex) {
SpelParseException spe = (SpelParseException) e; assertTrue(ex instanceof SpelParseException);
SpelParseException spe = (SpelParseException) ex;
assertEquals(SpelMessage.NON_TERMINATING_QUOTED_STRING, spe.getMessageCode()); assertEquals(SpelMessage.NON_TERMINATING_QUOTED_STRING, spe.getMessageCode());
assertEquals(0, spe.getPosition()); assertEquals(0, spe.getPosition());
} }
@ -274,7 +280,8 @@ public class SpelParserTests {
try { try {
new SpelExpressionParser().parseRaw("\"double quote: \\\"\\\".\""); new SpelExpressionParser().parseRaw("\"double quote: \\\"\\\".\"");
fail("Should have failed"); fail("Should have failed");
} catch (SpelParseException spe) { }
catch (SpelParseException spe) {
assertEquals(17, spe.getPosition()); assertEquals(17, spe.getPosition());
assertEquals(SpelMessage.UNEXPECTED_ESCAPE_CHAR, spe.getMessageCode()); assertEquals(SpelMessage.UNEXPECTED_ESCAPE_CHAR, spe.getMessageCode());
} }
@ -401,9 +408,10 @@ public class SpelParserTests {
Object o = expr.getValue(); Object o = expr.getValue();
assertEquals(value, o); assertEquals(value, o);
assertEquals(type, o.getClass()); assertEquals(type, o.getClass());
} catch (Exception e) { }
e.printStackTrace(); catch (Exception ex) {
fail(e.getMessage()); ex.printStackTrace();
fail(ex.getMessage());
} }
} }
@ -412,9 +420,10 @@ public class SpelParserTests {
SpelExpressionParser parser = new SpelExpressionParser(); SpelExpressionParser parser = new SpelExpressionParser();
parser.parseRaw(expression); parser.parseRaw(expression);
fail(); fail();
} catch (ParseException e) { }
assertTrue(e instanceof SpelParseException); catch (ParseException ex) {
SpelParseException spe = (SpelParseException) e; assertTrue(ex instanceof SpelParseException);
SpelParseException spe = (SpelParseException) ex;
assertEquals(expectedMessage, spe.getMessageCode()); assertEquals(expectedMessage, spe.getMessageCode());
} }
} }

View File

@ -1042,7 +1042,8 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
result[i] = rowsAffected.get(i); result[i] = rowsAffected.get(i);
} }
return result; return result;
} finally { }
finally {
if (pss instanceof ParameterDisposer) { if (pss instanceof ParameterDisposer) {
((ParameterDisposer) pss).cleanupParameters(); ((ParameterDisposer) pss).cleanupParameters();
} }

View File

@ -150,7 +150,8 @@ public class JdbcTemplateQueryTests {
this.thrown.expect(IncorrectResultSizeDataAccessException.class); this.thrown.expect(IncorrectResultSizeDataAccessException.class);
try { try {
this.template.queryForObject(sql, String.class); this.template.queryForObject(sql, String.class);
} finally { }
finally {
verify(this.resultSet).close(); verify(this.resultSet).close();
verify(this.statement).close(); verify(this.statement).close();
} }

View File

@ -292,13 +292,14 @@ public class DataSourceJtaTransactionTests {
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
verify(userTransaction, times(6)).begin(); verify(userTransaction, times(6)).begin();
verify(transactionManager, times(5)).resume(transaction); verify(transactionManager, times(5)).resume(transaction);
if(rollback) { if (rollback) {
verify(userTransaction, times(5)).commit(); verify(userTransaction, times(5)).commit();
verify(userTransaction).rollback(); verify(userTransaction).rollback();
} else { }
else {
verify(userTransaction, times(6)).commit(); verify(userTransaction, times(6)).commit();
} }
if(accessAfterResume && !openOuterConnection) { if (accessAfterResume && !openOuterConnection) {
verify(connection, times(7)).close(); verify(connection, times(7)).close();
} }
else { else {
@ -528,7 +529,7 @@ public class DataSourceJtaTransactionTests {
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
verify(userTransaction).begin(); verify(userTransaction).begin();
if(suspendException) { if (suspendException) {
verify(userTransaction).rollback(); verify(userTransaction).rollback();
} }

View File

@ -152,7 +152,7 @@ public class DataSourceTransactionManagerTests {
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse)); assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive());
if(autoCommit && (!lazyConnection || createStatement)) { if (autoCommit && (!lazyConnection || createStatement)) {
InOrder ordered = inOrder(con); InOrder ordered = inOrder(con);
ordered.verify(con).setAutoCommit(false); ordered.verify(con).setAutoCommit(false);
ordered.verify(con).commit(); ordered.verify(con).commit();
@ -244,7 +244,7 @@ public class DataSourceTransactionManagerTests {
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive());
if(autoCommit && (!lazyConnection || createStatement)) { if (autoCommit && (!lazyConnection || createStatement)) {
InOrder ordered = inOrder(con); InOrder ordered = inOrder(con);
ordered.verify(con).setAutoCommit(false); ordered.verify(con).setAutoCommit(false);
ordered.verify(con).rollback(); ordered.verify(con).rollback();

View File

@ -63,10 +63,11 @@ public class BeanFactoryDataSourceLookupTests {
BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup(beanFactory); BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup(beanFactory);
lookup.getDataSource(DATASOURCE_BEAN_NAME); lookup.getDataSource(DATASOURCE_BEAN_NAME);
fail("should have thrown DataSourceLookupFailureException"); fail("should have thrown DataSourceLookupFailureException");
} catch (DataSourceLookupFailureException ex) { /* expected */ } }
catch (DataSourceLookupFailureException ex) { /* expected */ }
} }
@Test(expected=IllegalStateException.class) @Test(expected = IllegalStateException.class)
public void testLookupWhereBeanFactoryHasNotBeenSupplied() throws Exception { public void testLookupWhereBeanFactoryHasNotBeenSupplied() throws Exception {
BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup(); BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup();
lookup.getDataSource(DATASOURCE_BEAN_NAME); lookup.getDataSource(DATASOURCE_BEAN_NAME);

View File

@ -81,7 +81,7 @@ public class StoredProcedureTests {
@After @After
public void verifyClosed() throws Exception { public void verifyClosed() throws Exception {
if(verifyClosedAfter) { if (verifyClosedAfter) {
verify(callableStatement).close(); verify(callableStatement).close();
verify(connection, atLeastOnce()).close(); verify(connection, atLeastOnce()).close();
} }

View File

@ -205,7 +205,8 @@ public class ResultSetWrappingRowSetTests {
if (arg instanceof String) { if (arg instanceof String) {
given(rset.findColumn((String) arg)).willReturn(1); given(rset.findColumn((String) arg)).willReturn(1);
given(rsetMethod.invoke(rset, 1)).willReturn(ret).willThrow(new SQLException("test")); given(rsetMethod.invoke(rset, 1)).willReturn(ret).willThrow(new SQLException("test"));
} else { }
else {
given(rsetMethod.invoke(rset, arg)).willReturn(ret).willThrow(new SQLException("test")); given(rsetMethod.invoke(rset, arg)).willReturn(ret).willThrow(new SQLException("test"));
} }
rowsetMethod.invoke(rowset, arg); rowsetMethod.invoke(rowset, arg);

View File

@ -307,7 +307,8 @@ public class MessageListenerAdapterTests {
try { try {
adapter.onMessage(sentTextMessage, session); adapter.onMessage(sentTextMessage, session);
fail("expected CouldNotSendReplyException with InvalidDestinationException"); fail("expected CouldNotSendReplyException with InvalidDestinationException");
} catch(ReplyFailureException ex) { }
catch (ReplyFailureException ex) {
assertEquals(InvalidDestinationException.class, ex.getCause().getClass()); assertEquals(InvalidDestinationException.class, ex.getCause().getClass());
} }
@ -345,7 +346,8 @@ public class MessageListenerAdapterTests {
try { try {
adapter.onMessage(sentTextMessage, session); adapter.onMessage(sentTextMessage, session);
fail("expected CouldNotSendReplyException with JMSException"); fail("expected CouldNotSendReplyException with JMSException");
} catch(ReplyFailureException ex) { }
catch (ReplyFailureException ex) {
assertEquals(JMSException.class, ex.getCause().getClass()); assertEquals(JMSException.class, ex.getCause().getClass());
} }
@ -371,7 +373,8 @@ public class MessageListenerAdapterTests {
try { try {
adapter.onMessage(message, session); adapter.onMessage(message, session);
fail("expected ListenerExecutionFailedException"); fail("expected ListenerExecutionFailedException");
} catch(ListenerExecutionFailedException ex) { /* expected */ } }
catch (ListenerExecutionFailedException ex) { /* expected */ }
} }
@Test @Test
@ -425,7 +428,8 @@ public class MessageListenerAdapterTests {
try { try {
adapter.onMessage(sentTextMessage, session); adapter.onMessage(sentTextMessage, session);
fail("expected CouldNotSendReplyException with MessageConversionException"); fail("expected CouldNotSendReplyException with MessageConversionException");
} catch(ReplyFailureException ex) { }
catch (ReplyFailureException ex) {
assertEquals(MessageConversionException.class, ex.getCause().getClass()); assertEquals(MessageConversionException.class, ex.getCause().getClass());
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2014 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -45,7 +45,7 @@ import static org.mockito.BDDMockito.*;
* @author Rick Evans * @author Rick Evans
* @since 18.09.2004 * @since 18.09.2004
*/ */
public final class SimpleMessageConverterTests { public class SimpleMessageConverterTests {
@Test @Test
public void testStringConversion() throws JMSException { public void testStringConversion() throws JMSException {
@ -124,19 +124,18 @@ public final class SimpleMessageConverterTests {
assertEquals(content, converter.fromMessage(msg)); assertEquals(content, converter.fromMessage(msg));
} }
@Test(expected=MessageConversionException.class) @Test(expected = MessageConversionException.class)
public void testToMessageThrowsExceptionIfGivenNullObjectToConvert() throws Exception { public void testToMessageThrowsExceptionIfGivenNullObjectToConvert() throws Exception {
new SimpleMessageConverter().toMessage(null, null); new SimpleMessageConverter().toMessage(null, null);
} }
@Test(expected=MessageConversionException.class) @Test(expected = MessageConversionException.class)
public void testToMessageThrowsExceptionIfGivenIncompatibleObjectToConvert() throws Exception { public void testToMessageThrowsExceptionIfGivenIncompatibleObjectToConvert() throws Exception {
new SimpleMessageConverter().toMessage(new Object(), null); new SimpleMessageConverter().toMessage(new Object(), null);
} }
@Test @Test
public void testToMessageSimplyReturnsMessageAsIsIfSuppliedWithMessage() throws JMSException { public void testToMessageSimplyReturnsMessageAsIsIfSuppliedWithMessage() throws JMSException {
Session session = mock(Session.class); Session session = mock(Session.class);
ObjectMessage message = mock(ObjectMessage.class); ObjectMessage message = mock(ObjectMessage.class);
@ -147,7 +146,6 @@ public final class SimpleMessageConverterTests {
@Test @Test
public void testFromMessageSimplyReturnsMessageAsIsIfSuppliedWithMessage() throws JMSException { public void testFromMessageSimplyReturnsMessageAsIsIfSuppliedWithMessage() throws JMSException {
Message message = mock(Message.class); Message message = mock(Message.class);
SimpleMessageConverter converter = new SimpleMessageConverter(); SimpleMessageConverter converter = new SimpleMessageConverter();
@ -157,36 +155,36 @@ public final class SimpleMessageConverterTests {
@Test @Test
public void testMapConversionWhereMapHasNonStringTypesForKeys() throws JMSException { public void testMapConversionWhereMapHasNonStringTypesForKeys() throws JMSException {
MapMessage message = mock(MapMessage.class); MapMessage message = mock(MapMessage.class);
final Session session = mock(Session.class); Session session = mock(Session.class);
given(session.createMapMessage()).willReturn(message); given(session.createMapMessage()).willReturn(message);
final Map<Integer, String> content = new HashMap<Integer, String>(1); Map<Integer, String> content = new HashMap<Integer, String>(1);
content.put(1, "value1"); content.put(1, "value1");
final SimpleMessageConverter converter = new SimpleMessageConverter(); SimpleMessageConverter converter = new SimpleMessageConverter();
try { try {
converter.toMessage(content, session); converter.toMessage(content, session);
fail("expected MessageConversionException"); fail("expected MessageConversionException");
} catch (MessageConversionException ex) { /* expected */ } }
catch (MessageConversionException ex) { /* expected */ }
} }
@Test @Test
public void testMapConversionWhereMapHasNNullForKey() throws JMSException { public void testMapConversionWhereMapHasNNullForKey() throws JMSException {
MapMessage message = mock(MapMessage.class); MapMessage message = mock(MapMessage.class);
final Session session = mock(Session.class); Session session = mock(Session.class);
given(session.createMapMessage()).willReturn(message); given(session.createMapMessage()).willReturn(message);
final Map<Object, String> content = new HashMap<Object, String>(1); Map<Object, String> content = new HashMap<Object, String>(1);
content.put(null, "value1"); content.put(null, "value1");
final SimpleMessageConverter converter = new SimpleMessageConverter(); SimpleMessageConverter converter = new SimpleMessageConverter();
try { try {
converter.toMessage(content, session); converter.toMessage(content, session);
fail("expected MessageConversionException"); fail("expected MessageConversionException");
} catch (MessageConversionException ex) { /* expected */ } }
catch (MessageConversionException ex) { /* expected */ }
} }
} }

View File

@ -275,7 +275,7 @@ public class MethodMessageHandlerTests {
private static Map<Class<? extends Throwable>, Method> initExceptionMappings(Class<?> handlerType) { private static Map<Class<? extends Throwable>, Method> initExceptionMappings(Class<?> handlerType) {
Map<Class<? extends Throwable>, Method> result = new HashMap<Class<? extends Throwable>, Method>(); Map<Class<? extends Throwable>, Method> result = new HashMap<Class<? extends Throwable>, Method>();
for (Method method : MethodIntrospector.selectMethods(handlerType, EXCEPTION_HANDLER_METHOD_FILTER)) { for (Method method : MethodIntrospector.selectMethods(handlerType, EXCEPTION_HANDLER_METHOD_FILTER)) {
for(Class<? extends Throwable> exception : getExceptionsFromMethodSignature(method)) { for (Class<? extends Throwable> exception : getExceptionsFromMethodSignature(method)) {
result.put(exception, method); result.put(exception, method);
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2015 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -13,10 +13,8 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.messaging.simp.stomp;
import static org.hamcrest.Matchers.*; package org.springframework.messaging.simp.stomp;
import static org.junit.Assert.*;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.ArrayList; import java.util.ArrayList;
@ -41,6 +39,9 @@ import org.springframework.util.Assert;
import org.springframework.util.SocketUtils; import org.springframework.util.SocketUtils;
import org.springframework.util.concurrent.ListenableFuture; import org.springframework.util.concurrent.ListenableFuture;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
/** /**
* Integration tests for {@link Reactor2TcpStompClient}. * Integration tests for {@link Reactor2TcpStompClient}.
* *
@ -86,7 +87,8 @@ public class Reactor2TcpStompClientTests {
public void tearDown() throws Exception { public void tearDown() throws Exception {
try { try {
this.client.shutdown(); this.client.shutdown();
} catch (Throwable ex) { }
catch (Throwable ex) {
logger.error("Failed to shut client", ex); logger.error("Failed to shut client", ex);
} }
final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch latch = new CountDownLatch(1);
@ -100,7 +102,6 @@ public class Reactor2TcpStompClientTests {
@Test @Test
public void publishSubscribe() throws Exception { public void publishSubscribe() throws Exception {
String destination = "/topic/foo"; String destination = "/topic/foo";
ConsumingHandler consumingHandler1 = new ConsumingHandler(destination); ConsumingHandler consumingHandler1 = new ConsumingHandler(destination);
ListenableFuture<StompSession> consumerFuture1 = this.client.connect(consumingHandler1); ListenableFuture<StompSession> consumerFuture1 = this.client.connect(consumingHandler1);
@ -146,9 +147,9 @@ public class Reactor2TcpStompClientTests {
public void handleTransportError(StompSession session, Throwable exception) { public void handleTransportError(StompSession session, Throwable exception) {
logger.error(exception); logger.error(exception);
} }
} }
private static class ConsumingHandler extends LoggingSessionHandler { private static class ConsumingHandler extends LoggingSessionHandler {
private final List<String> topics; private final List<String> topics;
@ -157,14 +158,12 @@ public class Reactor2TcpStompClientTests {
private final List<String> received = new ArrayList<>(); private final List<String> received = new ArrayList<>();
public ConsumingHandler(String... topics) { public ConsumingHandler(String... topics) {
Assert.notEmpty(topics); Assert.notEmpty(topics);
this.topics = Arrays.asList(topics); this.topics = Arrays.asList(topics);
this.subscriptionLatch = new CountDownLatch(this.topics.size()); this.subscriptionLatch = new CountDownLatch(this.topics.size());
} }
public List<String> getReceived() { public List<String> getReceived() {
return this.received; return this.received;
} }
@ -208,16 +207,15 @@ public class Reactor2TcpStompClientTests {
} }
return true; return true;
} }
} }
private static class ProducingHandler extends LoggingSessionHandler { private static class ProducingHandler extends LoggingSessionHandler {
private final List<String> topics = new ArrayList<>(); private final List<String> topics = new ArrayList<>();
private final List<Object> payloads = new ArrayList<>(); private final List<Object> payloads = new ArrayList<>();
public ProducingHandler addToSend(String topic, Object payload) { public ProducingHandler addToSend(String topic, Object payload) {
this.topics.add(topic); this.topics.add(topic);
this.payloads.add(payload); this.payloads.add(payload);
@ -226,7 +224,7 @@ public class Reactor2TcpStompClientTests {
@Override @Override
public void afterConnected(StompSession session, StompHeaders connectedHeaders) { public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
for (int i=0; i < this.topics.size(); i++) { for (int i = 0; i < this.topics.size(); i++) {
session.send(this.topics.get(i), this.payloads.get(i)); session.send(this.topics.get(i), this.payloads.get(i));
} }
} }

View File

@ -326,7 +326,7 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
} }
public boolean matchMessage(Message<?> message) { public boolean matchMessage(Message<?> message) {
for (int i=0 ; i < this.expected.length; i++) { for (int i = 0 ; i < this.expected.length; i++) {
if (this.expected[i].match(message)) { if (this.expected[i].match(message)) {
this.actual[i] = message; this.actual[i] = message;
return true; return true;

View File

@ -325,7 +325,8 @@ public class StompCodecTests {
this.decoder.apply(buffer); this.decoder.apply(buffer);
if (consumer.arguments.isEmpty()) { if (consumer.arguments.isEmpty()) {
return null; return null;
} else { }
else {
return consumer.arguments.get(0); return consumer.arguments.get(0);
} }
} }

View File

@ -166,7 +166,8 @@ public class HibernateJtaTransactionTests {
if (readOnly) { if (readOnly) {
verify(session).setFlushMode(FlushMode.MANUAL); verify(session).setFlushMode(FlushMode.MANUAL);
} else { }
else {
verify(session).flush(); verify(session).flush();
} }
verify(session).close(); verify(session).close();
@ -188,7 +189,8 @@ public class HibernateJtaTransactionTests {
UserTransaction ut = mock(UserTransaction.class); UserTransaction ut = mock(UserTransaction.class);
if (status == Status.STATUS_NO_TRANSACTION) { if (status == Status.STATUS_NO_TRANSACTION) {
given(ut.getStatus()).willReturn(status, status, Status.STATUS_ACTIVE); given(ut.getStatus()).willReturn(status, status, Status.STATUS_ACTIVE);
} else { }
else {
given(ut.getStatus()).willReturn(status); given(ut.getStatus()).willReturn(status);
} }
@ -520,13 +522,13 @@ public class HibernateJtaTransactionTests {
verify(ut).commit(); verify(ut).commit();
if (flushNever) { if (flushNever) {
if(!readOnly) { if (!readOnly) {
InOrder ordered = inOrder(session); InOrder ordered = inOrder(session);
ordered.verify(session).setFlushMode(FlushMode.AUTO); ordered.verify(session).setFlushMode(FlushMode.AUTO);
ordered.verify(session).setFlushMode(FlushMode.MANUAL); ordered.verify(session).setFlushMode(FlushMode.MANUAL);
} }
} }
if(!flushNever && !readOnly) { if (!flushNever && !readOnly) {
verify(session).flush(); verify(session).flush();
} }
verify(session).afterTransactionCompletion(true, null); verify(session).afterTransactionCompletion(true, null);
@ -716,7 +718,7 @@ public class HibernateJtaTransactionTests {
} }
verify(session1).disconnect(); verify(session1).disconnect();
verify(session1).close(); verify(session1).close();
if(!rollback) { if (!rollback) {
verify(session1).flush(); verify(session1).flush();
verify(session2, atLeastOnce()).flush(); verify(session2, atLeastOnce()).flush();
} }
@ -792,7 +794,7 @@ public class HibernateJtaTransactionTests {
} }
verify(ut, atLeastOnce()).begin(); verify(ut, atLeastOnce()).begin();
if(!suspendException) { if (!suspendException) {
verify(tm).resume(tx); verify(tm).resume(tx);
} }
verify(ut).rollback(); verify(ut).rollback();
@ -1448,10 +1450,11 @@ public class HibernateJtaTransactionTests {
assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
InOrder ordered = inOrder(session); InOrder ordered = inOrder(session);
if(flushNever) { if (flushNever) {
ordered.verify(session).setFlushMode(FlushMode.AUTO); ordered.verify(session).setFlushMode(FlushMode.AUTO);
ordered.verify(session).setFlushMode(FlushMode.MANUAL); ordered.verify(session).setFlushMode(FlushMode.MANUAL);
} else { }
else {
ordered.verify(session).flush(); ordered.verify(session).flush();
} }
ordered.verify(session).disconnect(); ordered.verify(session).disconnect();

View File

@ -79,7 +79,7 @@ public class MockFilterChainTests {
chain.doFilter(this.request, this.response); chain.doFilter(this.request, this.response);
fail("Expected Exception"); fail("Expected Exception");
} }
catch(IllegalStateException ex) { catch (IllegalStateException ex) {
assertEquals("This FilterChain has already been called!", ex.getMessage()); assertEquals("This FilterChain has already been called!", ex.getMessage());
} }
} }
@ -94,7 +94,7 @@ public class MockFilterChainTests {
chain.doFilter(this.request, this.response); chain.doFilter(this.request, this.response);
fail("Expected Exception"); fail("Expected Exception");
} }
catch(IllegalStateException ex) { catch (IllegalStateException ex) {
assertEquals("This FilterChain has already been called!", ex.getMessage()); assertEquals("This FilterChain has already been called!", ex.getMessage());
} }
} }
@ -118,7 +118,7 @@ public class MockFilterChainTests {
chain.doFilter(this.request, this.response); chain.doFilter(this.request, this.response);
fail("Expected Exception"); fail("Expected Exception");
} }
catch(IllegalStateException ex) { catch (IllegalStateException ex) {
assertEquals("This FilterChain has already been called!", ex.getMessage()); assertEquals("This FilterChain has already been called!", ex.getMessage());
} }
} }

View File

@ -59,7 +59,7 @@ public class StatusResultMatchersTests {
List<AssertionError> failures = new ArrayList<AssertionError>(); List<AssertionError> failures = new ArrayList<AssertionError>();
for(HttpStatus status : HttpStatus.values()) { for (HttpStatus status : HttpStatus.values()) {
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
response.setStatus(status.value()); response.setStatus(status.value());
MvcResult mvcResult = new StubMvcResult(request, null, null, null, null, null, response); MvcResult mvcResult = new StubMvcResult(request, null, null, null, null, null, response);
@ -91,9 +91,7 @@ public class StatusResultMatchersTests {
@Test @Test
public void statusRanges() throws Exception { public void statusRanges() throws Exception {
for (HttpStatus status : HttpStatus.values()) {
for(HttpStatus status : HttpStatus.values()) {
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
response.setStatus(status.value()); response.setStatus(status.value());
MvcResult mvcResult = new StubMvcResult(request, null, null, null, null, null, response); MvcResult mvcResult = new StubMvcResult(request, null, null, null, null, null, response);

View File

@ -123,7 +123,7 @@ public class UrlBasedCorsConfigurationSource implements CorsConfigurationSource
@Override @Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) { public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
String lookupPath = this.urlPathHelper.getLookupPathForRequest(request); String lookupPath = this.urlPathHelper.getLookupPathForRequest(request);
for(Map.Entry<String, CorsConfiguration> entry : this.corsConfigurations.entrySet()) { for (Map.Entry<String, CorsConfiguration> entry : this.corsConfigurations.entrySet()) {
if (this.pathMatcher.match(entry.getKey(), lookupPath)) { if (this.pathMatcher.match(entry.getKey(), lookupPath)) {
return entry.getValue(); return entry.getValue();
} }

View File

@ -48,9 +48,8 @@ import org.springframework.web.method.support.ModelAndViewContainer;
* Assist with initialization of the {@link Model} before controller method * Assist with initialization of the {@link Model} before controller method
* invocation and with updates to it after the invocation. * invocation and with updates to it after the invocation.
* *
* <p>On initialization the model is populated with attributes temporarily * <p>On initialization the model is populated with attributes temporarily stored
* stored in the session and through the invocation of {@code @ModelAttribute} * in the session and through the invocation of {@code @ModelAttribute} methods.
* methods.
* *
* <p>On update model attributes are synchronized with the session and also * <p>On update model attributes are synchronized with the session and also
* {@link BindingResult} attributes are added if missing. * {@link BindingResult} attributes are added if missing.
@ -62,7 +61,6 @@ public final class ModelFactory {
private static final Log logger = LogFactory.getLog(ModelFactory.class); private static final Log logger = LogFactory.getLog(ModelFactory.class);
private final List<ModelMethod> modelMethods = new ArrayList<ModelMethod>(); private final List<ModelMethod> modelMethods = new ArrayList<ModelMethod>();
private final WebDataBinderFactory dataBinderFactory; private final WebDataBinderFactory dataBinderFactory;
@ -92,11 +90,11 @@ public final class ModelFactory {
/** /**
* Populate the model in the following order: * Populate the model in the following order:
* <ol> * <ol>
* <li>Retrieve "known" session attributes listed as {@code @SessionAttributes}. * <li>Retrieve "known" session attributes listed as {@code @SessionAttributes}.
* <li>Invoke {@code @ModelAttribute} methods * <li>Invoke {@code @ModelAttribute} methods
* <li>Find {@code @ModelAttribute} method arguments also listed as * <li>Find {@code @ModelAttribute} method arguments also listed as
* {@code @SessionAttributes} and ensure they're present in the model raising * {@code @SessionAttributes} and ensure they're present in the model raising
* an exception if necessary. * an exception if necessary.
* </ol> * </ol>
* @param request the current request * @param request the current request
* @param container a container with the model to be initialized * @param container a container with the model to be initialized
@ -108,15 +106,13 @@ public final class ModelFactory {
Map<String, ?> sessionAttributes = this.sessionAttributesHandler.retrieveAttributes(request); Map<String, ?> sessionAttributes = this.sessionAttributesHandler.retrieveAttributes(request);
container.mergeAttributes(sessionAttributes); container.mergeAttributes(sessionAttributes);
invokeModelAttributeMethods(request, container); invokeModelAttributeMethods(request, container);
for (String name : findSessionAttributeArguments(handlerMethod)) { for (String name : findSessionAttributeArguments(handlerMethod)) {
if (!container.containsAttribute(name)) { if (!container.containsAttribute(name)) {
Object value = this.sessionAttributesHandler.retrieveAttribute(request, name); Object value = this.sessionAttributesHandler.retrieveAttribute(request, name);
if (value == null) { if (value == null) {
throw new HttpSessionRequiredException( throw new HttpSessionRequiredException("Expected session attribute '" + name + "'");
"Expected session attribute '" + name + "'");
} }
container.addAttribute(name, value); container.addAttribute(name, value);
} }
@ -127,8 +123,8 @@ public final class ModelFactory {
* Invoke model attribute methods to populate the model. * Invoke model attribute methods to populate the model.
* Attributes are added only if not already present in the model. * Attributes are added only if not already present in the model.
*/ */
private void invokeModelAttributeMethods(NativeWebRequest request, private void invokeModelAttributeMethods(NativeWebRequest request, ModelAndViewContainer container)
ModelAndViewContainer container) throws Exception { throws Exception {
while (!this.modelMethods.isEmpty()) { while (!this.modelMethods.isEmpty()) {
InvocableHandlerMethod modelMethod = getNextModelMethod(container).getHandlerMethod(); InvocableHandlerMethod modelMethod = getNextModelMethod(container).getHandlerMethod();
@ -141,7 +137,6 @@ public final class ModelFactory {
} }
Object returnValue = modelMethod.invokeForRequest(request, container); Object returnValue = modelMethod.invokeForRequest(request, container);
if (!modelMethod.isVoid()){ if (!modelMethod.isVoid()){
String returnValueName = getNameForReturnValue(returnValue, modelMethod.getReturnType()); String returnValueName = getNameForReturnValue(returnValue, modelMethod.getReturnType());
if (!ann.binding()) { if (!ann.binding()) {
@ -291,7 +286,6 @@ public final class ModelFactory {
private final Set<String> dependencies = new HashSet<String>(); private final Set<String> dependencies = new HashSet<String>();
private ModelMethod(InvocableHandlerMethod handlerMethod) { private ModelMethod(InvocableHandlerMethod handlerMethod) {
this.handlerMethod = handlerMethod; this.handlerMethod = handlerMethod;
for (MethodParameter parameter : handlerMethod.getMethodParameters()) { for (MethodParameter parameter : handlerMethod.getMethodParameters()) {

View File

@ -288,7 +288,7 @@ final class HierarchicalUriComponents extends UriComponents {
return; return;
} }
int length = source.length(); int length = source.length();
for (int i=0; i < length; i++) { for (int i = 0; i < length; i++) {
char ch = source.charAt(i); char ch = source.charAt(i);
if (ch == '%') { if (ch == '%') {
if ((i + 2) < length) { if ((i + 2) < length) {

View File

@ -61,7 +61,8 @@ public class ProtobufHttpMessageConverterTests {
public void extensionRegistryNull() { public void extensionRegistryNull() {
try { try {
new ProtobufHttpMessageConverter(null); new ProtobufHttpMessageConverter(null);
} catch (Exception e) { }
catch (Exception ex) {
fail("Unable to create ProtobufHttpMessageConverter with null extensionRegistry"); fail("Unable to create ProtobufHttpMessageConverter with null extensionRegistry");
} }
} }

View File

@ -150,8 +150,9 @@ public class WebAsyncManagerTests {
try { try {
this.asyncManager.startCallableProcessing(task); this.asyncManager.startCallableProcessing(task);
fail("Expected Exception"); fail("Expected Exception");
}catch(Exception e) { }
assertEquals(exception, e); catch (Exception ex) {
assertEquals(exception, ex);
} }
assertFalse(this.asyncManager.hasConcurrentResult()); assertFalse(this.asyncManager.hasConcurrentResult());
@ -162,7 +163,6 @@ public class WebAsyncManagerTests {
@Test @Test
public void startCallableProcessingPreProcessException() throws Exception { public void startCallableProcessingPreProcessException() throws Exception {
Callable<Object> task = new StubCallable(21); Callable<Object> task = new StubCallable(21);
Exception exception = new Exception(); Exception exception = new Exception();
@ -183,7 +183,6 @@ public class WebAsyncManagerTests {
@Test @Test
public void startCallableProcessingPostProcessException() throws Exception { public void startCallableProcessingPostProcessException() throws Exception {
Callable<Object> task = new StubCallable(21); Callable<Object> task = new StubCallable(21);
Exception exception = new Exception(); Exception exception = new Exception();
@ -205,7 +204,6 @@ public class WebAsyncManagerTests {
@Test @Test
public void startCallableProcessingPostProcessContinueAfterException() throws Exception { public void startCallableProcessingPostProcessContinueAfterException() throws Exception {
Callable<Object> task = new StubCallable(21); Callable<Object> task = new StubCallable(21);
Exception exception = new Exception(); Exception exception = new Exception();
@ -231,7 +229,6 @@ public class WebAsyncManagerTests {
@Test @Test
public void startCallableProcessingWithAsyncTask() throws Exception { public void startCallableProcessingWithAsyncTask() throws Exception {
AsyncTaskExecutor executor = mock(AsyncTaskExecutor.class); AsyncTaskExecutor executor = mock(AsyncTaskExecutor.class);
given(this.asyncWebRequest.getNativeRequest(HttpServletRequest.class)).willReturn(this.servletRequest); given(this.asyncWebRequest.getNativeRequest(HttpServletRequest.class)).willReturn(this.servletRequest);
@ -259,7 +256,6 @@ public class WebAsyncManagerTests {
@Test @Test
public void startDeferredResultProcessing() throws Exception { public void startDeferredResultProcessing() throws Exception {
DeferredResult<String> deferredResult = new DeferredResult<String>(1000L); DeferredResult<String> deferredResult = new DeferredResult<String>(1000L);
String concurrentResult = "abc"; String concurrentResult = "abc";
@ -282,7 +278,6 @@ public class WebAsyncManagerTests {
@Test @Test
public void startDeferredResultProcessingBeforeConcurrentHandlingException() throws Exception { public void startDeferredResultProcessingBeforeConcurrentHandlingException() throws Exception {
DeferredResult<Integer> deferredResult = new DeferredResult<Integer>(); DeferredResult<Integer> deferredResult = new DeferredResult<Integer>();
Exception exception = new Exception(); Exception exception = new Exception();
@ -295,7 +290,7 @@ public class WebAsyncManagerTests {
this.asyncManager.startDeferredResultProcessing(deferredResult); this.asyncManager.startDeferredResultProcessing(deferredResult);
fail("Expected Exception"); fail("Expected Exception");
} }
catch(Exception success) { catch (Exception success) {
assertEquals(exception, success); assertEquals(exception, success);
} }
@ -328,7 +323,6 @@ public class WebAsyncManagerTests {
@Test @Test
public void startDeferredResultProcessingPostProcessException() throws Exception { public void startDeferredResultProcessingPostProcessException() throws Exception {
DeferredResult<Integer> deferredResult = new DeferredResult<Integer>(); DeferredResult<Integer> deferredResult = new DeferredResult<Integer>();
Exception exception = new Exception(); Exception exception = new Exception();
@ -371,6 +365,7 @@ public class WebAsyncManagerTests {
verify(this.asyncWebRequest).dispatch(); verify(this.asyncWebRequest).dispatch();
} }
private final class StubCallable implements Callable<Object> { private final class StubCallable implements Callable<Object> {
private Object value; private Object value;
@ -388,6 +383,7 @@ public class WebAsyncManagerTests {
} }
} }
@SuppressWarnings("serial") @SuppressWarnings("serial")
private static class SyncTaskExecutor extends SimpleAsyncTaskExecutor { private static class SyncTaskExecutor extends SimpleAsyncTaskExecutor {

View File

@ -49,7 +49,8 @@ public class Spr8510Tests {
try { try {
cll.contextInitialized(new ServletContextEvent(sc)); cll.contextInitialized(new ServletContextEvent(sc));
fail("expected exception"); fail("expected exception");
} catch (Throwable t) { }
catch (Throwable t) {
// assert that an attempt was made to load the correct XML // assert that an attempt was made to load the correct XML
assertTrue(t.getMessage(), t.getMessage().endsWith( assertTrue(t.getMessage(), t.getMessage().endsWith(
"Could not open ServletContext resource [/programmatic.xml]")); "Could not open ServletContext resource [/programmatic.xml]"));
@ -75,7 +76,8 @@ public class Spr8510Tests {
try { try {
cll.contextInitialized(new ServletContextEvent(sc)); cll.contextInitialized(new ServletContextEvent(sc));
fail("expected exception"); fail("expected exception");
} catch (Throwable t) { }
catch (Throwable t) {
// assert that an attempt was made to load the correct XML // assert that an attempt was made to load the correct XML
assertTrue(t.getMessage(), t.getMessage().endsWith( assertTrue(t.getMessage(), t.getMessage().endsWith(
"Could not open ServletContext resource [/from-init-param.xml]")); "Could not open ServletContext resource [/from-init-param.xml]"));
@ -98,7 +100,8 @@ public class Spr8510Tests {
try { try {
cll.contextInitialized(new ServletContextEvent(sc)); cll.contextInitialized(new ServletContextEvent(sc));
fail("expected exception"); fail("expected exception");
} catch (Throwable t) { }
catch (Throwable t) {
// assert that an attempt was made to load the correct XML // assert that an attempt was made to load the correct XML
assertTrue(t.getMessage().endsWith( assertTrue(t.getMessage().endsWith(
"Could not open ServletContext resource [/from-init-param.xml]")); "Could not open ServletContext resource [/from-init-param.xml]"));
@ -125,7 +128,8 @@ public class Spr8510Tests {
try { try {
cll.contextInitialized(new ServletContextEvent(sc)); cll.contextInitialized(new ServletContextEvent(sc));
fail("expected exception"); fail("expected exception");
} catch (Throwable t) { }
catch (Throwable t) {
// assert that an attempt was made to load the correct XML // assert that an attempt was made to load the correct XML
System.out.println(t.getMessage()); System.out.println(t.getMessage());
assertTrue(t.getMessage().endsWith( assertTrue(t.getMessage().endsWith(
@ -150,7 +154,8 @@ public class Spr8510Tests {
try { try {
cll.contextInitialized(new ServletContextEvent(sc)); cll.contextInitialized(new ServletContextEvent(sc));
fail("expected exception"); fail("expected exception");
} catch (Throwable t) { }
catch (Throwable t) {
// assert that an attempt was made to load the correct XML // assert that an attempt was made to load the correct XML
System.out.println(t.getMessage()); System.out.println(t.getMessage());
assertTrue(t.getMessage().endsWith( assertTrue(t.getMessage().endsWith(

View File

@ -101,7 +101,8 @@ public class Log4jWebConfigurerTests {
try { try {
assertLogOutput(); assertLogOutput();
} finally { }
finally {
Log4jWebConfigurer.shutdownLogging(sc); Log4jWebConfigurer.shutdownLogging(sc);
} }
assertTrue(MockLog4jAppender.closeCalled); assertTrue(MockLog4jAppender.closeCalled);
@ -132,7 +133,8 @@ public class Log4jWebConfigurerTests {
try { try {
assertLogOutput(); assertLogOutput();
} finally { }
finally {
listener.contextDestroyed(new ServletContextEvent(sc)); listener.contextDestroyed(new ServletContextEvent(sc));
} }
assertTrue(MockLog4jAppender.closeCalled); assertTrue(MockLog4jAppender.closeCalled);

View File

@ -58,7 +58,7 @@ public class XmlPortletApplicationContextTests extends AbstractXmlWebApplication
beanFactory.addBeanPostProcessor(new BeanPostProcessor() { beanFactory.addBeanPostProcessor(new BeanPostProcessor() {
@Override @Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if(bean instanceof TestBean) { if (bean instanceof TestBean) {
((TestBean) bean).getFriends().add("myFriend"); ((TestBean) bean).getFriends().add("myFriend");
} }
return bean; return bean;

View File

@ -162,9 +162,11 @@ public final class PortletWrappingControllerTests {
public void processAction(ActionRequest request, ActionResponse response) throws PortletException { public void processAction(ActionRequest request, ActionResponse response) throws PortletException {
if (request.getParameter("test") != null) { if (request.getParameter("test") != null) {
response.setRenderParameter(RESULT_RENDER_PARAMETER_NAME, "myPortlet-action"); response.setRenderParameter(RESULT_RENDER_PARAMETER_NAME, "myPortlet-action");
} else if (request.getParameter(PORTLET_NAME_ACTION_REQUEST_PARAMETER_NAME) != null) { }
else if (request.getParameter(PORTLET_NAME_ACTION_REQUEST_PARAMETER_NAME) != null) {
response.setRenderParameter(RESULT_RENDER_PARAMETER_NAME, getPortletConfig().getPortletName()); response.setRenderParameter(RESULT_RENDER_PARAMETER_NAME, getPortletConfig().getPortletName());
} else { }
else {
throw new IllegalArgumentException("no request parameters"); throw new IllegalArgumentException("no request parameters");
} }
} }

View File

@ -435,12 +435,13 @@ public final class PortletUtilsTests {
public void testGetRequiredSessionAttributeWithExistingSessionAndNoAttribute() throws Exception { public void testGetRequiredSessionAttributeWithExistingSessionAndNoAttribute() throws Exception {
MockPortletSession session = new MockPortletSession(); MockPortletSession session = new MockPortletSession();
final PortletRequest request = mock(PortletRequest.class); PortletRequest request = mock(PortletRequest.class);
given(request.getPortletSession(false)).willReturn(session); given(request.getPortletSession(false)).willReturn(session);
try { try {
PortletUtils.getRequiredSessionAttribute(request, "foo"); PortletUtils.getRequiredSessionAttribute(request, "foo");
fail("expected IllegalStateException"); fail("expected IllegalStateException");
} catch (IllegalStateException ex) { /* expected */ } }
catch (IllegalStateException ex) { /* expected */ }
} }

View File

@ -224,7 +224,7 @@ public class ResourceHttpRequestHandler extends WebContentGenerator
if (this.contentNegotiationManager == null) { if (this.contentNegotiationManager == null) {
this.contentNegotiationManager = initContentNegotiationManager(); this.contentNegotiationManager = initContentNegotiationManager();
} }
if( this.resourceHttpMessageConverter == null) { if ( this.resourceHttpMessageConverter == null) {
this.resourceHttpMessageConverter = new ResourceHttpMessageConverter(); this.resourceHttpMessageConverter = new ResourceHttpMessageConverter();
} }
} }
@ -486,7 +486,7 @@ public class ResourceHttpRequestHandler extends WebContentGenerator
ServletWebRequest webRequest = new ServletWebRequest(request); ServletWebRequest webRequest = new ServletWebRequest(request);
try { try {
List<MediaType> mediaTypes = getContentNegotiationManager().resolveMediaTypes(webRequest); List<MediaType> mediaTypes = getContentNegotiationManager().resolveMediaTypes(webRequest);
if(!mediaTypes.isEmpty()) { if (!mediaTypes.isEmpty()) {
mediaType = mediaTypes.get(0); mediaType = mediaTypes.get(0);
} }
} }

View File

@ -218,7 +218,7 @@ public class ResourceUrlProvider implements ApplicationListener<ContextRefreshed
if (!matchingPatterns.isEmpty()) { if (!matchingPatterns.isEmpty()) {
Comparator<String> patternComparator = getPathMatcher().getPatternComparator(lookupPath); Comparator<String> patternComparator = getPathMatcher().getPatternComparator(lookupPath);
Collections.sort(matchingPatterns, patternComparator); Collections.sort(matchingPatterns, patternComparator);
for(String pattern : matchingPatterns) { for (String pattern : matchingPatterns) {
String pathWithinMapping = getPathMatcher().extractPathWithinPattern(pattern, lookupPath); String pathWithinMapping = getPathMatcher().extractPathWithinPattern(pattern, lookupPath);
String pathMapping = lookupPath.substring(0, lookupPath.indexOf(pathWithinMapping)); String pathMapping = lookupPath.substring(0, lookupPath.indexOf(pathWithinMapping));
if (logger.isTraceEnabled()) { if (logger.isTraceEnabled()) {

View File

@ -123,9 +123,9 @@ public class VersionResourceResolver extends AbstractResourceResolver {
List<String> patternsList = Arrays.asList(pathPatterns); List<String> patternsList = Arrays.asList(pathPatterns);
List<String> prefixedPatterns = new ArrayList<String>(pathPatterns.length); List<String> prefixedPatterns = new ArrayList<String>(pathPatterns.length);
String versionPrefix = "/" + version; String versionPrefix = "/" + version;
for(String pattern : patternsList) { for (String pattern : patternsList) {
prefixedPatterns.add(pattern); prefixedPatterns.add(pattern);
if(!pattern.startsWith(versionPrefix) && !patternsList.contains(versionPrefix + pattern)) { if (!pattern.startsWith(versionPrefix) && !patternsList.contains(versionPrefix + pattern)) {
prefixedPatterns.add(versionPrefix + pattern); prefixedPatterns.add(versionPrefix + pattern);
} }
} }

View File

@ -176,7 +176,8 @@ public class AnnotationDrivenBeanDefinitionParserTests {
List<HttpMessageConverter<?>> converters = (List<HttpMessageConverter<?>>) value; List<HttpMessageConverter<?>> converters = (List<HttpMessageConverter<?>>) value;
if (hasDefaultRegistrations) { if (hasDefaultRegistrations) {
assertTrue("Default and custom converter expected", converters.size() > 2); assertTrue("Default and custom converter expected", converters.size() > 2);
} else { }
else {
assertTrue("Only custom converters expected", converters.size() == 2); assertTrue("Only custom converters expected", converters.size() == 2);
} }
assertTrue(converters.get(0) instanceof StringHttpMessageConverter); assertTrue(converters.get(0) instanceof StringHttpMessageConverter);

View File

@ -181,7 +181,7 @@ public class FlashMapManagerTests {
@Test @Test
public void retrieveAndUpdateRemoveExpired() throws InterruptedException { public void retrieveAndUpdateRemoveExpired() throws InterruptedException {
List<FlashMap> flashMaps = new ArrayList<FlashMap>(); List<FlashMap> flashMaps = new ArrayList<FlashMap>();
for (int i=0; i < 5; i++) { for (int i = 0; i < 5; i++) {
FlashMap expiredFlashMap = new FlashMap(); FlashMap expiredFlashMap = new FlashMap();
expiredFlashMap.startExpirationPeriod(-1); expiredFlashMap.startExpirationPeriod(-1);
flashMaps.add(expiredFlashMap); flashMaps.add(expiredFlashMap);

View File

@ -465,7 +465,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
tag.setValue("foo"); tag.setValue("foo");
tag.doStartTag(); tag.doStartTag();
fail("Must throw an IllegalStateException when not nested within a <select/> tag."); fail("Must throw an IllegalStateException when not nested within a <select/> tag.");
} catch (IllegalStateException ex) { }
catch (IllegalStateException ex) {
// expected // expected
} }
} }
@ -542,7 +543,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
public String toId() { public String toId() {
if (this.variant != null) { if (this.variant != null) {
return this.rules + "-" + this.variant; return this.rules + "-" + this.variant;
} else { }
else {
return rules; return rules;
} }
} }

View File

@ -100,7 +100,8 @@ public class PasswordInputTagTests extends InputTagTests {
protected void assertValueAttribute(String output, String expectedValue) { protected void assertValueAttribute(String output, String expectedValue) {
if (this.getPasswordTag().isShowPassword()) { if (this.getPasswordTag().isShowPassword()) {
super.assertValueAttribute(output, expectedValue); super.assertValueAttribute(output, expectedValue);
} else { }
else {
super.assertValueAttribute(output, ""); super.assertValueAttribute(output, "");
} }
} }

View File

@ -147,11 +147,11 @@ public class ScriptTemplateViewTests {
this.view.setApplicationContext(this.wac); this.view.setApplicationContext(this.wac);
ExecutorService executor = Executors.newFixedThreadPool(4); ExecutorService executor = Executors.newFixedThreadPool(4);
List<Future<Boolean>> results = new ArrayList<>(); List<Future<Boolean>> results = new ArrayList<>();
for(int i = 0; i < iterations; i++) { for (int i = 0; i < iterations; i++) {
results.add(executor.submit(() -> view.getEngine() != null)); results.add(executor.submit(() -> view.getEngine() != null));
} }
assertEquals(iterations, results.size()); assertEquals(iterations, results.size());
for(int i = 0; i < iterations; i++) { for (int i = 0; i < iterations; i++) {
assertTrue(results.get(i).get()); assertTrue(results.get(i).get());
} }
executor.shutdown(); executor.shutdown();

View File

@ -32,7 +32,7 @@ public abstract class AbstractSockJsMessageCodec implements SockJsMessageCodec {
Assert.notNull(messages, "messages must not be null"); Assert.notNull(messages, "messages must not be null");
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("a["); sb.append("a[");
for (int i=0; i < messages.length; i++) { for (int i = 0; i < messages.length; i++) {
sb.append('"'); sb.append('"');
char[] quotedChars = applyJsonQuoting(messages[i]); char[] quotedChars = applyJsonQuoting(messages[i]);
sb.append(escapeSockJsSpecialChars(quotedChars)); sb.append(escapeSockJsSpecialChars(quotedChars));

View File

@ -38,7 +38,8 @@ public class ContextLoaderTestUtils {
public static void setCurrentWebApplicationContext(ClassLoader classLoader, WebApplicationContext applicationContext) { public static void setCurrentWebApplicationContext(ClassLoader classLoader, WebApplicationContext applicationContext) {
if (applicationContext != null) { if (applicationContext != null) {
currentContextPerThread.put(classLoader, applicationContext); currentContextPerThread.put(classLoader, applicationContext);
} else { }
else {
currentContextPerThread.remove(classLoader); currentContextPerThread.remove(classLoader);
} }
} }

View File

@ -88,7 +88,7 @@ public class ConcurrentWebSocketSessionDecoratorTests {
assertTrue(concurrentSession.getTimeSinceSendStarted() > 0); assertTrue(concurrentSession.getTimeSinceSendStarted() > 0);
TextMessage payload = new TextMessage("payload"); TextMessage payload = new TextMessage("payload");
for (int i=0; i < 5; i++) { for (int i = 0; i < 5; i++) {
concurrentSession.sendMessage(payload); concurrentSession.sendMessage(payload);
} }
@ -166,7 +166,7 @@ public class ConcurrentWebSocketSessionDecoratorTests {
assertTrue(sentMessageLatch.await(5, TimeUnit.SECONDS)); assertTrue(sentMessageLatch.await(5, TimeUnit.SECONDS));
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (int i=0 ; i < 1023; i++) { for (int i = 0 ; i < 1023; i++) {
sb.append("a"); sb.append("a");
} }

View File

@ -91,7 +91,7 @@ public class RestTemplateXhrTransportTests {
@Test @Test
public void connectReceiveAndCloseWithPrelude() throws Exception { public void connectReceiveAndCloseWithPrelude() throws Exception {
StringBuilder sb = new StringBuilder(2048); StringBuilder sb = new StringBuilder(2048);
for (int i=0; i < 2048; i++) { for (int i = 0; i < 2048; i++) {
sb.append('h'); sb.append('h');
} }
String body = sb.toString() + "\n" + "o\n" + "a[\"foo\"]\n" + "c[3000,\"Go away!\"]"; String body = sb.toString() + "\n" + "o\n" + "a[\"foo\"]\n" + "c[3000,\"Go away!\"]";

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