/**
   * Creates a single webapp configuration to be run in Tomcat.
   *
   * @param contextName the context name without leading slash, for example, "openmrs"
   * @param port the port at which to run tomcat.
   */
  public TomcatManager(String contextName, int port) {

    // create server
    container = new Embedded();
    container.setCatalinaHome("tomcat");

    // create context
    Context rootContext = container.createContext("/" + contextName, contextName);
    rootContext.setReloadable(true);

    // create host
    Host localHost = container.createHost("localhost", "webapps");
    localHost.addChild(rootContext);

    // create engine
    Engine engine = container.createEngine();
    engine.setName("Catalina");
    engine.addChild(localHost);
    engine.setDefaultHost(localHost.getName());
    container.addEngine(engine);

    // create http connector
    Connector httpConnector = container.createConnector((InetAddress) null, port, false);
    container.addConnector(httpConnector);
  }
 /** {@inheritDoc} */
 public String getJvmRoute() {
   if (jvmRoute_ == null) {
     Engine e = getEngine();
     jvmRoute_ = (e == null ? null : e.getJvmRoute());
   }
   return jvmRoute_;
 }
  /**
   * 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();
        }
      }
    }
  }
 public void registerListenersForServer(Server server) throws RemoteException, RemoteException {
   for (Service service : server.findServices()) {
     Engine engine = (Engine) service.getContainer();
     engine.addContainerListener(this);
     registerListenersForEngine(engine);
   }
 }
  private void initServer() throws Exception {
    // point catalina at the provided home directory
    server = new Embedded();
    server.setCatalinaHome(catalinaHome.getAbsolutePath());

    Engine engine = server.createEngine();
    engine.setName("embedded");
    server.addEngine(engine);

    host = server.createHost("localhost", new File(catalinaHome, "webapps").getAbsolutePath());
    engine.addChild(host);
    engine.setDefaultHost(host.getName());

    // bind to an available port
    httpConnector = new EmbeddedConnector();
    server.addConnector(httpConnector);

    // disable session persistence on restart
    sessions = new MemoryStore();
    sessionManager = new PersistentManager();
    sessionManager.setDistributable(false);
    sessionManager.setSaveOnRestart(false);
    sessionManager.setStore(sessions);

    Context root = server.createContext("", new File(catalinaHome, "conf").getAbsolutePath());
    root.setManager(sessionManager);
    host.addChild(root);
  }
  @BeforeClass(alwaysRun = true)
  public void setUpGlobal() throws Exception {

    port1 = findFreePort();
    embedded = new Embedded();
    String path = new File(".").getAbsolutePath();
    embedded.setCatalinaHome(path);

    Engine engine = embedded.createEngine();
    engine.setDefaultHost("127.0.0.1");

    Host host = embedded.createHost("127.0.0.1", path);
    engine.addChild(host);

    Context c = embedded.createContext("/", path);
    c.setReloadable(false);
    Wrapper w = c.createWrapper();
    w.addMapping("/*");
    w.setServletClass(org.apache.catalina.servlets.WebdavServlet.class.getName());
    w.addInitParameter("readonly", "false");
    w.addInitParameter("listings", "true");

    w.setLoadOnStartup(0);

    c.addChild(w);
    host.addChild(c);

    Connector connector =
        embedded.createConnector("127.0.0.1", port1, Http11NioProtocol.class.getName());
    connector.setContainer(host);
    embedded.addEngine(engine);
    embedded.addConnector(connector);
    embedded.start();
  }
 private void addInstanceIdToEngineName() {
   int instanceId = containerCounter.incrementAndGet();
   if (instanceId > 0) {
     Engine engine = this.tomcat.getEngine();
     engine.setName(engine.getName() + "-" + instanceId);
   }
 }
 /**
  * Doing the start, stop, reload and lazy unload of webapps inside all hosts respectively when
  * getting request.
  *
  * @param nameOfOperation the operation to be performed in oder to hot update the host
  * @throws CarbonException if errors occurs when hot update the host
  */
 private void handleHotUpdateToHost(String nameOfOperation) throws CarbonException {
   if (DataHolder.getHotUpdateService() != null) {
     List<String> mappings =
         URLMappingHolder.getInstance().getUrlMappingsPerApplication(this.context.getName());
     Engine engine = DataHolder.getCarbonTomcatService().getTomcat().getEngine();
     Context hostContext;
     Host host;
     for (String hostName : mappings) {
       host = (Host) engine.findChild(hostName);
       if (host != null) {
         hostContext = (Context) host.findChild("/");
         if (hostContext != null) {
           if (nameOfOperation.equalsIgnoreCase("start")) {
             start(hostContext);
           } else if (nameOfOperation.equalsIgnoreCase("stop")) {
             stop(hostContext);
           } else if (nameOfOperation.equalsIgnoreCase("reload")) {
             reload(hostContext);
           } else if (nameOfOperation.equalsIgnoreCase("lazyunload")) {
             lazyUnload(hostContext);
             DataHolder.getHotUpdateService().removeHost(hostName);
           } else if (nameOfOperation.equalsIgnoreCase("delete")) {
             DataHolder.getHotUpdateService().deleteHost(hostName);
           }
         }
       }
     }
   }
 }
Exemple #9
0
 public static void setupContainer(String warName, String jvmRoute, Manager mgr) {
   Engine engine = new MockEngine();
   engine.setName(JVM_ROUTE_CACHE_NAME);
   engine.setJvmRoute(jvmRoute);
   Host host = new MockHost();
   host.setName("localhost");
   engine.addChild(host);
   StandardContext context = new StandardContext();
   context.setName(warName);
   context.setDomain(jvmRoute);
   host.addChild(context);
   context.setManager(mgr);
 }
Exemple #10
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;
 }
 public void registerListenersForEngine(Engine engine) throws RemoteException, RemoteException {
   for (Container hostContainer : engine.findChildren()) {
     Host host = (Host) hostContainer;
     host.addContainerListener(this);
     registerListenersForHost(host);
   }
 }
  public EmbeddedTomcat(String contextPath, int port, String jvmRoute)
      throws MalformedURLException {
    this.contextPath = contextPath;
    this.port = port;

    // create server
    container = new Embedded();
    container.setCatalinaHome(catalinaHome);
    // Not really necessasry, but let's still do it...
    container.setRealm(new MemoryRealm());

    // create webapp loader
    WebappLoader loader = new WebappLoader(this.getClass().getClassLoader());
    if (classesDir != null) {
      loader.addRepository(new File(classesDir).toURI().toURL().toString());
    }

    rootContext = container.createContext("", webappDir);
    rootContext.setLoader(loader);
    rootContext.setReloadable(true);
    // Otherwise we get NPE when instantiating servlets
    rootContext.setIgnoreAnnotations(true);

    // create host
    Host localHost = container.createHost("127.0.0.1", new File("").getAbsolutePath());
    localHost.addChild(rootContext);

    localHost.setDeployOnStartup(true);

    // create engine
    engine = container.createEngine();
    engine.setName("localEngine");
    engine.addChild(localHost);
    engine.setDefaultHost(localHost.getName());
    engine.setJvmRoute(jvmRoute);
    engine.setService(new StandardService());
    container.addEngine(engine);

    // create http connector
    Connector httpConnector = container.createConnector((InetAddress) null, port, false);
    container.addConnector(httpConnector);
    container.setAwait(true);

    // Create the JVMRoute valve for session failover
    ValveBase valve = new JvmRouteBinderValve();
    ((StandardEngine) engine).addValve(valve);
  }
  protected Realm getRealm(HttpServletRequest request) {
    String serverName = request.getServerName();
    String contextPath = request.getContextPath();

    Host host = (Host) engine.findChild(serverName);
    if (host == null) {
      // if it cannot find host, then use the default host.
      host = (Host) engine.findChild(engine.getDefaultHost());
      if (host == null)
        throw new NullPointerException(
            "Could not find Tomcat host for: " + serverName + " or: " + engine.getDefaultHost());
    }
    Context context = (Context) host.findChild(contextPath);
    if (context == null)
      throw new NullPointerException("Could not find Tomcat context for: " + contextPath);
    Realm realm = context.getRealm();
    if (realm == null)
      throw new NullPointerException(
          "Could not find Tomcat realm for: " + serverName + "" + contextPath);

    return realm;
  }
 /**
  * Retrieve the JvmRoute for the enclosing Engine.
  *
  * @return the JvmRoute or null.
  */
 public String getJvmRoute() {
   Engine e = getEngine();
   return e == null ? null : e.getJvmRoute();
 }
  private void bootstrap(String catalinaHome, String webRoot, int port, String address)
      throws LifecycleException {
    Engine engine = null;

    // Create an embedded server
    this.embedded = new Embedded();
    this.embedded.setUseNaming(false);
    this.embedded.setCatalinaHome(catalinaHome);
    // set the memory realm
    MemoryRealm memRealm = new MemoryRealm();
    this.embedded.setRealm(memRealm);

    engine = this.embedded.createEngine();
    engine.setDefaultHost("localhost");

    // Create a default virtual host
    File tempHost = null;

    try {
      tempHost = File.createTempFile("empty", "");
      tempHost.mkdirs();
      log.debug("Embbed Host Root:" + tempHost.getAbsolutePath());
    } catch (IOException e) {
      tempHost = new File(".");
      log.warn(e, e);
    }
    this.host = this.embedded.createHost("localhost", tempHost.getAbsolutePath());
    engine.addChild(this.host);

    // Create the ROOT context
    this.rootcontext = this.embedded.createContext("", webRoot);

    this.rootcontext.addApplicationListener(SiteLoader.class.getName());
    this.rootcontext.setPrivileged(true);
    this.rootcontext.setReloadable(false);
    this.rootcontext.addWelcomeFile("index.jsp");
    this.host.addChild(this.rootcontext);

    // Install the assembled container hierarchy
    this.embedded.addEngine(engine);
    // String addr = null;
    connector = this.embedded.createConnector(address, port, false);
    if (connector == null) {
      /*
       * embedded.createConnector(...)
       * seems to be broken.. it always returns a null connector.
       * see work around below
       */
      try {
        connector = new Connector();
        // httpConnector.setScheme("http");
        connector.setSecure(false);
        // address = InetAddress.getLocalHost();
        IntrospectionUtils.setProperty(connector, "address", "" + address);
        IntrospectionUtils.setProperty(connector, "port", "" + port);

      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
    connector.setEnableLookups(false);
    this.embedded.addConnector(connector);

    // Start the embedded server
    this.embedded.start();
  }
  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);
      }
    }
  }