public void stopServer(String[] arguments) {

    if (arguments != null) {
      arguments(arguments);
    }

    Server s = getServer();
    if (s == null) {
      // Create and execute our Digester
      Digester digester = createStopDigester();
      digester.setClassLoader(Thread.currentThread().getContextClassLoader());
      File file = configFile();
      try {
        InputSource is = new InputSource("file://" + file.getAbsolutePath());
        FileInputStream fis = new FileInputStream(file);
        is.setByteStream(fis);
        digester.push(this);
        digester.parse(is);
        fis.close();
      } catch (Exception e) {
        log.error("Catalina.stop: ", e);
        System.exit(1);
      }
    } else {
      // Server object already present. Must be running as a service
      if (s instanceof Lifecycle) {
        try {
          ((Lifecycle) s).stop();
        } catch (LifecycleException e) {
          log.error("Catalina.stop: ", e);
        }
        return;
      }
      // else fall down
    }

    // Stop the existing server
    s = getServer();
    try {
      if (s.getPort() > 0) {
        String hostAddress = InetAddress.getByName("localhost").getHostAddress();
        Socket socket = new Socket(hostAddress, getServer().getPort());
        OutputStream stream = socket.getOutputStream();
        String shutdown = s.getShutdown();
        for (int i = 0; i < shutdown.length(); i++) stream.write(shutdown.charAt(i));
        stream.flush();
        stream.close();
        socket.close();
      } else {
        log.error(sm.getString("catalina.stopServer"));
        System.exit(1);
      }
    } catch (IOException e) {
      log.error("Catalina.stop: ", e);
      System.exit(1);
    }
  }
Esempio n. 2
0
 /** Create the digester which will be used to parse context config files. */
 protected static Digester createDigester() {
   Digester digester = new Digester();
   digester.setValidating(false);
   // Add object creation rule
   digester.addObjectCreate("Context", "org.apache.catalina.core.StandardContext", "className");
   // Set the properties on that object (it doesn't matter if extra
   // properties are set)
   digester.addSetProperties("Context");
   return (digester);
 }
  /** Create and configure the Digester we will be using for shutdown. */
  protected Digester createStopDigester() {

    // Initialize the digester
    Digester digester = new Digester();

    // Configure the rules we need for shutting down
    digester.addObjectCreate("Server", "org.apache.catalina.core.StandardServer", "className");
    digester.addSetProperties("Server");
    digester.addSetNext("Server", "setServer", "org.apache.catalina.Server");

    return (digester);
  }
  /**
   * Resolve the requested external entity.
   *
   * @param publicId The public identifier of the entity being referenced
   * @param systemId The system identifier of the entity being referenced
   * @exception SAXException if a parsing exception occurs
   */
  public InputSource resolveEntity(String publicId, String systemId) throws SAXException {

    if (publicId != null) {
      this.publicId = publicId;
      digester.setPublicId(publicId);
    }

    // Has this system identifier been registered?
    String entityURL = null;
    if (publicId != null) {
      entityURL = entityValidator.get(publicId);
    }

    // Redirect the schema location to a local destination
    String key = null;
    if (entityURL == null && systemId != null) {
      key = systemId.substring(systemId.lastIndexOf('/') + 1);
      entityURL = entityValidator.get(key);
    }

    if (entityURL == null) {
      return (null);
    }

    try {
      return (new InputSource(entityURL));
    } catch (Exception e) {
      throw new SAXException(e);
    }
  }
  void configure(Configuration configuration) {
    long start = System.nanoTime();
    initBaseDir(configuration);
    Digester digester = new FakeCatalina().createStartDigester();
    digester.push(this);

    URL tomcatResource = configuration.getConfigurationURL();
    if (tomcatResource == null) {
      tomcatResource = getClass().getResource("/tomcat-server.xml");
    }

    File configurationFile = new File(configuration.getConfigurationDir(), SERVER_CONFIG_FILE_NAME);
    if (configurationFile.exists()) {
      try {
        tomcatResource = configurationFile.toURI().toURL();
      } catch (MalformedURLException e) {
        LOG.error("Exception while starting Tomcat:", e);
        throw new RuntimeException("Exception while starting Tomcat", e);
      }
    }
    if (tomcatResource != null) {
      ClassLoader loader = Thread.currentThread().getContextClassLoader();
      try {
        Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
        LOG.debug("Configure using resource " + tomcatResource);

        digester.parse(tomcatResource.openStream());
        long elapsed = start - System.nanoTime();
        if (LOG.isInfoEnabled()) {
          LOG.info("configuration processed in {} ms", (elapsed / 1000000));
        }
      } catch (IOException e) {
        LOG.error("Exception while starting Tomcat:", e);
        throw new RuntimeException("Exception while starting Tomcat", e);
      } catch (SAXException e) {
        LOG.error("Exception while starting Tomcat:", e);
        throw new RuntimeException("Exception while starting Tomcat", e);
      } finally {
        Thread.currentThread().setContextClassLoader(loader);
      }
    }

    mergeConfiguration(configuration);
  }
  /**
   * Execute the specified command. This logic only performs the common attribute validation
   * required by all subclasses; it does not perform any functional logic directly.
   *
   * @exception BuildException if a validation error occurs
   */
  @Override
  public void execute() throws BuildException {

    if (path == null) {
      throw new BuildException("Must specify 'path'");
    }

    File file = new File(path, Constants17.getApplicationwebxml());
    if ((!file.exists()) || (!file.canRead())) {
      throw new BuildException("Cannot find web.xml");
    }

    // Commons-logging likes having the context classloader set
    ClassLoader oldCL = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(ValidatorTask.class.getClassLoader());

    // Called through trusted manager interface. If running under a
    // SecurityManager assume that untrusted applications may be deployed.
    Digester digester = DigesterFactory2.newDigester(true, true, null, Globals.isSecurityEnabled());
    try {
      file = file.getCanonicalFile();
      InputStream stream = new BufferedInputStream(new FileInputStream(file));
      InputSource is = new InputSource(file.toURI().toURL().toExternalForm());
      is.setByteStream(stream);
      digester.parse(is);
      handleOutput("web.xml validated");
    } catch (Exception e) {
      if (isFailOnError()) {
        throw new BuildException("Validation failure", e);
      } else {
        handleErrorOutput("Validation failure: " + e);
      }
    } finally {
      Thread.currentThread().setContextClassLoader(oldCL);
      closeRedirector();
    }
  }
Esempio n. 7
0
 /** Cluster support is optional. The JARs may have been removed. */
 private void addClusterRuleSet(Digester digester, String prefix) {
   Class<?> clazz = null;
   Constructor<?> constructor = null;
   try {
     clazz = Class.forName("org.apache.catalina.ha.ClusterRuleSet");
     constructor = clazz.getConstructor(String.class);
     RuleSet ruleSet = (RuleSet) constructor.newInstance(prefix);
     digester.addRuleSet(ruleSet);
   } catch (Exception e) {
     if (log.isDebugEnabled()) {
       log.debug(
           sm.getString("catalina.noCluster", e.getClass().getName() + ": " + e.getMessage()), e);
     } else if (log.isInfoEnabled()) {
       log.info(
           sm.getString("catalina.noCluster", e.getClass().getName() + ": " + e.getMessage()));
     }
   }
 }
  /**
   * Create a <code>Digester</code> parser.
   *
   * @param xmlValidation turn on/off xml validation
   * @param xmlNamespaceAware turn on/off namespace validation
   * @param rule an instance of <code>RuleSet</code> used for parsing the xml.
   */
  public static Digester newDigester(
      boolean xmlValidation, boolean xmlNamespaceAware, RuleSet rule) {
    Digester digester = new Digester();
    digester.setNamespaceAware(xmlNamespaceAware);
    digester.setValidating(xmlValidation);
    digester.setUseContextClassLoader(true);

    SchemaResolver schemaResolver = new SchemaResolver(digester);
    registerLocalSchema(schemaResolver);

    digester.setEntityResolver(schemaResolver);
    if (rule != null) {
      digester.addRuleSet(rule);
    }

    return (digester);
  }
Esempio n. 9
0
  /** Create and configure the Digester we will be using for startup. */
  protected Digester createStartDigester() {
    long t1 = System.currentTimeMillis();
    // Initialize the digester
    Digester digester = new Digester();
    digester.setValidating(false);
    digester.setRulesValidation(true);
    HashMap<Class<?>, List<String>> fakeAttributes = new HashMap<Class<?>, List<String>>();
    ArrayList<String> attrs = new ArrayList<String>();
    attrs.add("className");
    fakeAttributes.put(Object.class, attrs);
    digester.setFakeAttributes(fakeAttributes);
    digester.setUseContextClassLoader(true);

    // Configure the actions we will be using
    digester.addObjectCreate("Server", "org.apache.catalina.core.StandardServer", "className");
    digester.addSetProperties("Server");
    digester.addSetNext("Server", "setServer", "org.apache.catalina.Server");

    digester.addObjectCreate(
        "Server/GlobalNamingResources", "org.apache.catalina.deploy.NamingResources");
    digester.addSetProperties("Server/GlobalNamingResources");
    digester.addSetNext(
        "Server/GlobalNamingResources",
        "setGlobalNamingResources",
        "org.apache.catalina.deploy.NamingResources");

    digester.addObjectCreate(
        "Server/Listener",
        null, // MUST be specified in the element
        "className");
    digester.addSetProperties("Server/Listener");
    digester.addSetNext(
        "Server/Listener", "addLifecycleListener", "org.apache.catalina.LifecycleListener");

    digester.addObjectCreate(
        "Server/Service", "org.apache.catalina.core.StandardService", "className");
    digester.addSetProperties("Server/Service");
    digester.addSetNext("Server/Service", "addService", "org.apache.catalina.Service");

    digester.addObjectCreate(
        "Server/Service/Listener",
        null, // MUST be specified in the element
        "className");
    digester.addSetProperties("Server/Service/Listener");
    digester.addSetNext(
        "Server/Service/Listener", "addLifecycleListener", "org.apache.catalina.LifecycleListener");

    // Executor
    digester.addObjectCreate(
        "Server/Service/Executor", "org.apache.catalina.core.StandardThreadExecutor", "className");
    digester.addSetProperties("Server/Service/Executor");

    digester.addSetNext("Server/Service/Executor", "addExecutor", "org.apache.catalina.Executor");

    digester.addRule("Server/Service/Connector", new ConnectorCreateRule());
    digester.addRule(
        "Server/Service/Connector", new SetAllPropertiesRule(new String[] {"executor"}));
    digester.addSetNext(
        "Server/Service/Connector", "addConnector", "org.apache.catalina.connector.Connector");

    digester.addObjectCreate(
        "Server/Service/Connector/Listener",
        null, // MUST be specified in the element
        "className");
    digester.addSetProperties("Server/Service/Connector/Listener");
    digester.addSetNext(
        "Server/Service/Connector/Listener",
        "addLifecycleListener",
        "org.apache.catalina.LifecycleListener");

    // Add RuleSets for nested elements
    digester.addRuleSet(new NamingRuleSet("Server/GlobalNamingResources/"));
    digester.addRuleSet(new EngineRuleSet("Server/Service/"));
    digester.addRuleSet(new HostRuleSet("Server/Service/Engine/"));
    digester.addRuleSet(new ContextRuleSet("Server/Service/Engine/Host/"));
    addClusterRuleSet(digester, "Server/Service/Engine/Host/Cluster/");
    digester.addRuleSet(new NamingRuleSet("Server/Service/Engine/Host/Context/"));

    // When the 'engine' is found, set the parentClassLoader.
    digester.addRule("Server/Service/Engine", new SetParentClassLoaderRule(parentClassLoader));
    addClusterRuleSet(digester, "Server/Service/Engine/Cluster/");

    long t2 = System.currentTimeMillis();
    if (log.isDebugEnabled()) {
      log.debug("Digester for server.xml created " + (t2 - t1));
    }
    return (digester);
  }
  /** Start a new server instance. */
  public void load() {

    long t1 = System.nanoTime();

    initDirs();

    // Before digester - it may be needed

    initNaming();

    // Create and execute our Digester
    Digester digester = createStartDigester();

    InputSource inputSource = null;
    InputStream inputStream = null;
    File file = null;
    try {
      file = configFile();
      inputStream = new FileInputStream(file);
      inputSource = new InputSource("file://" + file.getAbsolutePath());
    } catch (Exception e) {;
    }
    if (inputStream == null) {
      try {
        inputStream = getClass().getClassLoader().getResourceAsStream(getConfigFile());
        inputSource =
            new InputSource(getClass().getClassLoader().getResource(getConfigFile()).toString());
      } catch (Exception e) {;
      }
    }

    // This should be included in catalina.jar
    // Alternative: don't bother with xml, just create it manually.
    if (inputStream == null) {
      try {
        inputStream = getClass().getClassLoader().getResourceAsStream("server-embed.xml");
        inputSource =
            new InputSource(getClass().getClassLoader().getResource("server-embed.xml").toString());
      } catch (Exception e) {;
      }
    }

    if ((inputStream == null) && (file != null)) {
      log.warn("Can't load server.xml from " + file.getAbsolutePath());
      if (file.exists() && !file.canRead()) {
        log.warn("Permissions incorrect, read permission is not allowed on the file.");
      }
      return;
    }

    try {
      inputSource.setByteStream(inputStream);
      digester.push(this);
      digester.parse(inputSource);
      inputStream.close();
    } catch (Exception e) {
      log.warn("Catalina.start using " + getConfigFile() + ": ", e);
      return;
    }

    // Stream redirection
    initStreams();

    // Start the new server
    if (getServer() instanceof Lifecycle) {
      try {
        getServer().initialize();
      } catch (LifecycleException e) {
        if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE"))
          throw new java.lang.Error(e);
        else log.error("Catalina.start", e);
      }
    }

    long t2 = System.nanoTime();
    if (log.isInfoEnabled())
      log.info("Initialization processed in " + ((t2 - t1) / 1000000) + " ms");
  }
Esempio n. 11
0
 @Override
 protected Digester createStartDigester() {
   Digester digester = super.createStartDigester();
   digester.setClassLoader(getClass().getClassLoader());
   return digester;
 }
Esempio n. 12
0
  /**
   * Add the set of Rule instances defined in this RuleSet to the specified <code>Digester</code>
   * instance, associating them with our namespace URI (if any). This method should only be called
   * by a Digester instance.
   *
   * @param digester Digester instance to which the new Rule instances should be added.
   */
  @Override
  public void addRuleInstances(Digester digester) {
    // Cluster configuration start
    digester.addObjectCreate(
        prefix + "Manager",
        null, // MUST be specified in the element
        "className");
    digester.addSetProperties(prefix + "Manager");
    digester.addSetNext(
        prefix + "Manager", "setManagerTemplate", "org.apache.catalina.ha.ClusterManager");

    digester.addObjectCreate(
        prefix + "Channel",
        null, // MUST be specified in the element
        "className");
    digester.addSetProperties(prefix + "Channel");
    digester.addSetNext(prefix + "Channel", "setChannel", "org.apache.catalina.tribes.Channel");

    String channelPrefix = prefix + "Channel/";

    // channel properties
    digester.addObjectCreate(
        channelPrefix + "Membership",
        null, // MUST be specified in the element
        "className");
    digester.addSetProperties(channelPrefix + "Membership");
    digester.addSetNext(
        channelPrefix + "Membership",
        "setMembershipService",
        "org.apache.catalina.tribes.MembershipService");

    digester.addObjectCreate(
        channelPrefix + "Sender",
        null, // MUST be specified in the element
        "className");
    digester.addSetProperties(channelPrefix + "Sender");
    digester.addSetNext(
        channelPrefix + "Sender", "setChannelSender", "org.apache.catalina.tribes.ChannelSender");

    digester.addObjectCreate(
        channelPrefix + "Sender/Transport",
        null, // MUST be specified in the element
        "className");
    digester.addSetProperties(channelPrefix + "Sender/Transport");
    digester.addSetNext(
        channelPrefix + "Sender/Transport",
        "setTransport",
        "org.apache.catalina.tribes.transport.MultiPointSender");

    digester.addObjectCreate(
        channelPrefix + "Receiver",
        null, // MUST be specified in the element
        "className");
    digester.addSetProperties(channelPrefix + "Receiver");
    digester.addSetNext(
        channelPrefix + "Receiver",
        "setChannelReceiver",
        "org.apache.catalina.tribes.ChannelReceiver");

    digester.addObjectCreate(
        channelPrefix + "Interceptor",
        null, // MUST be specified in the element
        "className");
    digester.addSetProperties(channelPrefix + "Interceptor");
    digester.addSetNext(
        channelPrefix + "Interceptor",
        "addInterceptor",
        "org.apache.catalina.tribes.ChannelInterceptor");

    digester.addObjectCreate(
        channelPrefix + "Interceptor/Member",
        null, // MUST be specified in the element
        "className");
    digester.addSetProperties(channelPrefix + "Interceptor/Member");
    digester.addSetNext(
        channelPrefix + "Interceptor/Member",
        "addStaticMember",
        "org.apache.catalina.tribes.Member");

    digester.addObjectCreate(
        prefix + "Valve",
        null, // MUST be specified in the element
        "className");
    digester.addSetProperties(prefix + "Valve");
    digester.addSetNext(prefix + "Valve", "addValve", "org.apache.catalina.Valve");

    digester.addObjectCreate(
        prefix + "Deployer",
        null, // MUST be specified in the element
        "className");
    digester.addSetProperties(prefix + "Deployer");
    digester.addSetNext(
        prefix + "Deployer", "setClusterDeployer", "org.apache.catalina.ha.ClusterDeployer");

    digester.addObjectCreate(
        prefix + "Listener",
        null, // MUST be specified in the element
        "className");
    digester.addSetProperties(prefix + "Listener");
    digester.addSetNext(
        prefix + "Listener", "addLifecycleListener", "org.apache.catalina.LifecycleListener");

    digester.addObjectCreate(
        prefix + "ClusterListener",
        null, // MUST be specified in the element
        "className");
    digester.addSetProperties(prefix + "ClusterListener");
    digester.addSetNext(
        prefix + "ClusterListener", "addClusterListener", "org.apache.catalina.ha.ClusterListener");
    // Cluster configuration end
  }
Esempio n. 13
0
  /**
   * @param contextPath
   * @param dir
   * @param file
   */
  protected void deployDirectory(String contextPath, File dir, String file) {
    DeployedApplication deployedApp = new DeployedApplication(contextPath);

    if (deploymentExists(contextPath)) return;

    // Deploy the application in this directory
    if (log.isInfoEnabled()) log.info(sm.getString("hostConfig.deployDir", file));
    try {
      Context context = null;
      File xml = new File(dir, Constants.ApplicationContextXml);
      File xmlCopy = null;
      if (deployXML && xml.exists()) {
        // Will only do this on initial deployment. On subsequent
        // deployments the copied xml file means we'll use
        // deployDescriptor() instead
        synchronized (digester) {
          try {
            context = (Context) digester.parse(xml);
            if (context == null) {
              log.error(sm.getString("hostConfig.deployDescriptor.error", xml));
              return;
            }
          } finally {
            digester.reset();
          }
        }
        configBase.mkdirs();
        xmlCopy = new File(configBase, file + ".xml");
        InputStream is = null;
        OutputStream os = null;
        try {
          is = new FileInputStream(xml);
          os = new FileOutputStream(xmlCopy);
          IOTools.flow(is, os);
          // Don't catch IOE - let the outer try/catch handle it
        } finally {
          try {
            if (is != null) is.close();
          } catch (IOException e) {
            // Ignore
          }
          try {
            if (os != null) os.close();
          } catch (IOException e) {
            // Ignore
          }
        }
        context.setConfigFile(xmlCopy.getAbsolutePath());
      } else {
        context = (Context) Class.forName(contextClass).newInstance();
      }

      if (context instanceof Lifecycle) {
        Class clazz = Class.forName(host.getConfigClass());
        LifecycleListener listener = (LifecycleListener) clazz.newInstance();
        ((Lifecycle) context).addLifecycleListener(listener);
      }
      context.setPath(contextPath);
      context.setDocBase(file);
      host.addChild(context);
      deployedApp.redeployResources.put(dir.getAbsolutePath(), new Long(dir.lastModified()));
      if (xmlCopy != null) {
        deployedApp.redeployResources.put(
            xmlCopy.getAbsolutePath(), new Long(xmlCopy.lastModified()));
      }
      addWatchedResources(deployedApp, dir.getAbsolutePath(), context);
    } catch (Throwable t) {
      log.error(sm.getString("hostConfig.deployDir.error", file), t);
    }

    deployed.put(contextPath, deployedApp);
  }
Esempio n. 14
0
  /**
   * @param contextPath
   * @param war
   * @param file
   */
  protected void deployWAR(String contextPath, File war, String file) {

    if (deploymentExists(contextPath)) return;

    // Checking for a nested /META-INF/context.xml
    JarFile jar = null;
    JarEntry entry = null;
    InputStream istream = null;
    BufferedOutputStream ostream = null;
    File xml = new File(configBase, file.substring(0, file.lastIndexOf(".")) + ".xml");
    if (deployXML && !xml.exists()) {
      try {
        jar = new JarFile(war);
        entry = jar.getJarEntry(Constants.ApplicationContextXml);
        if (entry != null) {
          istream = jar.getInputStream(entry);

          configBase.mkdirs();

          ostream = new BufferedOutputStream(new FileOutputStream(xml), 1024);
          byte buffer[] = new byte[1024];
          while (true) {
            int n = istream.read(buffer);
            if (n < 0) {
              break;
            }
            ostream.write(buffer, 0, n);
          }
          ostream.flush();
          ostream.close();
          ostream = null;
          istream.close();
          istream = null;
          entry = null;
          jar.close();
          jar = null;
        }
      } catch (Exception e) {
        // Ignore and continue
        if (ostream != null) {
          try {
            ostream.close();
          } catch (Throwable t) {;
          }
          ostream = null;
        }
        if (istream != null) {
          try {
            istream.close();
          } catch (Throwable t) {;
          }
          istream = null;
        }
      } finally {
        entry = null;
        if (jar != null) {
          try {
            jar.close();
          } catch (Throwable t) {;
          }
          jar = null;
        }
      }
    }

    DeployedApplication deployedApp = new DeployedApplication(contextPath);

    // Deploy the application in this WAR file
    if (log.isInfoEnabled()) log.info(sm.getString("hostConfig.deployJar", file));

    try {
      Context context = null;
      if (deployXML && xml.exists()) {
        synchronized (digester) {
          try {
            context = (Context) digester.parse(xml);
            if (context == null) {
              log.error(sm.getString("hostConfig.deployDescriptor.error", file));
              return;
            }
          } finally {
            digester.reset();
          }
        }
        context.setConfigFile(xml.getAbsolutePath());
      } else {
        context = (Context) Class.forName(contextClass).newInstance();
      }

      // Populate redeploy resources with the WAR file
      deployedApp.redeployResources.put(war.getAbsolutePath(), new Long(war.lastModified()));

      if (deployXML && xml.exists()) {
        deployedApp.redeployResources.put(xml.getAbsolutePath(), new Long(xml.lastModified()));
      }

      if (context instanceof Lifecycle) {
        Class clazz = Class.forName(host.getConfigClass());
        LifecycleListener listener = (LifecycleListener) clazz.newInstance();
        ((Lifecycle) context).addLifecycleListener(listener);
      }
      context.setPath(contextPath);
      context.setDocBase(file);
      host.addChild(context);
      // If we're unpacking WARs, the docBase will be mutated after
      // starting the context
      if (unpackWARs && (context.getDocBase() != null)) {
        String name = null;
        String path = context.getPath();
        if (path.equals("")) {
          name = "ROOT";
        } else {
          if (path.startsWith("/")) {
            name = path.substring(1);
          } else {
            name = path;
          }
        }
        name = name.replace('/', '#');
        File docBase = new File(name);
        if (!docBase.isAbsolute()) {
          docBase = new File(appBase(), name);
        }
        deployedApp.redeployResources.put(
            docBase.getAbsolutePath(), new Long(docBase.lastModified()));
        addWatchedResources(deployedApp, docBase.getAbsolutePath(), context);
      } else {
        addWatchedResources(deployedApp, null, context);
      }
    } catch (Throwable t) {
      log.error(sm.getString("hostConfig.deployJar.error", file), t);
    }

    deployed.put(contextPath, deployedApp);
  }
Esempio n. 15
0
  /**
   * @param contextPath
   * @param contextXml
   * @param file
   */
  protected void deployDescriptor(String contextPath, File contextXml, String file) {
    if (deploymentExists(contextPath)) {
      return;
    }

    DeployedApplication deployedApp = new DeployedApplication(contextPath);

    // Assume this is a configuration descriptor and deploy it
    if (log.isInfoEnabled()) {
      log.info(sm.getString("hostConfig.deployDescriptor", file));
    }

    Context context = null;
    try {
      synchronized (digester) {
        try {
          context = (Context) digester.parse(contextXml);
          if (context == null) {
            log.error(sm.getString("hostConfig.deployDescriptor.error", file));
            return;
          }
        } finally {
          digester.reset();
        }
      }
      if (context instanceof Lifecycle) {
        Class clazz = Class.forName(host.getConfigClass());
        LifecycleListener listener = (LifecycleListener) clazz.newInstance();
        ((Lifecycle) context).addLifecycleListener(listener);
      }
      context.setConfigFile(contextXml.getAbsolutePath());
      context.setPath(contextPath);
      // Add the associated docBase to the redeployed list if it's a WAR
      boolean isExternalWar = false;
      boolean isExternal = false;
      if (context.getDocBase() != null) {
        File docBase = new File(context.getDocBase());
        if (!docBase.isAbsolute()) {
          docBase = new File(appBase(), context.getDocBase());
        }
        // If external docBase, register .xml as redeploy first
        if (!docBase.getCanonicalPath().startsWith(appBase().getAbsolutePath() + File.separator)) {
          isExternal = true;
          deployedApp.redeployResources.put(
              contextXml.getAbsolutePath(), new Long(contextXml.lastModified()));
          deployedApp.redeployResources.put(
              docBase.getAbsolutePath(), new Long(docBase.lastModified()));
          if (docBase.getAbsolutePath().toLowerCase().endsWith(".war")) {
            isExternalWar = true;
          }
        } else {
          log.warn(sm.getString("hostConfig.deployDescriptor.localDocBaseSpecified", docBase));
          // Ignore specified docBase
          context.setDocBase(null);
        }
      }
      host.addChild(context);
      // Get paths for WAR and expanded WAR in appBase
      String name = null;
      String path = context.getPath();
      if (path.equals("")) {
        name = "ROOT";
      } else {
        if (path.startsWith("/")) {
          name = path.substring(1);
        } else {
          name = path;
        }
      }
      File expandedDocBase = new File(appBase(), name);
      if (context.getDocBase() != null) {
        // first assume docBase is absolute
        expandedDocBase = new File(context.getDocBase());
        if (!expandedDocBase.isAbsolute()) {
          // if docBase specified and relative, it must be relative to appBase
          expandedDocBase = new File(appBase(), context.getDocBase());
        }
      }
      // Add the eventual unpacked WAR and all the resources which will be
      // watched inside it
      if (isExternalWar && unpackWARs) {
        deployedApp.redeployResources.put(
            expandedDocBase.getAbsolutePath(), new Long(expandedDocBase.lastModified()));
        deployedApp.redeployResources.put(
            contextXml.getAbsolutePath(), new Long(contextXml.lastModified()));
        addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context);
      } else {
        // Find an existing matching war and expanded folder
        if (!isExternal) {
          File warDocBase = new File(expandedDocBase.getAbsolutePath() + ".war");
          if (warDocBase.exists()) {
            deployedApp.redeployResources.put(
                warDocBase.getAbsolutePath(), new Long(warDocBase.lastModified()));
          }
        }
        if (expandedDocBase.exists()) {
          deployedApp.redeployResources.put(
              expandedDocBase.getAbsolutePath(), new Long(expandedDocBase.lastModified()));
          addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context);
        } else {
          addWatchedResources(deployedApp, null, context);
        }
        // Add the context XML to the list of files which should trigger a redeployment
        if (!isExternal) {
          deployedApp.redeployResources.put(
              contextXml.getAbsolutePath(), new Long(contextXml.lastModified()));
        }
      }
    } catch (Throwable t) {
      log.error(sm.getString("hostConfig.deployDescriptor.error", file), t);
    }

    if (context != null && host.findChild(context.getName()) != null) {
      deployed.put(contextPath, deployedApp);
    }
  }
Esempio n. 16
0
  public void stopServer(String[] arguments) {

    if (arguments != null) {
      arguments(arguments);
    }

    Server s = getServer();
    if (s == null) {
      // Create and execute our Digester
      Digester digester = createStopDigester();
      File file = configFile();
      FileInputStream fis = null;
      try {
        InputSource is = new InputSource(file.toURI().toURL().toString());
        fis = new FileInputStream(file);
        is.setByteStream(fis);
        digester.push(this);
        digester.parse(is);
      } catch (Exception e) {
        log.error("Catalina.stop: ", e);
        System.exit(1);
      } finally {
        if (fis != null) {
          try {
            fis.close();
          } catch (IOException e) {
            // Ignore
          }
        }
      }
    } else {
      // Server object already present. Must be running as a service
      try {
        s.stop();
      } catch (LifecycleException e) {
        log.error("Catalina.stop: ", e);
      }
      return;
    }

    // Stop the existing server
    s = getServer();
    if (s.getPort() > 0) {
      Socket socket = null;
      OutputStream stream = null;
      try {
        socket = new Socket(s.getAddress(), s.getPort());
        stream = socket.getOutputStream();
        String shutdown = s.getShutdown();
        for (int i = 0; i < shutdown.length(); i++) {
          stream.write(shutdown.charAt(i));
        }
        stream.flush();
      } catch (ConnectException ce) {
        log.error(
            sm.getString(
                "catalina.stopServer.connectException",
                s.getAddress(),
                String.valueOf(s.getPort())));
        log.error("Catalina.stop: ", ce);
        System.exit(1);
      } catch (IOException e) {
        log.error("Catalina.stop: ", e);
        System.exit(1);
      } finally {
        if (stream != null) {
          try {
            stream.close();
          } catch (IOException e) {
            // Ignore
          }
        }
        if (socket != null) {
          try {
            socket.close();
          } catch (IOException e) {
            // Ignore
          }
        }
      }
    } else {
      log.error(sm.getString("catalina.stopServer"));
      System.exit(1);
    }
  }
Esempio n. 17
0
  /** Start a new server instance. */
  public void load() {

    long t1 = System.nanoTime();

    initDirs();

    // Before digester - it may be needed

    initNaming();

    // Create and execute our Digester
    Digester digester = createStartDigester();

    InputSource inputSource = null;
    InputStream inputStream = null;
    File file = null;
    try {
      file = configFile();
      inputStream = new FileInputStream(file);
      inputSource = new InputSource(file.toURI().toURL().toString());
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.debug(sm.getString("catalina.configFail", file), e);
      }
    }
    if (inputStream == null) {
      try {
        inputStream = getClass().getClassLoader().getResourceAsStream(getConfigFile());
        inputSource =
            new InputSource(getClass().getClassLoader().getResource(getConfigFile()).toString());
      } catch (Exception e) {
        if (log.isDebugEnabled()) {
          log.debug(sm.getString("catalina.configFail", getConfigFile()), e);
        }
      }
    }

    // This should be included in catalina.jar
    // Alternative: don't bother with xml, just create it manually.
    if (inputStream == null) {
      try {
        inputStream = getClass().getClassLoader().getResourceAsStream("server-embed.xml");
        inputSource =
            new InputSource(getClass().getClassLoader().getResource("server-embed.xml").toString());
      } catch (Exception e) {
        if (log.isDebugEnabled()) {
          log.debug(sm.getString("catalina.configFail", "server-embed.xml"), e);
        }
      }
    }

    if (inputStream == null || inputSource == null) {
      if (file == null) {
        log.warn(sm.getString("catalina.configFail", getConfigFile() + "] or [server-embed.xml]"));
      } else {
        log.warn(sm.getString("catalina.configFail", file.getAbsolutePath()));
        if (file.exists() && !file.canRead()) {
          log.warn("Permissions incorrect, read permission is not allowed on the file.");
        }
      }
      return;
    }

    try {
      inputSource.setByteStream(inputStream);
      digester.push(this);
      digester.parse(inputSource);
    } catch (SAXParseException spe) {
      log.warn("Catalina.start using " + getConfigFile() + ": " + spe.getMessage());
      return;
    } catch (Exception e) {
      log.warn("Catalina.start using " + getConfigFile() + ": ", e);
      return;
    } finally {
      try {
        inputStream.close();
      } catch (IOException e) {
        // Ignore
      }
    }

    getServer().setCatalina(this);

    // Stream redirection
    initStreams();

    // Start the new server
    try {
      getServer().init();
    } catch (LifecycleException e) {
      if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) {
        throw new java.lang.Error(e);
      } else {
        log.error("Catalina.start", e);
      }
    }

    long t2 = System.nanoTime();
    if (log.isInfoEnabled()) {
      log.info("Initialization processed in " + ((t2 - t1) / 1000000) + " ms");
    }
  }
  public void ReadGlobalMessages() {

    Digester digester = new Digester();

    final MessagePool pool = MessagePool.getInstance();

    XMLReader reader;

    try {
      reader = digester.getXMLReader();
      reader.setContentHandler(
          new ContentHandler() {
            String key = "";
            Message message;

            public void startPrefixMapping(String prefix, String uri) throws SAXException {
              // TODO Auto-generated method stub

            }

            public void startElement(String uri, String localName, String qName, Attributes atts)
                throws SAXException {
              if (qName.equals("message")) {
                message = new Message();
                key = atts.getValue("key");
              } else if (qName.equals("property")) {
                message.putMessage(atts.getValue("name"), atts.getValue("value"));
              }
            }

            public void startDocument() throws SAXException {
              // TODO Auto-generated method stub

            }

            public void skippedEntity(String name) throws SAXException {
              // TODO Auto-generated method stub

            }

            public void setDocumentLocator(Locator locator) {
              // TODO Auto-generated method stub

            }

            public void processingInstruction(String target, String data) throws SAXException {
              // TODO Auto-generated method stub

            }

            public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
              // TODO Auto-generated method stub

            }

            public void endPrefixMapping(String prefix) throws SAXException {
              // TODO Auto-generated method stub

            }

            public void endElement(String uri, String localName, String qName) throws SAXException {
              if (qName.equals("message")) {
                pool.putKey(key, message);
              }
            }

            public void endDocument() throws SAXException {
              // TODO Auto-generated method stub

            }

            public void characters(char[] ch, int start, int length) throws SAXException {
              // TODO Auto-generated method stub

            }
          });
      File file = new File("messages.xml");
      InputStream stream = new FileInputStream(file);
      reader.parse(new InputSource(stream));
    } catch (SAXException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }