language
stringclasses
1 value
owner
stringlengths
2
15
repo
stringlengths
2
21
sha
stringlengths
45
45
message
stringlengths
7
36.3k
path
stringlengths
1
199
patch
stringlengths
15
102k
is_multipart
bool
2 classes
Other
spring-projects
spring-framework
461d99af29e8c358ff80ff9ff58a8ea63fe7b670.json
Fix package cycles in spring-test Code introduced in conjunction with SPR-5243 introduced package cycles between the ~.test.context and ~.test.context.web packages. This was caused by the fact that ContextLoaderUtils worked directly with the @WebAppConfiguration and WebMergedContextConfiguration types. To address this, the following methods have been introduced in ContextLoaderUtils. These methods use reflection to circumvent hard dependencies on the @WebAppConfiguration and WebMergedContextConfiguration types. - loadWebAppConfigurationClass() - buildWebMergedContextConfiguration() Issue: SPR-9924
spring-test/src/main/java/org/springframework/test/context/web/ServletTestExecutionListener.java
@@ -48,7 +48,7 @@ public class ServletTestExecutionListener implements TestExecutionListener { * The default implementation is <em>empty</em>. Can be overridden by * subclasses as necessary. * - * @see org.springframework.test.context.TestExecutionListener#beforeTestClass(TestContext) + * @see TestExecutionListener#beforeTestClass(TestContext) */ public void beforeTestClass(TestContext testContext) throws Exception { /* no-op */ @@ -57,7 +57,7 @@ public void beforeTestClass(TestContext testContext) throws Exception { /** * TODO [SPR-9864] Document overridden prepareTestInstance(). * - * @see org.springframework.test.context.TestExecutionListener#prepareTestInstance(TestContext) + * @see TestExecutionListener#prepareTestInstance(TestContext) */ public void prepareTestInstance(TestContext testContext) throws Exception { setUpRequestContextIfNecessary(testContext); @@ -66,7 +66,7 @@ public void prepareTestInstance(TestContext testContext) throws Exception { /** * TODO [SPR-9864] Document overridden beforeTestMethod(). * - * @see org.springframework.test.context.TestExecutionListener#beforeTestMethod(TestContext) + * @see TestExecutionListener#beforeTestMethod(TestContext) */ public void beforeTestMethod(TestContext testContext) throws Exception { setUpRequestContextIfNecessary(testContext); @@ -75,7 +75,7 @@ public void beforeTestMethod(TestContext testContext) throws Exception { /** * TODO [SPR-9864] Document overridden afterTestMethod(). * - * @see org.springframework.test.context.TestExecutionListener#afterTestMethod(TestContext) + * @see TestExecutionListener#afterTestMethod(TestContext) */ public void afterTestMethod(TestContext testContext) throws Exception { if (logger.isDebugEnabled()) { @@ -88,7 +88,7 @@ public void afterTestMethod(TestContext testContext) throws Exception { * The default implementation is <em>empty</em>. Can be overridden by * subclasses as necessary. * - * @see org.springframework.test.context.TestExecutionListener#afterTestClass(TestContext) + * @see TestExecutionListener#afterTestClass(TestContext) */ public void afterTestClass(TestContext testContext) throws Exception { /* no-op */
true
Other
spring-projects
spring-framework
33d5b011d3e6e85767e910896f5dacf5930eb08a.json
Reduce code duplication in ContextLoaderUtils Prior to this commit, the following two methods in ContextLoaderUtils contained almost identical loops for traversing the test class hierarchy: - resolveContextLoaderClass(Class<?>, String) - resolveContextConfigurationAttributes(Class<?>) With this commit, resolveContextLoaderClass() no longer traverses the class hierarchy. Instead, it now works directly with the resolved list of ContextConfigurationAttributes, thereby removing code duplication. Issue: SPR-9918
spring-test/src/main/java/org/springframework/test/context/ContextLoaderUtils.java
@@ -21,7 +21,6 @@ import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -64,58 +63,70 @@ private ContextLoaderUtils() { } /** - * Resolve the {@link ContextLoader} {@link Class class} to use for the - * supplied {@link Class testClass} and then instantiate and return that - * {@code ContextLoader}. + * Resolve the {@link ContextLoader} {@linkplain Class class} to use for the + * supplied list of {@link ContextConfigurationAttributes} and then + * instantiate and return that {@code ContextLoader}. * * <p>If the supplied <code>defaultContextLoaderClassName</code> is - * <code>null</code> or <em>empty</em>, the <em>standard</em> - * default context loader class name {@value #DEFAULT_CONTEXT_LOADER_CLASS_NAME} - * will be used. For details on the class resolution process, see - * {@link #resolveContextLoaderClass()}. + * {@code null} or <em>empty</em>, depending on the absence or presence + * of @{@link WebAppConfiguration} either {@value #DEFAULT_CONTEXT_LOADER_CLASS_NAME} + * or {@value #DEFAULT_WEB_CONTEXT_LOADER_CLASS_NAME} will be used as the + * default context loader class name. For details on the class resolution + * process, see {@link #resolveContextLoaderClass()}. * * @param testClass the test class for which the {@code ContextLoader} - * should be resolved (must not be <code>null</code>) + * should be resolved; must not be {@code null} + * @param configAttributesList the list of configuration attributes to process; + * must not be {@code null} or <em>empty</em>; must be ordered <em>bottom-up</em> + * (i.e., as if we were traversing up the class hierarchy) * @param defaultContextLoaderClassName the name of the default - * {@code ContextLoader} class to use (may be <code>null</code>) + * {@code ContextLoader} class to use; may be {@code null} or <em>empty</em> * @return the resolved {@code ContextLoader} for the supplied - * <code>testClass</code> (never <code>null</code>) + * <code>testClass</code> (never {@code null}) * @see #resolveContextLoaderClass() */ - static ContextLoader resolveContextLoader(Class<?> testClass, String defaultContextLoaderClassName) { - Assert.notNull(testClass, "Test class must not be null"); + static ContextLoader resolveContextLoader(Class<?> testClass, + List<ContextConfigurationAttributes> configAttributesList, String defaultContextLoaderClassName) { + Assert.notNull(testClass, "Class must not be null"); + Assert.notEmpty(configAttributesList, "ContextConfigurationAttributes list must not be empty"); if (!StringUtils.hasText(defaultContextLoaderClassName)) { defaultContextLoaderClassName = testClass.isAnnotationPresent(WebAppConfiguration.class) ? DEFAULT_WEB_CONTEXT_LOADER_CLASS_NAME : DEFAULT_CONTEXT_LOADER_CLASS_NAME; } - Class<? extends ContextLoader> contextLoaderClass = resolveContextLoaderClass(testClass, + Class<? extends ContextLoader> contextLoaderClass = resolveContextLoaderClass(testClass, configAttributesList, defaultContextLoaderClassName); return instantiateClass(contextLoaderClass, ContextLoader.class); } /** - * Resolve the {@link ContextLoader} {@link Class} to use for the supplied - * {@link Class testClass}. + * Resolve the {@link ContextLoader} {@linkplain Class class} to use for the + * supplied list of {@link ContextConfigurationAttributes}. + * + * <p>Beginning with the first level in the context configuration attributes + * hierarchy: * * <ol> - * <li>If the {@link ContextConfiguration#loader() loader} attribute of - * {@link ContextConfiguration &#064;ContextConfiguration} is configured - * with an explicit class, that class will be returned.</li> - * <li>If a <code>loader</code> class is not specified, the class hierarchy - * will be traversed to find a parent class annotated with - * {@code @ContextConfiguration}; go to step #1.</li> - * <li>If no explicit <code>loader</code> class is found after traversing - * the class hierarchy, an attempt will be made to load and return the class + * <li>If the {@link ContextConfigurationAttributes#getContextLoaderClass() + * contextLoaderClass} property of {@link ContextConfigurationAttributes} is + * configured with an explicit class, that class will be returned.</li> + * <li>If an explicit {@code ContextLoader} class is not specified at the + * current level in the hierarchy, traverse to the next level in the hierarchy + * and return to step #1.</li> + * <li>If no explicit {@code ContextLoader} class is found after traversing + * the hierarchy, an attempt will be made to load and return the class * with the supplied <code>defaultContextLoaderClassName</code>.</li> * </ol> * * @param testClass the class for which to resolve the {@code ContextLoader} - * class; must not be <code>null</code> + * class; must not be {@code null}; only used for logging purposes + * @param configAttributesList the list of configuration attributes to process; + * must not be {@code null} or <em>empty</em>; must be ordered <em>bottom-up</em> + * (i.e., as if we were traversing up the class hierarchy) * @param defaultContextLoaderClassName the name of the default - * {@code ContextLoader} class to use; must not be <code>null</code> or empty + * {@code ContextLoader} class to use; must not be {@code null} or empty * @return the {@code ContextLoader} class to use for the supplied test class * @throws IllegalArgumentException if {@code @ContextConfiguration} is not * <em>present</em> on the supplied test class @@ -124,46 +135,37 @@ static ContextLoader resolveContextLoader(Class<?> testClass, String defaultCont */ @SuppressWarnings("unchecked") static Class<? extends ContextLoader> resolveContextLoaderClass(Class<?> testClass, - String defaultContextLoaderClassName) { + List<ContextConfigurationAttributes> configAttributesList, String defaultContextLoaderClassName) { Assert.notNull(testClass, "Class must not be null"); + Assert.notEmpty(configAttributesList, "ContextConfigurationAttributes list must not be empty"); Assert.hasText(defaultContextLoaderClassName, "Default ContextLoader class name must not be null or empty"); - Class<ContextConfiguration> annotationType = ContextConfiguration.class; - Class<?> declaringClass = findAnnotationDeclaringClass(annotationType, testClass); - Assert.notNull(declaringClass, String.format( - "Could not find an 'annotation declaring class' for annotation type [%s] and test class [%s]", - annotationType, testClass)); - - while (declaringClass != null) { - ContextConfiguration contextConfiguration = declaringClass.getAnnotation(annotationType); - + for (ContextConfigurationAttributes configAttributes : configAttributesList) { if (logger.isTraceEnabled()) { - logger.trace(String.format( - "Processing ContextLoader for @ContextConfiguration [%s] and declaring class [%s]", - contextConfiguration, declaringClass)); + logger.trace(String.format("Processing ContextLoader for context configuration attributes %s", + configAttributes)); } - Class<? extends ContextLoader> contextLoaderClass = contextConfiguration.loader(); + Class<? extends ContextLoader> contextLoaderClass = configAttributes.getContextLoaderClass(); if (!ContextLoader.class.equals(contextLoaderClass)) { if (logger.isDebugEnabled()) { logger.debug(String.format( - "Found explicit ContextLoader class [%s] for @ContextConfiguration [%s] and declaring class [%s]", - contextLoaderClass, contextConfiguration, declaringClass)); + "Found explicit ContextLoader class [%s] for context configuration attributes %s", + contextLoaderClass.getName(), configAttributes)); } return contextLoaderClass; } - - declaringClass = findAnnotationDeclaringClass(annotationType, declaringClass.getSuperclass()); } try { if (logger.isTraceEnabled()) { logger.trace(String.format("Using default ContextLoader class [%s] for test class [%s]", - defaultContextLoaderClassName, testClass)); + defaultContextLoaderClassName, testClass.getName())); } return (Class<? extends ContextLoader>) ContextLoaderUtils.class.getClassLoader().loadClass( defaultContextLoaderClassName); - } catch (ClassNotFoundException ex) { + } + catch (ClassNotFoundException ex) { throw new IllegalStateException("Could not load default ContextLoader class [" + defaultContextLoaderClassName + "]. Specify @ContextConfiguration's 'loader' " + "attribute or make the default loader class available."); @@ -181,30 +183,29 @@ static Class<? extends ContextLoader> resolveContextLoaderClass(Class<?> testCla * consideration. If these flags need to be honored, that must be handled * manually when traversing the list returned by this method. * - * @param clazz the class for which to resolve the configuration attributes (must - * not be <code>null</code>) - * @return the list of configuration attributes for the specified class - * (never <code>null</code>) - * @throws IllegalArgumentException if the supplied class is <code>null</code> or + * @param testClass the class for which to resolve the configuration attributes (must + * not be {@code null}) + * @return the list of configuration attributes for the specified class, ordered <em>bottom-up</em> + * (i.e., as if we were traversing up the class hierarchy); never {@code null} + * @throws IllegalArgumentException if the supplied class is {@code null} or * if {@code @ContextConfiguration} is not <em>present</em> on the supplied class */ - static List<ContextConfigurationAttributes> resolveContextConfigurationAttributes(Class<?> clazz) { - Assert.notNull(clazz, "Class must not be null"); + static List<ContextConfigurationAttributes> resolveContextConfigurationAttributes(Class<?> testClass) { + Assert.notNull(testClass, "Class must not be null"); final List<ContextConfigurationAttributes> attributesList = new ArrayList<ContextConfigurationAttributes>(); Class<ContextConfiguration> annotationType = ContextConfiguration.class; - Class<?> declaringClass = findAnnotationDeclaringClass(annotationType, clazz); + Class<?> declaringClass = findAnnotationDeclaringClass(annotationType, testClass); Assert.notNull(declaringClass, String.format( - "Could not find an 'annotation declaring class' for annotation type [%s] and class [%s]", annotationType, - clazz)); + "Could not find an 'annotation declaring class' for annotation type [%s] and class [%s]", + annotationType.getName(), testClass.getName())); while (declaringClass != null) { ContextConfiguration contextConfiguration = declaringClass.getAnnotation(annotationType); - if (logger.isTraceEnabled()) { logger.trace(String.format("Retrieved @ContextConfiguration [%s] for declaring class [%s].", - contextConfiguration, declaringClass)); + contextConfiguration, declaringClass.getName())); } ContextConfigurationAttributes attributes = new ContextConfigurationAttributes(declaringClass, @@ -213,28 +214,14 @@ static List<ContextConfigurationAttributes> resolveContextConfigurationAttribute logger.trace("Resolved context configuration attributes: " + attributes); } - attributesList.add(0, attributes); + attributesList.add(attributes); declaringClass = findAnnotationDeclaringClass(annotationType, declaringClass.getSuperclass()); } return attributesList; } - /** - * Create a copy of the supplied list of {@code ContextConfigurationAttributes} - * in reverse order. - * - * @since 3.2 - */ - private static List<ContextConfigurationAttributes> reverseContextConfigurationAttributes( - List<ContextConfigurationAttributes> configAttributesList) { - List<ContextConfigurationAttributes> configAttributesListReversed = new ArrayList<ContextConfigurationAttributes>( - configAttributesList); - Collections.reverse(configAttributesListReversed); - return configAttributesListReversed; - } - /** * Resolve the list of merged {@code ApplicationContextInitializer} classes * for the supplied list of {@code ContextConfigurationAttributes}. @@ -247,22 +234,21 @@ private static List<ContextConfigurationAttributes> reverseContextConfigurationA * at the given level will be merged with those defined in higher levels * of the class hierarchy. * - * @param configAttributesList the list of configuration attributes to process - * (must not be <code>null</code>) - * @return the list of merged context initializer classes, including those - * from superclasses if appropriate (never <code>null</code>) + * @param configAttributesList the list of configuration attributes to process; + * must not be {@code null} or <em>empty</em>; must be ordered <em>bottom-up</em> + * (i.e., as if we were traversing up the class hierarchy) + * @return the set of merged context initializer classes, including those + * from superclasses if appropriate (never {@code null}) * @since 3.2 */ static Set<Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>> resolveInitializerClasses( List<ContextConfigurationAttributes> configAttributesList) { - Assert.notNull(configAttributesList, "configAttributesList must not be null"); + Assert.notEmpty(configAttributesList, "ContextConfigurationAttributes list must not be empty"); final Set<Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>> initializerClasses = // new HashSet<Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>>(); - // Traverse config attributes in reverse order (i.e., as if we were traversing up - // the class hierarchy). - for (ContextConfigurationAttributes configAttributes : reverseContextConfigurationAttributes(configAttributesList)) { + for (ContextConfigurationAttributes configAttributes : configAttributesList) { if (logger.isTraceEnabled()) { logger.trace(String.format("Processing context initializers for context configuration attributes %s", configAttributes)); @@ -287,23 +273,23 @@ static Set<Class<? extends ApplicationContextInitializer<? extends ConfigurableA * set to <code>true</code>, profiles defined in the test class will be * merged with those defined in superclasses. * - * @param clazz the class for which to resolve the active profiles (must - * not be <code>null</code>) + * @param testClass the class for which to resolve the active profiles (must + * not be {@code null}) * @return the set of active profiles for the specified class, including - * active profiles from superclasses if appropriate (never <code>null</code>) + * active profiles from superclasses if appropriate (never {@code null}) * @see org.springframework.test.context.ActiveProfiles * @see org.springframework.context.annotation.Profile */ - static String[] resolveActiveProfiles(Class<?> clazz) { - Assert.notNull(clazz, "Class must not be null"); + static String[] resolveActiveProfiles(Class<?> testClass) { + Assert.notNull(testClass, "Class must not be null"); Class<ActiveProfiles> annotationType = ActiveProfiles.class; - Class<?> declaringClass = findAnnotationDeclaringClass(annotationType, clazz); + Class<?> declaringClass = findAnnotationDeclaringClass(annotationType, testClass); if (declaringClass == null && logger.isDebugEnabled()) { logger.debug(String.format( "Could not find an 'annotation declaring class' for annotation type [%s] and class [%s]", - annotationType, clazz)); + annotationType.getName(), testClass.getName())); } final Set<String> activeProfiles = new HashSet<String>(); @@ -313,7 +299,7 @@ static String[] resolveActiveProfiles(Class<?> clazz) { if (logger.isTraceEnabled()) { logger.trace(String.format("Retrieved @ActiveProfiles [%s] for declaring class [%s].", annotation, - declaringClass)); + declaringClass.getName())); } String[] profiles = annotation.profiles(); @@ -322,11 +308,12 @@ static String[] resolveActiveProfiles(Class<?> clazz) { if (!ObjectUtils.isEmpty(valueProfiles) && !ObjectUtils.isEmpty(profiles)) { String msg = String.format("Test class [%s] has been configured with @ActiveProfiles' 'value' [%s] " + "and 'profiles' [%s] attributes. Only one declaration of active bean " - + "definition profiles is permitted per @ActiveProfiles annotation.", declaringClass, + + "definition profiles is permitted per @ActiveProfiles annotation.", declaringClass.getName(), ObjectUtils.nullSafeToString(valueProfiles), ObjectUtils.nullSafeToString(profiles)); logger.error(msg); throw new IllegalStateException(msg); - } else if (!ObjectUtils.isEmpty(valueProfiles)) { + } + else if (!ObjectUtils.isEmpty(valueProfiles)) { profiles = valueProfiles; } @@ -349,9 +336,9 @@ static String[] resolveActiveProfiles(Class<?> clazz) { * <code>defaultContextLoaderClassName</code>. * * @param testClass the test class for which the {@code MergedContextConfiguration} - * should be built (must not be <code>null</code>) + * should be built (must not be {@code null}) * @param defaultContextLoaderClassName the name of the default - * {@code ContextLoader} class to use (may be <code>null</code>) + * {@code ContextLoader} class to use (may be {@code null}) * @return the merged context configuration * @see #resolveContextLoader() * @see #resolveContextConfigurationAttributes() @@ -363,14 +350,13 @@ static String[] resolveActiveProfiles(Class<?> clazz) { static MergedContextConfiguration buildMergedContextConfiguration(Class<?> testClass, String defaultContextLoaderClassName) { - final ContextLoader contextLoader = resolveContextLoader(testClass, defaultContextLoaderClassName); final List<ContextConfigurationAttributes> configAttributesList = resolveContextConfigurationAttributes(testClass); + final ContextLoader contextLoader = resolveContextLoader(testClass, configAttributesList, + defaultContextLoaderClassName); final List<String> locationsList = new ArrayList<String>(); final List<Class<?>> classesList = new ArrayList<Class<?>>(); - // Traverse config attributes in reverse order (i.e., as if we were traversing up - // the class hierarchy). - for (ContextConfigurationAttributes configAttributes : reverseContextConfigurationAttributes(configAttributesList)) { + for (ContextConfigurationAttributes configAttributes : configAttributesList) { if (logger.isTraceEnabled()) { logger.trace(String.format("Processing locations and classes for context configuration attributes %s", configAttributes)); @@ -381,7 +367,8 @@ static MergedContextConfiguration buildMergedContextConfiguration(Class<?> testC smartContextLoader.processContextConfiguration(configAttributes); locationsList.addAll(0, Arrays.asList(configAttributes.getLocations())); classesList.addAll(0, Arrays.asList(configAttributes.getClasses())); - } else { + } + else { String[] processedLocations = contextLoader.processLocations(configAttributes.getDeclaringClass(), configAttributes.getLocations()); locationsList.addAll(0, Arrays.asList(processedLocations));
true
Other
spring-projects
spring-framework
33d5b011d3e6e85767e910896f5dacf5930eb08a.json
Reduce code duplication in ContextLoaderUtils Prior to this commit, the following two methods in ContextLoaderUtils contained almost identical loops for traversing the test class hierarchy: - resolveContextLoaderClass(Class<?>, String) - resolveContextConfigurationAttributes(Class<?>) With this commit, resolveContextLoaderClass() no longer traverses the class hierarchy. Instead, it now works directly with the resolved list of ContextConfigurationAttributes, thereby removing code duplication. Issue: SPR-9918
spring-test/src/test/java/org/springframework/test/context/ContextLoaderUtilsTests.java
@@ -16,8 +16,8 @@ package org.springframework.test.context; -import static org.springframework.test.context.ContextLoaderUtils.*; import static org.junit.Assert.*; +import static org.springframework.test.context.ContextLoaderUtils.*; import java.util.Arrays; import java.util.Collections; @@ -140,17 +140,17 @@ public void resolveConfigAttributesWithLocalAndInheritedAnnotationsAndLocations( List<ContextConfigurationAttributes> attributesList = resolveContextConfigurationAttributes(LocationsBar.class); assertNotNull(attributesList); assertEquals(2, attributesList.size()); - assertLocationsFooAttributes(attributesList.get(0)); - assertLocationsBarAttributes(attributesList.get(1)); + assertLocationsBarAttributes(attributesList.get(0)); + assertLocationsFooAttributes(attributesList.get(1)); } @Test public void resolveConfigAttributesWithLocalAndInheritedAnnotationsAndClasses() { List<ContextConfigurationAttributes> attributesList = resolveContextConfigurationAttributes(ClassesBar.class); assertNotNull(attributesList); assertEquals(2, attributesList.size()); - assertClassesFooAttributes(attributesList.get(0)); - assertClassesBarAttributes(attributesList.get(1)); + assertClassesBarAttributes(attributesList.get(0)); + assertClassesFooAttributes(attributesList.get(1)); } @Test(expected = IllegalArgumentException.class)
true
Other
spring-projects
spring-framework
90c5f226b62503b492167bcd87361842f73d18b1.json
Fix package cycles in spring-test Code introduced in conjunction with SPR-5243 introduced package cycles between the ~.test.context.web and ~.test.context.support packages. This was caused by the fact that ServletTestExecutionListener extended AbstractTestExecutionListener. To address this, ServletTestExecutionListener now implements TestExecutionListener directly. Issue: SPR-9924
spring-test/src/main/java/org/springframework/test/context/web/ServletTestExecutionListener.java
@@ -20,14 +20,15 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.TestContext; -import org.springframework.test.context.support.AbstractTestExecutionListener; +import org.springframework.test.context.TestExecutionListener; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletWebRequest; @@ -38,31 +39,61 @@ * @author Sam Brannen * @since 3.2 */ -public class ServletTestExecutionListener extends AbstractTestExecutionListener { +public class ServletTestExecutionListener implements TestExecutionListener { private static final Log logger = LogFactory.getLog(ServletTestExecutionListener.class); + /** + * The default implementation is <em>empty</em>. Can be overridden by + * subclasses as necessary. + * + * @see org.springframework.test.context.TestExecutionListener#beforeTestClass(TestContext) + */ + public void beforeTestClass(TestContext testContext) throws Exception { + /* no-op */ + } + /** * TODO [SPR-9864] Document overridden prepareTestInstance(). * - * @see org.springframework.test.context.support.AbstractTestExecutionListener#prepareTestInstance(org.springframework.test.context.TestContext) + * @see org.springframework.test.context.TestExecutionListener#prepareTestInstance(TestContext) */ - @Override public void prepareTestInstance(TestContext testContext) throws Exception { setUpRequestContextIfNecessary(testContext); } /** * TODO [SPR-9864] Document overridden beforeTestMethod(). * - * @see org.springframework.test.context.support.AbstractTestExecutionListener#beforeTestMethod(org.springframework.test.context.TestContext) + * @see org.springframework.test.context.TestExecutionListener#beforeTestMethod(TestContext) */ - @Override public void beforeTestMethod(TestContext testContext) throws Exception { setUpRequestContextIfNecessary(testContext); } + /** + * TODO [SPR-9864] Document overridden afterTestMethod(). + * + * @see org.springframework.test.context.TestExecutionListener#afterTestMethod(TestContext) + */ + public void afterTestMethod(TestContext testContext) throws Exception { + if (logger.isDebugEnabled()) { + logger.debug(String.format("Resetting RequestContextHolder for test context %s.", testContext)); + } + RequestContextHolder.resetRequestAttributes(); + } + + /** + * The default implementation is <em>empty</em>. Can be overridden by + * subclasses as necessary. + * + * @see org.springframework.test.context.TestExecutionListener#afterTestClass(TestContext) + */ + public void afterTestClass(TestContext testContext) throws Exception { + /* no-op */ + } + /** * TODO [SPR-9864] Document setUpRequestContext(). * @@ -106,17 +137,4 @@ private void setUpRequestContextIfNecessary(TestContext testContext) { } } - /** - * TODO [SPR-9864] Document overridden afterTestMethod(). - * - * @see org.springframework.test.context.support.AbstractTestExecutionListener#afterTestMethod(org.springframework.test.context.TestContext) - */ - @Override - public void afterTestMethod(TestContext testContext) throws Exception { - if (logger.isDebugEnabled()) { - logger.debug(String.format("Resetting RequestContextHolder for test context %s.", testContext)); - } - RequestContextHolder.resetRequestAttributes(); - } - }
false
Other
spring-projects
spring-framework
7d9c823a1550d0fe0050bd4184f3bb47dd4b7c51.json
Delete unused imports
spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/AnnotatedConfigClassesWithoutAtConfigurationTests.java
@@ -16,8 +16,6 @@ package org.springframework.test.context.junit4.spr9051; -import static org.hamcrest.Matchers.*; -import static org.hamcrest.Matchers.is; import static org.junit.Assert.*; import java.util.Arrays; @@ -32,7 +30,6 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - /** * This set of tests refutes the claims made in * <a href="https://jira.springsource.org/browse/SPR-9051" target="_blank">SPR-9051</a>. @@ -89,6 +86,7 @@ public LifecycleBean lifecycleBean() { @Autowired private LifecycleBean lifecycleBean; + @Test public void testSPR_9051() throws Exception { assertNotNull(enigma);
false
Other
spring-projects
spring-framework
fe77c3d5fe3b498ecba7f3e1dce31f0aec43d8d6.json
Fix failing test
spring-test-mvc/src/main/java/org/springframework/test/web/servlet/DefaultMvcResult.java
@@ -110,31 +110,33 @@ public void setAsyncResultLatch(CountDownLatch asyncResultLatch) { } public Object getAsyncResult() { - WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.mockRequest); - if (asyncManager.isConcurrentHandlingStarted()) { - if (!awaitAsyncResult()) { + HttpServletRequest request = this.mockRequest; + if (request.isAsyncStarted()) { + + long timeout = request.getAsyncContext().getTimeout(); + if (!awaitAsyncResult(timeout)) { throw new IllegalStateException( "Gave up waiting on async result from [" + this.handler + "] to complete"); } + + WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.mockRequest); if (asyncManager.hasConcurrentResult()) { return asyncManager.getConcurrentResult(); } } - return null; } - private boolean awaitAsyncResult() { - if (this.asyncResultLatch == null) { - return true; - } - long timeout = ((HttpServletRequest) this.mockRequest).getAsyncContext().getTimeout(); - try { - return this.asyncResultLatch.await(timeout, TimeUnit.MILLISECONDS); - } - catch (InterruptedException e) { - return false; + private boolean awaitAsyncResult(long timeout) { + if (this.asyncResultLatch != null) { + try { + return this.asyncResultLatch.await(timeout, TimeUnit.MILLISECONDS); + } + catch (InterruptedException e) { + return false; + } } + return true; } }
true
Other
spring-projects
spring-framework
fe77c3d5fe3b498ecba7f3e1dce31f0aec43d8d6.json
Fix failing test
spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/standalone/AsyncTests.java
@@ -72,7 +72,6 @@ public DeferredResult<Person> getDeferredResult() { public Callable<Person> getCallable() { return new Callable<Person>() { public Person call() throws Exception { - Thread.sleep(100); return new Person("Joe"); } };
true
Other
spring-projects
spring-framework
e14ba9dec329b0f2f3ea414e8119957abd8a2a4c.json
Add config options for MVC async interceptors The MVC namespace and the MVC Java config now allow configuring CallableProcessingInterceptor and DeferredResultProcessingInterceptor instances. Issue: SPR-9914
spring-web/src/main/java/org/springframework/web/context/request/async/WebAsyncManager.java
@@ -175,6 +175,11 @@ public void registerCallableInterceptor(Object key, CallableProcessingIntercepto this.callableInterceptors.put(key, interceptor); } + public void registerAllCallableInterceptors(Map<Object, CallableProcessingInterceptor> interceptors) { + Assert.notNull(interceptors); + this.callableInterceptors.putAll(interceptors); + } + /** * Register a {@link DeferredResultProcessingInterceptor} that will be * applied when concurrent request handling with a {@link DeferredResult} @@ -188,6 +193,11 @@ public void registerDeferredResultInterceptor(Object key, DeferredResultProcessi this.deferredResultInterceptors.put(key, interceptor); } + public void registerAllDeferredResultInterceptors(Map<Object, DeferredResultProcessingInterceptor> interceptors) { + Assert.notNull(interceptors); + this.deferredResultInterceptors.putAll(interceptors); + } + /** * Clear {@linkplain #getConcurrentResult() concurrentResult} and * {@linkplain #getConcurrentResultContext() concurrentResultContext}.
true
Other
spring-projects
spring-framework
e14ba9dec329b0f2f3ea414e8119957abd8a2a4c.json
Add config options for MVC async interceptors The MVC namespace and the MVC Java config now allow configuring CallableProcessingInterceptor and DeferredResultProcessingInterceptor instances. Issue: SPR-9914
spring-webmvc/src/main/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParser.java
@@ -174,6 +174,8 @@ public BeanDefinition parse(Element element, ParserContext parserContext) { ManagedList<?> returnValueHandlers = getReturnValueHandlers(element, source, parserContext); String asyncTimeout = getAsyncTimeout(element, source, parserContext); RuntimeBeanReference asyncExecutor = getAsyncExecutor(element, source, parserContext); + ManagedList<?> callableInterceptors = getCallableInterceptors(element, source, parserContext); + ManagedList<?> deferredResultInterceptors = getDeferredResultInterceptors(element, source, parserContext); RootBeanDefinition handlerAdapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class); handlerAdapterDef.setSource(source); @@ -197,6 +199,8 @@ public BeanDefinition parse(Element element, ParserContext parserContext) { if (asyncExecutor != null) { handlerAdapterDef.getPropertyValues().add("taskExecutor", asyncExecutor); } + handlerAdapterDef.getPropertyValues().add("callableInterceptors", callableInterceptors); + handlerAdapterDef.getPropertyValues().add("deferredResultInterceptors", deferredResultInterceptors); String handlerAdapterName = parserContext.getReaderContext().registerWithGeneratedName(handlerAdapterDef); RootBeanDefinition csInterceptorDef = new RootBeanDefinition(ConversionServiceExposingInterceptor.class); @@ -337,6 +341,40 @@ private RuntimeBeanReference getAsyncExecutor(Element element, Object source, Pa return null; } + private ManagedList<?> getCallableInterceptors(Element element, Object source, ParserContext parserContext) { + ManagedList<? super Object> interceptors = new ManagedList<Object>(); + Element asyncElement = DomUtils.getChildElementByTagName(element, "async-support"); + if (asyncElement != null) { + Element interceptorsElement = DomUtils.getChildElementByTagName(asyncElement, "callable-interceptors"); + if (interceptorsElement != null) { + interceptors.setSource(source); + for (Element converter : DomUtils.getChildElementsByTagName(interceptorsElement, "bean")) { + BeanDefinitionHolder beanDef = parserContext.getDelegate().parseBeanDefinitionElement(converter); + beanDef = parserContext.getDelegate().decorateBeanDefinitionIfRequired(converter, beanDef); + interceptors.add(beanDef); + } + } + } + return interceptors; + } + + private ManagedList<?> getDeferredResultInterceptors(Element element, Object source, ParserContext parserContext) { + ManagedList<? super Object> interceptors = new ManagedList<Object>(); + Element asyncElement = DomUtils.getChildElementByTagName(element, "async-support"); + if (asyncElement != null) { + Element interceptorsElement = DomUtils.getChildElementByTagName(asyncElement, "deferred-result-interceptors"); + if (interceptorsElement != null) { + interceptors.setSource(source); + for (Element converter : DomUtils.getChildElementsByTagName(interceptorsElement, "bean")) { + BeanDefinitionHolder beanDef = parserContext.getDelegate().parseBeanDefinitionElement(converter); + beanDef = parserContext.getDelegate().decorateBeanDefinitionIfRequired(converter, beanDef); + interceptors.add(beanDef); + } + } + } + return interceptors; + } + private ManagedList<?> getArgumentResolvers(Element element, Object source, ParserContext parserContext) { Element resolversElement = DomUtils.getChildElementByTagName(element, "argument-resolvers"); if (resolversElement != null) {
true
Other
spring-projects
spring-framework
e14ba9dec329b0f2f3ea414e8119957abd8a2a4c.json
Add config options for MVC async interceptors The MVC namespace and the MVC Java config now allow configuring CallableProcessingInterceptor and DeferredResultProcessingInterceptor instances. Issue: SPR-9914
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/AsyncSupportConfigurer.java
@@ -15,11 +15,18 @@ */ package org.springframework.web.servlet.config.annotation; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import java.util.concurrent.Callable; import org.springframework.core.task.AsyncTaskExecutor; import org.springframework.core.task.SimpleAsyncTaskExecutor; +import org.springframework.util.Assert; import org.springframework.web.context.request.async.AsyncTask; +import org.springframework.web.context.request.async.CallableProcessingInterceptor; +import org.springframework.web.context.request.async.DeferredResult; +import org.springframework.web.context.request.async.DeferredResultProcessingInterceptor; /** * Helps with configuring a options for asynchronous request processing. @@ -33,6 +40,13 @@ public class AsyncSupportConfigurer { private Long timeout; + private final List<CallableProcessingInterceptor> callableInterceptors = + new ArrayList<CallableProcessingInterceptor>(); + + private final List<DeferredResultProcessingInterceptor> deferredResultInterceptors = + new ArrayList<DeferredResultProcessingInterceptor>(); + + /** * Set the default {@link AsyncTaskExecutor} to use when a controller method * returns a {@link Callable}. Controller methods can override this default on @@ -64,6 +78,31 @@ public AsyncSupportConfigurer setDefaultTimeout(long timeout) { return this; } + /** + * Configure lifecycle intercepters with callbacks around concurrent request + * execution that starts when a controller returns a + * {@link java.util.concurrent.Callable}. + * + * @param interceptors the interceptors to register + */ + public AsyncSupportConfigurer registerCallableInterceptors(CallableProcessingInterceptor... interceptors) { + Assert.notNull(interceptors, "Interceptors are required"); + this.callableInterceptors.addAll(Arrays.asList(interceptors)); + return this; + } + + /** + * Configure lifecycle intercepters with callbacks around concurrent request + * execution that starts when a controller returns a {@link DeferredResult}. + * + * @param interceptors the interceptors to register + */ + public AsyncSupportConfigurer registerDeferredResultInterceptors(DeferredResultProcessingInterceptor... interceptors) { + Assert.notNull(interceptors, "Interceptors are required"); + this.deferredResultInterceptors.addAll(Arrays.asList(interceptors)); + return this; + } + protected AsyncTaskExecutor getTaskExecutor() { return this.taskExecutor; } @@ -72,4 +111,12 @@ protected Long getTimeout() { return this.timeout; } + protected List<CallableProcessingInterceptor> getCallableInterceptors() { + return this.callableInterceptors; + } + + protected List<DeferredResultProcessingInterceptor> getDeferredResultInterceptors() { + return this.deferredResultInterceptors; + } + }
true
Other
spring-projects
spring-framework
e14ba9dec329b0f2f3ea414e8119957abd8a2a4c.json
Add config options for MVC async interceptors The MVC namespace and the MVC Java config now allow configuring CallableProcessingInterceptor and DeferredResultProcessingInterceptor instances. Issue: SPR-9914
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java
@@ -378,6 +378,8 @@ public RequestMappingHandlerAdapter requestMappingHandlerAdapter() { if (configurer.getTimeout() != null) { adapter.setAsyncRequestTimeout(configurer.getTimeout()); } + adapter.setCallableInterceptors(configurer.getCallableInterceptors()); + adapter.setDeferredResultInterceptors(configurer.getDeferredResultInterceptors()); return adapter; }
true
Other
spring-projects
spring-framework
e14ba9dec329b0f2f3ea414e8119957abd8a2a4c.json
Add config options for MVC async interceptors The MVC namespace and the MVC Java config now allow configuring CallableProcessingInterceptor and DeferredResultProcessingInterceptor instances. Issue: SPR-9914
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapter.java
@@ -48,6 +48,7 @@ import org.springframework.http.converter.xml.SourceHttpMessageConverter; import org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter; import org.springframework.ui.ModelMap; +import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import org.springframework.util.ReflectionUtils.MethodFilter; import org.springframework.web.accept.ContentNegotiationManager; @@ -64,6 +65,8 @@ import org.springframework.web.context.request.WebRequest; import org.springframework.web.context.request.async.AsyncTask; import org.springframework.web.context.request.async.AsyncWebRequest; +import org.springframework.web.context.request.async.CallableProcessingInterceptor; +import org.springframework.web.context.request.async.DeferredResultProcessingInterceptor; import org.springframework.web.context.request.async.WebAsyncManager; import org.springframework.web.context.request.async.WebAsyncUtils; import org.springframework.web.method.ControllerAdviceBean; @@ -135,6 +138,12 @@ public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter i private Long asyncRequestTimeout; + private final Map<Object, CallableProcessingInterceptor> callableInterceptors = + new LinkedHashMap<Object, CallableProcessingInterceptor>(); + + private final Map<Object, DeferredResultProcessingInterceptor> deferredResultInterceptors = + new LinkedHashMap<Object, DeferredResultProcessingInterceptor>(); + private boolean ignoreDefaultModelOnRedirect = false; private int cacheSecondsForSessionAttributeHandlers = 0; @@ -363,6 +372,34 @@ public void setAsyncRequestTimeout(long timeout) { this.asyncRequestTimeout = timeout; } + /** + * Configure {@code CallableProcessingInterceptor}'s to register on async requests. + * @param interceptors the interceptors to register + */ + public void setCallableInterceptors(List<CallableProcessingInterceptor> interceptors) { + Assert.notNull(interceptors); + for (int index = 0 ; index < interceptors.size(); index++) { + CallableProcessingInterceptor interceptor = interceptors.get(index); + this.callableInterceptors.put(getInterceptorKey(interceptor, index), interceptor); + } + } + + /** + * Configure {@code DeferredResultProcessingInterceptor}'s to register on async requests. + * @param interceptors the interceptors to register + */ + public void setDeferredResultInterceptors(List<DeferredResultProcessingInterceptor> interceptors) { + Assert.notNull(interceptors); + for (int index = 0 ; index < interceptors.size(); index++) { + DeferredResultProcessingInterceptor interceptor = interceptors.get(index); + this.deferredResultInterceptors.put(getInterceptorKey(interceptor, index), interceptor); + } + } + + private String getInterceptorKey(Object interceptor, int index) { + return this.hashCode() + ":" + interceptor.getClass().getName() + "#" + index; + } + /** * By default the content of the "default" model is used both during * rendering and redirect scenarios. Alternatively a controller method @@ -703,6 +740,8 @@ private ModelAndView invokeHandleMethod(HttpServletRequest request, final WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); asyncManager.setTaskExecutor(this.taskExecutor); asyncManager.setAsyncWebRequest(asyncWebRequest); + asyncManager.registerAllCallableInterceptors(this.callableInterceptors); + asyncManager.registerAllDeferredResultInterceptors(this.deferredResultInterceptors); if (asyncManager.hasConcurrentResult()) { Object result = asyncManager.getConcurrentResult();
true
Other
spring-projects
spring-framework
e14ba9dec329b0f2f3ea414e8119957abd8a2a4c.json
Add config options for MVC async interceptors The MVC namespace and the MVC Java config now allow configuring CallableProcessingInterceptor and DeferredResultProcessingInterceptor instances. Issue: SPR-9914
spring-webmvc/src/main/resources/org/springframework/web/servlet/config/spring-mvc-3.2.xsd
@@ -97,6 +97,46 @@ ]]></xsd:documentation> </xsd:annotation> <xsd:complexType> + <xsd:all minOccurs="0"> + <xsd:element name="callable-interceptors" minOccurs="0"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The ordered set of interceptors that intercept the lifecycle of concurrently executed + requests, which start after a controller returns a java.util.concurrent.Callable. + ]]></xsd:documentation> + </xsd:annotation> + <xsd:complexType> + <xsd:sequence> + <xsd:element ref="beans:bean" minOccurs="1" maxOccurs="unbounded"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Registers a CallableProcessingInterceptor. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:element> + </xsd:sequence> + </xsd:complexType> + </xsd:element> + <xsd:element name="deferred-result-interceptors" minOccurs="0"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The ordered set of interceptors that intercept the lifecycle of concurrently executed + requests, which start after a controller returns a DeferredResult. + ]]></xsd:documentation> + </xsd:annotation> + <xsd:complexType> + <xsd:sequence> + <xsd:element ref="beans:bean" minOccurs="1" maxOccurs="unbounded"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Registers a DeferredResultProcessingInterceptor. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:element> + </xsd:sequence> + </xsd:complexType> + </xsd:element> + </xsd:all> <xsd:attribute name="task-executor" type="xsd:string"> <xsd:annotation> <xsd:documentation source="java:org.springframework.core.task.AsyncTaskExecutor"><![CDATA[
true
Other
spring-projects
spring-framework
e14ba9dec329b0f2f3ea414e8119957abd8a2a4c.json
Add config options for MVC async interceptors The MVC namespace and the MVC Java config now allow configuring CallableProcessingInterceptor and DeferredResultProcessingInterceptor instances. Issue: SPR-9914
spring-webmvc/src/test/java/org/springframework/web/servlet/config/MvcNamespaceTests.java
@@ -16,19 +16,27 @@ package org.springframework.web.servlet.config; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Locale; +import java.util.Map; + import javax.servlet.RequestDispatcher; import javax.validation.constraints.NotNull; import org.junit.Before; import org.junit.Test; - import org.springframework.beans.DirectFieldAccessor; import org.springframework.beans.TypeMismatchException; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; @@ -57,6 +65,10 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.ServletWebRequest; +import org.springframework.web.context.request.async.CallableProcessingInterceptor; +import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter; +import org.springframework.web.context.request.async.DeferredResultProcessingInterceptor; +import org.springframework.web.context.request.async.DeferredResultProcessingInterceptorAdapter; import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.method.HandlerMethod; import org.springframework.web.method.support.InvocableHandlerMethod; @@ -76,8 +88,6 @@ import org.springframework.web.servlet.resource.ResourceHttpRequestHandler; import org.springframework.web.servlet.theme.ThemeChangeInterceptor; -import static org.junit.Assert.*; - /** * @author Keith Donald * @author Arjen Poutsma @@ -469,8 +479,18 @@ public void testAsyncSupportOptions() throws Exception { RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class); assertNotNull(adapter); - assertEquals(ConcurrentTaskExecutor.class, new DirectFieldAccessor(adapter).getPropertyValue("taskExecutor").getClass()); - assertEquals(2500L, new DirectFieldAccessor(adapter).getPropertyValue("asyncRequestTimeout")); + + DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(adapter); + assertEquals(ConcurrentTaskExecutor.class, fieldAccessor.getPropertyValue("taskExecutor").getClass()); + assertEquals(2500L, fieldAccessor.getPropertyValue("asyncRequestTimeout")); + + Map<Object, CallableProcessingInterceptor> callableInterceptors = + (Map<Object, CallableProcessingInterceptor>) fieldAccessor.getPropertyValue("callableInterceptors"); + assertEquals(1, callableInterceptors.size()); + + Map<Object, DeferredResultProcessingInterceptor> deferredResultInterceptors = + (Map<Object, DeferredResultProcessingInterceptor>) fieldAccessor.getPropertyValue("deferredResultInterceptors"); + assertEquals(1, deferredResultInterceptors.size()); } @@ -539,4 +559,8 @@ public RequestDispatcher getNamedDispatcher(String path) { } } + public static class TestCallableProcessingInterceptor extends CallableProcessingInterceptorAdapter { } + + public static class TestDeferredResultProcessingInterceptor extends DeferredResultProcessingInterceptorAdapter { } + }
true
Other
spring-projects
spring-framework
e14ba9dec329b0f2f3ea414e8119957abd8a2a4c.json
Add config options for MVC async interceptors The MVC namespace and the MVC Java config now allow configuring CallableProcessingInterceptor and DeferredResultProcessingInterceptor instances. Issue: SPR-9914
spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupportExtensionTests.java
@@ -21,6 +21,7 @@ import java.util.Arrays; import java.util.List; +import java.util.Map; import org.junit.Before; import org.junit.Test; @@ -46,6 +47,10 @@ import org.springframework.web.bind.support.ConfigurableWebBindingInitializer; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.ServletWebRequest; +import org.springframework.web.context.request.async.CallableProcessingInterceptor; +import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter; +import org.springframework.web.context.request.async.DeferredResultProcessingInterceptor; +import org.springframework.web.context.request.async.DeferredResultProcessingInterceptorAdapter; import org.springframework.web.context.support.StaticWebApplicationContext; import org.springframework.web.method.annotation.ModelAttributeMethodProcessor; import org.springframework.web.method.support.HandlerMethodArgumentResolver; @@ -117,6 +122,7 @@ public void handlerMappings() throws Exception { assertNotNull(handler.getHandler()); } + @SuppressWarnings("unchecked") @Test public void requestMappingHandlerAdapter() throws Exception { RequestMappingHandlerAdapter adapter = webConfig.requestMappingHandlerAdapter(); @@ -128,22 +134,30 @@ public void requestMappingHandlerAdapter() throws Exception { // Message converters assertEquals(1, adapter.getMessageConverters().size()); + DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(adapter); + // Custom argument resolvers and return value handlers - @SuppressWarnings("unchecked") - List<HandlerMethodArgumentResolver> argResolvers= (List<HandlerMethodArgumentResolver>) - new DirectFieldAccessor(adapter).getPropertyValue("customArgumentResolvers"); + List<HandlerMethodArgumentResolver> argResolvers = + (List<HandlerMethodArgumentResolver>) fieldAccessor.getPropertyValue("customArgumentResolvers"); assertEquals(1, argResolvers.size()); - @SuppressWarnings("unchecked") - List<HandlerMethodReturnValueHandler> handlers = (List<HandlerMethodReturnValueHandler>) - new DirectFieldAccessor(adapter).getPropertyValue("customReturnValueHandlers"); + List<HandlerMethodReturnValueHandler> handlers = + (List<HandlerMethodReturnValueHandler>) fieldAccessor.getPropertyValue("customReturnValueHandlers"); assertEquals(1, handlers.size()); // Async support options - assertEquals(ConcurrentTaskExecutor.class, new DirectFieldAccessor(adapter).getPropertyValue("taskExecutor").getClass()); - assertEquals(2500L, new DirectFieldAccessor(adapter).getPropertyValue("asyncRequestTimeout")); + assertEquals(ConcurrentTaskExecutor.class, fieldAccessor.getPropertyValue("taskExecutor").getClass()); + assertEquals(2500L, fieldAccessor.getPropertyValue("asyncRequestTimeout")); + + Map<Object, CallableProcessingInterceptor> callableInterceptors = + (Map<Object, CallableProcessingInterceptor>) fieldAccessor.getPropertyValue("callableInterceptors"); + assertEquals(1, callableInterceptors.size()); + + Map<Object, DeferredResultProcessingInterceptor> deferredResultInterceptors = + (Map<Object, DeferredResultProcessingInterceptor>) fieldAccessor.getPropertyValue("deferredResultInterceptors"); + assertEquals(1, deferredResultInterceptors.size()); - assertEquals(false, new DirectFieldAccessor(adapter).getPropertyValue("ignoreDefaultModelOnRedirect")); + assertEquals(false, fieldAccessor.getPropertyValue("ignoreDefaultModelOnRedirect")); } @Test @@ -240,7 +254,9 @@ public void configureContentNegotiation(ContentNegotiationConfigurer configurer) @Override public void configureAsyncSupport(AsyncSupportConfigurer configurer) { - configurer.setDefaultTimeout(2500).setTaskExecutor(new ConcurrentTaskExecutor()); + configurer.setDefaultTimeout(2500).setTaskExecutor(new ConcurrentTaskExecutor()) + .registerCallableInterceptors(new CallableProcessingInterceptorAdapter() { }) + .registerDeferredResultInterceptors(new DeferredResultProcessingInterceptorAdapter() {}); } @Override
true
Other
spring-projects
spring-framework
e14ba9dec329b0f2f3ea414e8119957abd8a2a4c.json
Add config options for MVC async interceptors The MVC namespace and the MVC Java config now allow configuring CallableProcessingInterceptor and DeferredResultProcessingInterceptor instances. Issue: SPR-9914
spring-webmvc/src/test/resources/org/springframework/web/servlet/config/mvc-config-async-support.xml
@@ -5,7 +5,14 @@ http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <mvc:annotation-driven> - <mvc:async-support default-timeout="2500" task-executor="executor" /> + <mvc:async-support default-timeout="2500" task-executor="executor"> + <mvc:callable-interceptors> + <bean class="org.springframework.web.servlet.config.MvcNamespaceTests.TestCallableProcessingInterceptor" /> + </mvc:callable-interceptors> + <mvc:deferred-result-interceptors> + <bean class="org.springframework.web.servlet.config.MvcNamespaceTests.TestDeferredResultProcessingInterceptor" /> + </mvc:deferred-result-interceptors> + </mvc:async-support> </mvc:annotation-driven> <bean id="executor" class="org.springframework.scheduling.concurrent.ConcurrentTaskExecutor" />
true
Other
spring-projects
spring-framework
e14ba9dec329b0f2f3ea414e8119957abd8a2a4c.json
Add config options for MVC async interceptors The MVC namespace and the MVC Java config now allow configuring CallableProcessingInterceptor and DeferredResultProcessingInterceptor instances. Issue: SPR-9914
src/dist/changelog.txt
@@ -32,6 +32,7 @@ Changes in version 3.2 RC1 (2012-10-29) * added CallableProcessingInterceptor and DeferredResultProcessingInterceptor * added support for wildcard media types in AbstractView and ContentNegotiationViewResolver (SPR-9807) * the jackson message converters now include "application/*+json" in supported media types (SPR-7905) +* add options to configure MVC async interceptors in the MVC namespace and Java config (SPR-9914) Changes in version 3.2 M2 (2012-09-11) --------------------------------------
true
Other
spring-projects
spring-framework
5d4d1eaca4fa8af29f07e23b89bee8fd028820bd.json
Fix package cycle in @EnableMBeanExport Prior to this commit, @EnableMBeanExport was declared in the jmx.export.annotation package. This makes logical sense, but nevertheless creates a package cycle, because @EnableMBeanExport depends on MBeanExportConfiguration which in turn depends on context.annotation types like @Configuration, @Bean, and @Role. context.annotation.config.MBeanExportBeanDefinitionParser, on the other hand already has dependencies on types in jmx.support. Together, this means that a package cycle was introduced. The solution to this is simple: move @EnableMBeanExport and friends from jmx.export.annotation => context.annotation. This has been the strategy for other @Enable annotations and for the same reasons. It also makes a kind of logical sense: just like you find <context:mbean-export> and <context:load-time-weaver> under the context: XML namespace, so too do you find their @Enable* counterparts under the context.annotation namespace. Issue: SPR-8943
spring-context/src/main/java/org/springframework/context/annotation/EnableMBeanExport.java
@@ -14,15 +14,15 @@ * limitations under the License. */ -package org.springframework.jmx.export.annotation; +package org.springframework.context.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import org.springframework.context.annotation.Import; +import org.springframework.jmx.export.annotation.AnnotationMBeanExporter; import org.springframework.jmx.support.RegistrationPolicy; /**
true
Other
spring-projects
spring-framework
5d4d1eaca4fa8af29f07e23b89bee8fd028820bd.json
Fix package cycle in @EnableMBeanExport Prior to this commit, @EnableMBeanExport was declared in the jmx.export.annotation package. This makes logical sense, but nevertheless creates a package cycle, because @EnableMBeanExport depends on MBeanExportConfiguration which in turn depends on context.annotation types like @Configuration, @Bean, and @Role. context.annotation.config.MBeanExportBeanDefinitionParser, on the other hand already has dependencies on types in jmx.support. Together, this means that a package cycle was introduced. The solution to this is simple: move @EnableMBeanExport and friends from jmx.export.annotation => context.annotation. This has been the strategy for other @Enable annotations and for the same reasons. It also makes a kind of logical sense: just like you find <context:mbean-export> and <context:load-time-weaver> under the context: XML namespace, so too do you find their @Enable* counterparts under the context.annotation namespace. Issue: SPR-8943
spring-context/src/main/java/org/springframework/context/annotation/MBeanExportConfiguration.java
@@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.jmx.export.annotation; +package org.springframework.context.annotation; import java.util.Map; @@ -25,12 +25,9 @@ import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.ImportAware; -import org.springframework.context.annotation.Role; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.type.AnnotationMetadata; +import org.springframework.jmx.export.annotation.AnnotationMBeanExporter; import org.springframework.jmx.support.RegistrationPolicy; import org.springframework.jmx.support.WebSphereMBeanServerFactoryBean; import org.springframework.jndi.JndiObjectFactoryBean;
true
Other
spring-projects
spring-framework
5d4d1eaca4fa8af29f07e23b89bee8fd028820bd.json
Fix package cycle in @EnableMBeanExport Prior to this commit, @EnableMBeanExport was declared in the jmx.export.annotation package. This makes logical sense, but nevertheless creates a package cycle, because @EnableMBeanExport depends on MBeanExportConfiguration which in turn depends on context.annotation types like @Configuration, @Bean, and @Role. context.annotation.config.MBeanExportBeanDefinitionParser, on the other hand already has dependencies on types in jmx.support. Together, this means that a package cycle was introduced. The solution to this is simple: move @EnableMBeanExport and friends from jmx.export.annotation => context.annotation. This has been the strategy for other @Enable annotations and for the same reasons. It also makes a kind of logical sense: just like you find <context:mbean-export> and <context:load-time-weaver> under the context: XML namespace, so too do you find their @Enable* counterparts under the context.annotation namespace. Issue: SPR-8943
spring-context/src/test/java/org/springframework/jmx/export/annotation/EnableMBeanExportConfigurationTests.java
@@ -25,7 +25,9 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableMBeanExport; import org.springframework.context.annotation.Lazy; +import org.springframework.context.annotation.MBeanExportConfiguration; import org.springframework.jmx.export.MBeanExporterTests; import org.springframework.jmx.export.TestDynamicMBean; import org.springframework.jmx.support.MBeanServerFactoryBean;
true
Other
spring-projects
spring-framework
cb867121870b064df622274a0afc13d6198ba2c6.json
Provide method to set async TimeoutHandler Issue: SPR-9914
spring-web/src/main/java/org/springframework/web/context/request/async/WebAsyncManager.java
@@ -66,6 +66,8 @@ public final class WebAsyncManager { private AsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor(this.getClass().getSimpleName()); + private Runnable timeoutHandler; + private Object concurrentResult = RESULT_NONE; private Object[] concurrentResultContext; @@ -117,6 +119,15 @@ public void setTaskExecutor(AsyncTaskExecutor taskExecutor) { this.taskExecutor = taskExecutor; } + /** + * Set the handler to use when concurrent handling times out. If not set, by + * default a timeout is handled by returning SERVICE_UNAVAILABLE (503). + * @param timeoutHandler the handler + */ + public void setTimeoutHandler(Runnable timeoutHandler) { + this.timeoutHandler = timeoutHandler; + } + /** * Whether the selected handler for the current request chose to handle the * request asynchronously. A return value of "true" indicates concurrent @@ -348,6 +359,10 @@ private void startAsyncProcessing(Object[] processingContext) { Assert.state(this.asyncWebRequest != null, "AsyncWebRequest must not be null"); this.asyncWebRequest.startAsync(); + if (this.timeoutHandler != null) { + this.asyncWebRequest.setTimeoutHandler(this.timeoutHandler); + } + if (logger.isDebugEnabled()) { HttpServletRequest request = asyncWebRequest.getNativeRequest(HttpServletRequest.class); String requestUri = urlPathHelper.getRequestUri(request);
true
Other
spring-projects
spring-framework
cb867121870b064df622274a0afc13d6198ba2c6.json
Provide method to set async TimeoutHandler Issue: SPR-9914
spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTests.java
@@ -91,11 +91,7 @@ public void setAsyncWebRequestAfterAsyncStarted() { @Test public void startCallableProcessing() throws Exception { - Callable<Object> task = new Callable<Object>() { - public Object call() throws Exception { - return 1; - } - }; + Callable<Object> task = new StubCallable(); CallableProcessingInterceptor interceptor = createStrictMock(CallableProcessingInterceptor.class); interceptor.preProcess(this.asyncWebRequest, task); @@ -146,11 +142,7 @@ public void startCallableProcessingNullCallable() { public void startCallableProcessingNullRequest() { WebAsyncManager manager = WebAsyncUtils.getAsyncManager(new MockHttpServletRequest()); try { - manager.startCallableProcessing(new Callable<Object>() { - public Object call() throws Exception { - return 1; - } - }); + manager.startCallableProcessing(new StubCallable()); fail("Expected exception"); } catch (IllegalStateException ex) { @@ -191,6 +183,29 @@ public void startDeferredResultProcessing() throws Exception { verify(this.asyncWebRequest, interceptor); } + @Test + public void setTimeoutHandler() throws Exception { + + Runnable timeoutHandler = new Runnable() { public void run() {} }; + this.asyncManager.setTimeoutHandler(timeoutHandler); + + this.asyncWebRequest.startAsync(); + this.asyncWebRequest.setTimeoutHandler(timeoutHandler); + expect(this.asyncWebRequest.isAsyncComplete()).andReturn(false); + this.asyncWebRequest.dispatch(); + replay(this.asyncWebRequest); + + this.asyncManager.startCallableProcessing(new StubCallable()); + + verify(this.asyncWebRequest); + } + + + private final class StubCallable implements Callable<Object> { + public Object call() throws Exception { + return 1; + } + } @SuppressWarnings("serial") private static class SyncTaskExecutor extends SimpleAsyncTaskExecutor {
true
Other
spring-projects
spring-framework
59fb67e38dc8781db52a4ac1bc5e96b77e9ddc58.json
Update SpEL test to reflect native float support Issue: SPR-9486
spring-expression/src/test/java/org/springframework/expression/spel/standard/SpelParserTests.java
@@ -382,8 +382,7 @@ public void numerics() { checkNumberError("3.4L", SpelMessage.REAL_CANNOT_BE_LONG); - // Number is parsed as a float, but immediately promoted to a double - checkNumber("3.5f", 3.5d, Double.class); + checkNumber("3.5f", 3.5f, Float.class); checkNumber("1.2e3", 1.2e3d, Double.class); checkNumber("1.2e+3", 1.2e3d, Double.class);
false
Other
spring-projects
spring-framework
be8f23d75658a8b728912b644c138407d4914f8b.json
Add SpEL support for float literals This change ensures that SpEL expressions involving floats are supported natively as opposed to the previous behavior which required conversion to double, leading to potential downstream conversion ambiguities. Issue: SPR-9486
spring-expression/src/main/java/org/springframework/expression/spel/ast/FloatLiteral.java
@@ -0,0 +1,38 @@ +/* + * Copyright 2002-2012 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.expression.spel.ast; + +import org.springframework.expression.TypedValue; + +/** + * Expression language AST node that represents a float literal. + * + * @author Satyapal Reddy + * @since 3.2 + */ +public class FloatLiteral extends Literal { + private final TypedValue value; + + FloatLiteral(String payload, int pos, float value) { + super(payload, pos); + this.value = new TypedValue(value); + } + + @Override + public TypedValue getLiteralValue() { + return this.value; + } +}
true
Other
spring-projects
spring-framework
be8f23d75658a8b728912b644c138407d4914f8b.json
Add SpEL support for float literals This change ensures that SpEL expressions involving floats are supported natively as opposed to the previous behavior which required conversion to double, leading to potential downstream conversion ambiguities. Issue: SPR-9486
spring-expression/src/main/java/org/springframework/expression/spel/ast/Literal.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2012 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. @@ -17,11 +17,7 @@ package org.springframework.expression.spel.ast; import org.springframework.expression.TypedValue; -import org.springframework.expression.spel.ExpressionState; -import org.springframework.expression.spel.SpelEvaluationException; -import org.springframework.expression.spel.SpelMessage; -import org.springframework.expression.spel.SpelParseException; -import org.springframework.expression.spel.InternalParseException; +import org.springframework.expression.spel.*; /** * Common superclass for nodes representing literals (boolean, string, number, etc). @@ -80,12 +76,12 @@ public static Literal getLongLiteral(String numberToken, int pos, int radix) { } } - // TODO should allow for 'f' for float, not just double + public static Literal getRealLiteral(String numberToken, int pos, boolean isFloat) { try { if (isFloat) { float value = Float.parseFloat(numberToken); - return new RealLiteral(numberToken, pos, value); + return new FloatLiteral(numberToken, pos, value); } else { double value = Double.parseDouble(numberToken); return new RealLiteral(numberToken, pos, value);
true
Other
spring-projects
spring-framework
be8f23d75658a8b728912b644c138407d4914f8b.json
Add SpEL support for float literals This change ensures that SpEL expressions involving floats are supported natively as opposed to the previous behavior which required conversion to double, leading to potential downstream conversion ambiguities. Issue: SPR-9486
spring-expression/src/main/java/org/springframework/expression/spel/ast/OpDivide.java
@@ -43,8 +43,9 @@ public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep Number op2 = (Number) operandTwo; if (op1 instanceof Double || op2 instanceof Double) { return new TypedValue(op1.doubleValue() / op2.doubleValue()); - } - else if (op1 instanceof Long || op2 instanceof Long) { + } else if (op1 instanceof Float || op2 instanceof Float) { + return new TypedValue(op1.floatValue() / op2.floatValue()); + } else if (op1 instanceof Long || op2 instanceof Long) { return new TypedValue(op1.longValue() / op2.longValue()); } else {
true
Other
spring-projects
spring-framework
be8f23d75658a8b728912b644c138407d4914f8b.json
Add SpEL support for float literals This change ensures that SpEL expressions involving floats are supported natively as opposed to the previous behavior which required conversion to double, leading to potential downstream conversion ambiguities. Issue: SPR-9486
spring-expression/src/main/java/org/springframework/expression/spel/ast/OpEQ.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2012 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. @@ -41,6 +41,8 @@ public BooleanTypedValue getValueInternal(ExpressionState state) throws Evaluati Number op2 = (Number) right; if (op1 instanceof Double || op2 instanceof Double) { return BooleanTypedValue.forValue(op1.doubleValue() == op2.doubleValue()); + } else if (op1 instanceof Float || op2 instanceof Float) { + return BooleanTypedValue.forValue(op1.floatValue() == op2.floatValue()); } else if (op1 instanceof Long || op2 instanceof Long) { return BooleanTypedValue.forValue(op1.longValue() == op2.longValue()); } else {
true
Other
spring-projects
spring-framework
be8f23d75658a8b728912b644c138407d4914f8b.json
Add SpEL support for float literals This change ensures that SpEL expressions involving floats are supported natively as opposed to the previous behavior which required conversion to double, leading to potential downstream conversion ambiguities. Issue: SPR-9486
spring-expression/src/main/java/org/springframework/expression/spel/ast/OpGE.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2012 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. @@ -40,6 +40,8 @@ public BooleanTypedValue getValueInternal(ExpressionState state) throws Evaluati Number rightNumber = (Number) right; if (leftNumber instanceof Double || rightNumber instanceof Double) { return BooleanTypedValue.forValue(leftNumber.doubleValue() >= rightNumber.doubleValue()); + } else if (leftNumber instanceof Float || rightNumber instanceof Float) { + return BooleanTypedValue.forValue(leftNumber.floatValue() >= rightNumber.floatValue()); } else if (leftNumber instanceof Long || rightNumber instanceof Long) { return BooleanTypedValue.forValue( leftNumber.longValue() >= rightNumber.longValue()); } else {
true
Other
spring-projects
spring-framework
be8f23d75658a8b728912b644c138407d4914f8b.json
Add SpEL support for float literals This change ensures that SpEL expressions involving floats are supported natively as opposed to the previous behavior which required conversion to double, leading to potential downstream conversion ambiguities. Issue: SPR-9486
spring-expression/src/main/java/org/springframework/expression/spel/ast/OpLE.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2012 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. @@ -41,6 +41,8 @@ public BooleanTypedValue getValueInternal(ExpressionState state) throws Evaluati Number rightNumber = (Number) right; if (leftNumber instanceof Double || rightNumber instanceof Double) { return BooleanTypedValue.forValue(leftNumber.doubleValue() <= rightNumber.doubleValue()); + } else if (leftNumber instanceof Float || rightNumber instanceof Float) { + return BooleanTypedValue.forValue(leftNumber.floatValue() <= rightNumber.floatValue()); } else if (leftNumber instanceof Long || rightNumber instanceof Long) { return BooleanTypedValue.forValue(leftNumber.longValue() <= rightNumber.longValue()); } else {
true
Other
spring-projects
spring-framework
be8f23d75658a8b728912b644c138407d4914f8b.json
Add SpEL support for float literals This change ensures that SpEL expressions involving floats are supported natively as opposed to the previous behavior which required conversion to double, leading to potential downstream conversion ambiguities. Issue: SPR-9486
spring-expression/src/main/java/org/springframework/expression/spel/ast/OpLT.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2012 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. @@ -42,6 +42,8 @@ public BooleanTypedValue getValueInternal(ExpressionState state) throws Evaluati Number rightNumber = (Number) right; if (leftNumber instanceof Double || rightNumber instanceof Double) { return BooleanTypedValue.forValue(leftNumber.doubleValue() < rightNumber.doubleValue()); + } else if (leftNumber instanceof Float || rightNumber instanceof Float) { + return BooleanTypedValue.forValue(leftNumber.floatValue() < rightNumber.floatValue()); } else if (leftNumber instanceof Long || rightNumber instanceof Long) { return BooleanTypedValue.forValue(leftNumber.longValue() < rightNumber.longValue()); } else {
true
Other
spring-projects
spring-framework
be8f23d75658a8b728912b644c138407d4914f8b.json
Add SpEL support for float literals This change ensures that SpEL expressions involving floats are supported natively as opposed to the previous behavior which required conversion to double, leading to potential downstream conversion ambiguities. Issue: SPR-9486
spring-expression/src/main/java/org/springframework/expression/spel/ast/OpMinus.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2012 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. @@ -52,6 +52,8 @@ public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep Number n = (Number) operand; if (operand instanceof Double) { return new TypedValue(0 - n.doubleValue()); + } else if (operand instanceof Float) { + return new TypedValue(0 - n.floatValue()); } else if (operand instanceof Long) { return new TypedValue(0 - n.longValue()); } else { @@ -67,6 +69,8 @@ public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep Number op2 = (Number) right; if (op1 instanceof Double || op2 instanceof Double) { return new TypedValue(op1.doubleValue() - op2.doubleValue()); + } else if (op1 instanceof Float || op2 instanceof Float) { + return new TypedValue(op1.floatValue() - op2.floatValue()); } else if (op1 instanceof Long || op2 instanceof Long) { return new TypedValue(op1.longValue() - op2.longValue()); } else {
true
Other
spring-projects
spring-framework
be8f23d75658a8b728912b644c138407d4914f8b.json
Add SpEL support for float literals This change ensures that SpEL expressions involving floats are supported natively as opposed to the previous behavior which required conversion to double, leading to potential downstream conversion ambiguities. Issue: SPR-9486
spring-expression/src/main/java/org/springframework/expression/spel/ast/OpModulus.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2012 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. @@ -42,6 +42,8 @@ public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep Number op2 = (Number) operandTwo; if (op1 instanceof Double || op2 instanceof Double) { return new TypedValue(op1.doubleValue() % op2.doubleValue()); + } else if (op1 instanceof Float || op2 instanceof Float) { + return new TypedValue(op1.floatValue() % op2.floatValue()); } else if (op1 instanceof Long || op2 instanceof Long) { return new TypedValue(op1.longValue() % op2.longValue()); } else {
true
Other
spring-projects
spring-framework
be8f23d75658a8b728912b644c138407d4914f8b.json
Add SpEL support for float literals This change ensures that SpEL expressions involving floats are supported natively as opposed to the previous behavior which required conversion to double, leading to potential downstream conversion ambiguities. Issue: SPR-9486
spring-expression/src/main/java/org/springframework/expression/spel/ast/OpMultiply.java
@@ -66,6 +66,9 @@ public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep if (leftNumber instanceof Double || rightNumber instanceof Double) { return new TypedValue(leftNumber.doubleValue() * rightNumber.doubleValue()); } + else if (leftNumber instanceof Float || rightNumber instanceof Float) { + return new TypedValue(leftNumber.floatValue() * rightNumber.floatValue()); + } else if (leftNumber instanceof Long || rightNumber instanceof Long) { return new TypedValue(leftNumber.longValue() * rightNumber.longValue()); }
true
Other
spring-projects
spring-framework
be8f23d75658a8b728912b644c138407d4914f8b.json
Add SpEL support for float literals This change ensures that SpEL expressions involving floats are supported natively as opposed to the previous behavior which required conversion to double, leading to potential downstream conversion ambiguities. Issue: SPR-9486
spring-expression/src/main/java/org/springframework/expression/spel/ast/OpNE.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2012 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. @@ -41,6 +41,8 @@ public BooleanTypedValue getValueInternal(ExpressionState state) throws Evaluati Number op2 = (Number) right; if (op1 instanceof Double || op2 instanceof Double) { return BooleanTypedValue.forValue(op1.doubleValue() != op2.doubleValue()); + } else if (op1 instanceof Float || op2 instanceof Float) { + return BooleanTypedValue.forValue(op1.floatValue() != op2.floatValue()); } else if (op1 instanceof Long || op2 instanceof Long) { return BooleanTypedValue.forValue(op1.longValue() != op2.longValue()); } else {
true
Other
spring-projects
spring-framework
be8f23d75658a8b728912b644c138407d4914f8b.json
Add SpEL support for float literals This change ensures that SpEL expressions involving floats are supported natively as opposed to the previous behavior which required conversion to double, leading to potential downstream conversion ambiguities. Issue: SPR-9486
spring-expression/src/main/java/org/springframework/expression/spel/ast/OpPlus.java
@@ -55,6 +55,8 @@ public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep if (operandOne instanceof Number) { if (operandOne instanceof Double || operandOne instanceof Long) { return new TypedValue(operandOne); + } else if (operandOne instanceof Float) { + return new TypedValue(((Number) operandOne).floatValue()); } else { return new TypedValue(((Number) operandOne).intValue()); } @@ -73,6 +75,8 @@ public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep Number op2 = (Number) operandTwo; if (op1 instanceof Double || op2 instanceof Double) { return new TypedValue(op1.doubleValue() + op2.doubleValue()); + } else if (op1 instanceof Float || op2 instanceof Float) { + return new TypedValue(op1.floatValue() + op2.floatValue()); } else if (op1 instanceof Long || op2 instanceof Long) { return new TypedValue(op1.longValue() + op2.longValue()); } else { // TODO what about overflow?
true
Other
spring-projects
spring-framework
be8f23d75658a8b728912b644c138407d4914f8b.json
Add SpEL support for float literals This change ensures that SpEL expressions involving floats are supported natively as opposed to the previous behavior which required conversion to double, leading to potential downstream conversion ambiguities. Issue: SPR-9486
spring-expression/src/main/java/org/springframework/expression/spel/ast/OperatorPower.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2012 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. @@ -45,6 +45,8 @@ public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep Number op2 = (Number) operandTwo; if (op1 instanceof Double || op2 instanceof Double) { return new TypedValue(Math.pow(op1.doubleValue(),op2.doubleValue())); + } else if (op1 instanceof Float || op2 instanceof Float) { + return new TypedValue(Math.pow(op1.floatValue(), op2.floatValue())); } else if (op1 instanceof Long || op2 instanceof Long) { double d= Math.pow(op1.longValue(), op2.longValue()); return new TypedValue((long)d);
true
Other
spring-projects
spring-framework
be8f23d75658a8b728912b644c138407d4914f8b.json
Add SpEL support for float literals This change ensures that SpEL expressions involving floats are supported natively as opposed to the previous behavior which required conversion to double, leading to potential downstream conversion ambiguities. Issue: SPR-9486
spring-expression/src/test/java/org/springframework/expression/spel/LiteralTests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2012 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. @@ -17,10 +17,9 @@ package org.springframework.expression.spel; import junit.framework.Assert; - import org.junit.Test; -import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.expression.spel.standard.SpelExpression; +import org.springframework.expression.spel.support.StandardEvaluationContext; /** * Tests the evaluation of basic literals: boolean, integer, hex integer, long, real, null, date @@ -126,12 +125,12 @@ public void testLiteralReal01_CreatingDoubles() { @Test public void testLiteralReal02_CreatingFloats() { // For now, everything becomes a double... - evaluate("1.25f", 1.25d, Double.class); - evaluate("2.5f", 2.5d, Double.class); - evaluate("-3.5f", -3.5d, Double.class); - evaluate("1.25F", 1.25d, Double.class); - evaluate("2.5F", 2.5d, Double.class); - evaluate("-3.5F", -3.5d, Double.class); + evaluate("1.25f", 1.25f, Float.class); + evaluate("2.5f", 2.5f, Float.class); + evaluate("-3.5f", -3.5f, Float.class); + evaluate("1.25F", 1.25f, Float.class); + evaluate("2.5F", 2.5f, Float.class); + evaluate("-3.5F", -3.5f, Float.class); } @Test @@ -140,7 +139,7 @@ public void testLiteralReal03_UsingExponents() { evaluate("6.0221415e+23", "6.0221415E23", Double.class); evaluate("6.0221415E+23d", "6.0221415E23", Double.class); evaluate("6.0221415e+23D", "6.0221415E23", Double.class); - evaluate("6E2f", 600.0d, Double.class); + evaluate("6E2f", 6E2f, Float.class); } @Test
true
Other
spring-projects
spring-framework
be8f23d75658a8b728912b644c138407d4914f8b.json
Add SpEL support for float literals This change ensures that SpEL expressions involving floats are supported natively as opposed to the previous behavior which required conversion to double, leading to potential downstream conversion ambiguities. Issue: SPR-9486
spring-expression/src/test/java/org/springframework/expression/spel/OperatorTests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2012 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. @@ -17,7 +17,6 @@ package org.springframework.expression.spel; import junit.framework.Assert; - import org.junit.Test; import org.springframework.expression.spel.ast.Operator; import org.springframework.expression.spel.standard.SpelExpression; @@ -187,7 +186,7 @@ public void testIntegerArithmetic() { evaluate("5 - 4", "1", Integer.class); evaluate("3 * 5", 15, Integer.class); evaluate("3.2d * 5", 16.0d, Double.class); - evaluate("3 * 5f", 15d, Double.class); + evaluate("3 * 5f", 15f, Float.class); evaluate("3 / 1", 3, Integer.class); evaluate("3 % 2", 1, Integer.class); evaluate("3 mod 2", 1, Integer.class); @@ -199,7 +198,7 @@ public void testIntegerArithmetic() { @Test public void testPlus() throws Exception { evaluate("7 + 2", "9", Integer.class); - evaluate("3.0f + 5.0f", 8.0d, Double.class); + evaluate("3.0f + 5.0f", 8.0f, Float.class); evaluate("3.0d + 5.0d", 8.0d, Double.class); evaluate("'ab' + 2", "ab2", String.class); @@ -229,7 +228,7 @@ public void testPlus() throws Exception { @Test public void testMinus() throws Exception { evaluate("'c' - 2", "a", String.class); - evaluate("3.0f - 5.0f", -2.0d, Double.class); + evaluate("3.0f - 5.0f", -2.0f, Float.class); evaluateAndCheckError("'ab' - 2", SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES); evaluateAndCheckError("2-'ab'",SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES); SpelExpression expr = (SpelExpression)parser.parseExpression("-3"); @@ -247,16 +246,16 @@ public void testMinus() throws Exception { public void testModulus() { evaluate("3%2",1,Integer.class); evaluate("3L%2L",1L,Long.class); - evaluate("3.0f%2.0f",1d,Double.class); + evaluate("3.0f%2.0f",1f,Float.class); evaluate("5.0d % 3.1d", 1.9d, Double.class); evaluateAndCheckError("'abc'%'def'",SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES); } @Test public void testDivide() { - evaluate("3.0f / 5.0f", 0.6d, Double.class); + evaluate("3.0f / 5.0f", 0.6f, Float.class); evaluate("4L/2L",2L,Long.class); - evaluate("3.0f div 5.0f", 0.6d, Double.class); + evaluate("3.0f div 5.0f", 0.6f, Float.class); evaluate("4L DIV 2L",2L,Long.class); evaluateAndCheckError("'abc'/'def'",SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES); } @@ -350,9 +349,9 @@ public void testMixedOperands_FloatsAndDoubles() { public void testMixedOperands_DoublesAndInts() { evaluate("3.0d + 5", 8.0d, Double.class); evaluate("3.0D - 5", -2.0d, Double.class); - evaluate("3.0f * 5", 15.0d, Double.class); - evaluate("6.0f / 2", 3.0, Double.class); - evaluate("6.0f / 4", 1.5d, Double.class); + evaluate("3.0f * 5", 15.0f, Float.class); + evaluate("6.0f / 2", 3.0f, Float.class); + evaluate("6.0f / 4", 1.5f, Float.class); evaluate("5.0D % 3", 2.0d, Double.class); evaluate("5.5D % 3", 2.5, Double.class); }
true
Other
spring-projects
spring-framework
be8f23d75658a8b728912b644c138407d4914f8b.json
Add SpEL support for float literals This change ensures that SpEL expressions involving floats are supported natively as opposed to the previous behavior which required conversion to double, leading to potential downstream conversion ambiguities. Issue: SPR-9486
spring-expression/src/test/java/org/springframework/expression/spel/SpringEL300Tests.java
@@ -16,41 +16,25 @@ package org.springframework.expression.spel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - import junit.framework.Assert; - import org.junit.Ignore; import org.junit.Test; import org.springframework.core.convert.TypeDescriptor; -import org.springframework.expression.AccessException; -import org.springframework.expression.BeanResolver; -import org.springframework.expression.EvaluationContext; -import org.springframework.expression.EvaluationException; -import org.springframework.expression.Expression; -import org.springframework.expression.ExpressionParser; -import org.springframework.expression.MethodExecutor; -import org.springframework.expression.MethodResolver; -import org.springframework.expression.ParserContext; -import org.springframework.expression.PropertyAccessor; -import org.springframework.expression.TypedValue; +import org.springframework.expression.*; import org.springframework.expression.spel.standard.SpelExpression; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.ReflectiveMethodResolver; import org.springframework.expression.spel.support.ReflectivePropertyAccessor; import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.expression.spel.support.StandardTypeLocator; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.*; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + /** * Tests based on Jiras up to the release of Spring 3.0.0 * @@ -1204,6 +1188,425 @@ public void testArray() { assertEquals("Equal assertion failed: ", "class [[I", result.toString()); } + @Test + public void SPR_9486_floatFunctionResolverTest() { + try { + Number expectedResult = Math.abs(-10.2f); + ExpressionParser parser = new SpelExpressionParser(); + SPR_9486_FunctionsClass testObject = new SPR_9486_FunctionsClass(); + + StandardEvaluationContext context = new StandardEvaluationContext(); + org.springframework.expression.Expression expression = parser.parseExpression("abs(-10.2f)"); + Number result = expression.getValue(context, testObject, Number.class); + Assert.assertEquals("Equal assertion failed for SPR_9486_floatFunctionResolverTest Test: ", expectedResult, result); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Test failed - SPR_9486_floatFunctionResolverTest"); + } + } + + class SPR_9486_FunctionsClass { + public int abs(int value) { + return Math.abs(value); + } + + public float abs(float value) { + return Math.abs(value); + } + } + + @Test + public void SPR_9486_addFloatWithDoubleTest() { + try { + Number expectedNumber = 10.21f + 10.2; + ExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext context = new StandardEvaluationContext(); + org.springframework.expression.Expression expression = parser.parseExpression("10.21f + 10.2"); + Number result = expression.getValue(context, null, Number.class); + Assert.assertEquals("Equal assertion failed for SPR_9486_addFloatWithDoubleTest Test: ", expectedNumber, result); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Test failed - SPR_9486_addFloatWithDoubleTest"); + } + } + + @Test + public void SPR_9486_addFloatWithFloatTest() { + try { + Number expectedNumber = 10.21f + 10.2f; + ExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext context = new StandardEvaluationContext(); + org.springframework.expression.Expression expression = parser.parseExpression("10.21f + 10.2f"); + Number result = expression.getValue(context, null, Number.class); + Assert.assertEquals("Equal assertion failed for SPR_9486_addFloatWithFloatTest Test: ", expectedNumber, result); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Test failed - SPR_9486_addFloatWithFloatTest"); + } + } + + @Test + public void SPR_9486_subtractFloatWithDoubleTest() { + try { + Number expectedNumber = 10.21f - 10.2; + ExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext context = new StandardEvaluationContext(); + org.springframework.expression.Expression expression = parser.parseExpression("10.21f - 10.2"); + Number result = expression.getValue(context, null, Number.class); + Assert.assertEquals("Equal assertion failed for SPR_9486_subtractFloatWithDoubleTest Test: ", expectedNumber, result); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Test failed - SPR_9486_subtractFloatWithDoubleTest"); + } + } + + @Test + public void SPR_9486_subtractFloatWithFloatTest() { + try { + Number expectedNumber = 10.21f - 10.2f; + ExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext context = new StandardEvaluationContext(); + org.springframework.expression.Expression expression = parser.parseExpression("10.21f - 10.2f"); + Number result = expression.getValue(context, null, Number.class); + Assert.assertEquals("Equal assertion failed for SPR_9486_subtractFloatWithFloatTest Test: ", expectedNumber, result); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Test failed - SPR_9486_subtractFloatWithFloatTest"); + } + } + + @Test + public void SPR_9486_multiplyFloatWithDoubleTest() { + try { + Number expectedNumber = 10.21f * 10.2; + ExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext context = new StandardEvaluationContext(); + org.springframework.expression.Expression expression = parser.parseExpression("10.21f * 10.2"); + Number result = expression.getValue(context, null, Number.class); + Assert.assertEquals("Equal assertion failed for float multiplied by double Test: ", expectedNumber, result); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Test failed - SPR_9486_multiplyFloatWithDoubleTest"); + } + } + + @Test + public void SPR_9486_multiplyFloatWithFloatTest() { + try { + Number expectedNumber = 10.21f * 10.2f; + ExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext context = new StandardEvaluationContext(); + org.springframework.expression.Expression expression = parser.parseExpression("10.21f * 10.2f"); + Number result = expression.getValue(context, null, Number.class); + Assert.assertEquals("Equal assertion failed for float multiply by another float Test: ", expectedNumber, result); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Test failed - SPR_9486_multiplyFloatWithFloatTest"); + } + } + + @Test + public void SPR_9486_floatDivideByFloatTest() { + try { + Number expectedNumber = -10.21f/-10.2f; + ExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext context = new StandardEvaluationContext(); + org.springframework.expression.Expression expression = parser.parseExpression("-10.21f / -10.2f"); + Number result = expression.getValue(context, null, Number.class); + Assert.assertEquals("Equal assertion failed for float divide Test: ", expectedNumber, result); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Test failed - SPR_9486_floatDivideByFloatTest"); + } + } + + @Test + public void SPR_9486_floatDivideByDoubleTest() { + try { + Number expectedNumber = -10.21f/-10.2; + ExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext context = new StandardEvaluationContext(); + org.springframework.expression.Expression expression = parser.parseExpression("-10.21f / -10.2"); + Number result = expression.getValue(context, null, Number.class); + Assert.assertEquals("Equal assertion failed for float divide Test: ", expectedNumber, result); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Test failed - SPR_9486_floatDivideByDoubleTest"); + } + } + + @Test + public void SPR_9486_floatEqFloatUnaryMinusTest() { + try { + Boolean expectedResult = -10.21f == -10.2f; + ExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext context = new StandardEvaluationContext(); + org.springframework.expression.Expression expression = parser.parseExpression("-10.21f == -10.2f"); + Boolean result = expression.getValue(context, null, Boolean.class); + Assert.assertEquals("Equal assertion failed for SPR_9486_floatEqFloatUnaryMinusTest Test: ", expectedResult, result); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Test failed - SPR_9486_floatEqFloatUnaryMinusTest"); + } + } + + @Test + public void SPR_9486_floatEqDoubleUnaryMinusTest() { + try { + Boolean expectedResult = -10.21f == -10.2; + ExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext context = new StandardEvaluationContext(); + org.springframework.expression.Expression expression = parser.parseExpression("-10.21f == -10.2"); + Boolean result = expression.getValue(context, null, Boolean.class); + Assert.assertEquals("Equal assertion failed for SPR_9486_floatEqDoubleUnaryMinusTest Test: ", expectedResult, result); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Test failed - SPR_9486_floatEqDoubleUnaryMinusTest"); + } + } + + @Test + public void SPR_9486_floatEqFloatTest() { + try { + Boolean expectedResult = 10.215f == 10.2109f; + ExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext context = new StandardEvaluationContext(); + org.springframework.expression.Expression expression = parser.parseExpression("10.215f == 10.2109f"); + Boolean result = expression.getValue(context, null, Boolean.class); + Assert.assertEquals("Equal assertion failed for SPR_9486_floatEqFloatTest Test: ", expectedResult, result); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Test failed - SPR_9486_floatEqFloatTest"); + } + } + + @Test + public void SPR_9486_floatEqDoubleTest() { + try { + Boolean expectedResult = 10.215f == 10.2109; + ExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext context = new StandardEvaluationContext(); + org.springframework.expression.Expression expression = parser.parseExpression("10.215f == 10.2109"); + Boolean result = expression.getValue(context, null, Boolean.class); + Assert.assertEquals("Equal assertion failed for SPR_9486_floatEqDoubleTest() Test: ", expectedResult, result); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Test failed - SPR_9486_floatEqDoubleTest()"); + } + } + + @Test + public void SPR_9486_floatNotEqFloatTest() { + try { + Boolean expectedResult = 10.215f != 10.2109f; + ExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext context = new StandardEvaluationContext(); + org.springframework.expression.Expression expression = parser.parseExpression("10.215f != 10.2109f"); + Boolean result = expression.getValue(context, null, Boolean.class); + Assert.assertEquals("Equal assertion failed for SPR_9486_floatEqFloatTest Test: ", expectedResult, result); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Test failed - SPR_9486_floatEqFloatTest"); + } + } + + @Test + public void SPR_9486_floatNotEqDoubleTest() { + try { + Boolean expectedResult = 10.215f != 10.2109; + ExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext context = new StandardEvaluationContext(); + org.springframework.expression.Expression expression = parser.parseExpression("10.215f != 10.2109"); + Boolean result = expression.getValue(context, null, Boolean.class); + Assert.assertEquals("Equal assertion failed for SPR_9486_floatNotEqDoubleTest Test: ", expectedResult, result); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Test failed - SPR_9486_floatNotEqDoubleTest"); + } + } + + + + @Test + public void SPR_9486_floatLessThanFloatTest() { + try { + Boolean expectedNumber = -10.21f < -10.2f; + ExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext context = new StandardEvaluationContext(); + org.springframework.expression.Expression expression = parser.parseExpression("-10.21f < -10.2f"); + Boolean result = expression.getValue(context, null, Boolean.class); + Assert.assertEquals("Equal assertion failed for SPR_9486_floatLessThanFloatTest Test: ", expectedNumber, result); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Test failed - SPR_9486_floatLessThanFloatTest()"); + } + } + + @Test + public void SPR_9486_floatLessThanDoubleTest() { + try { + Boolean expectedNumber = -10.21f < -10.2; + ExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext context = new StandardEvaluationContext(); + org.springframework.expression.Expression expression = parser.parseExpression("-10.21f < -10.2"); + Boolean result = expression.getValue(context, null, Boolean.class); + Assert.assertEquals("Equal assertion failed for SPR_9486_floatLessThanDoubleTest Test: ", expectedNumber, result); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Test failed - SPR_9486_floatLessThanDoubleTest()"); + } + } + + @Test + public void SPR_9486_floatLessThanOrEqualFloatTest() { + try { + Boolean expectedNumber = -10.21f <= -10.22f; + ExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext context = new StandardEvaluationContext(); + org.springframework.expression.Expression expression = parser.parseExpression("-10.21f <= -10.22f"); + Boolean result = expression.getValue(context, null, Boolean.class); + Assert.assertEquals("Equal assertion failed for SPR_9486_floatLessThanOrEqualFloatTest Test: ", expectedNumber, result); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Test failed - SPR_9486_floatLessThanOrEqualFloatTest"); + } + } + + @Test + public void SPR_9486_floatLessThanOrEqualDoubleTest() { + try { + Boolean expectedNumber = -10.21f <= -10.2; + ExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext context = new StandardEvaluationContext(); + org.springframework.expression.Expression expression = parser.parseExpression("-10.21f <= -10.2"); + Boolean result = expression.getValue(context, null, Boolean.class); + Assert.assertEquals("Equal assertion failed for SPR_9486_floatLessThanOrEqualDoubleTest Test: ", expectedNumber, result); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Test failed - SPR_9486_floatLessThanOrEqualDoubleTest"); + } + } + + @Test + public void SPR_9486_floatGreaterThanFloatTest() { + try { + Boolean expectedNumber = -10.21f > -10.2f; + ExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext context = new StandardEvaluationContext(); + org.springframework.expression.Expression expression = parser.parseExpression("-10.21f > -10.2f"); + Boolean result = expression.getValue(context, null, Boolean.class); + Assert.assertEquals("Equal assertion failed for SPR_9486_floatGreaterThanFloatTest Test: ", expectedNumber, result); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Test failed - SPR_9486_floatGreaterThanTest"); + } + } + + @Test + public void SPR_9486_floatGreaterThanDoubleTest() { + try { + Boolean expectedResult = -10.21f > -10.2; + ExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext context = new StandardEvaluationContext(); + org.springframework.expression.Expression expression = parser.parseExpression("-10.21f > -10.2"); + Boolean result = expression.getValue(context, null, Boolean.class); + Assert.assertEquals("Equal assertion failed for SPR_9486_floatGreaterThanDoubleTest Test: ", expectedResult, result); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Test failed - SPR_9486_floatGreaterThanTest"); + } + } + + @Test + public void SPR_9486_floatGreaterThanOrEqualFloatTest() { + try { + Boolean expectedNumber = -10.21f >= -10.2f; + ExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext context = new StandardEvaluationContext(); + org.springframework.expression.Expression expression = parser.parseExpression("-10.21f >= -10.2f"); + Boolean result = expression.getValue(context, null, Boolean.class); + Assert.assertEquals("Equal assertion failed for SPR_9486_floatGreaterThanFloatTest Test: ", expectedNumber, result); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Test failed - SPR_9486_floatGreaterThanTest"); + } + } + + @Test + public void SPR_9486_floatGreaterThanEqualDoubleTest() { + try { + Boolean expectedResult = -10.21f >= -10.2; + ExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext context = new StandardEvaluationContext(); + org.springframework.expression.Expression expression = parser.parseExpression("-10.21f >= -10.2"); + Boolean result = expression.getValue(context, null, Boolean.class); + Assert.assertEquals("Equal assertion failed for SPR_9486_floatGreaterThanDoubleTest Test: ", expectedResult, result); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Test failed - SPR_9486_floatGreaterThanTest"); + } + } + + @Test + public void SPR_9486_floatModulusFloatTest() { + try { + Number expectedResult = 10.21f % 10.2f; + ExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext context = new StandardEvaluationContext(); + org.springframework.expression.Expression expression = parser.parseExpression("10.21f % 10.2f"); + Number result = expression.getValue(context, null, Number.class); + Assert.assertEquals("Equal assertion failed for SPR_9486_floatModulusFloatTest Test: ", expectedResult, result); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Test failed - SPR_9486_floatModulusFloatTest"); + } + } + + @Test + public void SPR_9486_floatModulusDoubleTest() { + try { + Number expectedResult = 10.21f % 10.2; + ExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext context = new StandardEvaluationContext(); + org.springframework.expression.Expression expression = parser.parseExpression("10.21f % 10.2"); + Number result = expression.getValue(context, null, Number.class); + Assert.assertEquals("Equal assertion failed for SPR_9486_floatModulusDoubleTest Test: ", expectedResult, result); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Test failed - SPR_9486_floatModulusDoubleTest"); + } + } + + @Test + public void SPR_9486_floatPowerFloatTest() { + try { + Number expectedResult = Math.pow(10.21f, -10.2f); + ExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext context = new StandardEvaluationContext(); + org.springframework.expression.Expression expression = parser.parseExpression("10.21f ^ -10.2f"); + Number result = expression.getValue(context, null, Number.class); + Assert.assertEquals("Equal assertion failed for SPR_9486_floatPowerFloatTest Test: ", expectedResult, result); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Test failed - SPR_9486_floatPowerFloatTest"); + } + } + + @Test + public void SPR_9486_floatPowerDoubleTest() { + try { + Number expectedResult = Math.pow(10.21f, 10.2); + ExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext context = new StandardEvaluationContext(); + org.springframework.expression.Expression expression = parser.parseExpression("10.21f ^ 10.2"); + Number result = expression.getValue(context, null, Number.class); + Assert.assertEquals("Equal assertion failed for SPR_9486_floatPowerDoubleTest Test: ", expectedResult, result); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Test failed - SPR_9486_floatPowerDoubleTest"); + } + } + }
true
Other
spring-projects
spring-framework
f64325882da41bb128dec1b6d687b6eb6525623f.json
Add SpEL support for increment/decrement operators With this commit the Spring Expression Language now supports increment (++) and decrement (--) operators. These can be used as either prefix or postfix operators. For example: 'somearray[index++]' and 'somearray[--index]' are valid. In order to support this there are serious changes to the evaluation process for expressions. The concept of a value reference for an expression component has been introduced. Value references can be passed around and at any time the actual value can be retrieved (via a get) or set (where applicable). This was needed to avoid double evaluation of expression components. For example, in evaluating the expression 'somearray[index++]--' without a value reference SpEL would need to evaluate the 'somearray[index++]' component twice, once to get the value and then again to determine where to put the new value. If that component is evaluated twice, index would be double incremented. A value reference for 'somearray[index++]' avoids this problem. Many new tests have been introduced into the EvaluationTests to ensure not only that ++ and -- work but also that the introduction of value references across the all of SpEL has not caused regressions. Issue: SPR-9751
spring-expression/src/main/java/org/springframework/expression/spel/ExpressionState.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2012 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. @@ -28,6 +28,7 @@ import org.springframework.expression.OperatorOverloader; import org.springframework.expression.PropertyAccessor; import org.springframework.expression.TypeComparator; +import org.springframework.expression.TypeConverter; import org.springframework.expression.TypedValue; /** @@ -140,6 +141,10 @@ public Object convertValue(Object value, TypeDescriptor targetTypeDescriptor) th return this.relatedContext.getTypeConverter().convertValue(value, TypeDescriptor.forObject(value), targetTypeDescriptor); } + public TypeConverter getTypeConverter() { + return this.relatedContext.getTypeConverter(); + } + public Object convertValue(TypedValue value, TypeDescriptor targetTypeDescriptor) throws EvaluationException { Object val = value.getValue(); return this.relatedContext.getTypeConverter().convertValue(val, TypeDescriptor.forObject(val), targetTypeDescriptor);
true
Other
spring-projects
spring-framework
f64325882da41bb128dec1b6d687b6eb6525623f.json
Add SpEL support for increment/decrement operators With this commit the Spring Expression Language now supports increment (++) and decrement (--) operators. These can be used as either prefix or postfix operators. For example: 'somearray[index++]' and 'somearray[--index]' are valid. In order to support this there are serious changes to the evaluation process for expressions. The concept of a value reference for an expression component has been introduced. Value references can be passed around and at any time the actual value can be retrieved (via a get) or set (where applicable). This was needed to avoid double evaluation of expression components. For example, in evaluating the expression 'somearray[index++]--' without a value reference SpEL would need to evaluate the 'somearray[index++]' component twice, once to get the value and then again to determine where to put the new value. If that component is evaluated twice, index would be double incremented. A value reference for 'somearray[index++]' avoids this problem. Many new tests have been introduced into the EvaluationTests to ensure not only that ++ and -- work but also that the introduction of value references across the all of SpEL has not caused regressions. Issue: SPR-9751
spring-expression/src/main/java/org/springframework/expression/spel/SpelMessage.java
@@ -104,7 +104,10 @@ public enum SpelMessage { MISSING_ARRAY_DIMENSION(Kind.ERROR, 1063, "A required array dimension has not been specified"), // INITIALIZER_LENGTH_INCORRECT( Kind.ERROR, 1064, "array initializer size does not match array dimensions"), // - UNEXPECTED_ESCAPE_CHAR(Kind.ERROR,1065,"unexpected escape character."); + UNEXPECTED_ESCAPE_CHAR(Kind.ERROR,1065,"unexpected escape character."), // + OPERAND_NOT_INCREMENTABLE(Kind.ERROR,1066,"the expression component ''{0}'' does not support increment"), // + OPERAND_NOT_DECREMENTABLE(Kind.ERROR,1067,"the expression component ''{0}'' does not support decrement"), // + NOT_ASSIGNABLE(Kind.ERROR,1068,"the expression component ''{0}'' is not assignable"), // ; private Kind kind;
true
Other
spring-projects
spring-framework
f64325882da41bb128dec1b6d687b6eb6525623f.json
Add SpEL support for increment/decrement operators With this commit the Spring Expression Language now supports increment (++) and decrement (--) operators. These can be used as either prefix or postfix operators. For example: 'somearray[index++]' and 'somearray[--index]' are valid. In order to support this there are serious changes to the evaluation process for expressions. The concept of a value reference for an expression component has been introduced. Value references can be passed around and at any time the actual value can be retrieved (via a get) or set (where applicable). This was needed to avoid double evaluation of expression components. For example, in evaluating the expression 'somearray[index++]--' without a value reference SpEL would need to evaluate the 'somearray[index++]' component twice, once to get the value and then again to determine where to put the new value. If that component is evaluated twice, index would be double incremented. A value reference for 'somearray[index++]' avoids this problem. Many new tests have been introduced into the EvaluationTests to ensure not only that ++ and -- work but also that the introduction of value references across the all of SpEL has not caused regressions. Issue: SPR-9751
spring-expression/src/main/java/org/springframework/expression/spel/ast/AstUtils.java
@@ -1,5 +1,5 @@ /* - * Copyright 2010 the original author or authors. + * Copyright 2010-2012 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. @@ -41,10 +41,10 @@ public class AstUtils { * @param targetType the type upon which property access is being attempted * @return a list of resolvers that should be tried in order to access the property */ - public static List<PropertyAccessor> getPropertyAccessorsToTry(Class<?> targetType, ExpressionState state) { + public static List<PropertyAccessor> getPropertyAccessorsToTry(Class<?> targetType, List<PropertyAccessor> propertyAccessors) { List<PropertyAccessor> specificAccessors = new ArrayList<PropertyAccessor>(); List<PropertyAccessor> generalAccessors = new ArrayList<PropertyAccessor>(); - for (PropertyAccessor resolver : state.getPropertyAccessors()) { + for (PropertyAccessor resolver : propertyAccessors) { Class<?>[] targets = resolver.getSpecificTargetClasses(); if (targets == null) { // generic resolver that says it can be used for any type generalAccessors.add(resolver);
true
Other
spring-projects
spring-framework
f64325882da41bb128dec1b6d687b6eb6525623f.json
Add SpEL support for increment/decrement operators With this commit the Spring Expression Language now supports increment (++) and decrement (--) operators. These can be used as either prefix or postfix operators. For example: 'somearray[index++]' and 'somearray[--index]' are valid. In order to support this there are serious changes to the evaluation process for expressions. The concept of a value reference for an expression component has been introduced. Value references can be passed around and at any time the actual value can be retrieved (via a get) or set (where applicable). This was needed to avoid double evaluation of expression components. For example, in evaluating the expression 'somearray[index++]--' without a value reference SpEL would need to evaluate the 'somearray[index++]' component twice, once to get the value and then again to determine where to put the new value. If that component is evaluated twice, index would be double incremented. A value reference for 'somearray[index++]' avoids this problem. Many new tests have been introduced into the EvaluationTests to ensure not only that ++ and -- work but also that the introduction of value references across the all of SpEL has not caused regressions. Issue: SPR-9751
spring-expression/src/main/java/org/springframework/expression/spel/ast/CompoundExpression.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2012 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. @@ -35,22 +35,19 @@ public CompoundExpression(int pos,SpelNodeImpl... expressionComponents) { throw new IllegalStateException("Dont build compound expression less than one entry: "+expressionComponents.length); } } - - /** - * Evalutes a compound expression. This involves evaluating each piece in turn and the return value from each piece - * is the active context object for the subsequent piece. - * @param state the state in which the expression is being evaluated - * @return the final value from the last piece of the compound expression - */ @Override - public TypedValue getValueInternal(ExpressionState state) throws EvaluationException { + protected ValueRef getValueRef(ExpressionState state) throws EvaluationException { + if (getChildCount()==1) { + return children[0].getValueRef(state); + } TypedValue result = null; SpelNodeImpl nextNode = null; try { nextNode = children[0]; result = nextNode.getValueInternal(state); - for (int i = 1; i < getChildCount(); i++) { + int cc = getChildCount(); + for (int i = 1; i < cc-1; i++) { try { state.pushActiveContextObject(result); nextNode = children[i]; @@ -59,57 +56,39 @@ public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep state.popActiveContextObject(); } } + try { + state.pushActiveContextObject(result); + nextNode = children[cc-1]; + return nextNode.getValueRef(state); + } finally { + state.popActiveContextObject(); + } } catch (SpelEvaluationException ee) { - // Correct the position for the error before rethrowing + // Correct the position for the error before re-throwing ee.setPosition(nextNode.getStartPosition()); throw ee; } - return result; + } + + /** + * Evaluates a compound expression. This involves evaluating each piece in turn and the return value from each piece + * is the active context object for the subsequent piece. + * @param state the state in which the expression is being evaluated + * @return the final value from the last piece of the compound expression + */ + @Override + public TypedValue getValueInternal(ExpressionState state) throws EvaluationException { + return getValueRef(state).getValue(); } @Override public void setValue(ExpressionState state, Object value) throws EvaluationException { - if (getChildCount() == 1) { - getChild(0).setValue(state, value); - return; - } - TypedValue ctx = children[0].getValueInternal(state); - for (int i = 1; i < getChildCount() - 1; i++) { - try { - state.pushActiveContextObject(ctx); - ctx = children[i].getValueInternal(state); - } finally { - state.popActiveContextObject(); - } - } - try { - state.pushActiveContextObject(ctx); - getChild(getChildCount() - 1).setValue(state, value); - } finally { - state.popActiveContextObject(); - } + getValueRef(state).setValue(value); } @Override public boolean isWritable(ExpressionState state) throws EvaluationException { - if (getChildCount() == 1) { - return getChild(0).isWritable(state); - } - TypedValue ctx = children[0].getValueInternal(state); - for (int i = 1; i < getChildCount() - 1; i++) { - try { - state.pushActiveContextObject(ctx); - ctx = children[i].getValueInternal(state); - } finally { - state.popActiveContextObject(); - } - } - try { - state.pushActiveContextObject(ctx); - return getChild(getChildCount() - 1).isWritable(state); - } finally { - state.popActiveContextObject(); - } + return getValueRef(state).isWritable(); } @Override
true
Other
spring-projects
spring-framework
f64325882da41bb128dec1b6d687b6eb6525623f.json
Add SpEL support for increment/decrement operators With this commit the Spring Expression Language now supports increment (++) and decrement (--) operators. These can be used as either prefix or postfix operators. For example: 'somearray[index++]' and 'somearray[--index]' are valid. In order to support this there are serious changes to the evaluation process for expressions. The concept of a value reference for an expression component has been introduced. Value references can be passed around and at any time the actual value can be retrieved (via a get) or set (where applicable). This was needed to avoid double evaluation of expression components. For example, in evaluating the expression 'somearray[index++]--' without a value reference SpEL would need to evaluate the 'somearray[index++]' component twice, once to get the value and then again to determine where to put the new value. If that component is evaluated twice, index would be double incremented. A value reference for 'somearray[index++]' avoids this problem. Many new tests have been introduced into the EvaluationTests to ensure not only that ++ and -- work but also that the introduction of value references across the all of SpEL has not caused regressions. Issue: SPR-9751
spring-expression/src/main/java/org/springframework/expression/spel/ast/Indexer.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2012 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. @@ -25,15 +25,17 @@ import org.springframework.expression.EvaluationContext; import org.springframework.expression.EvaluationException; import org.springframework.expression.PropertyAccessor; +import org.springframework.expression.TypeConverter; import org.springframework.expression.TypedValue; import org.springframework.expression.spel.ExpressionState; import org.springframework.expression.spel.SpelEvaluationException; import org.springframework.expression.spel.SpelMessage; import org.springframework.expression.spel.support.ReflectivePropertyAccessor; /** - * An Indexer can index into some proceeding structure to access a particular piece of it. - * Supported structures are: strings/collections (lists/sets)/arrays + * An Indexer can index into some proceeding structure to access a particular + * piece of it. Supported structures are: strings/collections + * (lists/sets)/arrays * * @author Andy Clement * @since 3.0 @@ -42,257 +44,420 @@ // TODO support correct syntax for multidimensional [][][] and not [,,,] public class Indexer extends SpelNodeImpl { - // These fields are used when the indexer is being used as a property read accessor. If the name and - // target type match these cached values then the cachedReadAccessor is used to read the property. - // If they do not match, the correct accessor is discovered and then cached for later use. + // These fields are used when the indexer is being used as a property read accessor. + // If the name and target type match these cached values then the cachedReadAccessor + // is used to read the property. If they do not match, the correct accessor is + // discovered and then cached for later use. private String cachedReadName; private Class<?> cachedReadTargetType; private PropertyAccessor cachedReadAccessor; - // These fields are used when the indexer is being used as a property write accessor. If the name and - // target type match these cached values then the cachedWriteAccessor is used to write the property. - // If they do not match, the correct accessor is discovered and then cached for later use. + // These fields are used when the indexer is being used as a property write accessor. + // If the name and target type match these cached values then the cachedWriteAccessor + // is used to write the property. If they do not match, the correct accessor is + // discovered and then cached for later use. private String cachedWriteName; private Class<?> cachedWriteTargetType; private PropertyAccessor cachedWriteAccessor; - public Indexer(int pos, SpelNodeImpl expr) { super(pos, expr); } @Override public TypedValue getValueInternal(ExpressionState state) throws EvaluationException { - TypedValue context = state.getActiveContextObject(); - Object targetObject = context.getValue(); - TypeDescriptor targetObjectTypeDescriptor = context.getTypeDescriptor(); - TypedValue indexValue = null; - Object index = null; - - // This first part of the if clause prevents a 'double dereference' of the property (SPR-5847) - if (targetObject instanceof Map && (children[0] instanceof PropertyOrFieldReference)) { - PropertyOrFieldReference reference = (PropertyOrFieldReference)children[0]; - index = reference.getName(); - indexValue = new TypedValue(index); + return getValueRef(state).getValue(); + } + + @Override + public void setValue(ExpressionState state, Object newValue) throws EvaluationException { + getValueRef(state).setValue(newValue); + } + + @Override + public boolean isWritable(ExpressionState expressionState) + throws SpelEvaluationException { + return true; + } + + class ArrayIndexingValueRef implements ValueRef { + + private TypeConverter typeConverter; + private Object array; + private int idx; + private TypeDescriptor typeDescriptor; + + ArrayIndexingValueRef(TypeConverter typeConverter, Object array, + int idx, TypeDescriptor typeDescriptor) { + this.typeConverter = typeConverter; + this.array = array; + this.idx = idx; + this.typeDescriptor = typeDescriptor; } - else { - // In case the map key is unqualified, we want it evaluated against the root object so - // temporarily push that on whilst evaluating the key - try { - state.pushActiveContextObject(state.getRootContextObject()); - indexValue = children[0].getValueInternal(state); - index = indexValue.getValue(); - } - finally { - state.popActiveContextObject(); - } + + public TypedValue getValue() { + Object arrayElement = accessArrayElement(array, idx); + return new TypedValue(arrayElement, + typeDescriptor.elementTypeDescriptor(arrayElement)); } - // Indexing into a Map - if (targetObject instanceof Map) { - Object key = index; - if (targetObjectTypeDescriptor.getMapKeyTypeDescriptor() != null) { - key = state.convertValue(key, targetObjectTypeDescriptor.getMapKeyTypeDescriptor()); + public void setValue(Object newValue) { + setArrayElement(typeConverter, array, idx, newValue, typeDescriptor + .getElementTypeDescriptor().getType()); + } + + public boolean isWritable() { + return true; + } + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + class MapIndexingValueRef implements ValueRef { + + private TypeConverter typeConverter; + private Map map; + private Object key; + private TypeDescriptor mapEntryTypeDescriptor; + + MapIndexingValueRef(TypeConverter typeConverter, Map map, Object key, + TypeDescriptor mapEntryTypeDescriptor) { + this.typeConverter = typeConverter; + this.map = map; + this.key = key; + this.mapEntryTypeDescriptor = mapEntryTypeDescriptor; + } + + public TypedValue getValue() { + Object value = map.get(key); + return new TypedValue(value, + mapEntryTypeDescriptor.getMapValueTypeDescriptor(value)); + } + + public void setValue(Object newValue) { + if (mapEntryTypeDescriptor.getMapValueTypeDescriptor() != null) { + newValue = typeConverter.convertValue(newValue, + TypeDescriptor.forObject(newValue), + mapEntryTypeDescriptor.getMapValueTypeDescriptor()); } - Object value = ((Map<?, ?>) targetObject).get(key); - return new TypedValue(value, targetObjectTypeDescriptor.getMapValueTypeDescriptor(value)); + map.put(key, newValue); } - - if (targetObject == null) { - throw new SpelEvaluationException(getStartPosition(),SpelMessage.CANNOT_INDEX_INTO_NULL_VALUE); + + public boolean isWritable() { + return true; } - - // if the object is something that looks indexable by an integer, attempt to treat the index value as a number - if (targetObject instanceof Collection || targetObject.getClass().isArray() || targetObject instanceof String) { - int idx = (Integer) state.convertValue(index, TypeDescriptor.valueOf(Integer.class)); - if (targetObject.getClass().isArray()) { - Object arrayElement = accessArrayElement(targetObject, idx); - return new TypedValue(arrayElement, targetObjectTypeDescriptor.elementTypeDescriptor(arrayElement)); - } else if (targetObject instanceof Collection) { - Collection c = (Collection) targetObject; - if (idx >= c.size()) { - if (!growCollection(state, targetObjectTypeDescriptor, idx, c)) { - throw new SpelEvaluationException(getStartPosition(),SpelMessage.COLLECTION_INDEX_OUT_OF_BOUNDS, c.size(), idx); - } + + } + + class PropertyIndexingValueRef implements ValueRef { + + private Object targetObject; + private String name; + private EvaluationContext eContext; + private TypeDescriptor td; + + public PropertyIndexingValueRef(Object targetObject, String value, + EvaluationContext evaluationContext, + TypeDescriptor targetObjectTypeDescriptor) { + this.targetObject = targetObject; + this.name = value; + this.eContext = evaluationContext; + this.td = targetObjectTypeDescriptor; + } + + public TypedValue getValue() { + Class<?> targetObjectRuntimeClass = getObjectClass(targetObject); + + try { + if (cachedReadName != null + && cachedReadName.equals(name) + && cachedReadTargetType != null + && cachedReadTargetType + .equals(targetObjectRuntimeClass)) { + // it is OK to use the cached accessor + return cachedReadAccessor + .read(eContext, targetObject, name); } - int pos = 0; - for (Object o : c) { - if (pos == idx) { - return new TypedValue(o, targetObjectTypeDescriptor.elementTypeDescriptor(o)); + + List<PropertyAccessor> accessorsToTry = AstUtils + .getPropertyAccessorsToTry(targetObjectRuntimeClass, + eContext.getPropertyAccessors()); + + if (accessorsToTry != null) { + for (PropertyAccessor accessor : accessorsToTry) { + if (accessor.canRead(eContext, targetObject, name)) { + if (accessor instanceof ReflectivePropertyAccessor) { + accessor = ((ReflectivePropertyAccessor) accessor) + .createOptimalAccessor(eContext, + targetObject, name); + } + cachedReadAccessor = accessor; + cachedReadName = name; + cachedReadTargetType = targetObjectRuntimeClass; + return accessor.read(eContext, targetObject, name); + } } - pos++; - } - } else if (targetObject instanceof String) { - String ctxString = (String) targetObject; - if (idx >= ctxString.length()) { - throw new SpelEvaluationException(getStartPosition(),SpelMessage.STRING_INDEX_OUT_OF_BOUNDS, ctxString.length(), idx); } - return new TypedValue(String.valueOf(ctxString.charAt(idx))); + } catch (AccessException e) { + throw new SpelEvaluationException(getStartPosition(), e, + SpelMessage.INDEXING_NOT_SUPPORTED_FOR_TYPE, + td.toString()); } + throw new SpelEvaluationException(getStartPosition(), + SpelMessage.INDEXING_NOT_SUPPORTED_FOR_TYPE, td.toString()); } - - // Try and treat the index value as a property of the context object - // TODO could call the conversion service to convert the value to a String - if (indexValue.getTypeDescriptor().getType()==String.class) { - Class<?> targetObjectRuntimeClass = getObjectClass(targetObject); - String name = (String)indexValue.getValue(); - EvaluationContext eContext = state.getEvaluationContext(); + + public void setValue(Object newValue) { + Class<?> contextObjectClass = getObjectClass(targetObject); try { - if (cachedReadName!=null && cachedReadName.equals(name) && cachedReadTargetType!=null && cachedReadTargetType.equals(targetObjectRuntimeClass)) { + if (cachedWriteName != null && cachedWriteName.equals(name) + && cachedWriteTargetType != null + && cachedWriteTargetType.equals(contextObjectClass)) { // it is OK to use the cached accessor - return cachedReadAccessor.read(eContext, targetObject, name); + cachedWriteAccessor.write(eContext, targetObject, name, + newValue); + return; } - - List<PropertyAccessor> accessorsToTry = AstUtils.getPropertyAccessorsToTry(targetObjectRuntimeClass, state); - - if (accessorsToTry != null) { + + List<PropertyAccessor> accessorsToTry = AstUtils + .getPropertyAccessorsToTry(contextObjectClass, + eContext.getPropertyAccessors()); + if (accessorsToTry != null) { for (PropertyAccessor accessor : accessorsToTry) { - if (accessor.canRead(eContext, targetObject, name)) { - if (accessor instanceof ReflectivePropertyAccessor) { - accessor = ((ReflectivePropertyAccessor)accessor).createOptimalAccessor(eContext, targetObject, name); - } - this.cachedReadAccessor = accessor; - this.cachedReadName = name; - this.cachedReadTargetType = targetObjectRuntimeClass; - return accessor.read(eContext, targetObject, name); - } + if (accessor.canWrite(eContext, targetObject, name)) { + cachedWriteName = name; + cachedWriteTargetType = contextObjectClass; + cachedWriteAccessor = accessor; + accessor.write(eContext, targetObject, name, + newValue); + return; + } } } - } catch (AccessException e) { - throw new SpelEvaluationException(getStartPosition(), e, SpelMessage.INDEXING_NOT_SUPPORTED_FOR_TYPE, targetObjectTypeDescriptor.toString()); + } catch (AccessException ae) { + throw new SpelEvaluationException(getStartPosition(), ae, + SpelMessage.EXCEPTION_DURING_PROPERTY_WRITE, name, + ae.getMessage()); } } - - throw new SpelEvaluationException(getStartPosition(),SpelMessage.INDEXING_NOT_SUPPORTED_FOR_TYPE, targetObjectTypeDescriptor.toString()); - } - - @Override - public boolean isWritable(ExpressionState expressionState) throws SpelEvaluationException { - return true; + + public boolean isWritable() { + return true; + } } - - @SuppressWarnings("unchecked") - @Override - public void setValue(ExpressionState state, Object newValue) throws EvaluationException { - TypedValue contextObject = state.getActiveContextObject(); - Object targetObject = contextObject.getValue(); - TypeDescriptor targetObjectTypeDescriptor = contextObject.getTypeDescriptor(); - TypedValue index = children[0].getValueInternal(state); - if (targetObject == null) { - throw new SpelEvaluationException(SpelMessage.CANNOT_INDEX_INTO_NULL_VALUE); + @SuppressWarnings({ "rawtypes", "unchecked" }) + class CollectionIndexingValueRef implements ValueRef { + + private TypeConverter typeConverter; + private Collection collection; + private int index; + private TypeDescriptor collectionEntryTypeDescriptor; + private boolean growCollection; + + CollectionIndexingValueRef(Collection collection, int index, + TypeDescriptor collectionEntryTypeDescriptor, TypeConverter typeConverter, boolean growCollection) { + this.typeConverter = typeConverter; + this.growCollection = growCollection; + this.collection = collection; + this.index = index; + this.collectionEntryTypeDescriptor = collectionEntryTypeDescriptor; } - // Indexing into a Map - if (targetObject instanceof Map) { - Map map = (Map) targetObject; - Object key = index.getValue(); - if (targetObjectTypeDescriptor.getMapKeyTypeDescriptor() != null) { - key = state.convertValue(index, targetObjectTypeDescriptor.getMapKeyTypeDescriptor()); + + public TypedValue getValue() { + if (index >= collection.size()) { + if (growCollection) { + growCollection(collectionEntryTypeDescriptor,index,collection); + } else { + throw new SpelEvaluationException(getStartPosition(), + SpelMessage.COLLECTION_INDEX_OUT_OF_BOUNDS, + collection.size(), index); + } } - if (targetObjectTypeDescriptor.getMapValueTypeDescriptor() != null) { - newValue = state.convertValue(newValue, targetObjectTypeDescriptor.getMapValueTypeDescriptor()); + int pos = 0; + for (Object o : collection) { + if (pos == index) { + return new TypedValue(o, + collectionEntryTypeDescriptor + .elementTypeDescriptor(o)); + } + pos++; } - map.put(key, newValue); - return; + throw new IllegalStateException(); } - if (targetObjectTypeDescriptor.isArray()) { - int idx = (Integer)state.convertValue(index, TypeDescriptor.valueOf(Integer.class)); - setArrayElement(state, contextObject.getValue(), idx, newValue, targetObjectTypeDescriptor.getElementTypeDescriptor().getType()); - return; - } - else if (targetObject instanceof Collection) { - int idx = (Integer) state.convertValue(index, TypeDescriptor.valueOf(Integer.class)); - Collection c = (Collection) targetObject; - if (idx >= c.size()) { - if (!growCollection(state, targetObjectTypeDescriptor, idx, c)) { - throw new SpelEvaluationException(getStartPosition(),SpelMessage.COLLECTION_INDEX_OUT_OF_BOUNDS, c.size(), idx); + public void setValue(Object newValue) { + if (index >= collection.size()) { + if (growCollection) { + growCollection(collectionEntryTypeDescriptor, index, collection); + } else { + throw new SpelEvaluationException(getStartPosition(), + SpelMessage.COLLECTION_INDEX_OUT_OF_BOUNDS, + collection.size(), index); } } - if (targetObject instanceof List) { - List list = (List) targetObject; - if (targetObjectTypeDescriptor.getElementTypeDescriptor() != null) { - newValue = state.convertValue(newValue, targetObjectTypeDescriptor.getElementTypeDescriptor()); + if (collection instanceof List) { + List list = (List) collection; + if (collectionEntryTypeDescriptor.getElementTypeDescriptor() != null) { + newValue = typeConverter.convertValue(newValue, + TypeDescriptor.forObject(newValue), + collectionEntryTypeDescriptor + .getElementTypeDescriptor()); } - list.set(idx, newValue); + list.set(index, newValue); return; + } else { + throw new SpelEvaluationException(getStartPosition(), + SpelMessage.INDEXING_NOT_SUPPORTED_FOR_TYPE, + collectionEntryTypeDescriptor.toString()); } - else { - throw new SpelEvaluationException(getStartPosition(),SpelMessage.INDEXING_NOT_SUPPORTED_FOR_TYPE, targetObjectTypeDescriptor.toString()); + } + + public boolean isWritable() { + return true; + } + } + + class StringIndexingLValue implements ValueRef { + + private String target; + private int index; + private TypeDescriptor td; + + public StringIndexingLValue(String target, int index, TypeDescriptor td) { + this.target = target; + this.index = index; + this.td = td; + } + + public TypedValue getValue() { + if (index >= target.length()) { + throw new SpelEvaluationException(getStartPosition(), + SpelMessage.STRING_INDEX_OUT_OF_BOUNDS, + target.length(), index); } + return new TypedValue(String.valueOf(target.charAt(index))); } - - // Try and treat the index value as a property of the context object - // TODO could call the conversion service to convert the value to a String - if (index.getTypeDescriptor().getType() == String.class) { - Class<?> contextObjectClass = getObjectClass(contextObject.getValue()); - String name = (String)index.getValue(); - EvaluationContext eContext = state.getEvaluationContext(); + + public void setValue(Object newValue) { + throw new SpelEvaluationException(getStartPosition(), + SpelMessage.INDEXING_NOT_SUPPORTED_FOR_TYPE, td.toString()); + } + + public boolean isWritable() { + return true; + } + + } + + @Override + protected ValueRef getValueRef(ExpressionState state) + throws EvaluationException { + TypedValue context = state.getActiveContextObject(); + Object targetObject = context.getValue(); + TypeDescriptor targetObjectTypeDescriptor = context.getTypeDescriptor(); + TypedValue indexValue = null; + Object index = null; + + // This first part of the if clause prevents a 'double dereference' of + // the property (SPR-5847) + if (targetObject instanceof Map && (children[0] instanceof PropertyOrFieldReference)) { + PropertyOrFieldReference reference = (PropertyOrFieldReference) children[0]; + index = reference.getName(); + indexValue = new TypedValue(index); + } else { + // In case the map key is unqualified, we want it evaluated against + // the root object so temporarily push that on whilst evaluating the key try { - if (cachedWriteName!=null && cachedWriteName.equals(name) && cachedWriteTargetType!=null && cachedWriteTargetType.equals(contextObjectClass)) { - // it is OK to use the cached accessor - cachedWriteAccessor.write(eContext, targetObject, name,newValue); - return; - } - - List<PropertyAccessor> accessorsToTry = AstUtils.getPropertyAccessorsToTry(contextObjectClass, state); - if (accessorsToTry != null) { - for (PropertyAccessor accessor : accessorsToTry) { - if (accessor.canWrite(eContext, contextObject.getValue(), name)) { - this.cachedWriteName = name; - this.cachedWriteTargetType = contextObjectClass; - this.cachedWriteAccessor = accessor; - accessor.write(eContext, contextObject.getValue(), name, newValue); - return; - } - } - } - } catch (AccessException ae) { - throw new SpelEvaluationException(getStartPosition(), ae, SpelMessage.EXCEPTION_DURING_PROPERTY_WRITE, - name, ae.getMessage()); + state.pushActiveContextObject(state.getRootContextObject()); + indexValue = children[0].getValueInternal(state); + index = indexValue.getValue(); + } finally { + state.popActiveContextObject(); + } + } + + // Indexing into a Map + if (targetObject instanceof Map) { + Object key = index; + if (targetObjectTypeDescriptor.getMapKeyTypeDescriptor() != null) { + key = state.convertValue(key, + targetObjectTypeDescriptor.getMapKeyTypeDescriptor()); + } + return new MapIndexingValueRef(state.getTypeConverter(), + (Map<?, ?>) targetObject, key, targetObjectTypeDescriptor); + } + + if (targetObject == null) { + throw new SpelEvaluationException(getStartPosition(), + SpelMessage.CANNOT_INDEX_INTO_NULL_VALUE); + } + + // if the object is something that looks indexable by an integer, + // attempt to treat the index value as a number + if (targetObject instanceof Collection + || targetObject.getClass().isArray() + || targetObject instanceof String) { + int idx = (Integer) state.convertValue(index, + TypeDescriptor.valueOf(Integer.class)); + if (targetObject.getClass().isArray()) { + return new ArrayIndexingValueRef(state.getTypeConverter(), + targetObject, idx, targetObjectTypeDescriptor); + } else if (targetObject instanceof Collection) { + return new CollectionIndexingValueRef( + (Collection<?>) targetObject, idx, + targetObjectTypeDescriptor,state.getTypeConverter(), + state.getConfiguration().isAutoGrowCollections()); + } else if (targetObject instanceof String) { + return new StringIndexingLValue((String) targetObject, idx, + targetObjectTypeDescriptor); } + } + // Try and treat the index value as a property of the context object + // TODO could call the conversion service to convert the value to a + // String + if (indexValue.getTypeDescriptor().getType() == String.class) { + return new PropertyIndexingValueRef(targetObject, + (String) indexValue.getValue(), + state.getEvaluationContext(), targetObjectTypeDescriptor); } - - throw new SpelEvaluationException(getStartPosition(),SpelMessage.INDEXING_NOT_SUPPORTED_FOR_TYPE, targetObjectTypeDescriptor.toString()); + + throw new SpelEvaluationException(getStartPosition(), + SpelMessage.INDEXING_NOT_SUPPORTED_FOR_TYPE, + targetObjectTypeDescriptor.toString()); } - + /** - * Attempt to grow the specified collection so that the specified index is valid. - * - * @param state the expression state + * Attempt to grow the specified collection so that the specified index is + * valid. + * * @param elementType the type of the elements in the collection * @param index the index into the collection that needs to be valid * @param collection the collection to grow with elements - * @return true if collection growing succeeded, otherwise false */ - @SuppressWarnings("unchecked") - private boolean growCollection(ExpressionState state, TypeDescriptor targetType, int index, - Collection collection) { - if (state.getConfiguration().isAutoGrowCollections()) { - if (targetType.getElementTypeDescriptor() == null) { - throw new SpelEvaluationException(getStartPosition(), SpelMessage.UNABLE_TO_GROW_COLLECTION_UNKNOWN_ELEMENT_TYPE); - } - TypeDescriptor elementType = targetType.getElementTypeDescriptor(); - Object newCollectionElement = null; - try { - int newElements = index - collection.size(); - while (newElements>0) { - collection.add(elementType.getType().newInstance()); - newElements--; - } - newCollectionElement = elementType.getType().newInstance(); - } - catch (Exception ex) { - throw new SpelEvaluationException(getStartPosition(), ex, SpelMessage.UNABLE_TO_GROW_COLLECTION); + private void growCollection(TypeDescriptor targetType, int index, Collection<Object> collection) { + if (targetType.getElementTypeDescriptor() == null) { + throw new SpelEvaluationException( + getStartPosition(), + SpelMessage.UNABLE_TO_GROW_COLLECTION_UNKNOWN_ELEMENT_TYPE); + } + TypeDescriptor elementType = targetType.getElementTypeDescriptor(); + Object newCollectionElement = null; + try { + int newElements = index - collection.size(); + while (newElements > 0) { + collection.add(elementType.getType().newInstance()); + newElements--; } - collection.add(newCollectionElement); - return true; + newCollectionElement = elementType.getType().newInstance(); + } catch (Exception ex) { + throw new SpelEvaluationException(getStartPosition(), ex, + SpelMessage.UNABLE_TO_GROW_COLLECTION); } - return false; + collection.add(newCollectionElement); } - + @Override public String toStringAST() { StringBuilder sb = new StringBuilder(); @@ -306,47 +471,66 @@ public String toStringAST() { return sb.toString(); } - private void setArrayElement(ExpressionState state, Object ctx, int idx, Object newValue, Class clazz) throws EvaluationException { + private void setArrayElement(TypeConverter converter, Object ctx, int idx, + Object newValue, Class<?> clazz) throws EvaluationException { Class<?> arrayComponentType = clazz; if (arrayComponentType == Integer.TYPE) { int[] array = (int[]) ctx; checkAccess(array.length, idx); - array[idx] = (Integer)state.convertValue(newValue, TypeDescriptor.valueOf(Integer.class)); + array[idx] = (Integer) converter.convertValue(newValue, + TypeDescriptor.forObject(newValue), + TypeDescriptor.valueOf(Integer.class)); } else if (arrayComponentType == Boolean.TYPE) { boolean[] array = (boolean[]) ctx; checkAccess(array.length, idx); - array[idx] = (Boolean)state.convertValue(newValue, TypeDescriptor.valueOf(Boolean.class)); + array[idx] = (Boolean) converter.convertValue(newValue, + TypeDescriptor.forObject(newValue), + TypeDescriptor.valueOf(Boolean.class)); } else if (arrayComponentType == Character.TYPE) { char[] array = (char[]) ctx; checkAccess(array.length, idx); - array[idx] = (Character)state.convertValue(newValue, TypeDescriptor.valueOf(Character.class)); + array[idx] = (Character) converter.convertValue(newValue, + TypeDescriptor.forObject(newValue), + TypeDescriptor.valueOf(Character.class)); } else if (arrayComponentType == Long.TYPE) { long[] array = (long[]) ctx; checkAccess(array.length, idx); - array[idx] = (Long)state.convertValue(newValue, TypeDescriptor.valueOf(Long.class)); + array[idx] = (Long) converter.convertValue(newValue, + TypeDescriptor.forObject(newValue), + TypeDescriptor.valueOf(Long.class)); } else if (arrayComponentType == Short.TYPE) { short[] array = (short[]) ctx; checkAccess(array.length, idx); - array[idx] = (Short)state.convertValue(newValue, TypeDescriptor.valueOf(Short.class)); + array[idx] = (Short) converter.convertValue(newValue, + TypeDescriptor.forObject(newValue), + TypeDescriptor.valueOf(Short.class)); } else if (arrayComponentType == Double.TYPE) { double[] array = (double[]) ctx; checkAccess(array.length, idx); - array[idx] = (Double)state.convertValue(newValue, TypeDescriptor.valueOf(Double.class)); + array[idx] = (Double) converter.convertValue(newValue, + TypeDescriptor.forObject(newValue), + TypeDescriptor.valueOf(Double.class)); } else if (arrayComponentType == Float.TYPE) { float[] array = (float[]) ctx; checkAccess(array.length, idx); - array[idx] = (Float)state.convertValue(newValue, TypeDescriptor.valueOf(Float.class)); + array[idx] = (Float) converter.convertValue(newValue, + TypeDescriptor.forObject(newValue), + TypeDescriptor.valueOf(Float.class)); } else if (arrayComponentType == Byte.TYPE) { byte[] array = (byte[]) ctx; checkAccess(array.length, idx); - array[idx] = (Byte)state.convertValue(newValue, TypeDescriptor.valueOf(Byte.class)); + array[idx] = (Byte) converter.convertValue(newValue, + TypeDescriptor.forObject(newValue), + TypeDescriptor.valueOf(Byte.class)); } else { Object[] array = (Object[]) ctx; checkAccess(array.length, idx); - array[idx] = state.convertValue(newValue, TypeDescriptor.valueOf(clazz)); - } + array[idx] = converter.convertValue(newValue, + TypeDescriptor.forObject(newValue), + TypeDescriptor.valueOf(clazz)); + } } - + private Object accessArrayElement(Object ctx, int idx) throws SpelEvaluationException { Class<?> arrayComponentType = ctx.getClass().getComponentType(); if (arrayComponentType == Integer.TYPE) { @@ -390,8 +574,9 @@ private Object accessArrayElement(Object ctx, int idx) throws SpelEvaluationExce private void checkAccess(int arrayLength, int index) throws SpelEvaluationException { if (index > arrayLength) { - throw new SpelEvaluationException(getStartPosition(), SpelMessage.ARRAY_INDEX_OUT_OF_BOUNDS, arrayLength, index); + throw new SpelEvaluationException(getStartPosition(), + SpelMessage.ARRAY_INDEX_OUT_OF_BOUNDS, arrayLength, index); } } -} +} \ No newline at end of file
true
Other
spring-projects
spring-framework
f64325882da41bb128dec1b6d687b6eb6525623f.json
Add SpEL support for increment/decrement operators With this commit the Spring Expression Language now supports increment (++) and decrement (--) operators. These can be used as either prefix or postfix operators. For example: 'somearray[index++]' and 'somearray[--index]' are valid. In order to support this there are serious changes to the evaluation process for expressions. The concept of a value reference for an expression component has been introduced. Value references can be passed around and at any time the actual value can be retrieved (via a get) or set (where applicable). This was needed to avoid double evaluation of expression components. For example, in evaluating the expression 'somearray[index++]--' without a value reference SpEL would need to evaluate the 'somearray[index++]' component twice, once to get the value and then again to determine where to put the new value. If that component is evaluated twice, index would be double incremented. A value reference for 'somearray[index++]' avoids this problem. Many new tests have been introduced into the EvaluationTests to ensure not only that ++ and -- work but also that the introduction of value references across the all of SpEL has not caused regressions. Issue: SPR-9751
spring-expression/src/main/java/org/springframework/expression/spel/ast/MethodReference.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2012 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. @@ -52,6 +52,94 @@ public MethodReference(boolean nullSafe, String methodName, int pos, SpelNodeImp this.nullSafe = nullSafe; } + class MethodValueRef implements ValueRef { + + private ExpressionState state; + private EvaluationContext evaluationContext; + private Object target; + private Object[] arguments; + + MethodValueRef(ExpressionState state, EvaluationContext evaluationContext, Object object, Object[] arguments) { + this.state = state; + this.evaluationContext = evaluationContext; + this.target = object; + this.arguments = arguments; + } + + public TypedValue getValue() { + MethodExecutor executorToUse = cachedExecutor; + if (executorToUse != null) { + try { + return executorToUse.execute(evaluationContext, target, arguments); + } + catch (AccessException ae) { + // Two reasons this can occur: + // 1. the method invoked actually threw a real exception + // 2. the method invoked was not passed the arguments it expected and has become 'stale' + + // In the first case we should not retry, in the second case we should see if there is a + // better suited method. + + // To determine which situation it is, the AccessException will contain a cause. + // If the cause is an InvocationTargetException, a user exception was thrown inside the method. + // Otherwise the method could not be invoked. + throwSimpleExceptionIfPossible(state, ae); + + // at this point we know it wasn't a user problem so worth a retry if a better candidate can be found + cachedExecutor = null; + } + } + + // either there was no accessor or it no longer existed + executorToUse = findAccessorForMethod(name, getTypes(arguments), target, evaluationContext); + cachedExecutor = executorToUse; + try { + return executorToUse.execute(evaluationContext, target, arguments); + } catch (AccessException ae) { + // Same unwrapping exception handling as above in above catch block + throwSimpleExceptionIfPossible(state, ae); + throw new SpelEvaluationException( getStartPosition(), ae, SpelMessage.EXCEPTION_DURING_METHOD_INVOCATION, + name, state.getActiveContextObject().getValue().getClass().getName(), ae.getMessage()); + } + } + + public void setValue(Object newValue) { + throw new IllegalAccessError(); + } + + public boolean isWritable() { + return false; + } + + } + + @Override + protected ValueRef getValueRef(ExpressionState state) throws EvaluationException { + TypedValue currentContext = state.getActiveContextObject(); + Object[] arguments = new Object[getChildCount()]; + for (int i = 0; i < arguments.length; i++) { + // Make the root object the active context again for evaluating the parameter + // expressions + try { + state.pushActiveContextObject(state.getRootContextObject()); + arguments[i] = children[i].getValueInternal(state).getValue(); + } + finally { + state.popActiveContextObject(); + } + } + if (currentContext.getValue() == null) { + if (nullSafe) { + return ValueRef.NullValueRef.instance; + } + else { + throw new SpelEvaluationException(getStartPosition(), SpelMessage.METHOD_CALL_ON_NULL_OBJECT_NOT_ALLOWED, + FormatHelper.formatMethodForMessage(name, getTypes(arguments))); + } + } + + return new MethodValueRef(state,state.getEvaluationContext(),state.getActiveContextObject().getValue(),arguments); + } @Override public TypedValue getValueInternal(ExpressionState state) throws EvaluationException { @@ -65,7 +153,7 @@ public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep arguments[i] = children[i].getValueInternal(state).getValue(); } finally { - state.popActiveContextObject(); + state.popActiveContextObject(); } } if (currentContext.getValue() == null) { @@ -88,15 +176,15 @@ public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep // Two reasons this can occur: // 1. the method invoked actually threw a real exception // 2. the method invoked was not passed the arguments it expected and has become 'stale' - - // In the first case we should not retry, in the second case we should see if there is a + + // In the first case we should not retry, in the second case we should see if there is a // better suited method. - + // To determine which situation it is, the AccessException will contain a cause. // If the cause is an InvocationTargetException, a user exception was thrown inside the method. // Otherwise the method could not be invoked. throwSimpleExceptionIfPossible(state, ae); - + // at this point we know it wasn't a user problem so worth a retry if a better candidate can be found this.cachedExecutor = null; } @@ -118,7 +206,7 @@ public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep /** - * Decode the AccessException, throwing a lightweight evaluation exception or, if the cause was a RuntimeException, + * Decode the AccessException, throwing a lightweight evaluation exception or, if the cause was a RuntimeException, * throw the RuntimeException directly. */ private void throwSimpleExceptionIfPossible(ExpressionState state, AccessException ae) { @@ -132,7 +220,7 @@ private void throwSimpleExceptionIfPossible(ExpressionState state, AccessExcepti "A problem occurred when trying to execute method '" + this.name + "' on object of type '" + state.getActiveContextObject().getValue().getClass().getName() + "'", rootCause); - } + } } } @@ -157,19 +245,22 @@ public String toStringAST() { return sb.toString(); } - private MethodExecutor findAccessorForMethod(String name, List<TypeDescriptor> argumentTypes, ExpressionState state) + private MethodExecutor findAccessorForMethod(String name, + List<TypeDescriptor> argumentTypes, ExpressionState state) throws SpelEvaluationException { + return findAccessorForMethod(name,argumentTypes,state.getActiveContextObject().getValue(),state.getEvaluationContext()); + } - TypedValue context = state.getActiveContextObject(); - Object contextObject = context.getValue(); - EvaluationContext eContext = state.getEvaluationContext(); + private MethodExecutor findAccessorForMethod(String name, + List<TypeDescriptor> argumentTypes, Object contextObject, EvaluationContext eContext) + throws SpelEvaluationException { List<MethodResolver> mResolvers = eContext.getMethodResolvers(); if (mResolvers != null) { for (MethodResolver methodResolver : mResolvers) { try { MethodExecutor cEx = methodResolver.resolve( - state.getEvaluationContext(), contextObject, name, argumentTypes); + eContext, contextObject, name, argumentTypes); if (cEx != null) { return cEx; }
true
Other
spring-projects
spring-framework
f64325882da41bb128dec1b6d687b6eb6525623f.json
Add SpEL support for increment/decrement operators With this commit the Spring Expression Language now supports increment (++) and decrement (--) operators. These can be used as either prefix or postfix operators. For example: 'somearray[index++]' and 'somearray[--index]' are valid. In order to support this there are serious changes to the evaluation process for expressions. The concept of a value reference for an expression component has been introduced. Value references can be passed around and at any time the actual value can be retrieved (via a get) or set (where applicable). This was needed to avoid double evaluation of expression components. For example, in evaluating the expression 'somearray[index++]--' without a value reference SpEL would need to evaluate the 'somearray[index++]' component twice, once to get the value and then again to determine where to put the new value. If that component is evaluated twice, index would be double incremented. A value reference for 'somearray[index++]' avoids this problem. Many new tests have been introduced into the EvaluationTests to ensure not only that ++ and -- work but also that the introduction of value references across the all of SpEL has not caused regressions. Issue: SPR-9751
spring-expression/src/main/java/org/springframework/expression/spel/ast/OpDec.java
@@ -0,0 +1,114 @@ +/* + * Copyright 2002-2012 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.expression.spel.ast; + +import org.springframework.expression.EvaluationException; +import org.springframework.expression.Operation; +import org.springframework.expression.TypedValue; +import org.springframework.expression.spel.ExpressionState; +import org.springframework.expression.spel.SpelEvaluationException; +import org.springframework.expression.spel.SpelMessage; +import org.springframework.util.Assert; + +/** + * Decrement operator. Can be used in a prefix or postfix form. This will throw + * appropriate exceptions if the operand in question does not support decrement. + * + * @author Andy Clement + * @since 3.2 + */ +public class OpDec extends Operator { + + private boolean postfix; // false means prefix + + public OpDec(int pos, boolean postfix, SpelNodeImpl... operands) { + super("--", pos, operands); + Assert.notEmpty(operands); + this.postfix = postfix; + } + + @Override + public TypedValue getValueInternal(ExpressionState state) throws EvaluationException { + SpelNodeImpl operand = getLeftOperand(); + + // The operand is going to be read and then assigned to, we don't want to evaluate it twice. + + ValueRef lvalue = operand.getValueRef(state); + + final TypedValue operandTypedValue = lvalue.getValue();//operand.getValueInternal(state); + final Object operandValue = operandTypedValue.getValue(); + TypedValue returnValue = operandTypedValue; + TypedValue newValue = null; + + if (operandValue instanceof Number) { + Number op1 = (Number) operandValue; + if (op1 instanceof Double) { + newValue = new TypedValue(op1.doubleValue() - 1.0d, operandTypedValue.getTypeDescriptor()); + } else if (op1 instanceof Float) { + newValue = new TypedValue(op1.floatValue() - 1.0f, operandTypedValue.getTypeDescriptor()); + } else if (op1 instanceof Long) { + newValue = new TypedValue(op1.longValue() - 1L, operandTypedValue.getTypeDescriptor()); + } else if (op1 instanceof Short) { + newValue = new TypedValue(op1.shortValue() - (short)1, operandTypedValue.getTypeDescriptor()); + } else { + newValue = new TypedValue(op1.intValue() - 1, operandTypedValue.getTypeDescriptor()); + } + } + if (newValue==null) { + try { + newValue = state.operate(Operation.SUBTRACT, returnValue.getValue(), 1); + } catch (SpelEvaluationException see) { + if (see.getMessageCode()==SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES) { + // This means the operand is not decrementable + throw new SpelEvaluationException(operand.getStartPosition(),SpelMessage.OPERAND_NOT_DECREMENTABLE,operand.toStringAST()); + } else { + throw see; + } + } + } + + // set the new value + try { + lvalue.setValue(newValue.getValue()); + } catch (SpelEvaluationException see) { + // if unable to set the value the operand is not writable (e.g. 1-- ) + if (see.getMessageCode()==SpelMessage.SETVALUE_NOT_SUPPORTED) { + throw new SpelEvaluationException(operand.getStartPosition(),SpelMessage.OPERAND_NOT_DECREMENTABLE); + } else { + throw see; + } + } + + if (!postfix) { + // the return value is the new value, not the original value + returnValue = newValue; + } + + return returnValue; + } + + @Override + public String toStringAST() { + return new StringBuilder().append(getLeftOperand().toStringAST()).append("--").toString(); + } + + @Override + public SpelNodeImpl getRightOperand() { + return null; + } + +}
true
Other
spring-projects
spring-framework
f64325882da41bb128dec1b6d687b6eb6525623f.json
Add SpEL support for increment/decrement operators With this commit the Spring Expression Language now supports increment (++) and decrement (--) operators. These can be used as either prefix or postfix operators. For example: 'somearray[index++]' and 'somearray[--index]' are valid. In order to support this there are serious changes to the evaluation process for expressions. The concept of a value reference for an expression component has been introduced. Value references can be passed around and at any time the actual value can be retrieved (via a get) or set (where applicable). This was needed to avoid double evaluation of expression components. For example, in evaluating the expression 'somearray[index++]--' without a value reference SpEL would need to evaluate the 'somearray[index++]' component twice, once to get the value and then again to determine where to put the new value. If that component is evaluated twice, index would be double incremented. A value reference for 'somearray[index++]' avoids this problem. Many new tests have been introduced into the EvaluationTests to ensure not only that ++ and -- work but also that the introduction of value references across the all of SpEL has not caused regressions. Issue: SPR-9751
spring-expression/src/main/java/org/springframework/expression/spel/ast/OpInc.java
@@ -0,0 +1,112 @@ +/* + * Copyright 2002-2012 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.expression.spel.ast; + +import org.springframework.expression.EvaluationException; +import org.springframework.expression.Operation; +import org.springframework.expression.TypedValue; +import org.springframework.expression.spel.ExpressionState; +import org.springframework.expression.spel.SpelEvaluationException; +import org.springframework.expression.spel.SpelMessage; +import org.springframework.util.Assert; + +/** + * Increment operator. Can be used in a prefix or postfix form. This will throw + * appropriate exceptions if the operand in question does not support increment. + * + * @author Andy Clement + * @since 3.2 + */ +public class OpInc extends Operator { + + private boolean postfix; // false means prefix + + public OpInc(int pos, boolean postfix, SpelNodeImpl... operands) { + super("++", pos, operands); + Assert.notEmpty(operands); + this.postfix = postfix; + } + + @Override + public TypedValue getValueInternal(ExpressionState state) throws EvaluationException { + SpelNodeImpl operand = getLeftOperand(); + + ValueRef lvalue = operand.getValueRef(state); + + final TypedValue operandTypedValue = lvalue.getValue(); + final Object operandValue = operandTypedValue.getValue(); + TypedValue returnValue = operandTypedValue; + TypedValue newValue = null; + + if (operandValue instanceof Number) { + Number op1 = (Number) operandValue; + if (op1 instanceof Double) { + newValue = new TypedValue(op1.doubleValue() + 1.0d, operandTypedValue.getTypeDescriptor()); + } else if (op1 instanceof Float) { + newValue = new TypedValue(op1.floatValue() + 1.0f, operandTypedValue.getTypeDescriptor()); + } else if (op1 instanceof Long) { + newValue = new TypedValue(op1.longValue() + 1L, operandTypedValue.getTypeDescriptor()); + } else if (op1 instanceof Short) { + newValue = new TypedValue(op1.shortValue() + (short)1, operandTypedValue.getTypeDescriptor()); + } else { + newValue = new TypedValue(op1.intValue() + 1, operandTypedValue.getTypeDescriptor()); + } + } + if (newValue==null) { + try { + newValue = state.operate(Operation.ADD, returnValue.getValue(), 1); + } catch (SpelEvaluationException see) { + if (see.getMessageCode()==SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES) { + // This means the operand is not incrementable + throw new SpelEvaluationException(operand.getStartPosition(),SpelMessage.OPERAND_NOT_INCREMENTABLE,operand.toStringAST()); + } else { + throw see; + } + } + } + + // set the name value + try { + lvalue.setValue(newValue.getValue()); + } catch (SpelEvaluationException see) { + // if unable to set the value the operand is not writable (e.g. 1++ ) + if (see.getMessageCode()==SpelMessage.SETVALUE_NOT_SUPPORTED) { + throw new SpelEvaluationException(operand.getStartPosition(),SpelMessage.OPERAND_NOT_INCREMENTABLE); + } else { + throw see; + } + } + + if (!postfix) { + // the return value is the new value, not the original value + returnValue = newValue; + } + + return returnValue; + } + + @Override + public String toStringAST() { + return new StringBuilder().append(getLeftOperand().toStringAST()).append("++").toString(); + } + + @Override + public SpelNodeImpl getRightOperand() { + return null; + } + +}
true
Other
spring-projects
spring-framework
f64325882da41bb128dec1b6d687b6eb6525623f.json
Add SpEL support for increment/decrement operators With this commit the Spring Expression Language now supports increment (++) and decrement (--) operators. These can be used as either prefix or postfix operators. For example: 'somearray[index++]' and 'somearray[--index]' are valid. In order to support this there are serious changes to the evaluation process for expressions. The concept of a value reference for an expression component has been introduced. Value references can be passed around and at any time the actual value can be retrieved (via a get) or set (where applicable). This was needed to avoid double evaluation of expression components. For example, in evaluating the expression 'somearray[index++]--' without a value reference SpEL would need to evaluate the 'somearray[index++]' component twice, once to get the value and then again to determine where to put the new value. If that component is evaluated twice, index would be double incremented. A value reference for 'somearray[index++]' avoids this problem. Many new tests have been introduced into the EvaluationTests to ensure not only that ++ and -- work but also that the introduction of value references across the all of SpEL has not caused regressions. Issue: SPR-9751
spring-expression/src/main/java/org/springframework/expression/spel/ast/Projection.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2012 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. @@ -51,6 +51,11 @@ public Projection(boolean nullSafe, int pos, SpelNodeImpl expression) { @Override public TypedValue getValueInternal(ExpressionState state) throws EvaluationException { + return getValueRef(state).getValue(); + } + + @Override + protected ValueRef getValueRef(ExpressionState state) throws EvaluationException { TypedValue op = state.getActiveContextObject(); Object operand = op.getValue(); @@ -65,7 +70,7 @@ public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep if (operand instanceof Map) { Map<?, ?> mapData = (Map<?, ?>) operand; List<Object> result = new ArrayList<Object>(); - for (Map.Entry entry : mapData.entrySet()) { + for (Map.Entry<?,?> entry : mapData.entrySet()) { try { state.pushActiveContextObject(new TypedValue(entry)); result.add(this.children[0].getValueInternal(state).getValue()); @@ -74,7 +79,7 @@ public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep state.popActiveContextObject(); } } - return new TypedValue(result); // TODO unable to build correct type descriptor + return new ValueRef.TypedValueHolderValueRef(new TypedValue(result),this); // TODO unable to build correct type descriptor } else if (operand instanceof Collection || operandIsArray) { Collection<?> data = (operand instanceof Collection ? (Collection<?>) operand : @@ -104,14 +109,14 @@ else if (operand instanceof Collection || operandIsArray) { } Object resultArray = Array.newInstance(arrayElementType, result.size()); System.arraycopy(result.toArray(), 0, resultArray, 0, result.size()); - return new TypedValue(resultArray); + return new ValueRef.TypedValueHolderValueRef(new TypedValue(resultArray),this); } - return new TypedValue(result); + return new ValueRef.TypedValueHolderValueRef(new TypedValue(result),this); } else { if (operand==null) { if (this.nullSafe) { - return TypedValue.NULL; + return ValueRef.NullValueRef.instance; } else { throw new SpelEvaluationException(getStartPosition(),
true
Other
spring-projects
spring-framework
f64325882da41bb128dec1b6d687b6eb6525623f.json
Add SpEL support for increment/decrement operators With this commit the Spring Expression Language now supports increment (++) and decrement (--) operators. These can be used as either prefix or postfix operators. For example: 'somearray[index++]' and 'somearray[--index]' are valid. In order to support this there are serious changes to the evaluation process for expressions. The concept of a value reference for an expression component has been introduced. Value references can be passed around and at any time the actual value can be retrieved (via a get) or set (where applicable). This was needed to avoid double evaluation of expression components. For example, in evaluating the expression 'somearray[index++]--' without a value reference SpEL would need to evaluate the 'somearray[index++]' component twice, once to get the value and then again to determine where to put the new value. If that component is evaluated twice, index would be double incremented. A value reference for 'somearray[index++]' avoids this problem. Many new tests have been introduced into the EvaluationTests to ensure not only that ++ and -- work but also that the introduction of value references across the all of SpEL has not caused regressions. Issue: SPR-9751
spring-expression/src/main/java/org/springframework/expression/spel/ast/PropertyOrFieldReference.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2012 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. @@ -49,7 +49,7 @@ public class PropertyOrFieldReference extends SpelNodeImpl { private volatile PropertyAccessor cachedReadAccessor; private volatile PropertyAccessor cachedWriteAccessor; - + public PropertyOrFieldReference(boolean nullSafe, String propertyOrFieldName, int pos) { super(pos); @@ -67,23 +67,63 @@ public String getName() { } + static class AccessorLValue implements ValueRef { + private PropertyOrFieldReference ref; + private TypedValue contextObject; + private EvaluationContext eContext; + private boolean isAutoGrowNullReferences; + + public AccessorLValue( + PropertyOrFieldReference propertyOrFieldReference, + TypedValue activeContextObject, + EvaluationContext evaluationContext, boolean isAutoGrowNullReferences) { + this.ref = propertyOrFieldReference; + this.contextObject = activeContextObject; + this.eContext =evaluationContext; + this.isAutoGrowNullReferences = isAutoGrowNullReferences; + } + + public TypedValue getValue() { + return ref.getValueInternal(contextObject,eContext,isAutoGrowNullReferences); + } + + public void setValue(Object newValue) { + ref.writeProperty(contextObject,eContext, ref.name, newValue); + } + + public boolean isWritable() { + return true; + } + + } + + @Override + public ValueRef getValueRef(ExpressionState state) throws EvaluationException { + return new AccessorLValue(this,state.getActiveContextObject(),state.getEvaluationContext(),state.getConfiguration().isAutoGrowNullReferences()); + } + @Override public TypedValue getValueInternal(ExpressionState state) throws EvaluationException { - TypedValue result = readProperty(state, this.name); - - // Dynamically create the objects if the user has requested that optional behaviour - if (result.getValue() == null && state.getConfiguration().isAutoGrowNullReferences() && + return getValueInternal(state.getActiveContextObject(), state.getEvaluationContext(), state.getConfiguration().isAutoGrowNullReferences()); + } + + private TypedValue getValueInternal(TypedValue contextObject, EvaluationContext eContext, boolean isAutoGrowNullReferences) throws EvaluationException { + + TypedValue result = readProperty(contextObject, eContext, this.name); + + // Dynamically create the objects if the user has requested that optional behavior + if (result.getValue() == null && isAutoGrowNullReferences && nextChildIs(Indexer.class, PropertyOrFieldReference.class)) { TypeDescriptor resultDescriptor = result.getTypeDescriptor(); // Creating lists and maps if ((resultDescriptor.getType().equals(List.class) || resultDescriptor.getType().equals(Map.class))) { // Create a new collection or map ready for the indexer if (resultDescriptor.getType().equals(List.class)) { try { - if (isWritable(state)) { - List newList = ArrayList.class.newInstance(); - writeProperty(state, this.name, newList); - result = readProperty(state, this.name); + if (isWritableProperty(this.name,contextObject,eContext)) { + List<?> newList = ArrayList.class.newInstance(); + writeProperty(contextObject, eContext, this.name, newList); + result = readProperty(contextObject, eContext, this.name); } } catch (InstantiationException ex) { @@ -97,10 +137,10 @@ public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep } else { try { - if (isWritable(state)) { - Map newMap = HashMap.class.newInstance(); - writeProperty(state, name, newMap); - result = readProperty(state, this.name); + if (isWritableProperty(this.name,contextObject,eContext)) { + Map<?,?> newMap = HashMap.class.newInstance(); + writeProperty(contextObject, eContext, name, newMap); + result = readProperty(contextObject, eContext, this.name); } } catch (InstantiationException ex) { @@ -116,10 +156,10 @@ public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep else { // 'simple' object try { - if (isWritable(state)) { + if (isWritableProperty(this.name,contextObject,eContext)) { Object newObject = result.getTypeDescriptor().getType().newInstance(); - writeProperty(state, name, newObject); - result = readProperty(state, this.name); + writeProperty(contextObject, eContext, name, newObject); + result = readProperty(contextObject, eContext, this.name); } } catch (InstantiationException ex) { @@ -137,12 +177,12 @@ public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep @Override public void setValue(ExpressionState state, Object newValue) throws SpelEvaluationException { - writeProperty(state, this.name, newValue); + writeProperty(state.getActiveContextObject(), state.getEvaluationContext(), this.name, newValue); } @Override public boolean isWritable(ExpressionState state) throws SpelEvaluationException { - return isWritableProperty(this.name, state); + return isWritableProperty(this.name, state.getActiveContextObject(), state.getEvaluationContext()); } @Override @@ -157,8 +197,7 @@ public String toStringAST() { * @return the value of the property * @throws SpelEvaluationException if any problem accessing the property or it cannot be found */ - private TypedValue readProperty(ExpressionState state, String name) throws EvaluationException { - TypedValue contextObject = state.getActiveContextObject(); + private TypedValue readProperty(TypedValue contextObject, EvaluationContext eContext, String name) throws EvaluationException { Object targetObject = contextObject.getValue(); if (targetObject == null && this.nullSafe) { @@ -168,7 +207,7 @@ private TypedValue readProperty(ExpressionState state, String name) throws Evalu PropertyAccessor accessorToUse = this.cachedReadAccessor; if (accessorToUse != null) { try { - return accessorToUse.read(state.getEvaluationContext(), contextObject.getValue(), name); + return accessorToUse.read(eContext, contextObject.getValue(), name); } catch (AccessException ae) { // this is OK - it may have gone stale due to a class change, @@ -178,8 +217,7 @@ private TypedValue readProperty(ExpressionState state, String name) throws Evalu } Class<?> contextObjectClass = getObjectClass(contextObject.getValue()); - List<PropertyAccessor> accessorsToTry = getPropertyAccessorsToTry(contextObjectClass, state); - EvaluationContext eContext = state.getEvaluationContext(); + List<PropertyAccessor> accessorsToTry = getPropertyAccessorsToTry(contextObjectClass, eContext.getPropertyAccessors()); // Go through the accessors that may be able to resolve it. If they are a cacheable accessor then // get the accessor and use it. If they are not cacheable but report they can read the property @@ -210,18 +248,16 @@ private TypedValue readProperty(ExpressionState state, String name) throws Evalu } } - private void writeProperty(ExpressionState state, String name, Object newValue) throws SpelEvaluationException { - TypedValue contextObject = state.getActiveContextObject(); - EvaluationContext eContext = state.getEvaluationContext(); + private void writeProperty(TypedValue contextObject, EvaluationContext eContext, String name, Object newValue) throws SpelEvaluationException { if (contextObject.getValue() == null && nullSafe) { return; } PropertyAccessor accessorToUse = this.cachedWriteAccessor; if (accessorToUse != null) { - try { - accessorToUse.write(state.getEvaluationContext(), contextObject.getValue(), name, newValue); + try { + accessorToUse.write(eContext, contextObject.getValue(), name, newValue); return; } catch (AccessException ae) { @@ -233,7 +269,7 @@ private void writeProperty(ExpressionState state, String name, Object newValue) Class<?> contextObjectClass = getObjectClass(contextObject.getValue()); - List<PropertyAccessor> accessorsToTry = getPropertyAccessorsToTry(contextObjectClass, state); + List<PropertyAccessor> accessorsToTry = getPropertyAccessorsToTry(contextObjectClass, eContext.getPropertyAccessors()); if (accessorsToTry != null) { try { for (PropertyAccessor accessor : accessorsToTry) { @@ -258,15 +294,14 @@ private void writeProperty(ExpressionState state, String name, Object newValue) } } - public boolean isWritableProperty(String name, ExpressionState state) throws SpelEvaluationException { - Object contextObject = state.getActiveContextObject().getValue(); + public boolean isWritableProperty(String name, TypedValue contextObject, EvaluationContext eContext) throws SpelEvaluationException { + Object contextObjectValue = contextObject.getValue(); // TypeDescriptor td = state.getActiveContextObject().getTypeDescriptor(); - EvaluationContext eContext = state.getEvaluationContext(); - List<PropertyAccessor> resolversToTry = getPropertyAccessorsToTry(getObjectClass(contextObject), state); + List<PropertyAccessor> resolversToTry = getPropertyAccessorsToTry(getObjectClass(contextObjectValue), eContext.getPropertyAccessors()); if (resolversToTry != null) { for (PropertyAccessor pfResolver : resolversToTry) { try { - if (pfResolver.canWrite(eContext, contextObject, name)) { + if (pfResolver.canWrite(eContext, contextObjectValue, name)) { return true; } } @@ -289,10 +324,10 @@ public boolean isWritableProperty(String name, ExpressionState state) throws Spe * @param targetType the type upon which property access is being attempted * @return a list of resolvers that should be tried in order to access the property */ - private List<PropertyAccessor> getPropertyAccessorsToTry(Class<?> targetType, ExpressionState state) { + private List<PropertyAccessor> getPropertyAccessorsToTry(Class<?> targetType, List<PropertyAccessor> propertyAccessors) { List<PropertyAccessor> specificAccessors = new ArrayList<PropertyAccessor>(); List<PropertyAccessor> generalAccessors = new ArrayList<PropertyAccessor>(); - for (PropertyAccessor resolver : state.getPropertyAccessors()) { + for (PropertyAccessor resolver : propertyAccessors) { Class<?>[] targets = resolver.getSpecificTargetClasses(); if (targets == null) { // generic resolver that says it can be used for any type generalAccessors.add(resolver);
true
Other
spring-projects
spring-framework
f64325882da41bb128dec1b6d687b6eb6525623f.json
Add SpEL support for increment/decrement operators With this commit the Spring Expression Language now supports increment (++) and decrement (--) operators. These can be used as either prefix or postfix operators. For example: 'somearray[index++]' and 'somearray[--index]' are valid. In order to support this there are serious changes to the evaluation process for expressions. The concept of a value reference for an expression component has been introduced. Value references can be passed around and at any time the actual value can be retrieved (via a get) or set (where applicable). This was needed to avoid double evaluation of expression components. For example, in evaluating the expression 'somearray[index++]--' without a value reference SpEL would need to evaluate the 'somearray[index++]' component twice, once to get the value and then again to determine where to put the new value. If that component is evaluated twice, index would be double incremented. A value reference for 'somearray[index++]' avoids this problem. Many new tests have been introduced into the EvaluationTests to ensure not only that ++ and -- work but also that the introduction of value references across the all of SpEL has not caused regressions. Issue: SPR-9751
spring-expression/src/main/java/org/springframework/expression/spel/ast/Selection.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2012 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. @@ -59,19 +59,23 @@ public Selection(boolean nullSafe, int variant,int pos,SpelNodeImpl expression) this.variant = variant; } - @SuppressWarnings("unchecked") @Override public TypedValue getValueInternal(ExpressionState state) throws EvaluationException { + return getValueRef(state).getValue(); + } + + @Override + protected ValueRef getValueRef(ExpressionState state) throws EvaluationException { TypedValue op = state.getActiveContextObject(); Object operand = op.getValue(); - + SpelNodeImpl selectionCriteria = children[0]; if (operand instanceof Map) { Map<?, ?> mapdata = (Map<?, ?>) operand; // TODO don't lose generic info for the new map Map<Object,Object> result = new HashMap<Object,Object>(); Object lastKey = null; - for (Map.Entry entry : mapdata.entrySet()) { + for (Map.Entry<?,?> entry : mapdata.entrySet()) { try { TypedValue kvpair = new TypedValue(entry); state.pushActiveContextObject(kvpair); @@ -80,7 +84,7 @@ public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep if (((Boolean) o).booleanValue() == true) { if (variant == FIRST) { result.put(entry.getKey(),entry.getValue()); - return new TypedValue(result); + return new ValueRef.TypedValueHolderValueRef(new TypedValue(result),this); } result.put(entry.getKey(),entry.getValue()); lastKey = entry.getKey(); @@ -94,15 +98,15 @@ public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep } } if ((variant == FIRST || variant == LAST) && result.size() == 0) { - return new TypedValue(null); + return new ValueRef.TypedValueHolderValueRef(new TypedValue(null),this); } if (variant == LAST) { - Map resultMap = new HashMap(); + Map<Object,Object> resultMap = new HashMap<Object,Object>(); Object lastValue = result.get(lastKey); resultMap.put(lastKey,lastValue); - return new TypedValue(resultMap); + return new ValueRef.TypedValueHolderValueRef(new TypedValue(resultMap),this); } - return new TypedValue(result); + return new ValueRef.TypedValueHolderValueRef(new TypedValue(result),this); } else if ((operand instanceof Collection) || ObjectUtils.isArray(operand)) { List<Object> data = new ArrayList<Object>(); Collection<?> c = (operand instanceof Collection) ? @@ -118,7 +122,7 @@ public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep if (o instanceof Boolean) { if (((Boolean) o).booleanValue() == true) { if (variant == FIRST) { - return new TypedValue(element); + return new ValueRef.TypedValueHolderValueRef(new TypedValue(element),this); } result.add(element); } @@ -133,24 +137,24 @@ public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep } } if ((variant == FIRST || variant == LAST) && result.size() == 0) { - return TypedValue.NULL; + return ValueRef.NullValueRef.instance; } if (variant == LAST) { - return new TypedValue(result.get(result.size() - 1)); + return new ValueRef.TypedValueHolderValueRef(new TypedValue(result.get(result.size() - 1)),this); } if (operand instanceof Collection) { - return new TypedValue(result); + return new ValueRef.TypedValueHolderValueRef(new TypedValue(result),this); } else { Class<?> elementType = ClassUtils.resolvePrimitiveIfNecessary(op.getTypeDescriptor().getElementTypeDescriptor().getType()); Object resultArray = Array.newInstance(elementType, result.size()); System.arraycopy(result.toArray(), 0, resultArray, 0, result.size()); - return new TypedValue(resultArray); + return new ValueRef.TypedValueHolderValueRef(new TypedValue(resultArray),this); } } else { if (operand==null) { if (nullSafe) { - return TypedValue.NULL; + return ValueRef.NullValueRef.instance; } else { throw new SpelEvaluationException(getStartPosition(), SpelMessage.INVALID_TYPE_FOR_SELECTION, "null");
true
Other
spring-projects
spring-framework
f64325882da41bb128dec1b6d687b6eb6525623f.json
Add SpEL support for increment/decrement operators With this commit the Spring Expression Language now supports increment (++) and decrement (--) operators. These can be used as either prefix or postfix operators. For example: 'somearray[index++]' and 'somearray[--index]' are valid. In order to support this there are serious changes to the evaluation process for expressions. The concept of a value reference for an expression component has been introduced. Value references can be passed around and at any time the actual value can be retrieved (via a get) or set (where applicable). This was needed to avoid double evaluation of expression components. For example, in evaluating the expression 'somearray[index++]--' without a value reference SpEL would need to evaluate the 'somearray[index++]' component twice, once to get the value and then again to determine where to put the new value. If that component is evaluated twice, index would be double incremented. A value reference for 'somearray[index++]' avoids this problem. Many new tests have been introduced into the EvaluationTests to ensure not only that ++ and -- work but also that the introduction of value references across the all of SpEL has not caused regressions. Issue: SPR-9751
spring-expression/src/main/java/org/springframework/expression/spel/ast/SpelNodeImpl.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2012 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. @@ -154,6 +154,10 @@ public int getStartPosition() { public int getEndPosition() { return (pos&0xffff); - } + } + + protected ValueRef getValueRef(ExpressionState state) throws EvaluationException { + throw new SpelEvaluationException(pos,SpelMessage.NOT_ASSIGNABLE,toStringAST()); + } }
true
Other
spring-projects
spring-framework
f64325882da41bb128dec1b6d687b6eb6525623f.json
Add SpEL support for increment/decrement operators With this commit the Spring Expression Language now supports increment (++) and decrement (--) operators. These can be used as either prefix or postfix operators. For example: 'somearray[index++]' and 'somearray[--index]' are valid. In order to support this there are serious changes to the evaluation process for expressions. The concept of a value reference for an expression component has been introduced. Value references can be passed around and at any time the actual value can be retrieved (via a get) or set (where applicable). This was needed to avoid double evaluation of expression components. For example, in evaluating the expression 'somearray[index++]--' without a value reference SpEL would need to evaluate the 'somearray[index++]' component twice, once to get the value and then again to determine where to put the new value. If that component is evaluated twice, index would be double incremented. A value reference for 'somearray[index++]' avoids this problem. Many new tests have been introduced into the EvaluationTests to ensure not only that ++ and -- work but also that the introduction of value references across the all of SpEL has not caused regressions. Issue: SPR-9751
spring-expression/src/main/java/org/springframework/expression/spel/ast/ValueRef.java
@@ -0,0 +1,107 @@ +/* + * Copyright 2002-2012 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.expression.spel.ast; + +import org.springframework.expression.TypedValue; +import org.springframework.expression.spel.SpelEvaluationException; +import org.springframework.expression.spel.SpelMessage; + +/** + * Represents a reference to a value. With a reference it is possible to get or set the + * value. Passing around value references rather than the values themselves can avoid + * incorrect duplication of operand evaluation. For example in 'list[index++]++' without a + * value reference for 'list[index++]' it would be necessary to evaluate list[index++] + * twice (once to get the value, once to determine where the value goes) and that would + * double increment index. + * + * @author Andy Clement + * @since 3.2 + */ +public interface ValueRef { + + /** + * A ValueRef for the null value. + */ + static class NullValueRef implements ValueRef { + + static NullValueRef instance = new NullValueRef(); + + public TypedValue getValue() { + return TypedValue.NULL; + } + + public void setValue(Object newValue) { + // The exception position '0' isn't right but the overhead of creating + // instances of this per node (where the node is solely for error reporting) + // would be unfortunate. + throw new SpelEvaluationException(0,SpelMessage.NOT_ASSIGNABLE,"null"); + } + + public boolean isWritable() { + return false; + } + + } + + /** + * A ValueRef holder for a single value, which cannot be set. + */ + static class TypedValueHolderValueRef implements ValueRef { + + private TypedValue typedValue; + private SpelNodeImpl node; // used only for error reporting + + public TypedValueHolderValueRef(TypedValue typedValue,SpelNodeImpl node) { + this.typedValue = typedValue; + this.node = node; + } + + public TypedValue getValue() { + return typedValue; + } + + public void setValue(Object newValue) { + throw new SpelEvaluationException( + node.pos, SpelMessage.NOT_ASSIGNABLE, node.toStringAST()); + } + + public boolean isWritable() { + return false; + } + + } + + /** + * Returns the value this ValueRef points to, it should not require expression + * component re-evaluation. + * @return the value + */ + TypedValue getValue(); + + /** + * Sets the value this ValueRef points to, it should not require expression component + * re-evaluation. + * @param newValue the new value + */ + void setValue(Object newValue); + + /** + * Indicates whether calling setValue(Object) is supported. + * @return true if setValue() is supported for this value reference. + */ + boolean isWritable(); +}
true
Other
spring-projects
spring-framework
f64325882da41bb128dec1b6d687b6eb6525623f.json
Add SpEL support for increment/decrement operators With this commit the Spring Expression Language now supports increment (++) and decrement (--) operators. These can be used as either prefix or postfix operators. For example: 'somearray[index++]' and 'somearray[--index]' are valid. In order to support this there are serious changes to the evaluation process for expressions. The concept of a value reference for an expression component has been introduced. Value references can be passed around and at any time the actual value can be retrieved (via a get) or set (where applicable). This was needed to avoid double evaluation of expression components. For example, in evaluating the expression 'somearray[index++]--' without a value reference SpEL would need to evaluate the 'somearray[index++]' component twice, once to get the value and then again to determine where to put the new value. If that component is evaluated twice, index would be double incremented. A value reference for 'somearray[index++]' avoids this problem. Many new tests have been introduced into the EvaluationTests to ensure not only that ++ and -- work but also that the introduction of value references across the all of SpEL has not caused regressions. Issue: SPR-9751
spring-expression/src/main/java/org/springframework/expression/spel/ast/VariableReference.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2012 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. @@ -16,6 +16,7 @@ package org.springframework.expression.spel.ast; +import org.springframework.expression.EvaluationContext; import org.springframework.expression.TypedValue; import org.springframework.expression.spel.ExpressionState; import org.springframework.expression.spel.SpelEvaluationException; @@ -41,6 +42,47 @@ public VariableReference(String variableName, int pos) { } + class VariableRef implements ValueRef { + + private String name; + private TypedValue value; + private EvaluationContext eContext; + + public VariableRef(String name, TypedValue value, + EvaluationContext evaluationContext) { + this.name = name; + this.value = value; + this.eContext = evaluationContext; + } + + public TypedValue getValue() { + return value; + } + + public void setValue(Object newValue) { + eContext.setVariable(name, newValue); + } + + public boolean isWritable() { + return true; + } + + } + + + @Override + public ValueRef getValueRef(ExpressionState state) throws SpelEvaluationException { + if (this.name.equals(THIS)) { + return new ValueRef.TypedValueHolderValueRef(state.getActiveContextObject(),this); + } + if (this.name.equals(ROOT)) { + return new ValueRef.TypedValueHolderValueRef(state.getRootContextObject(),this); + } + TypedValue result = state.lookupVariable(this.name); + // a null value will mean either the value was null or the variable was not found + return new VariableRef(this.name,result,state.getEvaluationContext()); + } + @Override public TypedValue getValueInternal(ExpressionState state) throws SpelEvaluationException { if (this.name.equals(THIS)) {
true
Other
spring-projects
spring-framework
f64325882da41bb128dec1b6d687b6eb6525623f.json
Add SpEL support for increment/decrement operators With this commit the Spring Expression Language now supports increment (++) and decrement (--) operators. These can be used as either prefix or postfix operators. For example: 'somearray[index++]' and 'somearray[--index]' are valid. In order to support this there are serious changes to the evaluation process for expressions. The concept of a value reference for an expression component has been introduced. Value references can be passed around and at any time the actual value can be retrieved (via a get) or set (where applicable). This was needed to avoid double evaluation of expression components. For example, in evaluating the expression 'somearray[index++]--' without a value reference SpEL would need to evaluate the 'somearray[index++]' component twice, once to get the value and then again to determine where to put the new value. If that component is evaluated twice, index would be double incremented. A value reference for 'somearray[index++]' avoids this problem. Many new tests have been introduced into the EvaluationTests to ensure not only that ++ and -- work but also that the introduction of value references across the all of SpEL has not caused regressions. Issue: SPR-9751
spring-expression/src/main/java/org/springframework/expression/spel/standard/InternalSpelExpressionParser.java
@@ -27,45 +27,7 @@ import org.springframework.expression.spel.SpelMessage; import org.springframework.expression.spel.SpelParseException; import org.springframework.expression.spel.SpelParserConfiguration; -import org.springframework.expression.spel.ast.Assign; -import org.springframework.expression.spel.ast.BeanReference; -import org.springframework.expression.spel.ast.BooleanLiteral; -import org.springframework.expression.spel.ast.CompoundExpression; -import org.springframework.expression.spel.ast.ConstructorReference; -import org.springframework.expression.spel.ast.Elvis; -import org.springframework.expression.spel.ast.FunctionReference; -import org.springframework.expression.spel.ast.Identifier; -import org.springframework.expression.spel.ast.Indexer; -import org.springframework.expression.spel.ast.InlineList; -import org.springframework.expression.spel.ast.Literal; -import org.springframework.expression.spel.ast.MethodReference; -import org.springframework.expression.spel.ast.NullLiteral; -import org.springframework.expression.spel.ast.OpAnd; -import org.springframework.expression.spel.ast.OpDivide; -import org.springframework.expression.spel.ast.OpEQ; -import org.springframework.expression.spel.ast.OpGE; -import org.springframework.expression.spel.ast.OpGT; -import org.springframework.expression.spel.ast.OpLE; -import org.springframework.expression.spel.ast.OpLT; -import org.springframework.expression.spel.ast.OpMinus; -import org.springframework.expression.spel.ast.OpModulus; -import org.springframework.expression.spel.ast.OpMultiply; -import org.springframework.expression.spel.ast.OpNE; -import org.springframework.expression.spel.ast.OpOr; -import org.springframework.expression.spel.ast.OpPlus; -import org.springframework.expression.spel.ast.OperatorInstanceof; -import org.springframework.expression.spel.ast.OperatorMatches; -import org.springframework.expression.spel.ast.OperatorNot; -import org.springframework.expression.spel.ast.OperatorPower; -import org.springframework.expression.spel.ast.Projection; -import org.springframework.expression.spel.ast.PropertyOrFieldReference; -import org.springframework.expression.spel.ast.QualifiedIdentifier; -import org.springframework.expression.spel.ast.Selection; -import org.springframework.expression.spel.ast.SpelNodeImpl; -import org.springframework.expression.spel.ast.StringLiteral; -import org.springframework.expression.spel.ast.Ternary; -import org.springframework.expression.spel.ast.TypeReference; -import org.springframework.expression.spel.ast.VariableReference; +import org.springframework.expression.spel.ast.*; import org.springframework.util.Assert; /** @@ -231,14 +193,13 @@ private SpelNodeImpl eatRelationalExpression() { //sumExpression: productExpression ( (PLUS^ | MINUS^) productExpression)*; private SpelNodeImpl eatSumExpression() { SpelNodeImpl expr = eatProductExpression(); - while (peekToken(TokenKind.PLUS,TokenKind.MINUS)) { - Token t = nextToken();//consume PLUS or MINUS + while (peekToken(TokenKind.PLUS,TokenKind.MINUS,TokenKind.INC)) { + Token t = nextToken();//consume PLUS or MINUS or INC SpelNodeImpl rhExpr = eatProductExpression(); checkRightOperand(t,rhExpr); if (t.kind==TokenKind.PLUS) { expr = new OpPlus(toPos(t),expr,rhExpr); - } else { - Assert.isTrue(t.kind==TokenKind.MINUS); + } else if (t.kind==TokenKind.MINUS) { expr = new OpMinus(toPos(t),expr,rhExpr); } } @@ -247,10 +208,10 @@ private SpelNodeImpl eatSumExpression() { // productExpression: powerExpr ((STAR^ | DIV^| MOD^) powerExpr)* ; private SpelNodeImpl eatProductExpression() { - SpelNodeImpl expr = eatPowerExpression(); + SpelNodeImpl expr = eatPowerIncDecExpression(); while (peekToken(TokenKind.STAR,TokenKind.DIV,TokenKind.MOD)) { Token t = nextToken(); // consume STAR/DIV/MOD - SpelNodeImpl rhExpr = eatPowerExpression(); + SpelNodeImpl rhExpr = eatPowerIncDecExpression(); checkRightOperand(t,rhExpr); if (t.kind==TokenKind.STAR) { expr = new OpMultiply(toPos(t),expr,rhExpr); @@ -264,19 +225,26 @@ private SpelNodeImpl eatProductExpression() { return expr; } - // powerExpr : unaryExpression (POWER^ unaryExpression)? ; - private SpelNodeImpl eatPowerExpression() { + // powerExpr : unaryExpression (POWER^ unaryExpression)? (INC || DEC) ; + private SpelNodeImpl eatPowerIncDecExpression() { SpelNodeImpl expr = eatUnaryExpression(); if (peekToken(TokenKind.POWER)) { Token t = nextToken();//consume POWER SpelNodeImpl rhExpr = eatUnaryExpression(); checkRightOperand(t,rhExpr); return new OperatorPower(toPos(t),expr, rhExpr); + } else if (expr!=null && peekToken(TokenKind.INC,TokenKind.DEC)) { + Token t = nextToken();//consume INC/DEC + if (t.getKind()==TokenKind.INC) { + return new OpInc(toPos(t),true,expr); + } else { + return new OpDec(toPos(t),true,expr); + } } return expr; } - // unaryExpression: (PLUS^ | MINUS^ | BANG^) unaryExpression | primaryExpression ; + // unaryExpression: (PLUS^ | MINUS^ | BANG^ | INC^ | DEC^) unaryExpression | primaryExpression ; private SpelNodeImpl eatUnaryExpression() { if (peekToken(TokenKind.PLUS,TokenKind.MINUS,TokenKind.NOT)) { Token t = nextToken(); @@ -289,6 +257,14 @@ private SpelNodeImpl eatUnaryExpression() { Assert.isTrue(t.kind==TokenKind.MINUS); return new OpMinus(toPos(t),expr); } + } else if (peekToken(TokenKind.INC,TokenKind.DEC)) { + Token t = nextToken(); + SpelNodeImpl expr = eatUnaryExpression(); + if (t.getKind()==TokenKind.INC) { + return new OpInc(toPos(t),false,expr); + } else { + return new OpDec(toPos(t),false,expr); + } } else { return eatPrimaryExpression(); }
true
Other
spring-projects
spring-framework
f64325882da41bb128dec1b6d687b6eb6525623f.json
Add SpEL support for increment/decrement operators With this commit the Spring Expression Language now supports increment (++) and decrement (--) operators. These can be used as either prefix or postfix operators. For example: 'somearray[index++]' and 'somearray[--index]' are valid. In order to support this there are serious changes to the evaluation process for expressions. The concept of a value reference for an expression component has been introduced. Value references can be passed around and at any time the actual value can be retrieved (via a get) or set (where applicable). This was needed to avoid double evaluation of expression components. For example, in evaluating the expression 'somearray[index++]--' without a value reference SpEL would need to evaluate the 'somearray[index++]' component twice, once to get the value and then again to determine where to put the new value. If that component is evaluated twice, index would be double incremented. A value reference for 'somearray[index++]' avoids this problem. Many new tests have been introduced into the EvaluationTests to ensure not only that ++ and -- work but also that the introduction of value references across the all of SpEL has not caused regressions. Issue: SPR-9751
spring-expression/src/main/java/org/springframework/expression/spel/standard/TokenKind.java
@@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.expression.spel.standard; /** @@ -29,12 +30,12 @@ enum TokenKind { DIV("/"), GE(">="), GT(">"), LE("<="), LT("<"), EQ("=="), NE("!="), MOD("%"), NOT("!"), ASSIGN("="), INSTANCEOF("instanceof"), MATCHES("matches"), BETWEEN("between"), SELECT("?["), POWER("^"), - ELVIS("?:"), SAFE_NAVI("?."), BEAN_REF("@"), SYMBOLIC_OR("||"), SYMBOLIC_AND("&&") + ELVIS("?:"), SAFE_NAVI("?."), BEAN_REF("@"), SYMBOLIC_OR("||"), SYMBOLIC_AND("&&"), INC("++"), DEC("--") ; - + char[] tokenChars; private boolean hasPayload; // is there more to this token than simply the kind - + private TokenKind(String tokenString) { tokenChars = tokenString.toCharArray(); hasPayload = tokenChars.length==0; @@ -43,15 +44,15 @@ private TokenKind(String tokenString) { private TokenKind() { this(""); } - + public String toString() { return this.name()+(tokenChars.length!=0?"("+new String(tokenChars)+")":""); } - + public boolean hasPayload() { return hasPayload; } - + public int getLength() { return tokenChars.length; }
true
Other
spring-projects
spring-framework
f64325882da41bb128dec1b6d687b6eb6525623f.json
Add SpEL support for increment/decrement operators With this commit the Spring Expression Language now supports increment (++) and decrement (--) operators. These can be used as either prefix or postfix operators. For example: 'somearray[index++]' and 'somearray[--index]' are valid. In order to support this there are serious changes to the evaluation process for expressions. The concept of a value reference for an expression component has been introduced. Value references can be passed around and at any time the actual value can be retrieved (via a get) or set (where applicable). This was needed to avoid double evaluation of expression components. For example, in evaluating the expression 'somearray[index++]--' without a value reference SpEL would need to evaluate the 'somearray[index++]' component twice, once to get the value and then again to determine where to put the new value. If that component is evaluated twice, index would be double incremented. A value reference for 'somearray[index++]' avoids this problem. Many new tests have been introduced into the EvaluationTests to ensure not only that ++ and -- work but also that the introduction of value references across the all of SpEL has not caused regressions. Issue: SPR-9751
spring-expression/src/main/java/org/springframework/expression/spel/standard/Tokenizer.java
@@ -55,13 +55,21 @@ public void process() { } else { switch (ch) { case '+': - pushCharToken(TokenKind.PLUS); + if (isTwoCharToken(TokenKind.INC)) { + pushPairToken(TokenKind.INC); + } else { + pushCharToken(TokenKind.PLUS); + } break; case '_': // the other way to start an identifier lexIdentifier(); break; case '-': - pushCharToken(TokenKind.MINUS); + if (isTwoCharToken(TokenKind.DEC)) { + pushPairToken(TokenKind.DEC); + } else { + pushCharToken(TokenKind.MINUS); + } break; case ':': pushCharToken(TokenKind.COLON);
true
Other
spring-projects
spring-framework
f64325882da41bb128dec1b6d687b6eb6525623f.json
Add SpEL support for increment/decrement operators With this commit the Spring Expression Language now supports increment (++) and decrement (--) operators. These can be used as either prefix or postfix operators. For example: 'somearray[index++]' and 'somearray[--index]' are valid. In order to support this there are serious changes to the evaluation process for expressions. The concept of a value reference for an expression component has been introduced. Value references can be passed around and at any time the actual value can be retrieved (via a get) or set (where applicable). This was needed to avoid double evaluation of expression components. For example, in evaluating the expression 'somearray[index++]--' without a value reference SpEL would need to evaluate the 'somearray[index++]' component twice, once to get the value and then again to determine where to put the new value. If that component is evaluated twice, index would be double incremented. A value reference for 'somearray[index++]' avoids this problem. Many new tests have been introduced into the EvaluationTests to ensure not only that ++ and -- work but also that the introduction of value references across the all of SpEL has not caused regressions. Issue: SPR-9751
spring-expression/src/test/java/org/springframework/expression/spel/EvaluationTests.java
@@ -27,6 +27,7 @@ import org.springframework.core.convert.TypeDescriptor; import org.springframework.expression.AccessException; +import org.springframework.expression.BeanResolver; import org.springframework.expression.EvaluationContext; import org.springframework.expression.EvaluationException; import org.springframework.expression.Expression; @@ -43,7 +44,7 @@ /** * Tests the evaluation of real expressions in a real context. - * + * * @author Andy Clement * @author Mark Fisher * @author Sam Brannen @@ -622,4 +623,765 @@ public List<Method> filter(List<Method> methods) { } + // increment/decrement operators - SPR-9751 + + static class Spr9751 { + public String type = "hello"; + public double ddd = 2.0d; + public float fff = 3.0f; + public long lll = 66666L; + public int iii = 42; + public short sss = (short)15; + public Spr9751_2 foo = new Spr9751_2(); + + public void m() {} + + public int[] intArray = new int[]{1,2,3,4,5}; + public int index1 = 2; + + public Integer[] integerArray; + public int index2 = 2; + + public List<String> listOfStrings; + public int index3 = 0; + + public Spr9751() { + integerArray = new Integer[5]; + integerArray[0] = 1; + integerArray[1] = 2; + integerArray[2] = 3; + integerArray[3] = 4; + integerArray[4] = 5; + listOfStrings = new ArrayList<String>(); + listOfStrings.add("abc"); + } + + public static boolean isEven(int i) { + return (i%2)==0; + } + } + + static class Spr9751_2 { + public int iii = 99; + } + + /** + * This test is checking that with the changes for 9751 that the refactoring in Indexer is + * coping correctly for references beyond collection boundaries. + */ + @Test + public void collectionGrowingViaIndexer() { + Spr9751 instance = new Spr9751(); + + // Add a new element to the list + StandardEvaluationContext ctx = new StandardEvaluationContext(instance); + ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); + Expression e = parser.parseExpression("listOfStrings[++index3]='def'"); + e.getValue(ctx); + assertEquals(2,instance.listOfStrings.size()); + assertEquals("def",instance.listOfStrings.get(1)); + + // Check reference beyond end of collection + ctx = new StandardEvaluationContext(instance); + parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); + e = parser.parseExpression("listOfStrings[0]"); + String value = e.getValue(ctx,String.class); + assertEquals("abc",value); + e = parser.parseExpression("listOfStrings[1]"); + value = e.getValue(ctx,String.class); + assertEquals("def",value); + e = parser.parseExpression("listOfStrings[2]"); + value = e.getValue(ctx,String.class); + assertEquals("",value); + + // Now turn off growing and reference off the end + ctx = new StandardEvaluationContext(instance); + parser = new SpelExpressionParser(new SpelParserConfiguration(false, false)); + e = parser.parseExpression("listOfStrings[3]"); + try { + e.getValue(ctx,String.class); + fail(); + } catch (SpelEvaluationException see) { + assertEquals(SpelMessage.COLLECTION_INDEX_OUT_OF_BOUNDS,see.getMessageCode()); + } + } + + // For now I am making #this not assignable + @Test + public void increment01root() { + Integer i = 42; + StandardEvaluationContext ctx = new StandardEvaluationContext(i); + ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); + Expression e = parser.parseExpression("#this++"); + assertEquals(42,i.intValue()); + try { + e.getValue(ctx,Integer.class); + fail(); + } catch (SpelEvaluationException see) { + assertEquals(SpelMessage.NOT_ASSIGNABLE,see.getMessageCode()); + } + } + + @Test + public void increment02postfix() { + Spr9751 helper = new Spr9751(); + StandardEvaluationContext ctx = new StandardEvaluationContext(helper); + ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); + Expression e = null; + + // double + e = parser.parseExpression("ddd++"); + assertEquals(2.0d,helper.ddd,0d); + double return_ddd = e.getValue(ctx,Double.TYPE); + assertEquals(2.0d,return_ddd,0d); + assertEquals(3.0d,helper.ddd,0d); + + // float + e = parser.parseExpression("fff++"); + assertEquals(3.0f,helper.fff,0d); + float return_fff = e.getValue(ctx,Float.TYPE); + assertEquals(3.0f,return_fff,0d); + assertEquals(4.0f,helper.fff,0d); + + // long + e = parser.parseExpression("lll++"); + assertEquals(66666L,helper.lll); + long return_lll = e.getValue(ctx,Long.TYPE); + assertEquals(66666L,return_lll); + assertEquals(66667L,helper.lll); + + // int + e = parser.parseExpression("iii++"); + assertEquals(42,helper.iii); + int return_iii = e.getValue(ctx,Integer.TYPE); + assertEquals(42,return_iii); + assertEquals(43,helper.iii); + return_iii = e.getValue(ctx,Integer.TYPE); + assertEquals(43,return_iii); + assertEquals(44,helper.iii); + + // short + e = parser.parseExpression("sss++"); + assertEquals(15,helper.sss); + short return_sss = e.getValue(ctx,Short.TYPE); + assertEquals(15,return_sss); + assertEquals(16,helper.sss); + } + + @Test + public void increment02prefix() { + Spr9751 helper = new Spr9751(); + StandardEvaluationContext ctx = new StandardEvaluationContext(helper); + ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); + Expression e = null; + + // double + e = parser.parseExpression("++ddd"); + assertEquals(2.0d,helper.ddd,0d); + double return_ddd = e.getValue(ctx,Double.TYPE); + assertEquals(3.0d,return_ddd,0d); + assertEquals(3.0d,helper.ddd,0d); + + // float + e = parser.parseExpression("++fff"); + assertEquals(3.0f,helper.fff,0d); + float return_fff = e.getValue(ctx,Float.TYPE); + assertEquals(4.0f,return_fff,0d); + assertEquals(4.0f,helper.fff,0d); + + // long + e = parser.parseExpression("++lll"); + assertEquals(66666L,helper.lll); + long return_lll = e.getValue(ctx,Long.TYPE); + assertEquals(66667L,return_lll); + assertEquals(66667L,helper.lll); + + // int + e = parser.parseExpression("++iii"); + assertEquals(42,helper.iii); + int return_iii = e.getValue(ctx,Integer.TYPE); + assertEquals(43,return_iii); + assertEquals(43,helper.iii); + return_iii = e.getValue(ctx,Integer.TYPE); + assertEquals(44,return_iii); + assertEquals(44,helper.iii); + + // short + e = parser.parseExpression("++sss"); + assertEquals(15,helper.sss); + int return_sss = (Integer)e.getValue(ctx); + assertEquals(16,return_sss); + assertEquals(16,helper.sss); + } + + @Test + public void increment03() { + Spr9751 helper = new Spr9751(); + StandardEvaluationContext ctx = new StandardEvaluationContext(helper); + ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); + Expression e = null; + + e = parser.parseExpression("m()++"); + try { + e.getValue(ctx,Double.TYPE); + fail(); + } catch (SpelEvaluationException see) { + assertEquals(SpelMessage.OPERAND_NOT_INCREMENTABLE,see.getMessageCode()); + } + + e = parser.parseExpression("++m()"); + try { + e.getValue(ctx,Double.TYPE); + fail(); + } catch (SpelEvaluationException see) { + assertEquals(SpelMessage.OPERAND_NOT_INCREMENTABLE,see.getMessageCode()); + } + } + + + @Test + public void increment04() { + Integer i = 42; + StandardEvaluationContext ctx = new StandardEvaluationContext(i); + ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); + try { + Expression e = parser.parseExpression("++1"); + e.getValue(ctx,Integer.class); + fail(); + } catch (SpelEvaluationException see) { + assertEquals(SpelMessage.NOT_ASSIGNABLE,see.getMessageCode()); + } + try { + Expression e = parser.parseExpression("1++"); + e.getValue(ctx,Integer.class); + fail(); + } catch (SpelEvaluationException see) { + assertEquals(SpelMessage.NOT_ASSIGNABLE,see.getMessageCode()); + } + } + @Test + public void decrement01root() { + Integer i = 42; + StandardEvaluationContext ctx = new StandardEvaluationContext(i); + ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); + Expression e = parser.parseExpression("#this--"); + assertEquals(42,i.intValue()); + try { + e.getValue(ctx,Integer.class); + fail(); + } catch (SpelEvaluationException see) { + assertEquals(SpelMessage.NOT_ASSIGNABLE,see.getMessageCode()); + } + } + + @Test + public void decrement02postfix() { + Spr9751 helper = new Spr9751(); + StandardEvaluationContext ctx = new StandardEvaluationContext(helper); + ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); + Expression e = null; + + // double + e = parser.parseExpression("ddd--"); + assertEquals(2.0d,helper.ddd,0d); + double return_ddd = e.getValue(ctx,Double.TYPE); + assertEquals(2.0d,return_ddd,0d); + assertEquals(1.0d,helper.ddd,0d); + + // float + e = parser.parseExpression("fff--"); + assertEquals(3.0f,helper.fff,0d); + float return_fff = e.getValue(ctx,Float.TYPE); + assertEquals(3.0f,return_fff,0d); + assertEquals(2.0f,helper.fff,0d); + + // long + e = parser.parseExpression("lll--"); + assertEquals(66666L,helper.lll); + long return_lll = e.getValue(ctx,Long.TYPE); + assertEquals(66666L,return_lll); + assertEquals(66665L,helper.lll); + + // int + e = parser.parseExpression("iii--"); + assertEquals(42,helper.iii); + int return_iii = e.getValue(ctx,Integer.TYPE); + assertEquals(42,return_iii); + assertEquals(41,helper.iii); + return_iii = e.getValue(ctx,Integer.TYPE); + assertEquals(41,return_iii); + assertEquals(40,helper.iii); + + // short + e = parser.parseExpression("sss--"); + assertEquals(15,helper.sss); + short return_sss = e.getValue(ctx,Short.TYPE); + assertEquals(15,return_sss); + assertEquals(14,helper.sss); + } + + @Test + public void decrement02prefix() { + Spr9751 helper = new Spr9751(); + StandardEvaluationContext ctx = new StandardEvaluationContext(helper); + ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); + Expression e = null; + + // double + e = parser.parseExpression("--ddd"); + assertEquals(2.0d,helper.ddd,0d); + double return_ddd = e.getValue(ctx,Double.TYPE); + assertEquals(1.0d,return_ddd,0d); + assertEquals(1.0d,helper.ddd,0d); + + // float + e = parser.parseExpression("--fff"); + assertEquals(3.0f,helper.fff,0d); + float return_fff = e.getValue(ctx,Float.TYPE); + assertEquals(2.0f,return_fff,0d); + assertEquals(2.0f,helper.fff,0d); + + // long + e = parser.parseExpression("--lll"); + assertEquals(66666L,helper.lll); + long return_lll = e.getValue(ctx,Long.TYPE); + assertEquals(66665L,return_lll); + assertEquals(66665L,helper.lll); + + // int + e = parser.parseExpression("--iii"); + assertEquals(42,helper.iii); + int return_iii = e.getValue(ctx,Integer.TYPE); + assertEquals(41,return_iii); + assertEquals(41,helper.iii); + return_iii = e.getValue(ctx,Integer.TYPE); + assertEquals(40,return_iii); + assertEquals(40,helper.iii); + + // short + e = parser.parseExpression("--sss"); + assertEquals(15,helper.sss); + int return_sss = (Integer)e.getValue(ctx); + assertEquals(14,return_sss); + assertEquals(14,helper.sss); + } + + @Test + public void decrement03() { + Spr9751 helper = new Spr9751(); + StandardEvaluationContext ctx = new StandardEvaluationContext(helper); + ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); + Expression e = null; + + e = parser.parseExpression("m()--"); + try { + e.getValue(ctx,Double.TYPE); + fail(); + } catch (SpelEvaluationException see) { + assertEquals(SpelMessage.OPERAND_NOT_DECREMENTABLE,see.getMessageCode()); + } + + e = parser.parseExpression("--m()"); + try { + e.getValue(ctx,Double.TYPE); + fail(); + } catch (SpelEvaluationException see) { + assertEquals(SpelMessage.OPERAND_NOT_DECREMENTABLE,see.getMessageCode()); + } + } + + + @Test + public void decrement04() { + Integer i = 42; + StandardEvaluationContext ctx = new StandardEvaluationContext(i); + ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); + try { + Expression e = parser.parseExpression("--1"); + e.getValue(ctx,Integer.class); + fail(); + } catch (SpelEvaluationException see) { + assertEquals(SpelMessage.NOT_ASSIGNABLE,see.getMessageCode()); + } + try { + Expression e = parser.parseExpression("1--"); + e.getValue(ctx,Integer.class); + fail(); + } catch (SpelEvaluationException see) { + assertEquals(SpelMessage.NOT_ASSIGNABLE,see.getMessageCode()); + } + } + + @Test + public void incdecTogether() { + Spr9751 helper = new Spr9751(); + StandardEvaluationContext ctx = new StandardEvaluationContext(helper); + ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); + Expression e = null; + + // index1 is 2 at the start - the 'intArray[#root.index1++]' should not be evaluated twice! + // intArray[2] is 3 + e = parser.parseExpression("intArray[#root.index1++]++"); + e.getValue(ctx,Integer.class); + assertEquals(3,helper.index1); + assertEquals(4,helper.intArray[2]); + + // index1 is 3 intArray[3] is 4 + e = parser.parseExpression("intArray[#root.index1++]--"); + assertEquals(4,e.getValue(ctx,Integer.class).intValue()); + assertEquals(4,helper.index1); + assertEquals(3,helper.intArray[3]); + + // index1 is 4, intArray[3] is 3 + e = parser.parseExpression("intArray[--#root.index1]++"); + assertEquals(3,e.getValue(ctx,Integer.class).intValue()); + assertEquals(3,helper.index1); + assertEquals(4,helper.intArray[3]); + } + + + + + 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 (++, --, =) + @Test + public void incrementAllNodeTypes() throws SecurityException, NoSuchMethodException { + Spr9751 helper = new Spr9751(); + StandardEvaluationContext ctx = new StandardEvaluationContext(helper); + ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); + Expression e = null; + + // BooleanLiteral + expectFailNotAssignable(parser, ctx, "true++"); + expectFailNotAssignable(parser, ctx, "--false"); + expectFailSetValueNotSupported(parser, ctx, "true=false"); + + // IntLiteral + expectFailNotAssignable(parser, ctx, "12++"); + expectFailNotAssignable(parser, ctx, "--1222"); + expectFailSetValueNotSupported(parser, ctx, "12=16"); + + // LongLiteral + expectFailNotAssignable(parser, ctx, "1.0d++"); + expectFailNotAssignable(parser, ctx, "--3.4d"); + expectFailSetValueNotSupported(parser, ctx, "1.0d=3.2d"); + + // NullLiteral + expectFailNotAssignable(parser, ctx, "null++"); + expectFailNotAssignable(parser, ctx, "--null"); + expectFailSetValueNotSupported(parser, ctx, "null=null"); + expectFailSetValueNotSupported(parser, ctx, "null=123"); + + // OpAnd + expectFailNotAssignable(parser, ctx, "(true && false)++"); + expectFailNotAssignable(parser, ctx, "--(false AND true)"); + expectFailSetValueNotSupported(parser, ctx, "(true && false)=(false && true)"); + + // OpDivide + expectFailNotAssignable(parser, ctx, "(3/4)++"); + expectFailNotAssignable(parser, ctx, "--(2/5)"); + expectFailSetValueNotSupported(parser, ctx, "(1/2)=(3/4)"); + + // OpEq + expectFailNotAssignable(parser, ctx, "(3==4)++"); + expectFailNotAssignable(parser, ctx, "--(2==5)"); + expectFailSetValueNotSupported(parser, ctx, "(1==2)=(3==4)"); + + // OpGE + expectFailNotAssignable(parser, ctx, "(3>=4)++"); + expectFailNotAssignable(parser, ctx, "--(2>=5)"); + expectFailSetValueNotSupported(parser, ctx, "(1>=2)=(3>=4)"); + + // OpGT + expectFailNotAssignable(parser, ctx, "(3>4)++"); + expectFailNotAssignable(parser, ctx, "--(2>5)"); + expectFailSetValueNotSupported(parser, ctx, "(1>2)=(3>4)"); + + // OpLE + expectFailNotAssignable(parser, ctx, "(3<=4)++"); + expectFailNotAssignable(parser, ctx, "--(2<=5)"); + expectFailSetValueNotSupported(parser, ctx, "(1<=2)=(3<=4)"); + + // OpLT + expectFailNotAssignable(parser, ctx, "(3<4)++"); + expectFailNotAssignable(parser, ctx, "--(2<5)"); + expectFailSetValueNotSupported(parser, ctx, "(1<2)=(3<4)"); + + // OpMinus + expectFailNotAssignable(parser, ctx, "(3-4)++"); + expectFailNotAssignable(parser, ctx, "--(2-5)"); + expectFailSetValueNotSupported(parser, ctx, "(1-2)=(3-4)"); + + // OpModulus + expectFailNotAssignable(parser, ctx, "(3%4)++"); + expectFailNotAssignable(parser, ctx, "--(2%5)"); + expectFailSetValueNotSupported(parser, ctx, "(1%2)=(3%4)"); + + // OpMultiply + expectFailNotAssignable(parser, ctx, "(3*4)++"); + expectFailNotAssignable(parser, ctx, "--(2*5)"); + expectFailSetValueNotSupported(parser, ctx, "(1*2)=(3*4)"); + + // OpNE + expectFailNotAssignable(parser, ctx, "(3!=4)++"); + expectFailNotAssignable(parser, ctx, "--(2!=5)"); + expectFailSetValueNotSupported(parser, ctx, "(1!=2)=(3!=4)"); + + // OpOr + expectFailNotAssignable(parser, ctx, "(true || false)++"); + expectFailNotAssignable(parser, ctx, "--(false OR true)"); + expectFailSetValueNotSupported(parser, ctx, "(true || false)=(false OR true)"); + + // OpPlus + expectFailNotAssignable(parser, ctx, "(3+4)++"); + expectFailNotAssignable(parser, ctx, "--(2+5)"); + expectFailSetValueNotSupported(parser, ctx, "(1+2)=(3+4)"); + + // RealLiteral + expectFailNotAssignable(parser, ctx, "1.0d++"); + expectFailNotAssignable(parser, ctx, "--2.0d"); + expectFailSetValueNotSupported(parser, ctx, "(1.0d)=(3.0d)"); + expectFailNotAssignable(parser, ctx, "1.0f++"); + expectFailNotAssignable(parser, ctx, "--2.0f"); + expectFailSetValueNotSupported(parser, ctx, "(1.0f)=(3.0f)"); + + // StringLiteral + expectFailNotAssignable(parser, ctx, "'abc'++"); + expectFailNotAssignable(parser, ctx, "--'def'"); + expectFailSetValueNotSupported(parser, ctx, "'abc'='def'"); + + // Ternary + expectFailNotAssignable(parser, ctx, "(true?true:false)++"); + expectFailNotAssignable(parser, ctx, "--(true?true:false)"); + expectFailSetValueNotSupported(parser, ctx, "(true?true:false)=(true?true:false)"); + + // TypeReference + expectFailNotAssignable(parser, ctx, "T(String)++"); + expectFailNotAssignable(parser, ctx, "--T(Integer)"); + expectFailSetValueNotSupported(parser, ctx, "T(String)=T(Integer)"); + + // OperatorBetween + expectFailNotAssignable(parser, ctx, "(3 between {1,5})++"); + expectFailNotAssignable(parser, ctx, "--(3 between {1,5})"); + expectFailSetValueNotSupported(parser, ctx, "(3 between {1,5})=(3 between {1,5})"); + + // OperatorInstanceOf + expectFailNotAssignable(parser, ctx, "(type instanceof T(String))++"); + expectFailNotAssignable(parser, ctx, "--(type instanceof T(String))"); + expectFailSetValueNotSupported(parser, ctx, "(type instanceof T(String))=(type instanceof T(String))"); + + // Elvis + expectFailNotAssignable(parser, ctx, "(true?:false)++"); + expectFailNotAssignable(parser, ctx, "--(true?:false)"); + expectFailSetValueNotSupported(parser, ctx, "(true?:false)=(true?:false)"); + + // OpInc + expectFailNotAssignable(parser, ctx, "(iii++)++"); + expectFailNotAssignable(parser, ctx, "--(++iii)"); + expectFailSetValueNotSupported(parser, ctx, "(iii++)=(++iii)"); + + // OpDec + expectFailNotAssignable(parser, ctx, "(iii--)++"); + expectFailNotAssignable(parser, ctx, "--(--iii)"); + expectFailSetValueNotSupported(parser, ctx, "(iii--)=(--iii)"); + + // OperatorNot + expectFailNotAssignable(parser, ctx, "(!true)++"); + expectFailNotAssignable(parser, ctx, "--(!false)"); + expectFailSetValueNotSupported(parser, ctx, "(!true)=(!false)"); + + // OperatorPower + expectFailNotAssignable(parser, ctx, "(iii^2)++"); + expectFailNotAssignable(parser, ctx, "--(iii^2)"); + expectFailSetValueNotSupported(parser, ctx, "(iii^2)=(iii^3)"); + + // Assign + // iii=42 + e = parser.parseExpression("iii=iii++"); + assertEquals(42,helper.iii); + int return_iii = e.getValue(ctx,Integer.TYPE); + assertEquals(42,helper.iii); + assertEquals(42,return_iii); + + // Identifier + e = parser.parseExpression("iii++"); + assertEquals(42,helper.iii); + return_iii = e.getValue(ctx,Integer.TYPE); + assertEquals(42,return_iii); + assertEquals(43,helper.iii); + + e = parser.parseExpression("--iii"); + assertEquals(43,helper.iii); + return_iii = e.getValue(ctx,Integer.TYPE); + assertEquals(42,return_iii); + assertEquals(42,helper.iii); + + e = parser.parseExpression("iii=99"); + assertEquals(42,helper.iii); + return_iii = e.getValue(ctx,Integer.TYPE); + assertEquals(99,return_iii); + assertEquals(99,helper.iii); + + // CompoundExpression + // foo.iii == 99 + e = parser.parseExpression("foo.iii++"); + assertEquals(99,helper.foo.iii); + int return_foo_iii = e.getValue(ctx,Integer.TYPE); + assertEquals(99,return_foo_iii); + assertEquals(100,helper.foo.iii); + + e = parser.parseExpression("--foo.iii"); + assertEquals(100,helper.foo.iii); + return_foo_iii = e.getValue(ctx,Integer.TYPE); + assertEquals(99,return_foo_iii); + assertEquals(99,helper.foo.iii); + + e = parser.parseExpression("foo.iii=999"); + assertEquals(99,helper.foo.iii); + return_foo_iii = e.getValue(ctx,Integer.TYPE); + assertEquals(999,return_foo_iii); + assertEquals(999,helper.foo.iii); + + // ConstructorReference + expectFailNotAssignable(parser, ctx, "(new String('abc'))++"); + expectFailNotAssignable(parser, ctx, "--(new String('abc'))"); + expectFailSetValueNotSupported(parser, ctx, "(new String('abc'))=(new String('abc'))"); + + // MethodReference + expectFailNotIncrementable(parser, ctx, "m()++"); + expectFailNotDecrementable(parser, ctx, "--m()"); + expectFailSetValueNotSupported(parser, ctx, "m()=m()"); + + // OperatorMatches + expectFailNotAssignable(parser, ctx, "('abc' matches '^a..')++"); + expectFailNotAssignable(parser, ctx, "--('abc' matches '^a..')"); + expectFailSetValueNotSupported(parser, ctx, "('abc' matches '^a..')=('abc' matches '^a..')"); + + // Selection + ctx.registerFunction("isEven", Spr9751.class.getDeclaredMethod("isEven", Integer.TYPE)); + + expectFailNotIncrementable(parser, ctx, "({1,2,3}.?[#isEven(#this)])++"); + expectFailNotDecrementable(parser, ctx, "--({1,2,3}.?[#isEven(#this)])"); + expectFailNotAssignable(parser, ctx, "({1,2,3}.?[#isEven(#this)])=({1,2,3}.?[#isEven(#this)])"); + + // slightly diff here because return value isn't a list, it is a single entity + expectFailNotAssignable(parser, ctx, "({1,2,3}.^[#isEven(#this)])++"); + expectFailNotAssignable(parser, ctx, "--({1,2,3}.^[#isEven(#this)])"); + expectFailNotAssignable(parser, ctx, "({1,2,3}.^[#isEven(#this)])=({1,2,3}.^[#isEven(#this)])"); + + expectFailNotAssignable(parser, ctx, "({1,2,3}.$[#isEven(#this)])++"); + expectFailNotAssignable(parser, ctx, "--({1,2,3}.$[#isEven(#this)])"); + expectFailNotAssignable(parser, ctx, "({1,2,3}.$[#isEven(#this)])=({1,2,3}.$[#isEven(#this)])"); + + // FunctionReference + expectFailNotAssignable(parser, ctx, "#isEven(3)++"); + expectFailNotAssignable(parser, ctx, "--#isEven(4)"); + expectFailSetValueNotSupported(parser, ctx, "#isEven(3)=#isEven(5)"); + + // VariableReference + ctx.setVariable("wibble", "hello world"); + expectFailNotIncrementable(parser, ctx, "#wibble++"); + expectFailNotDecrementable(parser, ctx, "--#wibble"); + e = parser.parseExpression("#wibble=#wibble+#wibble"); + String s = e.getValue(ctx,String.class); + assertEquals("hello worldhello world",s); + assertEquals("hello worldhello world",(String)ctx.lookupVariable("wibble")); + + ctx.setVariable("wobble", 3); + e = parser.parseExpression("#wobble++"); + assertEquals(3,((Integer)ctx.lookupVariable("wobble")).intValue()); + int r = e.getValue(ctx,Integer.TYPE); + assertEquals(3,r); + assertEquals(4,((Integer)ctx.lookupVariable("wobble")).intValue()); + + e = parser.parseExpression("--#wobble"); + assertEquals(4,((Integer)ctx.lookupVariable("wobble")).intValue()); + r = e.getValue(ctx,Integer.TYPE); + assertEquals(3,r); + assertEquals(3,((Integer)ctx.lookupVariable("wobble")).intValue()); + + e = parser.parseExpression("#wobble=34"); + assertEquals(3,((Integer)ctx.lookupVariable("wobble")).intValue()); + r = e.getValue(ctx,Integer.TYPE); + assertEquals(34,r); + assertEquals(34,((Integer)ctx.lookupVariable("wobble")).intValue()); + + // Projection + expectFailNotIncrementable(parser, ctx, "({1,2,3}.![#isEven(#this)])++"); // projection would be {false,true,false} + expectFailNotDecrementable(parser, ctx, "--({1,2,3}.![#isEven(#this)])"); // projection would be {false,true,false} + expectFailNotAssignable(parser, ctx, "({1,2,3}.![#isEven(#this)])=({1,2,3}.![#isEven(#this)])"); + + // InlineList + expectFailNotAssignable(parser, ctx, "({1,2,3})++"); + expectFailNotAssignable(parser, ctx, "--({1,2,3})"); + expectFailSetValueNotSupported(parser, ctx, "({1,2,3})=({1,2,3})"); + + // BeanReference + ctx.setBeanResolver(new MyBeanResolver()); + expectFailNotAssignable(parser, ctx, "@foo++"); + expectFailNotAssignable(parser, ctx, "--@foo"); + expectFailSetValueNotSupported(parser, ctx, "@foo=@bar"); + + // PropertyOrFieldReference + helper.iii = 42; + e = parser.parseExpression("iii++"); + assertEquals(42,helper.iii); + r = e.getValue(ctx,Integer.TYPE); + assertEquals(42,r); + assertEquals(43,helper.iii); + + e = parser.parseExpression("--iii"); + assertEquals(43,helper.iii); + r = e.getValue(ctx,Integer.TYPE); + assertEquals(42,r); + assertEquals(42,helper.iii); + + e = parser.parseExpression("iii=100"); + assertEquals(42,helper.iii); + r = e.getValue(ctx,Integer.TYPE); + assertEquals(100,r); + assertEquals(100,helper.iii); + + } + + static class MyBeanResolver implements BeanResolver { + + public Object resolve(EvaluationContext context, String beanName) + throws AccessException { + if (beanName.equals("foo") || beanName.equals("bar")) { + return new Spr9751_2(); + } + throw new AccessException("not heard of "+beanName); + } + + } + + }
true
Other
spring-projects
spring-framework
f64325882da41bb128dec1b6d687b6eb6525623f.json
Add SpEL support for increment/decrement operators With this commit the Spring Expression Language now supports increment (++) and decrement (--) operators. These can be used as either prefix or postfix operators. For example: 'somearray[index++]' and 'somearray[--index]' are valid. In order to support this there are serious changes to the evaluation process for expressions. The concept of a value reference for an expression component has been introduced. Value references can be passed around and at any time the actual value can be retrieved (via a get) or set (where applicable). This was needed to avoid double evaluation of expression components. For example, in evaluating the expression 'somearray[index++]--' without a value reference SpEL would need to evaluate the 'somearray[index++]' component twice, once to get the value and then again to determine where to put the new value. If that component is evaluated twice, index would be double incremented. A value reference for 'somearray[index++]' avoids this problem. Many new tests have been introduced into the EvaluationTests to ensure not only that ++ and -- work but also that the introduction of value references across the all of SpEL has not caused regressions. Issue: SPR-9751
spring-expression/src/test/java/org/springframework/expression/spel/InProgressTests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2012 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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.expression.spel; import java.util.ArrayList; @@ -22,22 +23,22 @@ import org.junit.Test; import org.springframework.expression.spel.standard.SpelExpression; -import org.springframework.expression.spel.support.StandardEvaluationContext; /** * These are tests for language features that are not yet considered 'live'. Either missing implementation or * documentation. - * + * * Where implementation is missing the tests are commented out. - * + * * @author Andy Clement */ public class InProgressTests extends ExpressionTestCase { @Test public void testRelOperatorsBetween01() { evaluate("1 between listOneFive", "true", Boolean.class); - // evaluate("1 between {1, 5}", "true", Boolean.class); // no inline list building at the moment + // no inline list building at the moment + // evaluate("1 between {1, 5}", "true", Boolean.class); } @Test @@ -78,7 +79,6 @@ public void testProjection05() { public void testProjection06() throws Exception { SpelExpression expr = (SpelExpression) parser.parseExpression("'abc'.![true]"); Assert.assertEquals("'abc'.![true]", expr.toStringAST()); - Assert.assertFalse(expr.isWritable(new StandardEvaluationContext())); } // SELECTION @@ -99,7 +99,6 @@ public void testSelectionError_NonBooleanSelectionCriteria() { @Test public void testSelection03() { evaluate("mapOfNumbersUpToTen.?[key>5].size()", "5", Integer.class); - // evaluate("listOfNumbersUpToTen.?{#this>5}", "5", ArrayList.class); } @Test @@ -143,284 +142,16 @@ public void testSelectionLast02() { public void testSelectionAST() throws Exception { SpelExpression expr = (SpelExpression) parser.parseExpression("'abc'.^[true]"); Assert.assertEquals("'abc'.^[true]", expr.toStringAST()); - Assert.assertFalse(expr.isWritable(new StandardEvaluationContext())); expr = (SpelExpression) parser.parseExpression("'abc'.?[true]"); Assert.assertEquals("'abc'.?[true]", expr.toStringAST()); - Assert.assertFalse(expr.isWritable(new StandardEvaluationContext())); expr = (SpelExpression) parser.parseExpression("'abc'.$[true]"); Assert.assertEquals("'abc'.$[true]", expr.toStringAST()); - Assert.assertFalse(expr.isWritable(new StandardEvaluationContext())); } // Constructor invocation - - // public void testPrimitiveTypeArrayConstructors() { - // evaluate("new int[]{1,2,3,4}.count()", 4, Integer.class); - // evaluate("new boolean[]{true,false,true}.count()", 3, Integer.class); - // evaluate("new char[]{'a','b','c'}.count()", 3, Integer.class); - // evaluate("new long[]{1,2,3,4,5}.count()", 5, Integer.class); - // evaluate("new short[]{2,3,4,5,6}.count()", 5, Integer.class); - // evaluate("new double[]{1d,2d,3d,4d}.count()", 4, Integer.class); - // evaluate("new float[]{1f,2f,3f,4f}.count()", 4, Integer.class); - // evaluate("new byte[]{1,2,3,4}.count()", 4, Integer.class); - // } - // - // public void testPrimitiveTypeArrayConstructorsElements() { - // evaluate("new int[]{1,2,3,4}[0]", 1, Integer.class); - // evaluate("new boolean[]{true,false,true}[0]", true, Boolean.class); - // evaluate("new char[]{'a','b','c'}[0]", 'a', Character.class); - // evaluate("new long[]{1,2,3,4,5}[0]", 1L, Long.class); - // evaluate("new short[]{2,3,4,5,6}[0]", (short) 2, Short.class); - // evaluate("new double[]{1d,2d,3d,4d}[0]", (double) 1, Double.class); - // evaluate("new float[]{1f,2f,3f,4f}[0]", (float) 1, Float.class); - // evaluate("new byte[]{1,2,3,4}[0]", (byte) 1, Byte.class); - // } - // - // public void testErrorCases() { - // evaluateAndCheckError("new char[7]{'a','c','d','e'}", SpelMessages.INITIALIZER_LENGTH_INCORRECT); - // evaluateAndCheckError("new char[3]{'a','c','d','e'}", SpelMessages.INITIALIZER_LENGTH_INCORRECT); - // evaluateAndCheckError("new char[2]{'hello','world'}", SpelMessages.TYPE_CONVERSION_ERROR); - // evaluateAndCheckError("new String('a','c','d')", SpelMessages.CONSTRUCTOR_NOT_FOUND); - // } - // - // public void testTypeArrayConstructors() { - // evaluate("new String[]{'a','b','c','d'}[1]", "b", String.class); - // evaluateAndCheckError("new String[]{'a','b','c','d'}.size()", SpelMessages.METHOD_NOT_FOUND, 30, "size()", - // "java.lang.String[]"); - // evaluateAndCheckError("new String[]{'a','b','c','d'}.juggernaut", SpelMessages.PROPERTY_OR_FIELD_NOT_FOUND, 30, - // "juggernaut", "java.lang.String[]"); - // evaluate("new String[]{'a','b','c','d'}.length", 4, Integer.class); - // } - - // public void testMultiDimensionalArrays() { - // evaluate( - // "new String[3,4]", - // "[Ljava.lang.String;[3]{java.lang.String[4]{null,null,null,null},java.lang.String[4]{null,null,null,null},java.lang.String[4]{null,null,null,null}}" - // , - // new String[3][4].getClass()); - // } - // - // - // evaluate("new String(new char[]{'h','e','l','l','o'})", "hello", String.class); - // - // - // - // public void testRelOperatorsIn01() { - // evaluate("3 in {1,2,3,4,5}", "true", Boolean.class); - // } - // - // public void testRelOperatorsIn02() { - // evaluate("name in {null, \"Nikola Tesla\"}", "true", Boolean.class); - // evaluate("name in {null, \"Anonymous\"}", "false", Boolean.class); - // } - // - // - // public void testRelOperatorsBetween02() { - // evaluate("'efg' between {'abc', 'xyz'}", "true", Boolean.class); - // } - // - // - // public void testRelOperatorsBetweenErrors02() { - // evaluateAndCheckError("'abc' between {5,7}", SpelMessages.NOT_COMPARABLE, 6); - // } - // Lambda calculations - // - // - // public void testLambda02() { - // evaluate("(#max={|x,y| $x > $y ? $x : $y };true)", "true", Boolean.class); - // } - // - // public void testLambdaMax() { - // evaluate("(#max = {|x,y| $x > $y ? $x : $y }; #max(5,25))", "25", Integer.class); - // } - // - // public void testLambdaFactorial01() { - // evaluate("(#fact = {|n| $n <= 1 ? 1 : $n * #fact($n-1) }; #fact(5))", "120", Integer.class); - // } - // - // public void testLambdaFactorial02() { - // evaluate("(#fact = {|n| $n <= 1 ? 1 : #fact($n-1) * $n }; #fact(5))", "120", Integer.class); - // } - // - // public void testLambdaAlphabet01() { - // evaluate("(#alpha = {|l,s| $l>'z'?$s:#alpha($l+1,$s+$l)};#alphabet={||#alpha('a','')}; #alphabet())", - // "abcdefghijklmnopqrstuvwxyz", String.class); - // } - // - // public void testLambdaAlphabet02() { - // evaluate("(#alphabet = {|l,s| $l>'z'?$s:#alphabet($l+1,$s+$l)};#alphabet('a',''))", - // "abcdefghijklmnopqrstuvwxyz", String.class); - // } - // - // public void testLambdaDelegation01() { - // evaluate("(#sqrt={|n| T(Math).sqrt($n)};#delegate={|f,n| $f($n)};#delegate(#sqrt,4))", "2.0", Double.class); - // } - // - // public void testVariableReferences() { - // evaluate("(#answer=42;#answer)", "42", Integer.class, true); - // evaluate("($answer=42;$answer)", "42", Integer.class, true); - // } - -// // inline map creation - // @Test - // public void testInlineMapCreation01() { - // evaluate("#{'key1':'Value 1', 'today':'Monday'}", "{key1=Value 1, today=Monday}", HashMap.class); - // } - // - // @Test - // public void testInlineMapCreation02() { - // // "{2=February, 1=January, 3=March}", HashMap.class); - // evaluate("#{1:'January', 2:'February', 3:'March'}.size()", 3, Integer.class); - // } - // - // @Test - // public void testInlineMapCreation03() { - // evaluate("#{'key1':'Value 1', 'today':'Monday'}['key1']", "Value 1", String.class); -// } -// -// @Test -// public void testInlineMapCreation04() { -// evaluate("#{1:'January', 2:'February', 3:'March'}[3]", "March", String.class); -// } -// -// @Test -// public void testInlineMapCreation05() { -// evaluate("#{1:'January', 2:'February', 3:'March'}.get(2)", "February", String.class); -// } - - // set construction @Test public void testSetConstruction01() { evaluate("new java.util.HashSet().addAll({'a','b','c'})", "true", Boolean.class); } - // - // public void testConstructorInvocation02() { - // evaluate("new String[3]", "java.lang.String[3]{null,null,null}", String[].class); - // } - // - // public void testConstructorInvocation03() { - // evaluateAndCheckError("new String[]", SpelMessages.NO_SIZE_OR_INITIALIZER_FOR_ARRAY_CONSTRUCTION, 4); - // } - // - // public void testConstructorInvocation04() { - // evaluateAndCheckError("new String[3]{'abc',3,'def'}", SpelMessages.INCORRECT_ELEMENT_TYPE_FOR_ARRAY, 4); - // } - // array construction - // @Test - // public void testArrayConstruction01() { - // evaluate("new int[] {1, 2, 3, 4, 5}", "int[5]{1,2,3,4,5}", int[].class); - // } - // public void testArrayConstruction02() { - // evaluate("new String[] {'abc', 'xyz'}", "java.lang.String[2]{abc,xyz}", String[].class); - // } - // - // collection processors - // from spring.net: count,sum,max,min,average,sort,orderBy,distinct,nonNull - // public void testProcessorsCount01() { - // evaluate("new String[] {'abc','def','xyz'}.count()", "3", Integer.class); - // } - // - // public void testProcessorsCount02() { - // evaluate("new int[] {1,2,3}.count()", "3", Integer.class); - // } - // - // public void testProcessorsMax01() { - // evaluate("new int[] {1,2,3}.max()", "3", Integer.class); - // } - // - // public void testProcessorsMin01() { - // evaluate("new int[] {1,2,3}.min()", "1", Integer.class); - // } - // - // public void testProcessorsKeys01() { - // evaluate("#{1:'January', 2:'February', 3:'March'}.keySet().sort()", "[1, 2, 3]", ArrayList.class); - // } - // - // public void testProcessorsValues01() { - // evaluate("#{1:'January', 2:'February', 3:'March'}.values().sort()", "[February, January, March]", - // ArrayList.class); - // } - // - // public void testProcessorsAverage01() { - // evaluate("new int[] {1,2,3}.average()", "2", Integer.class); - // } - // - // public void testProcessorsSort01() { - // evaluate("new int[] {3,2,1}.sort()", "int[3]{1,2,3}", int[].class); - // } - // - // public void testCollectionProcessorsNonNull01() { - // evaluate("{'a','b',null,'d',null}.nonnull()", "[a, b, d]", ArrayList.class); - // } - // - // public void testCollectionProcessorsDistinct01() { - // evaluate("{'a','b','a','d','e'}.distinct()", "[a, b, d, e]", ArrayList.class); - // } - // - // public void testProjection03() { - // evaluate("{1,2,3,4,5,6,7,8,9,10}.!{#this>5}", - // "[false, false, false, false, false, true, true, true, true, true]", ArrayList.class); - // } - // - // public void testProjection04() { - // evaluate("{1,2,3,4,5,6,7,8,9,10}.!{$index>5?'y':'n'}", "[n, n, n, n, n, n, y, y, y, y]", ArrayList.class); - // } - // Bean references - // public void testReferences01() { - // evaluate("@(apple).name", "Apple", String.class, true); - // } - // - // public void testReferences02() { - // evaluate("@(fruits:banana).name", "Banana", String.class, true); - // } - // - // public void testReferences03() { - // evaluate("@(a.b.c)", null, null); - // } // null - no context, a.b.c treated as name - // - // public void testReferences05() { - // evaluate("@(a/b/c:orange).name", "Orange", String.class, true); - // } - // - // public void testReferences06() { - // evaluate("@(apple).color.getRGB() == T(java.awt.Color).green.getRGB()", "true", Boolean.class); - // } - // - // public void testReferences07() { - // evaluate("@(apple).color.getRGB().equals(T(java.awt.Color).green.getRGB())", "true", Boolean.class); - // } - // - // value is not public, it is accessed through getRGB() - // public void testStaticRef01() { - // evaluate("T(Color).green.value!=0", "true", Boolean.class); - // } - // Indexer - // public void testCutProcessor01() { - // evaluate("{1,2,3,4,5}.cut(1,3)", "[2, 3, 4]", ArrayList.class); - // } - // - // public void testCutProcessor02() { - // evaluate("{1,2,3,4,5}.cut(3,1)", "[4, 3, 2]", ArrayList.class); - // } - // Ternary operator - // public void testTernaryOperator01() { - // evaluate("{1}.#isEven(#this[0]) == 'y'?'it is even':'it is odd'", "it is odd", String.class); - // } - // - // public void testTernaryOperator02() { - // evaluate("{2}.#isEven(#this[0]) == 'y'?'it is even':'it is odd'", "it is even", String.class); - // } - // public void testSelectionUsingIndex() { - // evaluate("{1,2,3,4,5,6,7,8,9,10}.?{$index > 5 }", "[7, 8, 9, 10]", ArrayList.class); - // } - // public void testSelection01() { - // inline list creation not supported: - // evaluate("{1,2,3,4,5,6,7,8,9,10}.?{#isEven(#this) == 'y'}", "[2, 4, 6, 8, 10]", ArrayList.class); - // } - // - // public void testSelectionUsingIndex() { - // evaluate("listOfNumbersUpToTen.?[#index > 5 ]", "[7, 8, 9, 10]", ArrayList.class); - // } - }
true
Other
spring-projects
spring-framework
3bb515bec72b1984ae422f7a9da12e412978f61c.json
Improve async support in Spring MVC Test When obtaining an async result, tests will now await concurrent processing to complete for the exact amount of time equal to the actual async timeout value. Issue: SPR-9875
spring-test-mvc/src/main/java/org/springframework/test/web/servlet/DefaultMvcResult.java
@@ -15,8 +15,15 @@ */ package org.springframework.test.web.servlet; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import javax.servlet.http.HttpServletRequest; + import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.web.context.request.async.WebAsyncManager; +import org.springframework.web.context.request.async.WebAsyncUtils; import org.springframework.web.servlet.FlashMap; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; @@ -43,6 +50,8 @@ class DefaultMvcResult implements MvcResult { private Exception resolvedException; + private CountDownLatch asyncResultLatch; + /** * Create a new instance with the given request and response. @@ -96,4 +105,36 @@ public FlashMap getFlashMap() { return RequestContextUtils.getOutputFlashMap(mockRequest); } + public void setAsyncResultLatch(CountDownLatch asyncResultLatch) { + this.asyncResultLatch = asyncResultLatch; + } + + public Object getAsyncResult() { + WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.mockRequest); + if (asyncManager.isConcurrentHandlingStarted()) { + if (!awaitAsyncResult()) { + throw new IllegalStateException( + "Gave up waiting on async result from [" + this.handler + "] to complete"); + } + if (asyncManager.hasConcurrentResult()) { + return asyncManager.getConcurrentResult(); + } + } + + return null; + } + + private boolean awaitAsyncResult() { + if (this.asyncResultLatch == null) { + return true; + } + long timeout = ((HttpServletRequest) this.mockRequest).getAsyncContext().getTimeout(); + try { + return this.asyncResultLatch.await(timeout, TimeUnit.MILLISECONDS); + } + catch (InterruptedException e) { + return false; + } + } + }
true
Other
spring-projects
spring-framework
3bb515bec72b1984ae422f7a9da12e412978f61c.json
Improve async support in Spring MVC Test When obtaining an async result, tests will now await concurrent processing to complete for the exact amount of time equal to the actual async timeout value. Issue: SPR-9875
spring-test-mvc/src/main/java/org/springframework/test/web/servlet/MvcResult.java
@@ -75,4 +75,14 @@ public interface MvcResult { */ FlashMap getFlashMap(); + /** + * Get the result of asynchronous execution or {@code null} if concurrent + * handling did not start. This method will hold and await the completion + * of concurrent handling. + * + * @throws IllegalStateException if concurrent handling does not complete + * within the allocated async timeout value. + */ + Object getAsyncResult(); + }
true
Other
spring-projects
spring-framework
3bb515bec72b1984ae422f7a9da12e412978f61c.json
Improve async support in Spring MVC Test When obtaining an async result, tests will now await concurrent processing to complete for the exact amount of time equal to the actual async timeout value. Issue: SPR-9875
spring-test-mvc/src/main/java/org/springframework/test/web/servlet/TestDispatcherServlet.java
@@ -19,7 +19,6 @@ import java.io.IOException; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; import javax.servlet.ServletException; import javax.servlet.ServletRequest; @@ -56,32 +55,41 @@ public TestDispatcherServlet(WebApplicationContext webApplicationContext) { super(webApplicationContext); } - protected DefaultMvcResult getMvcResult(ServletRequest request) { - return (DefaultMvcResult) request.getAttribute(MockMvc.MVC_RESULT_ATTRIBUTE); - } - @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); + CountDownLatch latch = registerAsyncInterceptors(request); + getMvcResult(request).setAsyncResultLatch(latch); - TestCallableInterceptor callableInterceptor = new TestCallableInterceptor(); - asyncManager.registerCallableInterceptor("mock-mvc", callableInterceptor); + super.service(request, response); + } - TestDeferredResultInterceptor deferredResultInterceptor = new TestDeferredResultInterceptor(); - asyncManager.registerDeferredResultInterceptor("mock-mvc", deferredResultInterceptor); + private CountDownLatch registerAsyncInterceptors(HttpServletRequest request) { - super.service(request, response); + final CountDownLatch asyncResultLatch = new CountDownLatch(1); + + WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); - // TODO: add CountDownLatch to DeferredResultInterceptor and wait in request().asyncResult(..) + asyncManager.registerCallableInterceptor("mockmvc", new CallableProcessingInterceptor() { + public void preProcess(NativeWebRequest request, Callable<?> task) throws Exception { } + public void postProcess(NativeWebRequest request, Callable<?> task, Object value) throws Exception { + asyncResultLatch.countDown(); + } + }); - Object handler = getMvcResult(request).getHandler(); - if (asyncManager.isConcurrentHandlingStarted() && !deferredResultInterceptor.wasInvoked) { - if (!callableInterceptor.await()) { - throw new ServletException( - "Gave up waiting on Callable from [" + handler.getClass().getName() + "] to complete"); + asyncManager.registerDeferredResultInterceptor("mockmvc", new DeferredResultProcessingInterceptor() { + public void preProcess(NativeWebRequest request, DeferredResult<?> result) throws Exception { } + public void postProcess(NativeWebRequest request, DeferredResult<?> result, Object value) throws Exception { + asyncResultLatch.countDown(); } - } + public void afterExpiration(NativeWebRequest request, DeferredResult<?> result) throws Exception { } + }); + + return asyncResultLatch; + } + + protected DefaultMvcResult getMvcResult(ServletRequest request) { + return (DefaultMvcResult) request.getAttribute(MockMvc.MVC_RESULT_ATTRIBUTE); } @Override @@ -118,38 +126,4 @@ protected ModelAndView processHandlerException(HttpServletRequest request, HttpS return mav; } - - private final class TestCallableInterceptor implements CallableProcessingInterceptor { - - private final CountDownLatch latch = new CountDownLatch(1); - - private boolean await() { - try { - return this.latch.await(5, TimeUnit.SECONDS); - } - catch (InterruptedException e) { - return false; - } - } - - public void preProcess(NativeWebRequest request, Callable<?> task) { } - - public void postProcess(NativeWebRequest request, Callable<?> task, Object concurrentResult) { - this.latch.countDown(); - } - } - - private final class TestDeferredResultInterceptor implements DeferredResultProcessingInterceptor { - - private boolean wasInvoked; - - public void preProcess(NativeWebRequest request, DeferredResult<?> deferredResult) { - this.wasInvoked = true; - } - - public void postProcess(NativeWebRequest request, DeferredResult<?> deferredResult, Object concurrentResult) { } - - public void afterExpiration(NativeWebRequest request, DeferredResult<?> deferredResult) { } - } - }
true
Other
spring-projects
spring-framework
3bb515bec72b1984ae422f7a9da12e412978f61c.json
Improve async support in Spring MVC Test When obtaining an async result, tests will now await concurrent processing to complete for the exact amount of time equal to the actual async timeout value. Issue: SPR-9875
spring-test-mvc/src/main/java/org/springframework/test/web/servlet/request/MockAsyncContext.java
@@ -48,7 +48,7 @@ class MockAsyncContext implements AsyncContext { private String dispatchedPath; - private long timeout = 10 * 60 * 1000L; // 10 seconds is Tomcat's default + private long timeout = 10 * 1000L; // 10 seconds is Tomcat's default public MockAsyncContext(ServletRequest request, ServletResponse response) {
true
Other
spring-projects
spring-framework
3bb515bec72b1984ae422f7a9da12e412978f61c.json
Improve async support in Spring MVC Test When obtaining an async result, tests will now await concurrent processing to complete for the exact amount of time equal to the actual async timeout value. Issue: SPR-9875
spring-test-mvc/src/main/java/org/springframework/test/web/servlet/result/RequestResultMatchers.java
@@ -30,8 +30,6 @@ import org.springframework.test.web.servlet.ResultMatcher; import org.springframework.web.context.request.async.AsyncTask; import org.springframework.web.context.request.async.DeferredResult; -import org.springframework.web.context.request.async.WebAsyncManager; -import org.springframework.web.context.request.async.WebAsyncUtils; /** * Factory for assertions on the request. An instance of this class is @@ -90,9 +88,8 @@ public <T> ResultMatcher asyncResult(final Matcher<T> matcher) { @SuppressWarnings("unchecked") public void match(MvcResult result) { HttpServletRequest request = result.getRequest(); - WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); MatcherAssert.assertThat("Async started", request.isAsyncStarted(), equalTo(true)); - MatcherAssert.assertThat("Async result", (T) asyncManager.getConcurrentResult(), matcher); + MatcherAssert.assertThat("Async result", (T) result.getAsyncResult(), matcher); } }; }
true
Other
spring-projects
spring-framework
3bb515bec72b1984ae422f7a9da12e412978f61c.json
Improve async support in Spring MVC Test When obtaining an async result, tests will now await concurrent processing to complete for the exact amount of time equal to the actual async timeout value. Issue: SPR-9875
spring-test-mvc/src/test/java/org/springframework/test/web/servlet/StubMvcResult.java
@@ -120,4 +120,8 @@ public void setResponse(MockHttpServletResponse response) { this.response = response; } + public Object getAsyncResult() { + return null; + } + }
true
Other
spring-projects
spring-framework
8270d82bda85f227780f03e6cdcac9ae721118ad.json
Fix failing test Issue: SPR-7905
spring-test-mvc/src/main/java/org/springframework/test/web/client/match/ContentRequestMatchers.java
@@ -56,14 +56,14 @@ protected ContentRequestMatchers() { /** * Assert the request content type as a String. */ - public RequestMatcher mimeType(String expectedContentType) { - return mimeType(MediaType.parseMediaType(expectedContentType)); + public RequestMatcher contentType(String expectedContentType) { + return contentType(MediaType.parseMediaType(expectedContentType)); } /** * Assert the request content type as a {@link MediaType}. */ - public RequestMatcher mimeType(final MediaType expectedContentType) { + public RequestMatcher contentType(final MediaType expectedContentType) { return new RequestMatcher() { public void match(ClientHttpRequest request) throws IOException, AssertionError { MediaType actualContentType = request.getHeaders().getContentType();
true
Other
spring-projects
spring-framework
8270d82bda85f227780f03e6cdcac9ae721118ad.json
Fix failing test Issue: SPR-7905
spring-test-mvc/src/test/java/org/springframework/test/web/client/match/ContentRequestMatchersTests.java
@@ -42,22 +42,22 @@ public void setUp() { public void testContentType() throws Exception { this.request.getHeaders().setContentType(MediaType.APPLICATION_JSON); - MockRestRequestMatchers.content().mimeType("application/json").match(this.request); - MockRestRequestMatchers.content().mimeType(MediaType.APPLICATION_JSON).match(this.request); + MockRestRequestMatchers.content().contentType("application/json").match(this.request); + MockRestRequestMatchers.content().contentType(MediaType.APPLICATION_JSON).match(this.request); } @Test(expected=AssertionError.class) public void testContentTypeNoMatch1() throws Exception { this.request.getHeaders().setContentType(MediaType.APPLICATION_JSON); - MockRestRequestMatchers.content().mimeType("application/xml").match(this.request); + MockRestRequestMatchers.content().contentType("application/xml").match(this.request); } @Test(expected=AssertionError.class) public void testContentTypeNoMatch2() throws Exception { this.request.getHeaders().setContentType(MediaType.APPLICATION_JSON); - MockRestRequestMatchers.content().mimeType(MediaType.APPLICATION_ATOM_XML).match(this.request); + MockRestRequestMatchers.content().contentType(MediaType.APPLICATION_ATOM_XML).match(this.request); } @Test
true
Other
spring-projects
spring-framework
8270d82bda85f227780f03e6cdcac9ae721118ad.json
Fix failing test Issue: SPR-7905
spring-test-mvc/src/test/java/org/springframework/test/web/client/samples/matchers/ContentRequestMatcherTests.java
@@ -62,14 +62,14 @@ public void setup() { @Test public void contentType() throws Exception { - this.mockServer.expect(content().mimeType("application/json;charset=UTF-8")).andRespond(withSuccess()); + this.mockServer.expect(content().contentType("application/json;charset=UTF-8")).andRespond(withSuccess()); this.restTemplate.put(new URI("/foo"), new Person()); this.mockServer.verify(); } @Test public void contentTypeNoMatch() throws Exception { - this.mockServer.expect(content().mimeType("application/json;charset=UTF-8")).andRespond(withSuccess()); + this.mockServer.expect(content().contentType("application/json;charset=UTF-8")).andRespond(withSuccess()); try { this.restTemplate.put(new URI("/foo"), "foo"); }
true
Other
spring-projects
spring-framework
8270d82bda85f227780f03e6cdcac9ae721118ad.json
Fix failing test Issue: SPR-7905
spring-test-mvc/src/test/java/org/springframework/test/web/client/samples/matchers/HeaderRequestMatcherTests.java
@@ -63,7 +63,7 @@ public void setup() { public void testString() throws Exception { this.mockServer.expect(requestTo("/person/1")) - .andExpect(header("Accept", "application/json")) + .andExpect(header("Accept", "application/json, application/*+json")) .andRespond(withSuccess(RESPONSE_BODY, MediaType.APPLICATION_JSON)); this.restTemplate.getForObject(new URI("/person/1"), Person.class);
true
Other
spring-projects
spring-framework
8270d82bda85f227780f03e6cdcac9ae721118ad.json
Fix failing test Issue: SPR-7905
spring-test-mvc/src/test/java/org/springframework/test/web/client/samples/matchers/JsonPathRequestMatcherTests.java
@@ -77,7 +77,7 @@ public void setup() { @Test public void testExists() throws Exception { this.mockServer.expect(requestTo("/composers")) - .andExpect(content().mimeType("application/json;charset=UTF-8")) + .andExpect(content().contentType("application/json;charset=UTF-8")) .andExpect(jsonPath("$.composers[0]").exists()) .andExpect(jsonPath("$.composers[1]").exists()) .andExpect(jsonPath("$.composers[2]").exists()) @@ -91,7 +91,7 @@ public void testExists() throws Exception { @Test public void testDoesNotExist() throws Exception { this.mockServer.expect(requestTo("/composers")) - .andExpect(content().mimeType("application/json;charset=UTF-8")) + .andExpect(content().contentType("application/json;charset=UTF-8")) .andExpect(jsonPath("$.composers[?(@.name = 'Edvard Grieeeeeeg')]").doesNotExist()) .andExpect(jsonPath("$.composers[?(@.name = 'Robert Schuuuuuuman')]").doesNotExist()) .andExpect(jsonPath("$.composers[-1]").doesNotExist()) @@ -105,7 +105,7 @@ public void testDoesNotExist() throws Exception { @Test public void testEqualTo() throws Exception { this.mockServer.expect(requestTo("/composers")) - .andExpect(content().mimeType("application/json;charset=UTF-8")) + .andExpect(content().contentType("application/json;charset=UTF-8")) .andExpect(jsonPath("$.composers[0].name").value("Johann Sebastian Bach")) .andExpect(jsonPath("$.performers[1].name").value("Yehudi Menuhin")) .andExpect(jsonPath("$.composers[0].name").value(equalTo("Johann Sebastian Bach"))) // Hamcrest @@ -119,7 +119,7 @@ public void testEqualTo() throws Exception { @Test public void testHamcrestMatcher() throws Exception { this.mockServer.expect(requestTo("/composers")) - .andExpect(content().mimeType("application/json;charset=UTF-8")) + .andExpect(content().contentType("application/json;charset=UTF-8")) .andExpect(jsonPath("$.composers[0].name", startsWith("Johann"))) .andExpect(jsonPath("$.performers[0].name", endsWith("Ashkenazy"))) .andExpect(jsonPath("$.performers[1].name", containsString("di Me"))) @@ -136,7 +136,7 @@ public void testHamcrestMatcherWithParameterizedJsonPath() throws Exception { String performerName = "$.performers[%s].name"; this.mockServer.expect(requestTo("/composers")) - .andExpect(content().mimeType("application/json;charset=UTF-8")) + .andExpect(content().contentType("application/json;charset=UTF-8")) .andExpect(jsonPath(composerName, 0).value(startsWith("Johann"))) .andExpect(jsonPath(performerName, 0).value(endsWith("Ashkenazy"))) .andExpect(jsonPath(performerName, 1).value(containsString("di Me")))
true
Other
spring-projects
spring-framework
8270d82bda85f227780f03e6cdcac9ae721118ad.json
Fix failing test Issue: SPR-7905
spring-test-mvc/src/test/java/org/springframework/test/web/client/samples/matchers/XmlContentRequestMatcherTests.java
@@ -89,7 +89,7 @@ public void setup() { @Test public void testXmlEqualTo() throws Exception { this.mockServer.expect(requestTo("/composers")) - .andExpect(content().mimeType("application/xml")) + .andExpect(content().contentType("application/xml")) .andExpect(content().xml(PEOPLE_XML)) .andRespond(withSuccess()); @@ -101,7 +101,7 @@ public void testXmlEqualTo() throws Exception { public void testHamcrestNodeMatcher() throws Exception { this.mockServer.expect(requestTo("/composers")) - .andExpect(content().mimeType("application/xml")) + .andExpect(content().contentType("application/xml")) .andExpect(content().node(hasXPath("/people/composers/composer[1]"))) .andRespond(withSuccess());
true
Other
spring-projects
spring-framework
8270d82bda85f227780f03e6cdcac9ae721118ad.json
Fix failing test Issue: SPR-7905
spring-test-mvc/src/test/java/org/springframework/test/web/client/samples/matchers/XpathRequestMatcherTests.java
@@ -97,7 +97,7 @@ public void testExists() throws Exception { String performer = "/ns:people/performers/performer[%s]"; this.mockServer.expect(requestTo("/composers")) - .andExpect(content().mimeType("application/xml")) + .andExpect(content().contentType("application/xml")) .andExpect(xpath(composer, NS, 1).exists()) .andExpect(xpath(composer, NS, 2).exists()) .andExpect(xpath(composer, NS, 3).exists()) @@ -117,7 +117,7 @@ public void testDoesNotExist() throws Exception { String performer = "/ns:people/performers/performer[%s]"; this.mockServer.expect(requestTo("/composers")) - .andExpect(content().mimeType("application/xml")) + .andExpect(content().contentType("application/xml")) .andExpect(xpath(composer, NS, 0).doesNotExist()) .andExpect(xpath(composer, NS, 5).doesNotExist()) .andExpect(xpath(performer, NS, 0).doesNotExist()) @@ -135,7 +135,7 @@ public void testString() throws Exception { String performerName = "/ns:people/performers/performer[%s]/name"; this.mockServer.expect(requestTo("/composers")) - .andExpect(content().mimeType("application/xml")) + .andExpect(content().contentType("application/xml")) .andExpect(xpath(composerName, NS, 1).string("Johann Sebastian Bach")) .andExpect(xpath(composerName, NS, 2).string("Johannes Brahms")) .andExpect(xpath(composerName, NS, 3).string("Edvard Grieg")) @@ -157,7 +157,7 @@ public void testNumber() throws Exception { String composerDouble = "/ns:people/composers/composer[%s]/someDouble"; this.mockServer.expect(requestTo("/composers")) - .andExpect(content().mimeType("application/xml")) + .andExpect(content().contentType("application/xml")) .andExpect(xpath(composerDouble, NS, 1).number(21d)) .andExpect(xpath(composerDouble, NS, 2).number(.0025)) .andExpect(xpath(composerDouble, NS, 3).number(1.6035)) @@ -176,7 +176,7 @@ public void testBoolean() throws Exception { String performerBooleanValue = "/ns:people/performers/performer[%s]/someBoolean"; this.mockServer.expect(requestTo("/composers")) - .andExpect(content().mimeType("application/xml")) + .andExpect(content().contentType("application/xml")) .andExpect(xpath(performerBooleanValue, NS, 1).booleanValue(false)) .andExpect(xpath(performerBooleanValue, NS, 2).booleanValue(true)) .andRespond(withSuccess()); @@ -189,7 +189,7 @@ public void testBoolean() throws Exception { public void testNodeCount() throws Exception { this.mockServer.expect(requestTo("/composers")) - .andExpect(content().mimeType("application/xml")) + .andExpect(content().contentType("application/xml")) .andExpect(xpath("/ns:people/composers/composer", NS).nodeCount(4)) .andExpect(xpath("/ns:people/performers/performer", NS).nodeCount(2)) .andExpect(xpath("/ns:people/composers/composer", NS).nodeCount(lessThan(5))) // Hamcrest..
true
Other
chartjs
Chart.js
41f2b5707a225bac47f786dea60b51cc1e4bb1f6.json
Add codeclimate config
.codeclimate.yml
@@ -0,0 +1,4 @@ +## Exclude dist files and samples from codeclimate +exclude_paths: + - dist/**/* + - samples/**/* \ No newline at end of file
false
Other
chartjs
Chart.js
58fcb37760ad1d0421f15b1081fd55bdbeccd314.json
fix typo in readme
README.md
@@ -1,6 +1,6 @@ # Chart.js -[![Build Status](https://travis-ci.org/nnnick/Chart.js.svg?branch=v2.0-dev)](https://travis-ci.org/nnnick/Chart.js) [![Code Climate](https://codeclimate.com/github/nnnick/Chart.js/badges/gpa.svg)](https://codeclimate.com/github/nnnick/Chart.js)[![Coverage Status](https://coveralls.io/repos/nnnick/Chart.js/badge.svg?branch=v2.0-dev)](https://coveralls.io/r/nnncik/Chart.js?branch=v2.0-dev) +[![Build Status](https://travis-ci.org/nnnick/Chart.js.svg?branch=v2.0-dev)](https://travis-ci.org/nnnick/Chart.js) [![Code Climate](https://codeclimate.com/github/nnnick/Chart.js/badges/gpa.svg)](https://codeclimate.com/github/nnnick/Chart.js)[![Coverage Status](https://coveralls.io/repos/nnnick/Chart.js/badge.svg?branch=v2.0-dev)](https://coveralls.io/r/nnnick/Chart.js?branch=v2.0-dev)
false
Other
chartjs
Chart.js
489f7ce6f7fb95225489fe9ec5f6257b65120771.json
use a new node version
.travis.yml
@@ -1,7 +1,7 @@ language: node_js node_js: - - "0.11" - - "0.10" + - "5.6" + - "4.3" before_install: - "export CHROME_BIN=chromium-browser" @@ -13,6 +13,8 @@ before_script: script: - gulp test + - gulp coverage + - cat ./coverage/lcov.info | ./node_modules/.bin/coveralls notifications: slack: chartjs:pcfCZR6ugg5TEcaLtmIfQYuA
false
Other
chartjs
Chart.js
a84f9d917721f4f06965c88186a37e8200aecce7.json
Update other test tasks to use karma-browserify
gulpfile.js
@@ -133,7 +133,7 @@ function validHTMLTask() { function unittestTask() { - var files = ['./dist/Chart.bundle.js'] + var files = ['./src/**/*.js']; Array.prototype.unshift.apply(files, preTestFiles); Array.prototype.push.apply(files, testFiles); @@ -145,7 +145,7 @@ function unittestTask() { } function unittestWatchTask() { - var files = ['./dist/Chart.bundle.js'] + var files = ['./src/**/*.js']; Array.prototype.unshift.apply(files, preTestFiles); Array.prototype.push.apply(files, testFiles); @@ -157,7 +157,6 @@ function unittestWatchTask() { } function coverageTask() { - //var files = ['./dist/Chart.bundle.js'] var files = ['./src/**/*.js']; Array.prototype.unshift.apply(files, preTestFiles); Array.prototype.push.apply(files, testFiles);
true
Other
chartjs
Chart.js
a84f9d917721f4f06965c88186a37e8200aecce7.json
Update other test tasks to use karma-browserify
karma.conf.ci.js
@@ -7,8 +7,14 @@ module.exports = function(config) { flags: ['--no-sandbox'] } }, - frameworks: ['jasmine'], + frameworks: ['browserify', 'jasmine'], reporters: ['progress', 'html'], + preprocessors: { + 'src/**/*.js': ['browserify'] + }, + browserify: { + debug: true + } }; if (process.env.TRAVIS) {
true
Other
chartjs
Chart.js
a84f9d917721f4f06965c88186a37e8200aecce7.json
Update other test tasks to use karma-browserify
karma.conf.js
@@ -1,7 +1,14 @@ module.exports = function(config) { config.set({ browsers: ['Chrome', 'Firefox'], - frameworks: ['jasmine'], + frameworks: ['browserify', 'jasmine'], reporters: ['progress', 'html'], + + preprocessors: { + 'src/**/*.js': ['browserify'] + }, + browserify: { + debug: true + } }); }; \ No newline at end of file
true
Other
chartjs
Chart.js
9cf31da4c92fc6200c4983127700f08f29a8c161.json
Add docs for global font options
docs/00-Getting-Started.md
@@ -103,6 +103,10 @@ hover |-|-|- *hover*.animationDuration | Number | 400 | Duration in milliseconds it takes to animate hover style changes onClick | Function | null | Called if the event is of type 'mouseup' or 'click'. Called in the context of the chart and passed an array of active elements defaultColor | Color | 'rgba(0,0,0,0.1)' | +defaultFontColor | Color | '#666' | Default font color for all text +defaultFontFamily | String | "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif" | Default font family for all text +defaultFontSize | Number | 12 | Default font size (in px) for text. Does not apply to radialLinear scale point labels +defaultFontStyle | String | 'normal' | Default font style. Does not apply to tooltip title or footer. Does not apply to chart title legendCallback | Function | ` function (chart) { // the chart object to generate a legend from. }` | Function to generate a legend. Default implementation returns an HTML string. The global options for the chart title is defined in `Chart.defaults.global.title`
false
Other
chartjs
Chart.js
0c534e1eb8140e09f8d55bba7431fd4116dc9dd6.json
Fix layout service
src/core/core.layoutService.js
@@ -179,7 +179,9 @@ bottom: 0, }; - box.update(box.options.fullWidth ? chartWidth : maxChartAreaWidth, minBoxSize.minSize.height, scaleMargin); + // Don't use min size here because of label rotation. When the labels are rotated, their rotation highly depends + // on the margin. Sometimes they need to increase in size slightly + box.update(box.options.fullWidth ? chartWidth : maxChartAreaWidth, chartHeight / 2, scaleMargin); } else { box.update(minBoxSize.minSize.width, maxChartAreaHeight); }
false
Other
chartjs
Chart.js
f2899934db78ad0edcc8d61b8bd9377e078a358c.json
Draw line at edge of scales & update tests
src/core/core.scale.js
@@ -603,7 +603,6 @@ } } - this.ctx.translate(xLabelValue, yLabelValue); this.ctx.rotate(helpers.toRadians(this.labelRotation) * -1); this.ctx.font = labelFont; @@ -630,6 +629,21 @@ this.ctx.restore(); } } + + // Draw the line at the edge of the axis + this.ctx.lineWidth = this.options.gridLines.lineWidth; + this.ctx.strokeStyle = this.options.gridLines.color; + var x1 = this.left, x2 = this.right, y1 = this.top, y2 = this.bottom; + + if (this.isHorizontal()) { + y1 = y2 = this.options.position === 'top' ? this.bottom : this.top; + } else { + x1 = x2 = this.options.position === 'left' ? this.right : this.left; + } + + this.ctx.moveTo(x1, y1); + this.ctx.lineTo(x2, y2); + this.ctx.stroke(); } } });
true
Other
chartjs
Chart.js
f2899934db78ad0edcc8d61b8bd9377e078a358c.json
Draw line at edge of scales & update tests
test/scale.linear.tests.js
@@ -978,6 +978,21 @@ describe('Linear Scale', function() { }, { "name": "restore", "args": [] + }, { + "name": "setLineWidth", + "args": [1] + }, { + "name": "setStrokeStyle", + "args": ["rgba(0, 0, 0, 0.1)"] + }, { + "name": "moveTo", + "args": [0, 100] + }, { + "name": "lineTo", + "args": [200, 100] + }, { + "name": "stroke", + "args": [] }]; expect(mockContext.getCalls()).toEqual(expected); @@ -1036,6 +1051,21 @@ describe('Linear Scale', function() { }, { "name": "fillText", "args": ["myLabel", 100, 122] + }, { + "name": "setLineWidth", + "args": [1] + }, { + "name": "setStrokeStyle", + "args": ["rgba(0, 0, 0, 0.1)"] + }, { + "name": "moveTo", + "args": [0, 100] + }, { + "name": "lineTo", + "args": [200, 100] + }, { + "name": "stroke", + "args": [] }]); // Turn off display @@ -1480,6 +1510,21 @@ describe('Linear Scale', function() { }, { "name": "restore", "args": [] + }, { + "name": "setLineWidth", + "args": [1] + }, { + "name": "setStrokeStyle", + "args": ["rgba(0, 0, 0, 0.1)"] + }, { + "name": "moveTo", + "args": [30, 0] + }, { + "name": "lineTo", + "args": [30, 300] + }, { + "name": "stroke", + "args": [] }]); // Turn off some drawing @@ -1596,6 +1641,21 @@ describe('Linear Scale', function() { }, { "name": "restore", "args": [] + }, { + "name": "setLineWidth", + "args": [1] + }, { + "name": "setStrokeStyle", + "args": ["rgba(0, 0, 0, 0.1)"] + }, { + "name": "moveTo", + "args": [30, 0] + }, { + "name": "lineTo", + "args": [30, 300] + }, { + "name": "stroke", + "args": [] }]); }); @@ -1838,6 +1898,21 @@ describe('Linear Scale', function() { }, { "name": "restore", "args": [] + }, { + "name": "setLineWidth", + "args": [1] + }, { + "name": "setStrokeStyle", + "args": ["rgba(0, 0, 0, 0.1)"] + }, { + "name": "moveTo", + "args": [30, 0] + }, { + "name": "lineTo", + "args": [30, 300] + }, { + "name": "stroke", + "args": [] }]) }); }); \ No newline at end of file
true
Other
chartjs
Chart.js
77185993df7c7e1171c8b3bac9b551ea616d54a8.json
fix spaces -> tabs
src/Chart.Doughnut.js
@@ -93,8 +93,8 @@ addData : function(segment, atIndex, silent){ var index = atIndex !== undefined ? atIndex : this.segments.length; if ( typeof(segment.color) === "undefined" ) { - segment.color = Chart.defaults.global.segmentColorDefault[index]; - segment.highlight = Chart.defaults.global.segmentHighlightColorDefaults[index]; + segment.color = Chart.defaults.global.segmentColorDefault[index]; + segment.highlight = Chart.defaults.global.segmentHighlightColorDefaults[index]; } this.segments.splice(index, 0, new this.SegmentArc({ value : segment.value,
false
Other
chartjs
Chart.js
fd2344dd5f9de7b4aebff48fb21af3670705551f.json
Update the docs to reflect the new feature
docs/05-Pie-Doughnut-Chart.md
@@ -137,6 +137,8 @@ myDoughnutChart.update(); Calling `addData(segmentData, index)` on your Chart instance passing an object in the same format as in the constructor. There is an optional second argument of 'index', this determines at what index the new segment should be inserted into the chart. +If you don't specify a color and highliht, one will be chosen from the global default array: segmentColorDefault and the corresponding segmentHighlightColorDefault. The index of the addded data is used to lookup a corresponding color from the defaults. + ```javascript // An object in the same format as the original data source myDoughnutChart.addData({
false
Other
chartjs
Chart.js
bbc6f5aa5fdcfd1be9def2787ecddc3003babcba.json
Fix broken test
test/element.rectangle.tests.js
@@ -109,7 +109,7 @@ describe('Rectangle element tests', function() { expect(rectangle.tooltipPosition()).toEqual({ x: 10, - y: 0, + y: 15, }); // Test when the y is below the base (negative bar)
false
Other
chartjs
Chart.js
8e7162ca91a704b637852e3a813519a7fcfdbf46.json
Add missing comma
docs/02-Line-Chart.md
@@ -81,7 +81,7 @@ var data = { pointHoverBorderWidth: 2, // Tension - bezier curve tension of the line. Set to 0 to draw straight Wlines connecting points - tension: 0.1 + tension: 0.1, // The actual data data: [65, 59, 80, 81, 56, 55, 40], @@ -151,4 +151,4 @@ new Chart(ctx, { // and the Line chart defaults, but this particular instance will have the x axis not displaying. ``` -We can also change these defaults values for each Line type that is created, this object is available at `Chart.defaults.line`. \ No newline at end of file +We can also change these defaults values for each Line type that is created, this object is available at `Chart.defaults.line`.
false
Other
chartjs
Chart.js
3d6b47b0d5de5e341ec69f978864609f11d7ef63.json
Fix legend generation when no datasets
src/controllers/controller.doughnut.js
@@ -35,16 +35,20 @@ module.exports = function(Chart) { legend: { labels: { generateLabels: function(data) { - return data.labels.map(function(label, i) { - return { - text: label, - fillStyle: data.datasets[0].backgroundColor[i], - hidden: isNaN(data.datasets[0].data[i]), - - // Extra data used for toggling the correct item - index: i - }; - }); + if (data.labels.length && data.datasets.length) { + return data.labels.map(function(label, i) { + return { + text: label, + fillStyle: data.datasets[0].backgroundColor[i], + hidden: isNaN(data.datasets[0].data[i]), + + // Extra data used for toggling the correct item + index: i + }; + }); + } else { + return []; + } } }, onClick: function(e, legendItem) {
true
Other
chartjs
Chart.js
3d6b47b0d5de5e341ec69f978864609f11d7ef63.json
Fix legend generation when no datasets
src/controllers/controller.polarArea.js
@@ -36,16 +36,20 @@ module.exports = function(Chart) { legend: { labels: { generateLabels: function(data) { - return data.labels.map(function(label, i) { - return { - text: label, - fillStyle: data.datasets[0].backgroundColor[i], - hidden: isNaN(data.datasets[0].data[i]), - - // Extra data used for toggling the correct item - index: i - }; - }); + if (data.labels.length && data.datasets.length) { + return data.labels.map(function(label, i) { + return { + text: label, + fillStyle: data.datasets[0].backgroundColor[i], + hidden: isNaN(data.datasets[0].data[i]), + + // Extra data used for toggling the correct item + index: i + }; + }); + } else { + return []; + } } }, onClick: function(e, legendItem) {
true
Other
chartjs
Chart.js
8d5b3809f6a607ebf2be7af40fb538ea5e42c4db.json
Fix global font settings
src/core/core.legend.js
@@ -22,10 +22,6 @@ module.exports = function(Chart) { labels: { boxWidth: 40, - fontSize: Chart.defaults.global.defaultFontSize, - fontStyle: Chart.defaults.global.defaultFontStyle, - fontColor: Chart.defaults.global.defaultFontColor, - fontFamily: Chart.defaults.global.defaultFontFamily, padding: 10, // Generates labels shown in the legend // Valid properties to return: @@ -156,7 +152,10 @@ module.exports = function(Chart) { fit: function() { var ctx = this.ctx; - var labelFont = helpers.fontString(this.options.labels.fontSize, this.options.labels.fontStyle, this.options.labels.fontFamily); + var fontSize = helpers.getValueOrDefault(this.options.labels.fontSize, Chart.defaults.global.defaultFontSize); + var fontStyle = helpers.getValueOrDefault(this.options.labels.fontStyle, Chart.defaults.global.defaultFontStyle); + var fontFamily = helpers.getValueOrDefault(this.options.labels.fontFamily, Chart.defaults.global.defaultFontFamily); + var labelFont = helpers.fontString(fontSize, fontStyle, fontFamily); // Reset hit boxes this.legendHitBoxes = []; @@ -182,16 +181,16 @@ module.exports = function(Chart) { // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one this.lineWidths = [0]; - var totalHeight = this.legendItems.length ? this.options.labels.fontSize + (this.options.labels.padding) : 0; + var totalHeight = this.legendItems.length ? fontSize + (this.options.labels.padding) : 0; ctx.textAlign = "left"; ctx.textBaseline = 'top'; ctx.font = labelFont; helpers.each(this.legendItems, function(legendItem, i) { - var width = this.options.labels.boxWidth + (this.options.labels.fontSize / 2) + ctx.measureText(legendItem.text).width; + var width = this.options.labels.boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width; if (this.lineWidths[this.lineWidths.length - 1] + width + this.options.labels.padding >= this.width) { - totalHeight += this.options.labels.fontSize + (this.options.labels.padding); + totalHeight += fontSize + (this.options.labels.padding); this.lineWidths[this.lineWidths.length] = this.left; } @@ -200,7 +199,7 @@ module.exports = function(Chart) { left: 0, top: 0, width: width, - height: this.options.labels.fontSize + height: fontSize }; this.lineWidths[this.lineWidths.length - 1] += width + this.options.labels.padding; @@ -234,24 +233,28 @@ module.exports = function(Chart) { line: 0 }; - var labelFont = helpers.fontString(this.options.labels.fontSize, this.options.labels.fontStyle, this.options.labels.fontFamily); + var fontColor = helpers.getValueOrDefault(this.options.labels.fontColor, Chart.defaults.global.defaultFontColor); + var fontSize = helpers.getValueOrDefault(this.options.labels.fontSize, Chart.defaults.global.defaultFontSize); + var fontStyle = helpers.getValueOrDefault(this.options.labels.fontStyle, Chart.defaults.global.defaultFontStyle); + var fontFamily = helpers.getValueOrDefault(this.options.labels.fontFamily, Chart.defaults.global.defaultFontFamily); + var labelFont = helpers.fontString(fontSize, fontStyle, fontFamily); // Horizontal if (this.isHorizontal()) { // Labels ctx.textAlign = "left"; ctx.textBaseline = 'top'; ctx.lineWidth = 0.5; - ctx.strokeStyle = this.options.labels.fontColor; // for strikethrough effect - ctx.fillStyle = this.options.labels.fontColor; // render in correct colour + ctx.strokeStyle = fontColor; // for strikethrough effect + ctx.fillStyle = fontColor; // render in correct colour ctx.font = labelFont; helpers.each(this.legendItems, function(legendItem, i) { var textWidth = ctx.measureText(legendItem.text).width; - var width = this.options.labels.boxWidth + (this.options.labels.fontSize / 2) + textWidth; + var width = this.options.labels.boxWidth + (fontSize / 2) + textWidth; if (cursor.x + width >= this.width) { - cursor.y += this.options.labels.fontSize + (this.options.labels.padding); + cursor.y += fontSize + (this.options.labels.padding); cursor.line++; cursor.x = this.left + ((this.width - this.lineWidths[cursor.line]) / 2); } @@ -276,23 +279,23 @@ module.exports = function(Chart) { } // Draw the box - ctx.strokeRect(cursor.x, cursor.y, this.options.labels.boxWidth, this.options.labels.fontSize); - ctx.fillRect(cursor.x, cursor.y, this.options.labels.boxWidth, this.options.labels.fontSize); + ctx.strokeRect(cursor.x, cursor.y, this.options.labels.boxWidth, fontSize); + ctx.fillRect(cursor.x, cursor.y, this.options.labels.boxWidth, fontSize); ctx.restore(); this.legendHitBoxes[i].left = cursor.x; this.legendHitBoxes[i].top = cursor.y; // Fill the actual label - ctx.fillText(legendItem.text, this.options.labels.boxWidth + (this.options.labels.fontSize / 2) + cursor.x, cursor.y); + ctx.fillText(legendItem.text, this.options.labels.boxWidth + (fontSize / 2) + cursor.x, cursor.y); if (legendItem.hidden) { // Strikethrough the text if hidden ctx.beginPath(); ctx.lineWidth = 2; - ctx.moveTo(this.options.labels.boxWidth + (this.options.labels.fontSize / 2) + cursor.x, cursor.y + (this.options.labels.fontSize / 2)); - ctx.lineTo(this.options.labels.boxWidth + (this.options.labels.fontSize / 2) + cursor.x + textWidth, cursor.y + (this.options.labels.fontSize / 2)); + ctx.moveTo(this.options.labels.boxWidth + (fontSize / 2) + cursor.x, cursor.y + (fontSize / 2)); + ctx.lineTo(this.options.labels.boxWidth + (fontSize / 2) + cursor.x + textWidth, cursor.y + (fontSize / 2)); ctx.stroke(); }
true
Other
chartjs
Chart.js
8d5b3809f6a607ebf2be7af40fb538ea5e42c4db.json
Fix global font settings
src/core/core.scale.js
@@ -21,11 +21,6 @@ module.exports = function(Chart) { // scale label scaleLabel: { - fontColor: Chart.defaults.global.defaultFontColor, - fontFamily: Chart.defaults.global.defaultFontFamily, - fontSize: Chart.defaults.global.defaultFontSize, - fontStyle: Chart.defaults.global.defaultFontStyle, - // actual label labelString: '', @@ -36,10 +31,6 @@ module.exports = function(Chart) { // label settings ticks: { beginAtZero: false, - fontSize: Chart.defaults.global.defaultFontSize, - fontStyle: Chart.defaults.global.defaultFontStyle, - fontColor: Chart.defaults.global.defaultFontColor, - fontFamily: Chart.defaults.global.defaultFontFamily, maxRotation: 90, mirror: false, padding: 10, @@ -187,8 +178,11 @@ module.exports = function(Chart) { calculateTickRotation: function() { //Get the width of each grid by calculating the difference //between x offsets between 0 and 1. - var labelFont = helpers.fontString(this.options.ticks.fontSize, this.options.ticks.fontStyle, this.options.ticks.fontFamily); - this.ctx.font = labelFont; + var tickFontSize = helpers.getValueOrDefault(this.options.ticks.fontSize, Chart.defaults.global.defaultFontSize); + var tickFontStyle = helpers.getValueOrDefault(this.options.ticks.fontStyle, Chart.defaults.global.defaultFontStyle); + var tickFontFamily = helpers.getValueOrDefault(this.options.ticks.fontFamily, Chart.defaults.global.defaultFontFamily); + var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily); + this.ctx.font = tickLabelFont; var firstWidth = this.ctx.measureText(this.ticks[0]).width; var lastWidth = this.ctx.measureText(this.ticks[this.ticks.length - 1]).width; @@ -206,7 +200,7 @@ module.exports = function(Chart) { if (!this.longestTextCache) { this.longestTextCache = {}; } - var originalLabelWidth = helpers.longestText(this.ctx, labelFont, this.ticks, this.longestTextCache); + var originalLabelWidth = helpers.longestText(this.ctx, tickLabelFont, this.ticks, this.longestTextCache); var labelWidth = originalLabelWidth; var cosRotation; var sinRotation; @@ -223,11 +217,11 @@ module.exports = function(Chart) { firstRotated = cosRotation * firstWidth; // We're right aligning the text now. - if (firstRotated + this.options.ticks.fontSize / 2 > this.yLabelWidth) { - this.paddingLeft = firstRotated + this.options.ticks.fontSize / 2; + if (firstRotated + tickFontSize / 2 > this.yLabelWidth) { + this.paddingLeft = firstRotated + tickFontSize / 2; } - this.paddingRight = this.options.ticks.fontSize / 2; + this.paddingRight = tickFontSize / 2; if (sinRotation * originalLabelWidth > this.maxHeight) { // go back one step @@ -262,6 +256,16 @@ module.exports = function(Chart) { height: 0 }; + var tickFontSize = helpers.getValueOrDefault(this.options.ticks.fontSize, Chart.defaults.global.defaultFontSize); + var tickFontStyle = helpers.getValueOrDefault(this.options.ticks.fontStyle, Chart.defaults.global.defaultFontStyle); + var tickFontFamily = helpers.getValueOrDefault(this.options.ticks.fontFamily, Chart.defaults.global.defaultFontFamily); + var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily); + + var scaleLabelFontSize = helpers.getValueOrDefault(this.options.scaleLabel.fontSize, Chart.defaults.global.defaultFontSize); + var scaleLabelFontStyle = helpers.getValueOrDefault(this.options.scaleLabel.fontStyle, Chart.defaults.global.defaultFontStyle); + var scaleLabelFontFamily = helpers.getValueOrDefault(this.options.scaleLabel.fontFamily, Chart.defaults.global.defaultFontFamily); + var scaleLabelFont = helpers.fontString(scaleLabelFontSize, scaleLabelFontStyle, scaleLabelFontFamily); + // Width if (this.isHorizontal()) { // subtract the margins to line up with the chartArea if we are a full width scale @@ -280,34 +284,29 @@ module.exports = function(Chart) { // Are we showing a title for the scale? if (this.options.scaleLabel.display) { if (this.isHorizontal()) { - this.minSize.height += (this.options.scaleLabel.fontSize * 1.5); + this.minSize.height += (scaleLabelFontSize * 1.5); } else { - this.minSize.width += (this.options.scaleLabel.fontSize * 1.5); + this.minSize.width += (scaleLabelFontSize * 1.5); } } if (this.options.ticks.display && this.options.display) { // Don't bother fitting the ticks if we are not showing them - var labelFont = helpers.fontString(this.options.ticks.fontSize, - this.options.ticks.fontStyle, this.options.ticks.fontFamily); - if (!this.longestTextCache) { this.longestTextCache = {}; } - var largestTextWidth = helpers.longestText(this.ctx, labelFont, this.ticks, this.longestTextCache); + var largestTextWidth = helpers.longestText(this.ctx, tickLabelFont, this.ticks, this.longestTextCache); if (this.isHorizontal()) { // A horizontal axis is more constrained by the height. this.longestLabelWidth = largestTextWidth; // TODO - improve this calculation - var labelHeight = (Math.sin(helpers.toRadians(this.labelRotation)) * this.longestLabelWidth) + 1.5 * this.options.ticks.fontSize; + var labelHeight = (Math.sin(helpers.toRadians(this.labelRotation)) * this.longestLabelWidth) + 1.5 * tickFontSize; this.minSize.height = Math.min(this.maxHeight, this.minSize.height + labelHeight); - - labelFont = helpers.fontString(this.options.ticks.fontSize, this.options.ticks.fontStyle, this.options.ticks.fontFamily); - this.ctx.font = labelFont; + this.ctx.font = tickLabelFont; var firstLabelWidth = this.ctx.measureText(this.ticks[0]).width; var lastLabelWidth = this.ctx.measureText(this.ticks[this.ticks.length - 1]).width; @@ -317,7 +316,7 @@ module.exports = function(Chart) { var cosRotation = Math.cos(helpers.toRadians(this.labelRotation)); var sinRotation = Math.sin(helpers.toRadians(this.labelRotation)); this.paddingLeft = this.labelRotation !== 0 ? (cosRotation * firstLabelWidth) + 3 : firstLabelWidth / 2 + 3; // add 3 px to move away from canvas edges - this.paddingRight = this.labelRotation !== 0 ? (sinRotation * (this.options.ticks.fontSize / 2)) + 3 : lastLabelWidth / 2 + 3; // when rotated + this.paddingRight = this.labelRotation !== 0 ? (sinRotation * (tickFontSize / 2)) + 3 : lastLabelWidth / 2 + 3; // when rotated } else { // A vertical axis is more constrained by the width. Labels are the dominant factor here, so get that length first var maxLabelWidth = this.maxWidth - this.minSize.width; @@ -335,8 +334,8 @@ module.exports = function(Chart) { this.minSize.width = this.maxWidth; } - this.paddingTop = this.options.ticks.fontSize / 2; - this.paddingBottom = this.options.ticks.fontSize / 2; + this.paddingTop = tickFontSize / 2; + this.paddingBottom = tickFontSize / 2; } } @@ -447,14 +446,25 @@ module.exports = function(Chart) { maxTicks = this.options.ticks.maxTicksLimit; } - // Make sure we draw text in the correct color and font - this.ctx.fillStyle = this.options.ticks.fontColor; - var labelFont = helpers.fontString(this.options.ticks.fontSize, this.options.ticks.fontStyle, this.options.ticks.fontFamily); + var tickFontColor = helpers.getValueOrDefault(this.options.ticks.fontColor, Chart.defaults.global.defaultFontColor); + var tickFontSize = helpers.getValueOrDefault(this.options.ticks.fontSize, Chart.defaults.global.defaultFontSize); + var tickFontStyle = helpers.getValueOrDefault(this.options.ticks.fontStyle, Chart.defaults.global.defaultFontStyle); + var tickFontFamily = helpers.getValueOrDefault(this.options.ticks.fontFamily, Chart.defaults.global.defaultFontFamily); + var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily); + + var scaleLabelFontColor = helpers.getValueOrDefault(this.options.scaleLabel.fontColor, Chart.defaults.global.defaultFontColor); + var scaleLabelFontSize = helpers.getValueOrDefault(this.options.scaleLabel.fontSize, Chart.defaults.global.defaultFontSize); + var scaleLabelFontStyle = helpers.getValueOrDefault(this.options.scaleLabel.fontStyle, Chart.defaults.global.defaultFontStyle); + var scaleLabelFontFamily = helpers.getValueOrDefault(this.options.scaleLabel.fontFamily, Chart.defaults.global.defaultFontFamily); + var scaleLabelFont = helpers.fontString(scaleLabelFontSize, scaleLabelFontStyle, scaleLabelFontFamily); var cosRotation = Math.cos(helpers.toRadians(this.labelRotation)); var sinRotation = Math.sin(helpers.toRadians(this.labelRotation)); var longestRotatedLabel = this.longestLabelWidth * cosRotation; - var rotatedLabelHeight = this.options.ticks.fontSize * sinRotation; + var rotatedLabelHeight = tickFontSize * sinRotation; + + // Make sure we draw text in the correct color and font + this.ctx.fillStyle = tickFontColor; if (this.isHorizontal()) { setContextLineSettings = true; @@ -529,7 +539,7 @@ module.exports = function(Chart) { this.ctx.save(); this.ctx.translate(xLabelValue, (isRotated) ? this.top + 12 : this.options.position === "top" ? this.bottom - 10 : this.top + 10); this.ctx.rotate(helpers.toRadians(this.labelRotation) * -1); - this.ctx.font = labelFont; + this.ctx.font = tickLabelFont; this.ctx.textAlign = (isRotated) ? "right" : "center"; this.ctx.textBaseline = (isRotated) ? "middle" : this.options.position === "top" ? "bottom" : "top"; this.ctx.fillText(label, 0, 0); @@ -541,11 +551,11 @@ module.exports = function(Chart) { // Draw the scale label this.ctx.textAlign = "center"; this.ctx.textBaseline = 'middle'; - this.ctx.fillStyle = this.options.scaleLabel.fontColor; // render in correct colour - this.ctx.font = helpers.fontString(this.options.scaleLabel.fontSize, this.options.scaleLabel.fontStyle, this.options.scaleLabel.fontFamily); + this.ctx.fillStyle = scaleLabelFontColor; // render in correct colour + this.ctx.font = scaleLabelFont; scaleLabelX = this.left + ((this.right - this.left) / 2); // midpoint of the width - scaleLabelY = this.options.position === 'bottom' ? this.bottom - (this.options.scaleLabel.fontSize / 2) : this.top + (this.options.scaleLabel.fontSize / 2); + scaleLabelY = this.options.position === 'bottom' ? this.bottom - (scaleLabelFontSize / 2) : this.top + (scaleLabelFontSize / 2); this.ctx.fillText(this.options.scaleLabel.labelString, scaleLabelX, scaleLabelY); } @@ -622,7 +632,7 @@ module.exports = function(Chart) { this.ctx.translate(xLabelValue, yLabelValue); this.ctx.rotate(helpers.toRadians(this.labelRotation) * -1); - this.ctx.font = labelFont; + this.ctx.font = tickLabelFont; this.ctx.textBaseline = "middle"; this.ctx.fillText(label, 0, 0); this.ctx.restore(); @@ -631,16 +641,16 @@ module.exports = function(Chart) { if (this.options.scaleLabel.display) { // Draw the scale label - scaleLabelX = this.options.position === 'left' ? this.left + (this.options.scaleLabel.fontSize / 2) : this.right - (this.options.scaleLabel.fontSize / 2); + scaleLabelX = this.options.position === 'left' ? this.left + (scaleLabelFontSize / 2) : this.right - (scaleLabelFontSize / 2); scaleLabelY = this.top + ((this.bottom - this.top) / 2); var rotation = this.options.position === 'left' ? -0.5 * Math.PI : 0.5 * Math.PI; this.ctx.save(); this.ctx.translate(scaleLabelX, scaleLabelY); this.ctx.rotate(rotation); this.ctx.textAlign = "center"; - this.ctx.fillStyle = this.options.scaleLabel.fontColor; // render in correct colour - this.ctx.font = helpers.fontString(this.options.scaleLabel.fontSize, this.options.scaleLabel.fontStyle, this.options.scaleLabel.fontFamily); + this.ctx.fillStyle =scaleLabelFontColor; // render in correct colour + this.ctx.font = scaleLabelFont; this.ctx.textBaseline = 'middle'; this.ctx.fillText(this.options.scaleLabel.labelString, 0, 0); this.ctx.restore();
true
Other
chartjs
Chart.js
8d5b3809f6a607ebf2be7af40fb538ea5e42c4db.json
Fix global font settings
src/core/core.title.js
@@ -9,9 +9,6 @@ module.exports = function(Chart) { position: 'top', fullWidth: true, // marks that this box should take the full width of the canvas (pushing down other boxes) - fontColor: Chart.defaults.global.defaultFontColor, - fontFamily: Chart.defaults.global.defaultFontFamily, - fontSize: Chart.defaults.global.defaultFontSize, fontStyle: 'bold', padding: 10, @@ -107,7 +104,10 @@ module.exports = function(Chart) { fit: function() { var ctx = this.ctx; - var titleFont = helpers.fontString(this.options.fontSize, this.options.fontStyle, this.options.fontFamily); + var fontSize = helpers.getValueOrDefault(this.options.fontSize, Chart.defaults.global.defaultFontSize); + var fontStyle = helpers.getValueOrDefault(this.options.fontStyle, Chart.defaults.global.defaultFontStyle); + var fontFamily = helpers.getValueOrDefault(this.options.fontFamily, Chart.defaults.global.defaultFontFamily); + var titleFont = helpers.fontString(fontSize, fontStyle, fontFamily); // Width if (this.isHorizontal()) { @@ -128,11 +128,11 @@ module.exports = function(Chart) { // Title if (this.options.display) { - this.minSize.height += this.options.fontSize + (this.options.padding * 2); + this.minSize.height += fontSize + (this.options.padding * 2); } } else { if (this.options.display) { - this.minSize.width += this.options.fontSize + (this.options.padding * 2); + this.minSize.width += fontSize + (this.options.padding * 2); } } @@ -153,41 +153,39 @@ module.exports = function(Chart) { var ctx = this.ctx; var titleX, titleY; + var fontColor = helpers.getValueOrDefault(this.options.fontColor, Chart.defaults.global.defaultFontColor); + var fontSize = helpers.getValueOrDefault(this.options.fontSize, Chart.defaults.global.defaultFontSize); + var fontStyle = helpers.getValueOrDefault(this.options.fontStyle, Chart.defaults.global.defaultFontStyle); + var fontFamily = helpers.getValueOrDefault(this.options.fontFamily, Chart.defaults.global.defaultFontFamily); + var titleFont = helpers.fontString(fontSize, fontStyle, fontFamily); + + ctx.fillStyle = fontColor; // render in correct colour + ctx.font = titleFont; + // Horizontal if (this.isHorizontal()) { // Title - if (this.options.display) { + ctx.textAlign = "center"; + ctx.textBaseline = 'middle'; - ctx.textAlign = "center"; - ctx.textBaseline = 'middle'; - ctx.fillStyle = this.options.fontColor; // render in correct colour - ctx.font = helpers.fontString(this.options.fontSize, this.options.fontStyle, this.options.fontFamily); + titleX = this.left + ((this.right - this.left) / 2); // midpoint of the width + titleY = this.top + ((this.bottom - this.top) / 2); // midpoint of the height - titleX = this.left + ((this.right - this.left) / 2); // midpoint of the width - titleY = this.top + ((this.bottom - this.top) / 2); // midpoint of the height - - ctx.fillText(this.options.text, titleX, titleY); - } + ctx.fillText(this.options.text, titleX, titleY); } else { // Title - if (this.options.display) { - titleX = this.options.position === 'left' ? this.left + (this.options.fontSize / 2) : this.right - (this.options.fontSize / 2); - titleY = this.top + ((this.bottom - this.top) / 2); - var rotation = this.options.position === 'left' ? -0.5 * Math.PI : 0.5 * Math.PI; - - ctx.save(); - ctx.translate(titleX, titleY); - ctx.rotate(rotation); - ctx.textAlign = "center"; - ctx.fillStyle = this.options.fontColor; // render in correct colour - ctx.font = helpers.fontString(this.options.fontSize, this.options.fontStyle, this.options.fontFamily); - ctx.textBaseline = 'middle'; - ctx.fillText(this.options.text, 0, 0); - ctx.restore(); - - } - + titleX = this.options.position === 'left' ? this.left + (fontSize / 2) : this.right - (fontSize / 2); + titleY = this.top + ((this.bottom - this.top) / 2); + var rotation = this.options.position === 'left' ? -0.5 * Math.PI : 0.5 * Math.PI; + + ctx.save(); + ctx.translate(titleX, titleY); + ctx.rotate(rotation); + ctx.textAlign = "center"; + ctx.textBaseline = 'middle'; + ctx.fillText(this.options.text, 0, 0); + ctx.restore(); } } }
true
Other
chartjs
Chart.js
8d5b3809f6a607ebf2be7af40fb538ea5e42c4db.json
Fix global font settings
src/core/core.tooltip.js
@@ -9,21 +9,14 @@ module.exports = function(Chart) { custom: null, mode: 'single', backgroundColor: "rgba(0,0,0,0.8)", - titleFontFamily: Chart.defaults.global.defaultFontFamily, - titleFontSize: Chart.defaults.global.defaultFontSize, titleFontStyle: "bold", titleSpacing: 2, titleMarginBottom: 6, titleColor: "#fff", titleAlign: "left", - bodyFontFamily: Chart.defaults.global.defaultFontFamily, - bodyFontSize: Chart.defaults.global.defaultFontSize, - bodyFontStyle: Chart.defaults.global.defaultFontStyle, bodySpacing: 2, bodyColor: "#fff", bodyAlign: "left", - footerFontFamily: Chart.defaults.global.defaultFontFamily, - footerFontSize: Chart.defaults.global.defaultFontSize, footerFontStyle: "bold", footerSpacing: 2, footerMarginTop: 6, @@ -98,26 +91,26 @@ module.exports = function(Chart) { // Body bodyColor: options.tooltips.bodyColor, - _bodyFontFamily: options.tooltips.bodyFontFamily, - _bodyFontStyle: options.tooltips.bodyFontStyle, + _bodyFontFamily: helpers.getValueOrDefault(options.tooltips.bodyFontFamily, Chart.defaults.global.defaultFontFamily), + _bodyFontStyle: helpers.getValueOrDefault(options.tooltips.bodyFontStyle, Chart.defaults.global.defaultFontStyle), _bodyAlign: options.tooltips.bodyAlign, - bodyFontSize: options.tooltips.bodyFontSize, + bodyFontSize: helpers.getValueOrDefault(options.tooltips.bodyFontSize, Chart.defaults.global.defaultFontSize), bodySpacing: options.tooltips.bodySpacing, // Title titleColor: options.tooltips.titleColor, - _titleFontFamily: options.tooltips.titleFontFamily, - _titleFontStyle: options.tooltips.titleFontStyle, - titleFontSize: options.tooltips.titleFontSize, + _titleFontFamily: helpers.getValueOrDefault(options.tooltips.titleFontFamily, Chart.defaults.global.defaultFontFamily), + _titleFontStyle: helpers.getValueOrDefault(options.tooltips.titleFontStyle, Chart.defaults.global.defaultFontStyle), + titleFontSize: helpers.getValueOrDefault(options.tooltips.titleFontSize, Chart.defaults.global.defaultFontSize), _titleAlign: options.tooltips.titleAlign, titleSpacing: options.tooltips.titleSpacing, titleMarginBottom: options.tooltips.titleMarginBottom, // Footer footerColor: options.tooltips.footerColor, - _footerFontFamily: options.tooltips.footerFontFamily, - _footerFontStyle: options.tooltips.footerFontStyle, - footerFontSize: options.tooltips.footerFontSize, + _footerFontFamily: helpers.getValueOrDefault(options.tooltips.footerFontFamily, Chart.defaults.global.defaultFontFamily), + _footerFontStyle: helpers.getValueOrDefault(options.tooltips.footerFontStyle, Chart.defaults.global.defaultFontStyle), + footerFontSize: helpers.getValueOrDefault(options.tooltips.footerFontSize, Chart.defaults.global.defaultFontSize), _footerAlign: options.tooltips.footerAlign, footerSpacing: options.tooltips.footerSpacing, footerMarginTop: options.tooltips.footerMarginTop,
true
Other
chartjs
Chart.js
8d5b3809f6a607ebf2be7af40fb538ea5e42c4db.json
Fix global font settings
src/scales/scale.linear.js
@@ -162,12 +162,11 @@ module.exports = function(Chart) { var maxTicks; if (this.isHorizontal()) { - maxTicks = Math.min(this.options.ticks.maxTicksLimit ? this.options.ticks.maxTicksLimit : 11, - Math.ceil(this.width / 50)); + maxTicks = Math.min(this.options.ticks.maxTicksLimit ? this.options.ticks.maxTicksLimit : 11, Math.ceil(this.width / 50)); } else { // The factor of 2 used to scale the font size has been experimentally determined. - maxTicks = Math.min(this.options.ticks.maxTicksLimit ? this.options.ticks.maxTicksLimit : 11, - Math.ceil(this.height / (2 * this.options.ticks.fontSize))); + var tickFontSize = helpers.getValueOrDefault(this.options.ticks.fontSize, Chart.defaults.global.defaultFontSize); + maxTicks = Math.min(this.options.ticks.maxTicksLimit ? this.options.ticks.maxTicksLimit : 11, Math.ceil(this.height / (2 * tickFontSize))); } // Make sure we always have at least 2 ticks
true
Other
chartjs
Chart.js
8d5b3809f6a607ebf2be7af40fb538ea5e42c4db.json
Fix global font settings
src/scales/scale.radialLinear.js
@@ -34,18 +34,9 @@ module.exports = function(Chart) { }, pointLabels: { - //String - Point label font declaration - fontFamily: Chart.defaults.global.defaultFontFamily, - - //String - Point label font weight - fontStyle: Chart.defaults.global.defaultFontStyle, - //Number - Point label font size in pixels fontSize: 10, - //String - Point label font colour - fontColor: Chart.defaults.global.defaultFontColor, - //Function - Used to convert point labels callback: function(label) { return label; @@ -65,7 +56,8 @@ module.exports = function(Chart) { this.yCenter = Math.round(this.height / 2); var minSize = helpers.min([this.height, this.width]); - this.drawingArea = (this.options.display) ? (minSize / 2) - (this.options.ticks.fontSize / 2 + this.options.ticks.backdropPaddingY) : (minSize / 2); + var tickFontSize = helpers.getValueOrDefault(this.options.ticks.fontSize, Chart.defaults.global.defaultFontSize); + this.drawingArea = (this.options.display) ? (minSize / 2) - (tickFontSize / 2 + this.options.ticks.backdropPaddingY) : (minSize / 2); }, determineDataLimits: function() { this.min = null; @@ -136,8 +128,8 @@ module.exports = function(Chart) { // the axis area. For now, we say that the minimum tick spacing in pixels must be 50 // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on // the graph - var maxTicks = Math.min(this.options.ticks.maxTicksLimit ? this.options.ticks.maxTicksLimit : 11, - Math.ceil(this.drawingArea / (1.5 * this.options.ticks.fontSize))); + var tickFontSize = helpers.getValueOrDefault(this.options.ticks.fontSize, Chart.defaults.global.defaultFontSize); + var maxTicks = Math.min(this.options.ticks.maxTicksLimit ? this.options.ticks.maxTicksLimit : 11, Math.ceil(this.drawingArea / (1.5 * tickFontSize))); maxTicks = Math.max(2, maxTicks); // Make sure we always have at least 2 ticks // To get a "nice" value for the tick spacing, we will use the appropriately named @@ -213,10 +205,14 @@ module.exports = function(Chart) { * https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif */ + var pointLabelFontSize = helpers.getValueOrDefault(this.options.pointLabels.fontSize, Chart.defaults.global.defaultFontSize); + var pointLabeFontStyle = helpers.getValueOrDefault(this.options.pointLabels.fontStyle, Chart.defaults.global.defaultFontStyle); + var pointLabeFontFamily = helpers.getValueOrDefault(this.options.pointLabels.fontFamily, Chart.defaults.global.defaultFontFamily); + var pointLabeFont = helpers.fontString(pointLabelFontSize, pointLabeFontStyle, pointLabeFontFamily); // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width. // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points - var largestPossibleRadius = helpers.min([(this.height / 2 - this.options.pointLabels.fontSize - 5), this.width / 2]), + var largestPossibleRadius = helpers.min([(this.height / 2 - pointLabelFontSize - 5), this.width / 2]), pointPosition, i, textWidth, @@ -232,7 +228,8 @@ module.exports = function(Chart) { radiusReductionRight, radiusReductionLeft, maxWidthRadius; - this.ctx.font = helpers.fontString(this.options.pointLabels.fontSize, this.options.pointLabels.fontStyle, this.options.pointLabels.fontFamily); + this.ctx.font = pointLabeFont; + for (i = 0; i < this.getValueCount(); i++) { // 5px to space the text slightly out - similar to what we do in the draw function. pointPosition = this.getPointPosition(i, largestPossibleRadius); @@ -357,22 +354,27 @@ module.exports = function(Chart) { } if (this.options.ticks.display) { - ctx.font = helpers.fontString(this.options.ticks.fontSize, this.options.ticks.fontStyle, this.options.ticks.fontFamily); + var tickFontColor = helpers.getValueOrDefault(this.options.ticks.fontColor, Chart.defaults.global.defaultFontColor); + var tickFontSize = helpers.getValueOrDefault(this.options.ticks.fontSize, Chart.defaults.global.defaultFontSize); + var tickFontStyle = helpers.getValueOrDefault(this.options.ticks.fontStyle, Chart.defaults.global.defaultFontStyle); + var tickFontFamily = helpers.getValueOrDefault(this.options.ticks.fontFamily, Chart.defaults.global.defaultFontFamily); + var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily); + ctx.font = tickLabelFont; if (this.options.ticks.showLabelBackdrop) { var labelWidth = ctx.measureText(label).width; ctx.fillStyle = this.options.ticks.backdropColor; ctx.fillRect( this.xCenter - labelWidth / 2 - this.options.ticks.backdropPaddingX, - yHeight - this.options.ticks.fontSize / 2 - this.options.ticks.backdropPaddingY, + yHeight - tickFontSize / 2 - this.options.ticks.backdropPaddingY, labelWidth + this.options.ticks.backdropPaddingX * 2, - this.options.ticks.fontSize + this.options.ticks.backdropPaddingY * 2 + tickFontSize + this.options.ticks.backdropPaddingY * 2 ); } ctx.textAlign = 'center'; ctx.textBaseline = "middle"; - ctx.fillStyle = this.options.ticks.fontColor; + ctx.fillStyle = tickFontColor; ctx.fillText(label, this.xCenter, yHeight); } } @@ -393,8 +395,15 @@ module.exports = function(Chart) { } // Extra 3px out for some label spacing var pointLabelPosition = this.getPointPosition(i, this.getDistanceFromCenterForValue(this.options.reverse ? this.min : this.max) + 5); - ctx.font = helpers.fontString(this.options.pointLabels.fontSize, this.options.pointLabels.fontStyle, this.options.pointLabels.fontFamily); - ctx.fillStyle = this.options.pointLabels.fontColor; + + var pointLabelFontColor = helpers.getValueOrDefault(this.options.pointLabels.fontColor, Chart.defaults.global.defaultFontColor); + var pointLabelFontSize = helpers.getValueOrDefault(this.options.pointLabels.fontSize, Chart.defaults.global.defaultFontSize); + var pointLabeFontStyle = helpers.getValueOrDefault(this.options.pointLabels.fontStyle, Chart.defaults.global.defaultFontStyle); + var pointLabeFontFamily = helpers.getValueOrDefault(this.options.pointLabels.fontFamily, Chart.defaults.global.defaultFontFamily); + var pointLabeFont = helpers.fontString(pointLabelFontSize, pointLabeFontStyle, pointLabeFontFamily); + + ctx.font = pointLabeFont; + ctx.fillStyle = pointLabelFontColor; var labelsCount = this.pointLabels.length, halfLabelsCount = this.pointLabels.length / 2,
true
Other
chartjs
Chart.js
8d5b3809f6a607ebf2be7af40fb538ea5e42c4db.json
Fix global font settings
src/scales/scale.time.js
@@ -145,8 +145,9 @@ module.exports = function(Chart) { this.tickRange = Math.ceil(this.lastTick.diff(this.firstTick, this.tickUnit, true)); } else { // Determine the smallest needed unit of the time + var tickFontSize = helpers.getValueOrDefault(this.options.ticks.fontSize, Chart.defaults.global.defaultFontSize); var innerWidth = this.isHorizontal() ? this.width - (this.paddingLeft + this.paddingRight) : this.height - (this.paddingTop + this.paddingBottom); - var labelCapacity = innerWidth / (this.options.ticks.fontSize + 10); + var labelCapacity = innerWidth / (tickFontSize + 10); var buffer = this.options.time.round ? 0 : 1; // Start as small as possible
true
Other
chartjs
Chart.js
8d5b3809f6a607ebf2be7af40fb538ea5e42c4db.json
Fix global font settings
test/core.helpers.tests.js
@@ -225,19 +225,11 @@ describe('Core helper tests', function() { }, position: "right", scaleLabel: { - fontColor: '#666', - fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", - fontSize: 12, - fontStyle: 'normal', labelString: '', display: false, }, ticks: { beginAtZero: false, - fontColor: "#666", - fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", - fontSize: 12, - fontStyle: "normal", maxRotation: 90, mirror: false, padding: 10, @@ -263,19 +255,11 @@ describe('Core helper tests', function() { }, position: "left", scaleLabel: { - fontColor: '#666', - fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", - fontSize: 12, - fontStyle: 'normal', labelString: '', display: false, }, ticks: { beginAtZero: false, - fontColor: "#666", - fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", - fontSize: 12, - fontStyle: "normal", maxRotation: 90, mirror: false, padding: 10,
true
Other
chartjs
Chart.js
8d5b3809f6a607ebf2be7af40fb538ea5e42c4db.json
Fix global font settings
test/core.legend.tests.js
@@ -18,10 +18,6 @@ describe('Legend block tests', function() { labels: { boxWidth: 40, - fontSize: Chart.defaults.global.defaultFontSize, - fontStyle: Chart.defaults.global.defaultFontStyle, - fontColor: Chart.defaults.global.defaultFontColor, - fontFamily: Chart.defaults.global.defaultFontFamily, padding: 10, generateLabels: jasmine.any(Function) }
true
Other
chartjs
Chart.js
8d5b3809f6a607ebf2be7af40fb538ea5e42c4db.json
Fix global font settings
test/core.title.tests.js
@@ -11,9 +11,6 @@ describe('Title block tests', function() { display: false, position: 'top', fullWidth: true, - fontColor: Chart.defaults.global.defaultFontColor, - fontFamily: Chart.defaults.global.defaultFontFamily, - fontSize: Chart.defaults.global.defaultFontSize, fontStyle: 'bold', padding: 10, text: '' @@ -146,6 +143,9 @@ describe('Title block tests', function() { title.draw(); expect(context.getCalls()).toEqual([{ + name: 'setFillStyle', + args: ['#666'] + }, { name: 'save', args: [] }, { @@ -154,9 +154,6 @@ describe('Title block tests', function() { }, { name: 'rotate', args: [-0.5 * Math.PI] - }, { - name: 'setFillStyle', - args: ['#666'] }, { name: 'fillText', args: ['My title', 0, 0] @@ -179,6 +176,9 @@ describe('Title block tests', function() { title.draw(); expect(context.getCalls()).toEqual([{ + name: 'setFillStyle', + args: ['#666'] + }, { name: 'save', args: [] }, { @@ -187,9 +187,6 @@ describe('Title block tests', function() { }, { name: 'rotate', args: [0.5 * Math.PI] - }, { - name: 'setFillStyle', - args: ['#666'] }, { name: 'fillText', args: ['My title', 0, 0]
true
Other
chartjs
Chart.js
8d5b3809f6a607ebf2be7af40fb538ea5e42c4db.json
Fix global font settings
test/scale.category.tests.js
@@ -24,19 +24,11 @@ describe('Category scale tests', function() { }, position: "bottom", scaleLabel: { - fontColor: '#666', - fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", - fontSize: 12, - fontStyle: 'normal', labelString: '', display: false, }, ticks: { beginAtZero: false, - fontColor: "#666", - fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", - fontSize: 12, - fontStyle: "normal", maxRotation: 90, mirror: false, padding: 10,
true
Other
chartjs
Chart.js
8d5b3809f6a607ebf2be7af40fb538ea5e42c4db.json
Fix global font settings
test/scale.linear.tests.js
@@ -23,19 +23,11 @@ describe('Linear Scale', function() { }, position: "left", scaleLabel: { - fontColor: '#666', - fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", - fontSize: 12, - fontStyle: 'normal', labelString: '', display: false, }, ticks: { beginAtZero: false, - fontColor: "#666", - fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", - fontSize: 12, - fontStyle: "normal", maxRotation: 90, mirror: false, padding: 10,
true
Other
chartjs
Chart.js
8d5b3809f6a607ebf2be7af40fb538ea5e42c4db.json
Fix global font settings
test/scale.logarithmic.tests.js
@@ -22,19 +22,11 @@ describe('Logarithmic Scale tests', function() { }, position: "left", scaleLabel: { - fontColor: '#666', - fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", - fontSize: 12, - fontStyle: 'normal', labelString: '', display: false, }, ticks: { beginAtZero: false, - fontColor: "#666", - fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", - fontSize: 12, - fontStyle: "normal", maxRotation: 90, mirror: false, padding: 10,
true