Java Code Examples for java.nio.channels.ClosedChannelException

The following examples show how to use java.nio.channels.ClosedChannelException. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: nanofix   Source File: OutboundMessageHandlerTest.java    License: 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 2
Source Project: openjdk-8   Source File: SctpChannelImpl.java    License: 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 3
Source Project: Bytecoder   Source File: AbstractSelectableChannel.java    License: 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 4
@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 Project: aeron   Source File: DataTransportPoller.java    License: 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 6
Source Project: gemfirexd-oss   Source File: GfxdThriftServerSelector.java    License: 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 7
Source Project: j2objc   Source File: ChannelsTest.java    License: Apache License 2.0 6 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 8
Source Project: dubbox   Source File: HeapChannelBuffer.java    License: 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 Project: jdk8u60   Source File: SctpMultiChannelImpl.java    License: 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 Project: Flink-CEPplus   Source File: Client.java    License: 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
@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 12
@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 13
Source Project: netty-4.1.22   Source File: HttpObjectAggregatorTest.java    License: 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 14
Source Project: dubbox   Source File: HeapChannelBuffer.java    License: 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 15
@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 16
Source Project: ambry   Source File: BlockingChannel.java    License: 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 17
Source Project: hottub   Source File: SctpServerChannelImpl.java    License: 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 18
@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 19
Source Project: ambry   Source File: ByteBufferReadableStreamChannel.java    License: 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 20
Source Project: Smack   Source File: XmppTcpTransportModule.java    License: 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 21
@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 Project: jdk8u-jdk   Source File: SctpChannelImpl.java    License: 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 23
/**
 * Check the integrity of all the nodes in the tree. Calls
 * {@link #assertNodeIntegrity} for every node in the tree.
 */
public void assertIntegrity() {
    try {
        for (int i = 0; i < getNodeCount(); i++) {
            assertNodeIntegrity(getNode(i));
        }
    } catch (ClosedChannelException e) {
        fail(e.getMessage());
    }
}
 
Example 24
Source Project: j2objc   Source File: SelectorTest.java    License: Apache License 2.0 5 votes vote down vote up
private void assert_select_OP_ACCEPT(SelectType type, int timeout)
        throws IOException, ClosedChannelException {
    SocketChannel sc = SocketChannel.open();
    SocketChannel client = null;
    try {
        ssc.register(selector, SelectionKey.OP_ACCEPT);
        sc.connect(localAddress);
        int count = blockingSelect(type, timeout);
        assertEquals(1, count);
        Set<SelectionKey> selectedKeys = selector.selectedKeys();
        assertEquals(1, selectedKeys.size());
        SelectionKey key = selectedKeys.iterator().next();
        assertEquals(ssc.keyFor(selector), key);
        assertEquals(SelectionKey.OP_ACCEPT, key.readyOps());
        // select again, it should return 0
        count = selectOnce(type, timeout);
        assertEquals(0,count);
        // but selectedKeys remains the same as previous
        assertSame(selectedKeys, selector.selectedKeys());
        client = ssc.accept();
        selectedKeys.clear();
    } finally {
        try {
            sc.close();
        } catch (IOException e) {
            // do nothing
        }
        if (null != client) {
            client.close();
        }
    }
    ssc.keyFor(selector).cancel();
}
 
Example 25
Source Project: cloudstack   Source File: Agent.java    License: Apache License 2.0 5 votes vote down vote up
private void postRequest(final Request request) throws AgentControlChannelException {
    if (_link != null) {
        try {
            _link.send(request.toBytes());
        } catch (final ClosedChannelException e) {
            s_logger.warn("Unable to post agent control reques: " + request.toString());
            throw new AgentControlChannelException("Unable to post agent control request due to " + e.getMessage());
        }
    } else {
        throw new AgentControlChannelException("Unable to post agent control request as link is not available");
    }
}
 
Example 26
Source Project: ambry   Source File: ByteBufferAWC.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Closes the channel and resolves all pending chunks with a {@link ClosedChannelException}. Also queues a poison
 * so that {@link #getNextChunk()} starts returning {@code null}.
 */
@Override
public void close() {
  if (channelOpen.compareAndSet(true, false)) {
    resolveAllRemainingChunks(new ClosedChannelException());
  }
}
 
Example 27
Source Project: lottie-android   Source File: Utils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * From http://vaibhavblogs.org/2012/12/common-java-networking-exceptions/
 */
public static boolean isNetworkException(Throwable e) {
  return e instanceof SocketException || e instanceof ClosedChannelException ||
      e instanceof InterruptedIOException || e instanceof ProtocolException ||
      e instanceof SSLException || e instanceof UnknownHostException ||
      e instanceof UnknownServiceException;
}
 
Example 28
private void handleDeferredRegistrations()
{
    synchronized (deferredRegistrations) {
        int deferredListSize = deferredRegistrations.size();
        for (int i = 0; i < deferredListSize; i++) {
            EventHandler eventHandler =
                (EventHandler)deferredRegistrations.get(i);
            if (orb.transportDebugFlag) {
                dprint(".handleDeferredRegistrations: " + eventHandler);
            }
            SelectableChannel channel = eventHandler.getChannel();
            SelectionKey selectionKey = null;
            try {
                selectionKey =
                    channel.register(selector,
                                     eventHandler.getInterestOps(),
                                     (Object)eventHandler);
            } catch (ClosedChannelException e) {
                if (orb.transportDebugFlag) {
                    dprint(".handleDeferredRegistrations: " + e);
                }
            }
            eventHandler.setSelectionKey(selectionKey);
        }
        deferredRegistrations.clear();
    }
}
 
Example 29
Source Project: offheap-store   Source File: FileBackedStorageEngineTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = IOException.class)
public void testConcurrentClose() throws Throwable {
  FileChannel spyChannel = spy(FileChannel.class);
  MappedPageSource source = new MappedPageSource(dataFile) {
    @Override
    public FileChannel getReadableChannel() {
      return spyChannel;
    }
  };
  FileBackedStorageEngine<byte[], byte[]> engine = new FileBackedStorageEngine<>(source, Long.MAX_VALUE, MemoryUnit.BYTES, PersistentByteArrayPortability.INSTANCE, PersistentByteArrayPortability.INSTANCE);
  when(spyChannel.read(notNull(), anyLong()))
    .thenAnswer(o -> {
      //deterministically simulate another thread closing the engine while
      //this thread is reading.
      engine.close();
      throw new ClosedChannelException();
    });
  try {
    byte[] buffer = new byte[10];
    long p = engine.writeMapping(new byte[0], buffer, 0, 0);
    Assert.assertTrue(p >= 0);
    engine.flush();
    engine.readValue(0);
  } catch (Throwable e) {
    Throwable cause = e;
    while (cause.getCause() != null) {
      cause = cause.getCause();
    }
    throw cause;
  } finally {
    source.close();
  }
}
 
Example 30
Source Project: netty-4.1.22   Source File: EpollSocketChannelConfigTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetOptionWhenClosed() {
    ch.close().syncUninterruptibly();
    try {
        ch.config().getSoLinger();
        fail();
    } catch (ChannelException e) {
        assertTrue(e.getCause() instanceof ClosedChannelException);
    }
}