1 /*
   2  * Copyright (c) 2002, 2010, 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  * Utility class for tests. A simple "in-thread" server to accept connections
  26  * and write bytes.
  27  * @author kladko
  28  */
  29 
  30 import java.net.Socket;
  31 import java.net.ServerSocket;
  32 import java.net.SocketAddress;
  33 import java.net.InetSocketAddress;
  34 import java.io.IOException;
  35 import java.io.Closeable;
  36 
  37 public class ByteServer implements Closeable {
  38 
  39     private final ServerSocket ss;
  40     private Socket s;
  41 
  42     ByteServer() throws IOException {
  43         this.ss = new ServerSocket(0);
  44     }
  45 
  46     SocketAddress address() {
  47         return new InetSocketAddress(ss.getInetAddress(), ss.getLocalPort());
  48     }
  49 
  50     void acceptConnection() throws IOException {
  51         if (s != null)
  52             throw new IllegalStateException("already connected");
  53         this.s = ss.accept();
  54     }
  55 
  56     void closeConnection() throws IOException {
  57         Socket s = this.s;
  58         if (s != null) {
  59             this.s = null;
  60             s.close();
  61         }
  62     }
  63 
  64     void write(int count) throws IOException {
  65         if (s == null)
  66             throw new IllegalStateException("no connection");
  67         s.getOutputStream().write(new byte[count]);
  68     }
  69 
  70     public void close() throws IOException {
  71         if (s != null)
  72             s.close();
  73         ss.close();
  74     }
  75 }