/**
   * Load a Spring {@link WebApplicationContext} from the supplied {@link
   * MergedContextConfiguration}.
   *
   * <p>Implementation details:
   *
   * <ul>
   *   <li>Creates a {@link GenericWebApplicationContext} instance.
   *   <li>Delegates to {@link #configureWebResources} to create the {@link MockServletContext} and
   *       set it in the {@code WebApplicationContext}.
   *   <li>Calls {@link #prepareContext} to allow for customizing the context before bean
   *       definitions are loaded.
   *   <li>Calls {@link #customizeBeanFactory} to allow for customizing the context's {@code
   *       DefaultListableBeanFactory}.
   *   <li>Delegates to {@link #loadBeanDefinitions} to populate the context from the locations or
   *       classes in the supplied {@code MergedContextConfiguration}.
   *   <li>Delegates to {@link AnnotationConfigUtils} for {@linkplain
   *       AnnotationConfigUtils#registerAnnotationConfigProcessors registering} annotation
   *       configuration processors.
   *   <li>Calls {@link #customizeContext} to allow for customizing the context before it is
   *       refreshed.
   *   <li>{@link ConfigurableApplicationContext#refresh Refreshes} the context and registers a JVM
   *       shutdown hook for it.
   * </ul>
   *
   * @return a new web application context
   * @see
   *     org.springframework.test.context.SmartContextLoader#loadContext(MergedContextConfiguration)
   * @see GenericWebApplicationContext
   */
  @Override
  public final ConfigurableApplicationContext loadContext(MergedContextConfiguration mergedConfig)
      throws Exception {

    if (!(mergedConfig instanceof WebMergedContextConfiguration)) {
      throw new IllegalArgumentException(
          String.format(
              "Cannot load WebApplicationContext from non-web merged context configuration %s. "
                  + "Consider annotating your test class with @WebAppConfiguration.",
              mergedConfig));
    }
    WebMergedContextConfiguration webMergedConfig = (WebMergedContextConfiguration) mergedConfig;

    if (logger.isDebugEnabled()) {
      logger.debug(
          String.format(
              "Loading WebApplicationContext for merged context configuration %s.",
              webMergedConfig));
    }

    GenericWebApplicationContext context = new GenericWebApplicationContext();
    configureWebResources(context, webMergedConfig);
    prepareContext(context, webMergedConfig);
    customizeBeanFactory(context.getDefaultListableBeanFactory(), webMergedConfig);
    loadBeanDefinitions(context, webMergedConfig);
    AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
    customizeContext(context, webMergedConfig);
    context.refresh();
    context.registerShutdownHook();
    return context;
  }
 @Override
 protected WebApplicationContext initApplicationContext() {
   MockServletContext servletContext = new MockServletContext();
   applicationContext = new GenericWebApplicationContext(servletContext);
   applicationContext.refresh();
   applicationContext.getAutowireCapableBeanFactory().initializeBean(validator, "validator");
   return applicationContext;
 }
 @Test
 public void testMessageConverters() {
   loadBeanDefinitions("mvc-config-message-converters.xml");
   verifyMessageConverters(appContext.getBean(RequestMappingHandlerAdapter.class), true);
   verifyMessageConverters(appContext.getBean(ExceptionHandlerExceptionResolver.class), true);
   verifyResponseBodyAdvice(appContext.getBean(RequestMappingHandlerAdapter.class));
   verifyResponseBodyAdvice(appContext.getBean(ExceptionHandlerExceptionResolver.class));
 }
 private WebApplicationContext initApplicationContext(String scope) {
   MockServletContext sc = new MockServletContext();
   GenericWebApplicationContext ac = new GenericWebApplicationContext(sc);
   GenericBeanDefinition bd = new GenericBeanDefinition();
   bd.setBeanClass(DerivedTestBean.class);
   bd.setScope(scope);
   ac.registerBeanDefinition(NAME, bd);
   ac.refresh();
   return ac;
 }
  @Test
  public void sockJsAttributesSupport() {
    loadBeanDefinitions("websocket-config-handlers-sockjs-attributes.xml");
    SimpleUrlHandlerMapping handlerMapping = appContext.getBean(SimpleUrlHandlerMapping.class);
    assertNotNull(handlerMapping);
    SockJsHttpRequestHandler handler =
        (SockJsHttpRequestHandler) handlerMapping.getUrlMap().get("/test/**");
    assertNotNull(handler);
    checkDelegateHandlerType(handler.getWebSocketHandler(), TestWebSocketHandler.class);
    SockJsService sockJsService = handler.getSockJsService();
    assertNotNull(sockJsService);
    assertThat(sockJsService, Matchers.instanceOf(TransportHandlingSockJsService.class));
    TransportHandlingSockJsService defaultSockJsService =
        (TransportHandlingSockJsService) sockJsService;
    assertThat(
        defaultSockJsService.getTaskScheduler(), Matchers.instanceOf(TestTaskScheduler.class));
    assertThat(
        defaultSockJsService.getTransportHandlers().values(),
        Matchers.containsInAnyOrder(
            Matchers.instanceOf(XhrPollingTransportHandler.class),
            Matchers.instanceOf(XhrStreamingTransportHandler.class)));

    assertEquals("testSockJsService", defaultSockJsService.getName());
    assertFalse(defaultSockJsService.isWebSocketEnabled());
    assertFalse(defaultSockJsService.isSessionCookieNeeded());
    assertEquals(2048, defaultSockJsService.getStreamBytesLimit());
    assertEquals(256, defaultSockJsService.getDisconnectDelay());
    assertEquals(1024, defaultSockJsService.getHttpMessageCacheSize());
    assertEquals(20, defaultSockJsService.getHeartbeatTime());
  }
 @Test
 public void beanNameUrlHandlerMapping() {
   loadBeanDefinitions("mvc-config.xml");
   BeanNameUrlHandlerMapping mapping = appContext.getBean(BeanNameUrlHandlerMapping.class);
   assertNotNull(mapping);
   assertEquals(2, mapping.getOrder());
 }
 private void loadBeanDefinitions(String fileName) {
   XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
   ClassPathResource resource =
       new ClassPathResource(fileName, AnnotationDrivenBeanDefinitionParserTests.class);
   reader.loadBeanDefinitions(resource);
   appContext.refresh();
 }
 public ApplicationContext loadContext(String... locations) throws Exception {
   if (logger.isDebugEnabled()) {
     logger.debug(
         "Loading ApplicationContext for locations ["
             + StringUtils.arrayToCommaDelimitedString(locations)
             + "].");
   }
   GenericWebApplicationContext context = new GenericWebApplicationContext();
   prepareContext(context);
   customizeBeanFactory(context.getDefaultListableBeanFactory());
   createBeanDefinitionReader(context).loadBeanDefinitions(locations);
   AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
   customizeContext(context);
   context.refresh();
   context.registerShutdownHook();
   return context;
 }
 @Override
 protected void onRefresh() {
   super.onRefresh();
   try {
     initPropertySources();
   } catch (Throwable ex) {
     throw new ApplicationContextException("Unable to start embedded container", ex);
   }
 }
  public ApplicationContext loadContext(MergedContextConfiguration config) throws Exception {
    GenericWebApplicationContext context = new GenericWebApplicationContext();

    // Commented out until SPR-10392 is fixed and we can upgrade to Spring 3.2.3.RELEASE or higher
    //		ApplicationContext parent = config.getParentApplicationContext();
    //		if(parent != null) {
    //			context.setParent(parent);
    //		}

    prepareContext(context);
    prepareContext(context, config);
    customizeBeanFactory(context.getDefaultListableBeanFactory());
    createBeanDefinitionReader(context).loadBeanDefinitions(config.getLocations());
    AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
    customizeContext(context);
    context.refresh();
    context.registerShutdownHook();

    return context;
  }
 @AfterClass
 public static void afterClassClearContextBaseResourceProviderDstu3Test() throws Exception {
   ourServer.stop();
   ourHttpClient.close();
   ourServer = null;
   ourHttpClient = null;
   myValidationSupport.flush();
   myValidationSupport = null;
   ourWebApplicationContext.close();
   ourWebApplicationContext = null;
   TestUtil.clearAllStaticFieldsForUnitTest();
 }
 @SuppressWarnings("unchecked")
 @Test
 public void testReturnValueHandlers() {
   loadBeanDefinitions("mvc-config-return-value-handlers.xml");
   RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
   assertNotNull(adapter);
   Object value = new DirectFieldAccessor(adapter).getPropertyValue("customReturnValueHandlers");
   assertNotNull(value);
   assertTrue(value instanceof List);
   List<HandlerMethodReturnValueHandler> handlers = (List<HandlerMethodReturnValueHandler>) value;
   assertEquals(1, handlers.size());
   assertEquals(TestHandlerMethodReturnValueHandler.class, handlers.get(0).getClass());
 }
  /**
   * Configures web resources for the supplied web application context.
   *
   * <p>Implementation details:
   *
   * <ul>
   *   <li>The resource base path is retrieved from the supplied {@code
   *       WebMergedContextConfiguration}.
   *   <li>A {@link ResourceLoader} is instantiated for the {@link MockServletContext}: if the
   *       resource base path is prefixed with "{@code classpath:}", a {@link DefaultResourceLoader}
   *       will be used; otherwise, a {@link FileSystemResourceLoader} will be used.
   *   <li>A {@code MockServletContext} will be created using the resource base path and resource
   *       loader.
   *   <li>The supplied {@link GenericWebApplicationContext} is then stored in the {@code
   *       MockServletContext} under the {@link
   *       WebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE} key.
   *   <li>Finally, the {@code MockServletContext} is set in the {@code WebApplicationContext}.
   *
   * @param context the web application context for which to configure the web resources
   * @param webMergedConfig the merged context configuration to use to load the web application
   *     context
   */
  protected void configureWebResources(
      GenericWebApplicationContext context, WebMergedContextConfiguration webMergedConfig) {

    String resourceBasePath = webMergedConfig.getResourceBasePath();
    ResourceLoader resourceLoader =
        resourceBasePath.startsWith(ResourceLoader.CLASSPATH_URL_PREFIX)
            ? new DefaultResourceLoader()
            : new FileSystemResourceLoader();

    ServletContext servletContext = new MockServletContext(resourceBasePath, resourceLoader);
    servletContext.setAttribute(
        WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
    context.setServletContext(servletContext);
  }
 @Test
 public void testPathMatchingConfiguration() {
   loadBeanDefinitions("mvc-config-path-matching.xml");
   RequestMappingHandlerMapping hm = appContext.getBean(RequestMappingHandlerMapping.class);
   assertNotNull(hm);
   assertTrue(hm.useSuffixPatternMatch());
   assertFalse(hm.useTrailingSlashMatch());
   assertTrue(hm.useRegisteredSuffixPatternMatch());
   assertThat(hm.getUrlPathHelper(), Matchers.instanceOf(TestPathHelper.class));
   assertThat(hm.getPathMatcher(), Matchers.instanceOf(TestPathMatcher.class));
   List<String> fileExtensions = hm.getContentNegotiationManager().getAllFileExtensions();
   assertThat(fileExtensions, Matchers.contains("xml"));
   assertThat(fileExtensions, Matchers.hasSize(1));
 }
 @Test
 public void testMessageCodesResolver() {
   loadBeanDefinitions("mvc-config-message-codes-resolver.xml");
   RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
   assertNotNull(adapter);
   Object initializer = adapter.getWebBindingInitializer();
   assertNotNull(initializer);
   MessageCodesResolver resolver =
       ((ConfigurableWebBindingInitializer) initializer).getMessageCodesResolver();
   assertNotNull(resolver);
   assertEquals(TestMessageCodesResolver.class, resolver.getClass());
   assertEquals(
       false, new DirectFieldAccessor(adapter).getPropertyValue("ignoreDefaultModelOnRedirect"));
 }
 @SuppressWarnings("unchecked")
 @Test
 public void testArgumentResolvers() {
   loadBeanDefinitions("mvc-config-argument-resolvers.xml");
   RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
   assertNotNull(adapter);
   Object value = new DirectFieldAccessor(adapter).getPropertyValue("customArgumentResolvers");
   assertNotNull(value);
   assertTrue(value instanceof List);
   List<HandlerMethodArgumentResolver> resolvers = (List<HandlerMethodArgumentResolver>) value;
   assertEquals(2, resolvers.size());
   assertTrue(resolvers.get(0) instanceof ServletWebArgumentResolverAdapter);
   assertTrue(resolvers.get(1) instanceof TestHandlerMethodArgumentResolver);
 }
  @Test
  @SuppressWarnings("unchecked")
  public void websocketHandlersAttributes() {
    loadBeanDefinitions("websocket-config-handlers-attributes.xml");
    HandlerMapping handlerMapping = appContext.getBean(HandlerMapping.class);
    assertNotNull(handlerMapping);
    assertTrue(handlerMapping instanceof SimpleUrlHandlerMapping);

    SimpleUrlHandlerMapping urlHandlerMapping = (SimpleUrlHandlerMapping) handlerMapping;
    assertEquals(2, urlHandlerMapping.getOrder());

    WebSocketHttpRequestHandler handler =
        (WebSocketHttpRequestHandler) urlHandlerMapping.getUrlMap().get("/foo");
    assertNotNull(handler);
    checkDelegateHandlerType(handler.getWebSocketHandler(), FooWebSocketHandler.class);
    HandshakeHandler handshakeHandler =
        (HandshakeHandler) new DirectFieldAccessor(handler).getPropertyValue("handshakeHandler");
    assertNotNull(handshakeHandler);
    assertTrue(handshakeHandler instanceof TestHandshakeHandler);
    List<HandshakeInterceptor> handshakeInterceptorList =
        (List<HandshakeInterceptor>)
            new DirectFieldAccessor(handler).getPropertyValue("interceptors");
    assertNotNull(handshakeInterceptorList);
    assertThat(
        handshakeInterceptorList,
        Matchers.contains(
            Matchers.instanceOf(FooTestInterceptor.class),
            Matchers.instanceOf(BarTestInterceptor.class)));

    handler = (WebSocketHttpRequestHandler) urlHandlerMapping.getUrlMap().get("/test");
    assertNotNull(handler);
    checkDelegateHandlerType(handler.getWebSocketHandler(), TestWebSocketHandler.class);
    handshakeHandler =
        (HandshakeHandler) new DirectFieldAccessor(handler).getPropertyValue("handshakeHandler");
    assertNotNull(handshakeHandler);
    assertTrue(handshakeHandler instanceof TestHandshakeHandler);
    handshakeInterceptorList =
        (List<HandshakeInterceptor>)
            new DirectFieldAccessor(handler).getPropertyValue("interceptors");
    assertNotNull(handshakeInterceptorList);
    assertThat(
        handshakeInterceptorList,
        Matchers.contains(
            Matchers.instanceOf(FooTestInterceptor.class),
            Matchers.instanceOf(BarTestInterceptor.class)));
  }
  private Object getProxyBean(Object handler) {
    GenericWebApplicationContext wac = new GenericWebApplicationContext();
    wac.registerBeanDefinition("controller", new RootBeanDefinition(handler.getClass()));

    DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
    autoProxyCreator.setBeanFactory(wac.getBeanFactory());
    wac.getBeanFactory().addBeanPostProcessor(autoProxyCreator);
    wac.getBeanFactory()
        .registerSingleton("advsr", new DefaultPointcutAdvisor(new SimpleTraceInterceptor()));

    wac.refresh();

    return wac.getBean("controller");
  }
  @Test
  public void sockJsSupport() {
    loadBeanDefinitions("websocket-config-handlers-sockjs.xml");
    SimpleUrlHandlerMapping handlerMapping = appContext.getBean(SimpleUrlHandlerMapping.class);
    assertNotNull(handlerMapping);
    SockJsHttpRequestHandler testHandler =
        (SockJsHttpRequestHandler) handlerMapping.getUrlMap().get("/test/**");
    assertNotNull(testHandler);
    checkDelegateHandlerType(testHandler.getWebSocketHandler(), TestWebSocketHandler.class);
    SockJsService testSockJsService = testHandler.getSockJsService();
    SockJsHttpRequestHandler fooHandler =
        (SockJsHttpRequestHandler) handlerMapping.getUrlMap().get("/foo/**");
    assertNotNull(fooHandler);
    checkDelegateHandlerType(fooHandler.getWebSocketHandler(), FooWebSocketHandler.class);

    SockJsService sockJsService = fooHandler.getSockJsService();
    assertNotNull(sockJsService);
    assertEquals(testSockJsService, sockJsService);

    assertThat(sockJsService, Matchers.instanceOf(DefaultSockJsService.class));
    DefaultSockJsService defaultSockJsService = (DefaultSockJsService) sockJsService;
    assertThat(
        defaultSockJsService.getTaskScheduler(),
        Matchers.instanceOf(ThreadPoolTaskScheduler.class));
    assertThat(
        defaultSockJsService.getTransportHandlers().values(),
        Matchers.containsInAnyOrder(
            Matchers.instanceOf(XhrPollingTransportHandler.class),
            Matchers.instanceOf(XhrReceivingTransportHandler.class),
            Matchers.instanceOf(JsonpPollingTransportHandler.class),
            Matchers.instanceOf(JsonpReceivingTransportHandler.class),
            Matchers.instanceOf(XhrStreamingTransportHandler.class),
            Matchers.instanceOf(EventSourceTransportHandler.class),
            Matchers.instanceOf(HtmlFileTransportHandler.class),
            Matchers.instanceOf(WebSocketTransportHandler.class)));
  }
  @Test
  public void webSocketHandlers() {
    loadBeanDefinitions("websocket-config-handlers.xml");
    Map<String, HandlerMapping> handlersMap = appContext.getBeansOfType(HandlerMapping.class);
    assertNotNull(handlersMap);
    assertThat(handlersMap.values(), Matchers.hasSize(2));

    for (HandlerMapping handlerMapping : handlersMap.values()) {
      assertTrue(handlerMapping instanceof SimpleUrlHandlerMapping);
      SimpleUrlHandlerMapping urlHandlerMapping = (SimpleUrlHandlerMapping) handlerMapping;

      if (urlHandlerMapping.getUrlMap().keySet().contains("/foo")) {
        assertThat(urlHandlerMapping.getUrlMap().keySet(), Matchers.contains("/foo", "/bar"));
        WebSocketHttpRequestHandler handler =
            (WebSocketHttpRequestHandler) urlHandlerMapping.getUrlMap().get("/foo");
        assertNotNull(handler);
        checkDelegateHandlerType(handler.getWebSocketHandler(), FooWebSocketHandler.class);
        HandshakeHandler handshakeHandler =
            (HandshakeHandler)
                new DirectFieldAccessor(handler).getPropertyValue("handshakeHandler");
        assertNotNull(handshakeHandler);
        assertTrue(handshakeHandler instanceof DefaultHandshakeHandler);
      } else {
        assertThat(urlHandlerMapping.getUrlMap().keySet(), Matchers.contains("/test"));
        WebSocketHttpRequestHandler handler =
            (WebSocketHttpRequestHandler) urlHandlerMapping.getUrlMap().get("/test");
        assertNotNull(handler);
        checkDelegateHandlerType(handler.getWebSocketHandler(), TestWebSocketHandler.class);
        HandshakeHandler handshakeHandler =
            (HandshakeHandler)
                new DirectFieldAccessor(handler).getPropertyValue("handshakeHandler");
        assertNotNull(handshakeHandler);
        assertTrue(handshakeHandler instanceof DefaultHandshakeHandler);
      }
    }
  }
  @SuppressWarnings({"unchecked", "rawtypes"})
  @Before
  public void before() throws Exception {
    myFhirCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER);
    myFhirCtx.getRestfulClientFactory().setSocketTimeout(1200 * 1000);

    if (ourServer == null) {
      ourPort = RandomServerPortProvider.findFreePort();

      ourRestServer = new RestfulServer(myFhirCtx);

      ourServerBase = "http://localhost:" + ourPort + "/fhir/context";

      ourRestServer.setResourceProviders((List) myResourceProviders);

      ourRestServer
          .getFhirContext()
          .setNarrativeGenerator(new DefaultThymeleafNarrativeGenerator());

      myTerminologyUploaderProvider = myAppCtx.getBean(TerminologyUploaderProviderDstu3.class);

      ourRestServer.setPlainProviders(mySystemProvider, myTerminologyUploaderProvider);

      JpaConformanceProviderDstu3 confProvider =
          new JpaConformanceProviderDstu3(ourRestServer, mySystemDao, myDaoConfig);
      confProvider.setImplementationDescription("THIS IS THE DESC");
      ourRestServer.setServerConformanceProvider(confProvider);

      ourRestServer.setPagingProvider(myAppCtx.getBean(DatabaseBackedPagingProvider.class));

      Server server = new Server(ourPort);

      ServletContextHandler proxyHandler = new ServletContextHandler();
      proxyHandler.setContextPath("/");

      ServletHolder servletHolder = new ServletHolder();
      servletHolder.setServlet(ourRestServer);
      proxyHandler.addServlet(servletHolder, "/fhir/context/*");

      ourWebApplicationContext = new GenericWebApplicationContext();
      ourWebApplicationContext.setParent(myAppCtx);
      ourWebApplicationContext.refresh();
      //			ContextLoaderListener loaderListener = new ContextLoaderListener(webApplicationContext);
      //			loaderListener.initWebApplicationContext(mock(ServletContext.class));
      //
      proxyHandler
          .getServletContext()
          .setAttribute(
              WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
              ourWebApplicationContext);

      DispatcherServlet dispatcherServlet = new DispatcherServlet();
      //			dispatcherServlet.setApplicationContext(webApplicationContext);
      dispatcherServlet.setContextClass(AnnotationConfigWebApplicationContext.class);
      ServletHolder subsServletHolder = new ServletHolder();
      subsServletHolder.setServlet(dispatcherServlet);
      subsServletHolder.setInitParameter(
          ContextLoader.CONFIG_LOCATION_PARAM, WebsocketDstu3Config.class.getName());
      proxyHandler.addServlet(subsServletHolder, "/*");

      // Register a CORS filter
      CorsConfiguration config = new CorsConfiguration();
      CorsInterceptor corsInterceptor = new CorsInterceptor(config);
      config.addAllowedHeader("x-fhir-starter");
      config.addAllowedHeader("Origin");
      config.addAllowedHeader("Accept");
      config.addAllowedHeader("X-Requested-With");
      config.addAllowedHeader("Content-Type");
      config.addAllowedHeader("Access-Control-Request-Method");
      config.addAllowedHeader("Access-Control-Request-Headers");
      config.addAllowedOrigin("*");
      config.addExposedHeader("Location");
      config.addExposedHeader("Content-Location");
      config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
      ourRestServer.registerInterceptor(corsInterceptor);

      server.setHandler(proxyHandler);
      server.start();

      WebApplicationContext wac =
          WebApplicationContextUtils.getWebApplicationContext(
              subsServletHolder.getServlet().getServletConfig().getServletContext());
      myValidationSupport = wac.getBean(JpaValidationSupportChainDstu3.class);

      ourClient = myFhirCtx.newRestfulGenericClient(ourServerBase);
      ourClient.registerInterceptor(new LoggingInterceptor(true));

      PoolingHttpClientConnectionManager connectionManager =
          new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS);
      HttpClientBuilder builder = HttpClientBuilder.create();
      builder.setConnectionManager(connectionManager);
      ourHttpClient = builder.build();

      ourServer = server;
    }
  }
 @Test
 public void testMessageConvertersWithoutDefaultRegistrations() {
   loadBeanDefinitions("mvc-config-message-converters-defaults-off.xml");
   verifyMessageConverters(appContext.getBean(RequestMappingHandlerAdapter.class), false);
   verifyMessageConverters(appContext.getBean(ExceptionHandlerExceptionResolver.class), false);
 }
 @Override
 public void setServletContext(ServletContext servletContext) {
   super.setServletContext(servletContext);
   prepareWebApplicationContext(servletContext);
 }
  /** {@inheritDoc} */
  public void configureWebApp() throws Exception {
    log.debug("Configuring Jetty webapp");

    // Get context
    WebAppContext context = getWebAppContext();

    // If app is already started...
    if (context.isStarted()) {
      log.debug("Cannot configure webapp after it is started");
      return;
    }

    // Get WEB_INF directory
    Resource webInf = context.getWebInf();
    if (webInf != null && webInf.isDirectory()) {
      // Get properties file with virtualHosts and context path
      Resource config = webInf.addPath("red5-web.properties");
      if (config.exists()) {
        log.debug("Configuring red5-web.properties");
        // Load configuration properties
        Properties props = new Properties();
        props.load(config.getInputStream());

        // Get context path and virtual hosts
        String contextPath = props.getProperty("webapp.contextPath");
        String virtualHosts = props.getProperty("webapp.virtualHosts");

        // Get hostnames
        String[] hostnames = virtualHosts.split(",");
        for (int i = 0; i < hostnames.length; i++) {
          hostnames[i] = hostnames[i].trim();
          if (hostnames[i].equals("*")) {
            // A virtual host "null" must be used so requests for
            // any host will be served.
            hostnames = null;
            break;
          }
        }

        // Set virtual hosts and context path to context
        context.setVirtualHosts(hostnames);
        context.setContextPath(contextPath);
        LoaderBase.setRed5ApplicationContext(contextPath, new JettyApplicationContext(context));
      }
    } else if (webInf == null) {
      // No WEB-INF directory found, register as default application
      log.info(
          "No WEB-INF directory found for "
              + context.getContextPath()
              + ", creating default application.");
      BeanFactoryLocator bfl = ContextSingletonBeanFactoryLocator.getInstance("red5.xml");
      BeanFactoryReference bfr = bfl.useBeanFactory("red5.common");

      // Create WebScope dynamically
      WebScope scope = new WebScope();
      IServer server = (IServer) bfr.getFactory().getBean(IServer.ID);
      scope.setServer(server);
      scope.setGlobalScope(server.getGlobal("default"));

      // Get default Red5 context from context loader that is JettyLoader in this case
      ApplicationContext appCtx = JettyLoader.getApplicationContext();
      ContextLoader loader = (ContextLoader) appCtx.getBean("context.loader");
      appCtx = loader.getContext("default.context");

      // Create context for the WebScope and initialize
      Context scopeContext = new Context();
      scopeContext.setContextPath("/");
      scopeContext.setClientRegistry((IClientRegistry) appCtx.getBean("global.clientRegistry"));
      scopeContext.setMappingStrategy((IMappingStrategy) appCtx.getBean("global.mappingStrategy"));
      scopeContext.setServiceInvoker((IServiceInvoker) appCtx.getBean("global.serviceInvoker"));
      scopeContext.setScopeResolver((IScopeResolver) appCtx.getBean("red5.scopeResolver"));

      // The context needs an ApplicationContext so resources can be
      // resolved
      GenericWebApplicationContext webCtx = new GenericWebApplicationContext();
      webCtx.setDisplayName("Automatic generated WebAppContext");
      webCtx.setParent(appCtx);
      webCtx.setServletContext(ContextHandler.getCurrentContext());
      scopeContext.setApplicationContext(webCtx);

      // Store context in scope
      scope.setContext(scopeContext);

      // Use default ApplicationAdapter as handler
      scope.setHandler(new ApplicationAdapter());

      // Make available as "/<directoryName>" and allow access from all
      // hosts
      scope.setContextPath(context.getContextPath());
      scope.setVirtualHosts("*");

      LoaderBase.setRed5ApplicationContext(
          context.getContextPath(), new JettyApplicationContext(context));

      // Register WebScope in server
      scope.register();
    }
  }
 private void prepareContext(GenericWebApplicationContext context) {
   MockServletContext servletContext = new MockServletContext();
   context.setServletContext(servletContext);
   servletContext.setAttribute(
       WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
 }