Java Code Examples for com.google.common.base.Throwables#getRootCause()

The following examples show how to use com.google.common.base.Throwables#getRootCause() . 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: SoftwareEffectorTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@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;
    }
}
 
Example 2
Source File: ConfigurationHelper.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 3
Source File: RequestUriTest.java    From riptide with MIT License 6 votes vote down vote up
@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));
    }
}
 
Example 4
Source File: Http2OkHttpTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 5
Source File: GuiUtils.java    From devcoretalk with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example 6
Source File: HiveMQExceptionHandlerBootstrap.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 7
Source File: RenamePositionTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
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);
    }
  }
}
 
Example 8
Source File: SarlDocumentationParser.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** 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);
}
 
Example 9
Source File: PostgreSQLGuavaRangeTypeTest.java    From hibernate-types with Apache License 2.0 5 votes vote down vote up
@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"));
    }
}
 
Example 10
Source File: PackageFunction.java    From bazel with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 11
Source File: NioClientManager.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
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);
}
 
Example 12
Source File: YangParserNegativeTest.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
@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"));

    }
}
 
Example 13
Source File: AbstractSkylarkFileParser.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 14
Source File: YangParserNegativeTest.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
@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"));
    }
}
 
Example 15
Source File: LiKafkaInstrumentedProducerIntegrationTest.java    From li-apache-kafka-clients with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@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();
}
 
Example 16
Source File: BugReport.java    From bazel with Apache License 2.0 4 votes vote down vote up
/** 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;
}
 
Example 17
Source File: AsyncVersionedTargetGraphBuilder.java    From buck with Apache License 2.0 4 votes vote down vote up
@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;
}
 
Example 18
Source File: TestCoreContainer.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@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();
}
 
Example 19
Source File: HttpAdapterClient.java    From enmasse with Apache License 2.0 4 votes vote down vote up
public static Predicate<Throwable> instanceOf() {
    return t -> Throwables.getRootCause(t) instanceof ResponseException;
}
 
Example 20
Source File: AbstractDocumentationMojo.java    From sarl with Apache License 2.0 4 votes vote down vote up
/** 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();
}