Java 类org.springframework.beans.TypeMismatchException 实例源码

项目:spring4-understanding    文件:MvcNamespaceTests.java   
@Test(expected = TypeMismatchException.class)
public void testCustomConversionService() throws Exception {
    loadBeanDefinitions("mvc-config-custom-conversion-service.xml", 14);

    RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
    assertNotNull(mapping);
    mapping.setDefaultHandler(handlerMethod);

    // default web binding initializer behavior test
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
    request.setRequestURI("/accounts/12345");
    request.addParameter("date", "2009-10-31");
    MockHttpServletResponse response = new MockHttpServletResponse();

    HandlerExecutionChain chain = mapping.getHandler(request);
    assertEquals(1, chain.getInterceptors().length);
    assertTrue(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor);
    ConversionServiceExposingInterceptor interceptor = (ConversionServiceExposingInterceptor) chain.getInterceptors()[0];
    interceptor.preHandle(request, response, handler);
    assertSame(appContext.getBean("conversionService"), request.getAttribute(ConversionService.class.getName()));

    RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
    assertNotNull(adapter);
    adapter.handle(request, response, handlerMethod);
}
项目:spring4-understanding    文件:ClassPathXmlApplicationContextTests.java   
@Test
public void testContextWithInvalidValueType() throws IOException {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            new String[] {INVALID_VALUE_TYPE_CONTEXT}, false);
    try {
        context.refresh();
        fail("Should have thrown BeanCreationException");
    }
    catch (BeanCreationException ex) {
        assertTrue(ex.contains(TypeMismatchException.class));
        assertTrue(ex.toString().contains("someMessageSource"));
        assertTrue(ex.toString().contains("useCodeAsDefaultMessage"));
        checkExceptionFromInvalidValueType(ex);
        checkExceptionFromInvalidValueType(new ExceptionInInitializerError(ex));
        assertFalse(context.isActive());
    }
}
项目:spring4-understanding    文件:DefaultListableBeanFactoryTests.java   
@Override
@SuppressWarnings("unchecked")
public Object convertIfNecessary(Object value, Class requiredType) {
    if (value instanceof String && Float.class.isAssignableFrom(requiredType)) {
        try {
            return new Float(this.numberFormat.parse((String) value).floatValue());
        }
        catch (ParseException ex) {
            throw new TypeMismatchException(value, requiredType, ex);
        }
    }
    else if (value instanceof String && int.class.isAssignableFrom(requiredType)) {
        return new Integer(5);
    }
    else {
        return value;
    }
}
项目:oldSyncopeIdM    文件:AbstractController.java   
protected TaskUtil getTaskUtil(final Task task) {
    TaskUtil result = (task instanceof PropagationTask)
            ? TaskUtil.PROPAGATION
            : (task instanceof NotificationTask)
            ? TaskUtil.NOTIFICATION
            : (task instanceof SyncTask)
            ? TaskUtil.SYNC
            : (task instanceof SchedTask)
            ? TaskUtil.SCHED
            : null;

    if (result == null) {
        LOG.error("Task not supported: " + task.getClass().getName());

        throw new TypeMismatchException(task.getClass().getName(),
                TaskUtil.class);
    }

    return result;
}
项目:oldSyncopeIdM    文件:AbstractController.java   
protected TaskUtil getTaskUtil(final TaskTO taskTO) {
    TaskUtil result = (taskTO instanceof PropagationTaskTO)
            ? TaskUtil.PROPAGATION
            : (taskTO instanceof SyncTaskTO)
            ? TaskUtil.SYNC
            : (taskTO instanceof SchedTaskTO)
            ? TaskUtil.SCHED
            : null;

    if (result == null) {
        LOG.error("Task not supported: " + taskTO.getClass().getName());

        throw new TypeMismatchException(taskTO.getClass().getName(),
                TaskUtil.class);
    }

    return result;
}
项目:ShoppingMall    文件:SimpleXmlHttpMessageConverter.java   
@Override
protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage) 
        throws IOException, HttpMessageNotReadableException {

    Reader source = new InputStreamReader(inputMessage.getBody(), getCharset(inputMessage.getHeaders()));

    try {
        Object result = this.serializer.read(clazz, source);
        if (!clazz.isInstance(result)) {
            throw new TypeMismatchException(result, clazz);
        }
        return result;
    } catch (Exception ex) {
        throw new HttpMessageNotReadableException("Could not read [" + clazz + "]", ex);
    }
}
项目:class-guard    文件:ClassPathXmlApplicationContextTests.java   
@Test
public void testContextWithInvalidValueType() throws IOException {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            new String[] {INVALID_VALUE_TYPE_CONTEXT}, false);
    try {
        context.refresh();
        fail("Should have thrown BeanCreationException");
    }
    catch (BeanCreationException ex) {
        assertTrue(ex.contains(TypeMismatchException.class));
        assertTrue(ex.toString().contains("someMessageSource"));
        assertTrue(ex.toString().contains("useCodeAsDefaultMessage"));
        checkExceptionFromInvalidValueType(ex);
        checkExceptionFromInvalidValueType(new ExceptionInInitializerError(ex));
        assertFalse(context.isActive());
    }
}
项目:class-guard    文件:MvcNamespaceTests.java   
@Test(expected=TypeMismatchException.class)
public void testCustomConversionService() throws Exception {
    loadBeanDefinitions("mvc-config-custom-conversion-service.xml", 12);

    RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
    assertNotNull(mapping);
    mapping.setDefaultHandler(handlerMethod);

    // default web binding initializer behavior test
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
    request.setRequestURI("/accounts/12345");
    request.addParameter("date", "2009-10-31");
    MockHttpServletResponse response = new MockHttpServletResponse();

    HandlerExecutionChain chain = mapping.getHandler(request);
    assertEquals(1, chain.getInterceptors().length);
    assertTrue(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor);
    ConversionServiceExposingInterceptor interceptor = (ConversionServiceExposingInterceptor) chain.getInterceptors()[0];
    interceptor.preHandle(request, response, handler);
    assertSame(appContext.getBean("conversionService"), request.getAttribute(ConversionService.class.getName()));

    RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
    assertNotNull(adapter);
    adapter.handle(request, response, handlerMethod);
}
项目:class-guard    文件:DefaultListableBeanFactoryTests.java   
@Override
@SuppressWarnings("unchecked")
public Object convertIfNecessary(Object value, Class requiredType) {
    if (value instanceof String && Float.class.isAssignableFrom(requiredType)) {
        try {
            return new Float(this.numberFormat.parse((String) value).floatValue());
        }
        catch (ParseException ex) {
            throw new TypeMismatchException(value, requiredType, ex);
        }
    }
    else if (value instanceof String && int.class.isAssignableFrom(requiredType)) {
        return new Integer(5);
    }
    else {
        return value;
    }
}
项目:sniffy    文件:SniffySpringConfiguration.java   
private boolean resolveBooleanProperty(String attributeValue) {
    Boolean value;

    String resolvedValue = beanFactory.resolveEmbeddedValue(attributeValue);
    Object injectHtmlObj = resolver.evaluate(resolvedValue, expressionContext);
    try {
        value = typeConverter.convertIfNecessary(injectHtmlObj, Boolean.class);
    } catch (TypeMismatchException e) {
        value = false;
    }

    if (null == value) {
        value = false;
    }

    return value;
}
项目:disconf    文件:MyExceptionHandler.java   
/**
 * TypeMismatchException中获取到参数错误类型
 *
 * @param e
 */
private ModelAndView getParamErrors(TypeMismatchException e) {

    Throwable t = e.getCause();

    if (t instanceof ConversionFailedException) {

        ConversionFailedException x = (ConversionFailedException) t;
        TypeDescriptor type = x.getTargetType();
        Annotation[] annotations = type != null ? type.getAnnotations() : new Annotation[0];
        Map<String, String> errors = new HashMap<String, String>();
        for (Annotation a : annotations) {
            if (a instanceof RequestParam) {
                errors.put(((RequestParam) a).value(), "parameter type error!");
            }
        }
        if (errors.size() > 0) {
            return paramError(errors, ErrorCode.TYPE_MIS_MATCH);
        }
    }

    JsonObjectBase jsonObject = JsonObjectUtils.buildGlobalError("parameter type error!", ErrorCode.TYPE_MIS_MATCH);
    return JsonObjectUtils.JsonObjectError2ModelView((JsonObjectError) jsonObject);
}
项目:lemon-fileservice    文件:ExceptionConfiguration.java   
/**
 * 400错误
 */
@ResponseBody
@ExceptionHandler({ TypeMismatchException.class })
public ResultResponse typeMismatchExceptionHandler(TypeMismatchException ex) {
    logger.error(ResultMessage.F4000.getMessage(), ex);
    return resultResponse.failure(ResultMessage.F4000, ex.getMessage());
}
项目:gemini.blueprint    文件:SpringBlueprintConverter.java   
public boolean canConvert(Object source, ReifiedType targetType) {
    Class<?> required = targetType.getRawClass();
    try {
        getConverter().convertIfNecessary(source, required);
        return true;
    } catch (TypeMismatchException ex) {
        return false;
    }
}
项目:lams    文件:JndiObjectFactoryBean.java   
/**
 * Look up the JNDI object and store it.
 */
@Override
public void afterPropertiesSet() throws IllegalArgumentException, NamingException {
    super.afterPropertiesSet();

    if (this.proxyInterfaces != null || !this.lookupOnStartup || !this.cache || this.exposeAccessContext) {
        // We need to create a proxy for this...
        if (this.defaultObject != null) {
            throw new IllegalArgumentException(
                    "'defaultObject' is not supported in combination with 'proxyInterface'");
        }
        // We need a proxy and a JndiObjectTargetSource.
        this.jndiObject = JndiObjectProxyFactory.createJndiObjectProxy(this);
    }
    else {
        if (this.defaultObject != null && getExpectedType() != null &&
                !getExpectedType().isInstance(this.defaultObject)) {
            TypeConverter converter = (this.beanFactory != null ?
                    this.beanFactory.getTypeConverter() : new SimpleTypeConverter());
            try {
                this.defaultObject = converter.convertIfNecessary(this.defaultObject, getExpectedType());
            }
            catch (TypeMismatchException ex) {
                throw new IllegalArgumentException("Default object [" + this.defaultObject + "] of type [" +
                        this.defaultObject.getClass().getName() + "] is not of expected type [" +
                        getExpectedType().getName() + "] and cannot be converted either", ex);
            }
        }
        // Locate specified JNDI object.
        this.jndiObject = lookupWithFallback();
    }
}
项目:lams    文件:ConstructorResolver.java   
/**
 * Resolve the prepared arguments stored in the given bean definition.
 */
private Object[] resolvePreparedArguments(
        String beanName, RootBeanDefinition mbd, BeanWrapper bw, Member methodOrCtor, Object[] argsToResolve) {

    Class<?>[] paramTypes = (methodOrCtor instanceof Method ?
            ((Method) methodOrCtor).getParameterTypes() : ((Constructor<?>) methodOrCtor).getParameterTypes());
    TypeConverter converter = (this.beanFactory.getCustomTypeConverter() != null ?
            this.beanFactory.getCustomTypeConverter() : bw);
    BeanDefinitionValueResolver valueResolver =
            new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd, converter);
    Object[] resolvedArgs = new Object[argsToResolve.length];
    for (int argIndex = 0; argIndex < argsToResolve.length; argIndex++) {
        Object argValue = argsToResolve[argIndex];
        MethodParameter methodParam = MethodParameter.forMethodOrConstructor(methodOrCtor, argIndex);
        GenericTypeResolver.resolveParameterType(methodParam, methodOrCtor.getDeclaringClass());
        if (argValue instanceof AutowiredArgumentMarker) {
            argValue = resolveAutowiredArgument(methodParam, beanName, null, converter);
        }
        else if (argValue instanceof BeanMetadataElement) {
            argValue = valueResolver.resolveValueIfNecessary("constructor argument", argValue);
        }
        else if (argValue instanceof String) {
            argValue = this.beanFactory.evaluateBeanDefinitionString((String) argValue, mbd);
        }
        Class<?> paramType = paramTypes[argIndex];
        try {
            resolvedArgs[argIndex] = converter.convertIfNecessary(argValue, paramType, methodParam);
        }
        catch (TypeMismatchException ex) {
            String methodType = (methodOrCtor instanceof Constructor ? "constructor" : "factory method");
            throw new UnsatisfiedDependencyException(
                    mbd.getResourceDescription(), beanName, argIndex, paramType,
                    "Could not convert " + methodType + " argument value of type [" +
                    ObjectUtils.nullSafeClassName(argValue) +
                    "] to required type [" + paramType.getName() + "]: " + ex.getMessage());
        }
    }
    return resolvedArgs;
}
项目:lams    文件:MarshallingHttpMessageConverter.java   
@Override
protected Object readFromSource(Class<?> clazz, HttpHeaders headers, Source source) throws IOException {
    Assert.notNull(this.unmarshaller, "Property 'unmarshaller' is required");
    try {
        Object result = this.unmarshaller.unmarshal(source);
        if (!clazz.isInstance(result)) {
            throw new TypeMismatchException(result, clazz);
        }
        return result;
    }
    catch (UnmarshallingFailureException ex) {
        throw new HttpMessageNotReadableException("Could not read [" + clazz + "]", ex);
    }
}
项目:uis    文件:GlobalExceptionHandler.java   
@ExceptionHandler(TypeMismatchException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public ModelAndView handleTypeMismatchExceptions(HttpServletRequest request, TypeMismatchException ex) {
    logger.warn("TypeMismatchRequest: " + request.getRequestURL(), ex);
    ModelAndView mav = new ModelAndView();
    mav.setViewName("error");
    return mav;
}
项目:xxproject    文件:CustomRestExceptionHandler.java   
@Override
protected ResponseEntity<Object> handleTypeMismatch(final TypeMismatchException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
    logger.info(ex.getClass().getName());
    //
    final String error = ex.getValue() + " value for " + ex.getPropertyName() + " should be of type " + ex.getRequiredType();

    final ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), error);
    return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus());
}
项目:ait-platform    文件:AitRestExceptionHandler.java   
@Override
protected ResponseEntity<Object> handleTypeMismatch(final TypeMismatchException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
    logger.info(ex.getClass().getName());
    //
    final String error = ex.getValue() + " value for " + ex.getPropertyName() + " should be of type " + ex.getRequiredType();

    final AitException AitException = new AitException(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), error);
    return handleExceptionInternal(ex, AitException, headers, AitException.getStatus(), request);
}
项目:spring4-understanding    文件:MarshallingMessageConverter.java   
@Override
protected Object convertFromInternal(Message<?> message, Class<?> targetClass, Object conversionHint) {
    Assert.notNull(this.unmarshaller, "Property 'unmarshaller' is required");
    try {
        Source source = getSource(message.getPayload());
        Object result = this.unmarshaller.unmarshal(source);
        if (!targetClass.isInstance(result)) {
            throw new TypeMismatchException(result, targetClass);
        }
        return result;
    }
    catch (Exception ex) {
        throw new MessageConversionException(message, "Could not unmarshal XML: " + ex.getMessage(), ex);
    }
}
项目:spring4-understanding    文件:JndiObjectFactoryBean.java   
/**
 * Look up the JNDI object and store it.
 */
@Override
public void afterPropertiesSet() throws IllegalArgumentException, NamingException {
    super.afterPropertiesSet();

    if (this.proxyInterfaces != null || !this.lookupOnStartup || !this.cache || this.exposeAccessContext) {
        // We need to create a proxy for this...
        if (this.defaultObject != null) {
            throw new IllegalArgumentException(
                    "'defaultObject' is not supported in combination with 'proxyInterface'");
        }
        // We need a proxy and a JndiObjectTargetSource.
        this.jndiObject = JndiObjectProxyFactory.createJndiObjectProxy(this);
    }
    else {
        if (this.defaultObject != null && getExpectedType() != null &&
                !getExpectedType().isInstance(this.defaultObject)) {
            TypeConverter converter = (this.beanFactory != null ?
                    this.beanFactory.getTypeConverter() : new SimpleTypeConverter());
            try {
                this.defaultObject = converter.convertIfNecessary(this.defaultObject, getExpectedType());
            }
            catch (TypeMismatchException ex) {
                throw new IllegalArgumentException("Default object [" + this.defaultObject + "] of type [" +
                        this.defaultObject.getClass().getName() + "] is not of expected type [" +
                        getExpectedType().getName() + "] and cannot be converted either", ex);
            }
        }
        // Locate specified JNDI object.
        this.jndiObject = lookupWithFallback();
    }
}
项目:spring4-understanding    文件:ResponseStatusExceptionResolverTests.java   
@Test
public void nestedException() throws Exception {
    Exception cause = new StatusCodeAndReasonMessageException();
    TypeMismatchException ex = new TypeMismatchException("value", ITestBean.class, cause);
    ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
    assertNotNull("No ModelAndView returned", mav);
    assertTrue("No Empty ModelAndView returned", mav.isEmpty());
    assertEquals("Invalid status code", 410, response.getStatus());
}
项目:spring4-understanding    文件:DefaultHandlerExceptionResolverTests.java   
@Test
public void handleTypeMismatch() {
    TypeMismatchException ex = new TypeMismatchException("foo", String.class);
    ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
    assertNotNull("No ModelAndView returned", mav);
    assertTrue("No Empty ModelAndView returned", mav.isEmpty());
    assertEquals("Invalid status code", 400, response.getStatus());
}
项目:spring4-understanding    文件:BeanPropertyRowMapperTests.java   
@Test
public void testMappingNullValue() throws Exception {
    BeanPropertyRowMapper<Person> mapper = new BeanPropertyRowMapper<Person>(Person.class);
    Mock mock = new Mock(MockType.TWO);
    thrown.expect(TypeMismatchException.class);
    mock.getJdbcTemplate().query(
            "select name, null as age, birth_date, balance from people", mapper);
}
项目:spring4-understanding    文件:MarshallingHttpMessageConverter.java   
@Override
protected Object readFromSource(Class<?> clazz, HttpHeaders headers, Source source) throws IOException {
    Assert.notNull(this.unmarshaller, "Property 'unmarshaller' is required");
    try {
        Object result = this.unmarshaller.unmarshal(source);
        if (!clazz.isInstance(result)) {
            throw new TypeMismatchException(result, clazz);
        }
        return result;
    }
    catch (UnmarshallingFailureException ex) {
        throw new HttpMessageNotReadableException("Could not read [" + clazz + "]", ex);
    }
}
项目:spring4-understanding    文件:MarshallingHttpMessageConverterTests.java   
@Test(expected = TypeMismatchException.class)
public void readWithTypeMismatchException() throws Exception {
    MockHttpInputMessage inputMessage = new MockHttpInputMessage(new byte[0]);

    Marshaller marshaller = mock(Marshaller.class);
    Unmarshaller unmarshaller = mock(Unmarshaller.class);
    given(unmarshaller.unmarshal(isA(StreamSource.class))).willReturn(Integer.valueOf(3));

    MarshallingHttpMessageConverter converter = new MarshallingHttpMessageConverter(marshaller, unmarshaller);
    converter.read(String.class, inputMessage);
}
项目:spring4-understanding    文件:ConstructorResolver.java   
/**
 * Resolve the prepared arguments stored in the given bean definition.
 */
private Object[] resolvePreparedArguments(
        String beanName, RootBeanDefinition mbd, BeanWrapper bw, Member methodOrCtor, Object[] argsToResolve) {

    Class<?>[] paramTypes = (methodOrCtor instanceof Method ?
            ((Method) methodOrCtor).getParameterTypes() : ((Constructor<?>) methodOrCtor).getParameterTypes());
    TypeConverter converter = (this.beanFactory.getCustomTypeConverter() != null ?
            this.beanFactory.getCustomTypeConverter() : bw);
    BeanDefinitionValueResolver valueResolver =
            new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd, converter);
    Object[] resolvedArgs = new Object[argsToResolve.length];
    for (int argIndex = 0; argIndex < argsToResolve.length; argIndex++) {
        Object argValue = argsToResolve[argIndex];
        MethodParameter methodParam = MethodParameter.forMethodOrConstructor(methodOrCtor, argIndex);
        GenericTypeResolver.resolveParameterType(methodParam, methodOrCtor.getDeclaringClass());
        if (argValue instanceof AutowiredArgumentMarker) {
            argValue = resolveAutowiredArgument(methodParam, beanName, null, converter);
        }
        else if (argValue instanceof BeanMetadataElement) {
            argValue = valueResolver.resolveValueIfNecessary("constructor argument", argValue);
        }
        else if (argValue instanceof String) {
            argValue = this.beanFactory.evaluateBeanDefinitionString((String) argValue, mbd);
        }
        Class<?> paramType = paramTypes[argIndex];
        try {
            resolvedArgs[argIndex] = converter.convertIfNecessary(argValue, paramType, methodParam);
        }
        catch (TypeMismatchException ex) {
            String methodType = (methodOrCtor instanceof Constructor ? "constructor" : "factory method");
            throw new UnsatisfiedDependencyException(
                    mbd.getResourceDescription(), beanName, argIndex, paramType,
                    "Could not convert " + methodType + " argument value of type [" +
                    ObjectUtils.nullSafeClassName(argValue) +
                    "] to required type [" + paramType.getName() + "]: " + ex.getMessage());
        }
    }
    return resolvedArgs;
}
项目:spring4-understanding    文件:DefaultListableBeanFactoryTests.java   
/**
 * Verifies that a dependency on a {@link FactoryBean} can <strong>not</strong>
 * be autowired <em>by name</em>, as &amp; is an illegal character in
 * Java method names. In other words, you can't name a method
 * {@code set&amp;FactoryBean(...)}.
 */
@Test(expected = TypeMismatchException.class)
public void testAutowireBeanWithFactoryBeanByName() {
    DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
    RootBeanDefinition bd = new RootBeanDefinition(LazyInitFactory.class);
    lbf.registerBeanDefinition("factoryBean", bd);
    LazyInitFactory factoryBean = (LazyInitFactory) lbf.getBean("&factoryBean");
    assertNotNull("The FactoryBean should have been registered.", factoryBean);
    lbf.autowire(FactoryBeanDependentBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true);
}
项目:my-spring-cache-redis    文件:JndiObjectFactoryBean.java   
/**
 * Look up the JNDI object and store it.
 */
@Override
public void afterPropertiesSet() throws IllegalArgumentException, NamingException {
    super.afterPropertiesSet();

    if (this.proxyInterfaces != null || !this.lookupOnStartup || !this.cache || this.exposeAccessContext) {
        // We need to create a proxy for this...
        if (this.defaultObject != null) {
            throw new IllegalArgumentException(
                    "'defaultObject' is not supported in combination with 'proxyInterface'");
        }
        // We need a proxy and a JndiObjectTargetSource.
        this.jndiObject = JndiObjectProxyFactory.createJndiObjectProxy(this);
    }
    else {
        if (this.defaultObject != null && getExpectedType() != null &&
                !getExpectedType().isInstance(this.defaultObject)) {
            TypeConverter converter = (this.beanFactory != null ?
                    this.beanFactory.getTypeConverter() : new SimpleTypeConverter());
            try {
                this.defaultObject = converter.convertIfNecessary(this.defaultObject, getExpectedType());
            }
            catch (TypeMismatchException ex) {
                throw new IllegalArgumentException("Default object [" + this.defaultObject + "] of type [" +
                        this.defaultObject.getClass().getName() + "] is not of expected type [" +
                        getExpectedType().getName() + "] and cannot be converted either", ex);
            }
        }
        // Locate specified JNDI object.
        this.jndiObject = lookupWithFallback();
    }
}
项目:backstopper    文件:OneOffSpringFrameworkExceptionHandlerListener.java   
protected String extractPropertyName(TypeMismatchException tme) {
    if (tme instanceof MethodArgumentTypeMismatchException) {
        return ((MethodArgumentTypeMismatchException) tme).getName();
    }

    if (tme instanceof MethodArgumentConversionNotSupportedException) {
        return ((MethodArgumentConversionNotSupportedException) tme).getName();
    }

    return null;
}
项目:backstopper    文件:OneOffSpringFrameworkExceptionHandlerListener.java   
protected boolean isRequiredTypeAssignableToOneOf(TypeMismatchException tme, Class<?>... allowedClasses) {
    Class<?> desiredClass = tme.getRequiredType();
    for (Class<?> allowedClass : allowedClasses) {
        if (allowedClass.isAssignableFrom(desiredClass)) {
            return true;
        }
    }

    return false;
}
项目:backstopper    文件:OneOffSpringFrameworkExceptionHandlerListenerTest.java   
@Test
public void shouldReturnTYPE_CONVERSION_ERRORForTypeMismatchException() {
    TypeMismatchException ex = new TypeMismatchException("blah", Integer.class);
    ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex);
    validateResponse(result, true, Collections.singletonList(
        new ApiErrorWithMetadata(
            testProjectApiErrors.getTypeConversionApiError(), Pair.of("bad_property_value", (Object)"blah"),
                                                              Pair.of("required_type", (Object)"int")
        )
    ));
}
项目:backstopper    文件:OneOffSpringFrameworkExceptionHandlerListenerTest.java   
@UseDataProvider("dataProviderForExtractRequiredTypeNoInfoLeak")
@Test
public void extractRequiredTypeNoInfoLeak_works_as_expected(Class<?> requiredType, String expectedResult) {
    // given
    TypeMismatchException typeMismatchExceptionMock = mock(TypeMismatchException.class);
    doReturn(requiredType).when(typeMismatchExceptionMock).getRequiredType();

    // when
    String result = listener.extractRequiredTypeNoInfoLeak(typeMismatchExceptionMock);

    // then
    Assertions.assertThat(result).isEqualTo(expectedResult);
}
项目:backstopper    文件:OneOffSpringFrameworkExceptionHandlerListenerTest.java   
@Test
public void extractPropertyName_returns_null_for_base_TypeMismatchException() {
    // given
    TypeMismatchException exMock = mock(TypeMismatchException.class);

    // when
    String result = listener.extractPropertyName(exMock);

    // then
    Assertions.assertThat(result).isNull();
}
项目:backstopper    文件:ClientfacingErrorITest.java   
@Test
public void shouldConvertTypeMismatchExceptionToTYPE_CONVERSION_ERROR() throws Exception {
    MvcResult result = this.mockMvc.perform(get("/clientFacingErrorTestDummy/validateRequiredInteger")
            .param("someInt", "notaninteger")
    ).andReturn();

    verifyErrorResponse(result, projectApiErrors, projectApiErrors.getTypeConversionApiError(), TypeMismatchException.class);
}
项目:spring_boot    文件:ApiExceptionHandler.java   
@ExceptionHandler({NumberFormatException.class, TypeMismatchException.class})
public
@ResponseBody
ResponseBean handleCustomException(Exception ex) {
    LOGGER.error("NUMBER FORMAT EXCEPTION HANDLER ",ex);
    final ResponseBean responseBase = new ResponseBean();
    responseBase.setStatusCode(403);
    responseBase.setStatusMessage("INVALID_INPUT");
    responseBase.setSuccess(false);
    return responseBase;
}
项目:spring    文件:JndiObjectFactoryBean.java   
/**
 * Look up the JNDI object and store it.
 */
@Override
public void afterPropertiesSet() throws IllegalArgumentException, NamingException {
    super.afterPropertiesSet();

    if (this.proxyInterfaces != null || !this.lookupOnStartup || !this.cache || this.exposeAccessContext) {
        // We need to create a proxy for this...
        if (this.defaultObject != null) {
            throw new IllegalArgumentException(
                    "'defaultObject' is not supported in combination with 'proxyInterface'");
        }
        // We need a proxy and a JndiObjectTargetSource.
        this.jndiObject = JndiObjectProxyFactory.createJndiObjectProxy(this);
    }
    else {
        if (this.defaultObject != null && getExpectedType() != null &&
                !getExpectedType().isInstance(this.defaultObject)) {
            TypeConverter converter = (this.beanFactory != null ?
                    this.beanFactory.getTypeConverter() : new SimpleTypeConverter());
            try {
                this.defaultObject = converter.convertIfNecessary(this.defaultObject, getExpectedType());
            }
            catch (TypeMismatchException ex) {
                throw new IllegalArgumentException("Default object [" + this.defaultObject + "] of type [" +
                        this.defaultObject.getClass().getName() + "] is not of expected type [" +
                        getExpectedType().getName() + "] and cannot be converted either", ex);
            }
        }
        // Locate specified JNDI object.
        this.jndiObject = lookupWithFallback();
    }
}
项目:spring    文件:ConstructorResolver.java   
/**
 * Resolve the prepared arguments stored in the given bean definition.
 */
private Object[] resolvePreparedArguments(
        String beanName, RootBeanDefinition mbd, BeanWrapper bw, Member methodOrCtor, Object[] argsToResolve) {

    Class<?>[] paramTypes = (methodOrCtor instanceof Method ?
            ((Method) methodOrCtor).getParameterTypes() : ((Constructor<?>) methodOrCtor).getParameterTypes());
    TypeConverter converter = (this.beanFactory.getCustomTypeConverter() != null ?
            this.beanFactory.getCustomTypeConverter() : bw);
    BeanDefinitionValueResolver valueResolver =
            new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd, converter);
    Object[] resolvedArgs = new Object[argsToResolve.length];
    for (int argIndex = 0; argIndex < argsToResolve.length; argIndex++) {
        Object argValue = argsToResolve[argIndex];
        MethodParameter methodParam = MethodParameter.forMethodOrConstructor(methodOrCtor, argIndex);
        GenericTypeResolver.resolveParameterType(methodParam, methodOrCtor.getDeclaringClass());
        if (argValue instanceof AutowiredArgumentMarker) {
            argValue = resolveAutowiredArgument(methodParam, beanName, null, converter);
        }
        else if (argValue instanceof BeanMetadataElement) {
            argValue = valueResolver.resolveValueIfNecessary("constructor argument", argValue);
        }
        else if (argValue instanceof String) {
            argValue = this.beanFactory.evaluateBeanDefinitionString((String) argValue, mbd);
        }
        Class<?> paramType = paramTypes[argIndex];
        try {
            resolvedArgs[argIndex] = converter.convertIfNecessary(argValue, paramType, methodParam);
        }
        catch (TypeMismatchException ex) {
            throw new UnsatisfiedDependencyException(
                    mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam),
                    "Could not convert argument value of type [" + ObjectUtils.nullSafeClassName(argValue) +
                    "] to required type [" + paramType.getName() + "]: " + ex.getMessage());
        }
    }
    return resolvedArgs;
}
项目:cicada    文件:AppResponseEntityExceptionHandler.java   
@Override
protected ResponseEntity<Object> handleTypeMismatch(final TypeMismatchException ex, //
    final HttpHeaders headers, //
    final HttpStatus status, //
    final WebRequest request) {
  log.error("handleTypeMismatch:{}", ex);

  final ErrorMessage errorMessage =  //
      new ErrorMessage(AppError.OTHER_HTTP_TYPE_MISMATCH.getErrorCode(), "params.type.mismatch");
  return new ResponseEntity<Object>(errorMessage, headers, status);
}
项目:herd    文件:HerdErrorInformationExceptionHandler.java   
/**
 * Handle exceptions that result in a "bad request" status.
 */
@ExceptionHandler(value = {IllegalArgumentException.class, HttpMessageNotReadableException.class, MissingServletRequestParameterException.class,
    TypeMismatchException.class, UnsupportedEncodingException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorInformation handleBadRequestException(Exception exception)
{
    return getErrorInformation(HttpStatus.BAD_REQUEST, exception);
}