View Javadoc

1   /*
2    * 
3    *   Magic-Project is a turn based strategy simulator
4    *   Copyright (C) 2003-2007 Fabrice Daugan
5    *
6    *   This program is free software; you can redistribute it and/or modify it 
7    * under the terms of the GNU General Public License as published by the Free 
8    * Software Foundation; either version 2 of the License, or (at your option) any
9    * later version.
10   *
11   *   This program is distributed in the hope that it will be useful, but WITHOUT 
12   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13   * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more 
14   * details.
15   *
16   *   You should have received a copy of the GNU General Public License along  
17   * with this program; if not, write to the Free Software Foundation, Inc., 
18   * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19   */
20  package net.sf.magicproject.network;
21  
22  import java.io.IOException;
23  import java.io.InputStream;
24  
25  /***
26   * @author <a href="mailto:fabdouglas@users.sourceforge.net">Fabrice Daugan </a>
27   */
28  class VirtualInputStream extends InputStream {
29  
30  	private static final int MAX_SIZE = 300;
31  
32  	/***
33  	 * As standard read method, if buffer is empty, current thread would be
34  	 * blocked until bytes would be available
35  	 * 
36  	 * @return the next available byte
37  	 * @throws IOException
38  	 *           never throwsn, but inheritence constraint the presence of this
39  	 *           tag
40  	 * @see java.io.InputStream#read()
41  	 */
42  	@Override
43  	public synchronized int read() throws IOException {
44  		if (disconnected) {
45  			throw new IOException("disconnected");
46  		}
47  		try {
48  			while (pointerRead == pointerAdd) {
49  				wait(500);
50  			}
51  		} catch (InterruptedException e) {
52  			e.printStackTrace();
53  		}
54  		if (disconnected) {
55  			throw new IOException("disconnected");
56  		}
57  		return buffer[pointerRead++ % MAX_SIZE];
58  	}
59  
60  	/***
61  	 * Update the buffer with the next message read from the given input stram.
62  	 * 
63  	 * @param in
64  	 *          the input stream containing the message to read.
65  	 * @throws IOException
66  	 *           If some other I/O error occurs
67  	 */
68  	synchronized void newMessage(InputStream in) throws IOException {
69  		int size = in.read();
70  		while (size-- > 0) {
71  			buffer[pointerAdd++ % MAX_SIZE] = in.read();
72  		}
73  		notify();
74  	}
75  
76  	@Override
77  	public synchronized void reset() {
78  		pointerAdd++;
79  		disconnected = true;
80  		notify();
81  	}
82  
83  	private boolean disconnected = false;
84  
85  	private int[] buffer = new int[MAX_SIZE];
86  
87  	private int pointerAdd = 0;
88  
89  	private int pointerRead = 0;
90  
91  }