Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * JBoss, Home of Professional Open Source.
   * Copyright 2006, Red Hat Middleware LLC, and individual contributors
   * as indicated by the @author tags. See the copyright.txt file in the
   * distribution for a full listing of individual contributors.
   *
   * This is free software; you can redistribute it and/or modify it
   * under the terms of the GNU Lesser General Public License as
   * published by the Free Software Foundation; either version 2.1 of
  * the License, or (at your option) any later version.
  *
  * This software is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */
 
 package org.jboss.web.tomcat.service.deployers;
 
 import java.io.File;
 import java.util.List;
 
 
Temporary workaround to support controlling the lifecycle of the webserver runtime portion of TomcatDeployer via a JMX service in the deploy directory. We want it in deploy so dependencies on services in deploy can be properly expressed. We want it as a JMX service so the ServiceBindingManager can alter the connector ports.

A more long term solution involves:

  1. separating out the JBossWeb runtime aspects from TomcatDeployer and putting them in a separate class
  2. developing a ProfileService-based alternative to ServiceBindingManager

Author(s):
Brian Stansberry
Version:
$Revision: 86387 $
 
 {
   
   
The associated Tomcat deployer *
 
    private TomcatDeployer tomcatDeployer;
   
   
The executor the Tomcat service should use *
 
    private Executor executor;
    
    // Use a flag because isInShutdown doesn't appear to be correct
    private boolean connectorsRunning = false;
 
    // Dependency inject the Executor pojo
 
   public Executor getExecutor()
   {
      return ;
   }
   public void setExecutor(Executor executor)
   {
      this. = executor;
   }
   // Dependency inject the TomcatDeployer pojo
   {
      return ;
   }
   public void setTomcatDeployer(TomcatDeployer tomcatDeployer)
   {
      this. = tomcatDeployer;
   }
   // In our lifecycle, we invoke the webserver lifecycle-related operations
   // in the TomcatDeployer
   protected void startService() throws Exception
   {
      if ( == null)
         throw new IllegalStateException("Must set TomcatDeployer before starting");
      // Load Catalina properties
      CatalinaProperties.getProperty("");
      .debug("Starting tomcat deployer");
      MBeanServer server = super.getServer();
      SecurityActions.setSystemProperty("catalina.ext.dirs"
            (SecurityActions.getSystemProperty("jboss.server.home.dir"null) + . + "lib"));
      String objectNameS = .getDomain() + ":type=Catalina";
      ObjectName objectName = new ObjectName(objectNameS);
      // Parse main server.xml
      // FIXME: this could be done somewhere else
      SchemaBinding schema = JBossXBBuilder.build(ServerMetaData.class);
      Unmarshaller u = UnmarshallerFactory.newInstance().newUnmarshaller();
      u.setSchemaValidation(false);
      u.setValidation(false);
      InputStream is = null;
      ServerMetaData serverMetaData = null;
      try {
         File configFile = new File(.getConfigFile());
         if (configFile.exists())
         {
            is = new FileInputStream(configFile);
         }
         else
         {
         }
         if (is == null) {
            .error("Could not read configured server.xml (will try default): " + .getConfigFile());
            is = getClass().getClassLoader().getResourceAsStream("server.xml");
         }
         serverMetaData = ServerMetaData.class.cast(u.unmarshal(isschema));
      } finally {
         if (is != null) {
            try {
               is.close();
            } catch (IOException e) {
               // Ignore
            }
         }
      }
      
      // FIXME: could try to do stuff with EngineConfig and HostConfig, although neither
      //        should be useful in JBoss
      
      // Create the Catalina instance
      Catalina catalina = new Catalina();
      catalina.setCatalinaHome(System.getProperty("jboss.server.home.dir"));
      catalina.setUseNaming(false);
      catalina.setUseShutdownHook(false);
      catalina.setAwait(false);
      catalina.setRedirectStreams(false);
      
      // Set the modeler Registry MBeanServer to the that of the tomcat service
      Registry.getRegistry(nullnull).setMBeanServer(server);
      // Register the Catalina instance
      Registry.getRegistry(nullnull).registerComponent(catalinaobjectName"org.apache.catalina.startup.Catalina");
      
      // Use the server.xml metadata to create a Server instance and assign it to the Catalina instance
      
      // Server
      org.apache.catalina.Server catalinaServer = 
         (org.apache.catalina.ServergetInstance(serverMetaData"org.apache.catalina.core.StandardServer");
      Registry.getRegistry(nullnull).registerComponent(catalinaServer
            new ObjectName(.getDomain() + ":type=Server"), "org.apache.catalina.startup.StandardServer");
      addLifecycleListeners(catalinaServerserverMetaData.getListeners());
      
      // Server/Service
      if (serverMetaData.getServices() == null)
      {
         throw new IllegalArgumentException("No services");
      }
      Iterator<ServiceMetaDataserviceMetaDatas = serverMetaData.getServices().iterator();
      while (serviceMetaDatas.hasNext())
      {
         ServiceMetaData serviceMetaData = serviceMetaDatas.next();
         org.apache.catalina.Service service = 
            (org.apache.catalina.ServicegetInstance(serviceMetaData"org.apache.catalina.core.StandardService");
         addLifecycleListeners(serviceserviceMetaData.getListeners());
         service.setName(serviceMetaData.getName());
         service.setServer(catalinaServer);
         catalinaServer.addService(service);
         
         // Server/Service/Executor
         // Executor is useless in JBoss: the Executor will get injected in the executor field
         // and used directly
         
         // Server/Service/Connector
         if (serviceMetaData.getConnectors() != null)
         {
            Iterator<ConnectorMetaDataconnectorMetaDatas = serviceMetaData.getConnectors().iterator();
            while (connectorMetaDatas.hasNext())
            {
               ConnectorMetaData connectorMetaData = connectorMetaDatas.next();
               Connector connector = new Connector(connectorMetaData.getProtocol());
               if (connectorMetaData.getAttributes() != null)
               {
                  Iterator<QNamenames = connectorMetaData.getAttributes().keySet().iterator();
                  while (names.hasNext())
                  {
                     QName name = names.next();
                     String value = (StringconnectorMetaData.getAttributes().get(name);
                     // FIXME: This should be done by XB
                     value = StringPropertyReplacer.replaceProperties(value);
                     IntrospectionUtils.setProperty(connectorname.getLocalPart(), value);
                  }
               }
               if ( != null)
               {
                  IntrospectionUtils.callMethod1(connector.getProtocolHandler(), "setExecutor"
                        java.util.concurrent.Executor.class.getName(), getClass().getClassLoader());
               }
               service.addConnector(connector);
            }
         }
         
         // Server/Service/Engine
         EngineMetaData engineMetaData = serviceMetaData.getEngine();
         org.apache.catalina.Engine engine = 
            (org.apache.catalina.EnginegetInstance(engineMetaData"org.apache.catalina.core.StandardEngine");
         addLifecycleListeners(engineengineMetaData.getListeners());
         engine.setName(engineMetaData.getName());
         // FIXME: This should be done by XB
         if (engineMetaData.getJvmRoute() != null) {
            engine.setJvmRoute(StringPropertyReplacer.replaceProperties(engineMetaData.getJvmRoute()));
         }
         //engine.setJvmRoute(engineMetaData.getJvmRoute());
         engine.setDefaultHost(engineMetaData.getDefaultHost());
         service.setContainer(engine);
         
         // Server/Service/Engine/Realm
         if (engineMetaData.getRealm() != null) {
            engine.setRealm((org.apache.catalina.RealmgetInstance(engineMetaData.getRealm(), null));
         }
         
         // Server/Service/Engine/Valve
         addValves(engineengineMetaData.getValves());
         
         // Server/Service/Engine/Host
         if (engineMetaData.getHosts() != null)
         {
            Iterator<HostMetaDatahostMetaDatas = engineMetaData.getHosts().iterator();
            while (hostMetaDatas.hasNext())
            {
               HostMetaData hostMetaData = hostMetaDatas.next();
               org.apache.catalina.Host host =
                  (org.apache.catalina.HostgetInstance(hostMetaData"org.apache.catalina.core.StandardHost");
               addLifecycleListeners(hosthostMetaData.getListeners());
               host.setName(hostMetaData.getName());
               engine.addChild(host);
               
               // Server/Service/Engine/Host/Realm
               if (hostMetaData.getRealm() != null) {
                  host.setRealm((org.apache.catalina.RealmgetInstance(hostMetaData.getRealm(), null));
               }
               
               // Server/Service/Engine/Host/Valve
               addValves(hosthostMetaData.getValves());
               
               // Server/Service/Engine/Host/Alias
               if (hostMetaData.getAliases() != null) {
                  Iterator<Stringaliases = hostMetaData.getAliases().iterator();
                  while (aliases.hasNext()) {
                     host.addAlias(aliases.next());
                  }
               }
               
            }
         }
         
      }
      
      // Set the resulting Server to the Catalina instance
      catalina.setServer(catalinaServer);
      
      // Start Tomcat
      catalina.create();
      catalinaServer.initialize();
      catalina.start();
      // Set up the authenticators in JNDI such that they can be configured for web apps
      InitialContext ic = new InitialContext();
      try
      {
         ic.bind("TomcatAuthenticators".getAuthenticators());
      }
      catch (NamingException ne)
      {
         if (.isTraceEnabled())
            .trace("Binding Authenticators to JNDI failed"ne);
      }
      finally
      {
         try
         {
            ic.close();
         }
         catch (NamingException nee)
         {
         }
      }
      // Register the web container JACC PolicyContextHandlers
      // If we are hot-deployed *after* the overall server is started
      // we'll never receive Server.START_NOTIFICATION_TYPE, so check
      // with the Server and start the connectors immediately, if this is the case.
      // Otherwise register to receive the server start-up notification.
      Boolean started = (Booleanserver.getAttribute(."Started");
      if (started.booleanValue() == true)
      {
         .debug("Server '" + . + "' already started, starting connectors now");
         startConnectors();
      }
      else
      {
         // Register for notification of the overall server startup
         .debug("Server '" + . + "' not started, registering for start-up notification");
         server.addNotificationListener(.thisnullnull);
      }
   }

   
Create a JavaBean corresponding to the given metadata, similar to what the digester is doing.
   protected static Object getInstance(AnyXmlMetaData metaDataString defaultClassNamethrows Exception
   {
      String className = metaData.getClassName();
      if (className == null) {
         className = defaultClassName;
      }
      if (className == null) {
         throw new IllegalArgumentException("No className specified for element");
      }
      Object instance = TomcatService.class.getClassLoader().loadClass(className).newInstance();
      if (metaData.getAttributes() != null) {
         Iterator<QNamenames = metaData.getAttributes().keySet().iterator();
         while (names.hasNext()) {
            QName name = names.next();
            String value = (StringmetaData.getAttributes().get(name);
            // FIXME: This should be done by XB
            value = StringPropertyReplacer.replaceProperties(value);
            IntrospectionUtils.setProperty(instancename.getLocalPart(), value);
         }
      }
      return instance;
   }
   
   
Associate lifecycle listeners with the instance, if it implements Lifecycle.
   protected static void addLifecycleListeners(Object instanceList<ListenerMetaDatalistthrows Exception
   {
      if (list == null) {
         return;
      }
      org.apache.catalina.Lifecycle lifecycle = null;
      if (!(instance instanceof org.apache.catalina.Lifecycle))
      {
         return;
      }
      else
      {
         lifecycle = (org.apache.catalina.Lifecycleinstance;
      }
      Iterator<ListenerMetaDatalistenerMetaDatas = list.iterator();
      while (listenerMetaDatas.hasNext())
      {
         ListenerMetaData listenerMetaData = listenerMetaDatas.next();
         lifecycle.addLifecycleListener((org.apache.catalina.LifecycleListenergetInstance(listenerMetaDatanull));
      }
   }
   
   
   
Associate valves with the instance, if it implements Lifecycle.
   protected static void addValves(Object instanceList<ValveMetaDatalistthrows Exception
   {
      if (list == null) {
         return;
      }
      org.apache.catalina.Pipeline pipeline = null;
      if (!(instance instanceof org.apache.catalina.Pipeline))
      {
         return;
      }
      else
      {
         pipeline = (org.apache.catalina.Pipelineinstance;
      }
      Iterator<ValveMetaDatavalveMetaDatas = list.iterator();
      while (valveMetaDatas.hasNext())
      {
         ValveMetaData valveMetaData = valveMetaDatas.next();
         pipeline.addValve((org.apache.catalina.ValvegetInstance(valveMetaDatanull));
      }
   }
   
   
   protected void stopService() throws Exception
   {
      if ( == null)
         throw new IllegalStateException("Must set TomcatDeployer before stopping");
      // Hot undeploy
      Boolean inShutdown = (Boolean.getAttribute(."InShutdown");
      if (inShutdown.booleanValue() == false)
      {
         .debug("Server '" + . + "' already started, stopping connectors now");
         stopConnectors();
      }
      MBeanServer server = super.getServer();
      String objectNameS = .getDomain() + ":type=Catalina";
      ObjectName objectName = new ObjectName(objectNameS);
      server.invoke(objectName"stop"new Object[]{}, new String[]{});
      server.invoke(objectName"destroy"new Object[]{}, new String[]{});
      server.unregisterMBean(objectName);
      MBeanServer server2 = server;
      // Unregister any remaining jboss.web or Catalina MBeans
      ObjectName queryObjectName = new ObjectName(.getDomain() + ":*");
      Iterator iterator = server2.queryMBeans(queryObjectNamenull).iterator();
      while (iterator.hasNext())
      {
         ObjectInstance oi = (ObjectInstanceiterator.next();
         ObjectName toRemove = oi.getObjectName();
         // Exception: Don't unregister the service right now
         if (!"WebServer".equals(toRemove.getKeyProperty("service")))
         {
            if (server2.isRegistered(toRemove))
            {
               server2.unregisterMBean(toRemove);
            }
         }
      }
   }
   // Expose the TomcatDeployer MBean interface
   public String getConfigFile()
   {
      return  == null ? null : .getConfigFile();
   }
   {
      return  == null ? null : .getContextMBeanCode();
   }
   public boolean getUseJBossWebLoader()
   {
      return  == null ? false : .getUseJBossWebLoader();
   }
   public String getDomain()
   {
      return  == null ? null : .getDomain();
   }
   public String[] getFilteredPackages()
   {
      return  == null ? null : .getFilteredPackages();
   }
   public String getManagerClass()
   {
      return  == null ? null : .getManagerClass();
   }
   {
      return  == null ? null : .getSessionIdAlphabet();
   }
   {
      return  == null ? null : .getSubjectAttributeName();
   }
   public boolean getDeleteWorkDirOnContextDestroy()
   {
      return  == null ? false : .getDeleteWorkDirOnContextDestroy();
   }
   public boolean isAllowSelfPrivilegedWebApps()
   {
      return  == null ? false : .isAllowSelfPrivilegedWebApps();
   }
   public void setAllowSelfPrivilegedWebApps(boolean flag)
   {
      if ( != null)
   }
   public void setConfigFile(String configFile)
   {
      if ( != null)
         .setConfigFile(configFile);
   }
   public void setContextMBeanCode(String className)
   {
      if ( != null)
         .setContextMBeanCode(className);
   }
   public void setDeleteWorkDirOnContextDestroy(boolean flag)
   {
      if ( != null)
   }
   public void setDomain(String domainName)
   {
      if ( != null)
         .setDomain(domainName);
   }
   public void setFilteredPackages(String[] pkgs)
   {
      if ( != null)
         .setFilteredPackages(pkgs);
   }
   public void setManagerClass(String managerClass)
   {
      if ( != null)
         .setManagerClass(managerClass);
   }
   {
      if ( != null)
   }
   public void setSessionIdAlphabet(String sessionIdAlphabet)
   {
      if ( != null)
         .setSessionIdAlphabet(sessionIdAlphabet);
   }
   public void setSubjectAttributeName(String name)
   {
      if ( != null)
   }
   public void setUseJBossWebLoader(boolean flag)
   {
      if ( != null)
         .setUseJBossWebLoader(flag);
   }
   public void startConnectors() throws Exception
   {
      if ( == null)
         throw new IllegalStateException("Must set TomcatDeployer before starting connectors");
      if ()
         return;
      MBeanServer server = super.getServer();
      ObjectName service = new ObjectName(.getDomain() + ":type=Service,serviceName=jboss.web");
      Object[] args = {};
      String[] sig = {};
      Connector[] connectors = (Connector[]) server.invoke(service"findConnectors"argssig);
      for (int n = 0; n < connectors.lengthn++)
      {
         Lifecycle lc = connectors[n];
         lc.start();
      }
      /*
       * TODO: // Notify listeners that connectors have started processing requests sendNotification(new
       * Notification(TOMCAT_CONNECTORS_STARTED, this, getNextNotificationSequenceNumber()));
       */
       = true;
   }
   public void stopConnectors() throws Exception
   {
      if ( == null)
         throw new IllegalStateException("Must set TomcatDeployer before stopping connectors");
      if (!)
         return;
      MBeanServer server = super.getServer();
      ObjectName service = new ObjectName(.getDomain() + ":type=Service,serviceName=jboss.web");
      Object[] args = {};
      String[] sig = {};
      Connector[] connectors = (Connector[]) server.invoke(service"findConnectors"argssig);
      for (int n = 0; n < connectors.lengthn++)
      {
         connectors[n].pause();
         connectors[n].stop();
      }
       = false;
   }

   
Used to receive notification of the server start msg so the tomcat connectors can be started after all web apps are deployed.
   public void handleNotification(Notification msgObject handback)
   {
      String type = msg.getType();
      if (type.equals(.))
      {
         .debug("Saw " + type + " notification, starting connectors");
         try
         {
            startConnectors();
         }
         catch (Exception e)
         {
            .warn("Failed to startConnectors"e);
         }
      }
      if (type.equals(.))
      {
         .debug("Saw " + type + " notification, stopping connectors");
         try
         {
            stopConnectors();
         }
         catch (Exception e)
         {
            .warn("Failed to stopConnectors"e);
         }
      }
   }
   {
      return  == null ? null : .getDefaultSecurityDomain();
   }
   public boolean getJava2ClassLoadingCompliance()
   {
      return  == null ? false : .getJava2ClassLoadingCompliance();
   }
   public boolean getLenientEjbLink()
   {
      return  == null ? false : .getLenientEjbLink();
   }
   public boolean getUnpackWars()
   {
      return  == null ? false : .getUnpackWars();
   }
   public void setDefaultSecurityDomain(String defaultSecurityDomain)
   {
      if ( != null)
         .setDefaultSecurityDomain(defaultSecurityDomain);
   }
   public void setJava2ClassLoadingCompliance(boolean flag)
   {
      if ( != null)
   }
   public void setLenientEjbLink(boolean flag)
   {
      if ( != null)
         .setLenientEjbLink(flag);
   }
   public void setUnpackWars(boolean flag)
   {
      if ( != null)
         .setUnpackWars(flag);
   }
   /*
    * (non-Javadoc)
    * 
    * @see org.jboss.web.tomcat.service.deployers.TomcatDeployerMBean#getHttpHeaderForSSOAuth()
    */
   {
      return  == null ? null : .getHttpHeaderForSSOAuth();
   }
   /*
    * (non-Javadoc)
    * 
    * @see org.jboss.web.tomcat.service.deployers.TomcatDeployerMBean#setHttpHeaderForSSOAuth(java.lang.String)
    */
   public void setHttpHeaderForSSOAuth(String httpHeaderForSSOAuth)
   {
      if (this. != null)
         this..setHttpHeaderForSSOAuth(httpHeaderForSSOAuth);
   }
   /*
    * (non-Javadoc)
    * 
    * @see org.jboss.web.tomcat.service.deployers.TomcatDeployerMBean#getSessionCookieForSSOAuth()
    */
   {
      return  == null ? null : .getSessionCookieForSSOAuth();
   }
   /*
    * (non-Javadoc)
    * 
    * @see org.jboss.web.tomcat.service.deployers.TomcatDeployerMBean#setSessionCookieForSSOAuth(java.lang.String)
    */
   public void setSessionCookieForSSOAuth(String sessionCookieForSSOAuth)
   {
      if (this. != null)
         this..setSessionCookieForSSOAuth(sessionCookieForSSOAuth);
   }
   
   
Overrides the superclass version to inject the KernelController into JBossWebMicrocontainerBeanLocator.
   public void setKernelControllerContext(KernelControllerContext controllerContextthrows Exception
   {
      super.setKernelControllerContext(controllerContext);
      KernelController kernelController = controllerContext == null ? null : controllerContext.getKernel().getController();
      JBossWebMicrocontainerBeanLocator.setKernelController(kernelController);
   }
   
   
Overrides the superclass version to clear the KernelController from JBossWebMicrocontainerBeanLocator.
   public void unsetKernelControllerContext(KernelControllerContext controllerContextthrows Exception
   {
      super.unsetKernelControllerContext(controllerContext);
      JBossWebMicrocontainerBeanLocator.setKernelController(null);
   }
New to GrepCode? Check out our FAQ X