@Test
  public void testTimerThreadLeak() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    if (ctx instanceof StandardContext) {
      ((StandardContext) ctx).setClearReferencesStopTimerThreads(true);
    }

    Tomcat.addServlet(ctx, "taskServlet", new TaskServlet());
    ctx.addServletMapping("/", "taskServlet");

    tomcat.start();

    // This will trigger the timer & thread creation
    getUrl("http://localhost:" + getPort() + "/");

    // Stop the context
    ctx.stop();

    Thread[] threads = getThreads();
    for (Thread thread : threads) {
      if (thread != null
          && thread.isAlive()
          && TaskServlet.TIMER_THREAD_NAME.equals(thread.getName())) {
        thread.join(5000);
        if (thread.isAlive()) {
          fail("Timer thread still running");
        }
      }
    }
  }
Ejemplo n.º 2
0
  private static void addServlets(JBossWebMetaData jbwebMD, StandardContext context) {
    for (JBossServletMetaData smd : jbwebMD.getServlets()) {
      final String sc = smd.getServletClass();
      if (sc.equals(WSFServlet.class.getName())) {
        final String servletName = smd.getServletName();
        List<ParamValueMetaData> params = smd.getInitParam();
        List<String> urlPatterns = null;
        for (ServletMappingMetaData smmd : jbwebMD.getServletMappings()) {
          if (smmd.getServletName().equals(servletName)) {
            urlPatterns = smmd.getUrlPatterns();
            break;
          }
        }

        WSFServlet wsfs = new WSFServlet();
        Wrapper wsfsWrapper = context.createWrapper();
        wsfsWrapper.setName(servletName);
        wsfsWrapper.setServlet(wsfs);
        wsfsWrapper.setServletClass(WSFServlet.class.getName());
        for (ParamValueMetaData param : params) {
          wsfsWrapper.addInitParameter(param.getParamName(), param.getParamValue());
        }
        context.addChild(wsfsWrapper);
        for (String urlPattern : urlPatterns) {
          context.addServletMapping(urlPattern, servletName);
        }
      }
    }
  }
Ejemplo n.º 3
0
  /**
   * Acknowledge the occurrence of the specified event.
   *
   * @param event LifecycleEvent that has occurred
   */
  @Override
  public void lifecycleEvent(LifecycleEvent event) {
    if (event.getType().equals(Lifecycle.BEFORE_START_EVENT)) {
      if (event.getLifecycle() instanceof StandardContext) {
        StandardContext context = (StandardContext) event.getLifecycle();

        if (appNames.get(context.getName()) != null) {
          showStatus("Starting " + appNames.get(context.getName()));
        }
      }
    }
  }
Ejemplo n.º 4
0
 public static void setupContainer(String warName, String jvmRoute, Manager mgr) {
   Engine engine = new MockEngine();
   engine.setName(JVM_ROUTE_CACHE_NAME);
   engine.setJvmRoute(jvmRoute);
   Host host = new MockHost();
   host.setName("localhost");
   engine.addChild(host);
   StandardContext context = new StandardContext();
   context.setName(warName);
   context.setDomain(jvmRoute);
   host.addChild(context);
   context.setManager(mgr);
 }
Ejemplo n.º 5
0
  private static StandardContext startWebApp(Host host, WSEndpointDeploymentUnit unit)
      throws Exception {
    StandardContext context = new StandardContext();
    try {
      JBossWebMetaData jbwebMD = unit.getAttachment(WSAttachmentKeys.JBOSSWEB_METADATA_KEY);
      context.setPath(jbwebMD.getContextRoot());
      context.addLifecycleListener(new ContextConfig());
      ServerConfigService config =
          (ServerConfigService)
              unit.getServiceRegistry().getService(WSServices.CONFIG_SERVICE).getService();
      File docBase = new File(config.getValue().getServerTempDir(), jbwebMD.getContextRoot());
      if (!docBase.exists()) {
        docBase.mkdirs();
      }
      context.setDocBase(docBase.getPath());

      final Loader loader = new WebCtxLoader(unit.getAttachment(WSAttachmentKeys.CLASSLOADER_KEY));
      loader.setContainer(host);
      context.setLoader(loader);
      context.setInstanceManager(new LocalInstanceManager());

      addServlets(jbwebMD, context);

      host.addChild(context);
      context.create();
    } catch (Exception e) {
      throw MESSAGES.createContextPhaseFailed(e);
    }
    try {
      context.start();
    } catch (LifecycleException e) {
      throw MESSAGES.startContextPhaseFailed(e);
    }
    return context;
  }
Ejemplo n.º 6
0
 private static void stopWebApp(StandardContext context) throws Exception {
   try {
     Container container = context.getParent();
     container.removeChild(context);
     context.stop();
   } catch (LifecycleException e) {
     throw MESSAGES.stopContextPhaseFailed(e);
   }
   try {
     context.destroy();
   } catch (Exception e) {
     throw MESSAGES.destroyContextPhaseFailed(e);
   }
 }
Ejemplo n.º 7
0
 @Override
 public void stop(StopContext stopContext) {
   registration.unregister();
   try {
     context.stop();
   } catch (LifecycleException e) {
     WEB_LOGGER.stopContextFailed(e);
   }
   try {
     context.destroy();
   } catch (Exception e) {
     WEB_LOGGER.destroyContextFailed(e);
   }
 }
Ejemplo n.º 8
0
 /** Un-initialization. */
 @Override
 public void destroy() throws Exception {
   log.debug("TomcatVHostLoader un-init");
   Container[] children = host.findChildren();
   for (Container c : children) {
     if (c instanceof StandardContext) {
       try {
         ((StandardContext) c).stop();
         host.removeChild(c);
       } catch (Exception e) {
         log.error("Could not stop context: {}", c.getName(), e);
       }
     }
   }
   // remove system prop
   String propertyPrefix = name;
   if (domain != null) {
     propertyPrefix += '_' + domain.replace('.', '_');
   }
   System.clearProperty(propertyPrefix + ".webapp.root");
   // stop the host
   try {
     ((StandardHost) host).stop();
   } catch (LifecycleException e) {
     log.error("Could not stop host: {}", host.getName(), e);
   }
   // remove host
   engine.removeChild(host);
   // unregister jmx
   unregisterJMX();
 }
Ejemplo n.º 9
0
  private void doTestOverrideDefaultServletWithSCI(String servletName) throws Exception {

    Tomcat tomcat = getTomcatInstance();

    File appDir = new File("test/webapp");
    StandardContext ctxt =
        (StandardContext) tomcat.addContext(null, "/test", appDir.getAbsolutePath());
    ctxt.setDefaultWebXml(new File("conf/web.xml").getAbsolutePath());
    ctxt.addLifecycleListener(new ContextConfig());

    ctxt.addServletContainerInitializer(new CustomDefaultServletSCI(servletName), null);

    tomcat.start();

    assertPageContains("/test", "OK - Custom default Servlet");
  }
Ejemplo n.º 10
0
 @Override
 public synchronized void stop() throws Exception {
   if (_serverContext != null) {
     // Destroy the web context unless if it is default
     if (!_serverContext.getPath().equals("/")) {
       try {
         Container container = _serverContext.getParent();
         container.removeChild(_serverContext);
         _serverContext.stop();
         _serverContext.destroy();
         _log.info("Destroyed HTTP context " + _serverContext.getPath());
       } catch (Exception e) {
         _log.error("Unable to destroy web context", e);
       }
     }
   }
 }
Ejemplo n.º 11
0
  public void init() {
    if (initialized) return;
    initialized = true;

    StandardContext ctx = (StandardContext) this.getContainer();
    distributable = ctx.getDistributable();
    if (org.apache.tomcat.util.Constants.ENABLE_MODELER) {
      if (oname == null) {
        try {
          Engine eng = (Engine) ctx.getParent().getParent();
          domain = ctx.getEngineName();
          StandardHost hst = (StandardHost) ctx.getParent();
          String path = ctx.getPath();
          if (path.equals("")) {
            path = "/";
          }
          oname = new ObjectName(domain + ":type=Manager,path=" + path + ",host=" + hst.getName());
          Registry.getRegistry(null, null).registerComponent(this, oname, null);
        } catch (Exception e) {
          CatalinaLogger.SESSION_LOGGER.failedSessionManagerJmxRegistration(oname, e);
        }
      }
    }

    if (CatalinaLogger.SESSION_LOGGER.isDebugEnabled())
      CatalinaLogger.SESSION_LOGGER.debug("Registering " + oname);
  }
Ejemplo n.º 12
0
  public void init() {
    if (initialized) return;
    initialized = true;

    log = Logger.getLogger(ManagerBase.class);

    StandardContext ctx = (StandardContext) this.getContainer();
    distributable = ctx.getDistributable();
    if (org.apache.tomcat.util.Constants.ENABLE_MODELER) {
      if (oname == null) {
        try {
          Engine eng = (Engine) ctx.getParent().getParent();
          domain = ctx.getEngineName();
          StandardHost hst = (StandardHost) ctx.getParent();
          String path = ctx.getPath();
          if (path.equals("")) {
            path = "/";
          }
          oname = new ObjectName(domain + ":type=Manager,path=" + path + ",host=" + hst.getName());
          Registry.getRegistry(null, null).registerComponent(this, oname, null);
        } catch (Exception e) {
          log.error("Error registering ", e);
        }
      }
    }

    if (log.isDebugEnabled()) log.debug("Registering " + oname);
  }
Ejemplo n.º 13
0
  /** lookup doesn't always throw the same exception. */
  @Test
  public void testLookupException() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    // Must have a real docBase - just use temp
    StandardContext ctx =
        (StandardContext) tomcat.addContext("", System.getProperty("java.io.tmpdir"));
    ctx.setCacheTTL(500);
    tomcat.start();

    try {
      ctx.getResources().lookup("/WEB-INF/web.xml");
      fail();
    } catch (final NameNotFoundException e) {
      // as expected
    }
    Thread.sleep(600); // see ProxyDirContext.cacheTTL
    try {
      ctx.getResources().lookup("/WEB-INF/web.xml");
      fail();
    } catch (final NameNotFoundException e) {
      // as expected
    }
  }
  @Test
  public void testTimerThreadLeak() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    if (ctx instanceof StandardContext) {
      ((StandardContext) ctx).setClearReferencesStopThreads(true);
    }

    ExecutorServlet executorServlet = new ExecutorServlet();
    Tomcat.addServlet(ctx, "taskServlet", executorServlet);
    ctx.addServletMapping("/", "taskServlet");

    tomcat.start();

    // This will trigger the timer & thread creation
    getUrl("http://localhost:" + getPort() + "/");

    // Stop the context
    ctx.stop();

    // Should be shutdown once the stop() method above exists
    Assert.assertTrue(executorServlet.tpe.isShutdown());

    // The time taken to shutdown the executor can vary between systems. Try
    // to avoid false test failures due to timing issues. Give the executor
    // upto 10 seconds to close down.
    int count = 0;
    while (count < 100 && !executorServlet.tpe.isTerminated()) {
      count++;
      Thread.sleep(100);
    }

    // If the executor has not terminated, there is a thread/memory leak
    Assert.assertTrue(executorServlet.tpe.isTerminated());
  }
Ejemplo n.º 15
0
  @Override
  public void start(StartContext startContext) throws StartException {

    ServerEnvironment env = injectedServerEnvironment.getValue();
    Host virtualHost = injectedVirtualHost.getValue().getHost();
    BundleContext syscontext = injectedSystemContext.getValue();
    WebServer webServer = injectedWebServer.getValue();

    File storageDir =
        new File(
            env.getServerTempDir()
                + File.separator
                + CONTEXT_NAME
                + File.separator
                + "httpservice-root");
    context.setDocBase(storageDir.getPath());
    storageDir.mkdirs();

    context.setPath(CONTEXT_NAME);
    context.addLifecycleListener(new ContextConfig());
    Loader loader = new WebCtxLoader(getClass().getClassLoader());
    loader.setContainer(virtualHost);
    context.setLoader(loader);
    context.setInstanceManager(new LocalInstanceManager());

    context.addMimeMapping("html", "text/html");
    context.addMimeMapping("jpg", "image/jpeg");
    context.addMimeMapping("png", "image/png");
    context.addMimeMapping("gif", "image/gif");
    context.addMimeMapping("css", "text/css");
    context.addMimeMapping("js", "text/javascript");

    virtualHost.addChild(context);

    WEB_LOGGER.registerWebapp(context.getName());
    try {
      context.create();
    } catch (Exception ex) {
      throw new StartException(WebMessages.MESSAGES.createContextFailed(), ex);
    }
    try {
      context.start();
    } catch (LifecycleException ex) {
      throw new StartException(WebMessages.MESSAGES.startContextFailed(), ex);
    }

    Hashtable<String, Object> props = new Hashtable<String, Object>();
    props.put(Constants.SERVICE_RANKING, Integer.MIN_VALUE);
    props.put("provider", getClass().getPackage().getName());

    ServiceFactory serviceFactory = new HttpServiceFactory(webServer, virtualHost, context);
    registration = syscontext.registerService(HttpService.class.getName(), serviceFactory, props);
  }
Ejemplo n.º 16
0
 /**
  * Initialization.
  *
  * @throws ServletException
  */
 @SuppressWarnings("cast")
 @Override
 public void start() throws ServletException {
   log.info("Loading tomcat virtual host");
   if (webappFolder != null) {
     // check for match with base webapp root
     if (webappFolder.equals(webappRoot)) {
       log.error("Web application root cannot be the same as base");
       return;
     }
   }
   ClassLoader classloader = Thread.currentThread().getContextClassLoader();
   // ensure we have a host
   if (host == null) {
     host = createHost();
   }
   host.setParentClassLoader(classloader);
   String propertyPrefix = name;
   if (domain != null) {
     propertyPrefix += '_' + domain.replace('.', '_');
   }
   log.debug("Generating name (for props) {}", propertyPrefix);
   System.setProperty(propertyPrefix + ".webapp.root", webappRoot);
   log.info("Virtual host root: {}", webappRoot);
   log.info("Virtual host context id: {}", defaultApplicationContextId);
   // Root applications directory
   File appDirBase = new File(webappRoot);
   // Subdirs of root apps dir
   File[] dirs = appDirBase.listFiles(new TomcatLoader.DirectoryFilter());
   // Search for additional context files
   for (File dir : dirs) {
     String dirName = '/' + dir.getName();
     // check to see if the directory is already mapped
     if (null == host.findChild(dirName)) {
       String webappContextDir = FileUtil.formatPath(appDirBase.getAbsolutePath(), dirName);
       Context ctx = null;
       if ("/root".equals(dirName) || "/root".equalsIgnoreCase(dirName)) {
         log.debug("Adding ROOT context");
         ctx = addContext("/", webappContextDir);
       } else {
         log.debug("Adding context from directory scan: {}", dirName);
         ctx = addContext(dirName, webappContextDir);
       }
       log.debug("Context: {}", ctx);
       webappContextDir = null;
     }
   }
   appDirBase = null;
   dirs = null;
   // Dump context list
   if (log.isDebugEnabled()) {
     for (Container cont : host.findChildren()) {
       log.debug("Context child name: {}", cont.getName());
     }
   }
   engine.addChild(host);
   // Start server
   try {
     log.info("Starting Tomcat virtual host");
     // may not have to do this step for every host
     LoaderBase.setApplicationLoader(
         new TomcatApplicationLoader(embedded, host, applicationContext));
     for (Container cont : host.findChildren()) {
       if (cont instanceof StandardContext) {
         StandardContext ctx = (StandardContext) cont;
         ServletContext servletContext = ctx.getServletContext();
         log.debug("Context initialized: {}", servletContext.getContextPath());
         // set the hosts id
         servletContext.setAttribute("red5.host.id", getHostId());
         String prefix = servletContext.getRealPath("/");
         log.debug("Path: {}", prefix);
         try {
           Loader cldr = ctx.getLoader();
           log.debug("Loader type: {}", cldr.getClass().getName());
           ClassLoader webClassLoader = cldr.getClassLoader();
           log.debug("Webapp classloader: {}", webClassLoader);
           // create a spring web application context
           XmlWebApplicationContext appctx = new XmlWebApplicationContext();
           appctx.setClassLoader(webClassLoader);
           appctx.setConfigLocations(new String[] {"/WEB-INF/red5-*.xml"});
           // check for red5 context bean
           if (applicationContext.containsBean(defaultApplicationContextId)) {
             appctx.setParent(
                 (ApplicationContext) applicationContext.getBean(defaultApplicationContextId));
           } else {
             log.warn(
                 "{} bean was not found in context: {}",
                 defaultApplicationContextId,
                 applicationContext.getDisplayName());
             // lookup context loader and attempt to get what we need from it
             if (applicationContext.containsBean("context.loader")) {
               ContextLoader contextLoader =
                   (ContextLoader) applicationContext.getBean("context.loader");
               appctx.setParent(contextLoader.getContext(defaultApplicationContextId));
             } else {
               log.debug("Context loader was not found, trying JMX");
               MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
               // get the ContextLoader from jmx
               ContextLoaderMXBean proxy = null;
               ObjectName oName = null;
               try {
                 oName = new ObjectName("org.red5.server:name=contextLoader,type=ContextLoader");
                 if (mbs.isRegistered(oName)) {
                   proxy = JMX.newMXBeanProxy(mbs, oName, ContextLoaderMXBean.class, true);
                   log.debug("Context loader was found");
                   proxy.setParentContext(defaultApplicationContextId, appctx.getId());
                 } else {
                   log.warn("Context loader was not found");
                 }
               } catch (Exception e) {
                 log.warn("Exception looking up ContextLoader", e);
               }
             }
           }
           if (log.isDebugEnabled()) {
             if (appctx.getParent() != null) {
               log.debug("Parent application context: {}", appctx.getParent().getDisplayName());
             }
           }
           //
           appctx.setServletContext(servletContext);
           // set the root webapp ctx attr on the each servlet context so spring can find it later
           servletContext.setAttribute(
               WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appctx);
           appctx.refresh();
         } catch (Throwable t) {
           log.error("Error setting up context: {}", servletContext.getContextPath(), t);
           if (log.isDebugEnabled()) {
             t.printStackTrace();
           }
         }
       }
     }
   } catch (Exception e) {
     log.error("Error loading Tomcat virtual host", e);
   }
 }
  /**
   * initialize & configure the correct persistence strategy including manager, store, uuid
   * generator
   *
   * @param ctx
   * @param smBean
   */
  public void initializePersistenceStrategy(Context ctx, SessionManager smBean) {
    super.initializePersistenceStrategy(ctx, smBean);

    _logger.finest("IN HaOndemandModifiedattributeStrategyBuilder");
    String persistenceType = "ha";
    String persistenceFrequency = "on-demand";
    String persistenceScope = "modified-attribute";
    Object[] params = {ctx.getPath(), persistenceType, persistenceFrequency, persistenceScope};
    _logger.log(Level.INFO, "webcontainer.haPersistence", params);
    HAWebEventPersistentManager mgr = new HAWebEventPersistentManager();
    mgr.setMaxActiveSessions(maxSessions);
    // mgr.setCheckInterval(reapInterval); //FIXME: put this back
    mgr.setMaxIdleBackup(0); // FIXME: Make configurable

    HAAttributeStore store = new HAAttributeStore();
    // store.setCheckInterval(storeReapInterval);  //FIXME: put this back
    mgr.setStore(store);

    // in the future can set other implementations
    // of UuidGenerator in server.xml
    // even if not set it defaults to UuidGeneratorImpl
    ServerConfigLookup lookup = new ServerConfigLookup();
    UuidGenerator generator = lookup.getUuidGeneratorFromConfig();
    mgr.setUuidGenerator(generator);
    _logger.finest("UUID_GENERATOR = " + generator);

    // for intra-vm session locking
    _logger.finest("sctx.restrictedSetPipeline(new SessionLockingStandardPipeline(sctx))");
    StandardContext sctx = (StandardContext) ctx;
    sctx.restrictedSetPipeline(new SessionLockingStandardPipeline(sctx));

    // special code for Java Server Faces
    if (sctx.findParameter(JSF_HA_ENABLED) == null) {
      sctx.addParameter(JSF_HA_ENABLED, "true");
    }
    // START OF 6364900
    mgr.setSessionLocker(new PESessionLocker(ctx));
    // END OF 6364900
    ctx.setManager(mgr);

    // this must be after ctx.setManager(mgr);
    if (!sctx.isSessionTimeoutOveridden()) {
      mgr.setMaxInactiveInterval(sessionMaxInactiveInterval);
    }

    // add SessionFactory
    mgr.setSessionFactory(new ModifiedAttributeSessionFactory());

    // add HAStorePool
    ServerConfigReader configReader = new ServerConfigReader();

    int haStorePoolSize = configReader.getHAStorePoolSizeFromConfig();
    int haStorePoolUpperSize = configReader.getHAStorePoolUpperSizeFromConfig();
    int haStorePoolPollTime = configReader.getHAStorePoolPollTimeFromConfig();

    /*
    HAAttributeStoreFactory haStoreFactory = new HAAttributeStoreFactory();
    _logger.finest("haStoreFactory  : "+haStoreFactory.getClass());
    HAStorePool storePool =
        new HAStorePool(haStorePoolSize, haStorePoolUpperSize,
            haStorePoolPollTime, haStoreFactory);
    mgr.setHAStorePool(storePool);
     */

    StoreFactory haStoreFactory = new HAAttributeStoreFactory();
    _logger.finest("haStoreFactory  : " + haStoreFactory.getClass());
    StorePool storePool =
        new StorePool(haStorePoolSize, haStorePoolUpperSize, haStorePoolPollTime, haStoreFactory);
    mgr.setStorePool(storePool);

    // add container listener for hooking sync calls
    ctx.addContainerListener(new HASyncContainerListener(mgr));
  }
 protected void initInternal() {
   StandardContext standardContext = (StandardContext) context;
   standardContext.addLifecycleListener(this);
 }
Ejemplo n.º 19
0
  static StandardContext configure(Tomcat tomcat, Props props) {
    try {
      StandardContext context =
          (StandardContext) tomcat.addWebapp(getContextPath(props), webappPath(props));
      context.setClearReferencesHttpClientKeepAliveThread(false);
      context.setClearReferencesStatic(false);
      context.setClearReferencesStopThreads(false);
      context.setClearReferencesStopTimerThreads(false);
      context.setClearReferencesStopTimerThreads(false);
      context.setAntiResourceLocking(false);
      context.setReloadable(false);
      context.setUseHttpOnly(true);
      context.setTldValidation(false);
      context.setXmlValidation(false);
      context.setXmlNamespaceAware(false);
      context.setUseNaming(false);
      context.setDelegate(true);
      context.setJarScanner(new NullJarScanner());
      configureRails(props, context);

      for (Map.Entry<Object, Object> entry : props.rawProperties().entrySet()) {
        String key = entry.getKey().toString();
        context.addParameter(key, entry.getValue().toString());
      }
      return context;

    } catch (Exception e) {
      throw new IllegalStateException("Fail to configure webapp", e);
    }
  }
Ejemplo n.º 20
0
  @Override
  public synchronized void start() throws Exception {

    Host host = ServerUtil.getDefaultHost().getHost();
    _serverContext = (StandardContext) host.findChild("/" + _contextName);
    if (_serverContext == null) {
      _serverContext = new StandardContext();
      _serverContext.setPath("/" + _contextName);
      File docBase = new File(SERVER_TEMP_DIR, _contextName);
      if (!docBase.exists()) {
        if (!docBase.mkdirs()) {
          throw new RuntimeException("Unable to create temp directory " + docBase.getPath());
        }
      }
      _serverContext.setDocBase(docBase.getPath());
      _serverContext.addLifecycleListener(new ContextConfig());

      final Loader loader = new WebCtxLoader(Thread.currentThread().getContextClassLoader());
      loader.setContainer(host);
      _serverContext.setLoader(loader);
      _serverContext.setInstanceManager(new LocalInstanceManager());

      Wrapper wrapper = _serverContext.createWrapper();
      wrapper.setName(SERVLET_NAME);
      wrapper.setServletClass(SwitchYardRemotingServlet.class.getName());
      wrapper.setLoadOnStartup(1);
      _serverContext.addChild(wrapper);
      _serverContext.addServletMapping("/*", SERVLET_NAME);

      host.addChild(_serverContext);
      _serverContext.create();
      _serverContext.start();

      SwitchYardRemotingServlet remotingServlet = (SwitchYardRemotingServlet) wrapper.getServlet();
      remotingServlet.setEndpointPublisher(this);
      _log.info("Published Remote Service Endpoint " + _serverContext.getPath());
    } else {
      throw new RuntimeException("Context " + _contextName + " already exists!");
    }
  }
Ejemplo n.º 21
0
  /**
   * Return the child Container that should be used to process this Request, based upon its
   * characteristics. If no such child Container can be identified, return <code>null</code>
   * instead.
   *
   * @param request Request being processed
   * @param update Update the Request to reflect the mapping selection?
   * @exception IllegalArgumentException if the relative portion of the path cannot be URL decoded
   */
  public Container map(Request request, boolean update) {

    int debug = context.getDebug();

    // Has this request already been mapped?
    if (update && (request.getWrapper() != null)) return (request.getWrapper());

    // Identify the context-relative URI to be mapped
    String contextPath = ((HttpServletRequest) request.getRequest()).getContextPath();
    String requestURI = ((HttpRequest) request).getDecodedRequestURI();
    String relativeURI = requestURI.substring(contextPath.length());

    // Apply the standard request URI mapping rules from the specification
    Wrapper wrapper = null;
    String servletPath = relativeURI;
    String pathInfo = null;
    String name = null;

    // Rule 1 -- Exact Match
    if (wrapper == null) {
      name = context.findServletMapping(requestURI);
      if (name == null) {
        if (!(relativeURI.equals("/"))) name = context.findServletMapping(relativeURI);
      }
      if (name != null) wrapper = (Wrapper) context.findChild(name);
      if (wrapper != null) {
        servletPath = relativeURI;
        pathInfo = null;
      }
    }

    // Rule 2 -- Prefix Match
    if (wrapper == null) {
      servletPath = relativeURI;
      while (true) {
        name = context.findServletMapping(servletPath + "/*");
        if (name != null) wrapper = (Wrapper) context.findChild(name);
        if (wrapper != null) {
          pathInfo = relativeURI.substring(servletPath.length());
          if (pathInfo.length() == 0) pathInfo = null;
          break;
        }
        int slash = servletPath.lastIndexOf('/');
        if (slash < 0) break;
        servletPath = servletPath.substring(0, slash);
      }
    }

    // Rule 3 -- Extension Match
    if (wrapper == null) {
      int slash = relativeURI.lastIndexOf('/');
      if (slash >= 0) {
        String last = relativeURI.substring(slash);
        int period = last.lastIndexOf('.');
        if (period >= 0) {
          String pattern = "*" + last.substring(period);
          name = context.findServletMapping(pattern);
          if (name != null) wrapper = (Wrapper) context.findChild(name);
          if (wrapper != null) {
            servletPath = relativeURI;
            pathInfo = null;
          }
        }
      }
    }

    // Rule 4 -- Default Match
    if (wrapper == null) {
      name = context.findServletMapping("/");
      if (name != null) wrapper = (Wrapper) context.findChild(name);
      if (wrapper != null) {
        servletPath = relativeURI;
        pathInfo = null;
      }
    }

    // Update the Request (if requested) and return this Wrapper
    if ((debug >= 1) && (wrapper != null))
      if (update) {
        request.setWrapper(wrapper);
        ((HttpRequest) request).setServletPath(servletPath);
        ((HttpRequest) request).setPathInfo(pathInfo);
      }
    return (wrapper);
  }
Ejemplo n.º 22
0
  protected void processDeployment(
      final String hostName, final WarMetaData warMetaData, final DeploymentUnitContext context)
      throws DeploymentUnitProcessingException {
    final VirtualFile deploymentRoot = VirtualFileAttachment.getVirtualFileAttachment(context);
    final Module module = context.getAttachment(ModuleDeploymentProcessor.MODULE_ATTACHMENT_KEY);
    if (module == null) {
      throw new DeploymentUnitProcessingException(
          "failed to resolve module for deployment " + deploymentRoot);
    }
    final ClassLoader classLoader = module.getClassLoader();
    final JBossWebMetaData metaData = warMetaData.getMergedJBossWebMetaData();

    // Create the context
    final StandardContext webContext = new StandardContext();
    final ContextConfig config = new JBossContextConfig(context);
    // Set the deployment root
    try {
      webContext.setDocBase(deploymentRoot.getPhysicalFile().getAbsolutePath());
    } catch (IOException e) {
      throw new DeploymentUnitProcessingException(e);
    }
    webContext.addLifecycleListener(config);

    // Set the path name
    final String deploymentName = context.getName();
    String pathName = null;
    if (metaData.getContextRoot() == null) {
      pathName = deploymentRoot.getName();
      if (pathName.equals("ROOT.war")) {
        pathName = "";
      } else {
        pathName = "/" + pathName.substring(0, pathName.length() - 4);
      }
    } else {
      pathName = metaData.getContextRoot();
      if ("/".equals(pathName)) {
        pathName = "";
      }
    }
    webContext.setPath(pathName);
    webContext.setIgnoreAnnotations(true);

    // Add a dummy realm for now
    Realm realm = new MemoryRealm();
    webContext.setRealm(realm);

    //
    final Loader loader = new WebCtxLoader(classLoader);
    final InstanceManager manager = new WebInjectionContainer(classLoader);
    webContext.setInstanceManager(manager);
    webContext.setLoader(loader);

    // Set the session cookies flag according to metadata
    switch (metaData.getSessionCookies()) {
      case JBossWebMetaData.SESSION_COOKIES_ENABLED:
        webContext.setCookies(true);
        break;
      case JBossWebMetaData.SESSION_COOKIES_DISABLED:
        webContext.setCookies(false);
        break;
    }

    String metaDataSecurityDomain = metaData.getSecurityDomain();
    if (metaDataSecurityDomain != null) {
      metaDataSecurityDomain = metaDataSecurityDomain.trim();
    }

    // Add the context service
    final BatchBuilder builder = context.getBatchBuilder();
    builder
        .addService(
            WebSubsystemElement.JBOSS_WEB.append(deploymentName),
            new WebDeploymentService(webContext))
        .addDependency(
            WebSubsystemElement.JBOSS_WEB_HOST.append(hostName),
            Host.class,
            new WebContextInjector(webContext))
        .setInitialMode(Mode.ACTIVE);
  }
Ejemplo n.º 23
0
  protected void processDeployment(
      final String hostName,
      final WarMetaData warMetaData,
      final DeploymentUnit deploymentUnit,
      final ServiceTarget serviceTarget)
      throws DeploymentUnitProcessingException {
    final VirtualFile deploymentRoot =
        deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot();
    final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
    if (module == null) {
      throw new DeploymentUnitProcessingException(MESSAGES.failedToResolveModule(deploymentRoot));
    }
    final ClassLoader classLoader = module.getClassLoader();
    final JBossWebMetaData metaData = warMetaData.getMergedJBossWebMetaData();
    final List<SetupAction> setupActions =
        deploymentUnit.getAttachmentList(org.jboss.as.ee.component.Attachments.WEB_SETUP_ACTIONS);

    // Create the context
    final StandardContext webContext = new StandardContext();
    final JBossContextConfig config = new JBossContextConfig(deploymentUnit);

    // Add SecurityAssociationValve right at the beginning
    webContext.addValve(new SecurityContextAssociationValve(deploymentUnit));

    // Set the deployment root
    try {
      webContext.setDocBase(deploymentRoot.getPhysicalFile().getAbsolutePath());
    } catch (IOException e) {
      throw new DeploymentUnitProcessingException(e);
    }
    webContext.addLifecycleListener(config);

    final String pathName = pathNameOfDeployment(deploymentUnit, metaData);
    webContext.setPath(pathName);
    webContext.setIgnoreAnnotations(true);
    webContext.setCrossContext(!metaData.isDisableCrossContext());

    final WebInjectionContainer injectionContainer =
        new WebInjectionContainer(module.getClassLoader());

    // see AS7-2077
    // basically we want to ignore components that have failed for whatever reason
    // if they are important they will be picked up when the web deployment actually starts
    final Map<String, ComponentInstantiator> components =
        deploymentUnit.getAttachment(WebAttachments.WEB_COMPONENT_INSTANTIATORS);
    if (components != null) {
      final Set<ServiceName> failed =
          deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.FAILED_COMPONENTS);
      for (Map.Entry<String, ComponentInstantiator> entry : components.entrySet()) {
        boolean skip = false;
        for (final ServiceName serviceName : entry.getValue().getServiceNames()) {
          if (failed.contains(serviceName)) {
            skip = true;
            break;
          }
        }
        if (!skip) {
          injectionContainer.addInstantiator(entry.getKey(), entry.getValue());
        }
      }
    }

    final Loader loader = new WebCtxLoader(classLoader);
    webContext.setLoader(loader);

    // Valves
    List<ValveMetaData> valves = metaData.getValves();
    if (valves == null) {
      metaData.setValves(valves = new ArrayList<ValveMetaData>());
    }
    for (ValveMetaData valve : valves) {
      Valve valveInstance =
          (Valve) getInstance(module, valve.getModule(), valve.getValveClass(), valve.getParams());
      webContext.getPipeline().addValve(valveInstance);
    }

    // Container listeners
    List<ContainerListenerMetaData> listeners = metaData.getContainerListeners();
    if (listeners != null) {
      for (ContainerListenerMetaData listener : listeners) {
        switch (listener.getListenerType()) {
          case CONTAINER:
            ContainerListener containerListener =
                (ContainerListener)
                    getInstance(
                        module,
                        listener.getModule(),
                        listener.getListenerClass(),
                        listener.getParams());
            webContext.addContainerListener(containerListener);
            break;
          case LIFECYCLE:
            LifecycleListener lifecycleListener =
                (LifecycleListener)
                    getInstance(
                        module,
                        listener.getModule(),
                        listener.getListenerClass(),
                        listener.getParams());
            if (webContext instanceof Lifecycle) {
              ((Lifecycle) webContext).addLifecycleListener(lifecycleListener);
            }
            break;
          case SERVLET_INSTANCE:
            webContext.addInstanceListener(listener.getListenerClass());
            break;
          case SERVLET_CONTAINER:
            webContext.addWrapperListener(listener.getListenerClass());
            break;
          case SERVLET_LIFECYCLE:
            webContext.addWrapperLifecycle(listener.getListenerClass());
            break;
        }
      }
    }

    // Set the session cookies flag according to metadata
    switch (metaData.getSessionCookies()) {
      case JBossWebMetaData.SESSION_COOKIES_ENABLED:
        webContext.setCookies(true);
        break;
      case JBossWebMetaData.SESSION_COOKIES_DISABLED:
        webContext.setCookies(false);
        break;
    }

    String metaDataSecurityDomain = metaData.getSecurityDomain();
    if (metaDataSecurityDomain != null) {
      metaDataSecurityDomain = metaDataSecurityDomain.trim();
    }

    String securityDomain =
        metaDataSecurityDomain == null
            ? SecurityConstants.DEFAULT_APPLICATION_POLICY
            : SecurityUtil.unprefixSecurityDomain(metaDataSecurityDomain);

    // Setup an deployer configured ServletContext attributes
    final List<ServletContextAttribute> attributes =
        deploymentUnit.getAttachment(ServletContextAttribute.ATTACHMENT_KEY);

    try {
      final ServiceName deploymentServiceName =
          WebSubsystemServices.deploymentServiceName(hostName, pathName);
      final ServiceName realmServiceName = deploymentServiceName.append("realm");

      final JBossWebRealmService realmService = new JBossWebRealmService(deploymentUnit);
      ServiceBuilder<?> builder = serviceTarget.addService(realmServiceName, realmService);
      builder
          .addDependency(
              DependencyType.REQUIRED,
              SecurityDomainService.SERVICE_NAME.append(securityDomain),
              SecurityDomainContext.class,
              realmService.getSecurityDomainContextInjector())
          .setInitialMode(Mode.ACTIVE)
          .install();

      final WebDeploymentService webDeploymentService =
          new WebDeploymentService(webContext, injectionContainer, setupActions, attributes);
      builder =
          serviceTarget
              .addService(deploymentServiceName, webDeploymentService)
              .addDependency(
                  WebSubsystemServices.JBOSS_WEB_HOST.append(hostName),
                  VirtualHost.class,
                  new WebContextInjector(webContext))
              .addDependencies(injectionContainer.getServiceNames())
              .addDependency(realmServiceName, Realm.class, webDeploymentService.getRealm())
              .addDependencies(deploymentUnit.getAttachmentList(Attachments.WEB_DEPENDENCIES))
              .addDependency(JndiNamingDependencyProcessor.serviceName(deploymentUnit));

      // add any dependencies required by the setup action
      for (final SetupAction action : setupActions) {
        builder.addDependencies(action.dependencies());
      }

      if (metaData.getDistributable() != null) {
        DistributedCacheManagerFactoryService factoryService =
            new DistributedCacheManagerFactoryService();
        DistributedCacheManagerFactory factory = factoryService.getValue();
        if (factory != null) {
          ServiceName factoryServiceName = deploymentServiceName.append("session");
          builder.addDependency(
              DependencyType.OPTIONAL,
              factoryServiceName,
              DistributedCacheManagerFactory.class,
              config.getDistributedCacheManagerFactoryInjector());

          ServiceBuilder<DistributedCacheManagerFactory> factoryBuilder =
              serviceTarget.addService(factoryServiceName, factoryService);
          boolean enabled = factory.addDependencies(serviceTarget, factoryBuilder, metaData);
          factoryBuilder
              .setInitialMode(
                  enabled ? ServiceController.Mode.ON_DEMAND : ServiceController.Mode.NEVER)
              .install();
        }
      }

      builder.install();

      // adding JACC service
      AbstractSecurityDeployer<?> deployer = new WarSecurityDeployer();
      JaccService<?> service = deployer.deploy(deploymentUnit);
      if (service != null) {
        ((WarJaccService) service).setContext(webContext);
        final ServiceName jaccServiceName =
            JaccService.SERVICE_NAME.append(deploymentUnit.getName());
        builder = serviceTarget.addService(jaccServiceName, service);
        if (deploymentUnit.getParent() != null) {
          // add dependency to parent policy
          final DeploymentUnit parentDU = deploymentUnit.getParent();
          builder.addDependency(
              JaccService.SERVICE_NAME.append(parentDU.getName()),
              PolicyConfiguration.class,
              service.getParentPolicyInjector());
        }
        // add dependency to web deployment service
        builder.addDependency(deploymentServiceName);
        builder.setInitialMode(Mode.ACTIVE).install();
      }
    } catch (ServiceRegistryException e) {
      throw new DeploymentUnitProcessingException(MESSAGES.failedToAddWebDeployment(), e);
    }

    // Process the web related mgmt information
    final ModelNode node = deploymentUnit.getDeploymentSubsystemModel("web");
    node.get("context-root").set("".equals(pathName) ? "/" : pathName);
    node.get("virtual-host").set(hostName);
    processManagement(deploymentUnit, metaData);
  }