View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.core.net.server.test;
15  
16  import java.io.IOException;
17  import java.util.concurrent.BlockingQueue;
18  import java.util.concurrent.LinkedBlockingQueue;
19  
20  import ch.qos.logback.core.net.server.Client;
21  import ch.qos.logback.core.net.server.ServerListener;
22  
23  /**
24   * A mock {@link ServerListener} that has a blocking queue to pass a client
25   * to a {@link #acceptClient()} caller.  If the {@link #close()} method is
26   * called while a caller is blocked waiting to take from the queue, the
27   * caller's thread is interrupted.
28   *
29   * @author Carl Harris
30   */
31  public class MockServerListener<T extends Client> implements ServerListener<T> {
32  
33      private final BlockingQueue<T> queue = new LinkedBlockingQueue<T>();
34  
35      private boolean closed;
36      private Thread waiter;
37  
38      public synchronized Thread getWaiter() {
39          return waiter;
40      }
41  
42      public synchronized void setWaiter(Thread waiter) {
43          this.waiter = waiter;
44      }
45  
46      public synchronized boolean isClosed() {
47          return closed;
48      }
49  
50      public synchronized void setClosed(boolean closed) {
51          this.closed = closed;
52      }
53  
54      public T acceptClient() throws IOException, InterruptedException {
55          if (isClosed()) {
56              throw new IOException("closed");
57          }
58          setWaiter(Thread.currentThread());
59          try {
60              return queue.take();
61          } finally {
62              setWaiter(null);
63          }
64      }
65  
66      public void addClient(T client) {
67          queue.offer(client);
68      }
69  
70      public synchronized void close() {
71          setClosed(true);
72          Thread waiter = getWaiter();
73          if (waiter != null) {
74              waiter.interrupt();
75          }
76      }
77  
78  }