org.springframework.beans.TypeMismatchException Java Examples

The following examples show how to use org.springframework.beans.TypeMismatchException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MarshallingMessageConverter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
@Nullable
protected Object convertFromInternal(Message<?> message, Class<?> targetClass, @Nullable 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);
	}
}
 
Example #2
Source File: MvcNamespaceTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #3
Source File: MarshallingHttpMessageConverterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
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);
	try {
		converter.read(String.class, inputMessage);
		fail("Should have thrown HttpMessageNotReadableException");
	}
	catch (HttpMessageNotReadableException ex) {
		assertTrue(ex.getCause() instanceof TypeMismatchException);
	}
}
 
Example #4
Source File: DefaultListableBeanFactoryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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;
	}
}
 
Example #5
Source File: MvcNamespaceTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test(expected = TypeMismatchException.class)
public void testCustomConversionService() throws Exception {
	loadBeanDefinitions("mvc-config-custom-conversion-service.xml");

	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);
}
 
Example #6
Source File: ClassPathXmlApplicationContextTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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());
	}
}
 
Example #7
Source File: MyExceptionHandler.java    From disconf with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #8
Source File: MvcNamespaceTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test(expected = TypeMismatchException.class)
public void testCustomConversionService() throws Exception {
	loadBeanDefinitions("mvc-config-custom-conversion-service.xml");

	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);
}
 
Example #9
Source File: RestExceptionHandler.java    From java-starthere with MIT License 6 votes vote down vote up
@Override
protected ResponseEntity<Object> handleTypeMismatch(TypeMismatchException ex,
                                                    HttpHeaders headers,
                                                    HttpStatus status,
                                                    WebRequest request)
{
    ErrorDetail errorDetail = new ErrorDetail();
    errorDetail.setTimestamp(new Date().getTime());
    errorDetail.setStatus(HttpStatus.BAD_REQUEST.value());
    errorDetail.setTitle(ex.getPropertyName() + " Parameter Type Mismatch");
    errorDetail.setDetail(ex.getMessage());
    errorDetail.setDeveloperMessage(request.getDescription(true));

    return new ResponseEntity<>(errorDetail,
                                headers,
                                HttpStatus.NOT_FOUND);
}
 
Example #10
Source File: TypeMismatchWebErrorHandlerTest.java    From errors-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
private TypeMismatchException mismatch(String name, String value, Class<?> type) {
    TypeMismatchException exception = mock(TypeMismatchException.class);
    when(exception.getPropertyName()).thenReturn(name);
    when(exception.getPropertyName()).thenReturn(name);
    doReturn(type).when(exception).getRequiredType();
    when(exception.getValue()).thenReturn(value);

    return exception;
}
 
Example #11
Source File: PetControllerExceptionHandler.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * The handleIdTypeMismatch method creates a response when the pet ID is invalid
 *
 * @param exception TypeMismatchException
 * @return 400 and the message 'The pet ID is invalid: it is not an integer'
 */
@ExceptionHandler(TypeMismatchException.class)
public ResponseEntity<ApiMessageView> handleIdTypeMismatch(TypeMismatchException exception) {
    Message message = messageService.createMessage("org.zowe.apiml.sampleservice.api.petIdTypeMismatch", exception.getValue());

    return ResponseEntity
        .status(HttpStatus.BAD_REQUEST)
        .contentType(MediaType.APPLICATION_JSON_UTF8)
        .body(message.mapToView());
}
 
Example #12
Source File: ConstructorResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Resolve the prepared arguments stored in the given bean definition.
 */
private Object[] resolvePreparedArguments(
		String beanName, RootBeanDefinition mbd, BeanWrapper bw, Member methodOrCtor, Object[] argsToResolve) {

	TypeConverter customConverter = this.beanFactory.getCustomTypeConverter();
	TypeConverter converter = (customConverter != null ? customConverter : bw);
	BeanDefinitionValueResolver valueResolver =
			new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd, converter);
	Class<?>[] paramTypes = (methodOrCtor instanceof Method ?
			((Method) methodOrCtor).getParameterTypes() : ((Constructor<?>) methodOrCtor).getParameterTypes());

	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;
}
 
Example #13
Source File: BaseController.java    From j360-dubbo-app-all with Apache License 2.0 5 votes vote down vote up
@ExceptionHandler({ServletRequestBindingException.class,
        HttpMediaTypeNotAcceptableException.class,
        HttpMediaTypeNotSupportedException.class,
        HttpMessageNotReadableException.class,
        HttpRequestMethodNotSupportedException.class,
        MissingServletRequestParameterException.class,
        MissingServletRequestPartException.class,
        TypeMismatchException.class
})
@ResponseBody
public ApiResponse ServletRequestBindingExHandler(Exception ex) {
    return createExResult(new ValidationException(ex));
}
 
Example #14
Source File: ConstructorResolver.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #15
Source File: CustomRestExceptionHandler.java    From xxproject with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #16
Source File: OneOffSpringCommonFrameworkExceptionHandlerListener.java    From backstopper with Apache License 2.0 5 votes vote down vote up
protected String extractPropertyName(TypeMismatchException tme) {
    if (tme instanceof MethodArgumentTypeMismatchException) {
        return ((MethodArgumentTypeMismatchException) tme).getName();
    }

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

    return null;
}
 
Example #17
Source File: MarshallingHttpMessageConverter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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);
	}
}
 
Example #18
Source File: BackstopperSpringWebFluxComponentTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@GetMapping(path = TYPE_MISMATCH_WITH_UNEXPECTED_STATUS_ENDPOINT)
@ResponseBody
public String typeMismatchWithUnexpectedStatusEndpoint() {
    throw new ResponseStatusException(
        HttpStatus.FORBIDDEN,
        "Synthetic ResponseStatusException with TypeMismatchException cause and unexpected status code",
        new TypeMismatchException("doesNotMatter", int.class)
    );
}
 
Example #19
Source File: BackstopperSpringWebFluxComponentTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void verify_TYPE_CONVERSION_ERROR_is_thrown_when_framework_cannot_convert_type() {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(SERVER_PORT)
            .log().all()
            .when()
            .queryParam("requiredQueryParamValue", "not-an-integer")
            .get(INT_QUERY_PARAM_REQUIRED_ENDPOINT)
            .then()
            .log().all()
            .extract();

    ApiError expectedApiError = new ApiErrorWithMetadata(
        SampleCoreApiError.TYPE_CONVERSION_ERROR,
        // We can't expect the bad_property_name=requiredQueryParamValue metadata like we do in Spring Web MVC,
        //      because Spring WebFlux doesn't add it to the TypeMismatchException cause.
        MapBuilder.builder("bad_property_value", (Object) "not-an-integer")
                  .put("required_type", "int")
                  .build()
    );

    verifyErrorReceived(response, expectedApiError);
    ServerWebInputException ex = verifyResponseStatusExceptionSeenByBackstopper(
        ServerWebInputException.class, 400
    );
    TypeMismatchException tme = verifyExceptionHasCauseOfType(ex, TypeMismatchException.class);
    verifyHandlingResult(
        expectedApiError,
        Pair.of("exception_message", quotesToApostrophes(ex.getMessage())),
        Pair.of("method_parameter", ex.getMethodParameter().toString()),
        Pair.of("bad_property_name", tme.getPropertyName()),
        Pair.of("bad_property_value", tme.getValue().toString()),
        Pair.of("required_type", tme.getRequiredType().toString())
    );
}
 
Example #20
Source File: MarshallingHttpMessageConverter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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);
	}
}
 
Example #21
Source File: TypeMismatchWebErrorHandlerTest.java    From errors-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
private Object[] paramsForCanHandle() {
    return p(
        p(mock(TypeMismatchException.class), true),
        p(new RuntimeException(), false),
        p(null, false)
    );
}
 
Example #22
Source File: JndiObjectFactoryBean.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
	}
}
 
Example #23
Source File: TypeMismatchWebErrorHandler.java    From errors-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
static List<Argument> getArguments(TypeMismatchException mismatchException) {
    List<Argument> arguments = new ArrayList<>();
    arguments.add(arg("property", getPropertyName(mismatchException)));
    arguments.add(arg("invalid", mismatchException.getValue()));
    Class<?> requiredType = mismatchException.getRequiredType();
    if (requiredType != null) {
        arguments.add(arg("expected", Classes.getClassName(requiredType)));
    }

    return arguments;
}
 
Example #24
Source File: TypeMismatchWebErrorHandler.java    From errors-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
/**
 * Cast the given exception to {@link TypeMismatchException} and return a handled exception
 * instance by extracting the error code and exposing appropriate arguments.
 *
 * @param exception The exception to handle.
 * @return The handled exception instance.
 */
@NonNull
@Override
public HandledException handle(Throwable exception) {
    TypeMismatchException mismatchException = (TypeMismatchException) exception;
    String errorCode = getErrorCode(mismatchException);
    List<Argument> arguments = getArguments(mismatchException);

    return new HandledException(errorCode, BAD_REQUEST, singletonMap(errorCode, arguments));
}
 
Example #25
Source File: DefaultListableBeanFactoryTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #26
Source File: OneOffSpringCommonFrameworkExceptionHandlerListenerTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void extractPropertyName_returns_null_for_base_TypeMismatchException() {
    // given
    TypeMismatchException exMock = mock(TypeMismatchException.class);

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

    // then
    assertThat(result).isNull();
}
 
Example #27
Source File: DefaultListableBeanFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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);
}
 
Example #28
Source File: ExceptionsHandler.java    From WeBASE-Node-Manager with Apache License 2.0 5 votes vote down vote up
/**
 * parameter exception:TypeMismatchException
 */
@ResponseBody
@ExceptionHandler(value = TypeMismatchException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public BaseResponse typeMismatchExceptionHandler(TypeMismatchException ex) {
    log.warn("catch typeMismatchException", ex);

    RetCode retCode = new RetCode(ConstantCode.PARAM_EXCEPTION.getCode(), ex.getMessage());
    BaseResponse bre = new BaseResponse(retCode);
    log.warn("typeMismatchException return:{}", JsonTools.toJSONString(bre));
    return bre;
}
 
Example #29
Source File: ResponseStatusExceptionResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test // SPR-12903
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);
	assertResolved(mav, 410, "gone.reason");
}
 
Example #30
Source File: JndiObjectFactoryBean.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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();
	}
}