Example usage for java.lang Throwable addSuppressed

List of usage examples for java.lang Throwable addSuppressed

Introduction

In this page you can find the example usage for java.lang Throwable addSuppressed.

Prototype

public final synchronized void addSuppressed(Throwable exception) 

Source Link

Document

Appends the specified exception to the exceptions that were suppressed in order to deliver this exception.

Usage

From source file:com.proofpoint.event.collector.LocalEventClient.java

@Override
public <T> ListenableFuture<Void> post(final Iterable<T> events) {
    checkNotNull(events, "events");
    Throwable throwable = null;
    for (T event : events) {
        for (EventWriter eventWriter : eventWriters) {
            try {
                eventWriter.write(serializeEvent(event));
            } catch (IOException e) {
                logger.debug("Failed to serialize event %s: %s", event, e.getMessage());
                if (throwable == null) {
                    throwable = e;/*from   w  w w .j  av  a  2 s.co m*/
                } else {
                    throwable.addSuppressed(e);
                }
            }
        }
    }

    if (throwable != null) {
        return Futures.immediateFailedFuture(throwable);
    }

    return Futures.immediateFuture(null);
}

From source file:org.echocat.jomon.spring.ContextLoadThreadGroup.java

public <T extends Throwable> void throwOn(@Nonnull Class<T> allowedThrowableType) throws T {
    synchronized (_failedThreads) {
        final Throwable highestRatedThrowable = findHighestRatedThrowableIn(_failedThreads);
        if (highestRatedThrowable != null) {
            for (final List<Throwable> throwables : _failedThreads.values()) {
                for (final Throwable throwable : throwables) {
                    if (!highestRatedThrowable.equals(throwable)) {
                        highestRatedThrowable.addSuppressed(throwable);
                    }/*from   www  .  j a v a 2  s  .  c o m*/
                }
            }
            if (allowedThrowableType.isInstance(highestRatedThrowable)) {
                throw allowedThrowableType.cast(highestRatedThrowable);
            } else if (highestRatedThrowable instanceof RuntimeException) {
                throw (RuntimeException) highestRatedThrowable;
            } else if (highestRatedThrowable instanceof Error) {
                throw (Error) highestRatedThrowable;
            } else {
                throw new RuntimeException(highestRatedThrowable);
            }
        }
    }
}

From source file:org.nuxeo.build.ant.artifact.PrintDependencyManagementTask.java

@Override
public void execute() throws BuildException {
    AntBuildMojo mojo = AntBuildMojo.getInstance();
    OutputStream out = System.out;
    OutputStream err = System.err;
    try {//  w  w  w .  j  a  v  a2  s .  c o m
        if (output != null) {
            out = new FileOutputStream(output, append);
        }
        if (checkOutput != null) {
            err = new FileOutputStream(checkOutput, append);
        }
        Artifact artifact;
        if (key == null) {
            artifact = RepositoryUtils.toArtifact(mojo.getProject().getArtifact());
        } else {
            ArtifactDescriptor ad = new ArtifactDescriptor(key);
            artifact = ad.getAetherArtifact();
        }
        if (StringUtils.isEmpty(artifact.getVersion())) {
            artifact = DependencyUtils.setManagedVersion(artifact);
        }
        if (StringUtils.isEmpty(artifact.getVersion())) {
            artifact = DependencyUtils.setNewestVersion(artifact);
        }
        ArtifactDescriptorRequest request = new ArtifactDescriptorRequest();
        request.setArtifact(artifact);
        request.setRepositories(mojo.getRemoteRepositories());
        ArtifactDescriptorResult result = mojo.getSystem().readArtifactDescriptor(mojo.getSession(), request);
        Throwable checks = new Throwable();
        for (Dependency dependency : result.getManagedDependencies()) {
            if (check) {
                try {
                    DependencyUtils.resolve(dependency.getArtifact());
                } catch (ArtifactResolutionException e) {
                    checks.addSuppressed(e);
                    String msg = "";
                    if (checkOutput == null) {
                        msg = "Cannot resolve ";
                    }
                    err.write((msg + toString(dependency)).getBytes(AntBuildMojo.getInstance().getEncoding()));
                    continue;
                }
            }
            String scope = dependency.getScope();
            if ("".equals(scope)) {
                scope = JavaScopes.COMPILE;
            }
            if (scopes == null || scopes.contains(scope)) {
                out.write(toString(dependency).getBytes(AntBuildMojo.getInstance().getEncoding()));
            }
        }
        for (Throwable t : checks.getSuppressed()) {
            log(t.getMessage(), Project.MSG_WARN);
        }
    } catch (IOException | ArtifactDescriptorException e) {
        throw new BuildException(e);
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(err);
    }

}

From source file:org.nuxeo.directory.connector.json.salesforce.SalesforceInMemoryConnector.java

protected DocumentModelList query(Map<String, Serializable> filter) {
    DirectoryService ds = (DirectoryService) Framework.getLocalService(DirectoryService.class);
    Session session = ds.open("oauth2Tokens");
    Throwable localThrowable3 = null;
    try {/*from   www . j ava2  s  . c o  m*/
        DocumentModelList localDocumentModelList = session.query(filter);
        return localDocumentModelList;
    } catch (Throwable localThrowable4) {
    } finally {
        if (session != null)
            if (localThrowable3 != null)
                try {
                    session.close();
                } catch (Throwable localThrowable2) {
                    localThrowable3.addSuppressed(localThrowable2);
                }
            else
                session.close();
    }
    return null;
}

From source file:com.arvato.thoroughly.util.security.impl.DefaultEncryptionKeyRetrievalStrategy.java

private SecretKeySpec tryToLoadKeyFromClasspath() throws IOException, Exception {
    final ClassLoader classloader = getClassLoader();

    if (classloader != null) {
        final InputStream stream = classloader.getResourceAsStream(this.keyFilePath);
        final Throwable localThrowable3 = null;
        try {//from www .j  a v a2 s  .c o m
            final SecretKeySpec localSecretKeySpec = convertStreamToKey(stream);
            return localSecretKeySpec;
        } catch (final Throwable localThrowable4) {
            LOGGER.error(localThrowable4.getMessage());
        } finally {
            if (stream != null) {
                if (localThrowable3 != null) {
                    try {
                        stream.close();
                    } catch (final Throwable localThrowable2) {
                        localThrowable3.addSuppressed(localThrowable2);
                    }
                } else {
                    try {
                        stream.close();
                    } catch (final IOException e) {
                        LOGGER.error(e.getMessage(), e);
                    }
                }
            }
        }
    }
    LOGGER.error("Error loading encryption key from classpath");
    return null;
}

From source file:org.sakuli.exceptions.SakuliExceptionHandler.java

/**
 * transforms any {@link Throwable} to SakuliException. If the property 'sakuli.screenshot.onError=true' is set, the
 * methods add a Screenshot./*w w w.  ja va  2 s. c o m*/
 *
 * @param e a {@link Throwable}
 * @return <EX>  {@link SakuliException} or any child.
 */
private SakuliException transformException(Throwable e) {
    if (loader.getActionProperties().isTakeScreenshots() && !(e instanceof NonScreenshotException)) {
        //try to get a screenshot
        try {
            Path screenshot = loader.getScreenshotActions().takeScreenshot(e.getMessage(),
                    loader.getActionProperties().getScreenShotFolder());
            return addResumeOnException(new SakuliExceptionWithScreenshot(e, screenshot),
                    resumeToTestExcecution(e));
        } catch (IOException e2) {
            logger.error("Screenshot could not be created", e2);
            e.addSuppressed(e2);
        }
    }
    return addResumeOnException((e instanceof SakuliException) ? (SakuliException) e : new SakuliException(e),
            resumeToTestExcecution(e));
}

From source file:org.springframework.test.context.TestContextManager.java

/**
 * Hook for post-processing a test class <em>after</em> execution of all
 * tests within the class. Should be called after any framework-specific
 * <em>after class methods</em> (e.g., methods annotated with JUnit 4's
 * {@link org.junit.AfterClass @AfterClass}).
 * <p>Each registered {@link TestExecutionListener} will be given a chance
 * to perform its post-processing. If a listener throws an exception, the
 * remaining registered listeners will still be called. After all listeners
 * have executed, the first caught exception will be rethrown with any
 * subsequent exceptions {@linkplain Throwable#addSuppressed suppressed} in
 * the first exception./*from   ww w.j av  a 2 s . co  m*/
 * <p>Note that registered listeners will be executed in the opposite
 * @throws Exception if a registered TestExecutionListener throws an exception
 * @since 3.0
 * @see #getTestExecutionListeners()
 * @see Throwable#addSuppressed(Throwable)
 */
public void afterTestClass() throws Exception {
    Class<?> testClass = getTestContext().getTestClass();
    if (logger.isTraceEnabled()) {
        logger.trace("afterTestClass(): class [" + testClass.getName() + "]");
    }
    getTestContext().updateState(null, null, null);

    Throwable afterTestClassException = null;
    // Traverse the TestExecutionListeners in reverse order to ensure proper
    // "wrapper"-style execution of listeners.
    for (TestExecutionListener testExecutionListener : getReversedTestExecutionListeners()) {
        try {
            testExecutionListener.afterTestClass(getTestContext());
        } catch (Throwable ex) {
            logException(ex, "afterTestClass", testExecutionListener, testClass);
            if (afterTestClassException == null) {
                afterTestClassException = ex;
            } else {
                afterTestClassException.addSuppressed(ex);
            }
        }
    }

    this.testContextHolder.remove();

    if (afterTestClassException != null) {
        ReflectionUtils.rethrowException(afterTestClassException);
    }
}

From source file:org.springframework.test.context.TestContextManager.java

/**
 * Hook for post-processing a test <em>after</em> execution of <em>after</em>
 * lifecycle callbacks of the underlying test framework &mdash; for example,
 * tearing down test fixtures, ending a transaction, etc.
 * <p>This method <strong>must</strong> be called immediately after
 * framework-specific <em>after</em> lifecycle callbacks (e.g., methods
 * annotated with JUnit 4's {@link org.junit.After @After}). For historical
 * reasons, this method is named {@code afterTestMethod}. Since the
 * introduction of {@link #afterTestExecution}, a more suitable name for
 * this method might be something like {@code afterTestTearDown} or
 * {@code afterEach}; however, it is unfortunately impossible to rename
 * this method due to backward compatibility concerns.
 * <p>The managed {@link TestContext} will be updated with the supplied
 * {@code testInstance}, {@code testMethod}, and {@code exception}.
 * <p>Each registered {@link TestExecutionListener} will be given a chance
 * to perform its post-processing. If a listener throws an exception, the
 * remaining registered listeners will still be called. After all listeners
 * have executed, the first caught exception will be rethrown with any
 * subsequent exceptions {@linkplain Throwable#addSuppressed suppressed} in
 * the first exception./*ww w  .  j a v  a2s  . c  o  m*/
 * <p>Note that registered listeners will be executed in the opposite
 * @param testInstance the current test instance (never {@code null})
 * @param testMethod the test method which has just been executed on the
 * test instance
 * @param exception the exception that was thrown during execution of the
 * test method or by a TestExecutionListener, or {@code null} if none
 * was thrown
 * @throws Exception if a registered TestExecutionListener throws an exception
 * @see #beforeTestMethod
 * @see #beforeTestExecution
 * @see #afterTestExecution
 * @see #getTestExecutionListeners()
 * @see Throwable#addSuppressed(Throwable)
 */
public void afterTestMethod(Object testInstance, Method testMethod, @Nullable Throwable exception)
        throws Exception {
    String callbackName = "afterTestMethod";
    prepareForAfterCallback(callbackName, testInstance, testMethod, exception);

    Throwable afterTestMethodException = null;
    // Traverse the TestExecutionListeners in reverse order to ensure proper
    // "wrapper"-style execution of listeners.
    for (TestExecutionListener testExecutionListener : getReversedTestExecutionListeners()) {
        try {
            testExecutionListener.afterTestMethod(getTestContext());
        } catch (Throwable ex) {
            logException(ex, callbackName, testExecutionListener, testInstance, testMethod);
            if (afterTestMethodException == null) {
                afterTestMethodException = ex;
            } else {
                afterTestMethodException.addSuppressed(ex);
            }
        }
    }
    if (afterTestMethodException != null) {
        ReflectionUtils.rethrowException(afterTestMethodException);
    }
}

From source file:com.arpnetworking.logback.StenoEncoderTest.java

@Test
public void testEncodeArrayWithSuppressedException() throws Exception {
    final LoggingEvent event = new LoggingEvent();
    event.setLevel(Level.INFO);//from  w w w . j ava 2  s .  c  o  m
    event.setMarker(StenoMarker.ARRAY_MARKER);
    event.setMessage("logEvent");
    event.setLoggerContextRemoteView(_context.getLoggerContextRemoteView());
    event.setTimeStamp(0);
    final Throwable throwable = new NullPointerException("npe!");
    throwable.addSuppressed(new UnsupportedOperationException("uoe!"));
    event.setThrowableProxy(new ThrowableProxy(throwable));
    final Object[] argArray = new Object[2];
    argArray[0] = new String[] {};
    argArray[1] = new Object[] {};
    event.setArgumentArray(argArray);
    _encoder.doEncode(event);
    final String logOutput = _baos.toString(StandardCharsets.UTF_8.name());
    assertOutput("StenoEncoderTest.testEncodeArrayWithSuppressedException.json", logOutput);
    assertMatchesJsonSchema(logOutput);
}

From source file:org.springframework.test.context.TestContextManager.java

/**
 * Hook for post-processing a test <em>immediately after</em> execution of
 * the {@linkplain java.lang.reflect.Method test method} in the supplied
 * {@linkplain TestContext test context} &mdash; for example, for timing
 * or logging purposes.//from  w w w  . j a v a  2 s.  co  m
 * <p>This method <strong>must</strong> be called before framework-specific
 * <em>after</em> lifecycle callbacks (e.g., methods annotated with JUnit 4's
 * {@link org.junit.After @After}).
 * <p>The managed {@link TestContext} will be updated with the supplied
 * {@code testInstance}, {@code testMethod}, and {@code exception}.
 * <p>Each registered {@link TestExecutionListener} will be given a chance
 * to perform its post-processing. If a listener throws an exception, the
 * remaining registered listeners will still be called. After all listeners
 * have executed, the first caught exception will be rethrown with any
 * subsequent exceptions {@linkplain Throwable#addSuppressed suppressed} in
 * the first exception.
 * <p>Note that registered listeners will be executed in the opposite
 * order in which they were registered.
 * @param testInstance the current test instance (never {@code null})
 * @param testMethod the test method which has just been executed on the
 * test instance
 * @param exception the exception that was thrown during execution of the
 * test method or by a TestExecutionListener, or {@code null} if none
 * was thrown
 * @throws Exception if a registered TestExecutionListener throws an exception
 * @since 5.0
 * @see #beforeTestMethod
 * @see #afterTestMethod
 * @see #beforeTestExecution
 * @see #getTestExecutionListeners()
 * @see Throwable#addSuppressed(Throwable)
 */
public void afterTestExecution(Object testInstance, Method testMethod, @Nullable Throwable exception)
        throws Exception {
    String callbackName = "afterTestExecution";
    prepareForAfterCallback(callbackName, testInstance, testMethod, exception);

    Throwable afterTestExecutionException = null;
    // Traverse the TestExecutionListeners in reverse order to ensure proper
    // "wrapper"-style execution of listeners.
    for (TestExecutionListener testExecutionListener : getReversedTestExecutionListeners()) {
        try {
            testExecutionListener.afterTestExecution(getTestContext());
        } catch (Throwable ex) {
            logException(ex, callbackName, testExecutionListener, testInstance, testMethod);
            if (afterTestExecutionException == null) {
                afterTestExecutionException = ex;
            } else {
                afterTestExecutionException.addSuppressed(ex);
            }
        }
    }
    if (afterTestExecutionException != null) {
        ReflectionUtils.rethrowException(afterTestExecutionException);
    }
}