com.google.common.base.Throwables#getRootCause ( )源码实例Demo

下面列出了com.google.common.base.Throwables#getRootCause ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: brooklyn-server   文件: SoftwareEffectorTest.java
@Test(groups="Integration")
public void testBadExitCodeCaught() {
    Task<Void> call = Entities.invokeEffector(app, app, Effectors.effector(Void.class, "badExitCode")
            .impl(new SshEffectorBody<Void>() {
                @Override
                public Void call(ConfigBag parameters) {
                    queue( ssh(COMMAND_THAT_DOES_NOT_EXIST).requiringZeroAndReturningStdout() );
                    return null;
                }
            }).build() );
    try {
        Object result = call.getUnchecked();
        Assert.fail("ERROR: should have failed earlier in this test, instead got successful task result "+result+" from "+call);
    } catch (Exception e) {
        Throwable root = Throwables.getRootCause(e);
        if (!(root instanceof IllegalStateException)) Assert.fail("Should have failed with IAE, but got: "+root);
        if (root.getMessage()==null || root.getMessage().indexOf("exit code")<=0) 
            Assert.fail("Should have failed with 'exit code' message, but got: "+root);
        // test passed
        return;
    }
}
 
源代码2 项目: googleads-java-lib   文件: ConfigurationHelper.java
/**
 * Loads configuration from a specified path. If not absolute, will look in
 * the user home directory, the current classpath and the system classpath.
 * Absolute classpath references will not work.
 *
 * @param path the path to try first as a resource, then as a file
 * @throws ConfigurationLoadException if the configuration could not be
 *         loaded.
 * @returns properties loaded from the specified path or null.
 */
public Configuration fromFile(String path) throws ConfigurationLoadException {
  PropertiesConfiguration propertiesConfiguration =
      setupConfiguration(new PropertiesConfiguration());
  propertiesConfiguration.setFileName(path);
  try {
    propertiesConfiguration.load();
  } catch (ConfigurationException e) {
    if (Throwables.getRootCause(e) instanceof AccessControlException){
      AdsServiceLoggers.ADS_API_LIB_LOG.debug("Properties could not be loaded.", e);
    } else {
      throw new ConfigurationLoadException(
          "Encountered a problem reading the provided configuration file \"" + path + "\"!", e);
    }
  }
  return propertiesConfiguration;
}
 
源代码3 项目: riptide   文件: RequestUriTest.java
@Override
public void execute(final String baseUrl, final UrlResolution resolution, @Nullable final String uri,
        final HttpMethod method, final Consumer<Http> tester) {

    try {
        final Http unit = Http.builder()
                .executor(Executors.newSingleThreadExecutor())
                .requestFactory(new SimpleClientHttpRequestFactory())
                .baseUrl(baseUrl)
                .urlResolution(resolution)
                .build();

        tester.accept(unit);
        fail("Expected exception");
    } catch (final Exception e) {
        final Throwable cause = Throwables.getRootCause(e);
        assertThat(cause, is(instanceOf(IllegalArgumentException.class)));
        assertThat(cause.getMessage(), is(message));
    }
}
 
源代码4 项目: devcoretalk   文件: GuiUtils.java
public static void crashAlert(Throwable t) {
    t.printStackTrace();
    Throwable rootCause = Throwables.getRootCause(t);
    Runnable r = () -> {
        runAlert((stage, controller) -> controller.crashAlert(stage, rootCause.toString()));
        Platform.exit();
    };
    if (Platform.isFxApplicationThread())
        r.run();
    else
        Platform.runLater(r);
}
 
源代码5 项目: grpc-nebula-java   文件: Http2OkHttpTest.java
@Test
public void hostnameVerifierWithCorrectHostname() throws Exception {
  ManagedChannel channel = createChannelBuilder()
      .overrideAuthority(GrpcUtil.authorityFromHostAndPort(
          TestUtils.TEST_SERVER_HOST, getPort()))
      .hostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
          return false;
        }
      })
      .build();
  TestServiceGrpc.TestServiceBlockingStub blockingStub =
      TestServiceGrpc.newBlockingStub(channel);

  Throwable actualThrown = null;
  try {
    blockingStub.emptyCall(Empty.getDefaultInstance());
  } catch (Throwable t) {
    actualThrown = t;
  }
  assertNotNull("The rpc should have been failed due to hostname verification", actualThrown);
  Throwable cause = Throwables.getRootCause(actualThrown);
  assertTrue(
      "Failed by unexpected exception: " + cause, cause instanceof SSLPeerUnverifiedException);
  channel.shutdown();
}
 
@VisibleForTesting
static void handleUncaughtException(final Thread t, final Throwable e) {
    if (e instanceof UnrecoverableException) {
        if (((UnrecoverableException) e).isShowException()) {
            log.error("An unrecoverable Exception occurred. Exiting HiveMQ", t, e);
        }
        System.exit(1);
    } else if (e instanceof CreationException) {
        if (e.getCause() instanceof UnrecoverableException) {
            log.error("An unrecoverable Exception occurred. Exiting HiveMQ");
            System.exit(1);
        }

        final CreationException creationException = (CreationException) e;
        checkGuiceErrorsForUnrecoverable(creationException.getErrorMessages());

    } else if (e instanceof ProvisionException) {
        if (e.getCause() instanceof UnrecoverableException) {
            log.error("An unrecoverable Exception occurred. Exiting HiveMQ");
            System.exit(1);
        }

        final ProvisionException provisionException = (ProvisionException) e;
        checkGuiceErrorsForUnrecoverable(provisionException.getErrorMessages());


    }
    final Throwable rootCause = Throwables.getRootCause(e);
    if (rootCause instanceof UnrecoverableException) {
        final boolean showException = ((UnrecoverableException) rootCause).isShowException();
        if (showException) {
            log.error("Cause: ", e);
        }
    } else {
        log.error("Uncaught Error:", e);
    }
}
 
源代码7 项目: xtext-core   文件: RenamePositionTest.java
protected void renameAndFail(final String model, final Position position, final String messageFragment) {
  final String modelFile = this.writeFile("MyType.testlang", model);
  this.initialize();
  try {
    final TextDocumentIdentifier identifier = new TextDocumentIdentifier(modelFile);
    PrepareRenameParams _prepareRenameParams = new PrepareRenameParams(identifier, position);
    final Either<Range, PrepareRenameResult> prepareRenameResult = this.languageServer.prepareRename(_prepareRenameParams).get();
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("expected null result got ");
    _builder.append(prepareRenameResult);
    _builder.append(" instead");
    Assert.assertNull(_builder.toString(), prepareRenameResult);
    TextDocumentIdentifier _textDocumentIdentifier = new TextDocumentIdentifier(modelFile);
    final RenameParams renameParams = new RenameParams(_textDocumentIdentifier, position, "Tescht");
    this.languageServer.rename(renameParams).get();
    Assert.fail("Rename should have failed");
  } catch (final Throwable _t) {
    if (_t instanceof Exception) {
      final Exception exc = (Exception)_t;
      final Throwable rootCause = Throwables.getRootCause(exc);
      Assert.assertTrue((rootCause instanceof ResponseErrorException));
      final ResponseError error = ((ResponseErrorException) rootCause).getResponseError();
      Assert.assertTrue(error.getData().toString().contains(messageFragment));
    } else {
      throw Exceptions.sneakyThrow(_t);
    }
  }
}
 
源代码8 项目: sarl   文件: SarlDocumentationParser.java
/** Report an error.
 *
 * @param message the message in a format compatible with {@link MessageFormat}.
 * @param parameters the parameters, starting at {1}.
 */
protected static void reportError(String message, Object... parameters) {
	Throwable cause = null;
	for (int i = 0; cause == null && i < parameters.length; ++i) {
		if (parameters[i] instanceof Throwable) {
			cause = (Throwable) parameters[i];
		}
	}
	final String msg = MessageFormat.format(message, parameters);
	if (cause != null) {
		throw new ParsingException(msg, null, 1, Throwables.getRootCause(cause));
	}
	throw new ParsingException(msg, null, 1);
}
 
源代码9 项目: GreenBits   文件: NioClientManager.java
private void handleKey(SelectionKey key) throws IOException {
    // We could have a !isValid() key here if the connection is already closed at this point
    if (key.isValid() && key.isConnectable()) { // ie a client connection which has finished the initial connect process
        // Create a ConnectionHandler and hook everything together
        PendingConnect data = (PendingConnect) key.attachment();
        StreamConnection connection = data.connection;
        SocketChannel sc = (SocketChannel) key.channel();
        ConnectionHandler handler = new ConnectionHandler(connection, key, connectedHandlers);
        try {
            if (sc.finishConnect()) {
                log.info("Connected to {}", sc.socket().getRemoteSocketAddress());
                key.interestOps((key.interestOps() | SelectionKey.OP_READ) & ~SelectionKey.OP_CONNECT).attach(handler);
                connection.connectionOpened();
                data.future.set(data.address);
            } else {
                log.warn("Failed to connect to {}", sc.socket().getRemoteSocketAddress());
                handler.closeConnection(); // Failed to connect for some reason
                data.future.setException(new ConnectException("Unknown reason"));
                data.future = null;
            }
        } catch (Exception e) {
            // If e is a CancelledKeyException, there is a race to get to interestOps after finishConnect() which
            // may cause this. Otherwise it may be any arbitrary kind of connection failure.
            // Calling sc.socket().getRemoteSocketAddress() here throws an exception, so we can only log the error itself
            Throwable cause = Throwables.getRootCause(e);
            log.warn("Failed to connect with exception: {}: {}", cause.getClass().getName(), cause.getMessage(), e);
            handler.closeConnection();
            data.future.setException(cause);
            data.future = null;
        }
    } else // Process bytes read
        ConnectionHandler.handleKey(key);
}
 
源代码10 项目: buck   文件: AbstractSkylarkFileParser.java
/**
 * Propagates underlying parse exception from {@link UncheckedExecutionException}.
 *
 * <p>This is an unfortunate consequence of having to use {@link
 * LoadingCache#getUnchecked(Object)} in when using stream transformations :(
 *
 * <p>TODO(ttsugrii): the logic of extracting root causes to make them user-friendly should be
 * happening somewhere in {@link com.facebook.buck.cli.MainRunner}, since this behavior is not
 * unique to parsing.
 */
private void propagateRootCause(UncheckedExecutionException e)
    throws IOException, InterruptedException {
  Throwable rootCause = Throwables.getRootCause(e);
  if (rootCause instanceof BuildFileParseException) {
    throw (BuildFileParseException) rootCause;
  }
  if (rootCause instanceof IOException) {
    throw (IOException) rootCause;
  }
  if (rootCause instanceof InterruptedException) {
    throw (InterruptedException) rootCause;
  }
  throw e;
}
 
源代码11 项目: yangtools   文件: YangParserNegativeTest.java
@Test
public void testInvalidAugmentTarget() throws IOException, ReactorException, YangSyntaxErrorException {
    try {
        TestUtils.loadModuleResources(getClass(),
            "/negative-scenario/testfile0.yang",
            "/negative-scenario/testfile3.yang");
        fail("SomeModifiersUnresolvedException should be thrown");
    } catch (final SomeModifiersUnresolvedException e) {
        final Throwable rootCause = Throwables.getRootCause(e);
        assertThat(rootCause, isA(InferenceException.class));
        assertThat(rootCause.getMessage(), startsWith(
            "Augment target 'Absolute{qnames=[(urn:simple.container.demo)unknown]}' not found"));
    }
}
 
源代码12 项目: yangtools   文件: YangParserNegativeTest.java
@Test
public void testDuplicityInAugmentTarget2() throws IOException, ReactorException, YangSyntaxErrorException {
    try {
        TestUtils.loadModuleResources(getClass(),
            "/negative-scenario/duplicity/augment0.yang",
                "/negative-scenario/duplicity/augment2.yang");
        fail("Duplicate leaf not detected");
    } catch (SomeModifiersUnresolvedException e) {
        final Throwable rootCause = Throwables.getRootCause(e);
        assertThat(rootCause, isA(SourceException.class));
        assertThat(rootCause.getMessage(), containsString("Cannot add schema tree child with name "
                + "(urn:simple.augment2.demo?revision=2014-06-02)delta, a conflicting child already exists"));

    }
}
 
源代码13 项目: bazel   文件: PackageFunction.java
private static BuildFileContainsErrorsException makeBzlLoadFailedException(
    PackageIdentifier packageId, BzlLoadFailedException e) {
  Throwable rootCause = Throwables.getRootCause(e);
  PackageFunctionException.Builder builder =
      PackageFunctionException.builder()
          .setType(PackageFunctionException.Type.BUILD_FILE_CONTAINS_ERRORS)
          .setPackageIdentifier(packageId)
          .setMessage(e.getMessage())
          .setPackageLoadingCode(PackageLoading.Code.IMPORT_STARLARK_FILE_ERROR);
  if (rootCause instanceof IOException) {
    builder.setException((IOException) rootCause);
  }
  return (BuildFileContainsErrorsException) builder.buildCause();
}
 
@Test
public void testUnboundedRangeStringIsRejected() {
    try {
        PostgreSQLGuavaRangeType instance = PostgreSQLGuavaRangeType.INSTANCE;
        instance.integerRange("(,)");
        fail("An unbounded range string should throw an exception!");
    } catch (Exception e) {
        Throwable rootCause = Throwables.getRootCause(e);
        assertTrue(rootCause instanceof IllegalArgumentException);
        assertTrue(rootCause.getMessage().contains("Cannot find bound type"));
    }
}
 
源代码15 项目: sarl   文件: AbstractDocumentationMojo.java
/** Format the error message.
 *
 * @param inputFile the input file.
 * @param exception the error.
 * @return the error message.
 */
protected String formatErrorMessage(File inputFile, Throwable exception) {
	File filename;
	int lineno = 0;
	final boolean addExceptionName;
	if (exception instanceof ParsingException) {
		addExceptionName = false;
		final ParsingException pexception = (ParsingException) exception;
		final File file = pexception.getFile();
		if (file != null) {
			filename = file;
		} else {
			filename = inputFile;
		}
		lineno = pexception.getLineno();
	} else {
		addExceptionName = true;
		filename = inputFile;
	}
	for (final String sourceDir : this.session.getCurrentProject().getCompileSourceRoots()) {
		final File root = new File(sourceDir);
		if (isParentFile(filename, root)) {
			try {
				filename = FileSystem.makeRelative(filename, root);
			} catch (IOException exception1) {
				//
			}
			break;
		}
	}
	final StringBuilder msg = new StringBuilder();
	msg.append(filename.toString());
	if (lineno > 0) {
		msg.append(":").append(lineno); //$NON-NLS-1$
	}
	msg.append(": "); //$NON-NLS-1$
	final Throwable rootEx = Throwables.getRootCause(exception);
	if (addExceptionName) {
		msg.append(rootEx.getClass().getName());
		msg.append(" - "); //$NON-NLS-1$
	}
	msg.append(rootEx.getLocalizedMessage());
	return msg.toString();
}
 
源代码16 项目: enmasse   文件: HttpAdapterClient.java
public static Predicate<Throwable> instanceOf() {
    return t -> Throwables.getRootCause(t) instanceof ResponseException;
}
 
源代码17 项目: lucene-solr   文件: TestCoreContainer.java
@Test
public void testCoreInitFailuresFromEmptyContainer() throws Exception {
  // reused state
  Map<String,CoreContainer.CoreLoadFailure> failures = null;
  Collection<String> cores = null;
  Exception fail = null;

  // ----
  // init the CoreContainer
  CoreContainer cc = init(CONFIGSETS_SOLR_XML);

  // check that we have the cores we expect
  cores = cc.getLoadedCoreNames();
  assertNotNull("core names is null", cores);
  assertEquals("wrong number of cores", 0, cores.size());

  // check that we have the failures we expect
  failures = cc.getCoreInitFailures();
  assertNotNull("core failures is a null map", failures);
  assertEquals("wrong number of core failures", 0, failures.size());

  // -----
  // try to add a collection with a configset that doesn't exist
  ignoreException(Pattern.quote("bogus_path"));
  SolrException thrown = expectThrows(SolrException.class, () -> {
    cc.create("bogus", ImmutableMap.of("configSet", "bogus_path"));
  });
  Throwable rootCause = Throwables.getRootCause(thrown);
  assertTrue("init exception doesn't mention bogus dir: " + rootCause.getMessage(),
      0 < rootCause.getMessage().indexOf("bogus_path"));

  // check that we have the cores we expect
  cores = cc.getLoadedCoreNames();
  assertNotNull("core names is null", cores);
  assertEquals("wrong number of cores", 0, cores.size());

  // check that we have the failures we expect
  failures = cc.getCoreInitFailures();
  assertNotNull("core failures is a null map", failures);
  assertEquals("wrong number of core failures", 1, failures.size());
  fail = failures.get("bogus").exception;
  assertNotNull("null failure for test core", fail);
  assertTrue("init failure doesn't mention problem: " + fail.getMessage(),
      0 < fail.getMessage().indexOf("bogus_path"));

  // check that we get null accessing a non-existent core
  assertNull(cc.getCore("does_not_exist"));
  // check that we get a 500 accessing the core with an init failure
  thrown = expectThrows(SolrException.class, () -> {
    SolrCore c = cc.getCore("bogus");
  });
  assertEquals(500, thrown.code());
  String cause = Throwables.getRootCause(thrown).getMessage();
  assertTrue("getCore() ex cause doesn't mention init fail: " + cause,
      0 < cause.indexOf("bogus_path"));

  cc.shutdown();
}
 
源代码18 项目: buck   文件: AsyncVersionedTargetGraphBuilder.java
@Override
@SuppressWarnings("PMD")
public TargetGraph build() throws TimeoutException, InterruptedException, VersionException {
  LOG.debug(
      "Starting version target graph transformation (nodes %d)",
      unversionedTargetGraphCreationResult.getTargetGraph().getNodes().size());
  long start = System.currentTimeMillis();

  ImmutableSet<VersionTargetGraphKey> rootKeys =
      RichStream.from(
              unversionedTargetGraphCreationResult
                  .getTargetGraph()
                  .getAll(unversionedTargetGraphCreationResult.getBuildTargets()))
          .map(ImmutableVersionTargetGraphKey::of)
          .collect(ImmutableSet.toImmutableSet());

  ImmutableMap<VersionTargetGraphKey, Future<TargetNode<?>>> results =
      asyncTransformationEngine.computeAll(rootKeys);

  // Wait for actions to complete.
  for (Future<TargetNode<?>> futures : results.values()) {
    try {
      futures.get(timeout, timeUnit);
    } catch (ExecutionException e) {
      Throwable rootCause = Throwables.getRootCause(e);
      Throwables.throwIfInstanceOf(rootCause, VersionException.class);
      Throwables.throwIfInstanceOf(rootCause, TimeoutException.class);
      Throwables.throwIfInstanceOf(rootCause, RuntimeException.class);
      throw new IllegalStateException(
          String.format("Unexpected exception: %s: %s", e.getClass(), e.getMessage()), e);
    }
  }

  asyncTransformationEngine.close();
  versionInfoAsyncTransformationEngine.close();

  long end = System.currentTimeMillis();

  VersionedTargetGraph graph = versionedTargetGraphTransformer.targetGraphBuilder.build();
  LOG.debug(
      "Finished version target graph transformation in %.2f (nodes %d, roots: %d)",
      (end - start) / 1000.0, graph.getSize(), versionedTargetGraphTransformer.roots.get());

  return graph;
}
 
源代码19 项目: bazel   文件: BugReport.java
/** Get exit code corresponding to throwable. */
public static ExitCode getExitCodeForThrowable(Throwable throwable) {
  return (Throwables.getRootCause(throwable) instanceof OutOfMemoryError)
      ? ExitCode.OOM_ERROR
      : ExitCode.BLAZE_INTERNAL_ERROR;
}
 
@Test
public void testProducerLiveConfigReload() throws Exception {
  String topic = "testProducerLiveConfigReload";
  createTopic(topic, 1);
  EmbeddableMario mario = new EmbeddableMario(null);
  Random random = new Random();

  // register kafka cluster to EmbeddableMario
  KafkaClusterDescriptor kafkaClusterDescriptor = new KafkaClusterDescriptor(
      null,
      0,
      "test",
      "test",
      "test",
      zkConnect(),
      bootstrapServers(),
      "test",
      0L
  );
  mario.addKafkaCluster(kafkaClusterDescriptor).get();

  Properties extra = new Properties();
  extra.setProperty(ProducerConfig.MAX_REQUEST_SIZE_CONFIG, "" + 1500);
  extra.setProperty(ProducerConfig.ACKS_CONFIG, "1");
  extra.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class.getCanonicalName());
  extra.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class.getCanonicalName());
  Properties baseProducerConfig = getProducerProperties(extra);
  LiKafkaInstrumentedProducerImpl<byte[], byte[]> producer = new LiKafkaInstrumentedProducerImpl<>(
      baseProducerConfig,
      Collections.emptyMap(),
      (baseConfig, overrideConfig) -> new LiKafkaProducerImpl<>(LiKafkaClientsUtils.getConsolidatedProperties(baseConfig, overrideConfig)),
      mario::getUrl);

  byte[] key = new byte[500];
  byte[] value = new byte[500];
  random.nextBytes(key);
  random.nextBytes(value);
  ProducerRecord<byte[], byte[]> record = new ProducerRecord<>(topic, 0, key, value);
  RecordMetadata recordMetadata = producer.send(record).get();

  Producer<byte[], byte[]> delegate = producer.getDelegate();

  key = new byte[3000];
  value = new byte[3000];
  random.nextBytes(key);
  random.nextBytes(value);
  record = new ProducerRecord<>(topic, 0, key, value);
  try {
    producer.send(record).get();
    Assert.fail("record expected to fail");
  } catch (Exception e) {
    Throwable root = Throwables.getRootCause(e);
    Assert.assertTrue(root instanceof RecordTooLargeException, root.getClass() + " is not a RecordTooLargeException");
  }

  //install a new config policy, wait for the push
  mario.setConfigPolicy(new ClientConfigRules(Collections.singletonList(
      new ClientConfigRule(ClientPredicates.ALL, ImmutableMap.of("max.request.size", "" + 9000)))));

  KafkaTestUtils.waitUntil("delegate recreated", () -> {
    Producer<byte[], byte[]> delegateNow = producer.getDelegate();
    return delegateNow != delegate;
  }, 1, 2, TimeUnit.MINUTES, false);

  producer.send(record).get(); //should succeed this time

  producer.close(Duration.ofSeconds(30));
  mario.close();
}