下面列出了怎么用java.io.InterruptedIOException的API类实例代码及写法,或者点击链接到github查看源代码。
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();
}
}
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";
}
}
/**
* 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++];
}
@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);
}
/**
* 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();
}
}
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();
}
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();
}
}
/**
* 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();
}
}
@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;
}
}
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;
}
@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();
}
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();
}
@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();
}
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);
}
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();
}
}
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);
}
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);
}
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;
}
}
}
@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();
}
}
}
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();
}
}
/**
* 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;
}
}
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;
}
});
}
/**
* 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);
}
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();
}
}
/**
* 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);
}
}
}
/**
* Called when registration is established.
* @param midletSuite MIDlet suite for the suite registering,
* the suite only has to implement isRegistered,
* checkForPermission, and getID.
* @param connection generic connection <em>protocol</em>, <em>host</em>
* and <em>port number</em>
* (optional parameters may be included
* separated with semi-colons (;))
* @param midlet class name of the <code>MIDlet</code> to be launched,
* when new external data is available
* @param filter a connection URL string indicating which senders
* are allowed to cause the MIDlet to be launched
* @exception IllegalArgumentException if the connection string is not
* valid
* @exception IOException if the connection is already
* registered or if there are insufficient resources
* to handle the registration request
* @exception ClassNotFoundException if the <code>MIDlet</code> class
* name can not be found in the current
* <code>MIDlet</code> suite
*/
public void registerConnection(MIDletSuite midletSuite, String connection,
String midlet, String filter)
throws IllegalArgumentException, IOException, ClassNotFoundException {
checkIsNotHost(connection, true);
/*
* Attempt to open the connection to perform security check
* int the context of the current MIDlet suite.
*/
try {
Class.forName(
"com.sun.midp.io.j2me.serversocket.Socket");
} catch (ClassNotFoundException e) {
throw new ConnectionNotFoundException(
"Connection not supported");
}
try {
midletSuite.checkForPermission("javax.microedition.io.Connector.serversocket",
connection);
} catch (InterruptedException ie) {
throw new InterruptedIOException(
"Interrupted while trying to ask the user permission");
}
}
@Override
public void preFlush(ObserverContext<RegionCoprocessorEnvironment> e,
FlushLifeCycleTracker tracker) throws IOException {
if (delayFlush) {
try {
if (Bytes.compareTo(e.getEnvironment().getRegionInfo().getStartKey(),
HConstants.EMPTY_START_ROW) != 0) {
Thread.sleep(100);
}
} catch (InterruptedException e1) {
throw new InterruptedIOException(e1.getMessage());
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void writeTo(OutputStream outStream) throws IOException {
if (outStream == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
InputStream inStream = null;
try {
inStream = getContent();
byte[] tmp = new byte[4096];
int len;
while ((len = inStream.read(tmp)) != -1) {
outStream.write(tmp, 0, len);
uploadedSize += len;
if (callBackHandler != null) {
if (!callBackHandler.updateProgress(uncompressedLength, uploadedSize, false)) {
throw new InterruptedIOException("cancel");
}
}
}
outStream.flush();
if (callBackHandler != null) {
callBackHandler.updateProgress(uncompressedLength, uploadedSize, true);
}
} finally {
IOUtils.closeQuietly(inStream);
}
}
/**
* Returns the stream's response headers, blocking if necessary if they
* have not been received yet.
*/
public synchronized List<String> getResponseHeaders() throws IOException {
long remaining = 0;
long start = 0;
if (readTimeoutMillis != 0) {
start = (System.nanoTime() / 1000000);
remaining = readTimeoutMillis;
}
try {
while (responseHeaders == null && errorCode == null) {
if (readTimeoutMillis == 0) { // No timeout configured.
wait();
} else if (remaining > 0) {
wait(remaining);
remaining = start + readTimeoutMillis - (System.nanoTime() / 1000000);
} else {
throw new SocketTimeoutException("Read response header timeout. readTimeoutMillis: "
+ readTimeoutMillis);
}
}
if (responseHeaders != null) {
return responseHeaders;
}
throw new IOException("stream was reset: " + errorCode);
} catch (InterruptedException e) {
InterruptedIOException rethrow = new InterruptedIOException();
rethrow.initCause(e);
throw rethrow;
}
}
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
if (executionCount >= 5) {// 如果已经重试了5次,就放弃
return false;
}
if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
return true;
}
if (exception instanceof InterruptedIOException) {// 超时
return false;
}
if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
return false;
}
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 true;
}
return false;
}