java.io.InterruptedIOException Java Examples

The following examples show how to use java.io.InterruptedIOException. 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 check out the related API usage on the sidebar.
Example #1
Source File: StreamPipe.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public void run() {
    try {
        byte[] buf = new byte[1024];

        while (true) {
            int nr = in.read(buf);
            if (nr == -1)
                break;
            out.write(buf, 0, nr);
        }
    } catch (InterruptedIOException iioe) {
        // Thread interrupted during IO operation. Terminate StreamPipe.
        return;
    } catch (IOException e) {
        System.err.println("*** IOException in StreamPipe.run:");
        e.printStackTrace();
    }
}
 
Example #2
Source File: FSUtils.java    From hbase with Apache License 2.0 6 votes vote down vote up
/**
 * If DFS, check safe mode and if so, wait until we clear it.
 * @param conf configuration
 * @param wait Sleep between retries
 * @throws IOException e
 */
public static void waitOnSafeMode(final Configuration conf,
  final long wait)
throws IOException {
  FileSystem fs = FileSystem.get(conf);
  if (!(fs instanceof DistributedFileSystem)) return;
  DistributedFileSystem dfs = (DistributedFileSystem)fs;
  // Make sure dfs is not in safe mode
  while (isInSafeMode(dfs)) {
    LOG.info("Waiting for dfs to exit safe mode...");
    try {
      Thread.sleep(wait);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      throw (InterruptedIOException) new InterruptedIOException().initCause(e);
    }
  }
}
 
Example #3
Source File: StreamPipe.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public void run() {
    try {
        byte[] buf = new byte[1024];

        while (true) {
            int nr = in.read(buf);
            if (nr == -1)
                break;
            out.write(buf, 0, nr);
        }
    } catch (InterruptedIOException iioe) {
        // Thread interrupted during IO operation. Terminate StreamPipe.
        return;
    } catch (IOException e) {
        System.err.println("*** IOException in StreamPipe.run:");
        e.printStackTrace();
    }
}
 
Example #4
Source File: EnsResolver.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
private String callSmartContractFunction(
        Function function, String contractAddress, int chainId) throws Exception
{
    try
    {
        String encodedFunction = FunctionEncoder.encode(function);

        org.web3j.protocol.core.methods.request.Transaction transaction
                = createEthCallTransaction(TokenscriptFunction.ZERO_ADDRESS, contractAddress, encodedFunction);
        EthCall response = TokenRepository.getWeb3jService(chainId).ethCall(transaction, DefaultBlockParameterName.LATEST).send();

        return response.getValue();
    }
    catch (InterruptedIOException | UnknownHostException e)
    {
        //expected to happen when user switches wallets
        return "0x";
    }
}
 
Example #5
Source File: StreamPipe.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public void run() {
    try {
        byte[] buf = new byte[1024];

        while (true) {
            int nr = in.read(buf);
            if (nr == -1)
                break;
            out.write(buf, 0, nr);
        }
    } catch (InterruptedIOException iioe) {
        // Thread interrupted during IO operation. Terminate StreamPipe.
        return;
    } catch (IOException e) {
        System.err.println("*** IOException in StreamPipe.run:");
        e.printStackTrace();
    }
}
 
Example #6
Source File: MessageFormatter.java    From openpojo with Apache License 2.0 6 votes vote down vote up
private static String format(final Throwable throwable) {
  final StringWriter sw = new StringWriter();
  final PrintWriter pw = new PrintWriter(sw);
  throwable.printStackTrace(pw);

  pw.flush();
  final LineNumberReader reader = new LineNumberReader(new StringReader(sw.toString()));
  final ArrayList<String> lines = new ArrayList<String>();
  try {
    String line = reader.readLine();
    while (line != null) {
      lines.add(line);
      line = reader.readLine();
    }
  } catch (final IOException ex) {
    if (ex instanceof InterruptedIOException) {
      Thread.currentThread().interrupt();
    }
    lines.add(ex.toString());
  }
  return lines.toString();
}
 
Example #7
Source File: SpdyStream.java    From bluemix-parking-meter with MIT License 6 votes vote down vote up
/**
 * Returns once the input stream is either readable or finished. Throws
 * a {@link SocketTimeoutException} if the read timeout elapses before
 * that happens.
 */
private void waitUntilReadable() throws IOException {
  long start = 0;
  long remaining = 0;
  if (readTimeoutMillis != 0) {
    start = (System.nanoTime() / 1000000);
    remaining = readTimeoutMillis;
  }
  try {
    while (pos == -1 && !finished && !closed && errorCode == null) {
      if (readTimeoutMillis == 0) {
        SpdyStream.this.wait();
      } else if (remaining > 0) {
        SpdyStream.this.wait(remaining);
        remaining = start + readTimeoutMillis - (System.nanoTime() / 1000000);
      } else {
        throw new SocketTimeoutException();
      }
    }
  } catch (InterruptedException e) {
    throw new InterruptedIOException();
  }
}
 
Example #8
Source File: OkHttpTimeoutLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenCallTimeoutExceeded_thenInterruptedIOException() {
    // Given
    OkHttpClient client = new OkHttpClient.Builder()
            .callTimeout(1, TimeUnit.SECONDS)
            .build();

    Request request = new Request.Builder()
            .url(HTTPS_ADDRESS_DELAY_2)
            .build();

    // When
    Throwable thrown = catchThrowable(() -> client.newCall(request).execute());

    // Then
    assertThat(thrown).isInstanceOf(InterruptedIOException.class);

    logThrown(thrown);
}
 
Example #9
Source File: DynamicBuffer.java    From j2ssh-maverick with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Read a byte from the buffer
 * 
 * @return
 * 
 * @throws IOException
 * @throws InterruptedIOException
 */
protected synchronized int read() throws IOException {
	try {
		block();
	} catch (InterruptedException ex) {
		throw new InterruptedIOException(
				"The blocking operation was interrupted");
	}

	if (closed && available() <= 0) {
		return -1;
	}

	return buf[readpos++];

}
 
Example #10
Source File: SpdyStream.java    From crosswalk-cordova-android with Apache License 2.0 6 votes vote down vote up
/**
 * Returns once the peer is ready to receive {@code count} bytes.
 *
 * @throws IOException if the stream was finished or closed, or the
 * thread was interrupted.
 */
private void waitUntilWritable(int count, boolean last) throws IOException {
  try {
    while (unacknowledgedBytes + count >= writeWindowSize) {
      SpdyStream.this.wait(); // Wait until we receive a WINDOW_UPDATE.

      // The stream may have been closed or reset while we were waiting!
      if (!last && closed) {
        throw new IOException("stream closed");
      } else if (finished) {
        throw new IOException("stream finished");
      } else if (errorCode != null) {
        throw new IOException("stream was reset: " + errorCode);
      }
    }
  } catch (InterruptedException e) {
    throw new InterruptedIOException();
  }
}
 
Example #11
Source File: BlockingQueueReader.java    From dict_build with Apache License 2.0 6 votes vote down vote up
@Override
public E readNext() throws IOException {
    if (_closed) {
        return null;
    }
    try {
        E value = _queue.take();
        if (value == _endMarker) {
            _closed = true;
            return null;
        }
        return value;
    } catch (InterruptedException e) {
        InterruptedIOException ie = new InterruptedIOException();
        ie.initCause(e);
        throw ie;
    }
}
 
Example #12
Source File: CustomDailyRollingFileAppender.java    From EdgeSim with MIT License 6 votes vote down vote up
/** 
 * This method differentiates DailyRollingFileAppender from its 
 * super class. 
 * 
 * <p>Before actually logging, this method will check whether it is 
 * time to do a rollover. If it is, it will schedule the next 
 * rollover time and then rollover. 
 * */  
@Override  
protected void subAppend(LoggingEvent event) {  
    long n = System.currentTimeMillis();  
    if (n >= nextCheck) {  
        now.setTime(n);  
        nextCheck = rc.getNextCheckMillis(now);  
        try {  
            rollOver();  
        } catch (IOException ioe) {  
            if (ioe instanceof InterruptedIOException) {  
                Thread.currentThread().interrupt();  
            }  
            LogLog.error("rollOver() failed.", ioe);  
        }  
    }  
    super.subAppend(event);  
}
 
Example #13
Source File: CanYouQueryFromRenameTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected FileObject handleRename(String name) throws IOException {
    FileObject retValue;
    
    MyLoader l = (MyLoader)getLoader();
    try {
        RequestProcessor.getDefault().post(l).waitFinished(1000);
    } catch (InterruptedException ex) {
        throw (InterruptedIOException)new InterruptedIOException(ex.getMessage()).initCause(ex);
    }
    
    assertNotNull("In middle of creation", l.middle);

    l.v = l.lookup.lookup(JButton.class);
    
    retValue = super.handleRename(name);
    return retValue;
}
 
Example #14
Source File: Protocol.java    From pluotsorbet with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check for the required permission.
 *
 * @param name name of resource to insert into the permission question
 *
 * @exception InterruptedIOException if another thread interrupts the
 *   calling thread while this method is waiting to preempt the
 *   display.
 */
private void checkForPermission(String name)
        throws InterruptedIOException {
    name = protocol + ":" + name;

    try {
        AccessController.checkPermission(HTTP_PERMISSION_NAME, name);
        permissionChecked = true;
    } catch (InterruptedSecurityException ise) {
        throw new InterruptedIOException(
            "Interrupted while trying to ask the user permission");
    }

    try {
        AccessController.
            checkPermission(AccessController.TRUSTED_APP_PERMISSION_NAME);
        ownerTrusted = true;
    } catch (SecurityException se) {
        ownerTrusted = false;
    } 
}
 
Example #15
Source File: StreamPipe.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public void run() {
    try {
        byte[] buf = new byte[1024];

        while (true) {
            int nr = in.read(buf);
            if (nr == -1)
                break;
            out.write(buf, 0, nr);
        }
    } catch (InterruptedIOException iioe) {
        // Thread interrupted during IO operation. Terminate StreamPipe.
        return;
    } catch (IOException e) {
        System.err.println("*** IOException in StreamPipe.run:");
        e.printStackTrace();
    }
}
 
Example #16
Source File: StreamTimeout.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static void gobble(InputStream is, Reader rd,
        int ec, boolean force)
                throws Exception
                {
    int a = is.available();
    boolean r = rd.ready();
    log.print("" + a + " bytes available, "
            + "reader " + (r ? "" : "not ") + "ready");
    if (!r && !force) {
        log.println();
        return;
    }
    int c;
    try {
        c = rd.read();
    } catch (InterruptedIOException x) {
        log.println();
        throw x;
    }
    log.println(", read() ==> "
            + (c >= 0 ? ("'" + (char)c + "'" ): "EOF"));
    if (c != ec)
        throw new Exception("Incorrect value read: Expected "
                + ec + ", read " + (char)c);
}
 
Example #17
Source File: StreamTimeout.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private static void gobble(InputStream is, Reader rd,
        int ec, boolean force)
                throws Exception
                {
    int a = is.available();
    boolean r = rd.ready();
    log.print("" + a + " bytes available, "
            + "reader " + (r ? "" : "not ") + "ready");
    if (!r && !force) {
        log.println();
        return;
    }
    int c;
    try {
        c = rd.read();
    } catch (InterruptedIOException x) {
        log.println();
        throw x;
    }
    log.println(", read() ==> "
            + (c >= 0 ? ("'" + (char)c + "'" ): "EOF"));
    if (c != ec)
        throw new Exception("Incorrect value read: Expected "
                + ec + ", read " + (char)c);
}
 
Example #18
Source File: LoggingBuilder.java    From rocketmq-read with Apache License 2.0 6 votes vote down vote up
protected void subAppend(LoggingEvent event) {
    long n = System.currentTimeMillis();
    if (n >= nextCheck) {
        now.setTime(n);
        nextCheck = rc.getNextCheckMillis(now);
        try {
            rollOver();
        } catch (IOException ioe) {
            if (ioe instanceof InterruptedIOException) {
                Thread.currentThread().interrupt();
            }
            SysLogger.error("rollOver() failed.", ioe);
        }
    }
    super.subAppend(event);
}
 
Example #19
Source File: SpliceDefaultCompactor.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
protected InternalScanner postCreateCoprocScanner(final CompactionRequest request,
                                                  final ScanType scanType, final InternalScanner scanner, User user) throws IOException {
    if (store.getCoprocessorHost() == null) return scanner;
    if (user == null) {
        return store.getCoprocessorHost().preCompact(store, scanner, scanType, null, request, null);
    } else {
        try {
            return user.getUGI().doAs(new PrivilegedExceptionAction<InternalScanner>() {
                @Override
                public InternalScanner run() throws Exception {
                    return store.getCoprocessorHost().preCompact(store, scanner, scanType, null, request, null);
                }
            });
        } catch (InterruptedException ie) {
            InterruptedIOException iioe = new InterruptedIOException();
            iioe.initCause(ie);
            throw iioe;
        }
    }
}
 
Example #20
Source File: TestFlushLifeCycleTracker.java    From hbase with Apache License 2.0 6 votes vote down vote up
@Override
public void postFlush(ObserverContext<RegionCoprocessorEnvironment> c, Store store,
    StoreFile resultFile, FlushLifeCycleTracker tracker) throws IOException {
  if (TRACKER != null) {
    assertSame(tracker, TRACKER);
  }
  // inject here so we can make a flush request to fail because of we already have a flush
  // ongoing.
  CountDownLatch arrive = ARRIVE;
  if (arrive != null) {
    arrive.countDown();
    try {
      BLOCK.await();
    } catch (InterruptedException e) {
      throw new InterruptedIOException();
    }
  }
}
 
Example #21
Source File: SslConduit.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void awaitReadable() throws IOException {
    synchronized (this) {
        if(outstandingTasks > 0) {
            try {
                wait();
                return;
            } catch (InterruptedException e) {
                throw new InterruptedIOException();
            }
        }
    }
    if(unwrappedData != null) {
        return;
    }
    if(anyAreSet(state, FLAG_DATA_TO_UNWRAP)) {
        return;
    }
    if(anyAreSet(state, FLAG_READ_REQUIRES_WRITE)) {
        awaitWritable();
        return;
    }
    source.awaitReadable();
}
 
Example #22
Source File: AzureCloudInstanceInformationProcessor.java    From helix with Apache License 2.0 6 votes vote down vote up
public AzureCloudInstanceInformationProcessor(HelixCloudProperty helixCloudProperty) {
  _helixCloudProperty = helixCloudProperty;

  RequestConfig requestConifg = RequestConfig.custom()
      .setConnectionRequestTimeout((int) helixCloudProperty.getCloudRequestTimeout())
      .setConnectTimeout((int) helixCloudProperty.getCloudConnectionTimeout()).build();

  HttpRequestRetryHandler httpRequestRetryHandler =
      (IOException exception, int executionCount, HttpContext context) -> {
        LOG.warn("Execution count: " + executionCount + ".", exception);
        return !(executionCount >= helixCloudProperty.getCloudMaxRetry()
            || exception instanceof InterruptedIOException
            || exception instanceof UnknownHostException || exception instanceof SSLException);
      };

  //TODO: we should regularize the way how httpClient should be used throughout Helix. e.g. Helix-rest could also use in the same way
  _closeableHttpClient = HttpClients.custom().setDefaultRequestConfig(requestConifg)
      .setRetryHandler(httpRequestRetryHandler).build();
}
 
Example #23
Source File: TestCopy.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testInterruptedRename() throws Exception {
  FSDataOutputStream out = mock(FSDataOutputStream.class);
  whenFsCreate().thenReturn(out);
  when(mockFs.getFileStatus(eq(tmpPath))).thenReturn(fileStat);
  when(mockFs.rename(eq(tmpPath), eq(path))).thenThrow(
      new InterruptedIOException());
  FSInputStream in = mock(FSInputStream.class);
  when(in.read(any(byte[].class), anyInt(), anyInt())).thenReturn(-1);
  
  tryCopyStream(in, false);
  verify(mockFs).delete(eq(tmpPath), anyBoolean());
  verify(mockFs).rename(eq(tmpPath), eq(path));
  verify(mockFs, never()).delete(eq(path), anyBoolean());
  verify(mockFs, never()).close();
}
 
Example #24
Source File: StreamPipe.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
public void run() {
    try {
        byte[] buf = new byte[1024];

        while (true) {
            int nr = in.read(buf);
            if (nr == -1)
                break;
            out.write(buf, 0, nr);
        }
    } catch (InterruptedIOException iioe) {
        // Thread interrupted during IO operation. Terminate StreamPipe.
        return;
    } catch (IOException e) {
        System.err.println("*** IOException in StreamPipe.run:");
        e.printStackTrace();
    }
}
 
Example #25
Source File: SafeAsyncTask.java    From MVPAndroidBootstrap with Apache License 2.0 6 votes vote down vote up
protected void doException(final Exception e) throws Exception {
    if (parent.launchLocation != null) {
        final ArrayList<StackTraceElement> stack = new ArrayList<StackTraceElement>(Arrays.asList(e.getStackTrace()));
        stack.addAll(Arrays.asList(parent.launchLocation));
        e.setStackTrace(stack.toArray(new StackTraceElement[stack.size()]));
    }
    postToUiThreadAndWait(new Callable<Object>() {
        public Object call() throws Exception {
            if (e instanceof InterruptedException || e instanceof InterruptedIOException)
                parent.onInterrupted(e);
            else
                parent.onException(e);
            return null;
        }
    });
}
 
Example #26
Source File: HttpClientUtils.java    From blog-sample with Apache License 2.0 5 votes vote down vote up
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
    if (executionCount >= 3) {// 如果已经重试了3次,就放弃
        return false;
    }
    if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
        return true;
    }
    if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
        return false;
    }
    if (exception instanceof InterruptedIOException) {// 超时
        return true;
    }
    if (exception instanceof UnknownHostException) {// 目标服务器不可达
        return false;
    }
    if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
        return false;
    }
    if (exception instanceof SSLException) {// ssl握手异常
        return false;
    }
    HttpClientContext clientContext = HttpClientContext.adapt(context);
    HttpRequest request = clientContext.getRequest();
    // 如果请求是幂等的,就再次尝试
    if (request instanceof HttpEntityEnclosingRequest) {
        return false;
    }
    return false;
}
 
Example #27
Source File: AbstractLauncher.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
synchronized void launchAndAccept() throws
                        IOException, VMStartException {

    process = Runtime.getRuntime().exec(commandArray);

    Thread acceptingThread = acceptConnection();
    Thread monitoringThread = monitorTarget();
    try {
        while ((connection == null) &&
               (acceptException == null) &&
               !exited) {
            wait();
        }

        if (exited) {
            throw new VMStartException(
                "VM initialization failed for: " + commandString(), process);
        }
        if (acceptException != null) {
            // Rethrow the exception in this thread
            throw acceptException;
        }
    } catch (InterruptedException e) {
        throw new InterruptedIOException("Interrupted during accept");
    } finally {
        acceptingThread.interrupt();
        monitoringThread.interrupt();
    }
}
 
Example #28
Source File: DFSOutputStream.java    From hadoop with Apache License 2.0 5 votes vote down vote up
private void waitForAckedSeqno(long seqno) throws IOException {
  TraceScope scope = Trace.startSpan("waitForAckedSeqno", Sampler.NEVER);
  try {
    if (DFSClient.LOG.isDebugEnabled()) {
      DFSClient.LOG.debug("Waiting for ack for: " + seqno);
    }
    long begin = Time.monotonicNow();
    try {
      synchronized (dataQueue) {
        while (!isClosed()) {
          checkClosed();
          if (lastAckedSeqno >= seqno) {
            break;
          }
          try {
            dataQueue.wait(1000); // when we receive an ack, we notify on
            // dataQueue
          } catch (InterruptedException ie) {
            throw new InterruptedIOException(
                "Interrupted while waiting for data to be acknowledged by pipeline");
          }
        }
      }
      checkClosed();
    } catch (ClosedChannelException e) {
    }
    long duration = Time.monotonicNow() - begin;
    if (duration > dfsclientSlowLogThresholdMs) {
      DFSClient.LOG.warn("Slow waitForAckedSeqno took " + duration
          + "ms (threshold=" + dfsclientSlowLogThresholdMs + "ms)");
    }
  } finally {
    scope.close();
  }
}
 
Example #29
Source File: Connection.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private void pauseReader() throws IOException {
    if (debug) {
        System.err.println("Pausing reader;  was reading from: " +
                            inStream);
    }
    paused = true;
    try {
        while (paused) {
            pauseLock.wait(); // notified by unpauseReader
        }
    } catch (InterruptedException e) {
        throw new InterruptedIOException(
                "Pause/unpause reader has problems.");
    }
}
 
Example #30
Source File: MiGzOutputStream.java    From migz with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void write(byte[] b, int off, int len) throws IOException {
  if (_closed) {
    throw new IOException("Stream already closed");
  }
  MiGzUtil.checkException(_exception);

  try {
    while (len > 0) {
      if (len >= _blockSize - _currentBufferOffset) {
        // this fills up our current buffer completely
        int toCopy = _blockSize - _currentBufferOffset;
        System.arraycopy(b, off, _currentBuffer, _currentBufferOffset, toCopy);
        off += toCopy;
        len -= toCopy;
        _currentBufferOffset = _blockSize;

        scheduleCurrentBlock(new WriteOptions(StreamDirective.NONE, null));
      } else {
        System.arraycopy(b, off, _currentBuffer, _currentBufferOffset, len);
        _currentBufferOffset += len;
        return; // everything copied
      }
    }
  } catch (InterruptedException e) {
    throw new InterruptedIOException(e.getMessage());
  }
}