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

Last change on this file was 2232, checked in by pharms, 7 years ago
  • solved some findbugs issues
File size: 9.5 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;
20import static org.junit.Assert.fail;
21
22import java.io.BufferedReader;
23import java.io.File;
24import java.io.IOException;
25import java.io.InputStream;
26import java.io.InputStreamReader;
27import java.util.logging.Level;
28
29import org.apache.catalina.Context;
30import org.apache.catalina.startup.Tomcat;
31import org.apache.http.HttpEntity;
32import org.apache.http.HttpResponse;
33import org.apache.http.client.methods.HttpGet;
34import org.apache.http.client.methods.HttpPost;
35import org.apache.http.client.methods.HttpRequestBase;
36import org.apache.http.entity.ContentType;
37import org.apache.http.entity.StringEntity;
38import org.apache.http.impl.client.DefaultHttpClient;
39import org.junit.After;
40import org.junit.Before;
41
42import de.ugoe.cs.autoquest.eventcore.Event;
43import de.ugoe.cs.autoquest.plugin.http.eventcore.HTTPEventType;
44import de.ugoe.cs.autoquest.plugin.http.eventcore.HTTPTarget;
45import de.ugoe.cs.autoquest.plugin.http.logdata.HttpExchange;
46import de.ugoe.cs.autoquest.plugin.http.logdata.Method;
47import de.ugoe.cs.util.console.TextConsole;
48
49/**
50 *
51 */
52public abstract class AbstractTC {
53   
54    /**
55     *
56     */
57    protected static final TextConsole CONSOLE = new TextConsole(Level.FINEST);
58   
59    /**
60     *
61     */
62    protected final static String LOG_FILE_DIR = "target/tmp/logfiles/";
63   
64    /**
65     *
66     */
67    protected static final int DUMMY_SERVER_PORT = 19098;
68   
69    /**
70     *
71     */
72    protected static final int PROXY_PORT = 19099;
73   
74    /**
75     *
76     */
77    protected static final int MONITOR_PORT = 19100;
78   
79    /**
80     * the servlet of the dummy web server responding to requests
81     */
82    private DummyServlet dummyServlet;
83   
84    /** */
85    private Tomcat tomcat = new Tomcat();
86   
87    /**
88     *
89     */
90    static String readStreamContentToString(InputStream stream) throws IOException {
91        return readToString(new BufferedReader(new InputStreamReader(stream)));
92    }
93   
94    /**
95     *
96     */
97    static String readToString(BufferedReader reader) throws IOException {
98        StringBuffer message = new StringBuffer();
99       
100        String line = reader.readLine();
101        while (line != null) {
102            System.err.println(line);
103            if (message.length() > 0) {
104                message.append('\n');
105            }
106            message.append(line);
107            line = reader.readLine();
108        }
109       
110        return message.toString();
111    }
112
113    /**
114     *
115     */
116    @Before
117    public void setUp() throws Exception {
118        // setup a simple HTTP server
119        dummyServlet = new DummyServlet();
120       
121        /*dummyServer = new Server(DUMMY_SERVER_PORT);
122       
123        ServletContextHandler root =
124            new ServletContextHandler(dummyServer, "/dummyServer", ServletContextHandler.SESSIONS);
125
126       
127        root.addServlet(new ServletHolder(dummyServlet), "/*");
128       
129        dummyServer.start();*/
130       
131        File tomcatDir = new File("target/test/tomcat");
132        File webappRootDir = new File(tomcatDir, "webapp");
133       
134        tomcat = new Tomcat();
135        tomcat.setPort(DUMMY_SERVER_PORT);
136        tomcat.setBaseDir(tomcatDir.getAbsolutePath());
137
138        File warFile = new File(webappRootDir, "dummyService.war");
139        tomcat.addWebapp("/dummyWebapp", warFile.getAbsolutePath());
140        System.out.println("configuring Dummy Service from " + warFile.getAbsolutePath());
141       
142        File servletRootDir = new File(tomcatDir, "servlet");
143        servletRootDir.mkdirs();
144        Context ctx = tomcat.addContext("/", servletRootDir.getAbsolutePath());
145        Tomcat.addServlet(ctx, "dummyServlet", dummyServlet);
146        ctx.addServletMapping("/dummyServlet", "dummyServlet");
147       
148        tomcat.start();
149       
150        setUpHook();
151    }
152
153    /**
154     *
155     */
156    protected abstract void setUpHook() throws Exception;
157
158    /**
159     *
160     */
161    @After
162    public void tearDown() throws Exception {
163        // give all started servers a second to finalize their internal work after the test
164        // execution. This prevents some unnecessary exceptions due to requests already processed
165        // by the test case but not finalized on server side.
166        Thread.sleep(2000);
167        tearDownHook();
168
169        if (tomcat != null) {
170            try {
171                tomcat.stop();
172                tomcat.getServer().await();
173                tomcat.destroy();
174            }
175            finally {
176                tomcat = null;
177            }
178        }
179       
180        deleteFiles(new File(LOG_FILE_DIR));
181       
182        // wait a little before the next server starts
183        Thread.sleep(2000);
184    }
185
186    /**
187     *
188     */
189    protected abstract void tearDownHook() throws Exception;
190
191    /**
192     *
193     */
194    protected String sendDummyMessage(String type, String query, String message, String respMsg)
195        throws Exception
196    {
197        dummyServlet.setResponse(respMsg);
198       
199        System.err.println("sending message: " + message);
200        DefaultHttpClient httpclient = new DefaultHttpClient();
201        HttpRequestBase httpRequest = null;
202       
203        String uri = "http://localhost:" + PROXY_PORT + "/dummyServlet";
204       
205        if (query != null) {
206            uri += "?" + query;
207        }
208       
209        if ("POST".equals(type)) {
210            httpRequest = new HttpPost(uri);
211            HttpEntity entity = new StringEntity(message, ContentType.TEXT_PLAIN);
212            ((HttpPost) httpRequest).setEntity(entity);
213        }
214        else if ("GET".equals(type)) {
215            httpRequest = new HttpGet(uri);
216        }
217       
218        try {
219            HttpResponse response = httpclient.execute(httpRequest);
220           
221            assertEquals(message, dummyServlet.getRequest());
222            assertEquals(query, dummyServlet.getQuery());
223            System.err.println(response.getStatusLine());
224            String responseStr = readStreamContentToString(response.getEntity().getContent());
225            System.err.println("received response: " + responseStr);
226            return responseStr;
227        }
228        finally {
229            httpRequest.releaseConnection();
230        }
231    }
232   
233    /**
234     *
235     */
236    protected void assertEvent(Event  event,
237                               String method,
238                               String query,
239                               String message,
240                               String response)
241    {
242        assertNotNull(event);
243        assertNotNull(event.getType());
244        assertNotNull(event.getTarget());
245       
246        assertTrue(event.getType() instanceof HTTPEventType);
247        assertTrue(event.getTarget() instanceof HTTPTarget);
248       
249        assertExchange(((HTTPEventType) event.getType()).getExchange(),
250                       method, query, message, response);
251    }
252   
253    /**
254     *
255     */
256    protected void assertExchange(HttpExchange exchange,
257                                  String       method,
258                                  String       query,
259                                  String       message,
260                                  String       response)
261    {
262        assertEquals(Method.fromValue(method), exchange.getRequest().getMethod());
263       
264        if (query != null) {
265            assertEquals(query, exchange.getRequest().getQuery());
266        }
267        else if (exchange.getRequest().getQuery() != null) {
268            System.err.println(exchange.getRequest().getQuery());
269            fail("unexpected query");
270        }
271       
272        if (message != null) {
273            assertEquals(message, exchange.getRequest().getContent().getData());
274        }
275        else if (exchange.getRequest().getContent() != null) {
276            System.err.println(exchange.getRequest().getContent().getData());
277        }
278       
279        if (response != null) {
280            assertEquals(response, exchange.getResponse().getContent().getData());
281        }
282        else if (exchange.getResponse().getContent() != null) {
283            System.err.println(exchange.getResponse().getContent().getData());
284        }
285       
286        assertNotNull(exchange.getRequest().getOrderingId());
287        assertNotNull(exchange.getResponse().getOrderingId());
288        assertTrue(exchange.getRequest().getOrderingId() < exchange.getResponse().getOrderingId());
289    }
290
291    /**
292     *
293     */
294    protected void deleteFiles(File file) {
295        if (file.exists()) {
296            if (file.isDirectory()) {
297                File[] files = file.listFiles();
298                if (files != null) {
299                    for (File child : files) {
300                       deleteFiles(child);
301                    }
302                }
303            }
304           
305            try {
306                file.delete();
307            }
308            catch (Exception e) {
309                // ignore and delete as much as possible
310            }
311        }
312    }
313
314}
Note: See TracBrowser for help on using the repository browser.