⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 httpservertestbase.java

📁 jetty SERVER連接資料庫用的軟體
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
//========================================================================//Copyright 2004-2008 Mort Bay Consulting Pty. Ltd.//------------------------------------------------------------------------//Licensed under the Apache License, Version 2.0 (the "License");//you may not use this file except in compliance with the License.//You may obtain a copy of the License at //http://www.apache.org/licenses/LICENSE-2.0//Unless required by applicable law or agreed to in writing, software//distributed under the License is distributed on an "AS IS" BASIS,//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.//See the License for the specific language governing permissions and//limitations under the License.//========================================================================package org.mortbay.jetty;import java.io.BufferedReader;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.LineNumberReader;import java.io.OutputStream;import java.io.PrintWriter;import java.io.Writer;import java.net.Socket;import java.net.URL;import java.util.Arrays;import java.util.Random;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import junit.framework.TestCase;import org.mortbay.jetty.handler.AbstractHandler;import org.mortbay.thread.BoundedThreadPool;import org.mortbay.util.IO;/** * HttpServer Tester. */public class HttpServerTestBase extends TestCase{    private static boolean stress=Boolean.getBoolean("STRESS");        // ~ Static fields/initializers    // ---------------------------------------------    /** The request. */    private static final String REQUEST1_HEADER="POST / HTTP/1.0\n"+"Host: localhost\n"+"Content-Type: text/xml; charset=utf-8\n"+"Connection: close\n"+"Content-Length: ";    private static final String REQUEST1_CONTENT="<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"            +"<nimbus xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"+"        xsi:noNamespaceSchemaLocation=\"nimbus.xsd\" version=\"1.0\">\n"            +"</nimbus>";    private static final String REQUEST1=REQUEST1_HEADER+REQUEST1_CONTENT.getBytes().length+"\n\n"+REQUEST1_CONTENT;    /** The expected response. */    private static final String RESPONSE1="HTTP/1.1 200 OK\n"+"Connection: close\n"+"Server: Jetty(6.1.x)\n"+"\n"+"Hello world\n";    // Break the request up into three pieces, splitting the header.    private static final String FRAGMENT1=REQUEST1.substring(0,16);    private static final String FRAGMENT2=REQUEST1.substring(16,34);    private static final String FRAGMENT3=REQUEST1.substring(34);    /** Second test request. */    private static final String REQUEST2_HEADER="POST / HTTP/1.0\n"+"Host: localhost\n"+"Content-Type: text/xml\n"+"Content-Length: ";    private static final String REQUEST2_CONTENT="<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"            +"<nimbus xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"+"        xsi:noNamespaceSchemaLocation=\"nimbus.xsd\" version=\"1.0\">\n"            +"    <request requestId=\"1\">\n"+"        <getJobDetails>\n"+"            <jobId>73</jobId>\n"+"        </getJobDetails>\n"+"    </request>\n"            +"</nimbus>";    private static final String REQUEST2=REQUEST2_HEADER+REQUEST2_CONTENT.getBytes().length+"\n\n"+REQUEST2_CONTENT;    private static final String RESPONSE2_CONTENT=            "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"+            "<nimbus xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"+            "        xsi:noNamespaceSchemaLocation=\"nimbus.xsd\" version=\"1.0\">\n"+            "    <request requestId=\"1\">\n"+            "        <getJobDetails>\n"+            "            <jobId>73</jobId>\n"+            "        </getJobDetails>\n"+            "    </request>\n"            +"</nimbus>\n";    private static final String RESPONSE2=        "HTTP/1.1 200 OK\n"+        "Content-Type: text/xml; charset=iso-8859-1\n"+        "Content-Length: "+RESPONSE2_CONTENT.getBytes().length+"\n"+        "Server: Jetty(6.1.x)\n"+        "\n"+        RESPONSE2_CONTENT;    // Useful constants    private static final long PAUSE=15L;    private static final int LOOPS=stress?250:25;    private static final String HOST="localhost";    private Connector _connector;    private int port=0;    protected void tearDown() throws Exception    {        super.tearDown();        Thread.sleep(100);    }    // ~ Methods    // ----------------------------------------------------------------    /**     * Feed the server the entire request at once.     *      * @throws Exception     * @throws InterruptedException     */    public void testRequest1_jetty() throws Exception, InterruptedException    {        Server server=startServer(new HelloWorldHandler());        Socket client=new Socket(HOST,port);        OutputStream os=client.getOutputStream();        os.write(REQUEST1.getBytes());        os.flush();        // Read the response.        String response=readResponse(client);        // Shut down        client.close();        server.stop();        // Check the response        assertEquals("response",RESPONSE1,response);    }    /* --------------------------------------------------------------- */    public void testFragmentedChunk() throws Exception    {        Server server=startServer(new EchoHandler());        Socket client=new Socket(HOST,port);        OutputStream os=client.getOutputStream();        os.write(("GET /R2 HTTP/1.1\015\012"+"Host: localhost\015\012"+"Transfer-Encoding: chunked\015\012"+"Content-Type: text/plain\015\012"                +"Connection: close\015\012"+"\015\012").getBytes());        os.flush();        Thread.sleep(PAUSE);        os.write(("5\015\012").getBytes());        os.flush();        Thread.sleep(PAUSE);        os.write(("ABCDE\015\012"+"0;\015\012\015\012").getBytes());        os.flush();        // Read the response.        String response=readResponse(client);        // Shut down        client.close();        server.stop();        assertTrue(true); // nothing checked yet.    }    /**     * Feed the server fragmentary headers and see how it copes with it.     *      * @throws Exception     * @throws InterruptedException     */    public void testRequest1Fragments_jetty() throws Exception, InterruptedException    {        Server server=startServer(new HelloWorldHandler());        String response;        try        {            Socket client=new Socket(HOST,port);            OutputStream os=client.getOutputStream();            // Write a fragment, flush, sleep, write the next fragment, etc.            os.write(FRAGMENT1.getBytes());            os.flush();            Thread.sleep(PAUSE);            os.write(FRAGMENT2.getBytes());            os.flush();            Thread.sleep(PAUSE);            os.write(FRAGMENT3.getBytes());            os.flush();            // Read the response            response=readResponse(client);            // Shut down            client.close();        }        finally        {            server.stop();        }        // Check the response        assertEquals("response",RESPONSE1,response);    }    public void testRequest2_jetty() throws Exception    {        byte[] bytes=REQUEST2.getBytes();        Server server=startServer(new EchoHandler());        try        {            for (int i=0; i<LOOPS; i++)            {                Socket client=new Socket(HOST,port);                OutputStream os=client.getOutputStream();                os.write(bytes);                os.flush();                // Read the response                String response=readResponse(client);                client.close();                // Check the response                assertEquals("response "+i,RESPONSE2,response);            }        }        finally        {            // Shut down            server.stop();        }    }    /**     * @throws Exception     */    public void testRequest2Fragments_jetty() throws Exception    {        Random random=new Random(System.currentTimeMillis());        byte[] bytes=REQUEST2.getBytes();        final int pointCount=2;        Server server=startServer(new EchoHandler());        try        {            for (int i=0; i<LOOPS; i++)            {                int[] points=new int[pointCount];                StringBuffer message=new StringBuffer();                message.append("iteration #"+(i+1));                // Pick fragment points at random                for (int j=0; j<points.length; ++j)                {                    points[j]=random.nextInt(bytes.length);                }                // Sort the list                Arrays.sort(points);                Socket client=new Socket(HOST,port);                OutputStream os=client.getOutputStream();                writeFragments(bytes,points,message,os);                // Read the response                String response=readResponse(client);                // Close the client                client.close();                // Check the response                assertEquals("response for "+i+" "+message.toString(),RESPONSE2,response);            }        }        finally        {            // Shut down            server.stop();        }    }    public void testRequest2Iterate_jetty() throws Exception    {        byte[] bytes=REQUEST2.getBytes();        Server server=startServer(new EchoHandler());        try        {            for (int i=0; i<bytes.length; i+=3)            {                int[] points=new int[] { i };                StringBuffer message=new StringBuffer();                message.append("iteration #"+(i+1));                // Sort the list                Arrays.sort(points);                Socket client=new Socket(HOST,port);                OutputStream os=client.getOutputStream();                writeFragments(bytes,points,message,os);                // Read the response                String response=readResponse(client);                // Close the client                client.close();                // Check the response                assertEquals("response for "+i+" "+message.toString(),RESPONSE2,response);            }        }        finally        {            // Shut down            server.stop();        }    }    /**     * After several iterations, I generated some known bad fragment points.     *      * @throws Exception     */    public void testRequest2KnownBad_jetty() throws Exception    {        byte[] bytes=REQUEST2.getBytes();        int[][] badPoints=new int[][]        {        { 70 }, // beginning here, drops last line of request                { 71 }, // no response at all                { 72 }, // again starts drops last line of request                { 74 }, // again, no response at all        };        Server server=startServer(new EchoHandler());        try        {            for (int i=0; i<badPoints.length; ++i)            {                Socket client=new Socket(HOST,port);                OutputStream os=client.getOutputStream();                StringBuffer message=new StringBuffer();                message.append("iteration #"+(i+1));                writeFragments(bytes,badPoints[i],message,os);                // Read the response                String response=readResponse(client);                // Close the client                client.close();                // Check the response                // TODO - change to equals when code gets fixed                assertNotSame("response for "+message.toString(),RESPONSE2,response);            }        }        finally        {            // Shut down            server.stop();        }    }    /**     * After several iterations, I generated some known bad fragment points.     *      * @throws Exception     */    public void testFlush() throws Exception    {        Server server=startServer(new DataHandler());        try        {               String[] encoding = {"NONE","UTF-8","ISO-8859-1","ISO-8859-2"};            for (int e =0; e<encoding.length;e++)            {                for (int b=1;b<=128;b=b==1?2:b==2?32:b==32?128:129)                {                    for (int w=41;w<42;w+=4096)                    {                        for (int c=0;c<1;c++)                        {                            String test=encoding[e]+"x"+b+"x"+w+"x"+c;                            URL url=new URL("http://"+HOST+":"+port+"/?writes="+w+"&block="+b+ (e==0?"":("&encoding="+encoding[e]))+(c==0?"&chars=true":""));                            InputStream in = (InputStream)url.getContent();                            String response=IO.toString(in,e==0?null:encoding[e]);                                                        assertEquals(test,b*w,response.length());                        }                    }                }            }        }        finally        {            // Shut down            server.stop();            Thread.yield();        }    }    /**     * After several iterations, I generated some known bad fragment points.     *      * @throws Exception     */    public void testReadWriteBlocking() throws Exception    {        Server server=startServer(new DataHandler());        try        {               long start=System.currentTimeMillis();            Socket client=new Socket(HOST,port);            OutputStream os=client.getOutputStream();            InputStream is=client.getInputStream();            os.write((                    "GET /data?writes=1024&block=256 HTTP/1.1\r\n"+                    "host: "+HOST+":"+port+"\r\n"+                    "connection: close\r\n"+                    "content-type: unknown\r\n"+                    "content-length: 30\r\n"+                    "\r\n"            ).getBytes());            os.flush();            Thread.sleep(200);            os.write((                    "\r\n23456890"            ).getBytes());

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -