コード例 #1
0
  public void setServer(Server server) {
    Service[] findServices = server.findServices();
    for (Service service : findServices) {
      Service existingService = getServer().findService(service.getName());
      if (existingService != null) {
        for (Connector connector : service.findConnectors()) {
          existingService.addConnector(connector);
        }
        for (Executor executor : service.findExecutors()) {
          existingService.addExecutor(executor);
        }
        for (LifecycleListener lifecycleListener : service.findLifecycleListeners()) {
          existingService.addLifecycleListener(lifecycleListener);
        }
        existingService.getContainer().setRealm(service.getContainer().getRealm());
        existingService
            .getContainer()
            .setBackgroundProcessorDelay(service.getContainer().getBackgroundProcessorDelay());
        existingService.getContainer().setCluster(service.getContainer().getCluster());
        // existingService.getContainer().setResources(
        // service.getContainer().getResources());
      } else {
        getServer().addService(service);
      }
    }
    this.setHostname(server.getAddress());

    this.setPort(server.getPort());
  }
コード例 #2
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();
      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);
    }
  }
 public void registerListenersForServer(Server server) throws RemoteException, RemoteException {
   for (Service service : server.findServices()) {
     Engine engine = (Engine) service.getContainer();
     engine.addContainerListener(this);
     registerListenersForEngine(engine);
   }
 }
コード例 #4
0
ファイル: Tomcat.java プロジェクト: anoopgecbh/Tomcat-4
  /**
   * Enables JNDI naming which is disabled by default. Server must implement {@link Lifecycle} in
   * order for the {@link NamingContextListener} to be used.
   */
  public void enableNaming() {
    // Make sure getServer() has been called as that is where naming is
    // disabled
    getServer();
    server.addLifecycleListener(new NamingContextListener());

    System.setProperty("catalina.useNaming", "true");

    String value = "org.apache.naming";
    String oldValue = System.getProperty(javax.naming.Context.URL_PKG_PREFIXES);
    if (oldValue != null) {
      if (oldValue.contains(value)) {
        value = oldValue;
      } else {
        value = value + ":" + oldValue;
      }
    }
    System.setProperty(javax.naming.Context.URL_PKG_PREFIXES, value);

    value = System.getProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY);
    if (value == null) {
      System.setProperty(
          javax.naming.Context.INITIAL_CONTEXT_FACTORY,
          "org.apache.naming.java.javaURLContextFactory");
    }
  }
コード例 #5
0
ファイル: Tomcat.java プロジェクト: anoopgecbh/Tomcat-4
  /**
   * Get the server object. You can add listeners and few more customizations. JNDI is disabled by
   * default.
   */
  public Server getServer() {

    if (server != null) {
      return server;
    }

    initBaseDir();

    System.setProperty("catalina.useNaming", "false");

    server = new StandardServer();
    server.setPort(-1);

    service = new StandardService();
    service.setName("Tomcat");
    server.addService(service);
    return server;
  }
コード例 #6
0
 @Override
 public void start() throws LifecycleException {
   // Use fast, insecure session ID generation for all tests
   Server server = getServer();
   for (Service service : server.findServices()) {
     Container e = service.getContainer();
     for (Container h : e.findChildren()) {
       for (Container c : h.findChildren()) {
         StandardManager m = (StandardManager) c.getManager();
         if (m == null) {
           m = new StandardManager();
           m.setSecureRandomClass("org.apache.catalina.startup.FastNonSecureRandom");
           c.setManager(m);
         }
       }
     }
   }
   super.start();
 }
コード例 #7
0
  public void configure(Map<String, String> params) {
    String serviceId = params.get("service");

    Server server = ServerFactory.getServer();
    if (server == null) throw new NullPointerException("Could not get Tomcat server");

    Service service = null;
    if (serviceId != null) service = server.findService(serviceId);
    else {
      Service[] services = server.findServices();
      if (services != null && services.length > 0) service = services[0];
    }
    if (service == null)
      throw new NullPointerException(
          "Could not find Tomcat service for: " + (serviceId != null ? serviceId : "(default)"));

    engine = (Engine) service.getContainer();
    if (engine == null)
      throw new NullPointerException(
          "Could not find Tomcat container for: " + (serviceId != null ? serviceId : "(default)"));
  }
コード例 #8
0
ファイル: Catalina.java プロジェクト: glorydom321/MyTomcat
  /** Stop an existing server instance. */
  public void stop() {

    try {
      // Remove the ShutdownHook first so that server.stop()
      // doesn't get invoked twice
      if (useShutdownHook) {
        Runtime.getRuntime().removeShutdownHook(shutdownHook);

        // If JULI is being used, re-enable JULI's shutdown to ensure
        // log messages are not lost
        LogManager logManager = LogManager.getLogManager();
        if (logManager instanceof ClassLoaderLogManager) {
          ((ClassLoaderLogManager) logManager).setUseShutdownHook(true);
        }
      }
    } catch (Throwable t) {
      ExceptionUtils.handleThrowable(t);
      // This will fail on JDK 1.2. Ignoring, as Tomcat can run
      // fine without the shutdown hook.
    }

    // Shut down the server
    try {
      Server s = getServer();
      LifecycleState state = s.getState();
      if (LifecycleState.STOPPING_PREP.compareTo(state) <= 0
          && LifecycleState.DESTROYED.compareTo(state) >= 0) {
        // Nothing to do. stop() was already called
      } else {
        s.stop();
        s.destroy();
      }
    } catch (LifecycleException e) {
      log.error("Catalina.stop", e);
    }
  }
コード例 #9
0
ファイル: Catalina.java プロジェクト: glorydom321/MyTomcat
  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);
    }
  }
コード例 #10
0
  private void start(boolean await) {

    // try to shutdown a previous Tomcat
    sendShutdownCommand();

    try {
      final ServerSocket srv = new ServerSocket(this.httpPort);
      srv.close();
    } catch (IOException e) {
      log.error("PORT " + this.httpPort + " ALREADY IN USE");
      return;
    }

    // Read a dummy value. This triggers loading of the catalina.properties
    // file
    CatalinaProperties.getProperty("dummy");

    appendSkipJars("tomcat.util.scan.DefaultJarScanner.jarsToSkip", this.skipJarsDefaultJarScanner);
    appendSkipJars(
        "org.apache.catalina.startup.ContextConfig.jarsToSkip", this.skipJarsContextConfig);
    appendSkipJars("org.apache.catalina.startup.TldConfig.jarsToSkip", this.skipJarsTldConfig);

    this.tomcat = new Tomcat();

    if (this.tempDirectory == null) {
      this.tempDirectory = new File(".", "/target/tomcat." + this.httpPort).getAbsolutePath();
    }

    this.tomcat.setBaseDir(this.tempDirectory);

    if (this.silent) {
      this.tomcat.setSilent(true);
    }

    if (this.addDefaultListeners) {
      this.tomcat.getServer().addLifecycleListener(new AprLifecycleListener());
    }

    if (this.useNio) {
      Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
      connector.setPort(this.httpPort);
      connector.setMaxPostSize(this.maxPostSize);
      connector.setURIEncoding("UTF-8");
      this.tomcat.setConnector(connector);
      this.tomcat.getService().addConnector(connector);
    } else {
      this.tomcat.setPort(this.httpPort);
      this.tomcat.getConnector().setURIEncoding("UTF-8");
      this.tomcat.getConnector().setMaxPostSize(this.maxPostSize);
    }

    if (this.compressionMinSize >= 0) {
      this.tomcat
          .getConnector()
          .setProperty("compression", String.valueOf(this.compressionMinSize));
      this.tomcat.getConnector().setProperty("compressableMimeType", this.compressableMimeType);
    }

    if (this.httpsPort != 0) {
      final Connector httpsConnector;
      if (this.useNio) {
        httpsConnector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
      } else {
        httpsConnector = new Connector("HTTP/1.1");
      }
      httpsConnector.setSecure(true);
      httpsConnector.setPort(this.httpsPort);
      httpsConnector.setMaxPostSize(this.maxPostSize);
      httpsConnector.setScheme("https");
      httpsConnector.setURIEncoding("UTF-8");

      httpsConnector.setProperty("SSLEnabled", "true");
      httpsConnector.setProperty("keyAlias", this.keyAlias);
      httpsConnector.setProperty("keystoreFile", this.keyStoreFile);
      httpsConnector.setProperty("keystorePass", this.keyStorePass);
      httpsConnector.setProperty("sslProtocol", this.sslProtocol);

      if (this.compressionMinSize >= 0) {
        httpsConnector.setProperty("compression", String.valueOf(this.compressionMinSize));
        httpsConnector.setProperty("compressableMimeType", this.compressableMimeType);
      }

      this.tomcat.getEngine().setDefaultHost("localhost");
      this.tomcat.getService().addConnector(httpsConnector);
    }

    if (this.shutdownPort != null) {
      this.tomcat.getServer().setPort(this.shutdownPort);
    }

    String contextDir = this.contextDirectory;
    if (contextDir == null) {
      contextDir = new File(".").getAbsolutePath() + "/src/main/webapp";
    }

    final Context ctx;
    try {

      if (!this.contextPath.equals("")) {
        File rootCtxDir = new File("./target/tcroot");
        if (!rootCtxDir.exists()) {
          rootCtxDir.mkdirs();
        }
        Context rootCtx = this.tomcat.addWebapp("", rootCtxDir.getAbsolutePath());
        rootCtx.setPrivileged(true);
        Tomcat.addServlet(rootCtx, "listContexts", new ListContextsServlet(rootCtx))
            .addMapping("/");
      }

      ctx = this.tomcat.addWebapp(this.contextPath, contextDir);
      ctx.setResources(new TargetClassesContext());
    } catch (ServletException e) {
      throw new RuntimeException(e);
    }

    if (this.privileged) {
      ctx.setPrivileged(true);
    }

    if (this.enableNaming
        || !this.contextEnvironments.isEmpty()
        || !this.contextResources.isEmpty()
        || this.contextFileURL != null) {
      this.tomcat.enableNaming();

      if (this.addDefaultListeners) {
        this.tomcat.getServer().addLifecycleListener(new GlobalResourcesLifecycleListener());
      }
    }

    if (this.addDefaultListeners) {
      Server server = this.tomcat.getServer();
      server.addLifecycleListener(new JasperListener());
      server.addLifecycleListener(new JreMemoryLeakPreventionListener());
      server.addLifecycleListener(new ThreadLocalLeakPreventionListener());
    }

    for (ContextEnvironment env : this.contextEnvironments) {
      ctx.getNamingResources().addEnvironment(env);
    }

    for (ContextResource res : this.contextResources) {
      ctx.getNamingResources().addResource(res);
    }

    for (ApplicationParameter param : this.contextInitializationParameters) {
      ctx.addApplicationParameter(param);
    }

    if (this.contextFileURL != null) {
      ctx.setConfigFile(this.contextFileURL);
    }

    // Shutdown tomcat if a failure occurs during startup
    ctx.addLifecycleListener(
        new LifecycleListener() {
          @Override
          public void lifecycleEvent(LifecycleEvent event) {
            if (event.getLifecycle().getState() == LifecycleState.FAILED) {
              ((StandardServer) EmbeddedTomcat.this.tomcat.getServer()).stopAwait();
            }
          }
        });

    try {
      this.tomcat.start();
    } catch (LifecycleException e) {
      throw new RuntimeException(e);
    }

    ((StandardManager) ctx.getManager()).setPathname(null);

    installSlf4jBridge();

    if (await) {
      this.tomcat.getServer().await();
      stop();
    }
  }
コード例 #11
0
ファイル: Tomcat.java プロジェクト: anoopgecbh/Tomcat-4
 /** Destroy the server. This object cannot be used once this method has been called. */
 public void destroy() throws LifecycleException {
   getServer();
   server.destroy();
   // Could null out objects here
 }
コード例 #12
0
ファイル: Tomcat.java プロジェクト: anoopgecbh/Tomcat-4
 /**
  * Stop the server.
  *
  * @throws LifecycleException
  */
 public void stop() throws LifecycleException {
   getServer();
   server.stop();
 }
コード例 #13
0
ファイル: Tomcat.java プロジェクト: anoopgecbh/Tomcat-4
 /**
  * Start the server.
  *
  * @throws LifecycleException
  */
 public void start() throws LifecycleException {
   getServer();
   getConnector();
   server.start();
 }
コード例 #14
0
  public static void main(String[] args) {

    System.setProperty("catalina.base", System.getProperty("user.dir"));
    Connector connector = new HttpConnector();

    Wrapper wrapper1 = new StandardWrapper();
    wrapper1.setName("Primitive");
    wrapper1.setServletClass("PrimitiveServlet");
    Wrapper wrapper2 = new StandardWrapper();
    wrapper2.setName("Modern");
    wrapper2.setServletClass("ModernServlet");

    Context context = new StandardContext();
    // StandardContext's start method adds a default mapper
    context.setPath("/app1");
    context.setDocBase("app1");

    context.addChild(wrapper1);
    context.addChild(wrapper2);

    LifecycleListener listener = new SimpleContextConfig();
    ((Lifecycle) context).addLifecycleListener(listener);

    Host host = new StandardHost();
    host.addChild(context);
    host.setName("localhost");
    host.setAppBase("webapps");

    Loader loader = new WebappLoader();
    context.setLoader(loader);
    // context.addServletMapping(pattern, name);
    context.addServletMapping("/Primitive", "Primitive");
    context.addServletMapping("/Modern", "Modern");

    Engine engine = new StandardEngine();
    engine.addChild(host);
    engine.setDefaultHost("localhost");

    Service service = new StandardService();
    service.setName("Stand-alone Service");
    Server server = new StandardServer();
    server.addService(service);
    service.addConnector(connector);

    // StandardService class's setContainer will call all its connector's setContainer method
    service.setContainer(engine);

    // Start the new server
    if (server instanceof Lifecycle) {
      try {
        server.initialize();
        ((Lifecycle) server).start();
        server.await();
        // the program waits until the await method returns,
        // i.e. until a shutdown command is received.
      } catch (LifecycleException e) {
        e.printStackTrace(System.out);
      }
    }

    // Shut down the server
    if (server instanceof Lifecycle) {
      try {
        ((Lifecycle) server).stop();
      } catch (LifecycleException e) {
        e.printStackTrace(System.out);
      }
    }
  }