📄 servletservertest.java
字号:
package org.placelab.proxy;import java.io.InputStream;import java.net.URL;import java.util.Hashtable;import org.placelab.test.TestResult;import org.placelab.test.Testable;public class ServletServerTest implements Testable { public int testPort = 6543; public String SUCCESS_STR = "Test was successful"; public String getName() { return "ServletServerTest";} public void runTests(TestResult result) { ServletServer ss = null; try { ss = new ServletServer(testPort); ServletServer.addServlet("/test",new TestServlet()); ss.startServer(); test404(ss,result); testServletNotOk(ss,result); testServletOk(ss,result); } catch (Exception ex) { result.errorCaught(this,ex); } finally { if (ss != null) { ss.stopServer(); } } } private void test404(ServletServer ss,TestResult result) throws Exception { URL u = new URL("http", // protocol, "localhost", // host name or IP of proxy server to use testPort, // proxy port "http://localhost/bogusbogus"); // a bogus URL try { u.openStream(); } catch (Exception ex) { result.assertTrue(this,true,true,"Ensure the 404 failed properly"); return; } result.fail(this,"404 was unrecognized"); } private void testServletOk(ServletServer ss,TestResult result) throws Exception { URL u = new URL("http", // protocol, "localhost", // host name or IP of proxy server to use testPort, // proxy port "/test/good"); // a bogus URL InputStream is = u.openStream(); byte[] buf = new byte[1024]; StringBuffer page = new StringBuffer(); boolean done = false; while (is.available() > 0) { int read = is.read(buf); if (read == -1) { done = true; } else { page.append(new String(buf,0,read)); } } String str = page.toString(); result.assertTrue(this,SUCCESS_STR.trim(),str.trim(),"Ensure that the servlet was properly invoked"); } private void testServletNotOk(ServletServer ss,TestResult result) throws Exception { URL u = new URL("http", // protocol, "localhost", // host name or IP of proxy server to use testPort, // proxy port "/test/bad"); // a bogus URL try { u.openStream(); } catch (Exception ex) { result.assertTrue(this,true,true,"Ensure the Servlet 404 failed properly"); return; } result.fail(this,"Servlet 404 was unrecognized"); } public class TestServlet implements Servlet { public String getName() { return "Test Servlet"; } public HTTPResponse serviceRequest(HTTPRequest req) { if (req.url.getPath().endsWith("/bad")) { // send back a 404 return new HTTPResponse(HTTPResponse.RESPONSE_NOT_FOUND, "text/html", -1, null); }; if (req.url.getPath().endsWith("/good")) { // send back good content return new HTTPResponse(HTTPResponse.RESPONSE_OK, "text/html", SUCCESS_STR.getBytes()); } String unknownMsg = "This should never be seen."; return new HTTPResponse(HTTPResponse.RESPONSE_OK, "text/html", unknownMsg.length(), unknownMsg.getBytes()); } public Hashtable injectHeaders(HTTPRequest req) { return null; } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -