@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); }
@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()); } }
@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; } }
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; }
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; }
@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); } }
@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); }
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; }
/** * 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); }
/** * 400错误 */ @ResponseBody @ExceptionHandler({ TypeMismatchException.class }) public ResultResponse typeMismatchExceptionHandler(TypeMismatchException ex) { logger.error(ResultMessage.F4000.getMessage(), ex); return resultResponse.failure(ResultMessage.F4000, ex.getMessage()); }
public boolean canConvert(Object source, ReifiedType targetType) { Class<?> required = targetType.getRawClass(); try { getConverter().convertIfNecessary(source, required); return true; } catch (TypeMismatchException ex) { return false; } }
/** * 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(); } }
/** * 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; }
@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); } }
@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; }
@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()); }
@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); }
@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); } }
@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()); }
@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()); }
@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); }
@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); }
/** * Verifies that a dependency on a {@link FactoryBean} can <strong>not</strong> * be autowired <em>by name</em>, as & is an illegal character in * Java method names. In other words, you can't name a method * {@code set&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); }
protected String extractPropertyName(TypeMismatchException tme) { if (tme instanceof MethodArgumentTypeMismatchException) { return ((MethodArgumentTypeMismatchException) tme).getName(); } if (tme instanceof MethodArgumentConversionNotSupportedException) { return ((MethodArgumentConversionNotSupportedException) tme).getName(); } return null; }
protected boolean isRequiredTypeAssignableToOneOf(TypeMismatchException tme, Class<?>... allowedClasses) { Class<?> desiredClass = tme.getRequiredType(); for (Class<?> allowedClass : allowedClasses) { if (allowedClass.isAssignableFrom(desiredClass)) { return true; } } return false; }
@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") ) )); }
@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); }
@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(); }
@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); }
@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; }
/** * 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; }
@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); }
/** * 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); }