Ejemplo n.º 1
0
  public Signaler() {
    //  Create the socketpair for signaling.
    Pipe pipe;

    try {
      pipe = Pipe.open();
    } catch (IOException e) {
      throw new ZError.IOException(e);
    }
    r = pipe.source();
    w = pipe.sink();

    //  Set both fds to non-blocking mode.
    try {
      Utils.unblockSocket(w);
      Utils.unblockSocket(r);
    } catch (IOException e) {
      throw new ZError.IOException(e);
    }

    try {
      selector = Selector.open();
      r.register(selector, SelectionKey.OP_READ);
    } catch (IOException e) {
      throw new ZError.IOException(e);
    }
  }
Ejemplo n.º 2
0
  private static void scScatter() throws Exception {
    Pipe p = Pipe.open();
    Pipe.SinkChannel sink = p.sink();
    Pipe.SourceChannel source = p.source();
    sink.configureBlocking(false);

    ByteBuffer outgoingdata = ByteBuffer.allocateDirect(30);
    byte[] someBytes = new byte[30];
    generator.nextBytes(someBytes);
    outgoingdata.put(someBytes);
    outgoingdata.flip();

    int totalWritten = 0;
    while (totalWritten < 30) {
      int written = sink.write(outgoingdata);
      if (written < 0) throw new Exception("Write failed");
      totalWritten += written;
    }

    ByteBuffer[] bufs = new ByteBuffer[3];
    for (int i = 0; i < 3; i++) bufs[i] = ByteBuffer.allocateDirect(10);
    long numBytesRead = source.read(bufs);
    if (numBytesRead < 30) throw new Exception("Pipe test failed");
    sink.close();
    source.close();
  }
Ejemplo n.º 3
0
 @Override
 public boolean onReadable() {
   if (!mReady) {
     try {
       mOutput.source().register(AdbServer.server().selector(), 0, this);
     } catch (ClosedChannelException e) {
       e.printStackTrace();
       return false;
     }
   }
   mOutputBuffer.clear();
   int result = -1;
   try {
     result = mOutput.source().read(mOutputBuffer);
   } catch (IOException e) {
     e.printStackTrace();
   }
   if (result < 0) {
     // Pipe is closed.
     return false;
   } else if (result > 0) {
     mOutputBuffer.flip();
     AdbMessage message = new AdbMessage();
     message.data = new byte[result];
     mOutputBuffer.get(message.data);
     mPeer.enqueue(message);
     mReady = false;
   }
   return true;
 }
Ejemplo n.º 4
0
  protected AdbThreadSocket(String name) throws IOException {
    mInput = Pipe.open();
    mInput.sink().configureBlocking(false);
    mOutput = Pipe.open();
    mOutput.source().configureBlocking(false);
    mOutputBuffer = ByteBuffer.allocate(AdbMessage.MAX_PAYLOAD);

    mThread =
        new Thread(
            new Runnable() {
              @Override
              public void run() {
                loop();
                try {
                  output().close();
                } catch (IOException e) {
                  e.printStackTrace();
                }
                try {
                  input().close();
                } catch (IOException e) {
                  e.printStackTrace();
                }
              }
            },
            name);
  }
Ejemplo n.º 5
0
  /**
   * A convenience method for the following code:
   *
   * <pre>
   * {@link Pipe} inputToOutput = {@link Pipe#open()};
   * {@link Pipe.SourceChannel} source = {@link Pipe#source() inputToOutput.source()};
   * {@link SelectableChannel#configureBlocking(boolean) source.configureBlocking(false)};
   * {@link #addRoute(SelectableChannel, SelectableChannel) addRoute(source, output)};
   *
   * {@link Pipe.SinkChannel} sink = {@link Pipe#sink() inputToOutput.sink()};
   * return {@link #wrapChannelInObjectOutputStream(WritableByteChannel) wrapChannelInObjectOutputStream(sink)};
   * </pre>
   *
   * Users must call {@link ObjectOutputStream#flush()} before attempting to construct a matching
   * {@link ObjectInputStream} to ensure a serialization header is available.
   *
   * @throws IOException pass-through for any {@link IOException} that occurs in the above code
   */
  public <T extends SelectableChannel & WritableByteChannel>
      ObjectOutputStream addRouteFromObjectOutputStream(T output) throws IOException {
    Pipe inputToOutput = Pipe.open();
    Pipe.SourceChannel source = inputToOutput.source();
    source.configureBlocking(false);
    addRoute(source, output);

    Pipe.SinkChannel sink = inputToOutput.sink();
    return wrapChannelInObjectOutputStream(sink);
  }
Ejemplo n.º 6
0
  /**
   * A convenience method for the following code:
   *
   * <pre>
   * {@link Pipe} inputToOutput = {@link Pipe#open()};
   * {@link Pipe.SinkChannel} sink = {@link Pipe#sink() inputToOutput.sink()};
   * {@link SelectableChannel#configureBlocking(boolean) sink.configureBlocking(false)};
   * {@link #addRoute(SelectableChannel, SelectableChannel) addRoute(input, sink)};
   *
   * {@link Pipe.SourceChannel} source = {@link Pipe#source() inputToOutput.source()};
   * return {@link #wrapChannelInObjectInputStream(ReadableByteChannel) wrapChannelInObjectInputStream(source)};
   * </pre>
   *
   * @throws IOException pass-through for any {@link IOException} that occurs in the above code
   */
  public <T extends SelectableChannel & ReadableByteChannel>
      ObjectInputStream addRouteToObjectInputStream(T input) throws IOException {
    Pipe inputToOutput = Pipe.open();
    Pipe.SinkChannel sink = inputToOutput.sink();
    sink.configureBlocking(false);
    addRoute(input, sink);

    Pipe.SourceChannel source = inputToOutput.source();
    return wrapChannelInObjectInputStream(source);
  }
	@Test
	public void testReadingCallable() throws Exception {

		// Exit gracefully on close

		Pipe pipe = Pipe.open();

		final SourceChannel sourceChannel = pipe.source();
		SinkChannel sinkChannel = pipe.sink();

		try {
			MockRegistrationReference mockRegistrationReference =
				new MockRegistrationReference(_executorIntraband);

			ChannelContext channelContext = new ChannelContext(
				new LinkedList<Datagram>());

			channelContext.setRegistrationReference(mockRegistrationReference);

			ReadingCallable readingCallable =
				_executorIntraband.new ReadingCallable(
					sourceChannel, channelContext);

			SyncThrowableThread<Void> syncThrowableThread =
				new SyncThrowableThread<>(
					new Callable<Void>() {

						@Override
						public Void call() throws Exception {
							sleep(100);

							sourceChannel.close();

							return null;
						}

					});

			syncThrowableThread.start();

			readingCallable.openLatch();

			Void result = readingCallable.call();

			syncThrowableThread.sync();

			Assert.assertNull(result);
			Assert.assertFalse(mockRegistrationReference.isValid());
		}
		finally {
			sourceChannel.close();
			sinkChannel.close();
		}
	}
 public SelectorImpl(SelectorProvider selectorProvider) {
   super(selectorProvider);
   try {
     Pipe mockSelector = selectorProvider.openPipe();
     sink = mockSelector.sink();
     source = mockSelector.source();
     sourcefd = ((FileDescriptorHandler) source).getFD();
     source.configureBlocking(false);
   } catch (IOException e) {
     // do nothing
   }
 }
Ejemplo n.º 9
0
  /** {@inheritDoc} */
  @Override
  public ReadableByteChannel getImagesData() {

    // Leverage the raw frame decoder as input to the colour decoder
    Pipe pipe = null;
    try {
      pipe = Pipe.open();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    decoderthreadpool.execute(new ColourFrameDecoder(getRawImageData(), pipe.sink()));
    return pipe.source();
  }
Ejemplo n.º 10
0
  /** {@inheritDoc} */
  @Override
  public ReadableByteChannel getRawImageData() {

    Pipe pipe = null;
    try {
      pipe = Pipe.open();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    decoderthreadpool.execute(
        new RawFrameDecoder(new DuplicateReadOnlyByteChannel(bytechannel), pipe.sink()));
    return pipe.source();
  }
Ejemplo n.º 11
0
  /** This is for thr_new(2) (fork(2) also uses this internally). */
  public Slave newSlave(
      PairId newPairId,
      Process process,
      NormalizedPath currentDirectory,
      Permissions permissions,
      Links links,
      Slave.Listener listener)
      throws IOException {
    Pipe slave2hub = Pipe.open();
    Pipe hub2slave = Pipe.open();

    Slave slave =
        new Slave(
            this,
            process,
            new SyscallReadableChannel(hub2slave.source()),
            new SyscallWritableChannel(slave2hub.sink()),
            currentDirectory,
            permissions,
            links,
            listener);
    process.add(slave);

    mSlaveHub.addSlave(
        new SyscallReadableChannel(slave2hub.source()),
        new SyscallWritableChannel(hub2slave.sink()),
        newPairId);

    return slave;
  }
Ejemplo n.º 12
0
  public Overlord() {
    try {
      selector = Selector.open();
      queue = new ConcurrentLinkedQueue<Communicator>();

      // open the pipe and register it with our selector
      pipe = Pipe.open();
      pipe.sink().configureBlocking(false);
      pipe.source().configureBlocking(false);
      pipe.source().register(selector, SelectionKey.OP_READ);
    } catch (IOException e) {
      throw new RuntimeException("select() failed");
    }
  }
Ejemplo n.º 13
0
 @Override
 public boolean onWritable() {
   try {
     if (mInputBuffer != null) {
       mInput.sink().write(mInputBuffer);
       if (!mInputBuffer.hasRemaining()) mInputBuffer = null;
     }
     if (mInputBuffer == null) {
       mInput.sink().register(AdbServer.server().selector(), SelectionKey.OP_WRITE, this);
     }
     return true;
   } catch (IOException e) {
     e.printStackTrace();
     return false;
   }
 }
Ejemplo n.º 14
0
  public int run(
      SyscallReadableChannel in,
      SyscallWritableChannel out,
      NormalizedPath currentDirectory,
      InputStream stdin,
      OutputStream stdout,
      OutputStream stderr,
      Permissions permissions,
      Links links,
      Slave.Listener listener,
      String resourceDirectory)
      throws IOException, InterruptedException {
    mLogger.info("starting a slave application");

    mResourceDirectory = resourceDirectory;

    initializeInitProcess();

    Process process = new Process(mPidGenerator.next(), mInit);
    mInit.addChild(process);
    addProcess(process);

    Pipe slave2hub = Pipe.open();
    Pipe hub2slave = Pipe.open();
    Slave slave =
        new Slave(
            this,
            process,
            new SyscallReadableChannel(hub2slave.source()),
            new SyscallWritableChannel(slave2hub.sink()),
            currentDirectory,
            stdin,
            stdout,
            stderr,
            permissions,
            links,
            listener);
    process.add(slave);

    mSlaveHub =
        new SlaveHub(
            this,
            in,
            out,
            new SyscallReadableChannel(slave2hub.source()),
            new SyscallWritableChannel(hub2slave.sink()));

    new Thread(slave).start();
    mSlaveHub.work();
    synchronized (mAlarm) {
      while (!mProcesses.isEmpty()) {
        mAlarm.wait();
      }
    }

    return !mCancelled ? mExitStatus : 255;
  }
Ejemplo n.º 15
0
  public static void main(String[] argv) throws Exception {
    Pipe[] pipes = new Pipe[PIPES_COUNT];
    Pipe pipe = Pipe.open();
    Pipe.SinkChannel sink = pipe.sink();
    Pipe.SourceChannel source = pipe.source();
    Selector sel = Selector.open();
    source.configureBlocking(false);
    source.register(sel, SelectionKey.OP_READ);

    for (int i = 0; i < PIPES_COUNT; i++) {
      pipes[i] = Pipe.open();
      Pipe.SourceChannel sc = pipes[i].source();
      sc.configureBlocking(false);
      sc.register(sel, SelectionKey.OP_READ);
      Pipe.SinkChannel sc2 = pipes[i].sink();
      sc2.configureBlocking(false);
      sc2.register(sel, SelectionKey.OP_WRITE);
    }

    for (int i = 0; i < LOOPS; i++) {
      sink.write(ByteBuffer.allocate(BUF_SIZE));
      int x = sel.selectNow();
      sel.selectedKeys().clear();
      source.read(ByteBuffer.allocate(BUF_SIZE));
    }

    for (int i = 0; i < PIPES_COUNT; i++) {
      pipes[i].sink().close();
      pipes[i].source().close();
    }
    pipe.sink().close();
    pipe.source().close();
    sel.close();
  }
Ejemplo n.º 16
0
  /**
   * Returns a readable byte channel based on the given representation's content and its
   * write(WritableByteChannel) method. Internally, it uses a writer thread and a pipe channel.
   *
   * @param representation the representation to get the {@link OutputStream} from.
   * @return A readable byte channel.
   * @throws IOException
   */
  public static ReadableByteChannel getChannel(final Representation representation)
      throws IOException {
    ReadableByteChannel result = null;
    if (Edition.CURRENT != Edition.GAE) {
      final java.nio.channels.Pipe pipe = java.nio.channels.Pipe.open();
      org.restlet.Application application = org.restlet.Application.getCurrent();

      // Get a thread that will handle the task of continuously
      // writing the representation into the input side of the pipe
      Runnable task =
          new Runnable() {
            public void run() {
              try {
                WritableByteChannel wbc = pipe.sink();
                representation.write(wbc);
                wbc.close();
              } catch (IOException ioe) {
                Context.getCurrentLogger()
                    .log(Level.FINE, "Error while writing to the piped channel.", ioe);
              }
            }
          };

      if (application != null && application.getTaskService() != null) {
        application.getTaskService().execute(task);
      } else {
        new Thread(task).start();
      }

      result = pipe.source();
    } else {
      Context.getCurrentLogger()
          .log(
              Level.WARNING,
              "The GAE edition is unable to return a channel for a representation given its write(WritableByteChannel) method.");
    }
    return result;
  }
Ejemplo n.º 17
0
 @Override
 public int enqueue(AdbMessage message) {
   if (mInputBuffer != null) return -1;
   mInputBuffer = ByteBuffer.wrap(message.data, 0, message.dataLength);
   try {
     mInput.sink().write(mInputBuffer);
   } catch (IOException e) {
     e.printStackTrace();
     mInputBuffer = null;
     return -1;
   }
   if (mInputBuffer.hasRemaining()) {
     try {
       mInput.sink().register(AdbServer.server().selector(), SelectionKey.OP_WRITE, this);
     } catch (ClosedChannelException e) {
       mInputBuffer = null;
       return -1;
     }
     return 1;
   }
   mInputBuffer = null;
   return 0;
 }
Ejemplo n.º 18
0
  public void ready() {
    if (mInitialized == false) {
      mThread.start();
      mInitialized = true;
    }

    try {
      mOutput.source().register(AdbServer.server().selector(), SelectionKey.OP_READ, this);
      mReady = true;
    } catch (ClosedChannelException e) {
      e.printStackTrace();
      close();
    }
  }
Ejemplo n.º 19
0
  public ProcessInCtrl(FT_Device ftDevice) {
    this.ftDevice = ftDevice;
    this.driverParameters = this.ftDevice.getDriverParameters();
    this.bufferCount = this.driverParameters.getBufferCount();
    int maxBufferSize = this.driverParameters.getMaxBufferSize();
    this.cbMaxPacketSizeIn = this.ftDevice.getCbMaxPacketSizeIn();
    this.mWritable = new Semaphore[this.bufferCount];
    this.mReadable = new Semaphore[this.bufferCount];
    this.mInputBufs = new InBuffer[this.bufferCount];
    this.byteBuffers = new ByteBuffer[256];
    this.mInFullLock = new ReentrantLock();
    this.mFullCon = this.mInFullLock.newCondition();
    this.mSinkFull = false;
    this.qLock = new ReentrantLock();
    this.qCondition = this.qLock.newCondition();
    this.cbAvailableToReadLock = new Object();
    this.mSinkFullLock = new Object();
    this.clearCbAvailableToRead();
    this.d = ByteBuffer.allocateDirect(maxBufferSize);

    try {
      this.pipe = Pipe.open();
      this.sinkChannel = this.pipe.sink();
      this.sourceChannel = this.pipe.source();
    } catch (IOException e) {
      Log.d("ProcessInCtrl", "Create mMainPipe failed!");
      e.printStackTrace();
    }

    for (int iBuffer = 0; iBuffer < this.bufferCount; ++iBuffer) {
      this.mInputBufs[iBuffer] = new InBuffer(maxBufferSize);
      this.mReadable[iBuffer] = new Semaphore(1);
      this.mWritable[iBuffer] = new Semaphore(1);

      try {
        this.acquireReadableBuffer(iBuffer);
      } catch (Exception var5) {
        Log.d("ProcessInCtrl", "Acquire read buffer " + iBuffer + " failed!");
        var5.printStackTrace();
      }
    }
  }
Ejemplo n.º 20
0
  public static void main(String[] args) throws IOException {
    ChannelRouter channelRouter =
        new ChannelRouter(
            new ExceptionListener<IOException>() {
              @Override
              public void exceptionThrown(IOException exception) {
                exception.printStackTrace();
              }
            });

    int port = Integer.parseInt(args[1]);
    SocketChannel socketChannel;
    if (args[0].equals("--server")) {
      System.out.println("Server mode started; listening on port " + port);
      ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
      serverSocketChannel.socket().bind(new InetSocketAddress(port));
      socketChannel = serverSocketChannel.accept();
      System.out.println("Client connected");
      serverSocketChannel.close();
    } else {
      String host = args[0];
      System.out.println("Client mode started; connecting to " + host + " on port " + port);
      socketChannel = SocketChannel.open(new InetSocketAddress(host, port));
      System.out.println("Connected to server");
    }
    socketChannel.configureBlocking(false);

    Pipe localToRemote = Pipe.open();
    localToRemote.source().configureBlocking(false);
    channelRouter.addRoute(localToRemote.source(), socketChannel);

    final Pipe remoteToLocal = Pipe.open();
    remoteToLocal.sink().configureBlocking(false);
    channelRouter.addRoute(socketChannel, remoteToLocal.sink());

    Thread channelRouterThread = new Thread(channelRouter, "ChannelRouter");
    channelRouterThread.start();

    Thread remoteReaderThread =
        new Thread("RemoteReader") {
          @Override
          public void run() {
            try {
              // BufferedReader.readLine() blocks until an end-of-line is
              // written, so make sure they get written by the main thread
              InputStream temporaryInputStream = Channels.newInputStream(remoteToLocal.source());
              BufferedReader in = new BufferedReader(new InputStreamReader(temporaryInputStream));
              String line = in.readLine();
              while (null != line) {
                System.out.println(line);
                line = in.readLine();
              }
            } catch (ClosedByInterruptException e) {
              // The main thread wants us to close, so do nothing
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        };
    remoteReaderThread.start();

    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    Writer temporaryWriter = new OutputStreamWriter(Channels.newOutputStream(localToRemote.sink()));
    temporaryWriter = new BufferedWriter(temporaryWriter);
    PrintWriter out = new PrintWriter(temporaryWriter, true);

    System.out.println(
        "Press end-of-file to terminate (Ctrl+Z on Windows, Ctrl+D on other platforms)");
    String line = in.readLine();
    while (null != line) {
      // The end-of-line is required for BufferedReader.readLine() to
      // return and this will automatically flush due to the auto-flush
      // parameter on construction
      out.println(line);
      line = in.readLine();
    }

    remoteReaderThread.interrupt();
    channelRouterThread.interrupt();
    socketChannel.close();
  }
Ejemplo n.º 21
0
 protected Pipe.SourceChannel input() {
   return mInput.source();
 }
  @Test
  public void testSendDatagramWithoutCallback() throws Exception {

    // Single datagram sending

    Pipe readPipe = Pipe.open();
    Pipe writePipe = Pipe.open();

    GatheringByteChannel gatheringByteChannel = writePipe.sink();
    ScatteringByteChannel scatteringByteChannel = readPipe.source();

    SelectionKeyRegistrationReference registrationReference =
        (SelectionKeyRegistrationReference)
            _selectorIntraband.registerChannel(writePipe.source(), readPipe.sink());

    Thread wakeUpThread = new Thread(new WakeUpRunnable(_selectorIntraband));

    wakeUpThread.start();

    Selector selector = _selectorIntraband.selector;

    synchronized (selector) {
      wakeUpThread.interrupt();
      wakeUpThread.join();

      Datagram requestDatagram = Datagram.createRequestDatagram(_type, _data);

      _selectorIntraband.sendDatagram(registrationReference, requestDatagram);

      SelectionKey writeSelectionKey = registrationReference.writeSelectionKey;

      ChannelContext channelContext = (ChannelContext) writeSelectionKey.attachment();

      Queue<Datagram> sendingQueue = channelContext.getSendingQueue();

      Assert.assertEquals(1, sendingQueue.size());
      Assert.assertSame(requestDatagram, sendingQueue.peek());
    }

    Datagram receiveDatagram = IntrabandTestUtil.readDatagramFully(scatteringByteChannel);

    Assert.assertEquals(_type, receiveDatagram.getType());

    ByteBuffer dataByteBuffer = receiveDatagram.getDataByteBuffer();

    Assert.assertArrayEquals(_data, dataByteBuffer.array());

    // Two datagrams continuous sending

    Datagram requestDatagram1 = Datagram.createRequestDatagram(_type, _data);
    Datagram requestDatagram2 = Datagram.createRequestDatagram(_type, _data);

    wakeUpThread = new Thread(new WakeUpRunnable(_selectorIntraband));

    wakeUpThread.start();

    synchronized (selector) {
      wakeUpThread.interrupt();
      wakeUpThread.join();

      _selectorIntraband.sendDatagram(registrationReference, requestDatagram1);
      _selectorIntraband.sendDatagram(registrationReference, requestDatagram2);

      SelectionKey writeSelectionKey = registrationReference.writeSelectionKey;

      ChannelContext channelContext = (ChannelContext) writeSelectionKey.attachment();

      Queue<Datagram> sendingQueue = channelContext.getSendingQueue();

      Assert.assertEquals(2, sendingQueue.size());

      Datagram[] datagrams = sendingQueue.toArray(new Datagram[2]);

      Assert.assertSame(requestDatagram1, datagrams[0]);
      Assert.assertSame(requestDatagram2, datagrams[1]);
    }

    Datagram receiveDatagram1 = IntrabandTestUtil.readDatagramFully(scatteringByteChannel);

    Assert.assertEquals(_type, receiveDatagram1.getType());

    dataByteBuffer = receiveDatagram1.getDataByteBuffer();

    Assert.assertArrayEquals(_data, dataByteBuffer.array());

    Datagram receiveDatagram2 = IntrabandTestUtil.readDatagramFully(scatteringByteChannel);

    Assert.assertEquals(_type, receiveDatagram2.getType());

    dataByteBuffer = receiveDatagram2.getDataByteBuffer();

    Assert.assertArrayEquals(_data, dataByteBuffer.array());

    // Two datagrams delay sending

    requestDatagram1 = Datagram.createRequestDatagram(_type, _data);
    requestDatagram2 = Datagram.createRequestDatagram(_type, _data);

    wakeUpThread = new Thread(new WakeUpRunnable(_selectorIntraband));

    wakeUpThread.start();

    SelectionKey writeSelectionKey = registrationReference.writeSelectionKey;

    ChannelContext channelContext = (ChannelContext) writeSelectionKey.attachment();

    Queue<Datagram> sendingQueue = channelContext.getSendingQueue();

    synchronized (writeSelectionKey) {
      synchronized (selector) {
        wakeUpThread.interrupt();
        wakeUpThread.join();

        _selectorIntraband.sendDatagram(registrationReference, requestDatagram1);

        Assert.assertEquals(1, sendingQueue.size());
        Assert.assertSame(requestDatagram1, sendingQueue.peek());
      }

      receiveDatagram1 = IntrabandTestUtil.readDatagramFully(scatteringByteChannel);

      Assert.assertEquals(_type, receiveDatagram1.getType());

      dataByteBuffer = receiveDatagram1.getDataByteBuffer();

      Assert.assertArrayEquals(_data, dataByteBuffer.array());

      Thread pollingThread = _selectorIntraband.pollingThread;

      while (pollingThread.getState() == Thread.State.RUNNABLE) ;

      _selectorIntraband.sendDatagram(registrationReference, requestDatagram2);

      Assert.assertEquals(1, sendingQueue.size());
      Assert.assertSame(requestDatagram2, sendingQueue.peek());
    }

    receiveDatagram2 = IntrabandTestUtil.readDatagramFully(scatteringByteChannel);

    Assert.assertEquals(_type, receiveDatagram2.getType());

    dataByteBuffer = receiveDatagram2.getDataByteBuffer();

    Assert.assertArrayEquals(_data, dataByteBuffer.array());

    // Huge datagram sending

    int hugeBufferSize = 1024 * 1024 * 10;

    ByteBuffer hugeBuffer = ByteBuffer.allocate(hugeBufferSize);

    for (int i = 0; i < hugeBufferSize; i++) {
      hugeBuffer.put(i, (byte) i);
    }

    _selectorIntraband.sendDatagram(
        registrationReference, Datagram.createRequestDatagram(_type, hugeBuffer));

    receiveDatagram = DatagramHelper.createReceiveDatagram();

    channelContext = (ChannelContext) writeSelectionKey.attachment();

    int count = 0;

    while (!DatagramHelper.readFrom(receiveDatagram, scatteringByteChannel)) {

      count++;
    }

    Assert.assertTrue(count > 0);

    sendingQueue = channelContext.getSendingQueue();

    Assert.assertTrue(sendingQueue.isEmpty());

    dataByteBuffer = receiveDatagram.getDataByteBuffer();

    Assert.assertArrayEquals(hugeBuffer.array(), dataByteBuffer.array());

    unregisterChannels(registrationReference);

    gatheringByteChannel.close();
    scatteringByteChannel.close();
  }
  @AdviseWith(adviceClasses = {Jdk14LogImplAdvice.class})
  @Test
  public void testSendDatagramWithCallback() throws Exception {

    // Submitted callback

    Pipe readPipe = Pipe.open();
    Pipe writePipe = Pipe.open();

    GatheringByteChannel gatheringByteChannel = writePipe.sink();
    ScatteringByteChannel scatteringByteChannel = readPipe.source();

    RegistrationReference registrationReference =
        _selectorIntraband.registerChannel(writePipe.source(), readPipe.sink());

    Object attachment = new Object();

    RecordCompletionHandler<Object> recordCompletionHandler = new RecordCompletionHandler<Object>();

    _selectorIntraband.sendDatagram(
        registrationReference,
        Datagram.createRequestDatagram(_type, _data),
        attachment,
        EnumSet.of(CompletionType.SUBMITTED),
        recordCompletionHandler);

    Datagram receiveDatagram = IntrabandTestUtil.readDatagramFully(scatteringByteChannel);

    recordCompletionHandler.waitUntilSubmitted();

    Assert.assertSame(attachment, recordCompletionHandler.getAttachment());
    Assert.assertEquals(_type, receiveDatagram.getType());

    ByteBuffer dataByteBuffer = receiveDatagram.getDataByteBuffer();

    Assert.assertArrayEquals(_data, dataByteBuffer.array());

    CaptureHandler captureHandler = null;

    try {

      // Callback timeout, with log

      captureHandler =
          JDKLoggerTestUtil.configureJDKLogger(BaseIntraband.class.getName(), Level.WARNING);

      List<LogRecord> logRecords = captureHandler.getLogRecords();

      recordCompletionHandler = new RecordCompletionHandler<Object>();

      _selectorIntraband.sendDatagram(
          registrationReference,
          Datagram.createRequestDatagram(_type, _data),
          attachment,
          EnumSet.of(CompletionType.DELIVERED),
          recordCompletionHandler,
          10,
          TimeUnit.MILLISECONDS);

      Selector selector = _selectorIntraband.selector;

      recordCompletionHandler.waitUntilTimeouted(selector);

      Assert.assertSame(attachment, recordCompletionHandler.getAttachment());
      Assert.assertEquals(1, logRecords.size());

      IntrabandTestUtil.assertMessageStartWith(
          logRecords.get(0), "Removed timeout response waiting datagram");

      // Callback timeout, without log

      logRecords = captureHandler.resetLogLevel(Level.OFF);

      recordCompletionHandler = new RecordCompletionHandler<Object>();

      _selectorIntraband.sendDatagram(
          registrationReference,
          Datagram.createRequestDatagram(_type, _data),
          attachment,
          EnumSet.of(CompletionType.DELIVERED),
          recordCompletionHandler,
          10,
          TimeUnit.MILLISECONDS);

      recordCompletionHandler.waitUntilTimeouted(selector);

      Assert.assertSame(attachment, recordCompletionHandler.getAttachment());
      Assert.assertTrue(logRecords.isEmpty());
    } finally {
      if (captureHandler != null) {
        captureHandler.close();
      }
    }

    // Callback timeout, completion handler causes NPE

    captureHandler =
        JDKLoggerTestUtil.configureJDKLogger(SelectorIntraband.class.getName(), Level.SEVERE);

    try {
      List<LogRecord> logRecords = captureHandler.getLogRecords();

      recordCompletionHandler =
          new RecordCompletionHandler<Object>() {

            @Override
            public void timedOut(Object attachment) {
              super.timedOut(attachment);

              throw new NullPointerException();
            }
          };

      Jdk14LogImplAdvice.reset();

      Selector selector = _selectorIntraband.selector;

      try {
        _selectorIntraband.sendDatagram(
            registrationReference,
            Datagram.createRequestDatagram(_type, _data),
            attachment,
            EnumSet.of(CompletionType.DELIVERED),
            recordCompletionHandler,
            10,
            TimeUnit.MILLISECONDS);
      } finally {
        recordCompletionHandler.waitUntilTimeouted(selector);

        Jdk14LogImplAdvice.waitUntilErrorCalled();
      }

      Assert.assertFalse(selector.isOpen());
      Assert.assertEquals(1, logRecords.size());

      IntrabandTestUtil.assertMessageStartWith(
          logRecords.get(0), SelectorIntraband.class + ".threadFactory-1 exiting exceptionally");

      gatheringByteChannel.close();
      scatteringByteChannel.close();
    } finally {
      captureHandler.close();
    }
  }
Ejemplo n.º 24
0
 protected Pipe.SinkChannel output() {
   return mOutput.sink();
 }
  @AdviseWith(adviceClasses = {Jdk14LogImplAdvice.class})
  @Test
  public void testReceiveDatagram() throws Exception {
    Pipe readPipe = Pipe.open();
    Pipe writePipe = Pipe.open();

    GatheringByteChannel gatheringByteChannel = writePipe.sink();
    ScatteringByteChannel scatteringByteChannel = readPipe.source();

    SelectionKeyRegistrationReference registrationReference =
        (SelectionKeyRegistrationReference)
            _selectorIntraband.registerChannel(writePipe.source(), readPipe.sink());

    long sequenceId = 100;

    CaptureHandler captureHandler = null;

    try {

      // Receive ACK response, no ACK request, with log

      captureHandler =
          JDKLoggerTestUtil.configureJDKLogger(BaseIntraband.class.getName(), Level.WARNING);

      List<LogRecord> logRecords = captureHandler.getLogRecords();

      Jdk14LogImplAdvice.reset();

      try {
        DatagramHelper.writeTo(
            DatagramHelper.createACKResponseDatagram(sequenceId), gatheringByteChannel);
      } finally {
        Jdk14LogImplAdvice.waitUntilWarnCalled();
      }

      Assert.assertEquals(1, logRecords.size());

      IntrabandTestUtil.assertMessageStartWith(
          logRecords.get(0), "Dropped ownerless ACK response ");

      // Receive ACK response, no ACK request, without log

      logRecords = captureHandler.resetLogLevel(Level.OFF);

      Jdk14LogImplAdvice.reset();

      try {
        DatagramHelper.writeTo(
            DatagramHelper.createACKResponseDatagram(sequenceId), gatheringByteChannel);
      } finally {
        Jdk14LogImplAdvice.waitUntilIsWarnEnableCalled();
      }

      Assert.assertTrue(logRecords.isEmpty());

      // Receive ACK response, with ACK request

      Datagram requestDatagram = Datagram.createRequestDatagram(_type, _data);

      DatagramHelper.setAttachment(requestDatagram, new Object());

      RecordCompletionHandler<Object> recordCompletionHandler =
          new RecordCompletionHandler<Object>();

      DatagramHelper.setCompletionHandler(requestDatagram, recordCompletionHandler);

      DatagramHelper.setSequenceId(requestDatagram, sequenceId);
      DatagramHelper.setTimeout(requestDatagram, 10000);

      BaseIntrabandHelper.addResponseWaitingDatagram(_selectorIntraband, requestDatagram);

      DatagramHelper.writeTo(
          DatagramHelper.createACKResponseDatagram(sequenceId), gatheringByteChannel);

      recordCompletionHandler.waitUntilDelivered();

      Assert.assertSame(
          DatagramHelper.getAttachment(requestDatagram), recordCompletionHandler.getAttachment());

      // Receive response, no request, with log

      logRecords = captureHandler.resetLogLevel(Level.WARNING);

      Jdk14LogImplAdvice.reset();

      try {
        DatagramHelper.writeTo(
            Datagram.createResponseDatagram(requestDatagram, _data), gatheringByteChannel);
      } finally {
        Jdk14LogImplAdvice.waitUntilWarnCalled();
      }

      Assert.assertEquals(1, logRecords.size());

      IntrabandTestUtil.assertMessageStartWith(logRecords.get(0), "Dropped ownerless response ");

      // Receive response, no request, without log

      logRecords = captureHandler.resetLogLevel(Level.OFF);

      Jdk14LogImplAdvice.reset();

      try {
        requestDatagram = Datagram.createRequestDatagram(_type, _data);

        DatagramHelper.setSequenceId(requestDatagram, sequenceId);

        DatagramHelper.writeTo(
            Datagram.createResponseDatagram(requestDatagram, _data), gatheringByteChannel);
      } finally {
        Jdk14LogImplAdvice.waitUntilIsWarnEnableCalled();
      }

      Assert.assertTrue(logRecords.isEmpty());

      // Receive response, with request, with replied completion handler

      requestDatagram = Datagram.createRequestDatagram(_type, _data);

      DatagramHelper.setAttachment(requestDatagram, new Object());

      recordCompletionHandler = new RecordCompletionHandler<Object>();

      DatagramHelper.setCompletionHandler(requestDatagram, recordCompletionHandler);

      DatagramHelper.setCompletionTypes(requestDatagram, EnumSet.of(CompletionType.REPLIED));
      DatagramHelper.setSequenceId(requestDatagram, sequenceId);
      DatagramHelper.setTimeout(requestDatagram, 10000);

      BaseIntrabandHelper.addResponseWaitingDatagram(_selectorIntraband, requestDatagram);

      DatagramHelper.writeTo(
          Datagram.createResponseDatagram(requestDatagram, _data), gatheringByteChannel);

      recordCompletionHandler.waitUntilReplied();

      Assert.assertSame(
          DatagramHelper.getAttachment(requestDatagram), recordCompletionHandler.getAttachment());

      // Receive response, with request, without replied completion
      // handler, with log

      logRecords = captureHandler.resetLogLevel(Level.WARNING);

      requestDatagram = Datagram.createRequestDatagram(_type, _data);

      DatagramHelper.setCompletionTypes(requestDatagram, EnumSet.noneOf(CompletionType.class));

      recordCompletionHandler = new RecordCompletionHandler<Object>();

      DatagramHelper.setCompletionHandler(requestDatagram, recordCompletionHandler);

      DatagramHelper.setSequenceId(requestDatagram, sequenceId);
      DatagramHelper.setTimeout(requestDatagram, 10000);

      BaseIntrabandHelper.addResponseWaitingDatagram(_selectorIntraband, requestDatagram);

      Jdk14LogImplAdvice.reset();

      try {
        DatagramHelper.writeTo(
            Datagram.createResponseDatagram(requestDatagram, _data), gatheringByteChannel);
      } finally {
        Jdk14LogImplAdvice.waitUntilWarnCalled();
      }

      Assert.assertEquals(1, logRecords.size());

      IntrabandTestUtil.assertMessageStartWith(logRecords.get(0), "Dropped unconcerned response ");

      // Receive response, with request, without replied completion
      // handler, without log

      logRecords = captureHandler.resetLogLevel(Level.OFF);

      requestDatagram = Datagram.createRequestDatagram(_type, _data);

      DatagramHelper.setCompletionTypes(requestDatagram, EnumSet.noneOf(CompletionType.class));

      recordCompletionHandler = new RecordCompletionHandler<Object>();

      DatagramHelper.setCompletionHandler(requestDatagram, recordCompletionHandler);

      DatagramHelper.setSequenceId(requestDatagram, sequenceId);
      DatagramHelper.setTimeout(requestDatagram, 10000);

      BaseIntrabandHelper.addResponseWaitingDatagram(_selectorIntraband, requestDatagram);

      Jdk14LogImplAdvice.reset();

      try {
        DatagramHelper.writeTo(
            Datagram.createResponseDatagram(requestDatagram, _data), gatheringByteChannel);
      } finally {
        Jdk14LogImplAdvice.waitUntilIsWarnEnableCalled();
      }

      Assert.assertTrue(logRecords.isEmpty());

      // Receive request, requires ACK, no datagram receive handler,
      // with log

      logRecords = captureHandler.resetLogLevel(Level.WARNING);

      requestDatagram = Datagram.createRequestDatagram(_type, _data);

      DatagramHelper.setAckRequest(requestDatagram);
      DatagramHelper.setSequenceId(requestDatagram, sequenceId);

      Jdk14LogImplAdvice.reset();

      try {
        DatagramHelper.writeTo(requestDatagram, gatheringByteChannel);
      } finally {
        Jdk14LogImplAdvice.waitUntilWarnCalled();
      }

      Datagram ackResponseDatagram = IntrabandTestUtil.readDatagramFully(scatteringByteChannel);

      Assert.assertEquals(sequenceId, DatagramHelper.getSequenceId(ackResponseDatagram));
      Assert.assertTrue(DatagramHelper.isAckResponse(ackResponseDatagram));

      ByteBuffer dataByteBuffer = ackResponseDatagram.getDataByteBuffer();

      Assert.assertEquals(0, dataByteBuffer.capacity());

      Assert.assertEquals(1, logRecords.size());

      IntrabandTestUtil.assertMessageStartWith(logRecords.get(0), "Dropped ownerless request ");

      // Receive request, no datagram receive handler, without log

      logRecords = captureHandler.resetLogLevel(Level.OFF);

      requestDatagram = Datagram.createRequestDatagram(_type, _data);

      DatagramHelper.setSequenceId(requestDatagram, sequenceId);

      Jdk14LogImplAdvice.reset();

      try {
        DatagramHelper.writeTo(requestDatagram, gatheringByteChannel);
      } finally {
        Jdk14LogImplAdvice.waitUntilIsWarnEnableCalled();
      }

      Assert.assertTrue(logRecords.isEmpty());

      // Receive request, with datagram receive handler,

      logRecords = captureHandler.resetLogLevel(Level.SEVERE);

      requestDatagram = Datagram.createRequestDatagram(_type, _data);

      DatagramHelper.setSequenceId(requestDatagram, sequenceId);

      RecordDatagramReceiveHandler recordDatagramReceiveHandler =
          new RecordDatagramReceiveHandler();

      _selectorIntraband.registerDatagramReceiveHandler(_type, recordDatagramReceiveHandler);

      Jdk14LogImplAdvice.reset();

      try {
        DatagramHelper.writeTo(requestDatagram, gatheringByteChannel);
      } finally {
        Jdk14LogImplAdvice.waitUntilErrorCalled();
      }

      Datagram receiveDatagram = recordDatagramReceiveHandler.getReceiveDatagram();

      Assert.assertEquals(sequenceId, DatagramHelper.getSequenceId(receiveDatagram));
      Assert.assertEquals(_type, receiveDatagram.getType());

      dataByteBuffer = receiveDatagram.getDataByteBuffer();

      Assert.assertArrayEquals(_data, dataByteBuffer.array());
      Assert.assertEquals(1, logRecords.size());

      IntrabandTestUtil.assertMessageStartWith(logRecords.get(0), "Unable to dispatch");

      unregisterChannels(registrationReference);

      gatheringByteChannel.close();
      scatteringByteChannel.close();
    } finally {
      if (captureHandler != null) {
        captureHandler.close();
      }
    }
  }
  @Test
  public void testRegisterChannelReadWrite() throws Exception {

    // Scattering byte channel is null

    try {
      _selectorIntraband.registerChannel(null, null);

      Assert.fail();
    } catch (NullPointerException npe) {
      Assert.assertEquals("Scattering byte channel is null", npe.getMessage());
    }

    // Gathering byte channel is null

    try {
      _selectorIntraband.registerChannel(
          IntrabandTestUtil.<ScatteringByteChannel>createProxy(ScatteringByteChannel.class), null);

      Assert.fail();
    } catch (NullPointerException npe) {
      Assert.assertEquals("Gathering byte channel is null", npe.getMessage());
    }

    // Scattering byte channel is not of type SelectableChannel

    try {
      _selectorIntraband.registerChannel(
          IntrabandTestUtil.<ScatteringByteChannel>createProxy(ScatteringByteChannel.class),
          IntrabandTestUtil.<GatheringByteChannel>createProxy(GatheringByteChannel.class));

      Assert.fail();
    } catch (IllegalArgumentException iae) {
      Assert.assertEquals(
          "Scattering byte channel is not of type SelectableChannel", iae.getMessage());
    }

    // Gathering byte channel is not of type SelectableChannel

    try {
      _selectorIntraband.registerChannel(
          new MockDuplexSelectableChannel(false, false),
          IntrabandTestUtil.<GatheringByteChannel>createProxy(GatheringByteChannel.class));

      Assert.fail();
    } catch (IllegalArgumentException iae) {
      Assert.assertEquals(
          "Gathering byte channel is not of type SelectableChannel", iae.getMessage());
    }

    // Scattering byte channel is not valid for reading

    try {
      _selectorIntraband.registerChannel(
          new MockDuplexSelectableChannel(false, true),
          new MockDuplexSelectableChannel(true, true));

      Assert.fail();
    } catch (IllegalArgumentException iae) {
      Assert.assertEquals("Scattering byte channel is not valid for reading", iae.getMessage());
    }

    // Gathering byte channel is not valid for writing

    try {
      _selectorIntraband.registerChannel(
          new MockDuplexSelectableChannel(true, true),
          new MockDuplexSelectableChannel(true, false));

      Assert.fail();
    } catch (IllegalArgumentException iae) {
      Assert.assertEquals("Gathering byte channel is not valid for writing", iae.getMessage());
    }

    // Interruptted on register

    Pipe pipe = Pipe.open();

    SourceChannel sourceChannel = pipe.source();
    SinkChannel sinkChannel = pipe.sink();

    final Thread mainThread = Thread.currentThread();

    Thread wakeUpThread = new Thread(new WakeUpRunnable(_selectorIntraband));

    Thread interruptThread =
        new Thread() {

          @Override
          public void run() {
            while (mainThread.getState() != Thread.State.WAITING) ;

            mainThread.interrupt();
          }
        };

    wakeUpThread.start();

    Selector selector = _selectorIntraband.selector;

    synchronized (selector) {
      wakeUpThread.interrupt();
      wakeUpThread.join();

      interruptThread.start();

      try {
        _selectorIntraband.registerChannel(sourceChannel, sinkChannel);

        Assert.fail();
      } catch (IOException ioe) {
        Throwable cause = ioe.getCause();

        Assert.assertTrue(cause instanceof InterruptedException);
      }

      interruptThread.join();
    }

    _selectorIntraband.close();

    // Normal register

    _selectorIntraband = new SelectorIntraband(_DEFAULT_TIMEOUT);

    SelectionKeyRegistrationReference selectionKeyRegistrationReference =
        (SelectionKeyRegistrationReference)
            _selectorIntraband.registerChannel(sourceChannel, sinkChannel);

    Assert.assertNotNull(selectionKeyRegistrationReference);

    SelectionKey readSelectionKey = selectionKeyRegistrationReference.readSelectionKey;

    Assert.assertTrue(readSelectionKey.isValid());
    Assert.assertEquals(SelectionKey.OP_READ, readSelectionKey.interestOps());
    Assert.assertNotNull(readSelectionKey.attachment());

    SelectionKey writeSelectionKey = selectionKeyRegistrationReference.writeSelectionKey;

    Assert.assertTrue(writeSelectionKey.isValid());
    Assert.assertEquals(0, writeSelectionKey.interestOps());
    Assert.assertNotNull(writeSelectionKey.attachment());
    Assert.assertSame(readSelectionKey.attachment(), writeSelectionKey.attachment());

    writeSelectionKey.interestOps(SelectionKey.OP_WRITE);

    selector = _selectorIntraband.selector;

    selector.wakeup();

    while (writeSelectionKey.interestOps() != 0) ;

    unregisterChannels(selectionKeyRegistrationReference);

    // Register after close

    _selectorIntraband.close();

    try {
      _selectorIntraband.registerChannel(sourceChannel, sinkChannel);

      Assert.fail();
    } catch (ClosedIntrabandException cibe) {
    }

    sourceChannel.close();
    sinkChannel.close();
  }