1 /*
   2  * Copyright (c) 2015, 2016, 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  * @bug 8151299
  27  * @summary Http client SelectorManager overwriting read and write events
  28  */
  29 package java.net.http;
  30 
  31 import java.net.*;
  32 import java.io.*;
  33 import java.nio.channels.*;
  34 import java.nio.ByteBuffer;
  35 import java.util.concurrent.CountDownLatch;
  36 import java.util.concurrent.atomic.AtomicInteger;
  37 import static java.lang.System.out;
  38 import static java.nio.charset.StandardCharsets.US_ASCII;
  39 import static java.util.concurrent.TimeUnit.SECONDS;
  40 
  41 import org.testng.annotations.Test;
  42 
  43 /**
  44  * Whitebox test of selector mechanics. Currently only a simple test
  45  * setting one read and one write event is done. It checks that the
  46  * write event occurs first, followed by the read event and then no
  47  * further events occur despite the conditions actually still existing.
  48  */
  49 @Test
  50 public class SelectorTest {
  51 
  52     AtomicInteger counter = new AtomicInteger();
  53     volatile boolean error;
  54     static final CountDownLatch finishingGate = new CountDownLatch(1);
  55 
  56     String readSomeBytes(RawChannel chan) {
  57         try {
  58             ByteBuffer buf = ByteBuffer.allocate(1024);
  59             int t = chan.read(buf);
  60             if (t <= 0) {
  61                 out.printf("chan read returned %d\n", t);
  62                 return null;
  63             }
  64             byte[] bb = new byte[t];
  65             buf.get(bb);
  66             return new String(bb, US_ASCII);
  67         } catch (IOException ioe) {
  68             throw new UncheckedIOException(ioe);
  69         }
  70     }
  71 
  72     @Test(timeOut = 10000)
  73     public void test() throws Exception {
  74 
  75         try (ServerSocket server = new ServerSocket(0)) {
  76             int port = server.getLocalPort();
  77 
  78             out.println("Listening on port " + server.getLocalPort());
  79 
  80             TestServer t = new TestServer(server);
  81             t.start();
  82             out.println("Started server thread");
  83 
  84             final RawChannel chan = getARawChannel(port);
  85 
  86             chan.registerEvent(new RawChannel.NonBlockingEvent() {
  87                 @Override
  88                 public int interestOps() {
  89                     return SelectionKey.OP_READ;
  90                 }
  91 
  92                 @Override
  93                 public void handle() {
  94                     readSomeBytes(chan);
  95                     out.printf("OP_READ\n");
  96                     if (counter.get() != 1) {
  97                         out.printf("OP_READ error counter = %d\n", counter);
  98                         error = true;
  99                     }
 100                 }
 101             });
 102 
 103             chan.registerEvent(new RawChannel.NonBlockingEvent() {
 104                 @Override
 105                 public int interestOps() {
 106                     return SelectionKey.OP_WRITE;
 107                 }
 108 
 109                 @Override
 110                 public void handle() {
 111                     out.printf("OP_WRITE\n");
 112                     if (counter.get() != 0) {
 113                         out.printf("OP_WRITE error counter = %d\n", counter);
 114                         error = true;
 115                     } else {
 116                         ByteBuffer bb = ByteBuffer.wrap(TestServer.INPUT);
 117                         counter.incrementAndGet();
 118                         try {
 119                             chan.write(bb);
 120                         } catch (IOException e) {
 121                             throw new UncheckedIOException(e);
 122                         }
 123                     }
 124                 }
 125 
 126             });
 127             out.println("Events registered. Waiting");
 128             finishingGate.await(30, SECONDS);
 129             if (error)
 130                 throw new RuntimeException("Error");
 131             else
 132                 out.println("No error");
 133         }
 134     }
 135 
 136     static RawChannel getARawChannel(int port) throws Exception {
 137         URI uri = URI.create("http://127.0.0.1:" + port + "/");
 138         out.println("client connecting to " + uri.toString());
 139         HttpRequest req = HttpRequest.create(uri).GET();
 140         HttpResponse r = req.response();
 141         r.body(HttpResponse.ignoreBody());
 142         return ((HttpResponseImpl) r).rawChannel();
 143     }
 144 
 145     static class TestServer extends Thread {
 146         static final byte[] INPUT = "Hello world".getBytes(US_ASCII);
 147         static final byte[] OUTPUT = "Goodbye world".getBytes(US_ASCII);
 148         static final String FIRST_RESPONSE = "HTTP/1.1 200 OK\r\nContent-length: 0\r\n\r\n";
 149         final ServerSocket server;
 150 
 151         TestServer(ServerSocket server) throws IOException {
 152             this.server = server;
 153         }
 154 
 155         public void run() {
 156             try (Socket s = server.accept();
 157                  InputStream is = s.getInputStream();
 158                  OutputStream os = s.getOutputStream()) {
 159 
 160                 out.println("Got connection");
 161                 readRequest(is);
 162                 os.write(FIRST_RESPONSE.getBytes());
 163                 read(is);
 164                 write(os);
 165                 Thread.sleep(1000);
 166                 // send some more data, and make sure WRITE op does not get called
 167                 write(os);
 168                 out.println("TestServer exiting");
 169                 SelectorTest.finishingGate.countDown();
 170             } catch (Exception e) {
 171                 e.printStackTrace();
 172             }
 173         }
 174 
 175         // consumes the HTTP request
 176         static void readRequest(InputStream is) throws IOException {
 177             out.println("starting readRequest");
 178             byte[] buf = new byte[1024];
 179             String s = "";
 180             while (true) {
 181                 int n = is.read(buf);
 182                 if (n <= 0)
 183                     throw new IOException("Error");
 184                 s = s + new String(buf, 0, n);
 185                 if (s.indexOf("\r\n\r\n") != -1)
 186                     break;
 187             }
 188             out.println("returning from readRequest");
 189         }
 190 
 191         static void read(InputStream is) throws IOException {
 192             out.println("starting read");
 193             for (int i = 0; i < INPUT.length; i++) {
 194                 int c = is.read();
 195                 if (c == -1)
 196                     throw new IOException("closed");
 197                 if (INPUT[i] != (byte) c)
 198                     throw new IOException("Error. Expected:" + INPUT[i] + ", got:" + c);
 199             }
 200             out.println("returning from read");
 201         }
 202 
 203         static void write(OutputStream os) throws IOException {
 204             out.println("doing write");
 205             os.write(OUTPUT);
 206         }
 207     }
 208 }