source: trunk/autoquest-httpmonitor-test/src/test/java/de/ugoe/cs/autoquest/httpmonitor/AbstractTC.java @ 1567

Last change on this file since 1567 was 1567, checked in by pharms, 10 years ago
  • next solved issue with reused buffers
File size: 8.1 KB
Line 
1//   Copyright 2012 Georg-August-Universität Göttingen, Germany
2//
3//   Licensed under the Apache License, Version 2.0 (the "License");
4//   you may not use this file except in compliance with the License.
5//   You may obtain a copy of the License at
6//
7//       http://www.apache.org/licenses/LICENSE-2.0
8//
9//   Unless required by applicable law or agreed to in writing, software
10//   distributed under the License is distributed on an "AS IS" BASIS,
11//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//   See the License for the specific language governing permissions and
13//   limitations under the License.
14
15package de.ugoe.cs.autoquest.httpmonitor;
16
17import static org.junit.Assert.assertEquals;
18import static org.junit.Assert.assertNotNull;
19import static org.junit.Assert.assertTrue;
20
21import java.io.BufferedReader;
22import java.io.File;
23import java.io.IOException;
24import java.io.InputStream;
25import java.io.InputStreamReader;
26import java.util.logging.Level;
27
28import org.apache.catalina.Context;
29import org.apache.catalina.startup.Tomcat;
30import org.apache.http.HttpEntity;
31import org.apache.http.HttpResponse;
32import org.apache.http.client.methods.HttpGet;
33import org.apache.http.client.methods.HttpPost;
34import org.apache.http.client.methods.HttpRequestBase;
35import org.apache.http.entity.ContentType;
36import org.apache.http.entity.StringEntity;
37import org.apache.http.impl.client.DefaultHttpClient;
38import org.junit.After;
39import org.junit.Before;
40
41import de.ugoe.cs.autoquest.eventcore.Event;
42import de.ugoe.cs.autoquest.plugin.http.eventcore.HTTPEventType;
43import de.ugoe.cs.autoquest.plugin.http.eventcore.HTTPTarget;
44import de.ugoe.cs.autoquest.plugin.http.logdata.HttpExchange;
45import de.ugoe.cs.autoquest.plugin.http.logdata.Method;
46import de.ugoe.cs.util.console.TextConsole;
47
48/**
49 *
50 */
51public abstract class AbstractTC {
52   
53    /**
54     *
55     */
56    protected static final TextConsole CONSOLE = new TextConsole(Level.FINEST);
57   
58    /**
59     *
60     */
61    protected final static String LOG_FILE_DIR = "target/tmp/logfiles/";
62   
63    /**
64     *
65     */
66    protected static final int DUMMY_SERVER_PORT = 19098;
67   
68    /**
69     *
70     */
71    protected static final int PROXY_PORT = 19099;
72   
73    /**
74     *
75     */
76    protected static final int MONITOR_PORT = 19100;
77   
78    /**
79     * the servlet of the dummy web server responding to requests
80     */
81    private DummyServlet dummyServlet;
82   
83    /** */
84    private static Tomcat tomcat = new Tomcat();
85   
86    /**
87     *
88     */
89    static String readStreamContentToString(InputStream stream) throws IOException {
90        return readToString(new BufferedReader(new InputStreamReader(stream)));
91    }
92   
93    /**
94     *
95     */
96    static String readToString(BufferedReader reader) throws IOException {
97        StringBuffer message = new StringBuffer();
98       
99        String line = reader.readLine();
100        while (line != null) {
101            System.err.println(line);
102            if (message.length() > 0) {
103                message.append('\n');
104            }
105            message.append(line);
106            line = reader.readLine();
107        }
108       
109        return message.toString();
110    }
111
112    /**
113     *
114     */
115    @Before
116    public void setUp() throws Exception {
117        // setup a simple HTTP server
118        dummyServlet = new DummyServlet();
119       
120        /*dummyServer = new Server(DUMMY_SERVER_PORT);
121       
122        ServletContextHandler root =
123            new ServletContextHandler(dummyServer, "/dummyServer", ServletContextHandler.SESSIONS);
124
125       
126        root.addServlet(new ServletHolder(dummyServlet), "/*");
127       
128        dummyServer.start();*/
129       
130        File tomcatDir = new File("target/test/tomcat");
131        File webappRootDir = new File(tomcatDir, "webapp");
132       
133        tomcat = new Tomcat();
134        tomcat.setPort(DUMMY_SERVER_PORT);
135        tomcat.setBaseDir(tomcatDir.getAbsolutePath());
136
137        File warFile = new File(webappRootDir, "dummyService.war");
138        tomcat.addWebapp("/dummyWebapp", warFile.getAbsolutePath());
139        System.out.println("configuring Dummy Service from " + warFile.getAbsolutePath());
140       
141        File servletRootDir = new File(tomcatDir, "servlet");
142        servletRootDir.mkdirs();
143        Context ctx = tomcat.addContext("/", servletRootDir.getAbsolutePath());
144        Tomcat.addServlet(ctx, "dummyServlet", dummyServlet);
145        ctx.addServletMapping("/dummyServlet", "dummyServlet");
146       
147        tomcat.start();
148       
149        setUpHook();
150    }
151
152    /**
153     *
154     */
155    protected abstract void setUpHook() throws Exception;
156
157    /**
158     *
159     */
160    @After
161    public void tearDown() throws Exception {
162        // give all started servers a second to finalize their internal work after the test
163        // execution. This prevents some unnecessary exceptions due to requests already processed
164        // by the test case but not finalized on server side.
165        Thread.sleep(1000);
166        tearDownHook();
167
168        if (tomcat != null) {
169            try {
170                tomcat.stop();
171                tomcat.getServer().await();
172                tomcat.destroy();
173            }
174            finally {
175                tomcat = null;
176            }
177        }
178       
179        deleteFiles(new File(LOG_FILE_DIR));
180    }
181
182    /**
183     *
184     */
185    protected abstract void tearDownHook() throws Exception;
186
187    /**
188     *
189     */
190    protected String sendDummyMessage(String type, String message, String respMsg)
191        throws Exception
192    {
193        dummyServlet.setResponse(respMsg);
194       
195        System.err.println("sending message: " + message);
196        DefaultHttpClient httpclient = new DefaultHttpClient();
197        HttpRequestBase httpRequest = null;
198       
199        if ("POST".equals(type)) {
200            httpRequest = new HttpPost("http://localhost:" + PROXY_PORT + "/dummyServlet");
201            HttpEntity entity = new StringEntity(message, ContentType.TEXT_PLAIN);
202            ((HttpPost) httpRequest).setEntity(entity);
203        }
204        else if ("GET".equals(type)) {
205            httpRequest = new HttpGet("http://localhost:" + PROXY_PORT + "/dummyServlet");
206        }
207       
208        try {
209            HttpResponse response = httpclient.execute(httpRequest);
210           
211            assertEquals(message, dummyServlet.getRequest());
212            System.err.println(response.getStatusLine());
213            String responseStr = readStreamContentToString(response.getEntity().getContent());
214            System.err.println("received response: " + responseStr);
215            return responseStr;
216        }
217        finally {
218            httpRequest.releaseConnection();
219        }
220    }
221   
222    /**
223     *
224     */
225    protected void assertEvent(Event event, String method, String message, String response) {
226        assertNotNull(event);
227        assertNotNull(event.getType());
228        assertNotNull(event.getTarget());
229       
230        assertTrue(event.getType() instanceof HTTPEventType);
231        assertTrue(event.getTarget() instanceof HTTPTarget);
232       
233        HttpExchange exchange = ((HTTPEventType) event.getType()).getExchange();
234       
235        assertEquals(Method.fromValue(method), exchange.getRequest().getMethod());
236       
237        if (message != null) {
238            assertEquals(message, exchange.getRequest().getContent().getData());
239        }
240        else if (exchange.getRequest().getContent() != null) {
241            System.err.println(exchange.getRequest().getContent().getData());
242        }
243       
244        if (response != null) {
245            assertEquals(response, exchange.getResponse().getContent().getData());
246        }
247        else if (exchange.getResponse().getContent() != null) {
248            System.err.println(exchange.getResponse().getContent().getData());
249        }
250    }
251
252    /**
253     *
254     */
255    protected void deleteFiles(File file) {
256        if (file.exists()) {
257            if (file.isDirectory()) {
258                for (File child : file.listFiles()) {
259                    deleteFiles(child);
260                }
261            }
262           
263            try {
264                file.delete();
265            }
266            catch (Exception e) {
267                // ignore and delete as much as possible
268            }
269        }
270    }
271
272}
Note: See TracBrowser for help on using the repository browser.