Search in sources :

Example 1 with TypeMismatchException

use of cn.taketoday.beans.TypeMismatchException in project today-infrastructure by TAKETODAY.

the class ConstructorResolver method createArgumentArray.

/**
 * Create an array of arguments to invoke a constructor or factory method,
 * given the resolved constructor argument values.
 */
private ArgumentsHolder createArgumentArray(String beanName, RootBeanDefinition merged, @Nullable ConstructorArgumentValues resolvedValues, Class<?>[] paramTypes, @Nullable String[] paramNames, Executable executable, BeanWrapper wrapper, boolean autowiring, boolean fallback) throws UnsatisfiedDependencyException {
    TypeConverter customConverter = this.beanFactory.getCustomTypeConverter();
    TypeConverter converter = customConverter != null ? customConverter : wrapper;
    ArgumentsHolder args = new ArgumentsHolder(paramTypes.length);
    HashSet<ValueHolder> usedValueHolders = new HashSet<>(paramTypes.length);
    LinkedHashSet<String> autowiredBeanNames = new LinkedHashSet<>(4);
    for (int paramIndex = 0; paramIndex < paramTypes.length; paramIndex++) {
        Class<?> paramType = paramTypes[paramIndex];
        String paramName = paramNames != null ? paramNames[paramIndex] : "";
        // Try to find matching constructor argument value, either indexed or generic.
        ValueHolder valueHolder = null;
        if (resolvedValues != null) {
            valueHolder = resolvedValues.getArgumentValue(paramIndex, paramType, paramName, usedValueHolders);
            // it could match after type conversion (for example, String -> int).
            if (valueHolder == null && (!autowiring || paramTypes.length == resolvedValues.getArgumentCount())) {
                valueHolder = resolvedValues.getGenericArgumentValue(null, null, usedValueHolders);
            }
        }
        if (valueHolder != null) {
            // We found a potential match - let's give it a try.
            // Do not consider the same value definition multiple times!
            usedValueHolders.add(valueHolder);
            Object originalValue = valueHolder.getValue();
            Object convertedValue;
            if (valueHolder.isConverted()) {
                convertedValue = valueHolder.getConvertedValue();
                args.preparedArguments[paramIndex] = convertedValue;
            } else {
                MethodParameter methodParam = MethodParameter.forExecutable(executable, paramIndex);
                try {
                    convertedValue = converter.convertIfNecessary(originalValue, paramType, methodParam);
                } catch (TypeMismatchException ex) {
                    throw new UnsatisfiedDependencyException(merged.getResourceDescription(), beanName, new InjectionPoint(methodParam), "Could not convert argument value of type [" + ObjectUtils.nullSafeClassName(valueHolder.getValue()) + "] to required type [" + paramType.getName() + "]: " + ex.getMessage());
                }
                Object sourceHolder = valueHolder.getSource();
                if (sourceHolder instanceof ValueHolder) {
                    Object sourceValue = ((ValueHolder) sourceHolder).getValue();
                    args.resolveNecessary = true;
                    args.preparedArguments[paramIndex] = sourceValue;
                }
            }
            args.arguments[paramIndex] = convertedValue;
            args.rawArguments[paramIndex] = originalValue;
        } else {
            MethodParameter methodParam = MethodParameter.forExecutable(executable, paramIndex);
            // have to fail creating an argument array for the given constructor.
            if (!autowiring) {
                throw new UnsatisfiedDependencyException(merged.getResourceDescription(), beanName, new InjectionPoint(methodParam), "Ambiguous argument values for parameter of type [" + paramType.getName() + "] - did you specify the correct bean references as arguments?");
            }
            try {
                Object autowiredArgument = resolveAutowiredArgument(methodParam, beanName, autowiredBeanNames, converter, fallback);
                args.resolveNecessary = true;
                args.arguments[paramIndex] = autowiredArgument;
                args.rawArguments[paramIndex] = autowiredArgument;
                args.preparedArguments[paramIndex] = autowiredArgumentMarker;
            } catch (BeansException ex) {
                throw new UnsatisfiedDependencyException(merged.getResourceDescription(), beanName, new InjectionPoint(methodParam), ex);
            }
        }
    }
    for (String autowiredBeanName : autowiredBeanNames) {
        beanFactory.registerDependentBean(autowiredBeanName, beanName);
        if (log.isDebugEnabled()) {
            log.debug("Autowiring by type from bean name '{}' via {} to bean named '{}'", beanName, (executable instanceof Constructor ? "constructor" : "factory method"), autowiredBeanName);
        }
    }
    return args;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) InjectionPoint(cn.taketoday.beans.factory.InjectionPoint) Constructor(java.lang.reflect.Constructor) TypeMismatchException(cn.taketoday.beans.TypeMismatchException) ValueHolder(cn.taketoday.beans.factory.config.ConstructorArgumentValues.ValueHolder) InjectionPoint(cn.taketoday.beans.factory.InjectionPoint) TypeConverter(cn.taketoday.beans.TypeConverter) UnsatisfiedDependencyException(cn.taketoday.beans.factory.UnsatisfiedDependencyException) MethodParameter(cn.taketoday.core.MethodParameter) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) BeansException(cn.taketoday.beans.BeansException)

Example 2 with TypeMismatchException

use of cn.taketoday.beans.TypeMismatchException in project today-infrastructure by TAKETODAY.

the class DateFormattingTests method styleDateWithInvalidFormat.

@Test
void styleDateWithInvalidFormat() {
    String propertyName = "styleDate";
    String propertyValue = "99/01/01";
    PropertyValues propertyValues = new PropertyValues();
    propertyValues.add(propertyName, propertyValue);
    binder.bind(propertyValues);
    BindingResult bindingResult = binder.getBindingResult();
    assertThat(bindingResult.getErrorCount()).isEqualTo(1);
    FieldError fieldError = bindingResult.getFieldError(propertyName);
    TypeMismatchException exception = fieldError.unwrap(TypeMismatchException.class);
    assertThat(exception).hasMessageContaining("for property 'styleDate'").hasCauseInstanceOf(ConversionFailedException.class).getCause().hasMessageContaining("for value '99/01/01'").hasCauseInstanceOf(IllegalArgumentException.class).getCause().hasMessageContaining("Parse attempt failed for value [99/01/01]").hasCauseInstanceOf(ParseException.class).getCause().hasMessageContainingAll("Unable to parse date time value \"99/01/01\" using configuration from", "@cn.taketoday.format.annotation.DateTimeFormat", "style=", "S-", "iso=NONE").hasCauseInstanceOf(ParseException.class).getCause().hasMessageStartingWith("Unparseable date: \"99/01/01\"").hasNoCause();
}
Also used : BindingResult(cn.taketoday.validation.BindingResult) PropertyValues(cn.taketoday.beans.PropertyValues) TypeMismatchException(cn.taketoday.beans.TypeMismatchException) FieldError(cn.taketoday.validation.FieldError) ParseException(java.text.ParseException) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 3 with TypeMismatchException

use of cn.taketoday.beans.TypeMismatchException in project today-infrastructure by TAKETODAY.

the class ResponseStatusExceptionHandlerTests method nestedException.

// SPR-12903
@Test
public void nestedException() throws Exception {
    Exception cause = new StatusCodeAndReasonMessageException();
    TypeMismatchException ex = new TypeMismatchException("value", ITestBean.class, cause);
    Object mav = handleException(ex);
    assertResolved(mav, 410, "gone.reason");
}
Also used : TypeMismatchException(cn.taketoday.beans.TypeMismatchException) TypeMismatchException(cn.taketoday.beans.TypeMismatchException) MethodNotAllowedException(cn.taketoday.web.MethodNotAllowedException) ResponseStatusException(cn.taketoday.web.ResponseStatusException) Test(org.junit.jupiter.api.Test)

Example 4 with TypeMismatchException

use of cn.taketoday.beans.TypeMismatchException in project today-infrastructure by TAKETODAY.

the class BeanPropertyRowMapper method mapRow.

/**
 * Extract the values for all columns in the current row.
 * <p>Utilizes public setters and result set meta-data.
 *
 * @see ResultSetMetaData
 */
@Override
public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
    BeanWrapperImpl beanWrapper = this.beanWrapper;
    T mappedObject = constructMappedInstance(rs, beanWrapper);
    beanWrapper.setBeanInstance(mappedObject);
    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    Set<String> populatedProperties = isCheckFullyPopulated() ? new HashSet<>() : null;
    HashMap<String, BeanProperty> mappedFields = this.mappedFields;
    for (int index = 1; index <= columnCount; index++) {
        String column = JdbcUtils.lookupColumnName(rsmd, index);
        String field = lowerCaseName(StringUtils.delete(column, " "));
        BeanProperty property = mappedFields != null ? mappedFields.get(field) : null;
        if (property != null) {
            try {
                // TODO using TypeHandler
                Object value = getColumnValue(rs, index, property);
                if (rowNumber == 0 && debugEnabled) {
                    log.debug("Mapping column '{}' to property '{}' of type '{}'", column, property.getName(), ClassUtils.getQualifiedName(property.getType()));
                }
                try {
                    beanWrapper.setPropertyValue(property.getName(), value);
                } catch (TypeMismatchException ex) {
                    if (value == null && this.primitivesDefaultedForNullValue) {
                        if (debugEnabled) {
                            log.debug("Intercepted TypeMismatchException for row {} and column '{}'" + " with null value when setting property '{}' of type '{}' on object: {}", rowNumber, column, property.getName(), ClassUtils.getQualifiedName(property.getType()), mappedObject, ex);
                        }
                    } else {
                        throw ex;
                    }
                }
                if (populatedProperties != null) {
                    populatedProperties.add(property.getName());
                }
            } catch (NotWritablePropertyException ex) {
                throw new DataRetrievalFailureException("Unable to map column '" + column + "' to property '" + property.getName() + "'", ex);
            }
        } else {
            // No BeanProperty found
            if (rowNumber == 0 && debugEnabled) {
                log.debug("No property found for column '{}' mapped to field '{}'", column, field);
            }
        }
    }
    if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) {
        throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields " + "necessary to populate object of " + this.mappedClass + ": " + this.mappedProperties);
    }
    return mappedObject;
}
Also used : BeanWrapperImpl(cn.taketoday.beans.BeanWrapperImpl) TypeMismatchException(cn.taketoday.beans.TypeMismatchException) BeanProperty(cn.taketoday.beans.BeanProperty) ResultSetMetaData(java.sql.ResultSetMetaData) NotWritablePropertyException(cn.taketoday.beans.NotWritablePropertyException) InvalidDataAccessApiUsageException(cn.taketoday.dao.InvalidDataAccessApiUsageException) DataRetrievalFailureException(cn.taketoday.dao.DataRetrievalFailureException)

Example 5 with TypeMismatchException

use of cn.taketoday.beans.TypeMismatchException in project today-framework by TAKETODAY.

the class ResponseEntityExceptionHandlerTests method typeMismatch.

@Test
public void typeMismatch() {
    Exception ex = new TypeMismatchException("foo", String.class);
    testException(ex);
}
Also used : TypeMismatchException(cn.taketoday.beans.TypeMismatchException) MissingRequestPartException(cn.taketoday.web.bind.resolver.MissingRequestPartException) MissingPathVariableException(cn.taketoday.web.bind.MissingPathVariableException) ServletException(jakarta.servlet.ServletException) HttpRequestMethodNotSupportedException(cn.taketoday.web.HttpRequestMethodNotSupportedException) MissingRequestParameterException(cn.taketoday.web.bind.MissingRequestParameterException) RequestBindingException(cn.taketoday.web.bind.RequestBindingException) ConversionNotSupportedException(cn.taketoday.beans.ConversionNotSupportedException) HttpMessageNotReadableException(cn.taketoday.http.converter.HttpMessageNotReadableException) TypeMismatchException(cn.taketoday.beans.TypeMismatchException) HttpMediaTypeNotSupportedException(cn.taketoday.web.HttpMediaTypeNotSupportedException) HttpMediaTypeNotAcceptableException(cn.taketoday.web.HttpMediaTypeNotAcceptableException) BindException(cn.taketoday.validation.BindException) AsyncRequestTimeoutException(cn.taketoday.web.context.async.AsyncRequestTimeoutException) HttpMessageNotWritableException(cn.taketoday.http.converter.HttpMessageNotWritableException) MethodArgumentNotValidException(cn.taketoday.web.bind.MethodArgumentNotValidException) Test(org.junit.jupiter.api.Test)

Aggregations

TypeMismatchException (cn.taketoday.beans.TypeMismatchException)16 TypeConverter (cn.taketoday.beans.TypeConverter)7 MethodParameter (cn.taketoday.core.MethodParameter)7 InjectionPoint (cn.taketoday.beans.factory.InjectionPoint)5 UnsatisfiedDependencyException (cn.taketoday.beans.factory.UnsatisfiedDependencyException)5 Test (org.junit.jupiter.api.Test)5 Nullable (cn.taketoday.lang.Nullable)4 BeansException (cn.taketoday.beans.BeansException)3 ConversionNotSupportedException (cn.taketoday.beans.ConversionNotSupportedException)3 ValueHolder (cn.taketoday.beans.factory.config.ConstructorArgumentValues.ValueHolder)3 Constructor (java.lang.reflect.Constructor)3 HashSet (java.util.HashSet)3 LinkedHashSet (java.util.LinkedHashSet)3 BeanMetadataElement (cn.taketoday.beans.BeanMetadataElement)2 BeanProperty (cn.taketoday.beans.BeanProperty)2 BeanWrapperImpl (cn.taketoday.beans.BeanWrapperImpl)2 NotWritablePropertyException (cn.taketoday.beans.NotWritablePropertyException)2 PropertyValues (cn.taketoday.beans.PropertyValues)2 SimpleTypeConverter (cn.taketoday.beans.SimpleTypeConverter)2 DataRetrievalFailureException (cn.taketoday.dao.DataRetrievalFailureException)2