KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tctest > server > appserver > unit > SessionInvalidatorTest


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright
3  * notice. All rights reserved.
4  */

5 package com.tctest.server.appserver.unit;
6
7 import org.apache.commons.httpclient.HttpClient;
8
9 import com.tc.test.server.appserver.unit.AbstractAppServerTestCase;
10 import com.tc.test.server.util.HttpUtil;
11
12 import java.io.IOException JavaDoc;
13 import java.net.ConnectException JavaDoc;
14 import java.net.URL JavaDoc;
15 import java.util.ArrayList JavaDoc;
16 import java.util.Date JavaDoc;
17 import java.util.HashMap JavaDoc;
18 import java.util.List JavaDoc;
19 import java.util.Map JavaDoc;
20 import java.util.Properties JavaDoc;
21
22 import javax.servlet.http.HttpServlet JavaDoc;
23 import javax.servlet.http.HttpServletRequest JavaDoc;
24 import javax.servlet.http.HttpServletResponse JavaDoc;
25 import javax.servlet.http.HttpSessionAttributeListener JavaDoc;
26 import javax.servlet.http.HttpSessionBindingEvent JavaDoc;
27 import javax.servlet.http.HttpSessionBindingListener JavaDoc;
28 import javax.servlet.http.HttpSessionEvent JavaDoc;
29 import javax.servlet.http.HttpSessionListener JavaDoc;
30
31 public class SessionInvalidatorTest extends AbstractAppServerTestCase {
32
33   public SessionInvalidatorTest() {
34     try {
35       collectVmStats();
36     } catch (IOException JavaDoc e) {
37       e.printStackTrace();
38     }
39     // disableAllUntil("2007-01-01");
40
}
41
42   public static final class ListenerReportingServlet extends HttpServlet JavaDoc {
43     private static Map JavaDoc callCounts = new HashMap JavaDoc();
44
45     protected void doGet(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc resp) throws IOException JavaDoc {
46       final String JavaDoc action = req.getParameter("action");
47       final String JavaDoc key = req.getParameter("key");
48       String JavaDoc reply = "OK";
49       if ("get".equals(action)) {
50         reply = key + "=" + req.getSession().getAttribute(key);
51       } else if ("set".equals(action)) {
52         req.getSession().setAttribute(key, new BindingListener JavaDoc(key));
53       } else if ("setwithexception".equals(action)) {
54         try {
55           req.getSession().setAttribute(key, new BindingListenerWithException(key));
56           reply = "Did not get expected exception!";
57         } catch (Throwable JavaDoc e) {
58           // this is expected
59
}
60       } else if ("remove".equals(action)) {
61         req.getSession().removeAttribute(key);
62       } else if ("call_count".equals(action)) {
63         reply = key + "=" + getCallCount(key);
64       } else if ("setmax".equals(action)) {
65         req.getSession().setMaxInactiveInterval(Integer.parseInt(key));
66       } else if ("isNew".equals(action)) {
67         if (!req.getSession().isNew()) reply = "OLD SESSION!";
68       } else if ("isOld".equals(action)) {
69         if (req.getSession().isNew()) reply = "NEW SESSION!";
70       } else if ("sleep".equals(action)) {
71         // lock session and go to sleep
72
req.getSession();
73         sleep(1000 * Integer.parseInt(key));
74         req.getSession().setMaxInactiveInterval(30 * 60);
75       } else {
76         reply = "INVALID REQUEST";
77       }
78       resp.getWriter().print(reply);
79       resp.flushBuffer();
80     }
81
82     private void sleep(int i) {
83       try {
84         Date JavaDoc now = new Date JavaDoc();
85         System.err.println("SERVLET: " + now + ": going to sleep for " + i + " millis");
86         Thread.sleep(i);
87         now = new Date JavaDoc();
88         System.err.println("SERVLET: " + now + ": woke up from sleeping for " + i + " millis");
89       } catch (InterruptedException JavaDoc e) {
90         e.printStackTrace();
91       }
92     }
93
94     private synchronized static int getCallCount(String JavaDoc key) {
95       Integer JavaDoc i = (Integer JavaDoc) callCounts.get(key);
96       return i == null ? 0 : i.intValue();
97     }
98
99     public synchronized static void incrementCallCount(String JavaDoc key) {
100       Integer JavaDoc i = (Integer JavaDoc) callCounts.get(key);
101       if (i == null) {
102         i = new Integer JavaDoc(1);
103       } else {
104         i = new Integer JavaDoc(i.intValue() + 1);
105       }
106       callCounts.put(key, i);
107     }
108   }
109
110   public static final class AttributeListener implements HttpSessionAttributeListener JavaDoc {
111
112     public AttributeListener() {
113       System.err.println("### AttributeListener() is here!!!");
114     }
115
116     public void attributeAdded(HttpSessionBindingEvent JavaDoc httpsessionbindingevent) {
117       ListenerReportingServlet.incrementCallCount("AttributeListener.attributeAdded");
118       System.err.println("### AttributeListener.attributeAdded() is here!!!");
119     }
120
121     public void attributeRemoved(HttpSessionBindingEvent JavaDoc httpsessionbindingevent) {
122       System.err.println("### AttributeListener.attributeRemoved() is here!!!");
123       ListenerReportingServlet.incrementCallCount("AttributeListener.attributeRemoved");
124     }
125
126     public void attributeReplaced(HttpSessionBindingEvent JavaDoc httpsessionbindingevent) {
127       System.err.println("### AttributeListener.attributeReplaced() is here!!!");
128       ListenerReportingServlet.incrementCallCount("AttributeListener.attributeReplaced");
129     }
130   }
131
132   public static final class SessionListener implements HttpSessionListener JavaDoc {
133     public SessionListener() {
134       System.err.println("### SessionListener() is here!!!");
135     }
136
137     public void sessionCreated(HttpSessionEvent JavaDoc httpsessionevent) {
138       System.err.println("### SessionListener.sessionCreated() is here!!!");
139       ListenerReportingServlet.incrementCallCount("SessionListener.sessionCreated");
140     }
141
142     public void sessionDestroyed(HttpSessionEvent JavaDoc httpsessionevent) {
143       System.err.println("### SessionListener.sessionDestroyed() is here!!!");
144       ListenerReportingServlet.incrementCallCount("SessionListener.sessionDestroyed");
145     }
146   }
147
148   public static final class BindingListener implements HttpSessionBindingListener JavaDoc {
149
150     private final String JavaDoc key;
151
152     public BindingListener(String JavaDoc key) {
153       System.err.println("### BindingListener is here!!! key = " + key);
154       this.key = key;
155     }
156
157     public void valueBound(HttpSessionBindingEvent JavaDoc e) {
158       // the value being bound must not be in session yet...
159
Object JavaDoc o = e.getSession().getAttribute(e.getName());
160       if (o == null) ListenerReportingServlet.incrementCallCount("BindingListener.valueBound");
161       else System.err.println("### Event sequence violated!!!");
162     }
163
164     public void valueUnbound(HttpSessionBindingEvent JavaDoc e) {
165       ListenerReportingServlet.incrementCallCount("BindingListener.valueUnbound");
166     }
167
168     public String JavaDoc toString() {
169       return key;
170     }
171   }
172
173   public static final class BindingListenerWithException implements HttpSessionBindingListener JavaDoc {
174     private final String JavaDoc key;
175
176     public BindingListenerWithException(String JavaDoc key) {
177       this.key = key;
178     }
179
180     public void valueBound(HttpSessionBindingEvent JavaDoc arg0) {
181       ListenerReportingServlet.incrementCallCount("BindingListener.valueBound");
182       throw new RuntimeException JavaDoc("Testing Exception Delivery");
183     }
184
185     public void valueUnbound(HttpSessionBindingEvent JavaDoc arg0) {
186       ListenerReportingServlet.incrementCallCount("BindingListener.valueUnbound");
187       throw new RuntimeException JavaDoc("Testing Exception Delivery");
188     }
189
190     public String JavaDoc toString() {
191       return key;
192     }
193   }
194
195   private int port;
196
197   public void testInvalidator() throws Exception JavaDoc {
198     startDsoServer();
199
200     final int invalidatorSleepSeconds = 1;
201     final int defaultMaxIdleSeconds = 5;
202     final int waitFactor = 4;
203     final List JavaDoc props = new ArrayList JavaDoc();
204     props.add("-Dcom.tc.session.invalidator.sleep=" + String.valueOf(invalidatorSleepSeconds));
205     props.add("-Dcom.tc.session.maxidle.seconds=" + String.valueOf(defaultMaxIdleSeconds));
206     port = startAppServer(true, new Properties JavaDoc(), (String JavaDoc[]) props.toArray(new String JavaDoc[] {})).serverPort();
207
208     HttpClient client = HttpUtil.createHttpClient();
209
210     // first, sanity check
211
URL JavaDoc url = new URL JavaDoc(createUrl(port, SessionInvalidatorTest.ListenerReportingServlet.class) + "?action=0");
212     checkResponse("INVALID REQUEST", url, client);
213
214     // now, put a string into session...
215
url = new URL JavaDoc(createUrl(port, SessionInvalidatorTest.ListenerReportingServlet.class) + "?action=set&key=attr1");
216     checkResponse("OK", url, client);
217     // ... and check if it made it there.
218
url = new URL JavaDoc(createUrl(port, SessionInvalidatorTest.ListenerReportingServlet.class) + "?action=get&key=attr1");
219     checkResponse("attr1=attr1", url, client);
220
221     checkCallCount("SessionListener.sessionCreated", 1, client);
222     checkCallCount("BindingListener.valueBound", 1, client);
223
224     // now set exception-throwing BindingListener..
225
url = new URL JavaDoc(createUrl(port, SessionInvalidatorTest.ListenerReportingServlet.class)
226                   + "?action=setwithexception&key=attr2");
227     checkResponse("OK", url, client);
228     // ... and check if it DID NOT made it there.
229
url = new URL JavaDoc(createUrl(port, SessionInvalidatorTest.ListenerReportingServlet.class) + "?action=get&key=attr2");
230     checkResponse("attr2=null", url, client);
231
232     checkCallCount("BindingListener.valueBound", 2, client);
233     checkCallCount("BindingListener.valueUnbound", 0, client);
234
235     // set session max idle time
236
url = new URL JavaDoc(createUrl(port, SessionInvalidatorTest.ListenerReportingServlet.class) + "?action=setmax&key=3");
237     checkResponse("OK", url, client);
238
239     Thread.sleep(waitFactor * defaultMaxIdleSeconds * 1000);
240
241     checkCallCount("BindingListener.valueUnbound", 1, client);
242     checkCallCount("SessionListener.sessionDestroyed", 1, client);
243     // =========================================================
244
// by this point we varified that our old session was invalidated successfully while it WAS NOT being used.
245
// now let's see what happens if it's in use by a LOOONG-running request
246
// =========================================================
247
// make sure we got a new, good session
248
url = new URL JavaDoc(createUrl(port, SessionInvalidatorTest.ListenerReportingServlet.class) + "?action=isNew");
249     checkResponse("OK", url, client);
250
251     // set session max idle time
252
url = new URL JavaDoc(createUrl(port, SessionInvalidatorTest.ListenerReportingServlet.class) + "?action=setmax&key=5");
253     checkResponse("OK", url, client);
254
255     // now, get a long-running request a-running
256
url = new URL JavaDoc(createUrl(port, SessionInvalidatorTest.ListenerReportingServlet.class) + "?action=sleep&key=15");
257     checkResponse("OK", url, client);
258
259     // make sure we still got the old session
260
url = new URL JavaDoc(createUrl(port, SessionInvalidatorTest.ListenerReportingServlet.class) + "?action=isOld");
261     checkResponse("OK", url, client);
262     checkCallCount("BindingListener.valueUnbound", 1, client);
263     checkCallCount("SessionListener.sessionDestroyed", 1, client);
264
265     // now let this session expire
266
// give invalidator at least 2 runs...
267
// set session max idle time
268
url = new URL JavaDoc(createUrl(port, SessionInvalidatorTest.ListenerReportingServlet.class) + "?action=setmax&key=5");
269     checkResponse("OK", url, client);
270     Thread.sleep(waitFactor * defaultMaxIdleSeconds * 1000);
271     checkCallCount("BindingListener.valueUnbound", 1, client);
272     checkCallCount("SessionListener.sessionDestroyed", 2, client);
273   }
274
275   private void checkResponse(String JavaDoc expectedResponse, URL JavaDoc url, HttpClient client) throws ConnectException JavaDoc, IOException JavaDoc {
276     System.err.println("=== Send Request [" + (new Date JavaDoc()) + "]: url=[" + url + "]");
277     final String JavaDoc actualResponse = HttpUtil.getResponseBody(url, client);
278     System.err.println("=== Got Response [" + (new Date JavaDoc()) + "]: url=[" + url + "], response=[" + actualResponse + "]");
279     assertTimeDirection();
280     assertEquals(expectedResponse, actualResponse);
281   }
282
283   private void checkCallCount(final String JavaDoc key, int expectedCount, HttpClient client) throws ConnectException JavaDoc,
284       IOException JavaDoc {
285     URL JavaDoc url = new URL JavaDoc(createUrl(port, SessionInvalidatorTest.ListenerReportingServlet.class)
286                       + "?action=call_count&key=" + key);
287     checkResponse(key + "=" + expectedCount, url, client);
288   }
289 }
290
Popular Tags