Esempio n. 1
0
  /**
   * Add a new Service to the set of defined Services.
   *
   * @param service The Service to be added
   */
  public void addService(Service service) {

    service.setServer(this);

    synchronized (services) {
      Service results[] = new Service[services.length + 1];
      System.arraycopy(services, 0, results, 0, services.length);
      results[services.length] = service;
      services = results;

      if (initialized) {
        try {
          service.initialize();
        } catch (LifecycleException e) {
          log.error(e);
        }
      }

      if (started && (service instanceof Lifecycle)) {
        try {
          ((Lifecycle) service).start();
        } catch (LifecycleException e) {;
        }
      }

      // Report this property change to interested listeners
      support.firePropertyChange("service", null, service);
    }
  }
 public void registerListenersForServer(Server server) throws RemoteException, RemoteException {
   for (Service service : server.findServices()) {
     Engine engine = (Engine) service.getContainer();
     engine.addContainerListener(this);
     registerListenersForEngine(engine);
   }
 }
  /**
   * Updates each ThreadPoolExecutor with the current time, which is the time when a context is
   * being stopped.
   *
   * @param context the context being stopped, used to discover all the Connectors of its parent
   *     Service.
   */
  public void stopIdleThreads(Context context) throws RemoteException, RemoteException {
    if (serverStopping) return;

    if (!(context instanceof StandardContextRemoteInterface)
        || !((StandardContextRemoteInterface) context).getRenewThreadsWhenStoppingContext()) {
      log.debug(
          "Not renewing threads when the context is stopping. " + "It is not configured to do it.");
      return;
    }

    Engine engine = (Engine) context.getParent().getParent();
    Service service = engine.getService();
    ConnectorRemoteInterface[] connectors = service.findConnectors();
    if (connectors != null) {
      for (ConnectorRemoteInterface connector : connectors) {
        ProtocolHandler handler = connector.getProtocolHandler();
        Executor executor = null;
        if (handler != null) {
          executor = handler.getExecutor();
        }

        if (executor instanceof ThreadPoolExecutor2RemoteInterface) {
          ThreadPoolExecutor2RemoteInterface threadPoolExecutor =
              (ThreadPoolExecutor2RemoteInterface) executor;
          threadPoolExecutor.contextStopping();
        } else if (executor instanceof StandardThreadExecutorRemoteInterface) {
          StandardThreadExecutorRemoteInterface stdThreadExecutor =
              (StandardThreadExecutorRemoteInterface) executor;
          stdThreadExecutor.contextStopping();
        }
      }
    }
  }
 private void removeServiceConnectors() {
   for (Service service : this.tomcat.getServer().findServices()) {
     Connector[] connectors = service.findConnectors().clone();
     this.serviceConnectors.put(service, connectors);
     for (Connector connector : connectors) {
       service.removeConnector(connector);
     }
   }
 }
Esempio n. 5
0
  /**
   * Process the beginning of this element.
   *
   * @param namespace the namespace URI of the matching element, or an empty string if the parser is
   *     not namespace aware or the element has no namespace
   * @param name the local name if the parser is namespace aware, or just the element name otherwise
   * @param attributes The attribute list for this element
   */
  @Override
  public void begin(String namespace, String name, Attributes attributes) throws Exception {
    Service svc = (Service) digester.peek();
    Executor ex = null;
    if (attributes.getValue("executor") != null) {
      ex = svc.getExecutor(attributes.getValue("executor"));
    }
    Connector con = new Connector(attributes.getValue("protocol"));
    if (ex != null) _setExecutor(con, ex);

    digester.push(con);
  }
  private String internalPickPort() {

    Service catalinaService = ServerFactory.getServer().findService("Catalina");
    for (Connector connector : catalinaService.findConnectors()) {
      if (connector.getProtocol().equals("HTTP/1.1")) {
        return new Integer(connector.getPort()).toString();
      }
    }

    throw new UnsupportedOperationException(
        "WSAT has test againest Tomcat 6.0, Please change to it.");
  }
 private void addPreviouslyRemovedConnectors() {
   Service[] services = this.tomcat.getServer().findServices();
   for (Service service : services) {
     Connector[] connectors = this.serviceConnectors.get(service);
     if (connectors != null) {
       for (Connector connector : connectors) {
         service.addConnector(connector);
         if (!this.autoStart) {
           stopProtocolHandler(connector);
         }
       }
       this.serviceConnectors.remove(service);
     }
   }
 }
 /**
  * Return the Server object that is the ultimate parent for the container with which this Realm is
  * associated. If the server cannot be found (eg because the container hierarchy is not complete),
  * <code>null</code> is returned.
  */
 protected Server getServer() {
   Container c = container;
   if (c instanceof Context) {
     c = c.getParent();
   }
   if (c instanceof Host) {
     c = c.getParent();
   }
   if (c instanceof Engine) {
     Service s = ((Engine) c).getService();
     if (s != null) {
       return s.getServer();
     }
   }
   return null;
 }
Esempio n. 9
0
  /**
   * Create an <code>ObjectName</code> for this <code>Service</code> object.
   *
   * @param domain Domain in which this name is to be created
   * @param service The Service to be named
   * @exception MalformedObjectNameException if a name cannot be created
   */
  static ObjectName createObjectName(String domain, Service service)
      throws MalformedObjectNameException {

    ObjectName name = null;
    name = new ObjectName(domain + ":type=Service,serviceName=" + service.getName());
    return (name);
  }
Esempio n. 10
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();
 }
  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)"));
  }
Esempio n. 12
0
 /** Access to the engine, for further customization. */
 public Engine getEngine() {
   if (engine == null) {
     getServer();
     engine = new StandardEngine();
     engine.setName("Tomcat");
     engine.setDefaultHost(hostname);
     if (defaultRealm == null) {
       initSimpleAuth();
     }
     engine.setRealm(defaultRealm);
     service.setContainer(engine);
   }
   return engine;
 }
Esempio n. 13
0
  /**
   * Get the default http connector. You can set more parameters - the port is already initialized.
   *
   * <p>Alternatively, you can construct a Connector and set any params, then call
   * addConnector(Connector)
   *
   * @return A connector object that can be customized
   */
  public Connector getConnector() {
    getServer();
    if (connector != null) {
      return connector;
    }
    // This will load Apr connector if available,
    // default to nio. I'm having strange problems with apr
    // XXX: jfclere weird... Don't add the AprLifecycleListener then.
    // and for the use case the speed benefit wouldn't matter.

    connector = new Connector("HTTP/1.1");
    // connector = new Connector("org.apache.coyote.http11.Http11Protocol");
    connector.setPort(port);
    service.addConnector(connector);
    return connector;
  }
Esempio n. 14
0
  /**
   * 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;
  }
Esempio n. 15
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);
      }
    }
  }
Esempio n. 16
0
  /**
   * Start the instance using the ports provided
   *
   * @param port the http port to use
   * @param securePort the secure https port to use
   */
  @SuppressWarnings("unchecked")
  public T start(final Integer port, final Integer securePort) {
    if (port == null && securePort == null)
      throw new IllegalStateException("You must specify a port or a secure port");
    if (isRunning()) throw new IllegalStateException("Server already running");
    final String startedMessage =
        "Started "
            + this.getClass().getSimpleName().replace("Runner", "")
            + " listening on:"
            + (port != null ? " standard port " + port : "")
            + (securePort != null ? " secure port " + securePort : "");

    try {
      String servletContext = "";

      tomcat = new Tomcat();
      tomcat.setBaseDir(
          new File(".").getCanonicalPath()
              + File.separatorChar
              + "tomcat"
              + (servletContext.length() > 0 ? "_" + servletContext : ""));

      // add http port
      tomcat.setPort(port != null ? port : securePort);

      if (securePort != null) {
        // add https connector
        SSLFactory.buildKeyStore();
        Connector httpsConnector = new Connector();
        httpsConnector.setPort(securePort);
        httpsConnector.setSecure(true);
        httpsConnector.setAttribute("keyAlias", SSLFactory.KEY_STORE_ALIAS);
        httpsConnector.setAttribute("keystorePass", SSLFactory.KEY_STORE_PASSWORD);
        logger.trace(
            "Loading key store from file ["
                + new File(SSLFactory.KEY_STORE_FILENAME).getAbsoluteFile()
                + "]");
        httpsConnector.setAttribute(
            "keystoreFile", new File(SSLFactory.KEY_STORE_FILENAME).getAbsoluteFile());
        httpsConnector.setAttribute("clientAuth", "false");
        httpsConnector.setAttribute("sslProtocol", "TLS");
        httpsConnector.setAttribute("SSLEnabled", true);

        Service service = tomcat.getService();
        service.addConnector(httpsConnector);

        Connector defaultConnector = tomcat.getConnector();
        defaultConnector.setRedirectPort(securePort);
      }

      // add servlet
      Context ctx = tomcat.addContext("/" + servletContext, new File(".").getAbsolutePath());
      tomcat.addServlet("/" + servletContext, "mockServerServlet", getServlet());
      ctx.addServletMapping("/*", "mockServerServlet");

      // start server
      tomcat.start();

      // create and start shutdown thread
      shutdownThread = new ShutdownThread(stopPort(port, securePort));
      shutdownThread.start();
      serverStarted(port, securePort);

      logger.info(startedMessage);
      System.out.println(startedMessage);

      join();
    } catch (Throwable t) {
      logger.error("Exception while starting server", t);
    }

    return (T) this;
  }
Esempio n. 17
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());
  }