本文整理汇总了Java中org.springframework.beans.TypeMismatchException类的典型用法代码示例。如果您正苦于以下问题:Java TypeMismatchException类的具体用法?Java TypeMismatchException怎么用?Java TypeMismatchException使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
TypeMismatchException类属于org.springframework.beans包,在下文中一共展示了TypeMismatchException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testCustomConversionService
import org.springframework.beans.TypeMismatchException; //导入依赖的package包/类
@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);
}
示例2: canConvert
import org.springframework.beans.TypeMismatchException; //导入依赖的package包/类
public boolean canConvert(Object source, ReifiedType targetType) {
Class<?> required = targetType.getRawClass();
try {
getConverter().convertIfNecessary(source, required);
return true;
} catch (TypeMismatchException ex) {
return false;
}
}
示例3: afterPropertiesSet
import org.springframework.beans.TypeMismatchException; //导入依赖的package包/类
/**
* 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();
}
}
示例4: readFromSource
import org.springframework.beans.TypeMismatchException; //导入依赖的package包/类
@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);
}
}
示例5: handleTypeMismatch
import org.springframework.beans.TypeMismatchException; //导入依赖的package包/类
@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());
}
示例6: handleTypeMismatch
import org.springframework.beans.TypeMismatchException; //导入依赖的package包/类
@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);
}
示例7: testContextWithInvalidValueType
import org.springframework.beans.TypeMismatchException; //导入依赖的package包/类
@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());
}
}
示例8: nestedException
import org.springframework.beans.TypeMismatchException; //导入依赖的package包/类
@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());
}
示例9: resolvePreparedArguments
import org.springframework.beans.TypeMismatchException; //导入依赖的package包/类
/**
* 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;
}
示例10: convertIfNecessary
import org.springframework.beans.TypeMismatchException; //导入依赖的package包/类
@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;
}
}
示例11: getTaskUtil
import org.springframework.beans.TypeMismatchException; //导入依赖的package包/类
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;
}
示例12: testCustomConversionService
import org.springframework.beans.TypeMismatchException; //导入依赖的package包/类
@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);
}
示例13: getParamErrors
import org.springframework.beans.TypeMismatchException; //导入依赖的package包/类
/**
* 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);
}
示例14: handleTypeMismatch
import org.springframework.beans.TypeMismatchException; //导入依赖的package包/类
@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());
}
示例15: testMappingNullValue
import org.springframework.beans.TypeMismatchException; //导入依赖的package包/类
@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);
}