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

Last change on this file since 1561 was 1561, checked in by pharms, 10 years ago
  • update of namespaces for HTTP logfiles
File size: 8.0 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    @Before
90    public void setUp() throws Exception {
91        // setup a simple HTTP server
92        dummyServlet = new DummyServlet();
93       
94        /*dummyServer = new Server(DUMMY_SERVER_PORT);
95       
96        ServletContextHandler root =
97            new ServletContextHandler(dummyServer, "/dummyServer", ServletContextHandler.SESSIONS);
98
99       
100        root.addServlet(new ServletHolder(dummyServlet), "/*");
101       
102        dummyServer.start();*/
103       
104        File tomcatDir = new File("target/test/tomcat");
105        File webappRootDir = new File(tomcatDir, "webapp");
106       
107        tomcat = new Tomcat();
108        tomcat.setPort(DUMMY_SERVER_PORT);
109        tomcat.setBaseDir(tomcatDir.getAbsolutePath());
110
111        File warFile = new File(webappRootDir, "dummyService.war");
112        tomcat.addWebapp("/dummyWebapp", warFile.getAbsolutePath());
113        System.out.println("configuring Dummy Service from " + warFile.getAbsolutePath());
114       
115        File servletRootDir = new File(tomcatDir, "servlet");
116        servletRootDir.mkdirs();
117        Context ctx = tomcat.addContext("/", servletRootDir.getAbsolutePath());
118        Tomcat.addServlet(ctx, "dummyServlet", dummyServlet);
119        ctx.addServletMapping("/dummyServlet", "dummyServlet");
120       
121        tomcat.start();
122       
123        setUpHook();
124    }
125
126    /**
127     *
128     */
129    protected abstract void setUpHook() throws Exception;
130
131    /**
132     *
133     */
134    @After
135    public void tearDown() throws Exception {
136        // give all started servers a second to finalize their internal work after the test
137        // execution. This prevents some unnecessary exceptions due to requests already processed
138        // by the test case but not finalized on server side.
139        Thread.sleep(1000);
140        tearDownHook();
141
142        if (tomcat != null) {
143            try {
144                tomcat.stop();
145                tomcat.getServer().await();
146                tomcat.destroy();
147            }
148            finally {
149                tomcat = null;
150            }
151        }
152       
153        deleteFiles(new File(LOG_FILE_DIR));
154    }
155
156    /**
157     *
158     */
159    protected abstract void tearDownHook() throws Exception;
160
161    /**
162     *
163     */
164    protected String sendDummyMessage(String type, String message, String respMsg)
165        throws Exception
166    {
167        dummyServlet.setResponse(respMsg);
168       
169        System.err.println("sending message: " + message);
170        DefaultHttpClient httpclient = new DefaultHttpClient();
171        HttpRequestBase httpRequest = null;
172       
173        if ("POST".equals(type)) {
174            httpRequest = new HttpPost("http://localhost:" + PROXY_PORT + "/dummyServlet");
175            HttpEntity entity = new StringEntity(message, ContentType.TEXT_PLAIN);
176            ((HttpPost) httpRequest).setEntity(entity);
177        }
178        else if ("GET".equals(type)) {
179            httpRequest = new HttpGet("http://localhost:" + PROXY_PORT + "/dummyServlet");
180        }
181       
182        try {
183            HttpResponse response = httpclient.execute(httpRequest);
184            System.err.println(response.getStatusLine());
185            String responseStr = readStreamContentToString(response.getEntity().getContent());
186            System.err.println("received response: " + responseStr);
187            return responseStr;
188        }
189        finally {
190            httpRequest.releaseConnection();
191        }
192    }
193   
194    /**
195     *
196     */
197    protected String readStreamContentToString(InputStream stream) throws IOException {
198        return readToString(new BufferedReader(new InputStreamReader(stream)));
199    }
200   
201    /**
202     *
203     */
204    protected String readToString(BufferedReader reader) throws IOException {
205        StringBuffer message = new StringBuffer();
206       
207        String line = reader.readLine();
208        while (line != null) {
209            System.err.println(line);
210            if (message.length() > 0) {
211                message.append('\n');
212            }
213            message.append(line);
214            line = reader.readLine();
215        }
216       
217        return message.toString();
218    }
219   
220    /**
221     *
222     */
223    protected void assertEvent(Event event, String method, String message, String response) {
224        assertNotNull(event);
225        assertNotNull(event.getType());
226        assertNotNull(event.getTarget());
227       
228        assertTrue(event.getType() instanceof HTTPEventType);
229        assertTrue(event.getTarget() instanceof HTTPTarget);
230       
231        HttpExchange exchange = ((HTTPEventType) event.getType()).getExchange();
232       
233        assertEquals(Method.fromValue(method), exchange.getRequest().getMethod());
234       
235        if (message != null) {
236            assertEquals(message, exchange.getRequest().getContent().getData());
237        }
238        else if (exchange.getRequest().getContent() != null) {
239            System.err.println(exchange.getRequest().getContent().getData());
240        }
241       
242        if (response != null) {
243            assertEquals(response, exchange.getResponse().getContent().getData());
244        }
245        else if (exchange.getResponse().getContent() != null) {
246            System.err.println(exchange.getResponse().getContent().getData());
247        }
248    }
249
250    /**
251     *
252     */
253    protected void deleteFiles(File file) {
254        if (file.exists()) {
255            if (file.isDirectory()) {
256                for (File child : file.listFiles()) {
257                    deleteFiles(child);
258                }
259            }
260           
261            try {
262                file.delete();
263            }
264            catch (Exception e) {
265                // ignore and delete as much as possible
266            }
267        }
268    }
269
270}
Note: See TracBrowser for help on using the repository browser.