</javac>
<copy todir="${http.test-classes}">
<fileset dir="${tomcat.lite.src}/test"
- includes="**/*.properties **/*.xml **/*.bin **/*.keystore" />
+ includes="**/*.properties **/*.xml **/*.bin **/*.keystore **/*.cert **/*.der" />
</copy>
</target>
private void bind(String name, Object o) {
try {
- registry.registerComponent(o, "name=" + name, null);
+ registry.registerComponent(o, "TomcatLite:name=" + name, null);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
log.warning("Unexpected message from server in client keep alive "
- + net.getIn());
+ + net.getIn() + ": " + net.getIn().readAll(null));
if (net.isOpen()) {
net.close();
}
@Override
public IOChannel channel(IOChannel net, String host, int port) throws IOException {
if (debug) {
- DumpChannel dch = new DumpChannel("S-ENC-" + id, net);
- net.setHead(dch);
- net = dch;
+ net = DumpChannel.wrap("S-ENC-" + id, net);
}
SslChannel ch = new SslChannel()
.setTarget(host, port)
public void handleConnected(IOChannel ch) throws IOException {
IOChannel first = ch;
if (debug) {
- DumpChannel dch = new DumpChannel("S-ENC-" + id, ch);
- ch.setHead(dch);
- first = dch;
+ first = DumpChannel.wrap("S-ENC-" + id, ch);
}
IOChannel sslch = serverChannel(first);
first.setHead(sslch);
if (debug) {
- DumpChannel dch2 = new DumpChannel("S-CLR-" + id, sslch);
- sslch.setHead(dch2);
- sslch = dch2;
+ sslch = DumpChannel.wrap("S-CLR-" + id, sslch);
id++;
}
public void handleConnected(IOChannel ch) throws IOException {
IOChannel first = ch;
if (debug) {
- DumpChannel dch = new DumpChannel("ENC-" + id);
- ch.setHead(dch);
- first = dch;
+ first = DumpChannel.wrap("ENC-" + id, first);
}
IOChannel sslch = channel(first, host, port);
// first.setHead(sslch);
if (debug) {
- DumpChannel dch2 = new DumpChannel("CLR-" + id);
- sslch.setHead(dch2);
- sslch = dch2;
+ sslch = DumpChannel.wrap("CLR-" + id, sslch);
id++;
}
if (unwrapR.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
tasks();
}
- if (unwrapR.getStatus() == Status.BUFFER_OVERFLOW ||
- unwrapR.getStatus() == Status.BUFFER_UNDERFLOW) {
- log.severe("Unhandled overflow");
+ if (unwrapR.getStatus() == Status.BUFFER_OVERFLOW) {
+ log.severe("Unhandled overflow " + unwrapR);
+ break;
+ }
+ if (unwrapR.getStatus() == Status.BUFFER_UNDERFLOW) {
+ // harmless
+ //log.severe("Unhandled underflow " + unwrapR);
break;
}
}
import javax.servlet.ServletException;
import org.apache.catalina.LifecycleException;
-import org.apache.tomcat.lite.servlet.TomcatLite;
-import org.apache.tomcat.lite.servlet.TomcatLiteWatchdog;
+import org.apache.tomcat.test.watchdog.WatchdogClient;
import junit.framework.Test;
-public class ServletTests extends TomcatLiteWatchdog {
+/**
+ * Wrapper to run watchdog.
+ *
+ */
+public class ServletTests extends WatchdogClient {
+
public ServletTests() {
super();
- port = 7075;
+ goldenDir = getWatchdogdir() + "/src/clients/org/apache/jcheck/servlet/client/";
+ testMatch =
+ //"HttpServletResponseWrapperSetStatusMsgTest";
+ //"ServletContextAttributeAddedEventTest";
+ null;
+ // ex: "ServletToJSP";
+ file = getWatchdogdir() + "/src/conf/servlet-gtest.xml";
+ targetMatch = "gtestservlet-test";
+
+ port = 8883;
exclude = new String[] {
+ "DoInit1Test", // tomcat returns 404 if perm. unavailable
+ "HttpServletDoInit1Test",
+ "GetMajorVersionTest", // tomcat7
+ "GetMinorVersionTest",
"ServletToJSPErrorPageTest",
"ServletToJSPError502PageTest",
};
}
public ServletTests(String name) {
- super(name);
- port = 7075;
+ this();
+ super.single = name;
+ port = 8883;
}
-
- protected void addConnector(TomcatLite connector) {
-
+
+ protected void beforeSuite() {
+ // required for the tests
+ System.setProperty("org.apache.coyote.USE_CUSTOM_STATUS_MSG_IN_HEADER",
+ "true");
+
+ try {
+ initServerWithWatchdog(getWatchdogdir());
+ } catch (ServletException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
}
public void initServerWithWatchdog(String wdDir) throws ServletException,
IOException {
Tomcat tomcat = new Tomcat();
-
- File f = new File(wdDir + "/build/webapps");
tomcat.setPort(port);
- tomcat.setBaseDir(f.getCanonicalPath());
- TomcatLiteCoyoteTest.setUp(tomcat, port);
+ File f = new File(wdDir + "/build/webapps");
+ tomcat.setBaseDir(f.getAbsolutePath());
for (String s : new String[] {
"servlet-compat",
"jsp-tests"} ) {
tomcat.addWebapp("/" + s, f.getCanonicalPath() + "/" + s);
}
-
+
+ TomcatStandaloneMain.setUp(tomcat, port);
+
try {
tomcat.start();
} catch (LifecycleException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
+ System.err.println("Init done");
}
/**
import org.apache.catalina.core.StandardServer;
import org.apache.catalina.core.StandardService;
import org.apache.catalina.core.StandardWrapper;
-import org.apache.catalina.realm.GenericPrincipal;
import org.apache.catalina.realm.RealmBase;
import org.apache.catalina.session.StandardManager;
import org.apache.catalina.startup.ContextConfig;
+// This class is here for compat with Tomcat6.
+
// TODO: lazy init for the temp dir - only when a JSP is compiled or
// get temp dir is called we need to create it. This will avoid the
// need for the baseDir
protected StandardService service;
protected StandardEngine engine;
protected Connector connector; // for more - customize the classes
-
+
+ boolean started = false;
// To make it a bit easier to config for the common case
// ( one host, one context ).
protected StandardHost host;
* @throws LifecycleException
*/
public void start() throws LifecycleException {
+ if (started) {
+ return;
+ }
+ started = true;
getServer();
getConnector();
- server.initialize();
server.start();
}
} else {
host.addChild(ctx);
}
-
+
return ctx;
}
package org.apache.coyote.lite;
import java.io.IOException;
-
-import javax.servlet.ServletException;
+import java.util.logging.Level;
+import java.util.logging.Logger;
import junit.framework.TestCase;
-import org.apache.catalina.LifecycleException;
-import org.apache.catalina.connector.Connector;
-import org.apache.tomcat.lite.http.DefaultHttpConnector;
+import org.apache.tomcat.lite.http.HttpClient;
import org.apache.tomcat.lite.http.HttpChannel;
import org.apache.tomcat.lite.http.HttpConnector;
import org.apache.tomcat.lite.io.BBuffer;
+/**
+ * Very simple test.
+ */
public class TomcatLiteCoyoteTest extends TestCase {
-
- static Tomcat tomcat;
- LiteProtocolHandler litePH;
-
- public void setUp() {
- if (tomcat == null) {
- try {
- tomcat = new Tomcat();
-
- tomcat.setPort(8885);
- tomcat.setBaseDir("../../output/build/webapps");
-
- tomcat.addWebapp("/", "ROOT");
-
-
- //tomcat.addServlet(ctx, "name", "class");
- // ctx.addServletMapping("/foo/*", "name");
-
- litePH = setUp(tomcat, 8885);
-
- tomcat.start();
- } catch (LifecycleException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (ServletException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
+ static int port = 8884;
+ static {
+ Logger.getLogger("org.apache.catalina.core.StandardService").setLevel(Level.WARNING);
+ Logger.getLogger("org.apache.catalina.core.StandardEngine").setLevel(Level.WARNING);
+ Logger.getLogger("org.apache.catalina.startup.ContextConfig").setLevel(Level.WARNING);
}
-
- public static LiteProtocolHandler setUp(Tomcat tomcat, int port) {
- Connector connector;
- try {
- connector = new Connector(LiteProtocolHandler.class.getName());
- tomcat.getService().addConnector(connector);
- connector.setPort(port);
- tomcat.setConnector(connector);
- LiteProtocolHandler ph =
- (LiteProtocolHandler) connector.getProtocolHandler();
- return ph;
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
+ static Tomcat main = TomcatStandaloneMain.setUp(port);
public void testSimple() throws IOException {
- HttpConnector clientCon = DefaultHttpConnector.get();
- HttpChannel ch = clientCon.get("localhost", 8885);
+ HttpConnector clientCon = HttpClient.newClient();
+
+ HttpChannel ch = clientCon.get("localhost", port);
ch.getRequest().setRequestURI("/index.html");
ch.getRequest().send();
+
BBuffer res = ch.readAll(null, 0);
- assertTrue(res.toString(), res.toString().indexOf("<title>Apache Tomcat</title>") >= 0);
+ assertTrue(res.toString(),
+ res.toString().indexOf("<title>Apache Tomcat</title>") >= 0);
}
--- /dev/null
+/*
+ */
+package org.apache.coyote.lite;
+
+import javax.servlet.ServletException;
+
+import org.apache.catalina.LifecycleException;
+import org.apache.catalina.connector.Connector;
+import org.apache.tomcat.lite.TestMain;
+
+/**
+ * Startup tomcat + coyote lite connector.
+ * No config files used.
+ *
+ * @author Costin Manolache
+ */
+public class TomcatStandaloneMain {
+
+ public static Tomcat setUp(int port) {
+ try {
+ Tomcat tomcat = new Tomcat();
+
+ tomcat.setPort(port);
+ String base = TestMain.findDir("/output/build");
+ tomcat.setBaseDir(base);
+ // Absolute path - tomcat6 and 7 are different,
+ // 7 adds webapps.
+ tomcat.addWebapp("/", base + "/webapps/ROOT");
+
+ LiteProtocolHandler litePH = setUp(tomcat, port);
+
+ tomcat.start();
+ return tomcat;
+ } catch (LifecycleException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (ServletException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ public static LiteProtocolHandler setUp(Tomcat tomcat, int port) {
+ Connector connector;
+ try {
+ connector = new Connector(LiteProtocolHandler.class.getName());
+ tomcat.getService().addConnector(connector);
+ connector.setPort(port);
+ tomcat.setConnector(connector);
+ LiteProtocolHandler ph =
+ (LiteProtocolHandler) connector.getProtocolHandler();
+ return ph;
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+}
package org.apache.tomcat.lite;
import java.io.BufferedInputStream;
+import java.io.File;
import java.io.IOException;
import java.io.InputStream;
+import java.lang.reflect.Constructor;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
-import org.apache.tomcat.integration.jmx.UJmxHandler;
-import org.apache.tomcat.integration.jmx.UJmxObjectManagerSpi;
-import org.apache.tomcat.integration.simple.Main;
-import org.apache.tomcat.integration.simple.SimpleObjectManager;
import org.apache.tomcat.lite.http.BaseMapper;
-import org.apache.tomcat.lite.http.DefaultHttpConnector;
+import org.apache.tomcat.lite.http.HttpClient;
import org.apache.tomcat.lite.http.Dispatcher;
-import org.apache.tomcat.lite.http.HttpChannel;
-import org.apache.tomcat.lite.http.HttpConnectionPool;
import org.apache.tomcat.lite.http.HttpConnector;
import org.apache.tomcat.lite.http.HttpRequest;
import org.apache.tomcat.lite.http.HttpResponse;
+import org.apache.tomcat.lite.http.HttpServer;
import org.apache.tomcat.lite.http.HttpChannel.HttpService;
-import org.apache.tomcat.lite.http.HttpConnectionPool.RemoteServer;
-import org.apache.tomcat.lite.http.HttpConnector.HttpChannelEvents;
-import org.apache.tomcat.lite.http.HttpConnector.HttpConnection;
import org.apache.tomcat.lite.http.services.EchoCallback;
import org.apache.tomcat.lite.http.services.SleepCallback;
import org.apache.tomcat.lite.io.BBuffer;
-import org.apache.tomcat.lite.io.IOConnector;
-import org.apache.tomcat.lite.io.SocketConnector;
-import org.apache.tomcat.lite.io.SslConnector;
+import org.apache.tomcat.lite.io.jsse.JsseSslProvider;
import org.apache.tomcat.lite.proxy.HttpProxyService;
import org.apache.tomcat.lite.proxy.StaticContentService;
import org.apache.tomcat.lite.service.IOStatus;
/**
- * Server with lost of test servlets.
+ * Laucher for tomcat-lite standalone, configured with test handlers.
*
* Used in tests - one is running for the entire suite.
*
public class TestMain {
static {
- SslConnector.fixUrlConnection();
+ JsseSslProvider.testModeURLConnection();
}
static TestMain defaultServer;
- private SimpleObjectManager om;
-
private boolean init = false;
- private SocketConnector serverCon = new SocketConnector();
-
- private HttpConnector testClient = DefaultHttpConnector.get();
- private HttpConnector testServer = new HttpConnector(serverCon);
- private HttpConnector testProxy = new HttpConnector(serverCon);
- private HttpConnector sslServer;
-
- private HttpProxyService proxy;
-
- UJmxObjectManagerSpi jmx = new UJmxObjectManagerSpi();
+ HttpConnector testClient;
+ HttpConnector testServer;
+ HttpConnector testProxy;
+ HttpConnector sslServer;
+ HttpProxyService proxy;
+
+ public TestMain() {
+ init();
+ }
- private IOConnector sslCon;
-
+ protected void init() {
+ testClient = HttpClient.newClient();
+ }
+
+ /**
+ * A single instance used for all tests.
+ */
public static TestMain shared() {
if (defaultServer == null) {
defaultServer = new TestMain();
return shared().testClient;
}
- public void initTestCallback(Dispatcher d) throws IOException {
- BaseMapper.ContextMapping mCtx = d.addContext(null, "", null, null, null, null);
+ public static BaseMapper.Context initTestContext(Dispatcher d) throws IOException {
+ BaseMapper.Context mCtx = d.addContext(null, "", null, null, null, null);
- d.addWrapper(mCtx, "/", new StaticContentService()
+ mCtx.addWrapper("/", new StaticContentService()
.setContentType("text/html")
.setData("<a href='/proc/cpool/client'>Client pool</a><br/>" +
"<a href='/proc/cpool/server'>Server pool</a><br/>" +
"<a href='/proc/cpool/proxy'>Proxy pool</a><br/>" +
""));
- d.addWrapper(mCtx, "/favicon.ico",
+ mCtx.addWrapper("/favicon.ico",
new StaticContentService().setStatus(404).setData("Not found"));
- d.addWrapper(mCtx, "/hello", new StaticContentService().setData("Hello world"));
- d.addWrapper(mCtx, "/2nd", new StaticContentService().setData("Hello world2"));
- d.addWrapper(mCtx, "/echo/*", new EchoCallback());
+ mCtx.addWrapper("/hello", new StaticContentService().setData("Hello world"));
+ mCtx.addWrapper("/2nd", new StaticContentService().setData("Hello world2"));
+ mCtx.addWrapper("/echo/*", new EchoCallback());
- d.addWrapper(mCtx, "/sleep/1", new SleepCallback().setData("sleep 1"));
- d.addWrapper(mCtx, "/sleep/10", new SleepCallback().sleep(10000).setData(
+ mCtx.addWrapper("/sleep/1", new SleepCallback().setData("sleep 1"));
+ mCtx.addWrapper("/sleep/10", new SleepCallback().sleep(10000).setData(
"sleep 1"));
- d.addWrapper(mCtx, "/chunked/*", new StaticContentService().setData("AAAA")
+ mCtx.addWrapper("/chunked/*", new StaticContentService().setData("AAAA")
.chunked());
-
- d.addWrapper(mCtx, "/proc/cpool/client", new IOStatus(testClient.cpool));
- d.addWrapper(mCtx, "/proc/cpool/proxy", new IOStatus(testProxy.cpool));
- d.addWrapper(mCtx, "/proc/cpool/server", new IOStatus(testServer.cpool));
-
- d.addWrapper(mCtx, "/helloClose", new HttpService() {
+ mCtx.addWrapper("/helloClose", new HttpService() {
@Override
public void service(HttpRequest httpReq, HttpResponse httpRes)
throws IOException {
httpRes.getBodyWriter().write("Hello");
}
});
-
- d.addWrapper(mCtx, "/ujmx", new UJmxHandler(jmx));
+ return mCtx;
}
+ public void initTestCallback(Dispatcher d) throws IOException {
+ BaseMapper.Context mCtx = initTestContext(d);
+ mCtx.addWrapper("/proc/cpool/client", new IOStatus(testClient.cpool));
+ mCtx.addWrapper("/proc/cpool/proxy", new IOStatus(testProxy.cpool));
+ mCtx.addWrapper("/proc/cpool/server", new IOStatus(testServer.cpool));
+ }
+
public void run() {
try {
- startAll(8000);
+ startAll();
+ // TODO(costin): clean up
+ // Hook in JMX and debug properties
+ try {
+ Class c = Class.forName("org.apache.tomcat.lite.TomcatLiteJmx");
+ Constructor constructor = c.getConstructor(TestMain.class);
+ constructor.newInstance(this);
+ } catch (Throwable t) {
+ // ignore
+ }
} catch (Throwable t) {
t.printStackTrace();
}
}
+ public static String findDir(String dir) {
+ String path = ".";
+ for (int i = 0; i < 5; i++) {
+ File f = new File(path + dir);
+ if (f.exists()) {
+ try {
+ return f.getCanonicalPath();
+ } catch (IOException e) {
+ return f.getAbsolutePath();
+ }
+ }
+ path = path + "/..";
+ }
+ return null;
+ }
+
public int getServerPort() {
return 8802;
}
return 8443;
}
- protected synchronized void startAll(int basePort) throws IOException {
- int port = basePort + 903;
- if (!init) {
+ static String PRIVATE_KEY =
+ "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALsz2milZGHliWte61TfMTSwpAdq" +
+"9uJkMTqgpSVtwxxOe8kT84QtIzhdAsQYjRz9ZtQn9DYWhJQs/cs/R3wWsjWwgiFHLzGalvsmMYJ3" +
+"vBO8VMj762fAWu7GjUApIXcxMJoK4sQUpZKbqTuXpwzVUeeqBcspsIDgOLCo233G7/fBAgMBAAEC" +
+"gYAWEaDX4VeaKuMuYzw+/yjf20sbDMMaIVGkZbfSV8Q+nAn/xHhaxq92P5DJ6VMJbd4neKZTkggD" +
+"J+KriUQ2Hr7XXd/nM+sllaDWGmUnMYFI4txaNkikMA3ZyE/Xa79eDpTnSst8Nm11vrX9oF/hDNo4" +
+"dhbU1krjAwVl/WijzSk4gQJBANvSmsmdjPlzvGNE11Aq3Ffb9/SqAOdE8NevMFeVKtBEKHIe1WlO" +
+"ThRyWv3I8bUKTQMNULruSFVghTh6Hkt/CBkCQQDaAuxaXjv2voYozkOviXMpt0X5LZJMQu2gFc2x" +
+"6UgBqYP2pNGDdRVWpbxF65PpXcLNKllCss2WB8i8kdeixYHpAkEAnIrzfia7sR2RiCQLLWUIe20D" +
+"vHGgqRG4bfCtfYGV9rDDGNoKYq7H/dmeIOML9kA6rbS6zBRK4LoWxSx6DIuPaQJAL2c3USbwTuR6" +
+"c2D2IrL2UXnCQz3/c4mR9Z8IDMk2mPXs9bI8xCKvMxnyaBmjHbj/ZHDy26fZP+gNY8MqagAcEQJA" +
+"SidPwFV6cO8LCIA43wSVHlKZt4yU5wa9EWfzqVZxj7VSav7431kuxktW/YlwwxO4Pn8hgpPqD+W1" +
+"E+Ssocxi8A==";
+
+ static String CERTIFICATE = "-----BEGIN CERTIFICATE-----\n" +
+"MIIC5DCCAk2gAwIBAgIJAMa8ioWQMpEZMA0GCSqGSIb3DQEBBQUAMFYxCzAJBgNV" +
+"BAYTAlVTMQswCQYDVQQIEwJDQTESMBAGA1UEChMJbG9jYWxob3N0MRIwEAYDVQQL" +
+"Ewlsb2NhbGhvc3QxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0xMDAyMjYyMzIxNDBa" +
+"Fw0xMTAyMjYyMzIxNDBaMFYxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDQTESMBAG" +
+"A1UEChMJbG9jYWxob3N0MRIwEAYDVQQLEwlsb2NhbGhvc3QxEjAQBgNVBAMTCWxv" +
+"Y2FsaG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAuzPaaKVkYeWJa17r" +
+"VN8xNLCkB2r24mQxOqClJW3DHE57yRPzhC0jOF0CxBiNHP1m1Cf0NhaElCz9yz9H" +
+"fBayNbCCIUcvMZqW+yYxgne8E7xUyPvrZ8Ba7saNQCkhdzEwmgrixBSlkpupO5en" +
+"DNVR56oFyymwgOA4sKjbfcbv98ECAwEAAaOBuTCBtjAdBgNVHQ4EFgQUj3OnBK8R" +
+"UN2CcmPvfQ1/IBeFwn8wgYYGA1UdIwR/MH2AFI9zpwSvEVDdgnJj730NfyAXhcJ/" +
+"oVqkWDBWMQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEjAQBgNVBAoTCWxvY2Fs" +
+"aG9zdDESMBAGA1UECxMJbG9jYWxob3N0MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQDG" +
+"vIqFkDKRGTAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4GBAKcJWWZbHRuG" +
+"77ir1ETltxNIsAFvuhDD6E68eBwpviWfKhFxiOdD1vmAGqWWDYpmgORBGxFMZxTq" +
+"c82iSbM0LseFeHwxAfeNXosSShMFtQzKt2wKZLLQB/Oqrea32m4hU//NP8rNbTux" +
+"dcAHeNQEDB5EUUSewAlh+fUE6HB6c8j0\n" +
+"-----END CERTIFICATE-----\n\n";
+
+ protected synchronized void startAll() throws IOException {
+ if (init) {
+ System.err.println("2x init ???");
+ } else {
init = true;
+ boolean debug = false;
+ if (debug) {
+ System.setProperty("javax.net.debug", "ssl");
+ System.setProperty("jsse", "conn_state,alert,engine,record,ssocket,socket,prf");
+ Logger.getLogger("SSL").setLevel(Level.FINEST);
+ testClient.setDebug(true);
+ testClient.setDebugHttp(true);
+ }
proxy = new HttpProxyService()
.withHttpClient(testClient);
- testProxy.setPort(port);
+ testProxy = HttpServer.newServer(getProxyPort());
+ if (debug) {
+ testProxy.setDebugHttp(true);
+ testProxy.setDebug(true);
+ }
+
// dispatcher rejects 'http://'
testProxy.setHttpService(proxy);
try {
testProxy.start();
} catch (IOException e) {
- // TODO Auto-generated catch block
e.printStackTrace();
}
- port = basePort + 802;
+ testServer = HttpServer.newServer(getServerPort());
+ if (debug) {
+ testServer.setDebugHttp(true);
+ testServer.setDebug(true);
+ }
initTestCallback(testServer.getDispatcher());
- testServer.setPort(port);
try {
testServer.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
+
+// Base64 b64 = new Base64();
+// byte[] keyBytes = b64.decode(PRIVATE_KEY);
+
+ sslServer = HttpServer.newSslServer(getSslServerPort());
+
+ if (debug) {
+ sslServer.setDebug(true);
+ sslServer.setDebugHttp(true);
+ }
+ JsseSslProvider sslCon = (JsseSslProvider) sslServer.getSslProvider();
- sslCon = new SslConnector()
- .setKeysResource("org/apache/tomcat/lite/http/test.keystore",
- "changeit");
- sslServer = new HttpConnector(sslCon);
+ sslCon = sslCon
+ .setKeyRes("org/apache/tomcat/lite/http/genrsa_512.cert",
+ "org/apache/tomcat/lite/http/genrsa_512.der");
initTestCallback(sslServer.getDispatcher());
- sslServer.setPort(basePort + 443);
sslServer.start();
-
-// System.setProperty("javax.net.debug", "ssl");
-
-// Logger.getLogger("SSL").setLevel(Level.FINEST);
-// testProxy.setDebugHttp(true);
-// testProxy.setDebug(true);
-// testClient.setDebug(true);
-// testClient.setDebugHttp(true);
-// testServer.setDebugHttp(true);
-// testServer.setDebug(true);
-// sslServer.setDebug(true);
-// sslServer.setDebugHttp(true);
-
- // Bind the objects, make them visible in JMX
- // additional settings from config
- initObjectManager("org/apache/tomcat/lite/test.properties");
}
Runtime.getRuntime().addShutdownHook(new Thread() {
});
}
- public void bindConnector(HttpConnector con, final String base) {
- om.bind("HttpConnector-" + base, con);
- om.bind("HttpConnectionPool-" + base, con.cpool);
- IOConnector io = con.getIOConnector();
- int ioLevel = 0;
- while (io != null) {
- om.bind("IOConnector-" + (ioLevel++) + "-" + base, io);
- if (io instanceof SocketConnector) {
- om.bind("NioThread-" + base,
- ((SocketConnector) io).getSelector());
-
- }
- io = io.getNet();
- }
- con.cpool.setEvents(new HttpConnectionPool.HttpConnectionPoolEvents() {
-
- @Override
- public void closedConnection(RemoteServer host, HttpConnection con) {
- om.unbind("HttpConnection-" + base + "-" + con.getId());
- }
-
- @Override
- public void newConnection(RemoteServer host, HttpConnection con) {
- om.bind("HttpConnection-" + base + "-" + con.getId(), con);
- }
-
- @Override
- public void newTarget(RemoteServer host) {
- om.bind("AsyncHttp-" + base + "-" + host.target, host);
- }
-
- @Override
- public void targetRemoved(RemoteServer host) {
- om.unbind("AsyncHttp-" + base + "-" + host.target);
- }
-
- });
-
- con.setOnCreate(new HttpChannelEvents() {
- @Override
- public void onCreate(HttpChannel data, HttpConnector extraData)
- throws IOException {
- om.bind("AsyncHttp-" + base + "-" + data.getId(), data);
- }
- @Override
- public void onDestroy(HttpChannel data, HttpConnector extraData)
- throws IOException {
- om.unbind("AsyncHttp-" + base + "-" + data.getId());
- }
- });
-
-
- }
-
- private void initObjectManager(String cfgFile) {
- if (om == null) {
- om = new SimpleObjectManager();
- }
- om.register(jmx);
-
- // Additional settings, via spring-like config file
- om.loadResource(cfgFile);
-
- // initialization - using runnables
- String run = (String) om.getProperty("RUN");
- String[] runNames = run == null ? new String[] {} : run.split(",");
- for (String name: runNames) {
- Object main = om.get(name);
-
- if (main instanceof Runnable) {
- ((Runnable) main).run();
- }
- }
-
- bindConnector(testServer, "TestServer");
- bindConnector(testClient, "Client");
- bindConnector(testProxy, "Proxy");
- bindConnector(sslServer, "Https");
-
- }
-
-
/**
* Blocking get, returns when the body has been read.
*/
BBuffer out = BBuffer.allocate();
- HttpRequest aclient = DefaultHttpConnector.get().request(url);
+ HttpRequest aclient = HttpClient.newClient().request(url);
aclient.send();
aclient.readAll(out,
//Long.MAX_VALUE);//
}
- public static void main(String[] args) throws Exception, IOException {
- TestMain testMain = new TestMain();
- TestMain.defaultServer = testMain;
- testMain.om = new SimpleObjectManager(args);
- testMain.run();
- Main.waitStop();
- }
-
-
}
*
* Since I want to test keep-alive works, I use a static one
*/
- static HttpConnector httpCon = DefaultHttpConnector.get();
+ static HttpConnector httpCon = HttpClient.newClient();
/**
* Start a http server, runs on 8802 - shared by all tests.
check(sb.toString(), null);
}
- public void testLarge100() throws Exception {
- for (int i = 0; i < 100; i++) {
+ public void testLarge10() throws Exception {
+ for (int i = 0; i < 10; i++) {
testLargeIn();
cf.recycle();
}
import org.apache.tomcat.lite.TestMain;
import org.apache.tomcat.lite.io.BBuffer;
-import org.apache.tomcat.lite.io.SslConnector;
-import org.apache.tomcat.lite.util.Base64;
public class HttpsTest extends TestCase {
static int port = 8443;
- final HttpConnector httpClient = TestMain.shared().getClient();
public void testSimpleClient() throws Exception {
+ final HttpConnector httpClient = TestMain.shared().getClient();
checkResponse(httpClient);
}
public void testSimpleServer() throws Exception {
+ final HttpConnector httpClient = TestMain.shared().getClient();
BBuffer res = TestMain.getUrl("https://localhost:8443/hello");
assertTrue(res.toString().indexOf("Hello") >= 0);
}
}
public void testSimpleClient20() throws Exception {
+ final HttpConnector httpClient = TestMain.shared().getClient();
for (int i = 0; i < 10; i++) {
checkResponse(httpClient);
}
}
public void testSimpleRequestGoogle() throws Exception {
+ for (int i = 0; i < 40; i++) {
+ final HttpConnector httpClient = TestMain.shared().getClient();
HttpRequest client = httpClient.request("www.google.com", 443).
setSecure(true);
- client.getHttpChannel().setIOTimeout(2000);
+ client.getHttpChannel().setIOTimeout(2000000);
client.setRequestURI("/accounts/ServiceLogin");
client.send();
BBuffer res = client.readAll();
assertTrue(res.toString().indexOf("<title>Google Accounts</title>") > 0);
+ }
}
- /**
- * Use byte[] for cert - avoids using the store file.
- * This may be nice for:
- * - tests without a file
- * - frameworks managing configs - no need to deal with files
- * @throws Exception
- *
- */
- public void testSeverWithKeys() throws Exception {
- Base64 b64 = new Base64();
- byte[] keyBytes = b64.decode(PRIVATE_KEY);
-
- SslConnector sslCon = new SslConnector()
- .setKeys(CERTIFICATE, keyBytes);
-
- HttpConnector con = new HttpConnector(sslCon);
- con.setPort(8444);
-
- TestMain.shared().initTestCallback(con.getDispatcher());
- con.start();
-
- BBuffer res = TestMain.getUrl("https://localhost:8444" +
- "/hello");
- assertTrue(res.toString().indexOf("Hello") >= 0);
-
- }
-
-
- //byte[] encoded =
- // SslConnector.getCertificateFromStore(
- // "test/org/apache/tomcat/lite/http/test.keystore",
- // "changeit");
- //byte[] encoded =
- // SslConnector.getPrivateKeyFromStore(
- // "test/org/apache/tomcat/lite/http/test.keystore",
- // "changeit");
- //
- //byte[] b64b = b64.encode(encoded);
- //System.out.println(new String(b64b));
- static String PRIVATE_KEY =
- "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALGOFqjC4Fefz0oOcfJeS8eLV8jY" +
- "zA3sHUnTKmASfgfhG8prWUgSEq7O/849MrBysiKpIvTN8R+ykV4QCAxauGURDsNI2ZtAv23YX2Mb" +
- "cfYfYqD0tgHEn355HKey0ICgmRuq3norlUWAH3hRv5qiQMc0UIhNrmdTs0jyvQ8E8AlZAgMBAAEC" +
- "gYBybr8P2Tk5gBfbBOBPcpKocpgLLB6nQmvF7sC61nA/p8d/eBw8pNlBrMuVIkAPFHzWdee/mxMy" +
- "eKXT18U4ISgBdIKLF9LwILhIgR8CwElLucmF2OdXqFe7baBIFI6OaqLvDgOwdHSIS6uZhAWOWIAZ" +
- "38DhJbHMzPpfeBv1bAIhAQJBAPwhjzWqSWZjAfcED4htKa/ZSbdqMa1iYtveoHdXIcLuj4Ck1DKQ" +
- "EFpzLnUe2gwul/TDcoW3ZVp85jn7jwnrNDECQQC0R5LgkGdGNMBih4kPU87tHFHUnggSMyIOBnCE" +
- "XuQEN6i68VOwbdm2F7Rg1XGHD8IIJmVeiTSgLtS/mJRht6WpAkEAqs9VhQbTaTDkEOPIXiWOW1q6" +
- "rS6dbxg7XzdowNDfx3706zM/qu2clpp3u9Ll5+DdA24xtNM1L+Nz2Y5KLm8Q0QJAQqpxEx/zQNAD" +
- "EKyEL6nTTHV7gT+LRoeoIT2aYCji8vhOKgtR4l1M8/xiFKj5mXNnUjI4rDPaxR1sSQm4XUZXOQJB" +
- "AJaCD0AhacU+KaOtk65tBJ7N2dKTbc5gs/CAz1uGgJtoD/jPjELMQwrxdp6AZP6+L6osqy6zDI3W" +
- "zNHXS+wWAd0=";
-
- static String CERTIFICATE =
- "-----BEGIN CERTIFICATE-----\n" +
- "MIICUzCCAbygAwIBAgIESviASzANBgkqhkiG9w0BAQUFADBuMRAwDgYDVQQGEwdVbmtub3duMRAw" +
- "DgYDVQQIEwdVbmtub3duMRAwDgYDVQQHEwdVbmtub3duMRAwDgYDVQQKEwdVbmtub3duMRAwDgYD" +
- "VQQLEwdVbmtub3duMRIwEAYDVQQDEwlsb2NhbGhvc3QwHhcNMDkxMTA5MjA0OTE1WhcNMTAwMjA3" +
- "MjA0OTE1WjBuMRAwDgYDVQQGEwdVbmtub3duMRAwDgYDVQQIEwdVbmtub3duMRAwDgYDVQQHEwdV" +
- "bmtub3duMRAwDgYDVQQKEwdVbmtub3duMRAwDgYDVQQLEwdVbmtub3duMRIwEAYDVQQDEwlsb2Nh" +
- "bGhvc3QwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALGOFqjC4Fefz0oOcfJeS8eLV8jYzA3s" +
- "HUnTKmASfgfhG8prWUgSEq7O/849MrBysiKpIvTN8R+ykV4QCAxauGURDsNI2ZtAv23YX2MbcfYf" +
- "YqD0tgHEn355HKey0ICgmRuq3norlUWAH3hRv5qiQMc0UIhNrmdTs0jyvQ8E8AlZAgMBAAEwDQYJ" +
- "KoZIhvcNAQEFBQADgYEAPHUr1BDENlV28yIQvJOWKYbcNWLd6Cp8xCltSI897xhPpKQ5tDvs+l0g" +
- "VfdBv5+jou0F5gbCkqgclBuUnUUWsU7r4HYBLVB8FiGSy9v5yuFJWyMMLJkWAfBgzxV1nHsCPhOn" +
- "rspSB+i6bwag0i3ENXstD/Fg1lN/7l9dRpurneI=\n" +
- "-----END CERTIFICATE-----\n\n";
}
import org.apache.tomcat.lite.TestMain;
import org.apache.tomcat.lite.io.BBuffer;
-import org.apache.tomcat.lite.io.SocketConnector;
public class LiveHttp1Test extends TestCase {
// Proxy tests extend this class, run same tests via proxy on 8903
protected int clientPort = 8802;
- HttpRequest httpClient;
+ HttpRequest httpReq;
BBuffer bodyRecvBuffer = BBuffer.allocate(1024);
// DefaultHttpConnector.get().setDebugHttp(true);
TestMain.getTestServer();
- httpClient = DefaultHttpConnector.get().request("localhost",
+ httpReq = HttpClient.newClient().request("localhost",
clientPort);
bodyRecvBuffer.recycle();
}
public void tearDown() throws Exception {
- if (httpClient != null) {
- httpClient.release(); // async
- httpClient = null;
+ if (httpReq != null) {
+ httpReq.release(); // async
+ httpReq = null;
}
}
public void testSimpleRequest() throws Exception {
- httpClient.requestURI().set("/hello");
+ httpReq.requestURI().set("/hello");
- httpClient.send();
- httpClient.readAll(bodyRecvBuffer, to);
+ httpReq.send();
+ httpReq.readAll(bodyRecvBuffer, to);
assertEquals("Hello world", bodyRecvBuffer.toString());
}
public void testSimpleRequestClose() throws Exception {
- httpClient.requestURI().set("/hello");
- httpClient.setHeader("Connection", "close");
+ httpReq.requestURI().set("/hello");
+ httpReq.setHeader("Connection", "close");
- httpClient.send();
- httpClient.readAll(bodyRecvBuffer, to);
+ httpReq.send();
+ httpReq.readAll(bodyRecvBuffer, to);
assertEquals("Hello world", bodyRecvBuffer.toString());
}
public void testPoolGetRelease() throws Exception {
- HttpConnector con = new HttpConnector(new SocketConnector());
+ HttpConnector con = HttpClient.newClient();
con.setMaxHttpPoolSize(10);
HttpChannel httpCh = con.get("localhost", clientPort);
httpCh.release();
}
public void testSimpleChunkedRequest() throws Exception {
- httpClient.requestURI().set("/chunked/foo");
- httpClient.send();
- httpClient.readAll(bodyRecvBuffer, to);
+ httpReq.requestURI().set("/chunked/foo");
+ httpReq.send();
+ httpReq.readAll(bodyRecvBuffer, to);
assertTrue(bodyRecvBuffer.toString(), bodyRecvBuffer.toString().indexOf("AAA") >= 0);
}
// Check waitResponseHead()
public void testRequestHead() throws Exception {
- httpClient.requestURI().set("/echo/foo");
+ httpReq.requestURI().set("/echo/foo");
// Send the request, wait response
- httpClient.send();
+ httpReq.send();
- httpClient.readAll(bodyRecvBuffer, to);
+ httpReq.readAll(bodyRecvBuffer, to);
assertTrue(bodyRecvBuffer.toString().indexOf("GET /echo/foo") > 0);
}
}
public void notFound() throws Exception {
- httpClient.requestURI().set("/foo");
- httpClient.send();
- httpClient.readAll(bodyRecvBuffer, to);
+ httpReq.requestURI().set("/foo");
+ httpReq.send();
+ httpReq.readAll(bodyRecvBuffer, to);
}
// compression not implemented
public void testGzipRequest() throws Exception {
- httpClient.requestURI().set("/hello");
- httpClient.setHeader("accept-encoding",
+ httpReq.requestURI().set("/hello");
+ httpReq.setHeader("accept-encoding",
"gzip");
// Send the request, wait response
- httpClient.send();
+ httpReq.send();
// cstate.waitResponseHead(10000); // headers are received
// ByteChunk data = new ByteChunk(1024);
// acstate.serializeResponse(acstate.res, data);
// System.err.println(bodyRecvBuffer.toString());
- httpClient.readAll(bodyRecvBuffer, to);
+ httpReq.readAll(bodyRecvBuffer, to);
// Done
}
public void testWrongPort() throws Exception {
- httpClient = DefaultHttpConnector.get().request("localhost", 18904);
- httpClient.requestURI().set("/hello");
+ httpReq = HttpClient.newClient().request("localhost", 18904);
+ httpReq.requestURI().set("/hello");
- httpClient.send();
+ httpReq.send();
- httpClient.readAll(bodyRecvBuffer, to);
+ httpReq.readAll(bodyRecvBuffer, to);
assertEquals(0, bodyRecvBuffer.remaining());
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
-import java.util.logging.Level;
-import java.util.logging.Logger;
import junit.framework.TestCase;
public class SpdyTest extends TestCase {
HttpConnector http11Con = TestMain.shared().getClient();
- static HttpConnector spdyCon =
- new HttpConnector(new SocketConnector());
+ static HttpConnector spdyCon = HttpClient.newClient();
- static HttpConnector spdyConSsl =
- new HttpConnector(new SocketConnector());
+ static HttpConnector spdyConSsl = HttpClient.newClient();
HttpConnector memSpdyCon = new HttpConnector(null);
assertEquals(200, res.getStatus());
//assertEquals("", res.getHeader(""));
+ res.setReadTimeout(2000);
BufferedReader reader = res.getReader();
String line1 = reader.readLine();
//assertEquals("", line1);
--- /dev/null
+-----BEGIN CERTIFICATE-----
+MIICXzCCAgmgAwIBAgIJAKl2huIxu+mhMA0GCSqGSIb3DQEBBQUAMFYxCzAJBgNV
+BAYTAlVTMQswCQYDVQQIEwJDQTESMBAGA1UEChMJbG9jYWxob3N0MRIwEAYDVQQL
+Ewlsb2NhbGhvc3QxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0xMDAyMjgwNTM1NDVa
+Fw0xMTAyMjgwNTM1NDVaMFYxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDQTESMBAG
+A1UEChMJbG9jYWxob3N0MRIwEAYDVQQLEwlsb2NhbGhvc3QxEjAQBgNVBAMTCWxv
+Y2FsaG9zdDBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQCkMTUYO8aijGGXIUTMRp3h
+NTBudLHDF66MDQxomS+drL1sDGzpsLG1ltZcSPrp2Ak2tDVLd9eDb6VmddgyvE0N
+AgMBAAGjgbkwgbYwHQYDVR0OBBYEFPfuRg3nOxppwBPdpOQTbjDbcPbEMIGGBgNV
+HSMEfzB9gBT37kYN5zsaacAT3aTkE24w23D2xKFapFgwVjELMAkGA1UEBhMCVVMx
+CzAJBgNVBAgTAkNBMRIwEAYDVQQKEwlsb2NhbGhvc3QxEjAQBgNVBAsTCWxvY2Fs
+aG9zdDESMBAGA1UEAxMJbG9jYWxob3N0ggkAqXaG4jG76aEwDAYDVR0TBAUwAwEB
+/zANBgkqhkiG9w0BAQUFAANBAFqvhtdEd1OKNZ2TbLeFJbvavSZUDd0d/vz+qZgh
+L2Oe+CU/82D4lVpf52g4HFMrnEnAiJFuq1SwoNJZzlxk8kU=
+-----END CERTIFICATE-----
import junit.framework.TestCase;
import org.apache.tomcat.lite.TestMain;
+import org.apache.tomcat.lite.http.HttpClient;
import org.apache.tomcat.lite.http.HttpChannel;
import org.apache.tomcat.lite.http.HttpConnector;
import org.apache.tomcat.lite.http.HttpRequest;
HttpConnector serverCon = TestMain.shared().getTestServer();
HttpConnector spdyClient =
- new HttpConnector(new SocketConnector()).setCompression(false);
+ HttpClient.newClient().setCompression(false);
- HttpConnector spdyClientCompress =
- new HttpConnector(new SocketConnector());
+ HttpConnector spdyClientCompress =
+ HttpClient.newClient();
HttpConnector spdyClientCompressSsl =
- new HttpConnector(new SocketConnector());
+ HttpClient.newClient();
ThreadRunner tr;
static boolean dumpHeap = true;
asyncRequest(20, 500, true, false, spdyClientCompress, "AsyncSpdyComp");
}
- public void test1000AsyncSpdySsl() throws Exception {
+ public void xtest1000AsyncSpdySsl() throws Exception {
asyncRequest(10, 100, true, true, spdyClient, "AsyncSpdySsl");
}
- public void test1000AsyncSpdyCompSsl() throws Exception {
+ public void xtest1000AsyncSpdyCompSsl() throws Exception {
asyncRequest(10, 100, true, true, spdyClientCompress, "AsyncSpdyCompSsl");
}
- public void test10000AsyncSpdyCompSsl() throws Exception {
+ public void xtest10000AsyncSpdyCompSsl() throws Exception {
asyncRequest(20, 500, true, true, spdyClientCompress, "AsyncSpdyCompSsl");
}
+++ /dev/null
-RUN=JMX,Log,Socks,TomcatLite,JMXHandler
-
-JMX.(class)=org.apache.tomcat.integration.jmx.JmxObjectManagerSpi
-JMXHandler.(class)=org.apache.tomcat.integration.jmx.JmxHandler
-
-Log.(class)=org.apache.tomcat.lite.service.LogConfig
-Log.debug=org.apache.tomcat.lite.http.HttpConnector
-Log.debug=Proxy
-
-Socks.(class)=org.apache.tomcat.lite.proxy.SocksServer
-Socks.port=2080
-Socks.idleTimeout=0
-
-#HttpConnector-TestServer.debug=true
-#HttpConnector-TestServer.debugHttp=true
-xHttpConnector-TestServer.clientKeepAlive=true
-xHttpConnector-TestServer.serverKeepAlive=true
-xHttpConnector-TestServer.maxHttpPoolSize=0
-
-#HttpConnector.debug=true
-#HttpConnector.debugHttp=true
-xHttpConnector.clientKeepAlive=true
-xHttpConnector.serverKeepAlive=true
-xHttpConnector.maxHttpPoolSize=0
-
-#HttpConnector-Proxy.debug=true
-#HttpConnector-Proxy.debugHttp=true
-xHttpConnector-Proxy.clientKeepAlive=true
-xHttpConnector-Proxy.serverKeepAlive=true
-xHttpConnector-Proxy.maxHttpPoolSize=0
-
-
-#IOConnector.debug=true
-
-# Tomcat-lite config
-# include:
-# config=org/apache/tomcat/lite/config.properties
-TomcatLite.(class)=org.apache.tomcat.lite.servlet.TomcatLite
-# TomcatLite.deployListener=org.apache.tomcat.servlets.config.deploy.WebXmlContextListener
-
-# Tomcat-lite plugins
-org.apache.tomcat.lite.WebappServletMapper.(class)=org.apache.tomcat.lite.WebappServletMapper
-org.apache.tomcat.lite.WebappFilterMapper.(class)=org.apache.tomcat.lite.WebappFilterMapper
-org.apache.tomcat.servlets.session.UserSessionManager.(class)=org.apache.tomcat.servlets.session.SimpleSessionManager
-org.apache.tomcat.servlets.jsp.UserTemplateClassMapper.(class)=org.apache.tomcat.servlets.jsp.JasperCompilerTemplateClassMapper
-org.apache.tomcat.servlets.file.Filesystem.(class)=org.apache.tomcat.file.LocalFilesystem
-default-servlet.(class)=org.apache.tomcat.servlets.file.WebdavServlet
-jspwildcard-servlet.(class)=org.apache.tomcat.servlets.jsp.WildcardTemplateServlet
-filetemplate-servlet.(class)=org.apache.tomcat.servlets.jsp.JspFileTemplateServlet
-
-org.apache.tomcat.lite.Connector.(class)=org.apache.tomcat.lite.AsyncConnector
-org.apache.tomcat.lite.Connector.port=8800
-
-
-
-TomcatLite.context.1=/examples:./webapps/examples
-TomcatLite.context.2=/:./webapps/ROOT
-TomcatLite.context.3=/lite:./modules/tomcat-lite/test-webapp
-// No base dir
-TomcatLite.context.4=/dynamic:
-
-
-JMXProxyServlet.(class)=org.apache.tomcat.integration.jmx.JMXProxyServlet
--- /dev/null
+/*
+ */
+package org.apache.tomcat.test.watchdog;
+
+import java.util.Hashtable;
+
+/**
+ * Extracted from IntrospectionHelper - a simple utility class to
+ * do ant style ${property} replacements on a string, using a map
+ * holding properties. Also allows a hook for dynamic, on-demand
+ * properties.
+ *
+ * @author Costin Manolache
+ */
+public class AntProperties {
+ public static interface PropertySource {
+ public String getProperty(String key);
+ }
+
+ /**
+ * Replace ${NAME} with the property value
+ */
+ public static String replaceProperties(String value,
+ Hashtable<Object,Object> staticProp, PropertySource dynamicProp[]) {
+ if (value.indexOf("$") < 0) {
+ return value;
+ }
+ StringBuffer sb = new StringBuffer();
+ int prev = 0;
+ // assert value!=nil
+ int pos;
+ while ((pos = value.indexOf("$", prev)) >= 0) {
+ if (pos > 0) {
+ sb.append(value.substring(prev, pos));
+ }
+ if (pos == (value.length() - 1)) {
+ sb.append('$');
+ prev = pos + 1;
+ } else if (value.charAt(pos + 1) != '{') {
+ sb.append('$');
+ prev = pos + 1; // XXX
+ } else {
+ int endName = value.indexOf('}', pos);
+ if (endName < 0) {
+ sb.append(value.substring(pos));
+ prev = value.length();
+ continue;
+ }
+ String n = value.substring(pos + 2, endName);
+ String v = null;
+ if (staticProp != null) {
+ v = (String) staticProp.get(n);
+ }
+ if (v == null && dynamicProp != null) {
+ for (int i = 0; i < dynamicProp.length; i++) {
+ v = dynamicProp[i].getProperty(n);
+ if (v != null) {
+ break;
+ }
+ }
+ }
+ if (v == null)
+ v = "${" + n + "}";
+
+ sb.append(v);
+ prev = endName + 1;
+ }
+ }
+ if (prev < value.length())
+ sb.append(value.substring(prev));
+ return sb.toString();
+ }
+
+
+}
--- /dev/null
+/*
+ */
+package org.apache.tomcat.test.watchdog;
+
+import java.lang.reflect.AccessibleObject;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * Refactoring of IntrospectionUtils and modeler dynamic bean.
+ *
+ * Unlike IntrospectionUtils, the method informations can be cached.
+ * Also I hope this class will be simpler to use.
+ * There is no static cache.
+ *
+ * @author Costin Manolache
+ */
+public class DynamicObject {
+ // Based on MbeansDescriptorsIntrospectionSource
+
+ private static Logger log = Logger.getLogger(DynamicObject.class.getName());
+
+ private static Class<?> NO_PARAMS[] = new Class[0];
+
+
+ private static String strArray[] = new String[0];
+
+ private static Class<?>[] supportedTypes = new Class[] { Boolean.class,
+ Boolean.TYPE, Byte.class, Byte.TYPE, Character.class,
+ Character.TYPE, Short.class, Short.TYPE, Integer.class,
+ Integer.TYPE, Long.class, Long.TYPE, Float.class, Float.TYPE,
+ Double.class, Double.TYPE, String.class, strArray.getClass(),
+ BigDecimal.class, BigInteger.class, AtomicInteger.class,
+ AtomicLong.class, java.io.File.class, };
+
+
+ private Class realClass;
+
+ // Method or Field
+ private Map<String, AccessibleObject> getAttMap;
+
+ public DynamicObject(Class beanClass) {
+ this.realClass = beanClass;
+ initCache();
+ }
+
+ private void initCache() {
+ Method methods[] = null;
+
+ getAttMap = new HashMap<String, AccessibleObject>();
+
+ methods = realClass.getMethods();
+ for (int j = 0; j < methods.length; ++j) {
+ if (ignorable(methods[j])) {
+ continue;
+ }
+ String name = methods[j].getName();
+
+ Class<?> params[] = methods[j].getParameterTypes();
+
+ if (name.startsWith("get") && params.length == 0) {
+ Class<?> ret = methods[j].getReturnType();
+ if (!supportedType(ret)) {
+ if (log.isLoggable(Level.FINE))
+ log.fine("Unsupported type " + methods[j]);
+ continue;
+ }
+ name = unCapitalize(name.substring(3));
+
+ getAttMap.put(name, methods[j]);
+ } else if (name.startsWith("is") && params.length == 0) {
+ Class<?> ret = methods[j].getReturnType();
+ if (Boolean.TYPE != ret) {
+ if (log.isLoggable(Level.FINE))
+ log.fine("Unsupported type " + methods[j] + " " + ret);
+ continue;
+ }
+ name = unCapitalize(name.substring(2));
+
+ getAttMap.put(name, methods[j]);
+ }
+ }
+ // non-private AtomicInteger and AtomicLong - stats
+ Field fields[] = realClass.getFields();
+ for (int j = 0; j < fields.length; ++j) {
+ if (fields[j].getType() == AtomicInteger.class) {
+ getAttMap.put(fields[j].getName(), fields[j]);
+ }
+ }
+
+ }
+
+ public List<String> attributeNames() {
+ return new ArrayList<String>(getAttMap.keySet());
+ }
+
+
+ public Object invoke(Object proxy, String method) throws Exception {
+ Method executeM = null;
+ Class<?> c = proxy.getClass();
+ executeM = c.getMethod(method, NO_PARAMS);
+ if (executeM == null) {
+ throw new RuntimeException("No execute in " + proxy.getClass());
+ }
+ return executeM.invoke(proxy, (Object[]) null);
+ }
+
+ // TODO
+// public Object invoke(String method, Object[] params) {
+// return null;
+// }
+
+ public Object getAttribute(Object o, String att) {
+ AccessibleObject m = getAttMap.get(att);
+ if (m instanceof Method) {
+ try {
+ return ((Method) m).invoke(o);
+ } catch (Throwable e) {
+ log.log(Level.INFO, "Error getting attribute " + realClass + " "
+ + att, e);
+ return null;
+ }
+ } if (m instanceof Field) {
+ if (((Field) m).getType() == AtomicInteger.class) {
+ try {
+ Object value = ((Field) m).get(o);
+ return ((AtomicInteger) value).get();
+ } catch (Throwable e) {
+ return null;
+ }
+ } else {
+ return null;
+ }
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Set an object-type attribute.
+ *
+ * Use setProperty to use a string value and convert it to the
+ * specific (primitive) type.
+ */
+ public boolean setAttribute(Object proxy, String name, Object value) {
+ // TODO: use the cache...
+ String methodName = "set" + capitalize(name);
+ Method[] methods = proxy.getClass().getMethods();
+ for (Method m : methods) {
+ Class<?>[] paramT = m.getParameterTypes();
+ if (methodName.equals(m.getName())
+ && paramT.length == 1
+ && (value == null || paramT[0].isAssignableFrom(value
+ .getClass()))) {
+ try {
+ m.invoke(proxy, value);
+ return true;
+ } catch (IllegalArgumentException e) {
+ log.severe("Error setting: " + name + " "
+ + proxy.getClass().getName() + " " + e);
+ } catch (IllegalAccessException e) {
+ log.severe("Error setting: " + name + " "
+ + proxy.getClass().getName() + " " + e);
+ } catch (InvocationTargetException e) {
+ log.severe("Error setting: " + name + " "
+ + proxy.getClass().getName() + " " + e);
+ }
+ }
+ }
+ return false;
+ }
+
+ public boolean setProperty(Object proxy, String name, String value) {
+ // TODO: use the cache...
+ String setter = "set" + capitalize(name);
+
+ try {
+ Method methods[] = proxy.getClass().getMethods();
+
+ Method setPropertyMethod = null;
+
+ // First, the ideal case - a setFoo( String ) method
+ for (int i = 0; i < methods.length; i++) {
+ if (ignorable(methods[i])) {
+ continue;
+ }
+ Class<?> paramT[] = methods[i].getParameterTypes();
+ if (setter.equals(methods[i].getName()) && paramT.length == 1) {
+ if ("java.lang.String".equals(paramT[0].getName())) {
+ methods[i].invoke(proxy, new Object[] { value });
+ return true;
+ } else {
+ // match - find the type and invoke it
+ Class<?> paramType = methods[i].getParameterTypes()[0];
+ Object params[] = new Object[1];
+ params[0] = convert(value, paramType);
+ if (params[0] != null) {
+ methods[i].invoke(proxy, params);
+ return true;
+ }
+ }
+ }
+ // save "setProperty" for later
+ if ("setProperty".equals(methods[i].getName()) &&
+ paramT.length == 2 &&
+ paramT[0] == String.class &&
+ paramT[1] == String.class) {
+ setPropertyMethod = methods[i];
+ }
+ }
+
+ try {
+ Field field = proxy.getClass().getField(name);
+ if (field != null) {
+ Object conv = convert(value, field.getType());
+ if (conv != null) {
+ field.set(proxy, conv);
+ return true;
+ }
+ }
+ } catch (NoSuchFieldException e) {
+ // ignore
+ }
+
+ // Ok, no setXXX found, try a setProperty("name", "value")
+ if (setPropertyMethod != null) {
+ Object params[] = new Object[2];
+ params[0] = name;
+ params[1] = value;
+ setPropertyMethod.invoke(proxy, params);
+ return true;
+ }
+
+ } catch (Throwable ex2) {
+ log.log(Level.WARNING, "IAE " + proxy + " " + name + " " + value,
+ ex2);
+ }
+ return false;
+ }
+
+ // ----------- Helpers ------------------
+
+ static Object convert(String object, Class<?> paramType) {
+ Object result = null;
+ if ("java.lang.String".equals(paramType.getName())) {
+ result = object;
+ } else if ("java.lang.Long".equals(paramType.getName())
+ || "long".equals(paramType.getName())) {
+ try {
+ result = Long.parseLong(object);
+ } catch (NumberFormatException ex) {
+ }
+ // Try a setFoo ( boolean )
+ } else if ("java.lang.Integer".equals(paramType.getName())
+ || "int".equals(paramType.getName())) {
+ try {
+ result = new Integer(object);
+ } catch (NumberFormatException ex) {
+ }
+ // Try a setFoo ( boolean )
+ } else if ("java.lang.Boolean".equals(paramType.getName())
+ || "boolean".equals(paramType.getName())) {
+ result = new Boolean(object);
+ } else {
+ log.info("Unknown type " + paramType.getName());
+ }
+ if (result == null) {
+ throw new IllegalArgumentException("Can't convert argument: "
+ + object + " to " + paramType );
+ }
+ return result;
+ }
+
+ /**
+ * Converts the first character of the given String into lower-case.
+ *
+ * @param name
+ * The string to convert
+ * @return String
+ */
+ static String unCapitalize(String name) {
+ if (name == null || name.length() == 0) {
+ return name;
+ }
+ char chars[] = name.toCharArray();
+ chars[0] = Character.toLowerCase(chars[0]);
+ return new String(chars);
+ }
+
+ /**
+ * Check if this class is one of the supported types. If the class is
+ * supported, returns true. Otherwise, returns false.
+ *
+ * @param ret
+ * The class to check
+ * @return boolean True if class is supported
+ */
+ static boolean supportedType(Class<?> ret) {
+ for (int i = 0; i < supportedTypes.length; i++) {
+ if (ret == supportedTypes[i]) {
+ return true;
+ }
+ }
+ if (isBeanCompatible(ret)) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Check if this class conforms to JavaBeans specifications. If the class is
+ * conformant, returns true.
+ *
+ * @param javaType
+ * The class to check
+ * @return boolean True if the class is compatible.
+ */
+ static boolean isBeanCompatible(Class<?> javaType) {
+ // Must be a non-primitive and non array
+ if (javaType.isArray() || javaType.isPrimitive()) {
+ return false;
+ }
+
+ // Anything in the java or javax package that
+ // does not have a defined mapping is excluded.
+ if (javaType.getName().startsWith("java.")
+ || javaType.getName().startsWith("javax.")) {
+ return false;
+ }
+
+ try {
+ javaType.getConstructor(new Class[] {});
+ } catch (java.lang.NoSuchMethodException e) {
+ return false;
+ }
+
+ // Make sure superclass is compatible
+ Class<?> superClass = javaType.getSuperclass();
+ if (superClass != null && superClass != java.lang.Object.class
+ && superClass != java.lang.Exception.class
+ && superClass != java.lang.Throwable.class) {
+ if (!isBeanCompatible(superClass)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Reverse of Introspector.decapitalize
+ */
+ static String capitalize(String name) {
+ if (name == null || name.length() == 0) {
+ return name;
+ }
+ char chars[] = name.toCharArray();
+ chars[0] = Character.toUpperCase(chars[0]);
+ return new String(chars);
+ }
+
+ private boolean ignorable(Method method) {
+ if (Modifier.isStatic(method.getModifiers()))
+ return true;
+ if (!Modifier.isPublic(method.getModifiers())) {
+ return true;
+ }
+ if (method.getDeclaringClass() == Object.class)
+ return true;
+ return false;
+ }
+
+
+}
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
+import java.io.InputStream;
+import java.io.StringReader;
import java.util.Properties;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import junit.framework.Test;
import junit.framework.TestResult;
import junit.framework.TestSuite;
-import org.apache.tomcat.servlets.config.deploy.DomUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
+import org.xml.sax.EntityResolver;
+import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class WatchdogClient {
return getSuite(port);
}
+ public static class NullResolver implements EntityResolver {
+ public InputSource resolveEntity (String publicId,
+ String systemId)
+ throws SAXException, IOException
+ {
+ return new InputSource(new StringReader(""));
+ }
+ }
+
+ /** Read XML as DOM.
+ */
+ public static Document readXml(InputStream is)
+ throws SAXException, IOException, ParserConfigurationException
+ {
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ dbf.setValidating(false);
+ dbf.setIgnoringComments(false);
+ dbf.setIgnoringElementContentWhitespace(true);
+ DocumentBuilder db = null;
+ db = dbf.newDocumentBuilder();
+ db.setEntityResolver( new NullResolver() );
+ Document doc = db.parse(is);
+ return doc;
+ }
+
/**
* Return a test suite for running a watchdog-like
* test file.
try {
- Document doc = DomUtil.readXml(new FileInputStream(file));
+ Document doc = readXml(new FileInputStream(file));
Element docE = doc.getDocumentElement();
NodeList targetsL = docE.getElementsByTagName("target");
for (int i = 0; i < targetsL.getLength(); i++) {
import junit.framework.Test;
import junit.framework.TestResult;
-import org.apache.tomcat.integration.DynamicObject;
-import org.apache.tomcat.integration.simple.AntProperties;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;