1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.catalina.comet;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import javax.net.SocketFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Test;
import org.junit.Ignore;
import org.apache.catalina.Context;
import org.apache.catalina.Wrapper;
import org.apache.catalina.comet.CometEvent.EventType;
import org.apache.catalina.connector.CometEventImpl;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.startup.TomcatBaseTest;
import org.apache.catalina.valves.TesterAccessLogValve;
import org.apache.catalina.valves.ValveBase;
public class TestCometProcessor extends TomcatBaseTest {
@Test
public void testAsyncClose() throws Exception {
Assume.assumeTrue(
"This test is skipped, because this connector does not support Comet.",
isCometSupported());
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
Context root = tomcat.addContext("", TEMP_DIR);
Tomcat.addServlet(root, "comet", new SimpleCometServlet());
root.addServletMapping("/comet", "comet");
Tomcat.addServlet(root, "hello", new HelloWorldServlet());
root.addServletMapping("/hello", "hello");
root.getPipeline().addValve(new AsyncCometCloseValve());
tomcat.getConnector().setProperty("connectionTimeout", "5000");
tomcat.start();
// Create connection to Comet servlet
final Socket socket =
SocketFactory.getDefault().createSocket("localhost", getPort());
socket.setSoTimeout(5000);
final OutputStream os = socket.getOutputStream();
String requestLine = "POST http://localhost:" + getPort() +
"/comet HTTP/1.1\r\n";
os.write(requestLine.getBytes());
os.write("transfer-encoding: chunked\r\n".getBytes());
os.write("\r\n".getBytes());
InputStream is = socket.getInputStream();
ResponseReaderThread readThread = new ResponseReaderThread(is);
readThread.start();
// Wait for the comet request/response to finish
int count = 0;
while (count < 10 && !readThread.getResponse().endsWith("0\r\n\r\n")) {
Thread.sleep(500);
count++;
}
if (count == 10) {
fail("Comet request did not complete");
}
// Send a standard HTTP request on the same connection
requestLine = "GET http://localhost:" + getPort() +
"/hello HTTP/1.1\r\n";
os.write(requestLine.getBytes());
os.write("\r\n".getBytes());
// Check for the expected response
count = 0;
while (count < 10 && !readThread.getResponse().contains(
HelloWorldServlet.RESPONSE_TEXT)) {
Thread.sleep(500);
count++;
}
if (count == 10) {
fail("Non-comet request did not complete");
}
readThread.join();
os.close();
is.close();
}
@Test
public void testSyncClose() throws Exception {
Assume.assumeTrue(
"This test is skipped, because this connector does not support Comet.",
isCometSupported());
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
Context root = tomcat.addContext("", TEMP_DIR);
Tomcat.addServlet(root, "comet", new CometCloseServlet());
root.addServletMapping("/comet", "comet");
Tomcat.addServlet(root, "hello", new HelloWorldServlet());
root.addServletMapping("/hello", "hello");
tomcat.getConnector().setProperty("connectionTimeout", "5000");
tomcat.start();
// Create connection to Comet servlet
final Socket socket =
SocketFactory.getDefault().createSocket("localhost", getPort());
socket.setSoTimeout(5000);
final OutputStream os = socket.getOutputStream();
String requestLine = "POST http://localhost:" + getPort() +
"/comet HTTP/1.1\r\n";
os.write(requestLine.getBytes());
os.write("transfer-encoding: chunked\r\n".getBytes());
os.write("\r\n".getBytes());
// Don't send any data
os.write("0\r\n\r\n".getBytes());
InputStream is = socket.getInputStream();
ResponseReaderThread readThread = new ResponseReaderThread(is);
readThread.start();
// Wait for the comet request/response to finish
int count = 0;
while (count < 10 && !readThread.getResponse().endsWith("0\r\n\r\n")) {
Thread.sleep(500);
count++;
}
Assert.assertTrue(readThread.getResponse().contains("2\r\nOK"));
if (count == 10) {
fail("Comet request did not complete");
}
// Send a standard HTTP request on the same connection
requestLine = "GET http://localhost:" + getPort() +
"/hello HTTP/1.1\r\n";
os.write(requestLine.getBytes());
os.write("connection: close\r\n".getBytes());
os.write("\r\n".getBytes());
// Check for the expected response
count = 0;
while (count < 10 && !readThread.getResponse().contains(
HelloWorldServlet.RESPONSE_TEXT)) {
Thread.sleep(500);
count++;
}
if (count == 10) {
fail("Non-comet request did not complete");
}
readThread.join();
os.close();
is.close();
}
@Ignore("fails consistently on Debian/Linux")
public void testConnectionClose() throws Exception {
Assume.assumeTrue(
"This test is skipped, because this connector does not support Comet.",
isCometSupported());
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
Context root = tomcat.addContext("", TEMP_DIR);
Tomcat.addServlet(root, "comet", new ConnectionCloseServlet());
root.addServletMapping("/comet", "comet");
Tomcat.addServlet(root, "hello", new HelloWorldServlet());
root.addServletMapping("/hello", "hello");
tomcat.getConnector().setProperty("connectionTimeout", "5000");
tomcat.start();
// Create connection to Comet servlet
final Socket socket =
SocketFactory.getDefault().createSocket("localhost", getPort());
socket.setSoTimeout(5000);
final OutputStream os = socket.getOutputStream();
String requestLine = "POST http://localhost:" + getPort() +
"/comet HTTP/1.1\r\n";
os.write(requestLine.getBytes());
os.write("transfer-encoding: chunked\r\n".getBytes());
os.write("\r\n".getBytes());
// Don't send any data
os.write("0\r\n\r\n".getBytes());
InputStream is = socket.getInputStream();
ResponseReaderThread readThread = new ResponseReaderThread(is);
readThread.start();
// Wait for the comet request/response to finish
int count = 0;
while (count < 10 && !readThread.getResponse().endsWith("OK")) {
Thread.sleep(500);
count++;
}
if (count == 10) {
fail("Comet request did not complete");
}
// Read thread should have terminated cleanly when the server closed the
// socket
Assert.assertFalse(readThread.isAlive());
Assert.assertNull(readThread.getException());
os.close();
is.close();
}
@Test
public void testSimpleCometClient() throws Exception {
doSimpleCometTest(null);
}
@Test
public void testSimpleCometClientBeginFail() throws Exception {
doSimpleCometTest(SimpleCometServlet.FAIL_ON_BEGIN);
}
@Test
public void testSimpleCometClientReadFail() throws Exception {
doSimpleCometTest(SimpleCometServlet.FAIL_ON_READ);
}
@Test
public void testSimpleCometClientEndFail() throws Exception {
doSimpleCometTest(SimpleCometServlet.FAIL_ON_END);
}
private void doSimpleCometTest(String initParam) throws Exception {
Assume.assumeTrue(
"This test is skipped, because this connector does not support Comet.",
isCometSupported());
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
Context root = tomcat.addContext("", TEMP_DIR);
Wrapper w = Tomcat.addServlet(root, "comet", new SimpleCometServlet());
if (initParam != null) {
w.addInitParameter(initParam, "true");
}
root.addServletMapping("/", "comet");
TesterAccessLogValve alv = new TesterAccessLogValve();
root.getPipeline().addValve(alv);
tomcat.start();
// Create connection to Comet servlet
final Socket socket =
SocketFactory.getDefault().createSocket("localhost", getPort());
socket.setSoTimeout(60000);
final OutputStream os = socket.getOutputStream();
String requestLine = "POST http://localhost:" + getPort() +
"/ HTTP/1.1\r\n";
os.write(requestLine.getBytes());
os.write("transfer-encoding: chunked\r\n".getBytes());
os.write("\r\n".getBytes());
PingWriterThread writeThread = new PingWriterThread(4, os);
writeThread.start();
socket.setSoTimeout(25000);
InputStream is = socket.getInputStream();
ResponseReaderThread readThread = new ResponseReaderThread(is);
readThread.start();
readThread.join();
os.close();
is.close();
String[] response = readThread.getResponse().split("\r\n");
if (initParam == null) {
// Normal response expected
// Validate response
assertEquals("HTTP/1.1 200 OK", response[0]);
assertEquals("Server: Apache-Coyote/1.1", response[1]);
assertTrue(response[2].startsWith("Set-Cookie: JSESSIONID="));
assertEquals("Content-Type: text/plain;charset=ISO-8859-1", response[3]);
assertEquals("Transfer-Encoding: chunked", response[4]);
assertTrue(response[5].startsWith("Date: "));
assertEquals("", response[6]);
assertEquals("7", response[7]);
assertEquals("BEGIN", response[8]);
assertEquals("", response[9]);
assertEquals("17", response[10]);
assertEquals("Client: READ: 4 bytes", response[11]);
assertEquals("", response[12]);
assertEquals("17", response[13]);
assertEquals("Client: READ: 4 bytes", response[14]);
assertEquals("", response[15]);
assertEquals("17", response[16]);
assertEquals("Client: READ: 4 bytes", response[17]);
assertEquals("", response[18]);
assertEquals("17", response[19]);
assertEquals("Client: READ: 4 bytes", response[20]);
assertEquals("", response[21]);
assertEquals("d", response[22]);
assertEquals("Client: END", response[23]);
assertEquals("", response[24]);
assertEquals("0", response[25]);
// Expect 26 lines
assertEquals(26, response.length);
} else {
// Failure expected only expected for the fail on begin
// Failure at any later stage and the response headers (including
// the 200 response code will already have been sent to the client
if (SimpleCometServlet.FAIL_ON_BEGIN.equals(initParam)) {
assertEquals("HTTP/1.1 500 Internal Server Error", response[0]);
alv.validateAccessLog(1, 500, 0, 1000);
} else {
assertEquals("HTTP/1.1 200 OK", response[0]);
alv.validateAccessLog(1, 200, 0, 5000);
}
}
}
/**
* Tests if the Comet connection is closed if the Tomcat connector is
* stopped.
*/
@Test
public void testCometConnectorStop() throws Exception {
Assume.assumeTrue(
"This test is skipped, because this connector does not support Comet.",
isCometSupported());
// Setup Tomcat instance
SimpleCometServlet servlet = new SimpleCometServlet();
Tomcat tomcat = getTomcatInstance();
Context root = tomcat.addContext("", TEMP_DIR);
Tomcat.addServlet(root, "comet", servlet);
root.addServletMapping("/", "comet");
tomcat.start();
// Create connection to Comet servlet
final Socket socket =
SocketFactory.getDefault().createSocket("localhost", getPort());
socket.setSoTimeout(10000);
final OutputStream os = socket.getOutputStream();
String requestLine = "POST http://localhost:" + getPort() +
"/ HTTP/1.1\r\n";
os.write(requestLine.getBytes());
os.write("transfer-encoding: chunked\r\n".getBytes());
os.write("\r\n".getBytes());
PingWriterThread writeThread = new PingWriterThread(100, os);
writeThread.start();
InputStream is = socket.getInputStream();
ResponseReaderThread readThread = new ResponseReaderThread(is);
readThread.start();
// Allow the first couple of PING messages to be written
Thread.sleep(3000);
tomcat.getConnector().stop();
int count = 0;
// Wait for the read thread to stop
while (readThread.isAlive() && count < 50) {
Thread.sleep(100);
count ++;
}
// Wait for the write thread to stop
count = 0;
while (writeThread.isAlive() && count < 50) {
Thread.sleep(100);
count ++;
}
// Destroy the connector once the executor has sent the end event
tomcat.getConnector().destroy();
String[] response = readThread.getResponse().split("\r\n");
String lastMessage = "";
String lastResponseLine = "";
for (int i = response.length; --i >= 0;) {
lastMessage = response[i];
if (lastMessage.startsWith("Client:")) {
break;
}
}
for (int i = response.length; --i >= 0;) {
lastResponseLine = response[i];
if (lastResponseLine.length() > 0) {
break;
}
}
StringBuilder status = new StringBuilder();
// Expected, but is not 100% reliable:
// WriteThread exception: java.net.SocketException
// ReaderThread exception: null
// Last message: [Client: END]
// Last response line: [0] (empty chunk)
// Last comet event: [END]
// END event occurred: [true]
status.append("Status:");
status.append("\nWriterThread exception: " + writeThread.getException());
status.append("\nReaderThread exception: " + readThread.getException());
status.append("\nLast message: [" + lastMessage + "]");
status.append("\nLast response line: [" + lastResponseLine + "]");
status.append("\nLast comet event: [" + servlet.getLastEvent() + "]");
status.append("\nEND event occurred: [" + servlet.getEndEventOccurred() + "]");
if (writeThread.getException() == null
|| !lastMessage.contains("Client: END")
|| !EventType.END.equals(servlet.getLastEvent())) {
log.error(status);
} else {
log.info(status);
}
assertTrue("Comet END event not received",
EventType.END.equals(servlet.getLastEvent()));
}
private boolean isCometSupported() {
String protocol =
getTomcatInstance().getConnector().getProtocolHandlerClassName();
return (protocol.contains("Nio") || protocol.contains("Apr"));
}
private static class SimpleCometServlet extends HttpServlet
implements CometProcessor {
private static final long serialVersionUID = 1L;
public static final String FAIL_ON_BEGIN = "failOnBegin";
public static final String FAIL_ON_READ = "failOnRead";
public static final String FAIL_ON_END = "failOnEnd";
private boolean failOnBegin = false;
private boolean failOnRead = false;
private boolean failOnEnd = false;
private volatile EventType lastEvent;
private volatile boolean endEventOccurred = false;
public EventType getLastEvent() {
return lastEvent;
}
public boolean getEndEventOccurred() {
return endEventOccurred;
}
@Override
public void init() throws ServletException {
failOnBegin = Boolean.valueOf(getServletConfig().getInitParameter(
FAIL_ON_BEGIN)).booleanValue();
failOnRead = Boolean.valueOf(getServletConfig().getInitParameter(
FAIL_ON_READ)).booleanValue();
failOnEnd = Boolean.valueOf(getServletConfig().getInitParameter(
FAIL_ON_END)).booleanValue();
}
@Override
public void event(CometEvent event) throws IOException,
ServletException {
HttpServletRequest request = event.getHttpServletRequest();
HttpServletResponse response = event.getHttpServletResponse();
HttpSession session = request.getSession(true);
session.setMaxInactiveInterval(30);
lastEvent = event.getEventType();
if (event.getEventType() == EventType.BEGIN) {
if (failOnBegin) {
throw new IOException("Fail on begin");
}
response.setContentType("text/plain");
response.getWriter().print("BEGIN" + "\r\n");
} else if (event.getEventType() == EventType.READ) {
if (failOnRead) {
throw new IOException("Fail on read");
}
InputStream is = request.getInputStream();
int count = 0;
while (is.available() > 0) {
is.read();
count ++;
}
String msg = "READ: " + count + " bytes";
response.getWriter().print("Client: " + msg + "\r\n");
} else if (event.getEventType() == EventType.END) {
endEventOccurred = true;
if (failOnEnd) {
throw new IOException("Fail on end");
}
String msg = "END";
response.getWriter().print("Client: " + msg + "\r\n");
event.close();
} else {
response.getWriter().print(event.getEventSubType() + "\r\n");
event.close();
}
response.getWriter().flush();
}
}
private static class CometCloseServlet extends HttpServlet
implements CometProcessor {
private static final long serialVersionUID = 1L;
@Override
public void event(CometEvent event) throws IOException,
ServletException {
HttpServletResponse response = event.getHttpServletResponse();
response.setContentType("text/plain");
// Force a chunked response since that is what the test client
// expects
response.flushBuffer();
response.getWriter().print("OK");
event.close();
}
}
private static class ConnectionCloseServlet extends HttpServlet
implements CometProcessor {
private static final long serialVersionUID = 1L;
@Override
public void event(CometEvent event) throws IOException,
ServletException {
HttpServletResponse response = event.getHttpServletResponse();
response.setContentType("text/plain");
// Disable keep-alive
response.setHeader("Connection", "close");
response.flushBuffer();
response.getWriter().print("OK");
event.close();
}
}
private static class PingWriterThread extends Thread {
private final int pingCount;
private final OutputStream os;
private volatile Exception e = null;
public PingWriterThread(int pingCount, OutputStream os) {
this.pingCount = pingCount;
this.os = os;
}
public Exception getException() {
return e;
}
@Override
public void run() {
try {
for (int i = 0; i < pingCount; i++) {
os.write("4\r\n".getBytes());
os.write("PING\r\n".getBytes());
os.flush();
Thread.sleep(1000);
}
os.write("0\r\n".getBytes());
os.write("\r\n".getBytes());
} catch (Exception e) {
this.e = e;
}
}
}
private static class ResponseReaderThread extends Thread {
private final InputStream is;
private StringBuilder response = new StringBuilder();
private volatile Exception e = null;
public ResponseReaderThread(InputStream is) {
this.is = is;
}
public Exception getException() {
return e;
}
public String getResponse() {
return response.toString();
}
@Override
public void run() {
try {
int c = is.read();
while (c > -1) {
response.append((char) c);
c = is.read();
}
} catch (Exception e) {
this.e = e;
}
}
}
private static class AsyncCometCloseValve extends ValveBase {
@Override
public void invoke(Request request, Response response)
throws IOException, ServletException {
CometEventImpl event = new CometEventImpl(request, response);
getNext().invoke(request, response);
if (request.isComet()) {
Thread t = new AsyncCometCloseThread(event);
t.start();
}
}
}
private static class AsyncCometCloseThread extends Thread {
private final CometEvent event;
public AsyncCometCloseThread(CometEvent event) {
this.event = event;
}
@Override
public void run() {
try {
Thread.sleep(2000);
event.close();
} catch (Exception e) {
// Test should fail. Report what went wrong.
e.printStackTrace();
}
}
}
}
|