{
log.info("entering: testVirtualSelector()");
try
{
final VirtualSelector vs = new VirtualSelector();
final GrowablePipedInputStream gpis1 = new GrowablePipedInputStream(vs);
final GrowablePipedOutputStream gpos1 = new GrowablePipedOutputStream(gpis1);
final GrowablePipedInputStream gpis2 = new GrowablePipedInputStream(vs);
final GrowablePipedOutputStream gpos2 = new GrowablePipedOutputStream(gpis2);
final int size = 128 * 1024;
final byte[] bytesOut1 = new byte[size];
final byte[] bytesOut2 = new byte[size];
final ShrinkableByteArrayOutputStream bytesIn1 = new ShrinkableByteArrayOutputStream();
final ShrinkableByteArrayOutputStream bytesIn2 = new ShrinkableByteArrayOutputStream();
for (int i = 0; i < size; i++)
{
bytesOut1[i] = (byte) i;
bytesOut2[i] = (byte) (i+1);
}
vs.register(gpis1, new Integer(1));
vs.register(gpis2, new Integer(2));
class ThreadIn extends Thread
{
Exception e;
public void run()
{
Map readyMap;
log.info("starting run()");
try
{
while ((readyMap = vs.select()) != null)
{
log.debug("readyMap != null");
Iterator it = readyMap.keySet().iterator();
while (it.hasNext())
{
InputStream is = (InputStream) it.next();
if (is.available() == 0)
{
it.remove();
continue;
}
Integer attachment = (Integer) readyMap.get(is);
ShrinkableByteArrayOutputStream bytesIn;
if (attachment.intValue() == 1)
bytesIn = bytesIn1;
else
bytesIn = bytesIn2;
try
{
int available = is.available();
log.debug("available: " + available);
log.debug("stream: " + attachment);
for (int i = 0; i < available; i++)
bytesIn.write((byte) is.read());
}
catch (IOException e)
{
this.e = e;
}
}
}
}
catch (Exception e)
{
log.error(e);
e.printStackTrace();
}
log.info("ending run()");
}
public Exception getException()
{
return e;
}
};
class ThreadOut extends Thread
{
OutputStream os;
byte[] bytesOut;
Exception e;
public ThreadOut(OutputStream os, byte[] bytesOut)
{
this.os = os;
this.bytesOut = bytesOut;
}
public void run()
{
try
{
for (int i = 0; i < size / 2; i++)
os.write(bytesOut[i]);
int chunk = 4096;
for (int i = size / 2; i < size; )
{
os.write(bytesOut, i, chunk);
i += chunk;
}
// for (int i = 0; i < size; i++)
// {
// log.warn("writing: " + bytesOut[i]);
// os.write(bytesOut[i]);
// }
}
catch (IOException e)
{
this.e = e;
}
}
public Exception getException()
{
return e;
}
};
ThreadIn tin = new ThreadIn();
ThreadOut t1out = new ThreadOut(gpos1, bytesOut1);
ThreadOut t2out = new ThreadOut(gpos2, bytesOut2);
tin.start();
t1out.start();
t2out.start();
t1out.join();
t2out.join();
Thread.sleep(1000);
log.info("waitUntilEmpty()");
vs.waitUntilEmpty();
log.info("close()");
vs.close();
log.info("tin.join()");
tin.join();
assertTrue(tin.getException() == null);
assertTrue(t1out.getException() == null);