org.springframework.beans.DirectFieldAccessor Java Examples

The following examples show how to use org.springframework.beans.DirectFieldAccessor. 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: ScriptTemplateViewTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void detectScriptTemplateConfigWithEngine() {
	InvocableScriptEngine engine = mock(InvocableScriptEngine.class);
	this.configurer.setEngine(engine);
	this.configurer.setRenderObject("Template");
	this.configurer.setRenderFunction("render");
	this.configurer.setCharset(StandardCharsets.ISO_8859_1);
	this.configurer.setSharedEngine(true);

	DirectFieldAccessor accessor = new DirectFieldAccessor(this.view);
	this.view.setApplicationContext(this.context);
	assertEquals(engine, accessor.getPropertyValue("engine"));
	assertEquals("Template", accessor.getPropertyValue("renderObject"));
	assertEquals("render", accessor.getPropertyValue("renderFunction"));
	assertEquals(StandardCharsets.ISO_8859_1, accessor.getPropertyValue("defaultCharset"));
	assertEquals(true, accessor.getPropertyValue("sharedEngine"));
}
 
Example #2
Source File: MvcNamespaceTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private void doTestCustomValidator(String xml) throws Exception {
	loadBeanDefinitions(xml, 14);

	RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
	assertNotNull(mapping);
	assertFalse(mapping.getUrlPathHelper().shouldRemoveSemicolonContent());

	RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
	assertNotNull(adapter);
	assertEquals(true, new DirectFieldAccessor(adapter).getPropertyValue("ignoreDefaultModelOnRedirect"));

	// default web binding initializer behavior test
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.addParameter("date", "2009-10-31");
	MockHttpServletResponse response = new MockHttpServletResponse();
	adapter.handle(request, response, handlerMethod);

	assertTrue(appContext.getBean(TestValidator.class).validatorInvoked);
	assertFalse(handler.recordedValidationError);
}
 
Example #3
Source File: RabbitBinderModuleTests.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 6 votes vote down vote up
@Test
public void testCloudProfile() {
	this.context = new SpringApplicationBuilder(SimpleProcessor.class,
			MockCloudConfiguration.class).web(WebApplicationType.NONE)
					.profiles("cloud").run();
	BinderFactory binderFactory = this.context.getBean(BinderFactory.class);
	Binder<?, ?, ?> binder = binderFactory.getBinder(null, MessageChannel.class);
	assertThat(binder).isInstanceOf(RabbitMessageChannelBinder.class);
	DirectFieldAccessor binderFieldAccessor = new DirectFieldAccessor(binder);
	ConnectionFactory binderConnectionFactory = (ConnectionFactory) binderFieldAccessor
			.getPropertyValue("connectionFactory");
	ConnectionFactory connectionFactory = this.context
			.getBean(ConnectionFactory.class);

	assertThat(binderConnectionFactory).isNotSameAs(connectionFactory);

	assertThat(TestUtils.getPropertyValue(connectionFactory, "addresses"))
			.isNotNull();
	assertThat(TestUtils.getPropertyValue(binderConnectionFactory, "addresses"))
			.isNull();

	Cloud cloud = this.context.getBean(Cloud.class);

	verify(cloud).getSingletonServiceConnector(ConnectionFactory.class, null);
}
 
Example #4
Source File: ScheduledAnnotationBeanPostProcessorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void cronTaskWithScopedProxy() {
	BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
	context.registerBeanDefinition("postProcessor", processorDefinition);
	new AnnotatedBeanDefinitionReader(context).register(ProxiedCronTestBean.class, ProxiedCronTestBeanDependent.class);
	context.refresh();

	ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class);
	assertEquals(1, postProcessor.getScheduledTasks().size());

	ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar)
			new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
	@SuppressWarnings("unchecked")
	List<CronTask> cronTasks = (List<CronTask>)
			new DirectFieldAccessor(registrar).getPropertyValue("cronTasks");
	assertEquals(1, cronTasks.size());
	CronTask task = cronTasks.get(0);
	ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
	Object targetObject = runnable.getTarget();
	Method targetMethod = runnable.getMethod();
	assertEquals(context.getBean(ScopedProxyUtils.getTargetBeanName("target")), targetObject);
	assertEquals("cron", targetMethod.getName());
	assertEquals("*/7 * * * * ?", task.getExpression());
}
 
Example #5
Source File: ScheduledAnnotationBeanPostProcessorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void metaAnnotationWithCronExpression() {
	BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
	BeanDefinition targetDefinition = new RootBeanDefinition(MetaAnnotationCronTestBean.class);
	context.registerBeanDefinition("postProcessor", processorDefinition);
	context.registerBeanDefinition("target", targetDefinition);
	context.refresh();

	ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class);
	assertEquals(1, postProcessor.getScheduledTasks().size());

	Object target = context.getBean("target");
	ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar)
			new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
	@SuppressWarnings("unchecked")
	List<CronTask> cronTasks = (List<CronTask>)
			new DirectFieldAccessor(registrar).getPropertyValue("cronTasks");
	assertEquals(1, cronTasks.size());
	CronTask task = cronTasks.get(0);
	ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
	Object targetObject = runnable.getTarget();
	Method targetMethod = runnable.getMethod();
	assertEquals(target, targetObject);
	assertEquals("generateReport", targetMethod.getName());
	assertEquals("0 0 * * * ?", task.getExpression());
}
 
Example #6
Source File: ScheduledAnnotationBeanPostProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void cronTask() {
	BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
	BeanDefinition targetDefinition = new RootBeanDefinition(CronTestBean.class);
	context.registerBeanDefinition("postProcessor", processorDefinition);
	context.registerBeanDefinition("target", targetDefinition);
	context.refresh();

	ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class);
	assertEquals(1, postProcessor.getScheduledTasks().size());

	Object target = context.getBean("target");
	ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar)
			new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
	@SuppressWarnings("unchecked")
	List<CronTask> cronTasks = (List<CronTask>)
			new DirectFieldAccessor(registrar).getPropertyValue("cronTasks");
	assertEquals(1, cronTasks.size());
	CronTask task = cronTasks.get(0);
	ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
	Object targetObject = runnable.getTarget();
	Method targetMethod = runnable.getMethod();
	assertEquals(target, targetObject);
	assertEquals("cron", targetMethod.getName());
	assertEquals("*/7 * * * * ?", task.getExpression());
}
 
Example #7
Source File: ScheduledAnnotationBeanPostProcessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void fixedRateTaskWithInitialDelay() {
	BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
	BeanDefinition targetDefinition = new RootBeanDefinition(FixedRateWithInitialDelayTestBean.class);
	context.registerBeanDefinition("postProcessor", processorDefinition);
	context.registerBeanDefinition("target", targetDefinition);
	context.refresh();

	Object postProcessor = context.getBean("postProcessor");
	Object target = context.getBean("target");
	ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar)
			new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
	@SuppressWarnings("unchecked")
	List<IntervalTask> fixedRateTasks = (List<IntervalTask>)
			new DirectFieldAccessor(registrar).getPropertyValue("fixedRateTasks");
	assertEquals(1, fixedRateTasks.size());
	IntervalTask task = fixedRateTasks.get(0);
	ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
	Object targetObject = runnable.getTarget();
	Method targetMethod = runnable.getMethod();
	assertEquals(target, targetObject);
	assertEquals("fixedRate", targetMethod.getName());
	assertEquals(1000L, task.getInitialDelay());
	assertEquals(3000L, task.getInterval());
}
 
Example #8
Source File: KafkaBinderTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testSyncProducerMetadata() throws Exception {
	Binder binder = getBinder(createConfigurationProperties());
	DirectChannel output = new DirectChannel();
	String testTopicName = UUID.randomUUID().toString();
	ExtendedProducerProperties<KafkaProducerProperties> properties = createProducerProperties();
	properties.getExtension().setSync(true);
	Binding<MessageChannel> producerBinding = binder.bindProducer(testTopicName,
			output, properties);
	DirectFieldAccessor accessor = new DirectFieldAccessor(
			extractEndpoint(producerBinding));
	KafkaProducerMessageHandler wrappedInstance = (KafkaProducerMessageHandler) accessor
			.getWrappedInstance();
	assertThat(new DirectFieldAccessor(wrappedInstance).getPropertyValue("sync")
			.equals(Boolean.TRUE))
					.withFailMessage("Kafka Sync Producer should have been enabled.");
	producerBinding.unbind();
}
 
Example #9
Source File: MvcNamespaceTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testCorsMinimal() throws Exception {
	loadBeanDefinitions("mvc-config-cors-minimal.xml");

	String[] beanNames = appContext.getBeanNamesForType(AbstractHandlerMapping.class);
	assertEquals(2, beanNames.length);
	for (String beanName : beanNames) {
		AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping)appContext.getBean(beanName);
		assertNotNull(handlerMapping);
		DirectFieldAccessor accessor = new DirectFieldAccessor(handlerMapping);
		Map<String, CorsConfiguration> configs = ((UrlBasedCorsConfigurationSource) accessor
				.getPropertyValue("corsConfigurationSource")).getCorsConfigurations();
		assertNotNull(configs);
		assertEquals(1, configs.size());
		CorsConfiguration config = configs.get("/**");
		assertNotNull(config);
		assertArrayEquals(new String[]{"*"}, config.getAllowedOrigins().toArray());
		assertArrayEquals(new String[]{"GET", "HEAD", "POST"}, config.getAllowedMethods().toArray());
		assertArrayEquals(new String[]{"*"}, config.getAllowedHeaders().toArray());
		assertNull(config.getExposedHeaders());
		assertNull(config.getAllowCredentials());
		assertEquals(Long.valueOf(1800), config.getMaxAge());
	}
}
 
Example #10
Source File: ScheduledAnnotationBeanPostProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void nonVoidReturnType() {
	BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
	BeanDefinition targetDefinition = new RootBeanDefinition(NonVoidReturnTypeTestBean.class);
	context.registerBeanDefinition("postProcessor", processorDefinition);
	context.registerBeanDefinition("target", targetDefinition);
	context.refresh();

	ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class);
	assertEquals(1, postProcessor.getScheduledTasks().size());

	Object target = context.getBean("target");
	ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar)
			new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
	@SuppressWarnings("unchecked")
	List<CronTask> cronTasks = (List<CronTask>)
			new DirectFieldAccessor(registrar).getPropertyValue("cronTasks");
	assertEquals(1, cronTasks.size());
	CronTask task = cronTasks.get(0);
	ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
	Object targetObject = runnable.getTarget();
	Method targetMethod = runnable.getMethod();
	assertEquals(target, targetObject);
	assertEquals("cron", targetMethod.getName());
	assertEquals("0 0 9-17 * * MON-FRI", task.getExpression());
}
 
Example #11
Source File: ScheduledAnnotationBeanPostProcessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void metaAnnotationWithFixedRate() {
	BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
	BeanDefinition targetDefinition = new RootBeanDefinition(MetaAnnotationFixedRateTestBean.class);
	context.registerBeanDefinition("postProcessor", processorDefinition);
	context.registerBeanDefinition("target", targetDefinition);
	context.refresh();

	Object postProcessor = context.getBean("postProcessor");
	Object target = context.getBean("target");
	ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar)
			new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
	@SuppressWarnings("unchecked")
	List<IntervalTask> fixedRateTasks = (List<IntervalTask>)
			new DirectFieldAccessor(registrar).getPropertyValue("fixedRateTasks");
	assertEquals(1, fixedRateTasks.size());
	IntervalTask task = fixedRateTasks.get(0);
	ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
	Object targetObject = runnable.getTarget();
	Method targetMethod = runnable.getMethod();
	assertEquals(target, targetObject);
	assertEquals("checkForUpdates", targetMethod.getName());
	assertEquals(5000L, task.getInterval());
}
 
Example #12
Source File: ThroughputSinkTests.java    From spring-cloud-stream-app-starters with Apache License 2.0 6 votes vote down vote up
@Test
public void testSink() throws Exception {
	assertNotNull(this.sink.input());
	this.sink.input().send(new GenericMessage<>("foo"));
	Log logger = spy(TestUtils.getPropertyValue(this.configuration, "logger", Log.class));
	new DirectFieldAccessor(this.configuration).setPropertyValue("logger", logger);
	final CountDownLatch latch = new CountDownLatch(1);
	doAnswer(new Answer<Void>() {

		@Override
		public Void answer(InvocationOnMock invocation) throws Throwable {
			invocation.callRealMethod();
			latch.countDown();
			return null;
		}

	}).when(logger).info(anyString());
	assertTrue(latch.await(10, TimeUnit.SECONDS));
}
 
Example #13
Source File: ScriptTemplateViewTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void detectScriptTemplateConfigWithEngine() {
	InvocableScriptEngine engine = mock(InvocableScriptEngine.class);
	this.configurer.setEngine(engine);
	this.configurer.setRenderObject("Template");
	this.configurer.setRenderFunction("render");
	this.configurer.setContentType(MediaType.TEXT_PLAIN_VALUE);
	this.configurer.setCharset(StandardCharsets.ISO_8859_1);
	this.configurer.setSharedEngine(true);

	DirectFieldAccessor accessor = new DirectFieldAccessor(this.view);
	this.view.setApplicationContext(this.wac);
	assertEquals(engine, accessor.getPropertyValue("engine"));
	assertEquals("Template", accessor.getPropertyValue("renderObject"));
	assertEquals("render", accessor.getPropertyValue("renderFunction"));
	assertEquals(MediaType.TEXT_PLAIN_VALUE, accessor.getPropertyValue("contentType"));
	assertEquals(StandardCharsets.ISO_8859_1, accessor.getPropertyValue("charset"));
	assertEquals(true, accessor.getPropertyValue("sharedEngine"));
}
 
Example #14
Source File: MvcNamespaceTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testViewResolutionWithContentNegotiation() throws Exception {
	loadBeanDefinitions("mvc-config-view-resolution-content-negotiation.xml", 7);

	ViewResolverComposite compositeResolver = this.appContext.getBean(ViewResolverComposite.class);
	assertNotNull(compositeResolver);
	assertEquals(1, compositeResolver.getViewResolvers().size());
	assertEquals(Ordered.HIGHEST_PRECEDENCE, compositeResolver.getOrder());

	List<ViewResolver> resolvers = compositeResolver.getViewResolvers();
	assertEquals(ContentNegotiatingViewResolver.class, resolvers.get(0).getClass());
	ContentNegotiatingViewResolver cnvr = (ContentNegotiatingViewResolver) resolvers.get(0);
	assertEquals(7, cnvr.getViewResolvers().size());
	assertEquals(1, cnvr.getDefaultViews().size());
	assertTrue(cnvr.isUseNotAcceptableStatusCode());

	String beanName = "contentNegotiationManager";
	DirectFieldAccessor accessor = new DirectFieldAccessor(cnvr);
	ContentNegotiationManager manager = (ContentNegotiationManager) accessor.getPropertyValue(beanName);
	assertNotNull(manager);
	assertSame(manager, this.appContext.getBean(ContentNegotiationManager.class));
}
 
Example #15
Source File: AbstractTyrusRequestUpgradeStrategy.java    From java-technology-stack with MIT License 6 votes vote down vote up
private Object createEndpoint(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 #16
Source File: MvcNamespaceTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testCorsMinimal() throws Exception {
	loadBeanDefinitions("mvc-config-cors-minimal.xml");

	String[] beanNames = appContext.getBeanNamesForType(AbstractHandlerMapping.class);
	assertEquals(2, beanNames.length);
	for (String beanName : beanNames) {
		AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping)appContext.getBean(beanName);
		assertNotNull(handlerMapping);
		DirectFieldAccessor accessor = new DirectFieldAccessor(handlerMapping);
		Map<String, CorsConfiguration> configs = ((UrlBasedCorsConfigurationSource)accessor
				.getPropertyValue("corsConfigurationSource")).getCorsConfigurations();
		assertNotNull(configs);
		assertEquals(1, configs.size());
		CorsConfiguration config = configs.get("/**");
		assertNotNull(config);
		assertArrayEquals(new String[]{"*"}, config.getAllowedOrigins().toArray());
		assertArrayEquals(new String[]{"GET", "HEAD", "POST"}, config.getAllowedMethods().toArray());
		assertArrayEquals(new String[]{"*"}, config.getAllowedHeaders().toArray());
		assertNull(config.getExposedHeaders());
		assertNull(config.getAllowCredentials());
		assertEquals(Long.valueOf(1800), config.getMaxAge());
	}
}
 
Example #17
Source File: ScheduledAnnotationBeanPostProcessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void fixedRateTask() {
	BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
	BeanDefinition targetDefinition = new RootBeanDefinition(FixedRateTestBean.class);
	context.registerBeanDefinition("postProcessor", processorDefinition);
	context.registerBeanDefinition("target", targetDefinition);
	context.refresh();

	Object postProcessor = context.getBean("postProcessor");
	Object target = context.getBean("target");
	ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar)
			new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
	@SuppressWarnings("unchecked")
	List<IntervalTask> fixedRateTasks = (List<IntervalTask>)
			new DirectFieldAccessor(registrar).getPropertyValue("fixedRateTasks");
	assertEquals(1, fixedRateTasks.size());
	IntervalTask task = fixedRateTasks.get(0);
	ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
	Object targetObject = runnable.getTarget();
	Method targetMethod = runnable.getMethod();
	assertEquals(target, targetObject);
	assertEquals("fixedRate", targetMethod.getName());
	assertEquals(0L, task.getInitialDelay());
	assertEquals(3000L, task.getInterval());
}
 
Example #18
Source File: RabbitBinderModuleTests.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 6 votes vote down vote up
@Test
public void testParentConnectionFactoryInheritedIfOverridden() {
	context = new SpringApplicationBuilder(SimpleProcessor.class,
			ConnectionFactoryConfiguration.class).web(WebApplicationType.NONE)
					.run("--server.port=0");
	BinderFactory binderFactory = context.getBean(BinderFactory.class);
	Binder<?, ?, ?> binder = binderFactory.getBinder(null, MessageChannel.class);
	assertThat(binder).isInstanceOf(RabbitMessageChannelBinder.class);
	DirectFieldAccessor binderFieldAccessor = new DirectFieldAccessor(binder);
	ConnectionFactory binderConnectionFactory = (ConnectionFactory) binderFieldAccessor
			.getPropertyValue("connectionFactory");
	assertThat(binderConnectionFactory).isSameAs(MOCK_CONNECTION_FACTORY);
	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();
	// mock connection factory behaves as if down
	assertThat(indicator.health().getStatus())
			.isEqualTo(Status.DOWN);
}
 
Example #19
Source File: ScriptTemplateViewTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void detectScriptTemplateConfigWithEngineName() {
	this.configurer.setEngineName("nashorn");
	this.configurer.setRenderObject("Template");
	this.configurer.setRenderFunction("render");

	DirectFieldAccessor accessor = new DirectFieldAccessor(this.view);
	this.view.setApplicationContext(this.wac);
	assertEquals("nashorn", accessor.getPropertyValue("engineName"));
	assertNotNull(accessor.getPropertyValue("engine"));
	assertEquals("Template", accessor.getPropertyValue("renderObject"));
	assertEquals("render", accessor.getPropertyValue("renderFunction"));
	assertEquals(MediaType.TEXT_HTML_VALUE, accessor.getPropertyValue("contentType"));
	assertEquals(StandardCharsets.UTF_8, accessor.getPropertyValue("charset"));
}
 
Example #20
Source File: ScriptTemplateViewTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void detectScriptTemplateConfigWithEngineName() {
	this.configurer.setEngineName("nashorn");
	this.configurer.setRenderObject("Template");
	this.configurer.setRenderFunction("render");

	DirectFieldAccessor accessor = new DirectFieldAccessor(this.view);
	this.view.setApplicationContext(this.context);
	assertEquals("nashorn", accessor.getPropertyValue("engineName"));
	assertNotNull(accessor.getPropertyValue("engine"));
	assertEquals("Template", accessor.getPropertyValue("renderObject"));
	assertEquals("render", accessor.getPropertyValue("renderFunction"));
	assertEquals(StandardCharsets.UTF_8, accessor.getPropertyValue("defaultCharset"));
}
 
Example #21
Source File: AnnotationDrivenBeanDefinitionParserTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void testReturnValueHandlers(Object bean) {
	assertNotNull(bean);
	Object value = new DirectFieldAccessor(bean).getPropertyValue("customReturnValueHandlers");
	assertNotNull(value);
	assertTrue(value instanceof List);
	@SuppressWarnings("unchecked")
	List<HandlerMethodReturnValueHandler> handlers = (List<HandlerMethodReturnValueHandler>) value;
	assertEquals(2, handlers.size());
	assertEquals(TestHandlerMethodReturnValueHandler.class, handlers.get(0).getClass());
	assertEquals(TestHandlerMethodReturnValueHandler.class, handlers.get(1).getClass());
	assertNotSame(handlers.get(0), handlers.get(1));
}
 
Example #22
Source File: SubProtocolWebSocketHandlerTests.java    From spring-analysis-note with MIT License 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 #23
Source File: MethodJmsListenerEndpointTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void setExtraCollaborators() {
	MessageConverter messageConverter = mock(MessageConverter.class);
	DestinationResolver destinationResolver = mock(DestinationResolver.class);
	this.container.setMessageConverter(messageConverter);
	this.container.setDestinationResolver(destinationResolver);

	MessagingMessageListenerAdapter listener = createInstance(this.factory,
			getListenerMethod("resolveObjectPayload", MyBean.class), this.container);
	DirectFieldAccessor accessor = new DirectFieldAccessor(listener);
	assertSame(messageConverter, accessor.getPropertyValue("messageConverter"));
	assertSame(destinationResolver, accessor.getPropertyValue("destinationResolver"));
}
 
Example #24
Source File: AnnotationDrivenBeanDefinitionParserTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void asyncPostProcessorExceptionHandlerReference() {
	Object exceptionHandler = context.getBean("testExceptionHandler");
	Object aspect = context.getBean(TaskManagementConfigUtils.ASYNC_EXECUTION_ASPECT_BEAN_NAME);
	assertSame(exceptionHandler, ((Supplier) new DirectFieldAccessor(aspect).getPropertyValue("exceptionHandler")).get());
}
 
Example #25
Source File: MvcNamespaceTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testCors() throws Exception {
	loadBeanDefinitions("mvc-config-cors.xml");

	String[] beanNames = appContext.getBeanNamesForType(AbstractHandlerMapping.class);
	assertEquals(2, beanNames.length);
	for (String beanName : beanNames) {
		AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping)appContext.getBean(beanName);
		assertNotNull(handlerMapping);
		DirectFieldAccessor accessor = new DirectFieldAccessor(handlerMapping);
		Map<String, CorsConfiguration> configs = ((UrlBasedCorsConfigurationSource)accessor
				.getPropertyValue("corsConfigurationSource")).getCorsConfigurations();
		assertNotNull(configs);
		assertEquals(2, configs.size());
		CorsConfiguration config = configs.get("/api/**");
		assertNotNull(config);
		assertArrayEquals(new String[]{"http://domain1.com", "http://domain2.com"}, config.getAllowedOrigins().toArray());
		assertArrayEquals(new String[]{"GET", "PUT"}, config.getAllowedMethods().toArray());
		assertArrayEquals(new String[]{"header1", "header2", "header3"}, config.getAllowedHeaders().toArray());
		assertArrayEquals(new String[]{"header1", "header2"}, config.getExposedHeaders().toArray());
		assertFalse(config.getAllowCredentials());
		assertEquals(Long.valueOf(123), config.getMaxAge());
		config = configs.get("/resources/**");
		assertArrayEquals(new String[]{"http://domain1.com"}, config.getAllowedOrigins().toArray());
		assertArrayEquals(new String[]{"GET", "HEAD", "POST"}, config.getAllowedMethods().toArray());
		assertArrayEquals(new String[]{"*"}, config.getAllowedHeaders().toArray());
		assertNull(config.getExposedHeaders());
		assertNull(config.getAllowCredentials());
		assertEquals(Long.valueOf(1800), config.getMaxAge());
	}
}
 
Example #26
Source File: ScheduledAnnotationBeanPostProcessorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void propertyPlaceholderWithCron() {
	String businessHoursCronExpression = "0 0 9-17 * * MON-FRI";
	BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
	BeanDefinition placeholderDefinition = new RootBeanDefinition(PropertyPlaceholderConfigurer.class);
	Properties properties = new Properties();
	properties.setProperty("schedules.businessHours", businessHoursCronExpression);
	placeholderDefinition.getPropertyValues().addPropertyValue("properties", properties);
	BeanDefinition targetDefinition = new RootBeanDefinition(PropertyPlaceholderWithCronTestBean.class);
	context.registerBeanDefinition("placeholder", placeholderDefinition);
	context.registerBeanDefinition("postProcessor", processorDefinition);
	context.registerBeanDefinition("target", targetDefinition);
	context.refresh();

	Object postProcessor = context.getBean("postProcessor");
	Object target = context.getBean("target");
	ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar)
			new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
	@SuppressWarnings("unchecked")
	List<CronTask> cronTasks = (List<CronTask>)
			new DirectFieldAccessor(registrar).getPropertyValue("cronTasks");
	assertEquals(1, cronTasks.size());
	CronTask task = cronTasks.get(0);
	ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
	Object targetObject = runnable.getTarget();
	Method targetMethod = runnable.getMethod();
	assertEquals(target, targetObject);
	assertEquals("x", targetMethod.getName());
	assertEquals(businessHoursCronExpression, task.getExpression());
}
 
Example #27
Source File: ScheduledTasksBeanDefinitionParserTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void cronTasks() {
	List<CronTask> tasks = (List<CronTask>) new DirectFieldAccessor(
			this.registrar).getPropertyValue("cronTasks");
	assertEquals(1, tasks.size());
	assertEquals("*/4 * 9-17 * * MON-FRI", tasks.get(0).getExpression());
}
 
Example #28
Source File: MvcNamespaceTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testCors() throws Exception {
	loadBeanDefinitions("mvc-config-cors.xml");

	String[] beanNames = appContext.getBeanNamesForType(AbstractHandlerMapping.class);
	assertEquals(2, beanNames.length);
	for (String beanName : beanNames) {
		AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping)appContext.getBean(beanName);
		assertNotNull(handlerMapping);
		DirectFieldAccessor accessor = new DirectFieldAccessor(handlerMapping);
		Map<String, CorsConfiguration> configs = ((UrlBasedCorsConfigurationSource) accessor
				.getPropertyValue("corsConfigurationSource")).getCorsConfigurations();
		assertNotNull(configs);
		assertEquals(2, configs.size());
		CorsConfiguration config = configs.get("/api/**");
		assertNotNull(config);
		assertArrayEquals(new String[]{"https://domain1.com", "https://domain2.com"}, config.getAllowedOrigins().toArray());
		assertArrayEquals(new String[]{"GET", "PUT"}, config.getAllowedMethods().toArray());
		assertArrayEquals(new String[]{"header1", "header2", "header3"}, config.getAllowedHeaders().toArray());
		assertArrayEquals(new String[]{"header1", "header2"}, config.getExposedHeaders().toArray());
		assertFalse(config.getAllowCredentials());
		assertEquals(Long.valueOf(123), config.getMaxAge());
		config = configs.get("/resources/**");
		assertArrayEquals(new String[]{"https://domain1.com"}, config.getAllowedOrigins().toArray());
		assertArrayEquals(new String[]{"GET", "HEAD", "POST"}, config.getAllowedMethods().toArray());
		assertArrayEquals(new String[]{"*"}, config.getAllowedHeaders().toArray());
		assertNull(config.getExposedHeaders());
		assertNull(config.getAllowCredentials());
		assertEquals(Long.valueOf(1800), config.getMaxAge());
	}
}
 
Example #29
Source File: ProcessorToFunctionsSupportTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Bean
public Consumer<String> log(OutputDestination out) {
	return x -> {
		DirectFieldAccessor dfa = new DirectFieldAccessor(out);
		MessageChannel channel = ((List<MessageChannel>) dfa.getPropertyValue("channels")).get(0);
		channel.send(new GenericMessage<byte[]>(x.getBytes()));
	};
}
 
Example #30
Source File: ScriptTemplateViewTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void detectScriptTemplateConfigWithEngineName() {
	this.configurer.setEngineName("nashorn");
	this.configurer.setRenderObject("Template");
	this.configurer.setRenderFunction("render");

	DirectFieldAccessor accessor = new DirectFieldAccessor(this.view);
	this.view.setApplicationContext(this.context);
	assertEquals("nashorn", accessor.getPropertyValue("engineName"));
	assertNotNull(accessor.getPropertyValue("engine"));
	assertEquals("Template", accessor.getPropertyValue("renderObject"));
	assertEquals("render", accessor.getPropertyValue("renderFunction"));
	assertEquals(StandardCharsets.UTF_8, accessor.getPropertyValue("defaultCharset"));
}