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
RevLine 
[1376]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
[1392]17import static org.junit.Assert.assertEquals;
18import static org.junit.Assert.assertNotNull;
19import static org.junit.Assert.assertTrue;
[1614]20import static org.junit.Assert.fail;
[1392]21
[1376]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
[1390]29import org.apache.catalina.Context;
30import org.apache.catalina.startup.Tomcat;
[1376]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
[1392]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;
[1561]45import de.ugoe.cs.autoquest.plugin.http.logdata.HttpExchange;
46import de.ugoe.cs.autoquest.plugin.http.logdata.Method;
[1376]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     */
[1390]67    protected static final int DUMMY_SERVER_PORT = 19098;
[1376]68   
69    /**
[1390]70     *
[1376]71     */
[1390]72    protected static final int PROXY_PORT = 19099;
[1376]73   
74    /**
[1390]75     *
76     */
77    protected static final int MONITOR_PORT = 19100;
78   
79    /**
[1376]80     * the servlet of the dummy web server responding to requests
81     */
82    private DummyServlet dummyServlet;
[1390]83   
84    /** */
[2232]85    private Tomcat tomcat = new Tomcat();
[1567]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    }
[1376]112
113    /**
114     *
115     */
116    @Before
117    public void setUp() throws Exception {
118        // setup a simple HTTP server
[1390]119        dummyServlet = new DummyServlet();
[1376]120       
[1390]121        /*dummyServer = new Server(DUMMY_SERVER_PORT);
122       
[1376]123        ServletContextHandler root =
[1390]124            new ServletContextHandler(dummyServer, "/dummyServer", ServletContextHandler.SESSIONS);
[1376]125
[1390]126       
[1376]127        root.addServlet(new ServletHolder(dummyServlet), "/*");
[1390]128       
129        dummyServer.start();*/
[1376]130       
[1390]131        File tomcatDir = new File("target/test/tomcat");
132        File webappRootDir = new File(tomcatDir, "webapp");
[1376]133       
[1390]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       
[1376]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.
[2116]166        Thread.sleep(2000);
[1376]167        tearDownHook();
168
[1390]169        if (tomcat != null) {
[1376]170            try {
[1390]171                tomcat.stop();
172                tomcat.getServer().await();
173                tomcat.destroy();
[1376]174            }
175            finally {
[1390]176                tomcat = null;
[1376]177            }
178        }
179       
180        deleteFiles(new File(LOG_FILE_DIR));
[2115]181       
182        // wait a little before the next server starts
[2116]183        Thread.sleep(2000);
[1376]184    }
185
186    /**
187     *
188     */
189    protected abstract void tearDownHook() throws Exception;
190
191    /**
192     *
193     */
[1614]194    protected String sendDummyMessage(String type, String query, String message, String respMsg)
[1376]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       
[1614]203        String uri = "http://localhost:" + PROXY_PORT + "/dummyServlet";
204       
205        if (query != null) {
206            uri += "?" + query;
207        }
208       
[1376]209        if ("POST".equals(type)) {
[1614]210            httpRequest = new HttpPost(uri);
[1376]211            HttpEntity entity = new StringEntity(message, ContentType.TEXT_PLAIN);
212            ((HttpPost) httpRequest).setEntity(entity);
213        }
214        else if ("GET".equals(type)) {
[1614]215            httpRequest = new HttpGet(uri);
[1376]216        }
217       
218        try {
219            HttpResponse response = httpclient.execute(httpRequest);
[1567]220           
221            assertEquals(message, dummyServlet.getRequest());
[1614]222            assertEquals(query, dummyServlet.getQuery());
[1390]223            System.err.println(response.getStatusLine());
[1376]224            String responseStr = readStreamContentToString(response.getEntity().getContent());
[1390]225            System.err.println("received response: " + responseStr);
[1376]226            return responseStr;
227        }
228        finally {
229            httpRequest.releaseConnection();
230        }
231    }
232   
233    /**
[1392]234     *
235     */
[1614]236    protected void assertEvent(Event  event,
237                               String method,
238                               String query,
239                               String message,
240                               String response)
241    {
[1392]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       
[1614]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    {
[1392]262        assertEquals(Method.fromValue(method), exchange.getRequest().getMethod());
263       
[1614]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       
[1392]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        }
[1991]285       
286        assertNotNull(exchange.getRequest().getOrderingId());
287        assertNotNull(exchange.getResponse().getOrderingId());
288        assertTrue(exchange.getRequest().getOrderingId() < exchange.getResponse().getOrderingId());
[1392]289    }
[1376]290
291    /**
292     *
293     */
294    protected void deleteFiles(File file) {
295        if (file.exists()) {
296            if (file.isDirectory()) {
[2232]297                File[] files = file.listFiles();
298                if (files != null) {
299                    for (File child : files) {
300                       deleteFiles(child);
301                    }
[1376]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.