use of org.apache.catalina.core.StandardHost in project tomcat by apache.
the class TestAbstractArchiveResource method testJarGetURL.
@Test
public void testJarGetURL() throws Exception {
Tomcat tomcat = getTomcatInstance();
File docBase = new File("test/webapp");
Context ctx = tomcat.addWebapp("/test", docBase.getAbsolutePath());
skipTldsForResourceJars(ctx);
((StandardHost) tomcat.getHost()).setUnpackWARs(false);
tomcat.start();
WebResource webResource = ctx.getResources().getClassLoaderResource("/META-INF/tags/echo.tag");
StringBuilder expectedURL = new StringBuilder("jar:");
expectedURL.append(docBase.getAbsoluteFile().toURI().toURL().toString());
expectedURL.append("WEB-INF/lib/test-lib.jar!/META-INF/tags/echo.tag");
Assert.assertEquals(expectedURL.toString(), webResource.getURL().toString());
}
use of org.apache.catalina.core.StandardHost in project tomcat by apache.
the class HostConfig method deployWAR.
/**
* Deploy packed WAR.
* @param cn The context name
* @param war The WAR file
*/
protected void deployWAR(ContextName cn, File war) {
File xml = new File(host.getAppBaseFile(), cn.getBaseName() + "/" + Constants.ApplicationContextXml);
File warTracker = new File(host.getAppBaseFile(), cn.getBaseName() + "/" + Constants.WarTracker);
boolean xmlInWar = false;
try (JarFile jar = new JarFile(war)) {
JarEntry entry = jar.getJarEntry(Constants.ApplicationContextXml);
if (entry != null) {
xmlInWar = true;
}
} catch (IOException e) {
/* Ignore */
}
// If there is an expanded directory then any xml in that directory
// should only be used if the directory is not out of date and
// unpackWARs is true. Note the code below may apply further limits
boolean useXml = false;
// test that here
if (xml.exists() && unpackWARs && (!warTracker.exists() || warTracker.lastModified() == war.lastModified())) {
useXml = true;
}
Context context = null;
try {
if (deployXML && useXml && !copyXML) {
synchronized (digesterLock) {
try {
context = (Context) digester.parse(xml);
} catch (Exception e) {
log.error(sm.getString("hostConfig.deployDescriptor.error", war.getAbsolutePath()), e);
} finally {
digester.reset();
if (context == null) {
context = new FailedContext();
}
}
}
context.setConfigFile(xml.toURI().toURL());
} else if (deployXML && xmlInWar) {
synchronized (digesterLock) {
try (JarFile jar = new JarFile(war)) {
JarEntry entry = jar.getJarEntry(Constants.ApplicationContextXml);
try (InputStream istream = jar.getInputStream(entry)) {
context = (Context) digester.parse(istream);
}
} catch (Exception e) {
log.error(sm.getString("hostConfig.deployDescriptor.error", war.getAbsolutePath()), e);
} finally {
digester.reset();
if (context == null) {
context = new FailedContext();
}
context.setConfigFile(UriUtil.buildJarUrl(war, Constants.ApplicationContextXml));
}
}
} else if (!deployXML && xmlInWar) {
// Block deployment as META-INF/context.xml may contain security
// configuration necessary for a secure deployment.
log.error(sm.getString("hostConfig.deployDescriptor.blocked", cn.getPath(), Constants.ApplicationContextXml, new File(host.getConfigBaseFile(), cn.getBaseName() + ".xml")));
} else {
context = (Context) Class.forName(contextClass).newInstance();
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.error(sm.getString("hostConfig.deployWar.error", war.getAbsolutePath()), t);
} finally {
if (context == null) {
context = new FailedContext();
}
}
boolean copyThisXml = false;
if (deployXML) {
if (host instanceof StandardHost) {
copyThisXml = ((StandardHost) host).isCopyXML();
}
// If Host is using default value Context can override it.
if (!copyThisXml && context instanceof StandardContext) {
copyThisXml = ((StandardContext) context).getCopyXML();
}
if (xmlInWar && copyThisXml) {
// Change location of XML file to config base
xml = new File(host.getConfigBaseFile(), cn.getBaseName() + ".xml");
try (JarFile jar = new JarFile(war)) {
JarEntry entry = jar.getJarEntry(Constants.ApplicationContextXml);
try (InputStream istream = jar.getInputStream(entry);
FileOutputStream fos = new FileOutputStream(xml);
BufferedOutputStream ostream = new BufferedOutputStream(fos, 1024)) {
byte[] buffer = new byte[1024];
while (true) {
int n = istream.read(buffer);
if (n < 0) {
break;
}
ostream.write(buffer, 0, n);
}
ostream.flush();
}
} catch (IOException e) {
/* Ignore */
}
}
}
DeployedApplication deployedApp = new DeployedApplication(cn.getName(), xml.exists() && deployXML && copyThisXml);
long startTime = 0;
// Deploy the application in this WAR file
if (log.isInfoEnabled()) {
startTime = System.currentTimeMillis();
log.info(sm.getString("hostConfig.deployWar", war.getAbsolutePath()));
}
try {
// Populate redeploy resources with the WAR file
deployedApp.redeployResources.put(war.getAbsolutePath(), Long.valueOf(war.lastModified()));
if (deployXML && xml.exists() && copyThisXml) {
deployedApp.redeployResources.put(xml.getAbsolutePath(), Long.valueOf(xml.lastModified()));
} else {
// In case an XML file is added to the config base later
deployedApp.redeployResources.put((new File(host.getConfigBaseFile(), cn.getBaseName() + ".xml")).getAbsolutePath(), Long.valueOf(0));
}
Class<?> clazz = Class.forName(host.getConfigClass());
LifecycleListener listener = (LifecycleListener) clazz.newInstance();
context.addLifecycleListener(listener);
context.setName(cn.getName());
context.setPath(cn.getPath());
context.setWebappVersion(cn.getVersion());
context.setDocBase(cn.getBaseName() + ".war");
host.addChild(context);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.error(sm.getString("hostConfig.deployWar.error", war.getAbsolutePath()), t);
} finally {
// If we're unpacking WARs, the docBase will be mutated after
// starting the context
boolean unpackWAR = unpackWARs;
if (unpackWAR && context instanceof StandardContext) {
unpackWAR = ((StandardContext) context).getUnpackWAR();
}
if (unpackWAR && context.getDocBase() != null) {
File docBase = new File(host.getAppBaseFile(), cn.getBaseName());
deployedApp.redeployResources.put(docBase.getAbsolutePath(), Long.valueOf(docBase.lastModified()));
addWatchedResources(deployedApp, docBase.getAbsolutePath(), context);
if (deployXML && !copyThisXml && (xmlInWar || xml.exists())) {
deployedApp.redeployResources.put(xml.getAbsolutePath(), Long.valueOf(xml.lastModified()));
}
} else {
// Passing null for docBase means that no resources will be
// watched. This will be logged at debug level.
addWatchedResources(deployedApp, null, context);
}
// Add the global redeploy resources (which are never deleted) at
// the end so they don't interfere with the deletion process
addGlobalRedeployResources(deployedApp);
}
deployed.put(cn.getName(), deployedApp);
if (log.isInfoEnabled()) {
log.info(sm.getString("hostConfig.deployWar.finished", war.getAbsolutePath(), Long.valueOf(System.currentTimeMillis() - startTime)));
}
}
use of org.apache.catalina.core.StandardHost in project tomcat by apache.
the class Tomcat method getHost.
public Host getHost() {
Engine engine = getEngine();
if (engine.findChildren().length > 0) {
return (Host) engine.findChildren()[0];
}
Host host = new StandardHost();
host.setName(hostname);
getEngine().addChild(host);
return host;
}
use of org.apache.catalina.core.StandardHost in project tomcat by apache.
the class HostManagerServlet method add.
// -------------------------------------------------------- Private Methods
/**
* Add a host using the specified parameters.
*
* @param writer Writer to render results to
* @param name host name
* @param aliases comma separated alias list
* @param appBase application base for the host
* @param manager should the manager webapp be deployed to the new host ?
* @param autoDeploy Flag value
* @param deployOnStartup Flag value
* @param deployXML Flag value
* @param unpackWARs Flag value
* @param copyXML Flag value
* @param smClient StringManager for the client's locale
*/
protected synchronized void add(PrintWriter writer, String name, String aliases, String appBase, boolean manager, boolean autoDeploy, boolean deployOnStartup, boolean deployXML, boolean unpackWARs, boolean copyXML, StringManager smClient) {
if (debug >= 1) {
log(sm.getString("hostManagerServlet.add", name));
}
// Validate the requested host name
if ((name == null) || name.length() == 0) {
writer.println(smClient.getString("hostManagerServlet.invalidHostName", name));
return;
}
// Check if host already exists
if (engine.findChild(name) != null) {
writer.println(smClient.getString("hostManagerServlet.alreadyHost", name));
return;
}
// Validate and create appBase
File appBaseFile = null;
File file = null;
String applicationBase = appBase;
if (applicationBase == null || applicationBase.length() == 0) {
applicationBase = name;
}
file = new File(applicationBase);
if (!file.isAbsolute())
file = new File(engine.getCatalinaBase(), file.getPath());
try {
appBaseFile = file.getCanonicalFile();
} catch (IOException e) {
appBaseFile = file;
}
if (!appBaseFile.mkdirs() && !appBaseFile.isDirectory()) {
writer.println(smClient.getString("hostManagerServlet.appBaseCreateFail", appBaseFile.toString(), name));
return;
}
// Create base for config files
File configBaseFile = getConfigBase(name);
// Copy manager.xml if requested
if (manager) {
if (configBaseFile == null) {
writer.println(smClient.getString("hostManagerServlet.configBaseCreateFail", name));
return;
}
try (InputStream is = getServletContext().getResourceAsStream("/manager.xml")) {
Path dest = (new File(configBaseFile, "manager.xml")).toPath();
Files.copy(is, dest);
} catch (IOException e) {
writer.println(smClient.getString("hostManagerServlet.managerXml"));
return;
}
}
StandardHost host = new StandardHost();
host.setAppBase(applicationBase);
host.setName(name);
host.addLifecycleListener(new HostConfig());
// Add host aliases
if ((aliases != null) && !("".equals(aliases))) {
StringTokenizer tok = new StringTokenizer(aliases, ", ");
while (tok.hasMoreTokens()) {
host.addAlias(tok.nextToken());
}
}
host.setAutoDeploy(autoDeploy);
host.setDeployOnStartup(deployOnStartup);
host.setDeployXML(deployXML);
host.setUnpackWARs(unpackWARs);
host.setCopyXML(copyXML);
// Add new host
try {
engine.addChild(host);
} catch (Exception e) {
writer.println(smClient.getString("hostManagerServlet.exception", e.toString()));
return;
}
host = (StandardHost) engine.findChild(name);
if (host != null) {
writer.println(smClient.getString("hostManagerServlet.add", name));
} else {
// Something failed
writer.println(smClient.getString("hostManagerServlet.addFailed", name));
}
}
use of org.apache.catalina.core.StandardHost in project tomcat by apache.
the class TestWebappClassLoaderThreadLocalMemoryLeak method testThreadLocalLeak2.
@Test
public void testThreadLocalLeak2() throws Exception {
Tomcat tomcat = getTomcatInstance();
// Need to make sure we see a leak for the right reasons
tomcat.getServer().addLifecycleListener(new JreMemoryLeakPreventionListener());
// No file system docBase required
Context ctx = tomcat.addContext("", null);
Tomcat.addServlet(ctx, "leakServlet2", "org.apache.tomcat.unittest.TesterLeakingServlet2");
ctx.addServletMappingDecoded("/leak2", "leakServlet2");
tomcat.start();
Executor executor = tomcat.getConnector().getProtocolHandler().getExecutor();
((ThreadPoolExecutor) executor).setThreadRenewalDelay(-1);
// Configure logging filter to check leak message appears
LogValidationFilter f = new LogValidationFilter("The web application [ROOT] created a ThreadLocal with key of");
LogManager.getLogManager().getLogger("org.apache.catalina.loader.WebappClassLoaderBase").setFilter(f);
// Need to force loading of all web application classes via the web
// application class loader
loadClass("TesterCounter", (WebappClassLoader) ctx.getLoader().getClassLoader());
loadClass("TesterThreadScopedHolder", (WebappClassLoader) ctx.getLoader().getClassLoader());
loadClass("TesterLeakingServlet2", (WebappClassLoader) ctx.getLoader().getClassLoader());
// This will trigger the ThreadLocal creation
int rc = getUrl("http://localhost:" + getPort() + "/leak2", new ByteChunk(), null);
// Make sure request is OK
Assert.assertEquals(HttpServletResponse.SC_OK, rc);
// Destroy the context
ctx.stop();
tomcat.getHost().removeChild(ctx);
ctx = null;
// Make sure we have a memory leak
String[] leaks = ((StandardHost) tomcat.getHost()).findReloadedContextMemoryLeaks();
Assert.assertNotNull(leaks);
Assert.assertTrue(leaks.length > 0);
// Make sure the message was logged
Assert.assertEquals(1, f.getMessageCount());
}
Aggregations