Example usage for java.lang Throwable getSuppressed

List of usage examples for java.lang Throwable getSuppressed

Introduction

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

Prototype

public final synchronized Throwable[] getSuppressed() 

Source Link

Document

Returns an array containing all of the exceptions that were suppressed, typically by the try -with-resources statement, in order to deliver this exception.

Usage

From source file:Main.java

public static void main(String[] argv) {
    Throwable t = new Exception("from java2s.com");

    System.out.println(t.getSuppressed());

}

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

public static String getAllExceptionMessages(Throwable e, boolean flatFormatted) {
    if (e != null) {
        String msg = format(e.getMessage());
        //add suppressed exceptions
        for (Throwable ee : e.getSuppressed()) {
            if (flatFormatted) {
                msg += " --  Suppressed EXCEPTION: " + format(ee.getMessage());
            } else {
                msg += "\n\t\t Suppressed EXCEPTION: " + format(ee.getMessage());
            }//from www  .  ja va2s  .com
        }
        if (flatFormatted) {
            msg = StringUtils.replace(msg, "\n", " ");
            msg = StringUtils.replace(msg, "\t", " ");
            return msg;
        }
        return msg;
    } else {
        return null;
    }
}

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

/**
 * Checks if a {@link Throwable} is an instance of the {@link SakuliExceptionWithScreenshot}.
 *
 * @param e any {@link Throwable}/*from  w w  w.  ja  v  a 2  s  . co m*/
 * @return If true the method returns a valid {@link Path}.
 */
public static Path getScreenshotFile(Throwable e) {
    if (e instanceof SakuliExceptionWithScreenshot) {
        if (((SakuliExceptionWithScreenshot) e).getScreenshot() != null) {
            return ((SakuliExceptionWithScreenshot) e).getScreenshot();
        }
    }
    if (e != null && e.getSuppressed() != null) {
        for (Throwable ee : e.getSuppressed()) {
            if (ee instanceof SakuliExceptionWithScreenshot) {
                return ((SakuliExceptionWithScreenshot) ee).getScreenshot();
            }
        }
    }
    //retrun null if nothing matches
    return null;
}

From source file:org.bigtester.ate.systemlogger.GenericTestCaseLogger.java

private boolean isAlreadyCasePointCut(Throwable error) {
    boolean retVal = false; // NOPMD
    for (int i = 0; i < error.getSuppressed().length; i++) {
        if (error.getSuppressed()[i].getMessage().equalsIgnoreCase(ExceptionMessage.MSG_ALREADY_CASEPOINTCUT)) {
            retVal = true; // NOPMD
        }/*  ww w .  ja  v  a  2 s .co m*/
    }
    return retVal;
}

From source file:org.elasticsearch.client.FailureTrackingResponseListenerTests.java

public void testOnFailure() {
    MockResponseListener responseListener = new MockResponseListener();
    RestClient.FailureTrackingResponseListener listener = new RestClient.FailureTrackingResponseListener(
            responseListener);//from   ww  w .j  a  va  2  s.  c  om
    int numIters = randomIntBetween(1, 10);
    Exception[] expectedExceptions = new Exception[numIters];
    for (int i = 0; i < numIters; i++) {
        RuntimeException runtimeException = new RuntimeException("test" + i);
        expectedExceptions[i] = runtimeException;
        listener.trackFailure(runtimeException);
        assertNull(responseListener.response.get());
        assertNull(responseListener.exception.get());
    }

    if (randomBoolean()) {
        Response response = mockResponse();
        listener.onSuccess(response);
        assertSame(response, responseListener.response.get());
        assertNull(responseListener.exception.get());
    } else {
        RuntimeException runtimeException = new RuntimeException("definitive");
        listener.onDefinitiveFailure(runtimeException);
        assertNull(responseListener.response.get());
        Throwable exception = responseListener.exception.get();
        assertSame(runtimeException, exception);

        int i = numIters - 1;
        do {
            assertNotNull(exception.getSuppressed());
            assertEquals(1, exception.getSuppressed().length);
            assertSame(expectedExceptions[i--], exception.getSuppressed()[0]);
            exception = exception.getSuppressed()[0];
        } while (i >= 0);
    }
}

From source file:com.vmware.photon.controller.common.dcp.ServiceHostUtils.java

/**
 * Function used to wait for a service to be available.
 *
 * @param host// w  w w. j  a v a  2s .  c o  m
 * @param timeout
 * @param serviceLinks
 * @throws Throwable
 */
public static void waitForServiceAvailability(ServiceHost host, long timeout, String... serviceLinks)
        throws Throwable {
    final CountDownLatch latch = new CountDownLatch(serviceLinks.length);
    final Throwable error = new Throwable("Error: registerForAvailability returned errors");

    Operation.CompletionHandler handler = new Operation.CompletionHandler() {
        @Override
        public void handle(Operation operation, Throwable throwable) {
            if (null != throwable) {
                error.addSuppressed(throwable);
            }

            latch.countDown();
        }
    };
    host.registerForServiceAvailability(handler, serviceLinks);

    if (!latch.await(timeout, TimeUnit.MILLISECONDS)) {
        throw new TimeoutException(
                String.format("One or several of service(s) %s not available", Utils.toJson(serviceLinks)));
    }

    if (error.getSuppressed().length > 0) {
        throw error;
    }
}

From source file:com.vmware.photon.controller.common.xenon.ServiceHostUtils.java

/**
 * Function used to wait for a service to be available.
 *
 * @param host/*  w  ww.  j a  v a2 s .  com*/
 * @param timeout
 * @param serviceLinks
 * @throws Throwable
 */
public static void waitForServiceAvailability(ServiceHost host, long timeout, String... serviceLinks)
        throws Throwable {
    final CountDownLatch latch = new CountDownLatch(serviceLinks.length);
    final Throwable error = new Throwable("Error: registerForAvailability returned errors");

    Operation.CompletionHandler handler = new Operation.CompletionHandler() {
        @Override
        public void handle(Operation operation, Throwable throwable) {
            if (null != throwable) {
                error.addSuppressed(throwable);
            }

            latch.countDown();
        }
    };
    host.registerForServiceAvailability(handler, serviceLinks);

    if (!latch.await(timeout, TimeUnit.MILLISECONDS)) {
        throw new TimeoutException(String.format("One or several of service(s) %s not available",
                Utils.toJson(false, false, serviceLinks)));
    }

    if (error.getSuppressed().length > 0) {
        throw error;
    }
}

From source file:edu.usu.sdl.openstorefront.common.util.StringProcessor.java

/**
 * This will produce html highlighted stacktrace
 *
 * @param throwable//  ww  w .  j a va  2  s .co  m
 * @return
 */
public static String parseStackTraceHtml(Throwable throwable) {
    StringBuilder exception = new StringBuilder();

    if (throwable != null) {
        String message = throwable.getMessage();
        if (StringUtils.isNotBlank(message)) {
            exception.append("<b>Message:</b> <span style='color: red;'><b>")
                    .append(message.replace("\n", "<br>")).append("</b><br>");
        }
        for (StackTraceElement stackTraceElement : throwable.getStackTrace()) {
            String style = "color: grey; font-size: 10px;";
            if (stackTraceElement.getClassName().contains("edu.usu.sdl")) {
                style = "color: black; font-size: 12px; font-wieght: bold;";
            }
            exception.append("<span style='").append(style).append("'>")
                    .append(stackTraceElement.getClassName()).append(" (")
                    .append(stackTraceElement.getMethodName()).append(") : ")
                    .append(stackTraceElement.getLineNumber()).append(" ").append("</span><br>");
        }
        if (throwable.getSuppressed().length > 0) {
            exception.append("Suppress Exceptions: ");
            for (Throwable suppressed : throwable.getSuppressed()) {
                exception.append(parseStackTraceHtml(suppressed)).append("<br>");
            }
        }

        if (throwable.getCause() != null) {

        }
    }

    return exception.toString();
}

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  ww.  j  a  v a  2s. 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.openehealth.ipf.commons.ihe.hl7v2.NakFactory.java

/**
 * Retrieves the given exception type from the exception.
 * <p/>//from w  w  w  . j a v  a  2s.co m
 * Is used to get the caused exception that typically have been wrapped in some sort
 * of Camel wrapper exception
 * <p/>
 * The strategy is to look in the exception hierarchy to find the first given cause that matches the type.
 * Will start from the bottom (the real cause) and walk upwards.
 *
 * @param type      the exception type wanted to retrieve
 * @param exception the caused exception
 * @return the exception found (or <tt>null</tt> if not found in the exception hierarchy)
 */
private static <T extends Throwable> Optional<T> getException(Class<T> type, Throwable exception) {
    if (exception == null) {
        return null;
    }

    //check the suppressed exception first
    Optional<T> result = identifyException(Stream.of(exception.getSuppressed()), type);
    if (result.isPresent())
        return result;
    return createExceptionStream(exception).filter(type::isInstance).map(type::cast).findFirst();
}