jdk/test/sample/chatserver/ChatTest.java
changeset 9254 142881732d3c
child 25859 3317bb8137f4
equal deleted inserted replaced
9253:12f80cd90505 9254:142881732d3c
       
     1 /*
       
     2  * Copyright (c) 2011 Oracle and/or its affiliates. All rights reserved.
       
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
       
     4  *
       
     5  * This code is free software; you can redistribute it and/or modify it
       
     6  * under the terms of the GNU General Public License version 2 only, as
       
     7  * published by the Free Software Foundation.
       
     8  *
       
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
       
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
       
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
       
    12  * version 2 for more details (a copy is included in the LICENSE file that
       
    13  * accompanied this code).
       
    14  *
       
    15  * You should have received a copy of the GNU General Public License version
       
    16  * 2 along with this work; if not, write to the Free Software Foundation,
       
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
       
    18  *
       
    19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
       
    20  * or visit www.oracle.com if you need additional information or have any
       
    21  * questions.
       
    22  */
       
    23 
       
    24 
       
    25 /* @test
       
    26  * @summary Test chat server chatserver test
       
    27  *
       
    28  * @library ../../../src/share/sample/nio/chatserver
       
    29  * @build ChatTest ChatServer Client ClientReader DataReader MessageReader NameReader
       
    30  * @run main ChatTest
       
    31  */
       
    32 
       
    33 import java.io.*;
       
    34 import java.net.InetSocketAddress;
       
    35 import java.net.Socket;
       
    36 import java.util.ArrayList;
       
    37 import java.util.Collections;
       
    38 import java.util.List;
       
    39 import java.util.concurrent.CyclicBarrier;
       
    40 
       
    41 public class ChatTest {
       
    42     public static int listeningPort = 0;
       
    43 
       
    44     public static void main(String[] args) throws Throwable {
       
    45         testStartStop();
       
    46         testPortOpen();
       
    47         testAsksForName();
       
    48         testUseName();
       
    49         testConnectDisconnectConnect();
       
    50         testUsernameAndMessage();
       
    51         testDontReceiveMessageInNameState();
       
    52     }
       
    53 
       
    54     private static ChatServer startServer() throws IOException {
       
    55         ChatServer server = new ChatServer(0);
       
    56         InetSocketAddress address = (InetSocketAddress) server.getSocketAddress();
       
    57         listeningPort = address.getPort();
       
    58         server.run();
       
    59         return server;
       
    60     }
       
    61 
       
    62     public static void testStartStop() throws Exception {
       
    63         ChatServer server = startServer();
       
    64         server.shutdown();
       
    65     }
       
    66 
       
    67     public static void testPortOpen() throws Exception {
       
    68         ChatServer server = startServer();
       
    69         try {
       
    70             Socket socket = new Socket("localhost", listeningPort);
       
    71             if (!socket.isConnected()) {
       
    72                 throw new RuntimeException("Failed to connect to server: port not open");
       
    73             }
       
    74         } finally {
       
    75             server.shutdown();
       
    76         }
       
    77     }
       
    78 
       
    79     public static void testAsksForName() throws Exception {
       
    80         ChatServer server = startServer();
       
    81         try {
       
    82             Socket socket = new Socket("localhost", listeningPort);
       
    83 
       
    84             Reader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
       
    85             String string = readAvailableString(reader);
       
    86             if (!string.equals("Name: ")) {
       
    87                 throw new RuntimeException("Server doesn't send Name: ");
       
    88             }
       
    89         } finally {
       
    90             server.shutdown();
       
    91         }
       
    92     }
       
    93 
       
    94     public static void testUseName() throws Throwable {
       
    95         ChatServer server = startServer();
       
    96         try {
       
    97             performTestUseName();
       
    98         } finally {
       
    99             server.shutdown();
       
   100         }
       
   101     }
       
   102 
       
   103     public static void testConnectDisconnectConnect() throws Exception {
       
   104         ChatServer server = startServer();
       
   105         try {
       
   106             performTestConnectDisconnectConnect();
       
   107         } finally {
       
   108             server.shutdown();
       
   109         }
       
   110     }
       
   111 
       
   112     public static void testUsernameAndMessage() throws Exception {
       
   113         ChatServer server = startServer();
       
   114         try {
       
   115             performTestUsernameAndMessage();
       
   116         } finally {
       
   117             server.shutdown();
       
   118         }
       
   119     }
       
   120 
       
   121     public static void testDontReceiveMessageInNameState() throws Exception {
       
   122         ChatServer server = startServer();
       
   123         try {
       
   124             performDontReceiveMessageInNameState();
       
   125         } finally {
       
   126             server.shutdown();
       
   127         }
       
   128     }
       
   129 
       
   130     private static void assertEqual(List<Exception> exception, Object value, Object expected) {
       
   131         if (expected == value) {
       
   132             return;
       
   133         }
       
   134         if (expected == null) {
       
   135             exception.add(new RuntimeException("Expected null, but was: " + value));
       
   136             return;
       
   137         }
       
   138         if (!expected.equals(value)) {
       
   139             exception.add(new RuntimeException("Expected: " + expected + " but was: " + value));
       
   140             return;
       
   141         }
       
   142     }
       
   143 
       
   144     private static void performDontReceiveMessageInNameState() throws Exception {
       
   145         final CyclicBarrier barrier1 = new CyclicBarrier(2);
       
   146         final CyclicBarrier barrier2 = new CyclicBarrier(2);
       
   147         final CyclicBarrier barrier3 = new CyclicBarrier(2);
       
   148         final List<Exception> exceptions = Collections.synchronizedList(new ArrayList<Exception>());
       
   149 
       
   150         ChatConnection chatConnection = new ChatConnection() {
       
   151             @Override
       
   152             public void run(Socket socket, BufferedReader reader, Writer writer) throws Exception {
       
   153                 String string = readAvailableString(reader);
       
   154                 assertEqual(exceptions, string, "Name: ");
       
   155                 writer.write("testClient1\n");
       
   156                 waitForJoin(reader, "testClient1");
       
   157                 barrier1.await();
       
   158                 writer.write("Ignore this!\n");
       
   159                 barrier2.await();
       
   160                 barrier3.await();
       
   161             }
       
   162         };
       
   163 
       
   164         Thread client2 = new Thread(new ChatConnection() {
       
   165             @Override
       
   166             public void run(Socket socket, BufferedReader reader, Writer writer) throws Exception {
       
   167                 barrier1.await();
       
   168                 barrier2.await();
       
   169                 String string = readAvailableString(reader);
       
   170                 assertEqual(exceptions, string, "Name: ");
       
   171                 string = readAvailableString(reader, true);
       
   172                 assertEqual(exceptions, string, null);
       
   173                 writer.write("testClient2\n");
       
   174                 barrier3.await();
       
   175             }
       
   176         });
       
   177 
       
   178         client2.start();
       
   179         chatConnection.run();
       
   180         if (!exceptions.isEmpty()) {
       
   181             throw exceptions.get(0);
       
   182         }
       
   183 
       
   184     }
       
   185 
       
   186     private static void waitForJoin(BufferedReader reader, String s) throws IOException {
       
   187         String joined;
       
   188         do {
       
   189             joined = readAvailableString(reader);
       
   190         } while (!(joined != null && joined.contains("Welcome " + s)));
       
   191     }
       
   192 
       
   193     private static void performTestUsernameAndMessage() throws Exception {
       
   194         final CyclicBarrier barrier1 = new CyclicBarrier(2);
       
   195         final CyclicBarrier barrier2 = new CyclicBarrier(2);
       
   196         final CyclicBarrier barrier3 = new CyclicBarrier(2);
       
   197         final List<Exception> exceptions = Collections.synchronizedList(new ArrayList<Exception>());
       
   198 
       
   199         ChatConnection chatConnection = new ChatConnection() {
       
   200             @Override
       
   201             public void run(Socket socket, BufferedReader reader, Writer writer) throws Exception {
       
   202                 String string = readAvailableString(reader);
       
   203                 assertEqual(exceptions, string, "Name: ");
       
   204                 writer.write("testClient1\n");
       
   205                 waitForJoin(reader, "testClient1");
       
   206                 barrier1.await();
       
   207                 barrier2.await();
       
   208                 string = readAvailableString(reader);
       
   209                 assertEqual(exceptions, string, "testClient2: Hello world!\n");
       
   210                 barrier3.await();
       
   211             }
       
   212         };
       
   213 
       
   214         Thread client2 = new Thread(new ChatConnection() {
       
   215             @Override
       
   216             public void run(Socket socket, BufferedReader reader, Writer writer) throws Exception {
       
   217                 String string = readAvailableString(reader);
       
   218                 assertEqual(exceptions, string, "Name: ");
       
   219                 barrier1.await();
       
   220                 writer.write("testClient2\nHello world!\n");
       
   221                 barrier2.await();
       
   222                 barrier3.await();
       
   223             }
       
   224         });
       
   225 
       
   226         client2.start();
       
   227         chatConnection.run();
       
   228         if (!exceptions.isEmpty()) {
       
   229             throw exceptions.get(0);
       
   230         }
       
   231     }
       
   232 
       
   233     private static void performTestConnectDisconnectConnect() throws Exception {
       
   234         final CyclicBarrier barrier1 = new CyclicBarrier(2);
       
   235         final CyclicBarrier barrier2 = new CyclicBarrier(2);
       
   236         final CyclicBarrier barrier3 = new CyclicBarrier(2);
       
   237         final List<Exception> exceptions = new ArrayList<Exception>();
       
   238 
       
   239         ChatConnection chatConnection = new ChatConnection() {
       
   240             @Override
       
   241             public void run(Socket socket, BufferedReader reader, Writer writer) throws Exception {
       
   242                 String string = readAvailableString(reader);
       
   243                 assertEqual(exceptions, string, "Name: ");
       
   244                 writer.write("testClient1\n");
       
   245             }
       
   246         };
       
   247 
       
   248         ChatConnection chatConnection2 = new ChatConnection() {
       
   249             @Override
       
   250             public void run(Socket socket, BufferedReader reader, Writer writer) throws Exception {
       
   251                 readAvailableString(reader);
       
   252                 writer.write("testClient1\n");
       
   253                 waitForJoin(reader, "testClient1");
       
   254                 barrier1.await();
       
   255                 writer.write("Good morning!\n");
       
   256                 barrier2.await();
       
   257                 String string = readAvailableString(reader);
       
   258                 assertEqual(exceptions, string, "testClient2: Hello world!\n");
       
   259                 barrier3.await();
       
   260             }
       
   261         };
       
   262 
       
   263         Thread client2 = new Thread(new ChatConnection() {
       
   264             @Override
       
   265             public void run(Socket socket, BufferedReader reader, Writer writer) throws Exception {
       
   266                 readAvailableString(reader);
       
   267                 writer.write("testClient2\n");
       
   268                 waitForJoin(reader, "testClient2");
       
   269                 barrier1.await();
       
   270                 writer.write("Hello world!\n");
       
   271                 barrier2.await();
       
   272                 String string = readAvailableString(reader);
       
   273                 assertEqual(exceptions, string, "testClient1: Good morning!\n");
       
   274                 barrier3.await();
       
   275             }
       
   276         });
       
   277 
       
   278         client2.start();
       
   279         chatConnection.run();
       
   280         chatConnection2.run();
       
   281         if (!exceptions.isEmpty()) {
       
   282             throw exceptions.get(0);
       
   283         }
       
   284     }
       
   285 
       
   286     private static void performTestUseName() throws Exception {
       
   287         final CyclicBarrier barrier1 = new CyclicBarrier(2);
       
   288         final CyclicBarrier barrier2 = new CyclicBarrier(2);
       
   289         final CyclicBarrier barrier3 = new CyclicBarrier(2);
       
   290         final List<Exception> exceptions = new ArrayList<Exception>();
       
   291 
       
   292         ChatConnection chatConnection = new ChatConnection() {
       
   293             @Override
       
   294             public void run(Socket socket, BufferedReader reader, Writer writer) throws Exception {
       
   295                 String string = readAvailableString(reader);
       
   296                 if (!"Name: ".equals(string)) {
       
   297                     exceptions.add(new RuntimeException("Expected Name: "));
       
   298                 }
       
   299                 writer.write("testClient1\n");
       
   300                 waitForJoin(reader, "testClient1");
       
   301                 barrier1.await();
       
   302                 barrier2.await();
       
   303                 string = readAvailableString(reader);
       
   304                 if (!"testClient2: Hello world!\n".equals(string)) {
       
   305                     exceptions.add(new RuntimeException("testClient2: Hello world!\n"));
       
   306                 }
       
   307                 barrier3.await();
       
   308             }
       
   309         };
       
   310 
       
   311         Thread client2 = new Thread(new ChatConnection() {
       
   312             @Override
       
   313             public void run(Socket socket, BufferedReader reader, Writer writer) throws Exception {
       
   314                 String string = readAvailableString(reader);
       
   315                 if (!"Name: ".equals(string)) {
       
   316                     exceptions.add(new RuntimeException("Expected Name: "));
       
   317                 }
       
   318                 writer.write("testClient2\n");
       
   319                 waitForJoin(reader, "testClient2");
       
   320                 barrier1.await();
       
   321                 writer.write("Hello world!\n");
       
   322                 barrier2.await();
       
   323                 barrier3.await();
       
   324             }
       
   325         });
       
   326 
       
   327         client2.start();
       
   328         chatConnection.run();
       
   329         if (!exceptions.isEmpty()) {
       
   330             throw exceptions.get(0);
       
   331         }
       
   332     }
       
   333 
       
   334     private static String readAvailableString(Reader reader) throws IOException {
       
   335         return readAvailableString(reader, false);
       
   336     }
       
   337 
       
   338     private static String readAvailableString(Reader reader, boolean now) throws IOException {
       
   339         StringBuilder builder = new StringBuilder();
       
   340         int bytes;
       
   341         if (now && !reader.ready()) {
       
   342             return null;
       
   343         }
       
   344         do {
       
   345             char[] buf = new char[256];
       
   346             bytes = reader.read(buf);
       
   347             builder.append(buf, 0, bytes);
       
   348         } while (bytes == 256);
       
   349         return builder.toString();
       
   350     }
       
   351 
       
   352     private abstract static class ChatConnection implements Runnable {
       
   353         public Exception exception;
       
   354 
       
   355         @Override
       
   356         public void run() {
       
   357             try (Socket socket = new Socket("localhost", listeningPort);
       
   358             BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
       
   359             Writer writer = new FlushingWriter(new OutputStreamWriter(socket.getOutputStream()))) {
       
   360                 socket.setTcpNoDelay(true);
       
   361 
       
   362                 run(socket, reader, writer);
       
   363             } catch (Exception e) {
       
   364                 exception = e;
       
   365             }
       
   366         }
       
   367 
       
   368         public abstract void run(Socket socket, BufferedReader reader, Writer writer) throws Exception;
       
   369     }
       
   370 
       
   371     private static class FlushingWriter extends Writer {
       
   372         public final Writer delegate;
       
   373 
       
   374         private FlushingWriter(Writer delegate) {
       
   375             this.delegate = delegate;
       
   376         }
       
   377 
       
   378         @Override
       
   379         public void write(char[] cbuf, int off, int len) throws IOException {
       
   380             delegate.write(cbuf, off, len);
       
   381         }
       
   382 
       
   383         @Override
       
   384         public void flush() throws IOException {
       
   385             delegate.flush();
       
   386         }
       
   387 
       
   388         @Override
       
   389         public void close() throws IOException {
       
   390             delegate.close();
       
   391         }
       
   392 
       
   393         @Override
       
   394         public void write(String str) throws IOException {
       
   395             super.write(str);
       
   396             flush();
       
   397         }
       
   398     }
       
   399 }