Java Code Examples for org.springframework.beans.DirectFieldAccessor#getPropertyValue()

The following examples show how to use org.springframework.beans.DirectFieldAccessor#getPropertyValue() . 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: InMemoryWebSessionStoreTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void expirationCheckPeriod() {

	DirectFieldAccessor accessor = new DirectFieldAccessor(this.store);
	Map<?,?> sessions = (Map<?, ?>) accessor.getPropertyValue("sessions");
	assertNotNull(sessions);

	// Create 100 sessions
	IntStream.range(0, 100).forEach(i -> insertSession());
	assertEquals(100, sessions.size());

	// Force a new clock (31 min later), don't use setter which would clean expired sessions
	accessor.setPropertyValue("clock", Clock.offset(this.store.getClock(), Duration.ofMinutes(31)));
	assertEquals(100, sessions.size());

	// Create 1 more which forces a time-based check (clock moved forward)
	insertSession();
	assertEquals(1, sessions.size());
}
 
Example 2
Source File: MvcNamespaceTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testAsyncSupportOptions() throws Exception {
	loadBeanDefinitions("mvc-config-async-support.xml");

	RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
	assertNotNull(adapter);

	DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(adapter);
	assertEquals(ConcurrentTaskExecutor.class, fieldAccessor.getPropertyValue("taskExecutor").getClass());
	assertEquals(2500L, fieldAccessor.getPropertyValue("asyncRequestTimeout"));

	CallableProcessingInterceptor[] callableInterceptors =
			(CallableProcessingInterceptor[]) fieldAccessor.getPropertyValue("callableInterceptors");
	assertEquals(1, callableInterceptors.length);

	DeferredResultProcessingInterceptor[] deferredResultInterceptors =
			(DeferredResultProcessingInterceptor[]) fieldAccessor.getPropertyValue("deferredResultInterceptors");
	assertEquals(1, deferredResultInterceptors.length);
}
 
Example 3
Source File: MvcNamespaceTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testAsyncSupportOptions() throws Exception {
	loadBeanDefinitions("mvc-config-async-support.xml");

	RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
	assertNotNull(adapter);

	DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(adapter);
	assertEquals(ConcurrentTaskExecutor.class, fieldAccessor.getPropertyValue("taskExecutor").getClass());
	assertEquals(2500L, fieldAccessor.getPropertyValue("asyncRequestTimeout"));

	CallableProcessingInterceptor[] callableInterceptors =
			(CallableProcessingInterceptor[]) fieldAccessor.getPropertyValue("callableInterceptors");
	assertEquals(1, callableInterceptors.length);

	DeferredResultProcessingInterceptor[] deferredResultInterceptors =
			(DeferredResultProcessingInterceptor[]) fieldAccessor.getPropertyValue("deferredResultInterceptors");
	assertEquals(1, deferredResultInterceptors.length);
}
 
Example 4
Source File: MvcNamespaceTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testAsyncSupportOptions() throws Exception {
	loadBeanDefinitions("mvc-config-async-support.xml", 15);

	RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
	assertNotNull(adapter);

	DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(adapter);
	assertEquals(ConcurrentTaskExecutor.class, fieldAccessor.getPropertyValue("taskExecutor").getClass());
	assertEquals(2500L, fieldAccessor.getPropertyValue("asyncRequestTimeout"));

	CallableProcessingInterceptor[] callableInterceptors =
			(CallableProcessingInterceptor[]) fieldAccessor.getPropertyValue("callableInterceptors");
	assertEquals(1, callableInterceptors.length);

	DeferredResultProcessingInterceptor[] deferredResultInterceptors =
			(DeferredResultProcessingInterceptor[]) fieldAccessor.getPropertyValue("deferredResultInterceptors");
	assertEquals(1, deferredResultInterceptors.length);
}
 
Example 5
Source File: AbstractTyrusRequestUpgradeStrategy.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public Object createdEndpoint(ServerEndpointRegistration registration, ComponentProviderService provider,
		WebSocketContainer container, TyrusWebSocketEngine engine) throws DeploymentException {

	DirectFieldAccessor accessor = new DirectFieldAccessor(engine);
	Object sessionListener = accessor.getPropertyValue("sessionListener");
	Object clusterContext = accessor.getPropertyValue("clusterContext");
	try {
		if (constructorWithBooleanArgument) {
			// Tyrus 1.11+
			return constructor.newInstance(registration.getEndpoint(), registration, provider, container,
					"/", registration.getConfigurator(), sessionListener, clusterContext, null, Boolean.TRUE);
		}
		else {
			return constructor.newInstance(registration.getEndpoint(), registration, provider, container,
					"/", registration.getConfigurator(), sessionListener, clusterContext, null);
		}
	}
	catch (Exception ex) {
		throw new HandshakeFailureException("Failed to register " + registration, ex);
	}
}
 
Example 6
Source File: WebMvcConfigurationSupportTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void requestMappingHandlerAdapter() throws Exception {
	ApplicationContext context = initContext(WebConfig.class);
	RequestMappingHandlerAdapter adapter = context.getBean(RequestMappingHandlerAdapter.class);
	List<HttpMessageConverter<?>> converters = adapter.getMessageConverters();
	assertEquals(9, converters.size());
	for(HttpMessageConverter<?> converter : converters) {
		if (converter instanceof AbstractJackson2HttpMessageConverter) {
			ObjectMapper objectMapper = ((AbstractJackson2HttpMessageConverter)converter).getObjectMapper();
			assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
			assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
			assertFalse(objectMapper.getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
			if (converter instanceof MappingJackson2XmlHttpMessageConverter) {
				assertEquals(XmlMapper.class, objectMapper.getClass());
			}
		}
	}

	ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();
	assertNotNull(initializer);

	ConversionService conversionService = initializer.getConversionService();
	assertNotNull(conversionService);
	assertTrue(conversionService instanceof FormattingConversionService);

	Validator validator = initializer.getValidator();
	assertNotNull(validator);
	assertTrue(validator instanceof LocalValidatorFactoryBean);

	DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(adapter);
	@SuppressWarnings("unchecked")
	List<Object> bodyAdvice = (List<Object>) fieldAccessor.getPropertyValue("requestResponseBodyAdvice");
	assertEquals(2, bodyAdvice.size());
	assertEquals(JsonViewRequestBodyAdvice.class, bodyAdvice.get(0).getClass());
	assertEquals(JsonViewResponseBodyAdvice.class, bodyAdvice.get(1).getClass());
}
 
Example 7
Source File: ViewResolverRegistryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void checkPropertyValues(ViewResolver resolver, Object... nameValuePairs) {
	DirectFieldAccessor accessor =  new DirectFieldAccessor(resolver);
	for (int i = 0; i < nameValuePairs.length ; i++, i++) {
		Object expected = nameValuePairs[i + 1];
		Object actual = accessor.getPropertyValue((String) nameValuePairs[i]);
		assertEquals(expected, actual);
	}
}
 
Example 8
Source File: KafkaBinderTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
private KafkaConsumer getKafkaConsumer(Binding binding) {
	DirectFieldAccessor bindingAccessor = new DirectFieldAccessor(binding);
	KafkaMessageDrivenChannelAdapter adapter = (KafkaMessageDrivenChannelAdapter) bindingAccessor
			.getPropertyValue("lifecycle");
	DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter);
	ConcurrentMessageListenerContainer messageListenerContainer = (ConcurrentMessageListenerContainer) adapterAccessor
			.getPropertyValue("messageListenerContainer");
	DirectFieldAccessor containerAccessor = new DirectFieldAccessor(
			messageListenerContainer);
	DefaultKafkaConsumerFactory consumerFactory = (DefaultKafkaConsumerFactory) containerAccessor
			.getPropertyValue("consumerFactory");
	return (KafkaConsumer) consumerFactory.createConsumer();
}
 
Example 9
Source File: GroovyMarkupViewTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void customTemplateEngine() throws Exception {
	GroovyMarkupView view = new GroovyMarkupView();
	view.setTemplateEngine(new TestTemplateEngine());
	view.setApplicationContext(this.webAppContext);

	DirectFieldAccessor accessor = new DirectFieldAccessor(view);
	TemplateEngine engine = (TemplateEngine) accessor.getPropertyValue("engine");
	assertNotNull(engine);
	assertEquals(TestTemplateEngine.class, engine.getClass());
}
 
Example 10
Source File: GroovyMarkupViewTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void detectTemplateEngine() throws Exception {

	GroovyMarkupView view = new GroovyMarkupView();

	view.setTemplateEngine(new TestTemplateEngine());
	view.setApplicationContext(this.webAppContext);

	DirectFieldAccessor accessor = new DirectFieldAccessor(view);
	TemplateEngine engine = (TemplateEngine) accessor.getPropertyValue("engine");
	assertNotNull(engine);
	assertEquals(TestTemplateEngine.class, engine.getClass());
}
 
Example 11
Source File: EntityModel.java    From webanno with Apache License 2.0 5 votes vote down vote up
private void analyze(T aObject)
{
    if (aObject != null) {
        entityClass = HibernateProxyHelper.getClassWithoutInitializingProxy(aObject);

        String idProperty = null;
        Metamodel metamodel = getEntityManager().getMetamodel();
        EntityType entity = metamodel.entity(entityClass);
        Set<SingularAttribute> singularAttributes = entity.getSingularAttributes();
        for (SingularAttribute singularAttribute : singularAttributes) {
            if (singularAttribute.isId()) {
                idProperty = singularAttribute.getName();
                break;
            }
        }
        if (idProperty == null) {
            throw new RuntimeException("id field not found");
        }

        DirectFieldAccessor accessor = new DirectFieldAccessor(aObject);
        id = (Number) accessor.getPropertyValue(idProperty);
    }
    else {
        entityClass = null;
        id = null;
    }
}
 
Example 12
Source File: SubProtocolWebSocketHandlerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void checkSession() throws Exception {
	TestWebSocketSession session1 = new TestWebSocketSession("id1");
	TestWebSocketSession session2 = new TestWebSocketSession("id2");
	session1.setOpen(true);
	session2.setOpen(true);
	session1.setAcceptedProtocol("v12.stomp");
	session2.setAcceptedProtocol("v12.stomp");

	this.webSocketHandler.setProtocolHandlers(Arrays.asList(this.stompHandler));
	this.webSocketHandler.afterConnectionEstablished(session1);
	this.webSocketHandler.afterConnectionEstablished(session2);

	DirectFieldAccessor handlerAccessor = new DirectFieldAccessor(this.webSocketHandler);
	Map<String, ?> map = (Map<String, ?>) handlerAccessor.getPropertyValue("sessions");
	DirectFieldAccessor session1Accessor = new DirectFieldAccessor(map.get("id1"));
	DirectFieldAccessor session2Accessor = new DirectFieldAccessor(map.get("id2"));

	long sixtyOneSecondsAgo = System.currentTimeMillis() - 61 * 1000;
	handlerAccessor.setPropertyValue("lastSessionCheckTime", sixtyOneSecondsAgo);
	session1Accessor.setPropertyValue("createTime", sixtyOneSecondsAgo);
	session2Accessor.setPropertyValue("createTime", sixtyOneSecondsAgo);

	this.webSocketHandler.start();
	this.webSocketHandler.handleMessage(session1, new TextMessage("foo"));

	assertTrue(session1.isOpen());
	assertNull(session1.getCloseStatus());

	assertFalse(session2.isOpen());
	assertEquals(CloseStatus.SESSION_NOT_RELIABLE, session2.getCloseStatus());

	assertNotEquals("lastSessionCheckTime not updated", sixtyOneSecondsAgo,
			handlerAccessor.getPropertyValue("lastSessionCheckTime"));
}
 
Example 13
Source File: ViewResolverRegistryTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private void checkPropertyValues(ViewResolver resolver, Object... nameValuePairs) {
	DirectFieldAccessor accessor =  new DirectFieldAccessor(resolver);
	for (int i = 0; i < nameValuePairs.length ; i++, i++) {
		Object expected = nameValuePairs[i + 1];
		Object actual = accessor.getPropertyValue((String) nameValuePairs[i]);
		assertEquals(expected, actual);
	}
}
 
Example 14
Source File: GroovyMarkupViewTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void customTemplateEngine() throws Exception {

	GroovyMarkupView view = new GroovyMarkupView();
	view.setTemplateEngine(new TestTemplateEngine());
	view.setApplicationContext(this.webAppContext);

	DirectFieldAccessor accessor = new DirectFieldAccessor(view);
	TemplateEngine engine = (TemplateEngine) accessor.getPropertyValue("engine");
	assertNotNull(engine);
	assertEquals(TestTemplateEngine.class, engine.getClass());
}
 
Example 15
Source File: WebMvcConfigurationSupportTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void handlerExceptionResolver() throws Exception {
	ApplicationContext context = initContext(WebConfig.class);
	HandlerExceptionResolverComposite compositeResolver =
			context.getBean("handlerExceptionResolver", HandlerExceptionResolverComposite.class);

	assertEquals(0, compositeResolver.getOrder());
	List<HandlerExceptionResolver> expectedResolvers = compositeResolver.getExceptionResolvers();

	assertEquals(ExceptionHandlerExceptionResolver.class, expectedResolvers.get(0).getClass());
	assertEquals(ResponseStatusExceptionResolver.class, expectedResolvers.get(1).getClass());
	assertEquals(DefaultHandlerExceptionResolver.class, expectedResolvers.get(2).getClass());

	ExceptionHandlerExceptionResolver eher = (ExceptionHandlerExceptionResolver) expectedResolvers.get(0);
	assertNotNull(eher.getApplicationContext());

	DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(eher);
	List<Object> interceptors = (List<Object>) fieldAccessor.getPropertyValue("responseBodyAdvice");
	assertEquals(1, interceptors.size());
	assertEquals(JsonViewResponseBodyAdvice.class, interceptors.get(0).getClass());

	LocaleContextHolder.setLocale(Locale.ENGLISH);
	try {
		ResponseStatusExceptionResolver rser = (ResponseStatusExceptionResolver) expectedResolvers.get(1);
		MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
		MockHttpServletResponse response = new MockHttpServletResponse();
		rser.resolveException(request, response, context.getBean(TestController.class), new UserAlreadyExistsException());
		assertEquals("User already exists!", response.getErrorMessage());
	}
	finally {
		LocaleContextHolder.resetLocaleContext();
	}
}
 
Example 16
Source File: RabbitBinderModuleTests.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 4 votes vote down vote up
@Test
public void testParentConnectionFactoryInheritedByDefault() throws Exception {
	context = new SpringApplicationBuilder(SimpleProcessor.class)
			.web(WebApplicationType.NONE).run("--server.port=0",
					"--spring.cloud.stream.rabbit.binder.connection-name-prefix=foo",
					"--spring.cloud.stream.rabbit.bindings.input.consumer.single-active-consumer=true");
	BinderFactory binderFactory = context.getBean(BinderFactory.class);
	Binder<?, ?, ?> binder = binderFactory.getBinder(null, MessageChannel.class);
	assertThat(binder).isInstanceOf(RabbitMessageChannelBinder.class);
	DirectFieldAccessor binderFieldAccessor = new DirectFieldAccessor(binder);
	CachingConnectionFactory binderConnectionFactory = (CachingConnectionFactory) binderFieldAccessor
			.getPropertyValue("connectionFactory");
	assertThat(binderConnectionFactory).isInstanceOf(CachingConnectionFactory.class);
	ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class);
	assertThat(binderConnectionFactory).isSameAs(connectionFactory);

	CompositeHealthContributor bindersHealthIndicator = context
			.getBean("bindersHealthContributor", CompositeHealthContributor.class);

	assertThat(bindersHealthIndicator).isNotNull();

	RabbitHealthIndicator indicator = (RabbitHealthIndicator) bindersHealthIndicator.getContributor("rabbit");
	assertThat(indicator).isNotNull();
	assertThat(indicator.health().getStatus())
			.isEqualTo(Status.UP);

	ConnectionFactory publisherConnectionFactory = binderConnectionFactory
			.getPublisherConnectionFactory();
	assertThat(TestUtils.getPropertyValue(publisherConnectionFactory,
			"connection.target")).isNull();
	DirectChannel checkPf = new DirectChannel();
	Binding<MessageChannel> binding = ((RabbitMessageChannelBinder) binder)
			.bindProducer("checkPF", checkPf,
					new ExtendedProducerProperties<>(new RabbitProducerProperties()));
	checkPf.send(new GenericMessage<>("foo".getBytes()));
	binding.unbind();
	assertThat(TestUtils.getPropertyValue(publisherConnectionFactory,
			"connection.target")).isNotNull();

	CachingConnectionFactory cf = this.context
			.getBean(CachingConnectionFactory.class);
	ConnectionNameStrategy cns = TestUtils.getPropertyValue(cf,
			"connectionNameStrategy", ConnectionNameStrategy.class);
	assertThat(cns.obtainNewConnectionName(cf)).isEqualTo("foo#2");
	new RabbitAdmin(rabbitTestSupport.getResource()).deleteExchange("checkPF");
	checkCustomizedArgs();
	binderConnectionFactory.resetConnection();
	binderConnectionFactory.createConnection();
	checkCustomizedArgs();
}
 
Example 17
Source File: RabbitBinderModuleTests.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 4 votes vote down vote up
@Test
public void testParentConnectionFactoryNotInheritedByCustomizedBindersAndProducerRetryBootProperties() {
	List<String> params = new ArrayList<>();
	params.add("--spring.cloud.stream.input.binder=custom");
	params.add("--spring.cloud.stream.output.binder=custom");
	params.add("--spring.cloud.stream.binders.custom.type=rabbit");
	params.add("--spring.cloud.stream.binders.custom.environment.foo=bar");
	params.add("--server.port=0");
	params.add("--spring.rabbitmq.template.retry.enabled=true");
	params.add("--spring.rabbitmq.template.retry.maxAttempts=2");
	params.add("--spring.rabbitmq.template.retry.initial-interval=1000");
	params.add("--spring.rabbitmq.template.retry.multiplier=1.1");
	params.add("--spring.rabbitmq.template.retry.max-interval=3000");
	context = new SpringApplicationBuilder(SimpleProcessor.class)
			.web(WebApplicationType.NONE)
			.run(params.toArray(new String[params.size()]));
	BinderFactory binderFactory = context.getBean(BinderFactory.class);
	// @checkstyle:off
	@SuppressWarnings("unchecked")
	Binder<MessageChannel, ExtendedConsumerProperties<RabbitConsumerProperties>, ExtendedProducerProperties<RabbitProducerProperties>> binder = (Binder<MessageChannel, ExtendedConsumerProperties<RabbitConsumerProperties>, ExtendedProducerProperties<RabbitProducerProperties>>) binderFactory
			.getBinder(null, MessageChannel.class);
	// @checkstyle:on
	assertThat(binder).isInstanceOf(RabbitMessageChannelBinder.class);
	DirectFieldAccessor binderFieldAccessor = new DirectFieldAccessor(binder);
	ConnectionFactory binderConnectionFactory = (ConnectionFactory) binderFieldAccessor
			.getPropertyValue("connectionFactory");
	ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class);
	assertThat(binderConnectionFactory).isNotSameAs(connectionFactory);
	CompositeHealthContributor bindersHealthIndicator = context
			.getBean("bindersHealthContributor", CompositeHealthContributor.class);
	assertThat(bindersHealthIndicator);

	RabbitHealthIndicator indicator = (RabbitHealthIndicator) bindersHealthIndicator.getContributor("custom");
	assertThat(indicator).isNotNull();
	assertThat(indicator.health().getStatus()).isEqualTo(Status.UP);
	String name = UUID.randomUUID().toString();
	Binding<MessageChannel> binding = binder.bindProducer(name, new DirectChannel(),
			new ExtendedProducerProperties<>(new RabbitProducerProperties()));
	RetryTemplate template = TestUtils.getPropertyValue(binding,
			"lifecycle.amqpTemplate.retryTemplate", RetryTemplate.class);
	assertThat(template).isNotNull();
	SimpleRetryPolicy retryPolicy = TestUtils.getPropertyValue(template,
			"retryPolicy", SimpleRetryPolicy.class);
	ExponentialBackOffPolicy backOff = TestUtils.getPropertyValue(template,
			"backOffPolicy", ExponentialBackOffPolicy.class);
	assertThat(retryPolicy.getMaxAttempts()).isEqualTo(2);
	assertThat(backOff.getInitialInterval()).isEqualTo(1000L);
	assertThat(backOff.getMultiplier()).isEqualTo(1.1);
	assertThat(backOff.getMaxInterval()).isEqualTo(3000L);
	binding.unbind();
	new RabbitAdmin(rabbitTestSupport.getResource()).deleteExchange(name);
	context.close();
}
 
Example 18
Source File: WebMvcConfigurationSupportExtensionTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void requestMappingHandlerAdapter() throws Exception {
	RequestMappingHandlerAdapter adapter = this.config.requestMappingHandlerAdapter();

	// ConversionService
	String actual = this.config.mvcConversionService().convert(new TestBean(), String.class);
	assertEquals("converted", actual);

	// Message converters
	assertEquals(2, adapter.getMessageConverters().size());
	assertEquals(StringHttpMessageConverter.class, adapter.getMessageConverters().get(0).getClass());
	assertEquals(MappingJackson2HttpMessageConverter.class, adapter.getMessageConverters().get(1).getClass());
	ObjectMapper objectMapper = ((MappingJackson2HttpMessageConverter)adapter.getMessageConverters().get(1)).getObjectMapper();
	assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
	assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
	assertFalse(objectMapper.getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));

	DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(adapter);

	// Custom argument resolvers and return value handlers
	List<HandlerMethodArgumentResolver> argResolvers =
		(List<HandlerMethodArgumentResolver>) fieldAccessor.getPropertyValue("customArgumentResolvers");
	assertEquals(1, argResolvers.size());

	List<HandlerMethodReturnValueHandler> handlers =
		(List<HandlerMethodReturnValueHandler>) fieldAccessor.getPropertyValue("customReturnValueHandlers");
	assertEquals(1, handlers.size());

	// Async support options
	assertEquals(ConcurrentTaskExecutor.class, fieldAccessor.getPropertyValue("taskExecutor").getClass());
	assertEquals(2500L, fieldAccessor.getPropertyValue("asyncRequestTimeout"));

	CallableProcessingInterceptor[] callableInterceptors =
			(CallableProcessingInterceptor[]) fieldAccessor.getPropertyValue("callableInterceptors");
	assertEquals(1, callableInterceptors.length);

	DeferredResultProcessingInterceptor[] deferredResultInterceptors =
			(DeferredResultProcessingInterceptor[]) fieldAccessor.getPropertyValue("deferredResultInterceptors");
	assertEquals(1, deferredResultInterceptors.length);

	assertEquals(false, fieldAccessor.getPropertyValue("ignoreDefaultModelOnRedirect"));
}
 
Example 19
Source File: WebMvcConfigurationSupportExtensionTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void requestMappingHandlerAdapter() throws Exception {
	RequestMappingHandlerAdapter adapter = this.config.requestMappingHandlerAdapter();

	// ConversionService
	String actual = this.config.mvcConversionService().convert(new TestBean(), String.class);
	assertEquals("converted", actual);

	// Message converters
	List<HttpMessageConverter<?>> converters = adapter.getMessageConverters();
	assertEquals(2, converters.size());
	assertEquals(StringHttpMessageConverter.class, converters.get(0).getClass());
	assertEquals(MappingJackson2HttpMessageConverter.class, converters.get(1).getClass());
	ObjectMapper objectMapper = ((MappingJackson2HttpMessageConverter) converters.get(1)).getObjectMapper();
	assertFalse(objectMapper.getDeserializationConfig().isEnabled(DEFAULT_VIEW_INCLUSION));
	assertFalse(objectMapper.getSerializationConfig().isEnabled(DEFAULT_VIEW_INCLUSION));
	assertFalse(objectMapper.getDeserializationConfig().isEnabled(FAIL_ON_UNKNOWN_PROPERTIES));

	DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(adapter);

	// Custom argument resolvers and return value handlers
	List<HandlerMethodArgumentResolver> argResolvers =
		(List<HandlerMethodArgumentResolver>) fieldAccessor.getPropertyValue("customArgumentResolvers");
	assertEquals(1, argResolvers.size());

	List<HandlerMethodReturnValueHandler> handlers =
		(List<HandlerMethodReturnValueHandler>) fieldAccessor.getPropertyValue("customReturnValueHandlers");
	assertEquals(1, handlers.size());

	// Async support options
	assertEquals(ConcurrentTaskExecutor.class, fieldAccessor.getPropertyValue("taskExecutor").getClass());
	assertEquals(2500L, fieldAccessor.getPropertyValue("asyncRequestTimeout"));

	CallableProcessingInterceptor[] callableInterceptors =
			(CallableProcessingInterceptor[]) fieldAccessor.getPropertyValue("callableInterceptors");
	assertEquals(1, callableInterceptors.length);

	DeferredResultProcessingInterceptor[] deferredResultInterceptors =
			(DeferredResultProcessingInterceptor[]) fieldAccessor.getPropertyValue("deferredResultInterceptors");
	assertEquals(1, deferredResultInterceptors.length);

	assertEquals(false, fieldAccessor.getPropertyValue("ignoreDefaultModelOnRedirect"));
}
 
Example 20
Source File: RabbitBinderModuleTests.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testParentConnectionFactoryInheritedByDefaultAndRabbitSettingsPropagated() {
	context = new SpringApplicationBuilder(SimpleProcessor.class)
			.web(WebApplicationType.NONE).run("--server.port=0",
					"--spring.cloud.stream.bindings.source.group=someGroup",
					"--spring.cloud.stream.bindings.input.group=someGroup",
					"--spring.cloud.stream.rabbit.bindings.input.consumer.transacted=true",
					"--spring.cloud.stream.rabbit.bindings.output.producer.transacted=true");
	BinderFactory binderFactory = context.getBean(BinderFactory.class);
	Binder<?, ?, ?> binder = binderFactory.getBinder(null, MessageChannel.class);
	assertThat(binder).isInstanceOf(RabbitMessageChannelBinder.class);
	BindingService bindingService = context.getBean(BindingService.class);
	DirectFieldAccessor channelBindingServiceAccessor = new DirectFieldAccessor(
			bindingService);
	// @checkstyle:off
	Map<String, List<Binding<MessageChannel>>> consumerBindings = (Map<String, List<Binding<MessageChannel>>>) channelBindingServiceAccessor
			.getPropertyValue("consumerBindings");
	// @checkstyle:on
	Binding<MessageChannel> inputBinding = consumerBindings.get("input").get(0);
	assertThat(TestUtils.getPropertyValue(inputBinding, "lifecycle.beanName"))
			.isEqualTo("setByCustomizer:someGroup");
	SimpleMessageListenerContainer container = TestUtils.getPropertyValue(
			inputBinding, "lifecycle.messageListenerContainer",
			SimpleMessageListenerContainer.class);
	assertThat(TestUtils.getPropertyValue(container, "beanName"))
			.isEqualTo("setByCustomizerForQueue:input.someGroup,andGroup:someGroup");
	assertThat(TestUtils.getPropertyValue(container, "transactional", Boolean.class))
			.isTrue();
	Map<String, Binding<MessageChannel>> producerBindings = (Map<String, Binding<MessageChannel>>) TestUtils
			.getPropertyValue(bindingService, "producerBindings");
	Binding<MessageChannel> outputBinding = producerBindings.get("output");
	assertThat(TestUtils.getPropertyValue(outputBinding,
			"lifecycle.amqpTemplate.transactional", Boolean.class)).isTrue();
	assertThat(TestUtils.getPropertyValue(outputBinding, "lifecycle.beanName"))
			.isEqualTo("setByCustomizer:output");
	DirectFieldAccessor binderFieldAccessor = new DirectFieldAccessor(binder);
	ConnectionFactory binderConnectionFactory = (ConnectionFactory) binderFieldAccessor
			.getPropertyValue("connectionFactory");
	assertThat(binderConnectionFactory).isInstanceOf(CachingConnectionFactory.class);
	ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class);
	assertThat(binderConnectionFactory).isSameAs(connectionFactory);
	CompositeHealthContributor bindersHealthIndicator = context
			.getBean("bindersHealthContributor", CompositeHealthContributor.class);

	assertThat(bindersHealthIndicator).isNotNull();

	RabbitHealthIndicator indicator = (RabbitHealthIndicator) bindersHealthIndicator.getContributor("rabbit");
	assertThat(indicator).isNotNull();
	assertThat(indicator.health().getStatus())
			.isEqualTo(Status.UP);

	CachingConnectionFactory cf = this.context
			.getBean(CachingConnectionFactory.class);
	ConnectionNameStrategy cns = TestUtils.getPropertyValue(cf,
			"connectionNameStrategy", ConnectionNameStrategy.class);
	assertThat(cns.obtainNewConnectionName(cf)).startsWith("rabbitConnectionFactory");
	assertThat(TestUtils.getPropertyValue(consumerBindings.get("source").get(0),
			"target.source.h.advised.targetSource.target.beanName"))
		.isEqualTo("setByCustomizer:someGroup");
}