Java Code Examples for java.net.SocketTimeoutException

The following examples show how to use java.net.SocketTimeoutException. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: exhibitor   Source File: TestRemoteInstanceRequestClient.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void     testConnectionTimeout() throws Exception
{
    int             port = InstanceSpec.getRandomPort();

    RemoteInstanceRequestClientImpl client = null;
    ServerSocket                    server = new ServerSocket(port, 0);
    try
    {
        client = new RemoteInstanceRequestClientImpl(new RemoteConnectionConfiguration());
        client.getWebResource(new URI("http://localhost:" + port), MediaType.WILDCARD_TYPE, Object.class);
    }
    catch ( Exception e )
    {
        Throwable cause = e.getCause();
        Assert.assertTrue(cause instanceof SocketTimeoutException);
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
        server.close();
    }
}
 
Example 2
Source Project: Tomcat8-Source-Read   Source File: AprEndpoint.java    License: MIT License 6 votes vote down vote up
/**
 * Timeout checks. Must only be called from {@link Poller#run()}.
 */
private synchronized void maintain() {
    long date = System.currentTimeMillis();
    // Maintain runs at most once every 1s, although it will likely get
    // called more
    if ((date - lastMaintain) < 1000L) {
        return;
    } else {
        lastMaintain = date;
    }
    long socket = timeouts.check(date);
    while (socket != 0) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("endpoint.debug.socketTimeout",
                    Long.valueOf(socket)));
        }
        SocketWrapperBase<Long> socketWrapper = connections.get(Long.valueOf(socket));
        socketWrapper.setError(new SocketTimeoutException());
        processSocket(socketWrapper, SocketEvent.ERROR, true);
        socket = timeouts.check(date);
    }

}
 
Example 3
Source Project: cordova-amazon-fireos   Source File: SpdyStream.java    License: Apache License 2.0 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 4
Source Project: dubbox-hystrix   Source File: RmiProtocol.java    License: Apache License 2.0 6 votes vote down vote up
protected int getErrorCode(Throwable e) {
    if (e instanceof RemoteAccessException) {
        e = e.getCause();
    }
    if (e != null && e.getCause() != null) {
        Class<?> cls = e.getCause().getClass();
        // 是根据测试Case发现的问题,对RpcException.setCode进行设置
        if (SocketTimeoutException.class.equals(cls)) {
            return RpcException.TIMEOUT_EXCEPTION;
        } else if (IOException.class.isAssignableFrom(cls)) {
            return RpcException.NETWORK_EXCEPTION;
        } else if (ClassNotFoundException.class.isAssignableFrom(cls)) {
            return RpcException.SERIALIZATION_EXCEPTION;
        }
    }
    return super.getErrorCode(e);
}
 
Example 5
Source Project: sahara-extra   Source File: ExceptionDiags.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Take an IOException and a URI, wrap it where possible with
 * something that includes the URI
 *
 * @param dest target URI
 * @param operation operation
 * @param exception the caught exception.
 * @return an exception to throw
 */
public static IOException wrapException(final String dest,
                                        final String operation,
                                        final IOException exception) {
  String action = operation + " " + dest;
  String xref = null;

  if (exception instanceof ConnectException) {
    xref = "ConnectionRefused";
  } else if (exception instanceof UnknownHostException) {
    xref = "UnknownHost";
  } else if (exception instanceof SocketTimeoutException) {
    xref = "SocketTimeout";
  } else if (exception instanceof NoRouteToHostException) {
    xref = "NoRouteToHost";
  }
  String msg = action
               + " failed on exception: "
               + exception;
  if (xref != null) {
     msg = msg + ";" + see(xref);
  }
  return wrapWithMessage(exception, msg);
}
 
Example 6
Source Project: big-c   Source File: BackupNode.java    License: Apache License 2.0 6 votes vote down vote up
private NamespaceInfo handshake(Configuration conf) throws IOException {
  // connect to name node
  InetSocketAddress nnAddress = NameNode.getServiceAddress(conf, true);
  this.namenode = NameNodeProxies.createNonHAProxy(conf, nnAddress,
      NamenodeProtocol.class, UserGroupInformation.getCurrentUser(),
      true).getProxy();
  this.nnRpcAddress = NetUtils.getHostPortString(nnAddress);
  this.nnHttpAddress = DFSUtil.getInfoServer(nnAddress, conf,
      DFSUtil.getHttpClientScheme(conf)).toURL();
  // get version and id info from the name-node
  NamespaceInfo nsInfo = null;
  while(!isStopRequested()) {
    try {
      nsInfo = handshake(namenode);
      break;
    } catch(SocketTimeoutException e) {  // name-node is busy
      LOG.info("Problem connecting to server: " + nnAddress);
      try {
        Thread.sleep(1000);
      } catch (InterruptedException ie) {
        LOG.warn("Encountered exception ", e);
      }
    }
  }
  return nsInfo;
}
 
Example 7
Source Project: KaellyBot   Source File: ExceptionManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static void manageIOException(Exception e, Message message, Command command, Language lg, DiscordException notFound){
    // First we try parsing the exception message to see if it contains the response code
    Matcher exMsgStatusCodeMatcher = Pattern.compile("^Server returned HTTP response code: (\\d+)")
            .matcher(e.getMessage());
    if(exMsgStatusCodeMatcher.find()) {
        int statusCode = Integer.parseInt(exMsgStatusCodeMatcher.group(1));
        if (statusCode >= 500 && statusCode < 600) {
            LOG.warn("manageIOException", e);
            gameWebsite503.throwException(message, command, lg);
        }
        else {
            LOG.error("manageIOException", e);
            BasicDiscordException.UNKNOWN_ERROR.throwException(message, command, lg);
        }
    } else if (e instanceof UnknownHostException || e instanceof SocketTimeoutException) {
        gameWebsite503.throwException(message, command, lg);
    } else if (e instanceof FileNotFoundException
            || e instanceof HttpStatusException
            || e instanceof NoRouteToHostException){
        notFound.throwException(message, command, lg);
    }
    else {
        LOG.error("manageIOException", e);
        BasicDiscordException.UNKNOWN_ERROR.throwException(message, command, lg);
    }
}
 
Example 8
Source Project: flink-learning   Source File: RetryRequestFailureHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onFailure(ActionRequest actionRequest, Throwable throwable, int i, RequestIndexer requestIndexer) throws Throwable {
    if (ExceptionUtils.findThrowable(throwable, EsRejectedExecutionException.class).isPresent()) {
        requestIndexer.add(new ActionRequest[]{actionRequest});
    } else {
        if (ExceptionUtils.findThrowable(throwable, SocketTimeoutException.class).isPresent()) {
            return;
        } else {
            Optional<IOException> exp = ExceptionUtils.findThrowable(throwable, IOException.class);
            if (exp.isPresent()) {
                IOException ioExp = exp.get();
                if (ioExp != null && ioExp.getMessage() != null && ioExp.getMessage().contains("max retry timeout")) {
                    log.error(ioExp.getMessage());
                    return;
                }
            }
        }
        throw throwable;
    }
}
 
Example 9
Source Project: buck   Source File: MoreThrowables.java    License: Apache License 2.0 6 votes vote down vote up
/** 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);
  }
}
 
Example 10
Source Project: L.TileLayer.Cordova   Source File: SpdyStream.java    License: 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 11
Source Project: hadoop   Source File: ExceptionDiags.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Take an IOException and a URI, wrap it where possible with
 * something that includes the URI
 *
 * @param dest target URI
 * @param operation operation
 * @param exception the caught exception.
 * @return an exception to throw
 */
public static IOException wrapException(final String dest,
                                        final String operation,
                                        final IOException exception) {
  String action = operation + " " + dest;
  String xref = null;

  if (exception instanceof ConnectException) {
    xref = "ConnectionRefused";
  } else if (exception instanceof UnknownHostException) {
    xref = "UnknownHost";
  } else if (exception instanceof SocketTimeoutException) {
    xref = "SocketTimeout";
  } else if (exception instanceof NoRouteToHostException) {
    xref = "NoRouteToHost";
  }
  String msg = action
               + " failed on exception: "
               + exception;
  if (xref != null) {
     msg = msg + ";" + see(xref);
  }
  return wrapWithMessage(exception, msg);
}
 
Example 12
Source Project: file-downloader   Source File: HttpFailReason.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void onInitTypeWithOriginalThrowable(Throwable throwable) {
    super.onInitTypeWithOriginalThrowable(throwable);

    if (throwable == null) {
        return;
    }

    if (throwable instanceof SocketTimeoutException) {
        setType(TYPE_NETWORK_TIMEOUT);
    } else if (throwable instanceof ConnectException || throwable instanceof UnknownHostException) {
        setType(TYPE_NETWORK_DENIED);
    } else if (throwable instanceof SocketException) {
        setType(TYPE_NETWORK_DENIED);
    }
}
 
Example 13
/**
    * Allows to call a remote URL in POST mode and pass parameters.
    *
    * @param url           the URL to call
    * @param parametersMap the parameters, empty if none. (Cannot be null).
    * @return the value returned by the call
    *
    * @throws IOException                  if an IOException occurs
    * @throws ProtocolException            if a ProtocolException occurs
    * @throws SocketTimeoutException       if a if a ProtocolException occurs
    *                                      occurs
    * @throws UnsupportedEncodingException if a if a ProtocolException occurs
    *                                      occurs
    */
   public String callWithPost(URL url, Map<String, String> parametersMap)
    throws IOException, ProtocolException, SocketTimeoutException, UnsupportedEncodingException {

if (url == null) {
    throw new NullPointerException("url is null!");
}

if (parametersMap == null) {
    throw new NullPointerException("parametersMap is null!");
}

String result = null;
try (InputStream in = callWithPostReturnStream(url, parametersMap);) {
    if (in != null) {
	ByteArrayOutputStream out = new ByteArrayOutputStream();
	IOUtils.copy(in, out);

	result = out.toString("UTF-8");
	trace("result :" + result + ":");
    }
}
return result;
   }
 
Example 14
Source Project: java   Source File: GenericKubernetesApiForCoreApiTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testReadTimeoutShouldThrowException() {
  ApiClient apiClient = new ClientBuilder().setBasePath("http://localhost:" + 8181).build();
  apiClient.setHttpClient(
      apiClient
          .getHttpClient()
          .newBuilder()
          .readTimeout(1, TimeUnit.MILLISECONDS) // timeout everytime
          .build());
  podClient =
      new GenericKubernetesApi<>(V1Pod.class, V1PodList.class, "", "v1", "pods", apiClient);
  try {
    KubernetesApiResponse<V1Pod> response = podClient.get("foo", "test");
  } catch (Throwable t) {
    assertTrue(t.getCause() instanceof SocketTimeoutException);
    return;
  }
  fail("no exception happened");
}
 
Example 15
Source Project: flink-learning   Source File: RetryRequestFailureHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onFailure(ActionRequest actionRequest, Throwable throwable, int i, RequestIndexer requestIndexer) throws Throwable {
    if (ExceptionUtils.findThrowable(throwable, EsRejectedExecutionException.class).isPresent()) {
        requestIndexer.add(new ActionRequest[]{actionRequest});
    } else {
        if (ExceptionUtils.findThrowable(throwable, SocketTimeoutException.class).isPresent()) {
            return;
        } else {
            Optional<IOException> exp = ExceptionUtils.findThrowable(throwable, IOException.class);
            if (exp.isPresent()) {
                IOException ioExp = exp.get();
                if (ioExp != null && ioExp.getMessage() != null && ioExp.getMessage().contains("max retry timeout")) {
                    log.error(ioExp.getMessage());
                    return;
                }
            }
        }
        throw throwable;
    }
}
 
Example 16
Source Project: DavidWebb   Source File: TestWebb_Timeouts.java    License: MIT License 5 votes vote down vote up
public void testReadTimeoutGlobal() throws Exception {
    // the REST api delivers after 500 millis
    Webb.setReadTimeout(800);
    webb.get("/read-timeout").ensureSuccess().asString();

    try {
        Webb.setReadTimeout(100);
        webb.get("/read-timeout").asString();
    } catch (WebbException e) {
        assertEquals(SocketTimeoutException.class, e.getCause().getClass());
    } finally {
        Webb.setReadTimeout(180000);
    }
}
 
Example 17
Source Project: TorrentEngine   Source File: FileUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static String
readInputStreamAsStringWithTruncation(
	InputStream 	is,
	int				size_limit )

	throws IOException
{
	StringBuffer result = new StringBuffer(1024);

	byte[] buffer = new byte[64*1024];

	try{
		while (true) {

			int len = is.read(buffer);

			if (len <= 0) {

				break;
			}

			result.append(new String(buffer, 0, len, "ISO-8859-1"));

			if (size_limit >= 0 && result.length() > size_limit) {

				result.setLength(size_limit);

				break;
			}
		}
	}catch( SocketTimeoutException e ){
	}

	return (result.toString());
}
 
Example 18
Source Project: hadoop   Source File: TestDFSClientRetries.java    License: Apache License 2.0 5 votes vote down vote up
/** Test that timeout occurs when DN does not respond to RPC.
 * Start up a server and ask it to sleep for n seconds. Make an
 * RPC to the server and set rpcTimeout to less than n and ensure
 * that socketTimeoutException is obtained
 */
@Test
public void testClientDNProtocolTimeout() throws IOException {
  final Server server = new TestServer(1, true);
  server.start();

  final InetSocketAddress addr = NetUtils.getConnectAddress(server);
  DatanodeID fakeDnId = DFSTestUtil.getLocalDatanodeID(addr.getPort());
  
  ExtendedBlock b = new ExtendedBlock("fake-pool", new Block(12345L));
  LocatedBlock fakeBlock = new LocatedBlock(b, new DatanodeInfo[0]);

  ClientDatanodeProtocol proxy = null;

  try {
    proxy = DFSUtil.createClientDatanodeProtocolProxy(
        fakeDnId, conf, 500, false, fakeBlock);

    proxy.getReplicaVisibleLength(new ExtendedBlock("bpid", 1));
    fail ("Did not get expected exception: SocketTimeoutException");
  } catch (SocketTimeoutException e) {
    LOG.info("Got the expected Exception: SocketTimeoutException");
  } finally {
    if (proxy != null) {
      RPC.stopProxy(proxy);
    }
    server.stop();
  }
}
 
Example 19
@Test
public void testRetryWithSocketTimeout() {
  Exception target = new SocketTimeoutException("Read timed out");
  Exception root = new Exception(target);
  boolean retriable = retryHandler.isRetriableException(root, false);
  Assert.assertTrue(retriable);
}
 
Example 20
@Override
public int read(final byte[] b, final int off, final int len) throws IOException {
    if (bufferedByte != null) {
        final byte retVal = bufferedByte;
        bufferedByte = null;
        b[off] = retVal;
        return 1;
    }

    final ByteBuffer buffer = ByteBuffer.wrap(b, off, len);

    final long maxTime = System.currentTimeMillis() + timeoutMillis;
    int bytesRead;
    do {
        bytesRead = channel.read(buffer);
        if (bytesRead == 0) {
            if (System.currentTimeMillis() > maxTime) {
                throw new SocketTimeoutException("Timed out reading from socket");
            }
            try {
                TimeUnit.NANOSECONDS.sleep(CHANNEL_EMPTY_WAIT_NANOS);
            } catch (InterruptedException e) {
                close();
                Thread.currentThread().interrupt(); // set the interrupt status
                throw new ClosedByInterruptException(); // simulate an interrupted blocked read operation
            }
        }
    } while (bytesRead == 0);

    return bytesRead;
}
 
Example 21
Source Project: etcd4j   Source File: EtcdTimeoutTest.java    License: MIT License 5 votes vote down vote up
private void validateTestResult(EtcdClientException e, long start) {
    long cost = System.currentTimeMillis() - start;
    Assert.assertTrue(cost >= TIMEOUT && cost <= MAX_ALLOWED_TIMEOUT);
    Exception cause = (Exception) e.getCause();
    Assert.assertTrue(cause instanceof ExecutionException);
    Assert.assertTrue(cause.getCause() instanceof SocketTimeoutException);
}
 
Example 22
Source Project: jdk8u-dev-jdk   Source File: SelectFdsLimit.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String [] args) throws IOException, FileNotFoundException {

        //The bug 8021820 is a Mac specific and because of that test will pass on all
        //other platforms
        if (!System.getProperty("os.name").contains("OS X")) {
           return;
        }

        //Create test directory with test files
        prepareTestEnv();

        //Consume FD ids for this java process to overflow the 1024
        openFiles(FDTOOPEN,new File(TESTFILE));

        //Wait for incoming connection and make the select() used in java.net
        //classes fail the limitation on FDSET_SIZE
        ServerSocket socket = new ServerSocket(0);

        //Set the minimal timeout, no one is
        //going to connect to this server socket
        socket.setSoTimeout(1);

        // The accept() call will throw SocketException if the
        // select() has failed due to limitation on fds size,
        // indicating test failure. A SocketTimeoutException
        // is expected, so it is caught and ignored, and the test
        // passes.
        try {
           socket.accept();
        } catch (SocketTimeoutException e) { }
    }
 
Example 23
Source Project: presto   Source File: TestStaticMetastoreLocator.java    License: Apache License 2.0 5 votes vote down vote up
private static ThriftMetastoreClient createFakeMetastoreClient()
{
    return new MockThriftMetastoreClient()
    {
        @Override
        public Table getTable(String dbName, String tableName)
                throws TException
        {
            throw new TException(new SocketTimeoutException("Read timeout"));
        }
    };
}
 
Example 24
Source Project: RDFS   Source File: Client.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Take an IOException and the address we were trying to connect to
 * and return an IOException with the input exception as the cause.
 * The new exception provides the stack trace of the place where 
 * the exception is thrown and some extra diagnostics information.
 * If the exception is ConnectException or SocketTimeoutException, 
 * return a new one of the same type; Otherwise return an IOException.
 * 
 * @param addr target address
 * @param exception the relevant exception
 * @return an exception to throw
 */
private IOException wrapException(InetSocketAddress addr,
                                       IOException exception) {
  if (exception instanceof ConnectException) {
    //connection refused; include the host:port in the error
    return (ConnectException)new ConnectException(
         "Call to " + addr + " failed on connection exception: " + exception)
                  .initCause(exception);
  } else if (exception instanceof SocketTimeoutException) {
    return (SocketTimeoutException)new SocketTimeoutException(
         "Call to " + addr + " failed on socket timeout exception: "
                    + exception).initCause(exception);
  } else if (exception instanceof NoRouteToHostException) {
    return (NoRouteToHostException)new NoRouteToHostException(
         "Call to " + addr + " failed on NoRouteToHostException exception: "
                    + exception).initCause(exception);
  } else if (exception instanceof PortUnreachableException) {
    return (PortUnreachableException)new PortUnreachableException(
         "Call to " + addr + " failed on PortUnreachableException exception: "
                    + exception).initCause(exception);
  } else {
    return (IOException)new IOException(
         "Call to " + addr + " failed on local exception: " + exception)
                               .initCause(exception);

  }
}
 
Example 25
Source Project: game-server   Source File: AcceptorTest.java    License: MIT License 5 votes vote down vote up
public void testUDP() throws Exception {
	DatagramSocket client = new DatagramSocket();
	client.connect(new InetSocketAddress("127.0.0.1", port));
	client.setSoTimeout(500);

	byte[] writeBuf = new byte[16];
	byte[] readBuf = new byte[writeBuf.length];
	DatagramPacket wp = new DatagramPacket(writeBuf, writeBuf.length);
	DatagramPacket rp = new DatagramPacket(readBuf, readBuf.length);

	for (int i = 0; i < 10; i++) {
		fillWriteBuffer(writeBuf, i);
		client.send(wp);

		client.receive(rp);
		assertEquals(writeBuf.length, rp.getLength());
		assertTrue(Arrays.equals(writeBuf, readBuf));
	}

	try {
		client.receive(rp);
		fail("Unexpected incoming data.");
	} catch (SocketTimeoutException e) {
	}

	client.close();
}
 
Example 26
Source Project: components   Source File: GoogleDriveBaseTestIT.java    License: Apache License 2.0 5 votes vote down vote up
public Statement apply(final Statement base, Description desc) {
    return new Statement() {

        public void evaluate() throws Throwable {
            try {
                base.evaluate();
            } catch (SocketTimeoutException ex) {
                LOG.error("{} caught during test execution.", ex.getMessage());
                // If called with an expression evaluating to false, the test will halt and be ignored.
                Assume.assumeTrue(false);
            }
        }
    };
}
 
Example 27
Source Project: neoscada   Source File: StreamIoHandler.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Handles read timeout.
 */
@Override
public void sessionIdle(IoSession session, IdleStatus status) {
    if (status == IdleStatus.READER_IDLE) {
        throw new StreamIoException(new SocketTimeoutException("Read timeout"));
    }
}
 
Example 28
Source Project: openjdk-8   Source File: LdapTimeoutTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
void simpleAuthConnectTest(Hashtable env) {
    InitialContext ctx = null;
    ScheduledFuture killer = killSwitch();
    long start = System.nanoTime();
    try {
        ctx = new InitialDirContext(env);
        // shouldn't reach here
        System.err.println("Fail: InitialDirContext succeeded");
        fail();
    } catch (NamingException e) {
        long end = System.nanoTime();
        if (e.getCause() instanceof SocketTimeoutException) {
            if (TimeUnit.NANOSECONDS.toMillis(end - start) < 2900) {
                pass();
            } else {
                System.err.println("Fail: Waited too long");
                fail();
            }
        } else if (e.getCause() instanceof InterruptedIOException) {
            Thread.interrupted();
            fail();
        } else {
            fail();
        }
    } finally {
        if (!shutItDown(killer, ctx)) fail();
    }
}
 
Example 29
Source Project: Rx-Retrofit   Source File: FactoryException.java    License: MIT License 5 votes vote down vote up
/**
 * 解析异常
 *
 * @param e
 * @return
 */
public static ApiException analysisExcetpion(Throwable e) {
    ApiException apiException = new ApiException(e);
    if (e instanceof HttpException) {
         /*网络异常*/
        apiException.setCode(CodeException.HTTP_ERROR);
        apiException.setDisplayMessage(HttpException_MSG);
    } else if (e instanceof HttpTimeException) {
         /*自定义运行时异常*/
        HttpTimeException exception = (HttpTimeException) e;
        apiException.setCode(CodeException.RUNTIME_ERROR);
        apiException.setDisplayMessage(exception.getMessage());
    } else if (e instanceof ConnectException||e instanceof SocketTimeoutException) {
         /*链接异常*/
        apiException.setCode(CodeException.HTTP_ERROR);
        apiException.setDisplayMessage(ConnectException_MSG);
    } else if ( e instanceof JSONException || e instanceof ParseException) {
         /*json解析异常*/
        apiException.setCode(CodeException.JSON_ERROR);
        apiException.setDisplayMessage(JSONException_MSG);
    }else if (e instanceof UnknownHostException){
        /*无法解析该域名异常*/
        apiException.setCode(CodeException.UNKOWNHOST_ERROR);
        apiException.setDisplayMessage(UnknownHostException_MSG);
    } else {
        /*未知异常*/
        apiException.setCode(CodeException.UNKNOWN_ERROR);
        apiException.setDisplayMessage(e.getMessage());
    }
    return apiException;
}
 
Example 30
Source Project: bcm-android   Source File: BaseHttp.java    License: GNU General Public License v3.0 5 votes vote down vote up
protected void sendFailResultCallback(final Call call, final Exception e, final Callback callback, final long id) {
    if (callback == null) return;

    Runnable r = () -> {
        if (e instanceof ConnectException || e instanceof SocketTimeoutException) {
            callback.onError(call, new ConnectionException(e), id);
        } else {
            callback.onError(call, e, id);
        }
    };

    switch (callback.callInThreadMode()) {
        case Callback.THREAD_MAIN: {
            mPlatform.execute(r);
            break;
        }
        case Callback.THREAD_SYNC: {
            getDelivery().execute(r);
            break;
        }
        case Callback.THREAD_CURRENT: {
            r.run();
            break;
        }
        default:
            break;
    }
}