/** * Converts an input file stream into a char sequence. * * @throws IOException */ static CharBuffer getCharSequence(final FileInputStream stream, Charset encoding) throws IOException { FileChannel channel = stream.getChannel(); ByteBuffer bbuf = ByteBuffer.allocate((int) channel.size()); try { channel.read(bbuf, 0); } catch (ClosedByInterruptException cbie) { return null; //this is actually okay } finally { channel.close(); } bbuf.rewind(); CharBuffer cbuf = encoding.decode(bbuf); return cbuf; }
/** * This test sets off a blocking thread and then interrupts it, before * checking that the thread was interrupted * * @throws Throwable any exception other than that which was expected */ @Test(timeout = 10000) public void testInterruptedWaitForProxy() throws Throwable { RpcThread worker = new RpcThread(100); worker.start(); Thread.sleep(1000); assertTrue("worker hasn't started", worker.waitStarted); worker.interrupt(); worker.join(); Throwable caught = worker.getCaught(); assertNotNull("No exception was raised", caught); // looking for the root cause here, which can be wrapped // as part of the NetUtils work. Having this test look // a the type of exception there would be brittle to improvements // in exception diagnostics. Throwable cause = caught.getCause(); if (cause == null) { // no inner cause, use outer exception as root cause. cause = caught; } if (!(cause instanceof InterruptedIOException) && !(cause instanceof ClosedByInterruptException)) { throw caught; } }
private void handleRefreshException(Exception e) { if (e instanceof AlreadyClosedException) { // ignore } else if (e instanceof RefreshFailedEngineException) { RefreshFailedEngineException rfee = (RefreshFailedEngineException) e; if (rfee.getCause() instanceof InterruptedException) { // ignore, we are being shutdown } else if (rfee.getCause() instanceof ClosedByInterruptException) { // ignore, we are being shutdown } else if (rfee.getCause() instanceof ThreadInterruptedException) { // ignore, we are being shutdown } else { if (state != IndexShardState.CLOSED) { logger.warn("Failed to perform engine refresh", e); } } } else { if (state != IndexShardState.CLOSED) { logger.warn("Failed to perform engine refresh", e); } } }
/** * 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(); } }
/** * Perform an operation on the file, reopening the file and redoing the operation if necessary * if we are interrupted in the middle of the operation */ private long doUninterruptibly(FileOperation op) throws IOException { boolean interrupted = false; try { synchronized (UninterruptibleRandomAccessFile.this) { while (true) { interrupted |= Thread.interrupted(); FileChannel d = delegate(); long lastPosition = UninterruptibleRandomAccessFile.this.getFilePointer(); try { return op.doOp(d); } catch (ClosedByInterruptException e) { interrupted = true; UninterruptibleRandomAccessFile.this.reopen(lastPosition); } } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } }
void handleException(DebugContext debug, IOException e) { if (debug != null && DebugOptions.DumpingErrorsAreFatal.getValue(debug.getOptions())) { throw new GraalError(e); } if (e instanceof ClosedByInterruptException) { /* * The current dumping was aborted by an interrupt so treat this as a transient failure. */ failuresCount = 0; } else { failuresCount++; } printer = null; e.printStackTrace(TTY.out); if (failuresCount > FAILURE_LIMIT) { TTY.println("Too many failures with dumping. Disabling dump in thread " + Thread.currentThread()); } }
private void reopen(int i, IOException e) throws IOException { if (i > 20) { throw e; } if (!(e instanceof ClosedByInterruptException) && !(e instanceof ClosedChannelException)) { throw e; } // clear the interrupt flag, to avoid re-opening many times Thread.interrupted(); FileChannel before = channel; // ensure we don't re-open concurrently; // sometimes we don't re-open, which is fine, // as this method is called in a loop synchronized (this) { if (before == channel) { open(); reLock(); } } }
void handleException(IOException e) { if (GraalDebugConfig.Options.DumpingErrorsAreFatal.getValue(DebugScope.getConfig().getOptions())) { throw new GraalError(e); } if (e instanceof ClosedByInterruptException) { /* * The current dumping was aborted by an interrupt so treat this as a transient failure. */ failuresCount = 0; } else { failuresCount++; } printer = null; if (failuresCount > FAILURE_LIMIT) { e.printStackTrace(TTY.out); TTY.println("Too many failures with dumping. Disabling dump in thread " + Thread.currentThread()); } else { TTY.println(e.getMessage()); } }
@Override public void run() { try { L2CAPConnection clientConnection; CommChannel channel; while ( (clientConnection = connectionNotifier.acceptAndOpen()) != null ) { channel = new BTL2CapCommChannel( clientConnection, inputPort().location(), createProtocol() ); channel.setParentInputPort( inputPort() ); interpreter().commCore().scheduleReceive( channel, inputPort() ); channel = null; // Dispose for garbage collection } } catch( ClosedByInterruptException ce ) { try { connectionNotifier.close(); } catch( IOException ioe ) { ioe.printStackTrace(); } } catch( IOException e ) { e.printStackTrace(); } }
/** Check if there is no space in disk * @param e that caused this checkDiskError call **/ protected void checkDiskError(Exception e ) throws IOException { LOG.warn("checkDiskError: exception: ", e); if (e instanceof SocketException || e instanceof SocketTimeoutException || e instanceof ClosedByInterruptException || e.getMessage().startsWith("An established connection was aborted") || e.getMessage().startsWith("Broken pipe") || e.getMessage().startsWith("Connection reset") || e.getMessage().contains("java.nio.channels.SocketChannel")) { LOG.info("Not checking disk as checkDiskError was called on a network" + " related exception"); return; } if (e.getMessage() != null && e.getMessage().startsWith("No space left on device")) { throw new DiskOutOfSpaceException("No space left on device"); } else { checkDiskError(); } }
private static Void doDownload(AddonReleaseData releaseData) throws WarDownloadException { String warURL = releaseData.getDownloadUrl(); String dlPath = dlPath(releaseData.getVersion()); try { URL website = new URL(warURL); ReadableByteChannel rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(dlPath); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); try (FileInputStream fis = new FileInputStream(dlPath)) { String sha256 = DigestUtils.sha256Hex(fis); if (!sha256.equals(releaseData.getSha256())) { throw new WarDownloadException("Download of War file either corrupted or some 3rd party has changed the file"); } } } catch (ClosedByInterruptException ignored) { App.logger.error("War download interrupted before it could complete"); } catch (IOException e) { throw new WarDownloadException(e); } return null; }
/** * 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 = "ClosedByInterruptException", args = {} ) }) public void testSerializationSelf() throws Exception { SerializationTest.verifySelf(new ClosedByInterruptException()); }
/** * @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 = "ClosedByInterruptException", args = {} ) }) public void testSerializationCompatibility() throws Exception { SerializationTest.verifyGolden(this, new ClosedByInterruptException()); }
/*** * * @param ex * @return * @throws InterruptedException */ public static <T extends Throwable> T handleInterruptible(final T ex) throws InterruptedException { if (getInitialException(ex, ClosedByInterruptException.class) != null) { // This is how you detect InterruptedException from within BufferedReader. // I figured this out by looking at the source code for the GNU nio Channels // interface but it's backed up by // http://java.sun.com/j2se/1.5.0/docs/api/java/nio/channels/ClosedByInterruptException.html throw (InterruptedException) new InterruptedException().initCause(ex); } if (getInitialException(ex, InterruptedException.class) != null) { // There was an underlying InterruptedException that was chained below another error. throw (InterruptedException) new InterruptedException().initCause(ex); } // The exception probably wasn't an InterruptedException. return ex; }
private boolean doDutyCycle(final IdleStrategy idleStrategy, final Agent agent) { try { idleStrategy.idle(agent.doWork()); } catch (final InterruptedException | ClosedByInterruptException ignore) { Thread.currentThread().interrupt(); return true; } catch (final AgentTerminationException ex) { handleError(ex); return true; } catch (final Throwable throwable) { handleError(throwable); } return false; }
@Test public void shouldNotReportRethrownClosedByInterruptException() throws Exception { when(mockAgent.doWork()).thenAnswer( (inv) -> { try { throw new ClosedByInterruptException(); } catch (final ClosedByInterruptException ex) { LangUtil.rethrowUnchecked(ex); } return null; }); assertExceptionNotReported(); }
/** * Check if the provided exception looks like it's from a network error * @param e the exception from a checkDiskError call * @return true if this exception is network related, false otherwise */ protected boolean isNetworkRelatedException(Exception e) { if (e instanceof SocketException || e instanceof SocketTimeoutException || e instanceof ClosedChannelException || e instanceof ClosedByInterruptException) { return true; } String msg = e.getMessage(); return null != msg && (msg.startsWith("An established connection was aborted") || msg.startsWith("Broken pipe") || msg.startsWith("Connection reset") || msg.contains("java.nio.channels.SocketChannel")); }
/** * Waits for the current outstanding request retrying it with exponential backoff if it fails. * * @throws ClosedByInterruptException if request was interrupted * @throws IOException In the event of FileNotFoundException, MalformedURLException * @throws RetriesExhaustedException if exceeding the number of retries */ private void waitForOutstandingRequest() throws IOException { if (outstandingRequest == null) { return; } try { RetryHelper.runWithRetries(new Callable<Void>() { @Override public Void call() throws IOException, InterruptedException { if (RetryHelper.getContext().getAttemptNumber() > 1) { outstandingRequest.retry(); } token = outstandingRequest.waitForNextToken(); outstandingRequest = null; return null; } }, retryParams, GcsServiceImpl.exceptionHandler); } catch (RetryInterruptedException ex) { token = null; throw new ClosedByInterruptException(); } catch (NonRetriableException e) { Throwables.propagateIfInstanceOf(e.getCause(), IOException.class); throw e; } }
@Override public GcsOutputChannel createOrReplace( final GcsFilename filename, final GcsFileOptions fileOptions) throws IOException { try { RawGcsCreationToken token = RetryHelper.runWithRetries(new Callable<RawGcsCreationToken>() { @Override public RawGcsCreationToken call() throws IOException { long timeout = options.getRetryParams().getRequestTimeoutMillisForCurrentAttempt(); return raw.beginObjectCreation(filename, fileOptions, timeout); } }, options.getRetryParams(), exceptionHandler); return new GcsOutputChannelImpl( raw, token, options.getRetryParams(), options.getDefaultWriteBufferSize(), options.getHttpHeaders()); } catch (RetryInterruptedException ex) { throw new ClosedByInterruptException(); } catch (NonRetriableException e) { Throwables.propagateIfInstanceOf(e.getCause(), IOException.class); throw e; } }
@Override public GcsFileMetadata getMetadata(final GcsFilename filename) throws IOException { try { return RetryHelper.runWithRetries(new Callable<GcsFileMetadata>() { @Override public GcsFileMetadata call() throws IOException { long timeout = options.getRetryParams().getRequestTimeoutMillisForCurrentAttempt(); return raw.getObjectMetadata(filename, timeout); } }, options.getRetryParams(), exceptionHandler); } catch (RetryInterruptedException ex) { throw new ClosedByInterruptException(); } catch (NonRetriableException e) { Throwables.propagateIfInstanceOf(e.getCause(), IOException.class); throw e; } }
@Override public boolean delete(final GcsFilename filename) throws IOException { try { return RetryHelper.runWithRetries(new Callable<Boolean>() { @Override public Boolean call() throws IOException { long timeout = options.getRetryParams().getRequestTimeoutMillisForCurrentAttempt(); return raw.deleteObject(filename, timeout); } }, options.getRetryParams(), exceptionHandler); } catch (RetryInterruptedException ex) { throw new ClosedByInterruptException(); } catch (NonRetriableException e) { Throwables.propagateIfInstanceOf(e.getCause(), IOException.class); throw e; } }
@Override public void compose(final Iterable<String> source, final GcsFilename dest) throws IOException { try { RetryHelper.runWithRetries(new Callable<Void>() { @Override public Void call() throws IOException { long timeout = options.getRetryParams().getRequestTimeoutMillisForCurrentAttempt(); raw.composeObject(source, dest, timeout); return null; } }, options.getRetryParams(), exceptionHandler); } catch (RetryInterruptedException ex) { throw new ClosedByInterruptException(); } catch (NonRetriableException e) { Throwables.propagateIfInstanceOf(e.getCause(), IOException.class); throw e; } }
@Override public void copy(final GcsFilename source, final GcsFilename dest) throws IOException { try { RetryHelper.runWithRetries(new Callable<Void>() { @Override public Void call() throws IOException { long timeout = options.getRetryParams().getRequestTimeoutMillisForCurrentAttempt(); raw.copyObject(source, dest, null, timeout); return null; } }, options.getRetryParams(), exceptionHandler); } catch (RetryInterruptedException ex) { throw new ClosedByInterruptException(); } catch (NonRetriableException e) { Throwables.propagateIfInstanceOf(e.getCause(), IOException.class); throw e; } }
@Override public void update(final GcsFilename source, final GcsFileOptions fileOptions) throws IOException { try { RetryHelper.runWithRetries(new Callable<Void>() { @Override public Void call() throws IOException { long timeout = options.getRetryParams().getRequestTimeoutMillisForCurrentAttempt(); raw.copyObject(source, source, fileOptions, timeout); return null; } }, options.getRetryParams(), exceptionHandler); } catch (RetryInterruptedException ex) { throw new ClosedByInterruptException(); } catch (NonRetriableException e) { Throwables.propagateIfInstanceOf(e.getCause(), IOException.class); throw e; } }
@Test public void testShouldTry() { ExceptionHandler handler = new ExceptionHandler.Builder().retryOn(IOException.class).build(); assertTrue(handler.shouldRetry(new IOException())); assertTrue(handler.shouldRetry(new ClosedByInterruptException())); assertFalse(handler.shouldRetry(new RuntimeException())); handler = new ExceptionHandler.Builder() .retryOn(IOException.class, NullPointerException.class) .abortOn(RuntimeException.class, ClosedByInterruptException.class, InterruptedException.class) .build(); assertTrue(handler.shouldRetry(new IOException())); assertFalse(handler.shouldRetry(new ClosedByInterruptException())); assertFalse(handler.shouldRetry(new InterruptedException())); assertFalse(handler.shouldRetry(new RuntimeException())); assertTrue(handler.shouldRetry(new NullPointerException())); }
/** * 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(); } }
static IOException unwindInterruptException(IOException e) throws IOException { // This is dumb. Sometimes httpcomponents will throw a ClientProtocolException which wraps the real // exception we want to throw when interrupted, ClosedByInterruptException. So, try to find that // exception in the stack, and then throw that one instead Throwable t = e.getCause(); int i = 10; // cause depth limit while (i-- > 0 && t != null && !(t instanceof ClosedByInterruptException)) { t = t.getCause(); } if (t instanceof ClosedByInterruptException) { throw (IOException)t; } else { throw e; } }
/** Propagates an {@link InterruptedException} masquerading as another {@code Throwable}. */ public static void propagateIfInterrupt(Throwable thrown) throws InterruptedException { // If it's already an `InterruptedException`, just rethrow it. if (thrown instanceof InterruptedException) { throw (InterruptedException) thrown; } // Thrown when a thread is interrupted while blocked on I/O. So propagate this as // an `InterruptedException`. if (thrown instanceof ClosedByInterruptException) { throw asInterruptedException(thrown); } // `InterruptedIOException` can also be thrown when a thread is interrupted while blocked // by I/O, so propagate this -- unless it's a `SocketTimeoutException` which is thrown when // when a the timeout set on a socket is triggered. if (thrown instanceof InterruptedIOException && !(thrown instanceof SocketTimeoutException)) { throw asInterruptedException(thrown); } }
@Override public FileLock lock(long position, long size, boolean shared) throws IOException { checkLockArguments(position, size, shared); // lock is interruptible boolean completed = false; try { begin(); completed = true; return new FakeFileLock(this, position, size, shared); } finally { try { end(completed); } catch (ClosedByInterruptException e) { throw new FileLockInterruptionException(); } } }