Example #1
0
  /*
   * Registers a subcontext with red5
   */
  public void registerSubContext(String webAppKey) {
    // get the sub contexts - servlet context
    ServletContext ctx = servletContext.getContext(webAppKey);
    if (ctx == null) {
      ctx = servletContext;
    }
    ContextLoader loader = new ContextLoader();
    ConfigurableWebApplicationContext appCtx =
        (ConfigurableWebApplicationContext) loader.initWebApplicationContext(ctx);
    appCtx.setParent(applicationContext);
    appCtx.refresh();

    ctx.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appCtx);

    ConfigurableBeanFactory appFactory = appCtx.getBeanFactory();

    logger.debug("About to grab Webcontext bean for " + webAppKey);
    Context webContext = (Context) appCtx.getBean("web.context");
    webContext.setCoreBeanFactory(parentFactory);
    webContext.setClientRegistry(clientRegistry);
    webContext.setServiceInvoker(globalInvoker);
    webContext.setScopeResolver(globalResolver);
    webContext.setMappingStrategy(globalStrategy);

    WebScope scope = (WebScope) appFactory.getBean("web.scope");
    scope.setServer(server);
    scope.setParent(global);
    scope.register();
    scope.start();

    // register the context so we dont try to reinitialize it
    registeredContexts.add(ctx);
  }
  /**
   * Instantiate the WebApplicationContext for this servlet, either a default {@link
   * org.springframework.web.context.support.XmlWebApplicationContext} or a {@link #setContextClass
   * custom context class}, if set.
   *
   * <p>This implementation expects custom contexts to implement the {@link
   * org.springframework.web.context.ConfigurableWebApplicationContext} interface. Can be overridden
   * in subclasses.
   *
   * <p>Do not forget to register this servlet instance as application listener on the created
   * context (for triggering its {@link #onRefresh callback}, and to call {@link
   * org.springframework.context.ConfigurableApplicationContext#refresh()} before returning the
   * context instance.
   *
   * @param parent the parent ApplicationContext to use, or {@code null} if none
   * @return the WebApplicationContext for this servlet
   * @see org.springframework.web.context.support.XmlWebApplicationContext
   */
  protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) {
    Class<?> contextClass = getContextClass();
    if (this.logger.isDebugEnabled()) {
      this.logger.debug(
          "Servlet with name '"
              + getServletName()
              + "' will try to create custom WebApplicationContext context of class '"
              + contextClass.getName()
              + "'"
              + ", using parent context ["
              + parent
              + "]");
    }
    if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
      throw new ApplicationContextException(
          "Fatal initialization error in servlet with name '"
              + getServletName()
              + "': custom WebApplicationContext class ["
              + contextClass.getName()
              + "] is not of type ConfigurableWebApplicationContext");
    }
    ConfigurableWebApplicationContext wac =
        (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);

    wac.setEnvironment(getEnvironment());
    wac.setParent(parent);
    wac.setConfigLocation(getContextConfigLocation());

    configureAndRefreshWebApplicationContext(wac);

    return wac;
  }
Example #3
0
 /**
  * Clearing the in-memory configuration parameters, we will receive notification that the servlet
  * context is about to be shut down
  */
 @Override
 public void contextDestroyed(ServletContextEvent sce) {
   synchronized (servletContext) {
     logger.info("Webapp shutdown");
     // XXX Paul: grabbed this from
     // http://opensource.atlassian.com/confluence/spring/display/DISC/Memory+leak+-+classloader+won%27t+let+go
     // in hopes that we can clear all the issues with J2EE containers
     // during shutdown
     try {
       ServletContext ctx = sce.getServletContext();
       // prepare spring for shutdown
       Introspector.flushCaches();
       // dereg any drivers
       for (Enumeration e = DriverManager.getDrivers(); e.hasMoreElements(); ) {
         Driver driver = (Driver) e.nextElement();
         if (driver.getClass().getClassLoader() == getClass().getClassLoader()) {
           DriverManager.deregisterDriver(driver);
         }
       }
       // shutdown jmx
       JMXAgent.shutdown();
       // shutdown the persistence thread
       FilePersistenceThread persistenceThread = FilePersistenceThread.getInstance();
       if (persistenceThread != null) {
         persistenceThread.shutdown();
       }
       // shutdown spring
       Object attr =
           ctx.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
       if (attr != null) {
         // get web application context from the servlet context
         ConfigurableWebApplicationContext applicationContext =
             (ConfigurableWebApplicationContext) attr;
         ConfigurableBeanFactory factory = applicationContext.getBeanFactory();
         // for (String scope : factory.getRegisteredScopeNames()) {
         // logger.debug("Registered scope: " + scope);
         // }
         try {
           for (String singleton : factory.getSingletonNames()) {
             logger.debug("Registered singleton: " + singleton);
             factory.destroyScopedBean(singleton);
           }
         } catch (RuntimeException e) {
         }
         factory.destroySingletons();
         ctx.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
         applicationContext.close();
       }
       getContextLoader().closeWebApplicationContext(ctx);
       //				org.apache.commons.logging.LogFactory.releaseAll();
       //				org.apache.log4j.LogManager.getLoggerRepository().shutdown();
       //				org.apache.log4j.LogManager.shutdown();
     } catch (Throwable e) {
       e.printStackTrace();
     }
   }
 }
  /**
   * Initialize and publish the WebApplicationContext for this servlet.
   *
   * <p>Delegates to {@link #createWebApplicationContext} for actual creation of the context. Can be
   * overridden in subclasses.
   *
   * @return the WebApplicationContext instance
   * @see #FrameworkServlet(WebApplicationContext)
   * @see #setContextClass
   * @see #setContextConfigLocation
   */
  protected WebApplicationContext initWebApplicationContext() {
    WebApplicationContext rootContext =
        WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    WebApplicationContext wac = null;

    if (this.webApplicationContext != null) {
      // A context instance was injected at construction time -> use it
      wac = this.webApplicationContext;
      if (wac instanceof ConfigurableWebApplicationContext) {
        ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
        if (!cwac.isActive()) {
          // The context has not yet been refreshed -> provide services such as
          // setting the parent context, setting the application context id, etc
          if (cwac.getParent() == null) {
            // The context instance was injected without an explicit parent -> set
            // the root application context (if any; may be null) as the parent
            cwac.setParent(rootContext);
          }
          configureAndRefreshWebApplicationContext(cwac);
        }
      }
    }
    if (wac == null) {
      // No context instance was injected at construction time -> see if one
      // has been registered in the servlet context. If one exists, it is assumed
      // that the parent context (if any) has already been set and that the
      // user has performed any initialization such as setting the context id
      wac = findWebApplicationContext();
    }
    if (wac == null) {
      // No context instance is defined for this servlet -> create a local one
      wac = createWebApplicationContext(rootContext);
    }

    if (!this.refreshEventReceived) {
      // Either the context is not a ConfigurableApplicationContext with refresh
      // support or the context injected at construction time had already been
      // refreshed -> trigger initial onRefresh manually here.
      onRefresh(wac);
    }

    if (this.publishContext) {
      // Publish the context as a servlet context attribute.
      String attrName = getServletContextAttributeName();
      getServletContext().setAttribute(attrName, wac);
      if (this.logger.isDebugEnabled()) {
        this.logger.debug(
            "Published WebApplicationContext of servlet '"
                + getServletName()
                + "' as ServletContext attribute with name ["
                + attrName
                + "]");
      }
    }

    return wac;
  }
  protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {
    if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
      // The application context id is still set to its original default value
      // -> assign a more useful id based on available information
      if (this.contextId != null) {
        wac.setId(this.contextId);
      } else {
        // Generate default id...
        wac.setId(
            ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX
                + ObjectUtils.getDisplayString(getServletContext().getContextPath())
                + "/"
                + getServletName());
      }
    }

    wac.setServletContext(getServletContext());
    wac.setServletConfig(getServletConfig());
    wac.setNamespace(getNamespace());
    wac.addApplicationListener(new SourceFilteringListener(wac, new ContextRefreshListener()));

    // The wac environment's #initPropertySources will be called in any case when the context
    // is refreshed; do it eagerly here to ensure servlet property sources are in place for
    // use in any post-processing or initialization that occurs below prior to #refresh
    ConfigurableEnvironment env = wac.getEnvironment();
    if (env instanceof ConfigurableWebEnvironment) {
      ((ConfigurableWebEnvironment) env)
          .initPropertySources(getServletContext(), getServletConfig());
    }

    postProcessWebApplicationContext(wac);
    applyInitializers(wac);
    wac.refresh();
  }
  @Override
  public void initialize(ConfigurableWebApplicationContext applicationContext) {

    // The profile can be read from property file or environment variable

    applicationContext.getEnvironment().setActiveProfiles("dev");
  }
 private Resource getResource(
     ServletContext servletContext,
     ConfigurableWebApplicationContext applicationContext,
     String locations) {
   Resource resource = null;
   String[] configFileLocations =
       locations == null
           ? DEFAULT_PROFILE_CONFIG_FILE_LOCATIONS
           : StringUtils.commaDelimitedListToStringArray(locations);
   for (String location : configFileLocations) {
     location = applicationContext.getEnvironment().resolvePlaceholders(location);
     servletContext.log("Testing for YAML resources at: " + location);
     resource = applicationContext.getResource(location);
     if (resource != null && resource.exists()) {
       break;
     }
   }
   return resource;
 }
  @Override
  public void initialize(ConfigurableWebApplicationContext applicationContext) {

    Resource resource = null;
    ServletContext servletContext = applicationContext.getServletContext();
    WebApplicationContextUtils.initServletPropertySources(
        applicationContext.getEnvironment().getPropertySources(),
        servletContext,
        applicationContext.getServletConfig());

    ServletConfig servletConfig = applicationContext.getServletConfig();
    String locations =
        servletConfig == null
            ? null
            : servletConfig.getInitParameter(PROFILE_CONFIG_FILE_LOCATIONS);
    resource = getResource(servletContext, applicationContext, locations);

    if (resource == null) {
      servletContext.log(
          "No YAML environment properties from servlet.  Defaulting to servlet context.");
      locations = servletContext.getInitParameter(PROFILE_CONFIG_FILE_LOCATIONS);
      resource = getResource(servletContext, applicationContext, locations);
    }

    try {
      servletContext.log("Loading YAML environment properties from location: " + resource);
      YamlMapFactoryBean factory = new YamlMapFactoryBean();
      factory.setResolutionMethod(ResolutionMethod.OVERRIDE_AND_IGNORE);

      List<Resource> resources = new ArrayList<Resource>();

      String defaultLocation =
          servletConfig == null
              ? null
              : servletConfig.getInitParameter(PROFILE_CONFIG_FILE_DEFAULT);
      if (defaultLocation != null) {
        Resource defaultResource = new ClassPathResource(defaultLocation);
        if (defaultResource.exists()) {
          resources.add(defaultResource);
        }
      }

      resources.add(resource);
      factory.setResources(resources.toArray(new Resource[resources.size()]));

      Map<String, Object> map = factory.getObject();
      String yamlStr = (new Yaml()).dump(map);
      map.put(rawYamlKey, yamlStr);
      NestedMapPropertySource properties = new NestedMapPropertySource("servletConfigYaml", map);
      applicationContext.getEnvironment().getPropertySources().addLast(properties);
      applySpringProfiles(applicationContext.getEnvironment(), servletContext);
      applyLog4jConfiguration(applicationContext.getEnvironment(), servletContext);

    } catch (Exception e) {
      servletContext.log("Error loading YAML environment properties from location: " + resource, e);
    }
  }
Example #9
0
  // Notification that the web application is ready to process requests
  @Override
  public void contextInitialized(ServletContextEvent sce) {
    if (null != servletContext) {
      return;
    }
    System.setProperty("red5.deployment.type", "war");

    servletContext = sce.getServletContext();
    String prefix = servletContext.getRealPath("/");

    long time = System.currentTimeMillis();

    logger.info("RED5 Server (http://www.osflash.org/red5)");
    logger.info("WAR loader");
    logger.debug("Path: " + prefix);

    try {
      // instance the context loader
      contextLoader = createContextLoader();
      applicationContext =
          (ConfigurableWebApplicationContext)
              contextLoader.initWebApplicationContext(servletContext);
      logger.debug("Root context path: " + applicationContext.getServletContext().getContextPath());

      ConfigurableBeanFactory factory = applicationContext.getBeanFactory();

      // register default
      factory.registerSingleton("default.context", applicationContext);

      // get the main factory
      parentFactory = (DefaultListableBeanFactory) factory.getParentBeanFactory();

    } catch (Throwable t) {
      logger.error("", t);
    }

    long startupIn = System.currentTimeMillis() - time;
    logger.info("Startup done in: " + startupIn + " ms");
  }
 @Override
 public void initialize(ConfigurableWebApplicationContext ctx) {
   ConfigurableEnvironment environment = ctx.getEnvironment();
   environment.setActiveProfiles("prod");
 }