org.apache.catalina.Host Java Examples

The following examples show how to use org.apache.catalina.Host. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Tomcat.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private String getLoggerName(Host host, String contextName) {
    if (host == null) {
        host = getHost();
    }
    StringBuilder loggerName = new StringBuilder();
    loggerName.append(ContainerBase.class.getName());
    loggerName.append(".[");
    // Engine name
    loggerName.append(host.getParent().getName());
    loggerName.append("].[");
    // Host name
    loggerName.append(host.getName());
    loggerName.append("].[");
    // Context name
    if (contextName == null || contextName.equals("")) {
        loggerName.append("/");
    } else if (contextName.startsWith("##")) {
        loggerName.append("/");
        loggerName.append(contextName);
    }
    loggerName.append(']');

    return loggerName.toString();
}
 
Example #2
Source File: RealmBase.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #3
Source File: TestHostConfigAutomaticDeployment.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
private static File getConfigBaseFile(Host host) {
    String path = null;
    if (host.getXmlBase() != null) {
        path = host.getXmlBase();
    } else {
        StringBuilder xmlDir = new StringBuilder("conf");
        Container parent = host.getParent();
        if (parent instanceof Engine) {
            xmlDir.append('/');
            xmlDir.append(parent.getName());
        }
        xmlDir.append('/');
        xmlDir.append(host.getName());
        path = xmlDir.toString();
    }
    
    return getCanonicalPath(path);
}
 
Example #4
Source File: MapperListener.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Register host.
 */
private void registerHost(Host host) {

    String[] aliases = host.findAliases();
    mapper.addHost(host.getName(), aliases, host);

    for (Container container : host.findChildren()) {
        if (container.getState().isAvailable()) {
            registerContext((Context) container);
        }
    }
    if(log.isDebugEnabled()) {
        log.debug(sm.getString("mapperListener.registerHost",
                host.getName(), domain, connector));
    }
}
 
Example #5
Source File: Tomcat.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * @param host The host in which the context will be deployed
 * @param contextPath The context mapping to use, "" for root context.
 * @param contextName The context name
 * @param dir Base directory for the context, for static files.
 *  Must exist, relative to the server home
 * @return the deployed context
 * @see #addContext(String, String)
 */
public Context addContext(Host host, String contextPath, String contextName,
        String dir) {
    silence(host, contextName);
    Context ctx = createContext(host, contextPath);
    ctx.setName(contextName);
    ctx.setPath(contextPath);
    ctx.setDocBase(dir);
    ctx.addLifecycleListener(new FixContextListener());

    if (host == null) {
        getHost().addChild(ctx);
    } else {
        host.addChild(ctx);
    }
    return ctx;
}
 
Example #6
Source File: StandardEngineValve.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Select the appropriate child Host to process this request,
 * based on the requested server name.  If no matching Host can
 * be found, return an appropriate HTTP error.
 *
 * @param request Request to be processed
 * @param response Response to be produced
 *
 * @exception IOException if an input/output error occurred
 * @exception ServletException if a servlet error occurred
 */
@Override
public final void invoke(Request request, Response response)
    throws IOException, ServletException {

    // Select the Host to be used for this Request
    Host host = request.getHost();
    if (host == null) {
        response.sendError
            (HttpServletResponse.SC_BAD_REQUEST,
             sm.getString("standardEngine.noHost", 
                          request.getServerName()));
        return;
    }
    if (request.isAsyncSupported()) {
        request.setAsyncSupported(host.getPipeline().isAsyncSupported());
    }

    // 责任链模式:将请求传递给 Host 管道
    // 从请求对象中取出该请求关联的Host(默认情况下是org.apache.catalina.core.StandardHost对象),
    // StandardHost 初始化的时候会设置基础阀 StandardHostValue
    // Ask this Host to process this request
    host.getPipeline().getFirst().invoke(request, response);

}
 
Example #7
Source File: HostManagerServlet.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Render a list of the currently active Contexts in our virtual host.
 *
 * @param writer Writer to render to
 * @param smClient StringManager for the client's locale
 */
protected void list(PrintWriter writer, StringManager smClient) {

    if (debug >= 1) {
        log(sm.getString("hostManagerServlet.list", engine.getName()));
    }

    writer.println(smClient.getString("hostManagerServlet.listed",
            engine.getName()));
    Container[] hosts = engine.findChildren();
    for (int i = 0; i < hosts.length; i++) {
        Host host = (Host) hosts[i];
        String name = host.getName();
        String[] aliases = host.findAliases();
        writer.println(smClient.getString("hostManagerServlet.listitem",
                name, StringUtils.join(aliases)));
    }
}
 
Example #8
Source File: Tomcat.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
private String getLoggerName(Host host, String contextName) {
    if (host == null) {
        host = getHost();
    }
    StringBuilder loggerName = new StringBuilder();
    loggerName.append(ContainerBase.class.getName());
    loggerName.append(".[");
    // Engine name
    loggerName.append(host.getParent().getName());
    loggerName.append("].[");
    // Host name
    loggerName.append(host.getName());
    loggerName.append("].[");
    // Context name
    if (contextName == null || contextName.equals("")) {
        loggerName.append("/");
    } else if (contextName.startsWith("##")) {
        loggerName.append("/");
        loggerName.append(contextName);
    }
    loggerName.append(']');

    return loggerName.toString();
}
 
Example #9
Source File: Tomcat.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
public Context addContext(Host host, String contextPath, String contextName,
        String dir) {
    silence(host, contextPath);
    Context ctx = createContext(host, contextPath);
    ctx.setName(contextName);
    ctx.setPath(contextPath);
    ctx.setDocBase(dir);
    ctx.addLifecycleListener(new FixContextListener());
    
    if (host == null) {
        getHost().addChild(ctx);
    } else {
        host.addChild(ctx);
    }
    return ctx;
}
 
Example #10
Source File: TestTomcat.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetBrokenContextPerAddWepapp() {
    Tomcat tomcat = getTomcatInstance();
    Host host = tomcat.getHost();
    if (host instanceof StandardHost) {
        ((StandardHost) host).setContextClass("InvalidContextClassName");
    }

    try {
        File appFile = new File("test/deployment/context.war");
        tomcat.addWebapp(null, "/test", appFile.getAbsolutePath());
        fail();
    } catch (IllegalArgumentException e) {
        // OK
    }
}
 
Example #11
Source File: TestHostConfigAutomaticDeployment.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testSetContextClassName() throws Exception {

    Tomcat tomcat = getTomcatInstance();

    Host host = tomcat.getHost();
    if (host instanceof StandardHost) {
        StandardHost standardHost = (StandardHost) host;
        standardHost.setContextClass(TesterContext.class.getName());
    }

    // Copy the WAR file
    File war = new File(host.getAppBaseFile(),
            APP_NAME.getBaseName() + ".war");
    Files.copy(WAR_XML_SOURCE.toPath(), war.toPath());

    // Deploy the copied war
    tomcat.start();
    host.backgroundProcess();

    // Check the Context class
    Context ctxt = (Context) host.findChild(APP_NAME.getName());

    Assert.assertTrue(ctxt instanceof TesterContext);
}
 
Example #12
Source File: UserConfig.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Process the START event for an associated Host.
 *
 * @param event The lifecycle event that has occurred
 */
@Override
public void lifecycleEvent(LifecycleEvent event) {

    // Identify the host we are associated with
    try {
        host = (Host) event.getLifecycle();
    } catch (ClassCastException e) {
        log.error(sm.getString("hostConfig.cce", event.getLifecycle()), e);
        return;
    }

    // Process the event that has occurred
    if (event.getType().equals(Lifecycle.START_EVENT))
        start();
    else if (event.getType().equals(Lifecycle.STOP_EVENT))
        stop();

}
 
Example #13
Source File: RedisSessionRequestValveTest.java    From redis-session-manager with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    this.request = mock(Request.class, withSettings().useConstructor()); // useConstructor to instantiate fields
    this.response = mock(Response.class);

    final Context contextContainer = mock(Context.class);
    this.hostContainer = mock(Host.class);

    when(contextContainer.getParent()).thenReturn(hostContainer);
    when(contextContainer.getPath()).thenReturn("/");

    when(request.getRequestURI()).thenReturn("/requestURI"); // override for tests
    when(request.getMethod()).thenReturn("GET");
    when(request.getQueryString()).thenReturn(null);
    when(request.getContext()).thenReturn(contextContainer);

    doCallRealMethod().when(request).setNote(Mockito.anyString(), Mockito.anyObject());
    doCallRealMethod().when(request).removeNote(Mockito.anyString());
    when(request.getNote(Mockito.anyString())).thenCallRealMethod();

    when(contextContainer.getLoader()).thenReturn(new WebappLoader(Thread.currentThread().getContextClassLoader()));
}
 
Example #14
Source File: TestTomcat.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testGetCustomContextPerAddWebappWithHost() {
    Tomcat tomcat = getTomcatInstance();
    Host host = tomcat.getHost();
    if (host instanceof StandardHost) {
        ((StandardHost) host).setContextClass(ReplicatedContext.class
                .getName());
    }

    File appFile = new File("test/deployment/context.war");
    Context context = tomcat.addWebapp(host, "/test",
            appFile.getAbsolutePath());

    Assert.assertEquals(ReplicatedContext.class.getName(), context.getClass()
            .getName());
}
 
Example #15
Source File: TestTomcat.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testGetCustomContextPerAddWebappWithNullHost() {
    Tomcat tomcat = getTomcatInstance();
    Host host = tomcat.getHost();
    if (host instanceof StandardHost) {
        ((StandardHost) host).setContextClass(ReplicatedContext.class
                .getName());
    }

    File appFile = new File("test/deployment/context.war");
    Context context = tomcat.addWebapp(null, "/test",
            appFile.getAbsolutePath());

    Assert.assertEquals(ReplicatedContext.class.getName(), context.getClass()
            .getName());
}
 
Example #16
Source File: TestTomcat.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCustomContextPerAddWebappWithHost() {
    Tomcat tomcat = getTomcatInstance();
    Host host = tomcat.getHost();
    if (host instanceof StandardHost) {
        ((StandardHost) host).setContextClass(ReplicatedContext.class
                .getName());
    }

    File appFile = new File("test/deployment/context.war");
    Context context = tomcat.addWebapp(host, "/test",
            appFile.getAbsolutePath());

    assertEquals(ReplicatedContext.class.getName(), context.getClass()
            .getName());
}
 
Example #17
Source File: RewriteValve.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Find the configuration path where the rewrite configuration file
 * will be stored.
 * @param resourceName The rewrite configuration file name
 * @return the full rewrite configuration path
 */
protected String getHostConfigPath(String resourceName) {
    StringBuffer result = new StringBuffer();
    Container container = getContainer();
    Container host = null;
    Container engine = null;
    while (container != null) {
        if (container instanceof Host)
            host = container;
        if (container instanceof Engine)
            engine = container;
        container = container.getParent();
    }
    if (engine != null) {
        result.append(engine.getName()).append('/');
    }
    if (host != null) {
        result.append(host.getName()).append('/');
    }
    result.append(resourceName);
    return result.toString();
}
 
Example #18
Source File: TestReplicatedContext.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testBug57425() throws LifecycleException, IOException {
    Tomcat tomcat = getTomcatInstance();
    Host host = tomcat.getHost();
    if (host instanceof StandardHost) {
        ((StandardHost) host).setContextClass(ReplicatedContext.class.getName());
    }

    File root = new File("test/webapp");
    Context context = tomcat.addWebapp(host, "", root.getAbsolutePath());

    Tomcat.addServlet(context, "test", new AccessContextServlet());
    context.addServletMappingDecoded("/access", "test");

    tomcat.start();

    ByteChunk result = getUrl("http://localhost:" + getPort() + "/access");

    Assert.assertEquals("OK", result.toString());

}
 
Example #19
Source File: TestTomcat.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCustomContextPerAddWebappWithHost() {
    Tomcat tomcat = getTomcatInstance();
    Host host = tomcat.getHost();
    if (host instanceof StandardHost) {
        ((StandardHost) host).setContextClass(ReplicatedContext.class
                .getName());
    }

    File appFile = new File("test/deployment/context.war");
    org.apache.catalina.Context context = tomcat.addWebapp(host, "/test",
            appFile.getAbsolutePath());

    assertEquals(ReplicatedContext.class.getName(), context.getClass()
            .getName());
}
 
Example #20
Source File: MapperListener.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Register host.
 */
private void registerHost(Host host) {

    String[] aliases = host.findAliases();
    mapper.addHost(host.getName(), aliases, host);

    for (Container container : host.findChildren()) {
        if (container.getState().isAvailable()) {
            registerContext((Context) container);
        }
    }
    if(log.isDebugEnabled()) {
        log.debug(sm.getString("mapperListener.registerHost",
                host.getName(), domain, service));
    }
}
 
Example #21
Source File: TestTomcat.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCustomContextPerAddWebappWithNullHost() {
    Tomcat tomcat = getTomcatInstance();
    Host host = tomcat.getHost();
    if (host instanceof StandardHost) {
        ((StandardHost) host).setContextClass(ReplicatedContext.class
                .getName());
    }

    File appFile = new File("test/deployment/context.war");
    Context context = tomcat.addWebapp(null, "/test",
            appFile.getAbsolutePath());

    assertEquals(ReplicatedContext.class.getName(), context.getClass()
            .getName());
}
 
Example #22
Source File: Embedded.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Remove the specified Host, along with all of its related Contexts,
 * from the set of defined Hosts for its associated Engine.  If this is
 * the last Host for this Engine, the Engine will also be removed.
 *
 * @param host The Host to be removed
 */
public synchronized void removeHost(Host host) {

    if( log.isDebugEnabled() )
        log.debug("Removing host[" + host.getName() + "]");

    // Is this Host actually among those that are defined?
    boolean found = false;
    for (int i = 0; i < engines.length; i++) {
        Container hosts[] = engines[i].findChildren();
        for (int j = 0; j < hosts.length; j++) {
            if (host == (Host) hosts[j]) {
                found = true;
                break;

            }
        }
        if (found)
            break;
    }
    if (!found)
        return;

    // Remove this Host from the associated Engine
    if( log.isDebugEnabled() )
        log.debug(" Removing this Host");
    host.getParent().removeChild(host);

}
 
Example #23
Source File: ThreadLocalLeakPreventionListener.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
protected void processContainerRemoveChild(Container parent,
    Container child) {

    if (log.isDebugEnabled())
        log.debug("Process removeChild[parent=" + parent + ",child=" +
            child + "]");

    if (child instanceof Context) {
        Context context = (Context) child;
        context.removeLifecycleListener(this);
    } else if (child instanceof Host || child instanceof Engine) {
        child.removeContainerListener(this);
    }
}
 
Example #24
Source File: ThreadLocalLeakPreventionListener.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
protected void processContainerAddChild(Container parent, Container child) {
    if (log.isDebugEnabled())
        log.debug("Process addChild[parent=" + parent + ",child=" + child +
            "]");

    if (child instanceof Context) {
        registerContextListener((Context) child);
    } else if (child instanceof Engine) {
        registerListenersForEngine((Engine) child);
    } else if (child instanceof Host) {
        registerListenersForHost((Host) child);
    }

}
 
Example #25
Source File: ThreadLocalLeakPreventionListener.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private void registerListenersForEngine(Engine engine) {
    for (Container hostContainer : engine.findChildren()) {
        Host host = (Host) hostContainer;
        host.addContainerListener(this);
        registerListenersForHost(host);
    }
}
 
Example #26
Source File: Tomcat.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
private String getLoggerName(Host host, String ctx) {
    String loggerName = "org.apache.catalina.core.ContainerBase.[default].[";
    if (host == null) {
        loggerName += getHost().getName();
    } else {
        loggerName += host.getName();
    }
    loggerName += "].[";
    loggerName += ctx;
    loggerName += "]";
    return loggerName;
}
 
Example #27
Source File: Mapper.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Constructor used for the primary Host
 *
 * @param name The name of the virtual host
 * @param host The host
 */
public MappedHost(String name, Host host) {
    super(name, host);
    realHost = this;
    contextList = new ContextList();
    aliases = new CopyOnWriteArrayList<>();
}
 
Example #28
Source File: PersistentValve.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
public void setContainer(Container container) {
    super.setContainer(container);
    if (container instanceof Engine || container instanceof Host) {
        clBindRequired = true;
    } else {
        clBindRequired = false;
    }
}
 
Example #29
Source File: ClusterSingleSignOn.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Start this component and implement the requirements
 * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
 *
 * @exception LifecycleException if this component detects a fatal error
 *  that prevents this component from being used
 */
@Override
protected synchronized void startInternal() throws LifecycleException {

    // Load the cluster component, if any
    try {
        if(cluster == null) {
            Container host = getContainer();
            if(host instanceof Host) {
                if(host.getCluster() instanceof CatalinaCluster) {
                    setCluster((CatalinaCluster) host.getCluster());
                }
            }
        }
        if (cluster == null) {
            throw new LifecycleException(sm.getString("clusterSingleSignOn.nocluster"));
        }

        ClassLoader[] cls = new ClassLoader[] { this.getClass().getClassLoader() };

        ReplicatedMap<String,SingleSignOnEntry> cache = new ReplicatedMap<>(
                this, cluster.getChannel(), rpcTimeout, cluster.getClusterName() + "-SSO-cache",
                cls, terminateOnStartFailure);
        cache.setChannelSendOptions(mapSendOptions);
        cache.setAccessTimeout(accessTimeout);
        this.cache = cache;
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        throw new LifecycleException(sm.getString("clusterSingleSignOn.clusterLoad.fail"), t);
    }

    super.startInternal();
}
 
Example #30
Source File: ClusterSingleSignOn.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Start this component and implement the requirements
 * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
 *
 * @exception LifecycleException if this component detects a fatal error
 *  that prevents this component from being used
 */
@Override
protected synchronized void startInternal() throws LifecycleException {
    
    // Load the cluster component, if any
    try {
        if(cluster == null) {
            Container host = getContainer();
            if(host instanceof Host) {
                if(host.getCluster() instanceof CatalinaCluster) {
                    setCluster((CatalinaCluster) host.getCluster());
                }
            }
        }
        if (cluster == null) {
            throw new LifecycleException(
                    "There is no Cluster for ClusterSingleSignOn");
        }

        ClassLoader[] cls = new ClassLoader[] { this.getClass().getClassLoader() };

        ReplicatedMap<String,SingleSignOnEntry> cache =
                new ReplicatedMap<String,SingleSignOnEntry>(
                this, cluster.getChannel(), rpcTimeout, cluster.getClusterName() + "-SSO-cache",
                cls, terminateOnStartFailure);
        cache.setChannelSendOptions(mapSendOptions);
        this.cache = cache;
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        throw new LifecycleException(
                "ClusterSingleSignOn exception during clusterLoad " + t);
    }

    super.startInternal();
}