@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; } }
@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(); } } }
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; }
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); }
@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); } }
@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; }
@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); } }
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; }
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); } }
@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); }
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); } }
@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; } }
@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); } }
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); } }
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); }
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(); }
/** * 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(); } }
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); } }
@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(); } } }
/** * 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; }
/** * 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"); } }
@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; }
/** * 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(); } }
@Override public Set<SocketAddress> getAllLocalAddresses() throws IOException { synchronized (stateLock) { if (!isOpen()) throw new ClosedChannelException(); if (!isBound()) return Collections.emptySet(); return SctpNet.getLocalAddresses(fdVal); } }
/** * 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); }
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(); }
@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 : "); } } }
public synchronized void sendMessage(RequestBody message) throws IOException { if (mWebSocket != null) { mWebSocket.sendMessage(message); } else { throw new ClosedChannelException(); } }
private void ensureOpenAndUnconnected() throws IOException { synchronized (stateLock) { if (!isOpen()) throw new ClosedChannelException(); if (isConnected()) throw new AlreadyConnectedException(); if (state == ChannelState.PENDING) throw new ConnectionPendingException(); } }
@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(); }
@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(); }
@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(); }
private boolean ensureReceiveOpen() throws ClosedChannelException { synchronized (stateLock) { if (!isOpen()) throw new ClosedChannelException(); if (!isConnected()) throw new NotYetConnectedException(); else return true; } }