NioSslEngine implements NioFilter { @Override public synchronized ByteBuffer wrap(ByteBuffer appData) throws IOException { checkClosed(); myNetData.clear(); while (appData.hasRemaining()) { int remaining = myNetData.capacity() - myNetData.position(); if (remaining < (appData.remaining() * 2)) { int newCapacity = expandedCapacity(appData, myNetData); myNetData = expandWriteBuffer(TRACKED_SENDER, myNetData, newCapacity); } SSLEngineResult wrapResult = engine.wrap(appData, myNetData); if (wrapResult.getHandshakeStatus() == NEED_TASK) { handleBlockingTasks(); } if (wrapResult.getStatus() != OK) { throw new SSLException("Error encrypting data: " + wrapResult); } } myNetData.flip(); return myNetData; } NioSslEngine(SSLEngine engine, BufferPool bufferPool); boolean handshake(SocketChannel socketChannel, int timeout,
      ByteBuffer peerNetData); @Override synchronized ByteBuffer wrap(ByteBuffer appData); @Override synchronized ByteBuffer unwrap(ByteBuffer wrappedBuffer); @Override ByteBuffer ensureWrappedCapacity(int amount, ByteBuffer wrappedBuffer,
      BufferType bufferType); @Override ByteBuffer readAtLeast(SocketChannel channel, int bytes,
      ByteBuffer wrappedBuffer); @Override ByteBuffer getUnwrappedBuffer(ByteBuffer wrappedBuffer); ByteBuffer ensureUnwrappedCapacity(int amount); @Override void doneReadingDirectAck(ByteBuffer unwrappedBuffer); @Override synchronized void close(SocketChannel socketChannel);  }
@Test public void wrap() throws Exception { ByteBuffer appData = ByteBuffer.allocate(nioSslEngine.myNetData.capacity() + 100); byte[] appBytes = new byte[appData.capacity()]; Arrays.fill(appBytes, (byte) 0x1F); appData.put(appBytes); appData.flip(); TestSSLEngine testEngine = new TestSSLEngine(); testEngine.addReturnResult( new SSLEngineResult(OK, NEED_TASK, appData.remaining(), appData.remaining())); spyNioSslEngine.engine = testEngine; ByteBuffer wrappedBuffer = spyNioSslEngine.wrap(appData); verify(spyNioSslEngine, times(1)).expandWriteBuffer(any(BufferPool.BufferType.class), any(ByteBuffer.class), any(Integer.class)); appData.flip(); assertThat(wrappedBuffer).isEqualTo(appData); verify(spyNioSslEngine, times(1)).handleBlockingTasks(); }
@Test public void wrapFails() { ByteBuffer appData = ByteBuffer.allocate(nioSslEngine.myNetData.capacity() + 100); byte[] appBytes = new byte[appData.capacity()]; Arrays.fill(appBytes, (byte) 0x1F); appData.put(appBytes); appData.flip(); TestSSLEngine testEngine = new TestSSLEngine(); testEngine.addReturnResult( new SSLEngineResult(CLOSED, NEED_TASK, appData.remaining(), appData.remaining())); spyNioSslEngine.engine = testEngine; assertThatThrownBy(() -> spyNioSslEngine.wrap(appData)).isInstanceOf(SSLException.class) .hasMessageContaining("Error encrypting data"); }