Java 类java.nio.channels.ClosedChannelException 实例源码

项目:openjdk-jdk10    文件:SctpServerChannelImpl.java   
@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;
    }
}
项目:jdk8u-jdk    文件:SctpMultiChannelImpl.java   
@Override
public Set<SocketAddress> getRemoteAddresses(Association association)
        throws IOException {
    synchronized (stateLock) {
        checkAssociation(association);
        if (!isOpen())
            throw new ClosedChannelException();

        try {
            return SctpNet.getRemoteAddresses(fdVal, association.associationID());
        } catch (SocketException se) {
            /* a valid association should always have remote addresses */
            Set<SocketAddress> addrs = associationMap.get(association);
            return addrs != null ? addrs : Collections.<SocketAddress>emptySet();
        }
    }
}
项目:dubbox-hystrix    文件:HeapChannelBuffer.java   
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;
}
项目:OpenJSharp    文件:FileChannelImpl.java   
public long transferTo(long position, long count,
                       WritableByteChannel target)
    throws IOException
{
    ensureOpen();
    if (!target.isOpen())
        throw new ClosedChannelException();
    if (!readable)
        throw new NonReadableChannelException();
    if (target instanceof FileChannelImpl &&
        !((FileChannelImpl)target).writable)
        throw new NonWritableChannelException();
    if ((position < 0) || (count < 0))
        throw new IllegalArgumentException();
    long sz = size();
    if (position > sz)
        return 0;
    int icount = (int)Math.min(count, Integer.MAX_VALUE);
    if ((sz - position) < icount)
        icount = (int)(sz - position);

    // Slow path for untrusted targets
    return transferToArbitraryChannel(position, icount, target);
}
项目:EatDubbo    文件:HeapChannelBuffer.java   
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;
}
项目:hadoop    文件:ShuffleHandler.java   
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
    throws Exception {
  Channel ch = e.getChannel();
  Throwable cause = e.getCause();
  if (cause instanceof TooLongFrameException) {
    sendError(ctx, BAD_REQUEST);
    return;
  } else if (cause instanceof IOException) {
    if (cause instanceof ClosedChannelException) {
      LOG.debug("Ignoring closed channel error", cause);
      return;
    }
    String message = String.valueOf(cause.getMessage());
    if (IGNORABLE_ERROR_MESSAGE.matcher(message).matches()) {
      LOG.debug("Ignoring client socket close", cause);
      return;
    }
  }

  LOG.error("Shuffle error: ", cause);
  if (ch.isConnected()) {
    LOG.error("Shuffle error " + e);
    sendError(ctx, INTERNAL_SERVER_ERROR);
  }
}
项目:openjdk-jdk10    文件:SctpChannelImpl.java   
@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;
}
项目:jdk8u-jdk    文件:SctpMultiChannelImpl.java   
@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);
    }
}
项目:dubbo2    文件:HeapChannelBuffer.java   
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;
}
项目:openjdk-jdk10    文件:SctpMultiChannelImpl.java   
@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);
    }
}
项目:gnirehtet    文件:Client.java   
public Client(Selector selector, SocketChannel clientChannel, CloseListener<Client> closeListener) throws ClosedChannelException {
    id = nextId++;
    this.clientChannel = clientChannel;
    router = new Router(this, selector);
    pendingIdBuffer = createIntBuffer(id);

    SelectionHandler selectionHandler = (selectionKey) -> {
        if (selectionKey.isValid() && selectionKey.isWritable()) {
            processSend();
        }
        if (selectionKey.isValid() && selectionKey.isReadable()) {
            processReceive();
        }
        if (selectionKey.isValid()) {
            updateInterests();
        }
    };
    // on start, we are interested only in writing (we must first send the client id)
    interests = SelectionKey.OP_WRITE;
    selectionKey = clientChannel.register(selector, interests, selectionHandler);

    this.closeListener = closeListener;
}
项目:dubbocloud    文件:HeapChannelBuffer.java   
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;
}
项目:lams    文件:WriteTimeoutStreamSinkConduit.java   
private void handleWriteTimeout(final long ret) throws IOException {
    if (!connection.isOpen()) {
        return;
    }
    if (ret == 0 && handle != null) {
        return;
    }
    Integer timeout = getTimeout();
    if (timeout == null || timeout <= 0) {
        return;
    }
    long currentTime = System.currentTimeMillis();
    long expireTimeVar = expireTime;
    if (expireTimeVar != -1 && currentTime > expireTimeVar) {
        IoUtils.safeClose(connection);
        throw new ClosedChannelException();
    }
    expireTime = currentTime + timeout;
    XnioExecutor.Key key = handle;
    if (key == null) {
        handle = connection.getIoThread().executeAfter(timeoutCommand, timeout, TimeUnit.MILLISECONDS);
    }
}
项目:CustomWorldGen    文件:NetworkDispatcher.java   
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
{
    // Stop the epic channel closed spam at close
    if (!(cause instanceof ClosedChannelException))
    {
        // Mute the reset by peer exception - it's disconnection noise
        if (cause.getMessage().contains("Connection reset by peer"))
        {
            FMLLog.log(Level.DEBUG, cause, "Muted NetworkDispatcher exception");
        }
        else
        {
            FMLLog.log(Level.ERROR, cause, "NetworkDispatcher exception");
        }
    }
    super.exceptionCaught(ctx, cause);
}
项目:lams    文件:IdleTimeoutConduit.java   
private void handleIdleTimeout() throws ClosedChannelException {
    if(timedOut) {
        return;
    }
    long idleTimeout = this.idleTimeout;
    if(idleTimeout <= 0) {
        return;
    }
    long currentTime = System.currentTimeMillis();
    long expireTimeVar = expireTime;
    if(expireTimeVar != -1 && currentTime > expireTimeVar) {
        timedOut = true;
        doClose();
        throw new ClosedChannelException();
    }
    expireTime = currentTime + idleTimeout;
    XnioExecutor.Key key = handle;
    if (key == null) {
        handle = sink.getWriteThread().executeAfter(timeoutCommand, idleTimeout, TimeUnit.MILLISECONDS);
    }
}
项目:lams    文件:DeflatingStreamSinkConduit.java   
@Override
public long write(final ByteBuffer[] srcs, final int offset, final int length) throws IOException {
    if (anyAreSet(state, SHUTDOWN | CLOSED) || currentBuffer == null) {
        throw new ClosedChannelException();
    }
    try {
        int total = 0;
        for (int i = offset; i < offset + length; ++i) {
            if (srcs[i].hasRemaining()) {
                int ret = write(srcs[i]);
                total += ret;
                if (ret == 0) {
                    return total;
                }
            }
        }
        return total;
    } catch (IOException e) {
        freeBuffer();
        throw e;
    }
}
项目:openjdk-jdk10    文件:SctpMultiChannelImpl.java   
@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);
    }
}
项目:lams    文件:AbstractFixedLengthStreamSinkConduit.java   
public long transferFrom(final FileChannel src, final long position, final long count) throws IOException {
    if (count == 0L) return 0L;
    long val = state;
    if (allAreSet(val, FLAG_CLOSE_REQUESTED)) {
        throw new ClosedChannelException();
    }
    if (allAreClear(val, MASK_COUNT)) {
        throw new FixedLengthOverflowException();
    }
    long res = 0L;
    try {
        return res = next.transferFrom(src, position, min(count, (val & MASK_COUNT)));
    } catch (IOException e) {
        broken = true;
        throw e;
    } finally {
        exitWrite(val, res);
    }
}
项目:OpenJSharp    文件:FileChannelImpl.java   
public long transferFrom(ReadableByteChannel src,
                         long position, long count)
    throws IOException
{
    ensureOpen();
    if (!src.isOpen())
        throw new ClosedChannelException();
    if (!writable)
        throw new NonWritableChannelException();
    if ((position < 0) || (count < 0))
        throw new IllegalArgumentException();
    if (position > size())
        return 0;
    if (src instanceof FileChannelImpl)
       return transferFromFileChannel((FileChannelImpl)src,
                                      position, count);

    return transferFromArbitraryChannel(src, position, count);
}
项目:lams    文件:GatedStreamSinkChannel.java   
public boolean flush() throws IOException {
    if (anyAreClear(state, FLAG_GATE_OPEN)) {
        return false;
    }
    if (anyAreSet(state, FLAG_CLOSED)) {
        throw new ClosedChannelException();
    }
    if (anyAreSet(state, FLAG_CLOSE_REQUESTED)) {
        boolean result = delegate.flush();
        if (result) {
            state |= FLAG_CLOSED;
        }
        return result;
    }
    return delegate.flush();
}
项目:jaer    文件:AEFileInputStream.java   
/**
 * set position in events from start of file
 *
 * @param event the number of the event, starting with 0
 */
@Override
synchronized public void position(long event) {
    // if(event==size()) event=event-1;
    int newChunkNumber;
    try {
        if ((newChunkNumber = getChunkNumber(event)) != chunkNumber) {
            mapChunk(newChunkNumber);

        }
        byteBuffer.position((int) ((event * eventSizeBytes) % chunkSizeBytes));

        position = event;
    } catch (ClosedByInterruptException e3) {
        log.info("caught interrupt, probably from single stepping this file");
    } catch (ClosedChannelException cce) {
        log.warning("caught exception " + cce);
        cce.printStackTrace();
    } catch (IOException e) {
        log.warning("caught exception " + e);
        e.printStackTrace();
    } catch (IllegalArgumentException e2) {
        log.warning("caught " + e2);
        e2.printStackTrace();
    }
}
项目:sstable-adaptor    文件:SyncUtil.java   
public static void force(FileChannel fc, boolean metaData) throws IOException
{
    Preconditions.checkNotNull(fc);
    if (SKIP_SYNC)
    {
        if (!fc.isOpen())
            throw new ClosedChannelException();
    }
    else
    {
        fc.force(metaData);
    }
}
项目:simulacron    文件:DisconnectActionTest.java   
@Test
public void testCloseConnection() throws Exception {
  // Validate that when a stub dictates to close a connection it does so and does not close the
  // NodeSpec's channel so it can remain accepting traffic.
  NodeSpec node = NodeSpec.builder().build();
  BoundNode boundNode = localServer.register(node);

  stubCloseOnStartup(Scope.CONNECTION);

  try (MockClient client = new MockClient(eventLoop)) {
    client.connect(boundNode.getAddress());
    // Sending a write should cause the connection to close.
    ChannelFuture f = client.write(new Startup());
    // Future should be successful since write was successful.
    f.get(5, TimeUnit.SECONDS);
    // Next write should fail because the channel was closed.
    f = client.write(Options.INSTANCE);
    try {
      f.get();
    } catch (ExecutionException e) {
      assertThat(e.getCause()).isInstanceOf(ClosedChannelException.class);
    } finally {
      assertThat(client.channel.isOpen()).isFalse();
      // node should still accept connections.
      assertThat(boundNode.channel.get().isOpen()).isTrue();
    }
  }
}
项目:hadoop    文件:DFSPacket.java   
/**
 * Write checksums to this packet
 *
 * @param inarray input array of checksums
 * @param off the offset of checksums to write
 * @param len the length of checksums to write
 * @throws ClosedChannelException
 */
synchronized void writeChecksum(byte[] inarray, int off, int len)
    throws ClosedChannelException {
  checkBuffer();
  if (len == 0) {
    return;
  }
  if (checksumPos + len > dataStart) {
    throw new BufferOverflowException();
  }
  System.arraycopy(inarray, off, buf, checksumPos, len);
  checksumPos += len;
}
项目:hadoop    文件:FsVolumeImpl.java   
/**
 * Increase the reference count. The caller must increase the reference count
 * before issuing IOs.
 *
 * @throws IOException if the volume is already closed.
 */
private void reference() throws ClosedChannelException {
  this.reference.reference();
  if (FsDatasetImpl.LOG.isTraceEnabled()) {
    printReferenceTraceInfo("incr");
  }
}
项目:openjdk-jdk10    文件:SctpServerChannelImpl.java   
@Override
public SctpServerChannel bind(SocketAddress local, int backlog)
        throws IOException {
    synchronized (lock) {
        synchronized (stateLock) {
            if (!isOpen())
                throw new ClosedChannelException();
            if (isBound())
                SctpNet.throwAlreadyBoundException();

            InetSocketAddress isa = (local == null) ?
                new InetSocketAddress(0) : Net.checkAddress(local);
            SecurityManager sm = System.getSecurityManager();
            if (sm != null)
                sm.checkListen(isa.getPort());
            Net.bind(fd, isa.getAddress(), isa.getPort());

            InetSocketAddress boundIsa = Net.localAddress(fd);
            port = boundIsa.getPort();
            localAddresses.add(isa);
                if (isa.getAddress().isAnyLocalAddress())
                    wildcard = true;

            SctpNet.listen(fdVal, backlog < 1 ? 50 : backlog);
        }
    }
    return this;
}
项目:hadoop-oss    文件:CloseableReferenceCount.java   
/**
 * Increment the reference count.
 *
 * @throws ClosedChannelException      If the status is closed.
 */
public void reference() throws ClosedChannelException {
  int curBits = status.incrementAndGet();
  if ((curBits & STATUS_CLOSED_MASK) != 0) {
    status.decrementAndGet();
    throw new ClosedChannelException();
  }
}
项目:openjdk-jdk10    文件:SctpMultiChannelImpl.java   
@Override
public Set<SocketAddress> getAllLocalAddresses()
        throws IOException {
    synchronized (stateLock) {
        if (!isOpen())
            throw new ClosedChannelException();
        if (!isBound())
            return Collections.emptySet();

        return SctpNet.getLocalAddresses(fdVal);
    }
}
项目:OpenJSharp    文件:SctpMultiChannelImpl.java   
@Override
public Set<SocketAddress> getAllLocalAddresses()
        throws IOException {
    synchronized (stateLock) {
        if (!isOpen())
            throw new ClosedChannelException();
        if (!isBound())
            return Collections.emptySet();

        return SctpNet.getLocalAddresses(fdVal);
    }
}
项目:monarch    文件:Connection.java   
/**
 * checks to see if an exception should not be logged: i.e., "forcibly closed", "reset by peer",
 * or "connection reset"
 */
public static final boolean isIgnorableIOException(Exception e) {
  if (e instanceof ClosedChannelException) {
    return true;
  }

  String msg = e.getMessage();
  if (msg == null) {
    msg = e.toString();
  }

  msg = msg.toLowerCase();
  return (msg.indexOf("forcibly closed") >= 0) || (msg.indexOf("reset by peer") >= 0)
      || (msg.indexOf("connection reset") >= 0);
}
项目:OpenJSharp    文件:SctpServerChannelImpl.java   
@Override
public Set<SocketAddress> getAllLocalAddresses()
        throws IOException {
    synchronized (stateLock) {
        if (!isOpen())
            throw new ClosedChannelException();
        if (!isBound())
            return Collections.emptySet();

        return SctpNet.getLocalAddresses(fdVal);
    }
}
项目:jdk8u-jdk    文件:SctpServerChannelImpl.java   
@Override
public SctpServerChannel bind(SocketAddress local, int backlog)
        throws IOException {
    synchronized (lock) {
        synchronized (stateLock) {
            if (!isOpen())
                throw new ClosedChannelException();
            if (isBound())
                SctpNet.throwAlreadyBoundException();

            InetSocketAddress isa = (local == null) ?
                new InetSocketAddress(0) : Net.checkAddress(local);
            SecurityManager sm = System.getSecurityManager();
            if (sm != null)
                sm.checkListen(isa.getPort());
            Net.bind(fd, isa.getAddress(), isa.getPort());

            InetSocketAddress boundIsa = Net.localAddress(fd);
            port = boundIsa.getPort();
            localAddresses.add(isa);
                if (isa.getAddress().isAnyLocalAddress())
                    wildcard = true;

            SctpNet.listen(fdVal, backlog < 1 ? 50 : backlog);
        }
    }
    return this;
}
项目:LightComm4J    文件:Connection.java   
public synchronized void write(byte[] data) throws ConnectionCloseException, ClosedChannelException {
    if (readyToClose)
        throw new ConnectionCloseException();
    ContextBean bean = context.getChanToContextBean().get(channel);
    ByteBuffer buffer = ByteBuffer.allocate(data.length + 4);
    buffer.putInt(data.length);
    buffer.put(data);
    buffer.flip();
    readyToWrite.add(buffer);
    int ops = bean.getOps();
    ops |= SelectionKey.OP_WRITE;
    bean.setOps(ops);
    this.channel.register(this.selector, ops);
    this.selector.wakeup();
}
项目:LightComm4J    文件:Connector.java   
@Override
public void run() {

    while (true) {
        try {
            this.selector.select();
            SocketChannel newChan = this.chanQueue.poll();
            if (newChan != null) {
                try {
                    newChan.register(selector, SelectionKey.OP_CONNECT);
                } catch (ClosedChannelException e) {
                    logger.warning("[Connector] channel close : " + e.toString());
                }
            }
            Set<SelectionKey> keys = this.selector.selectedKeys();
            Iterator<SelectionKey> iterator = keys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                handle(key);
                iterator.remove();
            }
        } catch (IOException e1) {
            this.logger.warning("[Connector] select error : " + e1.toString());
            this.selector = openSelector("[Connector]" + " selector open : ");
        }
    }
}
项目:RNLearn_Project1    文件:ReconnectingWebSocket.java   
public synchronized void sendMessage(RequestBody message) throws IOException {
  if (mWebSocket != null) {
    mWebSocket.sendMessage(message);
  } else {
    throw new ClosedChannelException();
  }
}
项目:openjdk-jdk10    文件:SctpChannelImpl.java   
private void ensureOpenAndUnconnected() throws IOException {
    synchronized (stateLock) {
        if (!isOpen())
            throw new ClosedChannelException();
        if (isConnected())
            throw new AlreadyConnectedException();
        if (state == ChannelState.PENDING)
            throw new ConnectionPendingException();
    }
}
项目:pcloud-networking-java    文件:RealApiChannelTest.java   
@Test
public void Reader_beginResponse_Throws_ClosedChannelException_On_Closed_Instance() throws Exception {
    ApiChannel apiChannel = createChannelInstance();
    connection.readBuffer().write(mockResponse());
    apiChannel.close();
    expectException(apiChannel, ClosedChannelException.class)
            .reader().beginResponse();
}
项目:pcloud-networking-java    文件:RealApiChannelTest.java   
@Test
public void Reader_endResponse_Throws_ClosedChannelException_On_Closed_Instance() throws Exception {
    ApiChannel apiChannel = createChannelInstance();
    connection.readBuffer().write(mockResponse());
    ProtocolResponseReader reader = apiChannel.reader();
    reader.beginResponse();
    apiChannel.close();
    expectException(reader, ClosedChannelException.class)
            .endResponse();
}
项目:pcloud-networking-java    文件:RealApiChannelTest.java   
@Test
public void Reader_beginObject_Throws_ClosedChannelException_On_Closed_Instance() throws Exception {
    ApiChannel apiChannel = createChannelInstance();
    connection.readBuffer().write(mockResponse());
    apiChannel.reader().beginResponse();
    apiChannel.close();
    expectException(apiChannel.reader(), ClosedChannelException.class).beginObject();
}
项目:openjdk-jdk10    文件:SctpChannelImpl.java   
private boolean ensureReceiveOpen() throws ClosedChannelException {
    synchronized (stateLock) {
        if (!isOpen())
            throw new ClosedChannelException();
        if (!isConnected())
            throw new NotYetConnectedException();
        else
            return true;
    }
}