@Override public void stop(boolean waitDone) throws IOException, InterruptedException { final CountDownLatch latch = connectionLatch; if (running.compareAndSet(true, false)) { try { if (serverSocketChannel != null) { serverSocketChannel.close(); serverSocketChannel = null; } } catch (AsynchronousCloseException e) { e.printStackTrace(); } finally { if (waitDone) { latch.await(); } } } }
@Override public void failed(Throwable exc, ByteBuffer buffer) { if((exc instanceof AsynchronousCloseException) || (exc instanceof ClosedChannelException)){ return; } if(exc instanceof Exception){ Exception e = (Exception)exc; //兼容 windows 的 "java.io.IOException: 指定的网络名不再可用" 错误 if(e.getStackTrace()[0].getClassName().contains("sun.nio.ch")){ session.close(); return; } //触发 onException 事件 EventTrigger.fireExceptionThread(session, (Exception)exc); } }
/** * Indicates the end of a code section that has been started with * {@code begin()} and that includes a potentially blocking I/O operation. * * @param success * pass {@code true} if the blocking operation has succeeded and * has had a noticeable effect; {@code false} otherwise. * @throws AsynchronousCloseException * if this channel is closed by another thread while this method * is executing. * @throws ClosedByInterruptException * if another thread interrupts the calling thread while this * method is executing. */ protected final void end(boolean success) throws AsynchronousCloseException { // FIXME: be accommodate before VM actually provides // setInterruptAction method if (setInterruptAction != null) { try { setInterruptAction.invoke(Thread.currentThread(), new Object[] { null }); } catch (Exception e) { throw new RuntimeException(e); } if (interrupted) { interrupted = false; throw new ClosedByInterruptException(); } } if (!success && closed) { throw new AsynchronousCloseException(); } }
/** * @tests serialization/deserialization compatibility. */ @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, notes = "Verifies serialization/deserialization compatibility.", method = "!SerializationSelf", args = {} ), @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "Verifies serialization/deserialization compatibility.", method = "AsynchronousCloseException", args = {} ) }) public void testSerializationSelf() throws Exception { SerializationTest.verifySelf(new AsynchronousCloseException()); }
/** * @tests serialization/deserialization compatibility with RI. */ @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, notes = "Verifies serialization/deserialization compatibility.", method = "!SerializationGolden", args = {} ), @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "Verifies serialization/deserialization compatibility.", method = "AsynchronousCloseException", args = {} ) }) public void testSerializationCompatibility() throws Exception { SerializationTest.verifyGolden(this, new AsynchronousCloseException()); }
private void transferStreams( BufferedReader reader, PrintWriter writer, boolean receive ) throws IOException { try { String line; while( ( line = reader.readLine() ) != null ) { writer.println( line ); writer.flush(); if( receive ) { publishProgress( CONNECTED.toString(), output.toString() ); } } } catch( AsynchronousCloseException e ) { // This exception is thrown when socket for receiver thread is closed by netcat Log.w( CLASS_NAME, e.toString() ); } }
/** * End an IO operation that was previously started with <code>begin()</code>. * * @param success * pass true if the operation succeeded and had a side effect on * the Java system, or false if not. * @throws AsynchronousCloseException * the channel was closed while the IO operation was in * progress. * @throws java.nio.channels.ClosedByInterruptException * the thread conducting the IO operation was interrupted. */ protected final void end(boolean success) throws AsynchronousCloseException { // FIXME: be accommodate before VM actually provides // setInterruptAction method if (setInterruptAction != null) { try { setInterruptAction.invoke(Thread.currentThread(), new Object[] { null }); } catch (Exception e) { throw new RuntimeException(e); } if (interrupted) { interrupted = false; throw new ClosedByInterruptException(); } } if (!success && closed) { throw new AsynchronousCloseException(); } }
/** * Reads the incoming network data from the socket and retrieves the OF * messages. * * @return list of OF messages * @throws Exception */ @Override public List<OFMessage> readMessages() throws IOException { if (!socket.isOpen()) { return null; } List<OFMessage> msgs = null; int bytesRead = -1; bytesRead = socket.read(inBuffer); if (bytesRead < 0) { throw new AsynchronousCloseException(); } inBuffer.flip(); msgs = factory.parseMessages(inBuffer); if (inBuffer.hasRemaining()) { inBuffer.compact(); } else { inBuffer.clear(); } return msgs; }
/** * Decrement the reference count, checking to make sure that the * CloseableReferenceCount is not closed. * * @throws AsynchronousCloseException If the status is closed. */ public void unreferenceCheckClosed() throws ClosedChannelException { int newVal = status.decrementAndGet(); if ((newVal & STATUS_CLOSED_MASK) != 0) { throw new AsynchronousCloseException(); } }
@Override public void failed(Throwable exc, AioServer serverHandler) { if (exc instanceof AsynchronousCloseException) { connectionLatch.countDown(); } else { exc.printStackTrace(); } }
public void processOnce() throws IOException { // set status of query to OK. ctx.getState().reset(); executor = null; // reset sequence id of MySQL protocol final MysqlChannel channel = ctx.getMysqlChannel(); channel.setSequenceId(0); // read packet from channel try { packetBuf = channel.fetchOnePacket(); if (packetBuf == null) { logger.warn("Null packet received from network. remote: {}", channel.getRemote()); throw new IOException("Error happened when receiving packet."); } } catch (AsynchronousCloseException e) { // when this happened, timeout checker close this channel // killed flag in ctx has been already set, just return return; } // dispatch dispatch(); // finalize finalizeCommand(); ctx.setCommand(MysqlCommand.COM_SLEEP); }
@Override public void failed(Throwable exc, AioSocketChannel channel) { if (exc instanceof AsynchronousCloseException) { //FIXME 产生该异常的原因是shutdownOutput后对方收到 read(-1)然后调用shutdownOutput,本地在收到read(-1)之前关闭了连接 return; } logger.error(exc.getMessage() + ", channel:" + channel, exc); CloseUtil.close(channel); }
void onFailed(Throwable e) { if (e instanceof AsynchronousCloseException) { onClosed(); return; } if (!connected) return; synchronized (sendSync) { connected = false; completeOutstandingRequestsExceptionally(e); } }
private int read(ByteBuffer[] dsts, int offset, int length, AtomicInteger posToUpdate) throws IOException { if(!isOpenForRead){ throw new NonReadableChannelException(); } throwExceptionIfClosed(); int counter = 0; synchronized(readWriteMonitor){ for(int j=offset; j<length; j++){ ByteBuffer dst = dsts[j]; int r = dst.remaining(); for(int i=0; i<r; i++){ int b = NativeMockedIO.read(path, posToUpdate); if(b < 0){ //end of stream return -1; } if(closed){ throw new AsynchronousCloseException(); } if(Thread.currentThread().isInterrupted()){ close(); throw new ClosedByInterruptException(); } dst.put((byte)b); counter++; } } } return counter; }
private int write(ByteBuffer[] srcs, int offset, int length, AtomicInteger posToUpdate) throws IOException { if(!isOpenForWrite){ throw new NonWritableChannelException(); } if( (offset < 0) || (offset > srcs.length) || (length < 0) || (length > srcs.length-offset) ){ throw new IndexOutOfBoundsException(); } throwExceptionIfClosed(); int counter = 0; byte[] buffer = new byte[1]; synchronized(readWriteMonitor){ for(int j=offset; j<length; j++){ ByteBuffer src = srcs[j]; int r = src.remaining(); for(int i=0; i<r; i++){ byte b = src.get(); buffer[0] = b; NativeMockedIO.writeBytes(path, posToUpdate, buffer, 0, 1); counter++; if(closed){ throw new AsynchronousCloseException(); } if(Thread.currentThread().isInterrupted()){ close(); throw new ClosedByInterruptException(); } } } } return counter; }
/** * @tests {@link java.nio.channels.AsynchronousCloseException#AsynchronousCloseException()} */ public void test_Constructor() { AsynchronousCloseException e = new AsynchronousCloseException(); assertNull(e.getMessage()); assertNull(e.getLocalizedMessage()); assertNull(e.getCause()); }
void _close() { try { sock.close(); } catch (IOException ex) { if (!(ex instanceof AsynchronousCloseException)) Logger.getLogger(Nio2Socket.class.getName()).log(Level.SEVERE, null, ex); } }
/** * @tests AbstractInterruptibleChannel#close/begin/end() */ public void test_close_begin_end() throws IOException { boolean complete = false; MockInterruptibleChannel testChannel = new MockInterruptibleChannel(); assertTrue(testChannel.isOpen()); try { testChannel.superBegin(); complete = true; } finally { testChannel.superEnd(complete); } assertTrue(testChannel.isOpen()); testChannel.close(); try { testChannel.superBegin(); complete = false; } finally { try { testChannel.superEnd(complete); fail("should throw AsynchronousCloseException"); } catch (AsynchronousCloseException e) { // expected } } assertFalse(testChannel.isOpen()); try { testChannel.superBegin(); complete = true; } finally { testChannel.superEnd(complete); } assertFalse(testChannel.isOpen()); }
/** * Ends a blocking operation, throwing an exception if the thread was interrupted while blocking * or if the channel was closed from another thread. */ private void endBlocking(boolean completed) throws AsynchronousCloseException { synchronized (blockingThreads) { blockingThreads.remove(Thread.currentThread()); } end(completed); }
/** * Assert that the future fails, with the failure caused by either * {@code AsynchronousCloseException} or (rarely) {@code ClosedChannelException}. */ private static void assertAsynchronousClose(Future<?> future) throws Throwable { try { future.get(10, SECONDS); fail("no exception was thrown"); } catch (ExecutionException expected) { Throwable t = expected.getCause(); if (!(t instanceof AsynchronousCloseException || t instanceof ClosedChannelException)) { fail("expected AsynchronousCloseException (or in rare cases ClosedChannelException): " + "got " + t); } } }
@Test public void testAsynchronousClose() throws Exception { RegularFile file = regularFile(10); final FileChannel channel = channel(file, READ, WRITE); file.writeLock().lock(); // ensure all operations on the channel will block ExecutorService executor = Executors.newCachedThreadPool(); CountDownLatch latch = new CountDownLatch(BLOCKING_OP_COUNT); List<Future<?>> futures = queueAllBlockingOperations(channel, executor, latch); // wait for all the threads to have started running latch.await(); // then ensure time for operations to start blocking Uninterruptibles.sleepUninterruptibly(20, MILLISECONDS); // close channel on this thread channel.close(); // the blocking operations are running on different threads, so they all get // AsynchronousCloseException for (Future<?> future : futures) { try { future.get(); fail(); } catch (ExecutionException expected) { assertThat(expected.getCause()) .named("blocking thread exception") .isInstanceOf(AsynchronousCloseException.class); } } }
private void reportError(Exception e) { if (e instanceof AsynchronousCloseException || e instanceof InterruptedException || e instanceof SocketException || e instanceof IOException || e instanceof ClosedSelectorException) { if (logger.isDebugEnabled()) { logger.debug("Caught exception {}", e.getMessage()); } } else { logger.warn("Caught exception ", e); } // notify core of this error event and disconnect the switch ((Controller) core).takeSwitchEventError(this); }
public void failed(Throwable e, Node node) { if (e instanceof AsynchronousCloseException) { log.debug("Channel " + node + " was closed, so can't close it."); } else { log.error("Channel " + node + " failed, close socket because " + e.getMessage()); node.close(getClass()); } }
@Override public void failed( Throwable reason ) { try{ if ( Logger.isEnabled()){ if ( reason instanceof EOFException ){ Logger.log(new LogEvent(LOGID, "AEProxyProcessor: " + getName() + ": connection closed" )); }else{ String message = Debug.getNestedExceptionMessage( reason ); message = message.toLowerCase( Locale.US ); if ( ( reason instanceof AsynchronousCloseException ) || message.contains( "closed" ) || message.contains( "aborted" ) || message.contains( "disconnected" ) || message.contains( "timeout" ) || message.contains( "timed" ) || message.contains( "refused" ) || message.contains( "unreachable" ) || message.contains( "reset" ) || message.contains( "no route" ) || message.contains( "family" ) || // address family not supported message.contains( "key is invalid" ) || message.contains( "dns lookup" )){ // boring Logger.log(new LogEvent(LOGID, "AEProxyProcessor: " + getName() + " failed: " + message )); }else{ Logger.log(new LogEvent(LOGID, "AEProxyProcessor: " + getName() + " failed", reason )); } } } close(); }catch( Throwable e ){ Debug.printStackTrace(e); } }
/** * Monitors the devices. This connects to the Debug Bridge */ private void deviceMonitorLoop() { do { try { if (mMainAdbConnection == null) { Log.d("DeviceMonitor", "Opening adb connection"); mMainAdbConnection = openAdbConnection(); if (mMainAdbConnection == null) { mConnectionAttempt++; Log.e("DeviceMonitor", "Connection attempts: " + mConnectionAttempt); if (mConnectionAttempt > 10) { if (mServer.startAdb() == false) { mRestartAttemptCount++; Log.e("DeviceMonitor", "adb restart attempts: " + mRestartAttemptCount); } else { mRestartAttemptCount = 0; } } waitABit(); } else { Log.d("DeviceMonitor", "Connected to adb for device monitoring"); mConnectionAttempt = 0; } } if (mMainAdbConnection != null && mMonitoring == false) { mMonitoring = sendDeviceListMonitoringRequest(); } if (mMonitoring) { // read the length of the incoming message: block int length = readLength(mMainAdbConnection, mLengthBuffer); if (length >= 0) { // read the incoming message processIncomingDeviceData(length); // flag the fact that we have build the list at least once. mInitialDeviceListDone = true; } } } catch (AsynchronousCloseException ace) { // this happens because of a call to Quit. We do nothing, and the loop will break. } catch (IOException ioe) { if (mQuit == false) { Log.e("DeviceMonitor", "Adb connection Error:" + ioe.getMessage()); mMonitoring = false; if (mMainAdbConnection != null) { try { mMainAdbConnection.close(); } catch (IOException ioe2) { // we can safely ignore that one. } mMainAdbConnection = null; } } } } while (mQuit == false); }
@Override public void run() { do { if (mAdbConnection == null) { Log.d("DeviceMonitor", "Opening adb connection"); mAdbConnection = openAdbConnection(); if (mAdbConnection == null) { mConnectionAttempt++; Log.e("DeviceMonitor", "Connection attempts: " + mConnectionAttempt); if (mConnectionAttempt > 10) { if (!mBridge.startAdb()) { mRestartAttemptCount++; Log.e("DeviceMonitor", "adb restart attempts: " + mRestartAttemptCount); } else { Log.i("DeviceMonitor", "adb restarted"); mRestartAttemptCount = 0; } } Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); } else { Log.d("DeviceMonitor", "Connected to adb for device monitoring"); mConnectionAttempt = 0; } } try { if (mAdbConnection != null && !mMonitoring) { mMonitoring = sendDeviceListMonitoringRequest(); } if (mMonitoring) { int length = readLength(mAdbConnection, mLengthBuffer); if (length >= 0) { // read the incoming message processIncomingDeviceData(length); // flag the fact that we have build the list at least once. mInitialDeviceListDone = true; } } } catch (AsynchronousCloseException ace) { // this happens because of a call to Quit. We do nothing, and the loop will break. } catch (TimeoutException | IOException ioe) { handleExceptionInMonitorLoop(ioe); } } while (!mQuit); }
@Override public void failed(Throwable exc, AioServerSocket attachment) { if(!(exc instanceof AsynchronousCloseException)) { Logger.error(new Exception(exc)); } }