java.net.SocketTimeoutException Java Examples

The following examples show how to use java.net.SocketTimeoutException. 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: SimpleHttpClient.java    From aceql-http with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
    * 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 #2
Source File: SpdyStream.java    From cordova-amazon-fireos with 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 #3
Source File: SpdyStream.java    From L.TileLayer.Cordova 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 #4
Source File: MoreThrowables.java    From buck with 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 #5
Source File: GenericKubernetesApiForCoreApiTest.java    From java with 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 #6
Source File: RetryRequestFailureHandler.java    From flink-learning with 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 #7
Source File: RmiProtocol.java    From dubbox-hystrix with 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 #8
Source File: RetryRequestFailureHandler.java    From flink-learning with 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 File: ExceptionDiags.java    From hadoop with 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 #10
Source File: ExceptionManager.java    From KaellyBot with 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 #11
Source File: AprEndpoint.java    From Tomcat8-Source-Read with 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 #12
Source File: HttpFailReason.java    From file-downloader with 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
Source File: TestRemoteInstanceRequestClient.java    From exhibitor with 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 #14
Source File: ExceptionDiags.java    From sahara-extra with 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 #15
Source File: BackupNode.java    From big-c with 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 #16
Source File: RpcStreamConnectionTest.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
@Test(expected=InvocationTargetException.class)
public void calculatePreambleBytesAndSendtoDownstream_with_SocketTimeoutException()
		throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, IOException {
	Method calculatePreambleBytesAndSendtoDownstream = getPrivateMethod(RpcStreamConnection.class,
			"calculatePreambleBytesAndSendtoDownstream", RpcStreamConnection.RpcPacketSupplier.class);

	RpcStreamConnection.RpcPacketSupplier supplier = createMockRpcPacketSupplier();
	doThrow(SocketTimeoutException.class).when(topOutputStream).write(any(byte[].class), eq(0), anyInt());
	calculatePreambleBytesAndSendtoDownstream.invoke(mockConnection, supplier);
}
 
Example #17
Source File: JdpTestCase.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public void run() throws Exception {
    log.fine("Test started.");
    log.fine("Listening for multicast packets at " + connection.address.getHostAddress()
            + ":" + String.valueOf(connection.port));
    log.fine(initialLogMessage());
    log.fine("Pause in between packets is: " + connection.pauseInSeconds + " seconds.");

    startTime = System.currentTimeMillis();
    timeOut = connection.pauseInSeconds * TIME_OUT_FACTOR;
    log.fine("Timeout set to " + String.valueOf(timeOut) + " seconds.");

    MulticastSocket socket = connection.connectWithTimeout(timeOut * 1000);

    byte[] buffer = new byte[BUFFER_LENGTH];
    DatagramPacket datagram = new DatagramPacket(buffer, buffer.length);

    do {
        try {
            socket.receive(datagram);
            onReceived(extractUDPpayload(datagram));
        } catch (SocketTimeoutException e) {
            onSocketTimeOut(e);
        }

        if (hasTestLivedLongEnough()) {
            shutdown();
        }

    } while (shouldContinue());
    log.fine("Test ended successfully.");
}
 
Example #18
Source File: LdapTimeoutTest.java    From openjdk-8 with 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 #19
Source File: DeadSSLLdapTimeoutTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public void handleNamingException(NamingException e, long start, long end) {
    if (e.getCause() instanceof SocketTimeoutException) {
        // SSL connect will timeout via readReply using
        // SocketTimeoutException
        e.printStackTrace();
        pass();
    } else if (e.getCause() instanceof SSLHandshakeException
            && e.getCause().getCause() instanceof EOFException) {
        // test seems to be failing intermittently on some
        // platforms.
        pass();
    } else {
        fail(e);
    }
}
 
Example #20
Source File: Multicast.java    From Bitcoin with Apache License 2.0 5 votes vote down vote up
/**
 * Blocking call
 */
public static boolean recvData(MulticastSocket s, byte[] buffer) throws IOException {
    s.setSoTimeout(100);
    // Create a DatagramPacket and do a receive
    final DatagramPacket pack = new DatagramPacket(buffer, buffer.length);
    try {
        s.receive(pack);
    } catch (SocketTimeoutException e) {
        return false;
    }
    // We have finished receiving data
    return true;
}
 
Example #21
Source File: SocketChannelOutputStream.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void write(final byte[] b, final int off, final int len) throws IOException {
    final ByteBuffer buffer = ByteBuffer.wrap(b, off, len);

    final int timeoutMillis = this.timeout;
    long maxTime = System.currentTimeMillis() + timeoutMillis;
    int bytesWritten;

    long sleepNanos = 1L;
    while (buffer.hasRemaining()) {
        bytesWritten = channel.write(buffer);
        if (bytesWritten == 0) {
            if (System.currentTimeMillis() > maxTime) {
                throw new SocketTimeoutException("Timed out writing to socket");
            }

            try {
                TimeUnit.NANOSECONDS.sleep(sleepNanos);
            } catch (InterruptedException e) {
                close();
                Thread.currentThread().interrupt(); // set the interrupt status
                throw new ClosedByInterruptException(); // simulate an interrupted blocked write operation
            }

            sleepNanos = Math.min(sleepNanos * 2, CHANNEL_FULL_WAIT_NANOS);
        } else {
            maxTime = System.currentTimeMillis() + timeoutMillis;
        }
    }
}
 
Example #22
Source File: LdapTimeoutTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public void handleNamingException(NamingException e, long start, long end) {
    if (e.getCause() instanceof SocketTimeoutException) {
        // SSL connect will timeout via readReply using
        // SocketTimeoutException
        pass();
    } else {
        fail();
    }
}
 
Example #23
Source File: RdeReportActionTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testRunWithLock_socketTimeout_doesRetry() throws Exception {
  when(httpResponse.getResponseCode()).thenReturn(SC_OK);
  when(httpResponse.getContent()).thenReturn(IIRDEA_GOOD_XML.read());
  when(urlFetchService.fetch(request.capture()))
      .thenThrow(new SocketTimeoutException())
      .thenReturn(httpResponse);
  createAction().runWithLock(loadRdeReportCursor());
  assertThat(response.getStatus()).isEqualTo(200);
  assertThat(response.getContentType()).isEqualTo(PLAIN_TEXT_UTF_8);
  assertThat(response.getPayload()).isEqualTo("OK test 2006-06-06T00:00:00.000Z\n");
}
 
Example #24
Source File: JdpOnTestCase.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * The socket should not timeout.
 * It is set to wait for 10 times the defined pause between Jdp packet. See JdpOnTestCase.TIME_OUT_FACTOR.
 */
@Override
protected void onSocketTimeOut(SocketTimeoutException e) throws Exception {
    String message = "Timed out waiting for JDP packet. Should arrive within " +
            connection.pauseInSeconds + " seconds, but waited for " +
            timeOut + " seconds.";
    log.severe(message);
    throw new Exception(message, e);
}
 
Example #25
Source File: SelectFdsLimit.java    From openjdk-jdk8u-backup with 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 #26
Source File: KdcComm.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public byte[] run() throws IOException, KrbException {

            byte[] ibuf = null;

            for (int i=1; i <= retries; i++) {
                String proto = useTCP?"TCP":"UDP";
                try (NetClient kdcClient = NetClient.getInstance(
                        proto, kdc, port, timeout)) {
                    if (DEBUG) {
                        System.out.println(">>> KDCCommunication: kdc=" + kdc
                            + " " + proto + ":"
                            +  port +  ", timeout="
                            + timeout
                            + ",Attempt =" + i
                            + ", #bytes=" + obuf.length);
                    }
                    try {
                        /*
                        * Send the data to the kdc.
                        */
                        kdcClient.send(obuf);
                        /*
                        * And get a response.
                        */
                        ibuf = kdcClient.receive();
                        break;
                    } catch (SocketTimeoutException se) {
                        if (DEBUG) {
                            System.out.println ("SocketTimeOutException with " +
                                                "attempt: " + i);
                        }
                        if (i == retries) {
                            ibuf = null;
                            throw se;
                        }
                    }
                }
            }
            return ibuf;
        }
 
Example #27
Source File: SocketChannelInputStream.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void waitForReady() throws IOException {
    int readyCount = readSelector.select(timeoutMillis);
    if (readyCount < 1) {
        if (interrupted) {
            throw new TransmissionDisabledException();
        }

        throw new SocketTimeoutException("Timed out reading from socket");
    }

    final Set<SelectionKey> selectedKeys = readSelector.selectedKeys();
    selectedKeys.clear(); // clear the selected keys so that the Selector will be able to add them back to the ready set next time they are ready.
}
 
Example #28
Source File: OAuth2Utils.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
static boolean runningOnComputeEngine(HttpTransport transport,
    SystemEnvironmentProvider environment) {
  // If the environment has requested that we do no GCE checks, return immediately.
  if (Boolean.parseBoolean(environment.getEnv("NO_GCE_CHECK"))) {
    return false;
  }

  GenericUrl tokenUrl = new GenericUrl(getMetadataServerUrl(environment));
  for (int i = 1; i <= MAX_COMPUTE_PING_TRIES; ++i) {
    try {
      HttpRequest request = transport.createRequestFactory().buildGetRequest(tokenUrl);
      request.setConnectTimeout(COMPUTE_PING_CONNECTION_TIMEOUT_MS);
      request.getHeaders().set("Metadata-Flavor", "Google");
      HttpResponse response = request.execute();
      try {
        HttpHeaders headers = response.getHeaders();
        return headersContainValue(headers, "Metadata-Flavor", "Google");
      } finally {
        response.disconnect();
      }
    } catch (SocketTimeoutException expected) {
      // Ignore logging timeouts which is the expected failure mode in non GCE environments.
    } catch (IOException e) {
      LOGGER.log(
          Level.WARNING,
          "Failed to detect whether we are running on Google Compute Engine.",
          e);
    }
  }
  return false;
}
 
Example #29
Source File: TestWebHdfsTimeouts.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * After a redirect, expect read timeout accessing the redirect location,
 * because the bogus server never sends a reply.
 */
@Test(timeout=TEST_TIMEOUT)
public void testRedirectReadTimeout() throws Exception {
  startSingleTemporaryRedirectResponseThread(false);
  try {
    fs.getFileChecksum(new Path("/file"));
    fail("expected timeout");
  } catch (SocketTimeoutException e) {
    assertEquals("Read timed out", e.getMessage());
  }
}
 
Example #30
Source File: BaseHttp.java    From bcm-android with 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;
    }
}