java.nio.channels.ClosedChannelException Java Examples

The following examples show how to use java.nio.channels.ClosedChannelException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ChannelsTest.java    From j2objc with Apache License 2.0 7 votes vote down vote up
public void testNewInputStreamReadableByteChannel() throws Exception {
    ByteBuffer readbcbuf = ByteBuffer.allocateDirect(this.testNum);
    byte[] readbuf = new byte[this.testNum];
    this.fins = new FileInputStream(tmpFile);
    ReadableByteChannel readbc = this.fins.getChannel();
    assertEquals(this.fileSize, this.fins.available());
    assertTrue(readbc.isOpen());
    InputStream testins = Channels.newInputStream(readbc);
    // read in testins and fins use the same pointer
    testins.read(readbuf);
    assertEquals(this.fins.available(), this.fileSize - this.testNum);
    int readNum = readbc.read(readbcbuf);
    assertEquals(readNum, this.testNum);
    assertEquals(this.fins.available(), this.fileSize - this.testNum * 2);
    testins.read(readbuf);
    assertEquals(this.fins.available(), this.fileSize - this.testNum * 3);
    // readbc.close() affect testins
    readbc.close();
    assertFalse(readbc.isOpen());
    try {
        testins.read(readbuf);
        fail();
    } catch (ClosedChannelException e) {
        // correct
    }
}
 
Example #2
Source File: ByteBufferReadableStreamChannel.java    From ambry with Apache License 2.0 6 votes vote down vote up
@Override
public Future<Long> readInto(AsyncWritableChannel asyncWritableChannel, Callback<Long> callback) {
  Future<Long> future;
  if (!channelOpen.get()) {
    ClosedChannelException closedChannelException = new ClosedChannelException();
    FutureResult<Long> futureResult = new FutureResult<Long>();
    futureResult.done(0L, closedChannelException);
    future = futureResult;
    if (callback != null) {
      callback.onCompletion(0L, closedChannelException);
    }
  } else if (!channelEmptied.compareAndSet(false, true)) {
    throw new IllegalStateException("ReadableStreamChannel cannot be read more than once");
  } else {
    future = asyncWritableChannel.write(buffer, callback);
  }
  return future;
}
 
Example #3
Source File: SctpChannelImpl.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public <T> SctpChannel setOption(SctpSocketOption<T> name, T value)
        throws IOException {
    if (name == null)
        throw new NullPointerException();
    if (!supportedOptions().contains(name))
        throw new UnsupportedOperationException("'" + name + "' not supported");

    synchronized (stateLock) {
        if (!isOpen())
            throw new ClosedChannelException();

        SctpNet.setSocketOption(fdVal, name, value, 0 /*oneToOne*/);
    }
    return this;
}
 
Example #4
Source File: DisconnectableClientTransport.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<DuplexConnection> connect() {
  return Mono.defer(
      () ->
          now() < nextConnectPermitMillis
              ? Mono.error(new ClosedChannelException())
              : clientTransport
                  .connect()
                  .map(
                      c -> {
                        if (curConnection.compareAndSet(null, c)) {
                          return c;
                        } else {
                          throw new IllegalStateException(
                              "Transport supports at most 1 connection");
                        }
                      }));
}
 
Example #5
Source File: AbstractSelectableChannel.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Adjusts this channel's blocking mode.
 *
 * <p> If the given blocking mode is different from the current blocking
 * mode then this method invokes the {@link #implConfigureBlocking
 * implConfigureBlocking} method, while holding the appropriate locks, in
 * order to change the mode.  </p>
 */
public final SelectableChannel configureBlocking(boolean block)
    throws IOException
{
    synchronized (regLock) {
        if (!isOpen())
            throw new ClosedChannelException();
        boolean blocking = !nonBlocking;
        if (block != blocking) {
            if (block && haveValidKeys())
                throw new IllegalBlockingModeException();
            implConfigureBlocking(block);
            nonBlocking = !block;
        }
    }
    return this;
}
 
Example #6
Source File: DataTransportPoller.java    From aeron with Apache License 2.0 6 votes vote down vote up
public SelectionKey registerForRead(
    final ReceiveChannelEndpoint channelEndpoint, final UdpChannelTransport transport, final int transportIndex)
{
    SelectionKey key = null;
    try
    {
        final ChannelAndTransport channelAndTransport = new ChannelAndTransport(
            channelEndpoint, transport, transportIndex);

        key = transport.receiveDatagramChannel().register(selector, SelectionKey.OP_READ, channelAndTransport);
        channelAndTransports = ArrayUtil.add(channelAndTransports, channelAndTransport);
    }
    catch (final ClosedChannelException ex)
    {
        LangUtil.rethrowUnchecked(ex);
    }

    return key;
}
 
Example #7
Source File: GfxdThriftServerSelector.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
protected void addNewClient(ClientProcessData clientData) {
  SelectionKey clientKey;
  try {
    // if client is already in execution then register OP_WRITE interest
    // too, else only OP_READ
    /*if (clientData.idle) {
      clientKey = clientData.clientSocket.registerSelector(this.selector,
          SelectionKey.OP_READ);
    }
    else*/ {
      clientKey = clientData.clientSocket.registerSelector(this.selector,
          SelectionKey.OP_READ | SelectionKey.OP_WRITE);
    }

    clientData.key = clientKey;
    clientKey.attach(clientData);
  } catch (ClosedChannelException cce) {
    cleanupSelectionKey(clientData);
  } catch (IOException ioe) {
    LOGGER.warn("Failed to register accepted connection to selector!",
        ioe);
    cleanupSelectionKey(clientData);
  }
}
 
Example #8
Source File: HeapChannelBuffer.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException {
    ByteBuffer buf = ByteBuffer.wrap(array, index, length);
    int readBytes = 0;

    do {
        int localReadBytes;
        try {
            localReadBytes = in.read(buf);
        } catch (ClosedChannelException e) {
            localReadBytes = -1;
        }
        if (localReadBytes < 0) {
            if (readBytes == 0) {
                return -1;
            } else {
                break;
            }
        } else if (localReadBytes == 0) {
            break;
        }
        readBytes += localReadBytes;
    } while (readBytes < length);

    return readBytes;
}
 
Example #9
Source File: SctpMultiChannelImpl.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public <T> SctpMultiChannel setOption(SctpSocketOption<T> name,
                                      T value,
                                      Association association)
        throws IOException {
    if (name == null)
        throw new NullPointerException();
    if (!(supportedOptions().contains(name)))
        throw new UnsupportedOperationException("'" + name + "' not supported");

    synchronized (stateLock) {
        if (association != null && (name.equals(SCTP_PRIMARY_ADDR) ||
                name.equals(SCTP_SET_PEER_PRIMARY_ADDR))) {
            checkAssociation(association);
        }
        if (!isOpen())
            throw new ClosedChannelException();

        int assocId = association == null ? 0 : association.associationID();
        SctpNet.setSocketOption(fdVal, name, value, assocId);
    }
    return this;
}
 
Example #10
Source File: Client.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a future holding the serialized request result.
 *
 * <p>If the channel has been established, forward the call to the
 * established channel, otherwise queue it for when the channel is
 * handed in.
 *
 * @param request the request to be sent.
 * @return Future holding the serialized result
 */
CompletableFuture<RESP> sendRequest(REQ request) {
	synchronized (connectLock) {
		if (failureCause != null) {
			return FutureUtils.getFailedFuture(failureCause);
		} else if (connectionShutdownFuture.get() != null) {
			return FutureUtils.getFailedFuture(new ClosedChannelException());
		} else {
			if (established != null) {
				return established.sendRequest(request);
			} else {
				// Queue this and handle when connected
				final PendingRequest pending = new PendingRequest(request);
				queuedRequests.add(pending);
				return pending;
			}
		}
	}
}
 
Example #11
Source File: OutboundMessageHandlerTest.java    From nanofix with Apache License 2.0 6 votes vote down vote up
@Test(expected = TransportClosedException.class)
public void shouldNotifyTransportObserverIfAnClosedChannelExceptionIsThrownWhileWritingACollection() throws Exception
{
    mockery.checking(new Expectations()
    {
        {
            //when
            one(writableByteChannel).write(with(any(ByteBuffer.class)));
            will(throwException(new ClosedChannelException()));

            //then
            one(connectionObserver).connectionClosed();
        }
    });

    handler.send(Arrays.asList(new FixMessageBuilder().build()));

}
 
Example #12
Source File: HttpObjectAggregatorTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testOversizedRequest() {
    EmbeddedChannel embedder = new EmbeddedChannel(new HttpObjectAggregator(4));
    HttpRequest message = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, "http://localhost");
    HttpContent chunk1 = new DefaultHttpContent(Unpooled.copiedBuffer("test", CharsetUtil.US_ASCII));
    HttpContent chunk2 = new DefaultHttpContent(Unpooled.copiedBuffer("test2", CharsetUtil.US_ASCII));
    HttpContent chunk3 = LastHttpContent.EMPTY_LAST_CONTENT;

    assertFalse(embedder.writeInbound(message));
    assertFalse(embedder.writeInbound(chunk1));
    assertFalse(embedder.writeInbound(chunk2));

    FullHttpResponse response = embedder.readOutbound();
    assertEquals(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, response.status());
    assertEquals("0", response.headers().get(HttpHeaderNames.CONTENT_LENGTH));
    assertFalse(embedder.isOpen());

    try {
        assertFalse(embedder.writeInbound(chunk3));
        fail();
    } catch (Exception e) {
        assertTrue(e instanceof ClosedChannelException);
    }

    assertFalse(embedder.finish());
}
 
Example #13
Source File: HeapChannelBuffer.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException {
    ByteBuffer buf = ByteBuffer.wrap(array, index, length);
    int readBytes = 0;

    do {
        int localReadBytes;
        try {
            localReadBytes = in.read(buf);
        } catch (ClosedChannelException e) {
            localReadBytes = -1;
        }
        if (localReadBytes < 0) {
            if (readBytes == 0) {
                return -1;
            } else {
                break;
            }
        } else if (localReadBytes == 0) {
            break;
        }
        readBytes += localReadBytes;
    } while (readBytes < length);

    return readBytes;
}
 
Example #14
Source File: SctpMultiChannelImpl.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> T getOption(SctpSocketOption<T> name, Association association)
        throws IOException {
    if (name == null)
        throw new NullPointerException();
    if (!supportedOptions().contains(name))
        throw new UnsupportedOperationException("'" + name + "' not supported");

    synchronized (stateLock) {
        if (association != null && (name.equals(SCTP_PRIMARY_ADDR) ||
                name.equals(SCTP_SET_PEER_PRIMARY_ADDR))) {
            checkAssociation(association);
        }
        if (!isOpen())
            throw new ClosedChannelException();

        int assocId = association == null ? 0 : association.associationID();
        return (T)SctpNet.getSocketOption(fdVal, name, assocId);
    }
}
 
Example #15
Source File: BlockingChannel.java    From ambry with Apache License 2.0 6 votes vote down vote up
@Override
public ChannelOutput receive() throws IOException {
  if (!connected) {
    throw new ClosedChannelException();
  }

  // consume the size header and return the remaining response.
  ByteBuffer streamSizeBuffer = ByteBuffer.allocate(8);
  while (streamSizeBuffer.position() < streamSizeBuffer.capacity()) {
    int read = readChannel.read();
    if (read == -1) {
      throw new IOException("Could not read complete size from readChannel ");
    }
    streamSizeBuffer.put((byte) read);
  }
  streamSizeBuffer.flip();
  return new ChannelOutput(readChannel, streamSizeBuffer.getLong() - 8);
}
 
Example #16
Source File: SctpServerChannelImpl.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Override
public <T> SctpServerChannel setOption(SctpSocketOption<T> name, T value)
        throws IOException {
    if (name == null)
        throw new NullPointerException();
    if (!supportedOptions().contains(name))
        throw new UnsupportedOperationException("'" + name + "' not supported");

    synchronized (stateLock) {
        if (!isOpen())
            throw new ClosedChannelException();

        SctpNet.setSocketOption(fdVal, name, value, 0 /*oneToOne*/);
        return this;
    }
}
 
Example #17
Source File: PrematureClosureBeforeResponsePayloadBodyTest.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
@Test
public void chunkedWithoutFinalCRLF() throws Exception {
    encodedResponse.set("HTTP/1.1 200 OK\r\n" +
            "Content-Type: text/plain\r\n" +
            "Transfer-Encoding: chunked\r\n" +
            "Connection: close\r\n" + "\r\n" +
            "5\r\n" +
            "hello\r\n" +
            "0\r\n");   // no final CRLF

    HttpRequest request = client.get("/");
    ReservedBlockingHttpConnection connection = client.reserveConnection(request);
    // Wait until a server closes the connection:
    connection.connectionContext().onClose().whenFinally(connectionClosedLatch::countDown).subscribe();

    assertThrows(ClosedChannelException.class, () -> connection.request(request));
    connectionClosedLatch.await();
}
 
Example #18
Source File: SctpMultiChannelImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> T getOption(SctpSocketOption<T> name, Association association)
        throws IOException {
    if (name == null)
        throw new NullPointerException();
    if (!supportedOptions().contains(name))
        throw new UnsupportedOperationException("'" + name + "' not supported");

    synchronized (stateLock) {
        if (association != null && (name.equals(SCTP_PRIMARY_ADDR) ||
                name.equals(SCTP_SET_PEER_PRIMARY_ADDR))) {
            checkAssociation(association);
        }
        if (!isOpen())
            throw new ClosedChannelException();

        int assocId = association == null ? 0 : association.associationID();
        return (T)SctpNet.getSocketOption(fdVal, name, assocId);
    }
}
 
Example #19
Source File: SctpMultiChannelImpl.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public SctpChannel branch(Association association)
        throws IOException {
    synchronized (stateLock) {
        checkAssociation(association);
        if (!isOpen())
            throw new ClosedChannelException();

        FileDescriptor bFd = SctpNet.branch(fdVal,
                                            association.associationID());
        /* successfully branched, we can now remove it from assoc list */
        removeAssociation(association);

        return new SctpChannelImpl(provider(), bFd, association);
    }
}
 
Example #20
Source File: SctpMultiChannelImpl.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SctpMultiChannel shutdown(Association association)
        throws IOException {
    synchronized (stateLock) {
        checkAssociation(association);
        if (!isOpen())
            throw new ClosedChannelException();

        SctpNet.shutdown(fdVal, association.associationID());
    }
    return this;
}
 
Example #21
Source File: SctpChannelImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> T getOption(SctpSocketOption<T> name) throws IOException {
    if (name == null)
        throw new NullPointerException();
    if (!supportedOptions().contains(name))
        throw new UnsupportedOperationException("'" + name + "' not supported");

    synchronized (stateLock) {
        if (!isOpen())
            throw new ClosedChannelException();

        return (T)SctpNet.getSocketOption(fdVal, name, 0 /*oneToOne*/);
    }
}
 
Example #22
Source File: SctpMultiChannelImpl.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Set<Association> associations()
        throws ClosedChannelException, NotYetBoundException {
    synchronized (stateLock) {
        if (!isOpen())
            throw new ClosedChannelException();
        if (!isBound())
            throw new NotYetBoundException();

        return Collections.unmodifiableSet(associationMap.keySet());
    }
}
 
Example #23
Source File: AsyncSocketAdapter.java    From Blink with Artistic License 2.0 5 votes vote down vote up
@Override
public boolean receiveAsync(IoEventArgs buffer) {
    if (mDisposed.get())
        return false;
    mReceiveArgs = buffer;
    try {
        return SelectorFactory.getInstance().registerReceive(mChannel, this) != null;
    } catch (ClosedChannelException e) {
        return false;
    }
}
 
Example #24
Source File: PooledDirectByteBuf.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException {
    checkIndex(index, length);
    ByteBuffer tmpBuf = internalNioBuffer();
    index = idx(index);
    tmpBuf.clear().position(index).limit(index + length);
    try {
        return in.read(tmpBuf);
    } catch (ClosedChannelException ignored) {
        return -1;
    }
}
 
Example #25
Source File: Slice.java    From aion with MIT License 5 votes vote down vote up
public int setBytes(int index, FileChannel in, int position, int length) throws IOException {
    Preconditions.checkPositionIndexes(index, index + length, this.length);
    index += offset;
    ByteBuffer buf = ByteBuffer.wrap(data, index, length);
    int readBytes = 0;

    do {
        int localReadBytes;
        try {
            localReadBytes = in.read(buf, position + readBytes);
        } catch (ClosedChannelException e) {
            localReadBytes = -1;
        }
        if (localReadBytes < 0) {
            if (readBytes == 0) {
                return -1;
            } else {
                break;
            }
        } else if (localReadBytes == 0) {
            break;
        }
        readBytes += localReadBytes;
    } while (readBytes < length);

    return readBytes;
}
 
Example #26
Source File: SctpChannelImpl.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> T getOption(SctpSocketOption<T> name) throws IOException {
    if (name == null)
        throw new NullPointerException();
    if (!supportedOptions().contains(name))
        throw new UnsupportedOperationException("'" + name + "' not supported");

    synchronized (stateLock) {
        if (!isOpen())
            throw new ClosedChannelException();

        return (T)SctpNet.getSocketOption(fdVal, name, 0 /*oneToOne*/);
    }
}
 
Example #27
Source File: XmppTcpTransportModule.java    From Smack with Apache License 2.0 5 votes vote down vote up
private void handleReadWriteIoException(IOException e) {
    if (e instanceof ClosedChannelException && !tcpNioTransport.isConnected()) {
        // The connection is already closed.
        return;
    }

   connectionInternal.notifyConnectionError(e);
}
 
Example #28
Source File: AjpClientConnection.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
AjpClientConnection(final AjpClientChannel connection, final OptionMap options, final ByteBufferPool bufferPool, ClientStatistics clientStatistics) {
    this.clientStatistics = clientStatistics;
    this.options = options;
    this.connection = connection;
    this.bufferPool = bufferPool;

    connection.addCloseTask(new ChannelListener<AjpClientChannel>() {
        @Override
        public void handleEvent(AjpClientChannel channel) {
            log.debugf("connection to %s closed", getPeerAddress());
            AjpClientConnection.this.state |= CLOSED;
            ChannelListeners.invokeChannelListener(AjpClientConnection.this, closeSetter.get());
            for(ChannelListener<ClientConnection> listener : closeListeners) {
                listener.handleEvent(AjpClientConnection.this);
            }
            AjpClientExchange pending = pendingQueue.poll();
            while (pending != null) {
                pending.setFailed(new ClosedChannelException());
                pending = pendingQueue.poll();
            }
            if(currentRequest != null) {
                currentRequest.setFailed(new ClosedChannelException());
                currentRequest = null;
            }
        }
    });
    connection.getReceiveSetter().set(new ClientReceiveListener());
    connection.resumeReceives();
}
 
Example #29
Source File: SctpChannelImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private void ensureOpenAndUnconnected() throws IOException {
    synchronized (stateLock) {
        if (!isOpen())
            throw new ClosedChannelException();
        if (isConnected())
            throw new AlreadyConnectedException();
        if (state == ChannelState.PENDING)
            throw new ConnectionPendingException();
    }
}
 
Example #30
Source File: SctpChannelImpl.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private void ensureOpenAndUnconnected() throws IOException {
    synchronized (stateLock) {
        if (!isOpen())
            throw new ClosedChannelException();
        if (isConnected())
            throw new AlreadyConnectedException();
        if (state == ChannelState.PENDING)
            throw new ConnectionPendingException();
    }
}