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

The following examples show how to use org.springframework.web.context.support.AnnotationConfigWebApplicationContext#register() . 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: 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 2
Source File: WebAppConfiguration.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.setServletContext(servletContext);
    rootContext.register(ThymeleafConfig.class);

    servletContext.addListener(new ToolListener());
    servletContext.addListener(new SakaiContextLoaderListener(rootContext));
    
    FilterRegistration requestFilterRegistration = servletContext.addFilter("sakai.request", RequestFilter.class);
    requestFilterRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE), true, "/*");
    requestFilterRegistration.setInitParameter(RequestFilter.CONFIG_UPLOAD_ENABLED, "true");       

    Dynamic servlet = servletContext.addServlet("sakai-site-group-manager", new DispatcherServlet(rootContext));
    servlet.addMapping("/");
    servlet.setLoadOnStartup(1);
}
 
Example 3
Source File: WebAppConfiguration.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.setServletContext(servletContext);
    rootContext.register(ThymeleafConfig.class);

    servletContext.addListener(new ToolListener());
    servletContext.addListener(new SakaiContextLoaderListener(rootContext));

    servletContext.addFilter("sakai.request", RequestFilter.class)
            .addMappingForUrlPatterns(
                    EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE),
                    true,
                    "/*");

    Dynamic servlet = servletContext.addServlet("sakai.message.bundle.manager", new DispatcherServlet(rootContext));
    servlet.addMapping("/");
    servlet.setLoadOnStartup(1);
}
 
Example 4
Source File: MyWebAppInitializer.java    From resteasy-examples with Apache License 2.0 6 votes vote down vote up
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    // `ResteasyBootstrap` is not mandatory if you want to setup `ResteasyContext` and `ResteasyDeployment` manually.
    servletContext.addListener(ResteasyBootstrap.class);

    // Create Spring context.
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    context.register(MyConfig.class);

    // Implement our own `ContextLoaderListener`, so we can implement our own `SpringBeanProcessor` if necessary.
    servletContext.addListener(new MyContextLoaderListener(context));

    // We can use `HttpServletDispatcher` or `FilterDispatcher` here, and implement our own solution.
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("resteasy-dispatcher", new HttpServletDispatcher());
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/rest/*");
}
 
Example 5
Source File: WebConfigurer.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes Spring and Spring MVC.
 */
private ServletRegistration.Dynamic initSpring(ServletContext servletContext, AnnotationConfigWebApplicationContext rootContext) {
    LOGGER.debug("Configuring Spring Web application context");
    AnnotationConfigWebApplicationContext dispatcherServletConfiguration = new AnnotationConfigWebApplicationContext();
    dispatcherServletConfiguration.setParent(rootContext);
    dispatcherServletConfiguration.register(DispatcherServletConfiguration.class);

    LOGGER.debug("Registering Spring MVC Servlet");
    ServletRegistration.Dynamic dispatcherServlet = servletContext.addServlet("dispatcher", new DispatcherServlet(dispatcherServletConfiguration));
    dispatcherServlet.addMapping("/service/*");
    dispatcherServlet.setMultipartConfig(new MultipartConfigElement((String) null));
    dispatcherServlet.setLoadOnStartup(1);
    dispatcherServlet.setAsyncSupported(true);

    return dispatcherServlet;
}
 
Example 6
Source File: ResourceUrlProviderJavaConfigTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Before
@SuppressWarnings("resource")
public void setup() throws Exception {
	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();

	this.filterChain = new MockFilterChain(this.servlet,
			new ResourceUrlEncodingFilter(),
			(request, response, chain) -> {
				Object urlProvider = context.getBean(ResourceUrlProvider.class);
				request.setAttribute(ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR, urlProvider);
				chain.doFilter(request, response);
			});
}
 
Example 7
Source File: WebAppConfiguration.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.setServletContext(servletContext);
    rootContext.register(ThymeleafConfig.class);

    servletContext.addListener(new ToolListener());
    servletContext.addListener(new SakaiContextLoaderListener(rootContext));
    
    FilterRegistration requestFilterRegistration = servletContext.addFilter("sakai.request", RequestFilter.class);
    requestFilterRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE), true, "/*");
    requestFilterRegistration.setInitParameter(RequestFilter.CONFIG_UPLOAD_ENABLED, "true");       

    Dynamic servlet = servletContext.addServlet("sakai-site-group-manager", new DispatcherServlet(rootContext));
    servlet.addMapping("/");
    servlet.setLoadOnStartup(1);
}
 
Example 8
Source File: TraceeInterceptorSpringApplicationInitializer.java    From tracee with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void initialize(AnnotationConfigWebApplicationContext applicationContext) {
	final AnnotationConfigWebApplicationContext rootCtx = new AnnotationConfigWebApplicationContext();
	rootCtx.register(TraceeInterceptorSpringConfig.class);
	final ServletContext servletContext = applicationContext.getServletContext();

	// Manage the lifecycle of the root application context
	servletContext.addListener(new ContextLoaderListener(rootCtx));

	// Create the dispatcher servlet's Spring application context
	AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
	dispatcherContext.register(TraceeInterceptorSpringConfig.class);

	// Register and map the dispatcher servlet
	ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
	dispatcher.setLoadOnStartup(1);
	dispatcher.addMapping("/");

}
 
Example 9
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 10
Source File: SpringWebInitializer.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
private void useRootContext(ServletContext container) {
  // Create the 'root' Spring application context
  AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
  rootContext.register(SpringContextConfig.class); // <-- Use RootConfig.java
	 
  // Manage the lifecycle of the root application context
  container.addListener(new ContextLoaderListener(rootContext));
}
 
Example 11
Source File: StudentControllerConfig.java    From tutorials with MIT License 5 votes vote down vote up
public void onStartup(ServletContext sc) throws ServletException {
    AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
    root.register(WebConfig.class);
    root.setServletContext(sc);
    sc.addListener(new ContextLoaderListener(root));

    DispatcherServlet dv = new DispatcherServlet(root);
    
    ServletRegistration.Dynamic appServlet = sc.addServlet("test-mvc", dv);
    appServlet.setLoadOnStartup(1);
    appServlet.addMapping("/test/*");
}
 
Example 12
Source File: AppInitializer.java    From FRC-2018-Public with MIT License 5 votes vote down vote up
public void onStartup(ServletContext container) throws ServletException {
    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    ctx.register(AppConfig.class);
    ctx.setServletContext(container);

    ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx));

    servlet.setLoadOnStartup(1);
    servlet.addMapping("/");
}
 
Example 13
Source File: SpringWebinitializer.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
private void addDispatcherContext(ServletContext container) {
  // Create the dispatcher servlet's Spring application context
  AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
  dispatcherContext.register(SpringDispatcherConfig.class); 
	 
  // Declare  <servlet> and <servlet-mapping> for the DispatcherServlet
  ServletRegistration.Dynamic dispatcher = container.addServlet("ch07-servlet", 
  		new DispatcherServlet(dispatcherContext));
  dispatcher.addMapping("/");
  dispatcher.setLoadOnStartup(1);
  
 
     
}
 
Example 14
Source File: AbstractAnnotationConfigDispatcherServletInitializer.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>This implementation creates an {@link AnnotationConfigWebApplicationContext},
 * providing it the annotated classes returned by {@link #getRootConfigClasses()}.
 * Returns {@code null} if {@link #getRootConfigClasses()} returns {@code null}.
 */
@Override
@Nullable
protected WebApplicationContext createRootApplicationContext() {
	Class<?>[] configClasses = getRootConfigClasses();
	if (!ObjectUtils.isEmpty(configClasses)) {
		AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
		context.register(configClasses);
		return context;
	}
	else {
		return null;
	}
}
 
Example 15
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 16
Source File: MolgenisWebAppInitializer.java    From molgenis with GNU Lesser General Public License v3.0 4 votes vote down vote up
/** A Molgenis common web application initializer */
protected void onStartup(ServletContext servletContext, Class<?> appConfig, int maxFileSize) {
  // Create the 'root' Spring application context
  AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
  rootContext.registerShutdownHook();
  rootContext.setAllowBeanDefinitionOverriding(false);
  rootContext.register(appConfig);

  // Manage the lifecycle of the root application context
  servletContext.addListener(new ContextLoaderListener(rootContext));

  // Register and map the dispatcher servlet
  DispatcherServlet dispatcherServlet = new DispatcherServlet(rootContext);
  dispatcherServlet.setDispatchOptionsRequest(true);
  // instead of throwing a 404 when a handler is not found allow for custom handling
  dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);

  ServletRegistration.Dynamic dispatcherServletRegistration =
      servletContext.addServlet("dispatcher", dispatcherServlet);
  if (dispatcherServletRegistration == null) {
    LOG.warn(
        "ServletContext already contains a complete ServletRegistration for servlet 'dispatcher'");
  } else {
    final long maxSize = (long) maxFileSize * MB;
    dispatcherServletRegistration.addMapping("/");
    dispatcherServletRegistration.setMultipartConfig(
        new MultipartConfigElement(null, maxSize, maxSize, FILE_SIZE_THRESHOLD));
    dispatcherServletRegistration.setAsyncSupported(true);
  }

  // Add filters
  Dynamic browserDetectionFiler =
      servletContext.addFilter("browserDetectionFilter", BrowserDetectionFilter.class);
  browserDetectionFiler.setAsyncSupported(true);
  browserDetectionFiler.addMappingForUrlPatterns(
      EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC), false, "*");

  Dynamic etagFilter = servletContext.addFilter("etagFilter", ShallowEtagHeaderFilter.class);
  etagFilter.setAsyncSupported(true);
  etagFilter.addMappingForServletNames(
      EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC), true, "dispatcher");

  // enable use of request scoped beans in FrontController
  servletContext.addListener(new RequestContextListener());

  servletContext.addListener(HttpSessionEventPublisher.class);
}
 
Example 17
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();
	}
}
 
Example 18
Source File: WebSocketTransportTest.java    From chassis with Apache License 2.0 4 votes vote down vote up
@Test
public void testEmptyWebSocketFrameUsingBinary() 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", "false");
	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(TestWebSocketService.class);

	WebSocketClient wsClient = new WebSocketClient();
	
	try {
		//start server
		context.refresh();

		// start client
		wsClient.start();

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

		final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class);
		
		QueuingWebSocketListener listener = new QueuingWebSocketListener(serDe, messageRegistry, null);
		
		WebSocketSession session = (WebSocketSession)wsClient.connect(listener, new URI("ws://localhost:" +  properties.get("websocket.port") + "/" + serDe.getMessageFormatName()))
				.get(5000, TimeUnit.MILLISECONDS);
		
		session.getRemote().sendBytes(ByteBuffer.wrap(new byte[0]));
		
		ServiceError error = listener.getResponse(5, TimeUnit.SECONDS);
		
		Assert.assertNotNull(error);
		Assert.assertEquals("EMPTY_ENVELOPE", error.code);
		Assert.assertEquals("STOPPED", session.getState());
	} finally {
		try {
			wsClient.stop();
		} finally {
			context.close();
		}
	}
}
 
Example 19
Source File: TestServerUtil.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
public static TestServer createAndStartServer(Class<?>... configClasses) {
    AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
    applicationContext.register(configClasses);
    applicationContext.refresh();
    return createAndStartServer(applicationContext);
}
 
Example 20
Source File: JettyEmbeddedContainer.java    From gravitee-management-rest-api with Apache License 2.0 3 votes vote down vote up
protected ServletContextHandler configureAPI(String apiContextPath, String applicationName, Class<? extends GlobalAuthenticationConfigurerAdapter> securityConfigurationClass) {
    final ServletContextHandler childContext = new ServletContextHandler(server, apiContextPath, ServletContextHandler.SESSIONS);

    final ServletHolder servletHolder = new ServletHolder(ServletContainer.class);
    servletHolder.setInitParameter("javax.ws.rs.Application", applicationName);
    servletHolder.setInitOrder(0);
    childContext.addServlet(servletHolder, "/*");

    AnnotationConfigWebApplicationContext webApplicationContext = new AnnotationConfigWebApplicationContext();
    webApplicationContext.register(securityConfigurationClass);

    webApplicationContext.setEnvironment((ConfigurableEnvironment) applicationContext.getEnvironment());
    webApplicationContext.setParent(applicationContext);

    childContext.addEventListener(new ContextLoaderListener(webApplicationContext));

    // Spring Security filter
    childContext.addFilter(new FilterHolder(new DelegatingFilterProxy("springSecurityFilterChain")),"/*", EnumSet.allOf(DispatcherType.class));
    return childContext;


}