java.net.NoRouteToHostException Java Examples

The following examples show how to use java.net.NoRouteToHostException. 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: 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 #2
Source File: Errors.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
static void throwConnectException(String method, NativeConnectException refusedCause, int err)
        throws IOException {
    if (err == refusedCause.expectedErr()) {
        throw refusedCause;
    }
    if (err == ERROR_EALREADY_NEGATIVE) {
        throw new ConnectionPendingException();
    }
    if (err == ERROR_ENETUNREACH_NEGATIVE) {
        throw new NoRouteToHostException();
    }
    if (err == ERROR_EISCONN_NEGATIVE) {
        throw new AlreadyConnectedException();
    }
    if (err == ERRNO_ENOENT_NEGATIVE) {
        throw new FileNotFoundException();
    }
    throw new ConnectException(method + "(..) failed: " + ERRORS[-err]);
}
 
Example #3
Source File: HttpUtils.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
public static URL handleRedirectRequest(LocalProxyConfig config, URL url, HashMap<String, String> headers) throws IOException {
    int redirectCount = 0;
    while (redirectCount++ < MAX_REDIRECT) {
        HttpURLConnection connection = makeConnection(config, url, headers);
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_MULT_CHOICE
                || responseCode == HttpURLConnection.HTTP_MOVED_PERM
                || responseCode == HttpURLConnection.HTTP_MOVED_TEMP
                || responseCode == HttpURLConnection.HTTP_SEE_OTHER
                && (responseCode == 307 /* HTTP_TEMP_REDIRECT */
                || responseCode == 308 /* HTTP_PERM_REDIRECT */)) {
            String location = connection.getHeaderField("Location");
            connection.disconnect();
            url = handleRedirect(url, location);
            return handleRedirectRequest(config, url, headers);
        } else {
            return url;
        }
    }
    throw new NoRouteToHostException("Too many redirects: " + redirectCount);
}
 
Example #4
Source File: WebExceptionUtility.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
private static boolean isWebExceptionRetriableInternal(Exception ex) {
    if (ex instanceof PoolExhaustedException) {
        return true;
    }

    IOException webEx = Utils.as(ex, IOException.class);
    if (webEx == null) {
        return false;
    }

    // any network failure for which we are certain the request hasn't reached the service endpoint.
    if (webEx instanceof ConnectException ||
            webEx instanceof UnknownHostException ||
            webEx instanceof SSLHandshakeException ||
            webEx instanceof NoRouteToHostException ||
            webEx instanceof SSLPeerUnverifiedException) {
        return true;
    }

    return false;
}
 
Example #5
Source File: TestLog4Json.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
public void testException() throws Throwable {
  Exception e =
      new NoRouteToHostException("that box caught fire 3 years ago");
  ThrowableInformation ti = new ThrowableInformation(e);
  Log4Json l4j = new Log4Json();
  long timeStamp = Time.now();
  String outcome = l4j.toJson(new StringWriter(),
      "testException",
      timeStamp,
      "INFO",
      "quoted\"",
      "new line\n and {}",
      ti)
      .toString();
  println("testException", outcome);
}
 
Example #6
Source File: BugzillaExecutor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static String getNotFoundError(CoreException ce) {
    IStatus status = ce.getStatus();
    Throwable t = status.getException();
    if(t instanceof UnknownHostException ||
       // XXX maybe a different msg ?     
       t instanceof SocketTimeoutException || 
       t instanceof NoRouteToHostException ||
       t instanceof ConnectException) 
    {
        Bugzilla.LOG.log(Level.FINER, null, t);
        return NbBundle.getMessage(BugzillaExecutor.class, "MSG_HOST_NOT_FOUND");                   // NOI18N
    }
    String msg = getMessage(ce);
    if(msg != null) {
        msg = msg.trim().toLowerCase();
        if(HTTP_ERROR_NOT_FOUND.equals(msg)) {
            Bugzilla.LOG.log(Level.FINER, "returned error message [{0}]", msg);                     // NOI18N
            return NbBundle.getMessage(BugzillaExecutor.class, "MSG_HOST_NOT_FOUND");               // NOI18N
        }
    }
    return null;
}
 
Example #7
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 #8
Source File: TestLog4Json.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testException() throws Throwable {
  Exception e =
      new NoRouteToHostException("that box caught fire 3 years ago");
  ThrowableInformation ti = new ThrowableInformation(e);
  Log4Json l4j = new Log4Json();
  long timeStamp = Time.now();
  String outcome = l4j.toJson(new StringWriter(),
      "testException",
      timeStamp,
      "INFO",
      "quoted\"",
      "new line\n and {}",
      ti)
      .toString();
  println("testException", outcome);
}
 
Example #9
Source File: ExceptionDiags.java    From big-c 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: ExceptionManager.java    From KaellyBot with GNU General Public License v3.0 6 votes vote down vote up
public static void manageSilentlyIOException(Exception e){
    Reporter.report(e);
    // 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("manageSilentlyIOException", e);
        else
            LOG.error("manageSilentlyIOException", e);
    } else if (e instanceof UnknownHostException
            || e instanceof SocketTimeoutException
            || e instanceof FileNotFoundException
            || e instanceof HttpStatusException
            || e instanceof NoRouteToHostException)
        LOG.warn("manageSilentlyIOException", e);
    else
        LOG.error("manageSilentlyIOException", e);

}
 
Example #12
Source File: ProxyServer.java    From j2ssh-maverick with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void handleException(IOException ioe){
   //If we couldn't read the request, return;
   if(msg == null) return;
   //If have been aborted by other thread
   if(mode == ABORT_MODE) return;
   //If the request was successfully completed, but exception happened later
   if(mode == PIPE_MODE) return;

   int error_code = Proxy.SOCKS_FAILURE;

   if(ioe instanceof SocksException)
       error_code = ((SocksException)ioe).errCode;
   else if(ioe instanceof NoRouteToHostException)
       error_code = Proxy.SOCKS_HOST_UNREACHABLE;
   else if(ioe instanceof ConnectException)
       error_code = Proxy.SOCKS_CONNECTION_REFUSED;
   else if(ioe instanceof InterruptedIOException)
       error_code = Proxy.SOCKS_TTL_EXPIRE;

   if(error_code > Proxy.SOCKS_ADDR_NOT_SUPPORTED || error_code < 0){
       error_code = Proxy.SOCKS_FAILURE; 
   }

   sendErrorMessage(error_code);
}
 
Example #13
Source File: GobblinHttpMethodRetryHandler.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@Override
public boolean retryMethod(final HttpMethod method, final IOException exception, int executionCount) {
  if (method == null) {
    throw new IllegalArgumentException("HTTP method may not be null");
  }
  if (exception == null) {
    throw new IllegalArgumentException("Exception parameter may not be null");
  }
  if (executionCount > super.getRetryCount()) {
    // Do not retry if over max retry count
    return false;
  }
  //Override the behavior of DefaultHttpMethodRetryHandler to retry in case of UnknownHostException
  // and NoRouteToHostException.
  if (exception instanceof UnknownHostException || exception instanceof NoRouteToHostException) {
    return true;
  }
  return super.retryMethod(method, exception, executionCount);
}
 
Example #14
Source File: QEmuProcess.java    From qemu-java with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @throws NoRouteToHostException if the process is terminated.
 * @throws UnknownServiceException if the process has no known monitor address.
 */
@Nonnull
public QApiConnection getConnection() throws IOException {
    if (monitor == null)
        throw new UnknownServiceException("No monitor address known.");

    try {
        // If this succeeds, then we have exited.
        int exitValue = process.exitValue();
        connection = null;
        throw new NoRouteToHostException("Process terminated with exit code " + exitValue);
    } catch (IllegalThreadStateException e) {
    }

    synchronized (lock) {
        if (connection != null)
            return connection;
        connection = new QApiConnection(monitor);
        return connection;
    }
}
 
Example #15
Source File: ErrorHandler.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * This method handles a connection error that was caused while connecting the gateway to the backend.
 *
 * @param error the connection error to be handled
 * @return a new ConnectorException
 */
public static ConnectorException handleConnectionError(Throwable error) {
    ConnectorException ce = null;
    if (error instanceof UnknownHostException || error instanceof ConnectException || error instanceof NoRouteToHostException) {
        ce = new ConnectorException("Unable to connect to backend", error); //$NON-NLS-1$
        ce.setStatusCode(502); // BAD GATEWAY
    } else if (error instanceof InterruptedIOException || error instanceof java.util.concurrent.TimeoutException) {
        ce = new ConnectorException("Connection to backend terminated" + error.getMessage(), error); //$NON-NLS-1$
        ce.setStatusCode(504); // GATEWAY TIMEOUT

    }
    if (ce != null) {
        return ce;
    } else {
        return new ConnectorException(error.getMessage(), error);
    }
}
 
Example #16
Source File: HPipelineExceptionFactory.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public boolean canInfinitelyRetry(Throwable t){
    t=Throwables.getRootCause(t);
    t=processPipelineException(t);
    if(t instanceof NotServingPartitionException
            || t instanceof NoServerForRegionException
            || t instanceof WrongPartitionException
            || t instanceof PipelineTooBusy
            || t instanceof RegionBusyException
            || t instanceof NoRouteToHostException
            || t instanceof org.apache.hadoop.hbase.ipc.FailedServerException
            || t instanceof FailedServerException
            || t instanceof ServerNotRunningYetException
            || t instanceof ConnectTimeoutException
            || t instanceof IndexNotSetUpException) return true;
    return false;
}
 
Example #17
Source File: RemoteSdkException.java    From consulo with Apache License 2.0 6 votes vote down vote up
public RemoteSdkException(String s, Throwable throwable) {
  super(s, throwable);

  myAuthFailed = false;
  Throwable t = throwable;
  while (t != null) {
    if (t instanceof NoRouteToHostException) {
      myCause = t;
      myNoRouteToHost = true;
      return;
    }

    t = t.getCause();
  }
  myNoRouteToHost = false;
  myCause = throwable;
}
 
Example #18
Source File: ChaosPluginTest.java    From riptide with MIT License 5 votes vote down vote up
@Test
void shouldInjectException() {
    when(exceptionProbability.test()).thenReturn(true);

    driver.addExpectation(onRequestTo("/foo"), giveEmptyResponse());

    final CompletableFuture<ClientHttpResponse> future = unit.get("/foo")
            .call(pass());

    final CompletionException exception = assertThrows(CompletionException.class, future::join);

    assertThat(exception.getCause(), anyOf(
            instanceOf(ConnectException.class),
            instanceOf(NoRouteToHostException.class)));
}
 
Example #19
Source File: RemoteSystemClient.java    From ghwatch with Apache License 2.0 5 votes vote down vote up
public static Response<String> deleteToURL(Context context, GHCredentials apiCredentials, String url, Map<String, String> headers)
        throws URISyntaxException, IOException, AuthenticationException {
  if (!Utils.isInternetConnectionAvailable(context))
    throw new NoRouteToHostException("Network not available");

  try {
    URI uri = new URI(url);
    DefaultHttpClient httpClient = prepareHttpClient(uri);

    HttpDelete httpPut = new HttpDelete(uri);
    setAuthenticationHeader(httpPut, apiCredentials);
    setHeaders(httpPut, requestGzipCompression(headers));

    // create response object here to measure request duration
    Response<String> ret = new Response<String>();
    ret.requestStartTime = System.currentTimeMillis();

    HttpResponse httpResponse = httpClient.execute(httpPut);

    parseResponseHeaders(context, httpResponse, ret);

    processStandardHttpResponseCodes(httpResponse);

    ret.data = getResponseContentAsString(httpResponse);

    ret.snapRequestDuration();
    writeReponseInfo(ret, context);
    return ret;
  } catch (IOException e) {
    logGithubAPiCallError(context, e);
    throw e;
  }
}
 
Example #20
Source File: RemoteSystemClient.java    From ghwatch with Apache License 2.0 5 votes vote down vote up
public static Response<?> postNoData(Context context, GHCredentials apiCredentials, String url, Map<String, String> headers) throws
        URISyntaxException, IOException, AuthenticationException {
  if (!Utils.isInternetConnectionAvailable(context))
    throw new NoRouteToHostException("Network not available");
  Log.d(TAG, "Going to perform POST request to " + url);

  try {
    URI uri = new URI(url);
    DefaultHttpClient httpClient = prepareHttpClient(uri);

    HttpPost httpPost = new HttpPost(uri);
    setAuthenticationHeader(httpPost, apiCredentials);
    setHeaders(httpPost, headers);

    // create response object here to measure request duration
    Response<String> ret = new Response<String>();
    ret.requestStartTime = System.currentTimeMillis();

    HttpResponse httpResponse = httpClient.execute(httpPost);
    parseResponseHeaders(context, httpResponse, ret);

    processStandardHttpResponseCodes(httpResponse);

    ret.snapRequestDuration();
    writeReponseInfo(ret, context);
    return ret;
  } catch (IOException e) {
    logGithubAPiCallError(context, e);
    throw e;
  }
}
 
Example #21
Source File: AbstractChannel.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Appends the remote address to the message of the exceptions caused by connection attempt failure.将远程地址附加到连接尝试失败所引起的异常的消息。
 */
protected final Throwable annotateConnectException(Throwable cause, SocketAddress remoteAddress) {
    if (cause instanceof ConnectException) {
        return new AnnotatedConnectException((ConnectException) cause, remoteAddress);
    }
    if (cause instanceof NoRouteToHostException) {
        return new AnnotatedNoRouteToHostException((NoRouteToHostException) cause, remoteAddress);
    }
    if (cause instanceof SocketException) {
        return new AnnotatedSocketException((SocketException) cause, remoteAddress);
    }

    return cause;
}
 
Example #22
Source File: Client.java    From RDFS with 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 #23
Source File: UnreadNotificationsService.java    From ghwatch with Apache License 2.0 5 votes vote down vote up
/**
 * @param lastModified timestamp used in "If-Modified-Since" http header, can be null
 * @return null if lastModified used and nothing new
 * @throws InvalidObjectException
 * @throws NoRouteToHostException
 * @throws AuthenticationException
 * @throws IOException
 * @throws JSONException
 * @throws URISyntaxException
 */
protected NotificationStream readNotificationStreamFromServer(String lastModified) throws InvalidObjectException, NoRouteToHostException,
        AuthenticationException, IOException, JSONException, URISyntaxException {

  NotificationStreamParser.IRepoVisibilityAdapter rva = createRepoVisibilityAdapter();

  String url = prepareNotificationLoadingURL(rva);

  Map<String, String> headers = null;
  if (lastModified != null) {
    headers = new HashMap<String, String>();
    headers.put("If-Modified-Since", lastModified);
  }

  Response<JSONArray> resp = RemoteSystemClient.getJSONArrayFromUrl(context, authenticationManager.getGhApiCredentials(context), url, headers);

  if (resp.notModified)
    return null;

  NotificationStream ns = NotificationStreamParser.parseNotificationStream(null, resp.data, rva);
  ns.setLastModified(resp.lastModified);
  if (lastModified == null)
    ns.setLastFullUpdateTimestamp(System.currentTimeMillis());

  //handle paging
  while (resp.linkNext != null) {
    resp = RemoteSystemClient.getJSONArrayFromUrl(context, authenticationManager.getGhApiCredentials(context), resp.linkNext, headers);
    NotificationStreamParser.parseNotificationStream(ns, resp.data, rva);
  }

  return ns;
}
 
Example #24
Source File: WatchedRepositoriesService.java    From ghwatch with Apache License 2.0 5 votes vote down vote up
protected WatchedRepositories readFromServer(String url) throws InvalidObjectException, NoRouteToHostException, AuthenticationException, IOException,
    JSONException, URISyntaxException {

  Response<JSONArray> resp = RemoteSystemClient.getJSONArrayFromUrl(context, authenticationManager.getGhApiCredentials(context), url, null);

  if (resp.notModified)
    return null;

  WatchedRepositories ns = WatchedRepositoriesParser.parseNotificationStream(resp.data);
  ns.setLastFullUpdateTimestamp(System.currentTimeMillis());
  return ns;
}
 
Example #25
Source File: TcpCollectorTest.java    From monsoon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void connectNoRouteToHost() throws Exception {
    Mockito.doThrow(new NoRouteToHostException()).when(mockSocket).connect(Mockito.any());

    final TcpCollector.ConnectDatum result;
    try (TcpCollector tcpCollector = new TcpCollector(dstAddress, GROUP)) {
        result = tcpCollector.tryConnect(mockSocket);
    }

    assertThat(result.getResult(), equalTo(TcpCollector.ConnectResult.NO_ROUTE_TO_HOST));
    Mockito.verify(mockSocket, times(1)).connect(Mockito.eq(dstAddress));
    Mockito.verifyNoMoreInteractions(mockSocket);
}
 
Example #26
Source File: TestLog4Json.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Test
public void testNestedException() throws Throwable {
  Exception e =
      new NoRouteToHostException("that box caught fire 3 years ago");
  Exception ioe = new IOException("Datacenter problems", e);
  ThrowableInformation ti = new ThrowableInformation(ioe);
  Log4Json l4j = new Log4Json();
  long timeStamp = Time.now();
  String outcome = l4j.toJson(new StringWriter(),
      "testNestedException",
      timeStamp,
      "INFO",
      "quoted\"",
      "new line\n and {}",
      ti)
      .toString();
  println("testNestedException", outcome);
  ContainerNode rootNode = Log4Json.parse(outcome);
  assertEntryEquals(rootNode, Log4Json.LEVEL, "INFO");
  assertEntryEquals(rootNode, Log4Json.NAME, "testNestedException");
  assertEntryEquals(rootNode, Log4Json.TIME, timeStamp);
  assertEntryEquals(rootNode, Log4Json.EXCEPTION_CLASS,
      ioe.getClass().getName());
  JsonNode node = assertNodeContains(rootNode, Log4Json.STACK);
  assertTrue("Not an array: " + node, node.isArray());
  node = assertNodeContains(rootNode, Log4Json.DATE);
  assertTrue("Not a string: " + node, node.isTextual());
  //rather than try and make assertions about the format of the text
  //message equalling another ISO date, this test asserts that the hypen
  //and colon characters are in the string.
  String dateText = node.getTextValue();
  assertTrue("No '-' in " + dateText, dateText.contains("-"));
  assertTrue("No '-' in " + dateText, dateText.contains(":"));

}
 
Example #27
Source File: TcpFailureDetector.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
protected boolean memberAlive(Member mbr, byte[] msgData,
                                     boolean sendTest, boolean readTest,
                                     long readTimeout, long conTimeout,
                                     int optionFlag) {
    //could be a shutdown notification
    if ( Arrays.equals(mbr.getCommand(),Member.SHUTDOWN_PAYLOAD) ) return false;

    try (Socket socket = new Socket()) {
        InetAddress ia = InetAddress.getByAddress(mbr.getHost());
        InetSocketAddress addr = new InetSocketAddress(ia, mbr.getPort());
        socket.setSoTimeout((int)readTimeout);
        socket.connect(addr, (int) conTimeout);
        if ( sendTest ) {
            ChannelData data = new ChannelData(true);
            data.setAddress(getLocalMember(false));
            data.setMessage(new XByteBuffer(msgData,false));
            data.setTimestamp(System.currentTimeMillis());
            int options = optionFlag | Channel.SEND_OPTIONS_BYTE_MESSAGE;
            if ( readTest ) options = (options | Channel.SEND_OPTIONS_USE_ACK);
            else options = (options & (~Channel.SEND_OPTIONS_USE_ACK));
            data.setOptions(options);
            byte[] message = XByteBuffer.createDataPackage(data);
            socket.getOutputStream().write(message);
            if ( readTest ) {
                int length = socket.getInputStream().read(message);
                return length > 0;
            }
        }//end if
        return true;
    } catch (SocketTimeoutException | ConnectException | NoRouteToHostException noop) {
        //do nothing, we couldn't connect
    } catch (Exception x) {
        log.error(sm.getString("tcpFailureDetector.failureDetection.failed", mbr),x);
    }
    return false;
}
 
Example #28
Source File: RetryPolicies.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Override
public RetryAction shouldRetry(Exception e, int retries,
    int failovers, boolean isIdempotentOrAtMostOnce) throws Exception {
  if (failovers >= maxFailovers) {
    return new RetryAction(RetryAction.RetryDecision.FAIL, 0,
        "failovers (" + failovers + ") exceeded maximum allowed ("
        + maxFailovers + ")");
  }
  if (retries - failovers > maxRetries) {
    return new RetryAction(RetryAction.RetryDecision.FAIL, 0, "retries ("
        + retries + ") exceeded maximum allowed (" + maxRetries + ")");
  }
  
  if (e instanceof ConnectException ||
      e instanceof NoRouteToHostException ||
      e instanceof UnknownHostException ||
      e instanceof StandbyException ||
      e instanceof ConnectTimeoutException ||
      isWrappedStandbyException(e)) {
    return new RetryAction(RetryAction.RetryDecision.FAILOVER_AND_RETRY,
        getFailoverOrRetrySleepTime(failovers));
  } else if (e instanceof RetriableException
      || getWrappedRetriableException(e) != null) {
    // RetriableException or RetriableException wrapped 
    return new RetryAction(RetryAction.RetryDecision.RETRY,
          getFailoverOrRetrySleepTime(retries));
  } else if (e instanceof SocketException
      || (e instanceof IOException && !(e instanceof RemoteException))) {
    if (isIdempotentOrAtMostOnce) {
      return RetryAction.FAILOVER_AND_RETRY;
    } else {
      return new RetryAction(RetryAction.RetryDecision.FAIL, 0,
          "the invoked method is not idempotent, and unable to determine "
              + "whether it was invoked");
    }
  } else {
      return fallbackPolicy.shouldRetry(e, retries, failovers,
          isIdempotentOrAtMostOnce);
  }
}
 
Example #29
Source File: GitlabExceptionHandler.java    From mylyn-gitlab with Eclipse Public License 1.0 5 votes vote down vote up
public static GitlabException handle(Throwable e) {
	if(e instanceof SSLHandshakeException) {
		return new GitlabException("Invalid TLS Certificate: " + e.getMessage());
	} else if(e instanceof ConnectException) {
		return new GitlabException("Connection refused");
	} else if(e instanceof NoRouteToHostException) {
		return new GitlabException("No route to host");
	} else if(e instanceof FileNotFoundException) {
		return new GitlabException("Invalid path in host");
	} else if(e instanceof IOException) {
		return new GitlabException("Invalid username/password/private token combination");
	}
	
	return new GitlabException("Unknown Exception: " + e.getMessage());
}
 
Example #30
Source File: AuthenticationManager.java    From ghwatch with Apache License 2.0 5 votes vote down vote up
private String remoteLogin(Context context, GHCredentials cred, String otp) throws JSONException, NoRouteToHostException, AuthenticationException,
    ClientProtocolException, URISyntaxException, IOException {
  Map<String, String> headers = null;
  otp = Utils.trimToNull(otp);
  if (otp != null) {
    headers = new HashMap<String, String>();
    headers.put("X-GitHub-OTP", otp);
  }
  String content = GH_AUTH_REQ_CONTENT.replace("*fp*", System.currentTimeMillis() + "");
  Response<String> resp = RemoteSystemClient.putToURL(context, cred, GH_AUTH_REQ_URL, headers, content);
  JSONObject jo = new JSONObject(resp.data);
  return jo.getString("token");
}