Java Code Examples for org.springframework.web.context.support.AnnotationConfigWebApplicationContext#refresh()

The following examples show how to use org.springframework.web.context.support.AnnotationConfigWebApplicationContext#refresh() . 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: WebConfigurer.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce) {
    ServletContext servletContext = sce.getServletContext();

    log.debug("Configuring Spring root application context");
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.register(ApplicationConfiguration.class);
    rootContext.refresh();

    servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, rootContext);

    EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC);

    initSpring(servletContext, rootContext);
    initSpringSecurity(servletContext, disps);

    log.debug("Web application fully configured");
}
 
Example 2
Source File: TestServerUtil.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
public static TestServer createAndStartServer(Class<?>... configClasses) {
    int port = NEXT_PORT.incrementAndGet();
    Server server = new Server(port);

    HashSessionIdManager idmanager = new HashSessionIdManager();
    server.setSessionIdManager(idmanager);

    AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
    applicationContext.register(configClasses);
    applicationContext.refresh();

    try {
        server.setHandler(getServletContextHandler(applicationContext));
        server.start();
    } catch (Exception e) {
        LOGGER.error("Error starting server", e);
    }

    return new TestServer(server, applicationContext, port);
}
 
Example 3
Source File: TestServerUtil.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
public static TestServer createAndStartServer(Class<?>... configClasses) {
    int port = NEXT_PORT.incrementAndGet();
    Server server = new Server(port);

    HashSessionIdManager idmanager = new HashSessionIdManager();
    server.setSessionIdManager(idmanager);

    AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
    applicationContext.register(configClasses);
    applicationContext.refresh();

    try {
        server.setHandler(getServletContextHandler(applicationContext));
        server.start();
    } catch (Exception e) {
        LOGGER.error("Error starting server", e);
    }

    return new TestServer(server, applicationContext, port);
}
 
Example 4
Source File: ViewResolutionIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
private MockHttpServletResponse runTest(Class<?> configClass) throws ServletException, IOException {
	String basePath = "org/springframework/web/servlet/config/annotation";
	MockServletContext servletContext = new MockServletContext(basePath);
	MockServletConfig servletConfig = new MockServletConfig(servletContext);
	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
	MockHttpServletResponse response = new MockHttpServletResponse();

	AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
	context.register(configClass);
	context.setServletContext(servletContext);
	context.refresh();
	DispatcherServlet servlet = new DispatcherServlet(context);
	servlet.init(servletConfig);
	servlet.service(request, response);
	return response;
}
 
Example 5
Source File: ResourceUrlProviderJavaConfigTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Before
@SuppressWarnings("resource")
public void setup() throws Exception {
	this.filterChain = new MockFilterChain(this.servlet, new ResourceUrlEncodingFilter());

	AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
	context.setServletContext(new MockServletContext());
	context.register(WebConfig.class);
	context.refresh();

	this.request = new MockHttpServletRequest("GET", "/");
	this.request.setContextPath("/myapp");
	this.response = new MockHttpServletResponse();

	Object urlProvider = context.getBean(ResourceUrlProvider.class);
	this.request.setAttribute(ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR, urlProvider);
}
 
Example 6
Source File: BaseJPARestTestCase.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
public static void createAndStartServer() {
  server = new Server(HTTP_SERVER_PORT);

  HashSessionIdManager idmanager = new HashSessionIdManager();
  server.setSessionIdManager(idmanager);

  AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
  applicationContext.register(JPAApplicationConfiguration.class);
  applicationContext.refresh();

  appContext = applicationContext;

  try {
    server.setHandler(getServletContextHandler(applicationContext));
    server.start();
  } catch (Exception e) {
    log.error("Error starting server", e);
  }
}
 
Example 7
Source File: TestServerUtil.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
public static TestServer createAndStartServer(Class<?>... configClasses) {
    int port = NEXT_PORT.incrementAndGet();
    Server server = new Server(port);

    HashSessionIdManager idmanager = new HashSessionIdManager();
    server.setSessionIdManager(idmanager);

    AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
    applicationContext.register(configClasses);
    applicationContext.refresh();

    try {
        server.setHandler(getServletContextHandler(applicationContext));
        server.start();
    } catch (Exception e) {
        LOGGER.error("Error starting server", e);
    }

    return new TestServer(server, applicationContext, port);
}
 
Example 8
Source File: MvcUriComponentsBuilderTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testFromMappingName() throws Exception {
	AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
	context.setServletContext(new MockServletContext());
	context.register(WebConfig.class);
	context.refresh();

	this.request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
	this.request.setServerName("example.org");
	this.request.setServerPort(9999);
	this.request.setContextPath("/base");

	String mappingName = "PAC#getAddressesForCountry";
	String url = MvcUriComponentsBuilder.fromMappingName(mappingName).arg(0, "DE").buildAndExpand(123);
	assertEquals("/base/people/123/addresses/DE", url);
}
 
Example 9
Source File: ResourceUrlProviderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test  // SPR-12592
@SuppressWarnings("resource")
public void initializeOnce() {
	AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
	context.setServletContext(new MockServletContext());
	context.register(HandlerMappingConfiguration.class);
	context.refresh();

	assertThat(context.getBean(ResourceUrlProvider.class).getHandlerMap(),
			Matchers.hasKey(pattern("/resources/**")));
}
 
Example 10
Source File: EnvironmentSystemIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void annotationConfigWebApplicationContext() {
	AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
	ctx.setEnvironment(prodWebEnv);
	ctx.setConfigLocation(EnvironmentAwareBean.class.getName());
	ctx.refresh();

	assertHasEnvironment(ctx, prodWebEnv);
	assertEnvironmentBeanRegistered(ctx);
	assertEnvironmentAwareInvoked(ctx, prodWebEnv);
}
 
Example 11
Source File: EnvironmentSystemIntegrationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void annotationConfigWebApplicationContext() {
	AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
	ctx.setEnvironment(prodWebEnv);
	ctx.setConfigLocation(EnvironmentAwareBean.class.getName());
	ctx.refresh();

	assertHasEnvironment(ctx, prodWebEnv);
	assertEnvironmentBeanRegistered(ctx);
	assertEnvironmentAwareInvoked(ctx, prodWebEnv);
}
 
Example 12
Source File: SpringApplicationConfigurator.java    From micro-server with Apache License 2.0 5 votes vote down vote up
@Override
public ConfigurableApplicationContext createSpringApp(Config config, Class... classes) {

    logger.debug("Configuring Spring");
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.setAllowCircularReferences(config.isAllowCircularReferences());
    rootContext.register(classes);

    rootContext.scan(config.getBasePackages());
    rootContext.refresh();
    logger.debug("Configuring Additional Spring Beans");
    ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) rootContext).getBeanFactory();

    config.getDataSources()
          .stream()
            .map(Tuple2::_1)
          .filter(it -> !new ConfigAccessor().get()
                                             .getDefaultDataSourceName()
                                             .equals(it))
          .forEach(name -> {

              List<SpringDBConfig> dbConfig = getConfig(config, rootContext, beanFactory);
              dbConfig.forEach(spring -> spring.createSpringApp(name));

          });
    logger.debug("Finished Configuring Spring");

    return rootContext;
}
 
Example 13
Source File: ConvertingEncoderDecoderSupportTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void setup(Class<?> configurationClass) {
	AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
	applicationContext.register(configurationClass);
	applicationContext.refresh();
	this.applicationContext = applicationContext;
	ContextLoaderTestUtils.setCurrentWebApplicationContext(this.applicationContext);
}
 
Example 14
Source File: PropertySources.java    From rice with Educational Community License v2.0 5 votes vote down vote up
protected static PropertySource<?> getPropertySource(String className, AnnotationConfigWebApplicationContext context) {
    try {
        logger.info("Loading [{}] to setup a Spring property source", className);
        Class<?> annotatedClass = Class.forName(className);
        context.register(annotatedClass);
        context.refresh();
        PropertySource<?> propertySource = getPropertySource(context, annotatedClass);
        context.close();
        logger.info("Spring property source was successfully setup");
        return propertySource;
    } catch (Exception e) {
        throw new IllegalStateException("Unexpected error configuring Spring property source", e);
    }
}
 
Example 15
Source File: HandlerMappingIntrospectorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void getCorsConfigurationActual() throws Exception {
	AnnotationConfigWebApplicationContext cxt = new AnnotationConfigWebApplicationContext();
	cxt.register(TestConfig.class);
	cxt.refresh();

	MockHttpServletRequest request = new MockHttpServletRequest("POST", "/path");
	request.addHeader("Origin", "http://localhost:9000");
	CorsConfiguration corsConfig = getIntrospector(cxt).getCorsConfiguration(request);

	assertNotNull(corsConfig);
	assertEquals(Collections.singletonList("http://localhost:9000"), corsConfig.getAllowedOrigins());
	assertEquals(Collections.singletonList("POST"), corsConfig.getAllowedMethods());
}
 
Example 16
Source File: SharedTest.java    From chassis with Apache License 2.0 4 votes vote down vote up
@Test
public void testClassPath() throws Exception {

       Map<String, Object> properties = new HashMap<String, Object>();
       properties.put("admin.enabled", "true");
       properties.put("admin.port", "" + SocketUtils.findAvailableTcpPort());
       properties.put("admin.hostname", "localhost");

       properties.put("websocket.enabled", "true");
       properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
       properties.put("websocket.hostname", "localhost");

       properties.put("http.enabled", "true");
       properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
       properties.put("http.hostname", "localhost");

       AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
       StandardEnvironment environment = new StandardEnvironment();
       environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
       context.setEnvironment(environment);
       context.register(PropertySourcesPlaceholderConfigurer.class);
       context.register(TransportConfiguration.class);
       context.register(MetricsConfiguration.class);
	RestTemplate httpClient = new RestTemplate();
	
	try {
		context.refresh();

		httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
		List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
		for (MessageSerDe messageSerDe : context.getBeansOfType(MessageSerDe.class).values()) {
			messageConverters.add(new SerDeHttpMessageConverter(messageSerDe));
		}
		messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
		httpClient.setMessageConverters(messageConverters);

		ResponseEntity<String> response = httpClient.getForEntity(new URI("http://localhost:" + properties.get("admin.port") + "/admin/classpath"), String.class);
		
		logger.info("Got response: [{}]", response);
		
		Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value());
		Assert.assertTrue(response.getBody().length() > 0);
	} finally {
		context.close();
	}
}
 
Example 17
Source File: SharedTest.java    From chassis with Apache License 2.0 4 votes vote down vote up
@Test
public void testHealthcheck() throws Exception {
	Map<String, Object> properties = new HashMap<String, Object>();
	properties.put("admin.enabled", "true");
	properties.put("admin.port", "" + SocketUtils.findAvailableTcpPort());
	properties.put("admin.hostname", "localhost");
	
	properties.put("websocket.enabled", "true");
	properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
	properties.put("websocket.hostname", "localhost");

	properties.put("http.enabled", "true");
	properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
	properties.put("http.hostname", "localhost");
	
	AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
	StandardEnvironment environment = new StandardEnvironment();
	environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
	context.setEnvironment(environment);
	context.register(PropertySourcesPlaceholderConfigurer.class);
	context.register(TransportConfiguration.class);
	context.register(MetricsConfiguration.class);

	RestTemplate httpClient = new RestTemplate();
	
	try {
		context.refresh();

		httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
		List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
		for (MessageSerDe messageSerDe : context.getBeansOfType(MessageSerDe.class).values()) {
			messageConverters.add(new SerDeHttpMessageConverter(messageSerDe));
		}
		messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
		httpClient.setMessageConverters(messageConverters);

		ResponseEntity<String> response = httpClient.getForEntity(new URI("http://localhost:" + properties.get("admin.port") + "/healthcheck"), String.class);
		
		logger.info("Got response: [{}]", response);
		
		Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value());
		Assert.assertEquals("OK", response.getBody());
	} finally {
		context.close();
	}
}
 
Example 18
Source File: HybridServiceTest.java    From chassis with Apache License 2.0 4 votes vote down vote up
@Test
public void testHybridService() throws Exception {
	Map<String, Object> properties = new HashMap<String, Object>();
	properties.put("websocket.enabled", "true");
	properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
	properties.put("websocket.hostname", "localhost");

	properties.put("http.enabled", "true");
	properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
	properties.put("http.hostname", "localhost");
	
	AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
	StandardEnvironment environment = new StandardEnvironment();
	environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
	context.setEnvironment(environment);
	context.register(PropertySourcesPlaceholderConfigurer.class);
	context.register(TransportConfiguration.class);
	context.register(TestCombinedService.class);

	WebSocketClient wsClient = new WebSocketClient();

	RestTemplate httpClient = new RestTemplate();
	
	try {
		context.refresh();

		final MessageSerDe serDe = context.getBean(ProtobufMessageSerDe.class);

		final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class);
		
		messageRegistry.registerType("stuff", TestObject.class);
		
		wsClient.start();

		httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
		List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
		for (MessageSerDe messageSerDe : context.getBeansOfType(MessageSerDe.class).values()) {
			messageConverters.add(new SerDeHttpMessageConverter(messageSerDe));
		}
		messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
		httpClient.setMessageConverters(messageConverters);
		
		QueuingWebSocketListener webSocket = new QueuingWebSocketListener(serDe, messageRegistry, null);

		Session session = wsClient.connect(webSocket, new URI("ws://localhost:" +  properties.get("websocket.port") + "/protobuf")).get(5000, TimeUnit.MILLISECONDS);

		Envelope envelope = new Envelope("getStuff", null, null, null);
		
		session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));
		
		TestObject response = webSocket.getResponse(5, TimeUnit.SECONDS);
		
		Assert.assertNotNull(response);
		Assert.assertEquals("stuff", response.value);

		byte[] rawStuff = serDe.serialize(new TestObject("more stuff"));
		
		envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff));
		
		session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));
		
		response = webSocket.getResponse(5, TimeUnit.SECONDS);
		
		Assert.assertNotNull(response);
		Assert.assertEquals("stuff", response.value);

		envelope = new Envelope("getStuff", null, null, null);
		
		session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));
		
		response = webSocket.getResponse(5, TimeUnit.SECONDS);
		
		Assert.assertNotNull(response);
		Assert.assertEquals("more stuff", response.value);
		
		response = httpClient.getForObject(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), 
				TestObject.class);
		
		Assert.assertNotNull(response);
		Assert.assertEquals("more stuff", response.value);

		response = httpClient.postForObject(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), 
				new TestObject("even more stuff"),
				TestObject.class);
		
		Assert.assertNotNull(response);
		Assert.assertEquals("more stuff", response.value);
		
		response = httpClient.getForObject(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), 
				TestObject.class);
		
		Assert.assertNotNull(response);
		Assert.assertEquals("even more stuff", response.value);
	} finally {
		try {
			wsClient.stop();
		} finally {
			context.close();
		}
	}
}
 
Example 19
Source File: MetricsTest.java    From chassis with Apache License 2.0 4 votes vote down vote up
@Test
public void testMetricsPing() throws Exception {
	Map<String, Object> properties = new HashMap<String, Object>();
	properties.put("admin.enabled", "true");
	properties.put("admin.port", "" + SocketUtils.findAvailableTcpPort());
	properties.put("admin.hostname", "localhost");
	
	properties.put("websocket.enabled", "true");
	properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
	properties.put("websocket.hostname", "localhost");

	properties.put("http.enabled", "true");
	properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
	properties.put("http.hostname", "localhost");
	
	AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
	StandardEnvironment environment = new StandardEnvironment();
	environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
	context.setEnvironment(environment);
	context.register(PropertySourcesPlaceholderConfigurer.class);
	context.register(TransportConfiguration.class);
	context.register(MetricsConfiguration.class);

	RestTemplate httpClient = new RestTemplate();
	
	try {
		context.refresh();

		httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
		List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
		for (MessageSerDe serDe : context.getBeansOfType(MessageSerDe.class).values()) {
			messageConverters.add(new SerDeHttpMessageConverter(serDe));
		}
		messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
		httpClient.setMessageConverters(messageConverters);

		ResponseEntity<String> response = httpClient.getForEntity(new URI("http://localhost:" + properties.get("admin.port") + "/metrics/ping"), String.class);
		
		logger.info("Got response: [{}]", response);
		
		Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value());
		Assert.assertEquals("pong".trim(), response.getBody().trim());
	} finally {
		context.close();
	}
}
 
Example 20
Source File: SharedTest.java    From chassis with Apache License 2.0 4 votes vote down vote up
@Test
public void testProperties() throws Exception {
	Map<String, Object> properties = new HashMap<String, Object>();
	properties.put("admin.enabled", "true");
	properties.put("admin.port", "" + SocketUtils.findAvailableTcpPort());
	properties.put("admin.hostname", "localhost");
	
	properties.put("websocket.enabled", "true");
	properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
	properties.put("websocket.hostname", "localhost");

	properties.put("http.enabled", "true");
	properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
	properties.put("http.hostname", "localhost");
	
	AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
	StandardEnvironment environment = new StandardEnvironment();
	environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
	context.setEnvironment(environment);
	context.register(PropertySourcesPlaceholderConfigurer.class);
	context.register(TransportConfiguration.class);
	context.register(MetricsConfiguration.class);

	RestTemplate httpClient = new RestTemplate();
	
	try {
		context.refresh();

		httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
		List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
		for (MessageSerDe messageSerDe : context.getBeansOfType(MessageSerDe.class).values()) {
			messageConverters.add(new SerDeHttpMessageConverter(messageSerDe));
		}
		messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
		httpClient.setMessageConverters(messageConverters);

		ResponseEntity<String> response = httpClient.getForEntity(new URI("http://localhost:" + properties.get("admin.port") + "/admin/properties"), String.class);
		
		logger.info("Got response: [{}]", response);
		
		Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value());
		Assert.assertTrue(response.getBody().contains("user.dir=" + System.getProperty("user.dir")));
	} finally {
		context.close();
	}
}