Example usage for org.apache.commons.lang3.exception ExceptionUtils getRootCause

List of usage examples for org.apache.commons.lang3.exception ExceptionUtils getRootCause

Introduction

In this page you can find the example usage for org.apache.commons.lang3.exception ExceptionUtils getRootCause.

Prototype

public static Throwable getRootCause(final Throwable throwable) 

Source Link

Document

Introspects the Throwable to obtain the root cause.

This method walks through the exception chain to the last element, "root" of the tree, using #getCause(Throwable) , and returns that exception.

From version 2.2, this method handles recursive cause structures that might otherwise cause infinite loops.

Usage

From source file:ch.cyberduck.core.sftp.SFTPExceptionMappingService.java

@Override
public BackgroundException map(final IOException e) {
    if (ExceptionUtils.getRootCause(e) instanceof SSHException) {
        return this.map((SSHException) ExceptionUtils.getRootCause(e));
    }/*  w  w  w.j  a  v  a2s. com*/
    final StringBuilder buffer = new StringBuilder();
    this.append(buffer, e.getMessage());
    if (ExceptionUtils.getRootCause(e) != null) {
        if (!StringUtils.equals(e.getMessage(), ExceptionUtils.getRootCause(e).getMessage())) {
            this.append(buffer, ExceptionUtils.getRootCause(e).getMessage());
        }
    }
    if (e instanceof SFTPException) {
        final SFTPException failure = (SFTPException) e;
        final Response.StatusCode code = failure.getStatusCode();
        switch (code) {
        case UNKNOWN:
        case BAD_MESSAGE:
        case FAILURE:
        case OP_UNSUPPORTED:
            return new InteroperabilityException(buffer.toString(), e);
        case NO_SUCH_FILE:
            return new NotfoundException(buffer.toString(), e);
        case PERMISSION_DENIED:
            return new AccessDeniedException(buffer.toString(), e);
        case NO_CONNECTION:
        case CONNECITON_LOST:
            return new ConnectionRefusedException(buffer.toString(), e);
        }
    }
    if (e instanceof UserAuthException) {
        return new LoginFailureException(buffer.toString(), e);
    }
    if (e instanceof ConnectionException) {
        return new ConnectionRefusedException(buffer.toString(), e);
    }
    if (e instanceof Buffer.BufferException) {
        return new InteroperabilityException(buffer.toString(), e);
    }
    if (e instanceof SSHException) {
        final SSHException failure = (SSHException) e;
        final DisconnectReason reason = failure.getDisconnectReason();
        return this.map(e, buffer, reason);
    }
    return this.wrap(e, buffer);
}

From source file:ch.cyberduck.core.http.ExtendedHttpRequestRetryHandler.java

@Override
public boolean retryRequest(final IOException exception, final int executionCount, final HttpContext context) {
    final Throwable cause = ExceptionUtils.getRootCause(exception);
    if (cause != null) {
        if (cause instanceof RuntimeException) {
            log.warn(String.format("Cancel retry request with execution count %d for failure %s",
                    executionCount, cause));
            return false;
        }/*  w ww .ja v a2  s  .  c om*/
    }
    final boolean retry = super.retryRequest(exception, executionCount, context);
    if (retry) {
        log.info(String.format("Retry request with failure %s", exception));
    } else {
        log.warn(String.format("Cancel retry request with execution count %d for failure %s", executionCount,
                exception));
    }
    return retry;
}

From source file:at.ac.tuwien.dsg.comot.m.common.event.state.ExceptionMessage.java

public ExceptionMessage(String serviceId, String origin, Long time, String eventCauseId, Exception exception) {
    super();//from   ww w .  j  av a 2 s.com

    Throwable root = ExceptionUtils.getRootCause(exception);
    String type;
    String message;
    String details;

    if (root == null) {
        type = exception.getClass().getName();
        message = exception.getMessage();
        details = ExceptionUtils.getStackTrace(exception);
    } else {
        type = root.getClass().getName();
        message = root.getMessage();
        details = ExceptionUtils.getStackTrace(root);
    }

    this.origin = origin;
    this.type = type;
    this.message = message;
    this.details = details;
    this.serviceId = serviceId;
    this.time = time;
    this.eventCauseId = eventCauseId;
}

From source file:cc.sion.core.utils.Exceptions.java

/**
 * ?Root Cause.
 *
 * Cause, 
 *
 */
public static Throwable getRootCause(Throwable ex) {
    return ExceptionUtils.getRootCause(ex);
}

From source file:io.brooklyn.ambari.service.AbstractExtraServiceTest.java

@Test
public void getComponentMappingsThrowExIfNoHost() {
    try {//from   w  w w.  ja  v  a 2s  . c  o m
        app.createAndManageChild(createDummyExtraServiceSpec(null, null, ImmutableList.of("MY_COMPONENT")))
                .getComponentMappings();
        fail();
    } catch (Throwable throwable) {
        Throwable rootCause = ExceptionUtils.getRootCause(throwable);

        assertEquals(NullPointerException.class, rootCause.getClass());
        assertEquals("Default host is required", rootCause.getMessage());
    }
}

From source file:com.mirth.connect.util.MessageExporter.java

/**
 * Executes the message exporter.//from  ww w .  ja  va 2 s  .c  o m
 * 
 * @param messageList
 *            The paginated list to read messages from
 * @param messageWriter
 *            The message writer to write messages to
 * @return A list of the message ids that were exported.
 */
public synchronized int exportMessages(PaginatedList<Message> messageList, MessageWriter messageWriter,
        AttachmentSource attachmentSource) throws InterruptedException, MessageExportException {
    int pageNumber = 0;
    numExported = 0;

    do {
        ThreadUtils.checkInterruptedStatus();

        try {
            messageList.loadPageNumber(++pageNumber);
        } catch (Exception e) {
            throw new MessageExportException(e);
        }

        for (Message message : messageList) {
            ThreadUtils.checkInterruptedStatus();

            try {
                if (attachmentSource != null) {
                    List<Attachment> attachments = attachmentSource.getMessageAttachments(message);

                    if (CollectionUtils.isNotEmpty(attachments)) {
                        message.setAttachments(attachments);
                    }
                }

                if (messageWriter.write(message)) {
                    numExported++;
                }

                numProcessed++;
            } catch (Exception e) {
                Throwable cause = ExceptionUtils.getRootCause(e);
                throw new MessageExportException("Failed to export message: " + cause.getMessage(), cause);
            }
        }
    } while (messageList.hasNextPage());

    return numExported;
}

From source file:eu.crisis_economics.abm.model.clearing.RandomModelExecutionTest.java

/**
  * Test the {@link MasterModel} model file for execution errors. The test
  * behaves as follows:<br>/*from   w w w . j  a va  2 s  . c om*/
  * 
  * <ul>
  *   <li> one instance ({@code M}) of {@link MasterModel} is created;
  *   <li> {@code M} is executed for {@code N} simulation cycles, where
  *        {@code N} is a customizable integer greater than {@code zero};
  *   <li> if any exception is raised during the execution of {@code M},
  *        this test fails. Otherwise, this test succeeds.
  * </ul>
  * 
  * Important notes: model files consume a relatively large amount of
  * memory. It is recommended that the java heap space is increased
  * when running this unit test (eg. -Xms6g).
  */
private void testASingleRandomModelExecution() {
    try {
        model.start();
        while (Simulation.getTime() < numberOfStepsToRun) {
            model.schedule.step(model);
        }
    } catch (final Exception e) {
        System.err.println(
                "Test failed: " + ExceptionUtils.getRootCause(e).getClass().getSimpleName() + " was raised.");
        Assert.fail();
    }
}

From source file:com.yahoo.parsec.clients.ParsecHttpRequestRetryCallable.java

/**
 * Check status code and handles retry if T is type {@link Response} or Ning {@link com.ning.http.client.Response}.
 *
 * @return T// w  w  w. j  a v a 2s.  c om
 * @throws Exception exception
 */
@Override
public T call() throws Exception {
    responses.clear();
    final Request ningRequest = request.getNingRequest();
    final List<Integer> retryStatusCodes = request.getRetryStatusCodes();
    final List<Class<? extends Throwable>> retryExceptions = request.getRetryExceptions();
    final int maxRetries = request.getMaxRetries();

    T response;
    Exception exception;
    int retries = 0;
    for (;;) {
        response = null;
        exception = null;
        try {
            response = executeRequest(ningRequest);
            responses.add(response);
            int statusCode = getStatusCode(response);
            if (statusCode == -1 || !retryStatusCodes.contains(statusCode)) {
                break;
            }
        } catch (Exception e) {
            Throwable root = ExceptionUtils.getRootCause(e);
            if (!retryExceptions.contains(root.getClass())) {
                throw e;
            }
            exception = e;
        }

        if (retries == maxRetries) {
            LOGGER.debug("Max retries reached: " + retries + " (max: " + maxRetries + ")");
            break;
        }
        retries++;
        LOGGER.debug("Retry number: " + retries + " (max: " + maxRetries + ")");
    }
    if (exception != null) {
        throw exception;
    }
    return response;
}

From source file:io.dropwizard.revolver.resource.RevolverMailboxResource.java

@Path("/v1/request/status/{requestId}")
@GET/*  w  w  w. ja  v a  2 s.  com*/
@Metered
@ApiOperation(value = "Get the status of the request in the mailbox")
@Produces({ MediaType.APPLICATION_JSON, MsgPackMediaType.APPLICATION_MSGPACK, MediaType.APPLICATION_XML,
        MediaType.TEXT_HTML })
public RevolverRequestStateResponse requestStatus(@PathParam("requestId") final String requestId)
        throws RevolverException {
    try {
        RevolverRequestState state = persistenceProvider.requestState(requestId);
        if (state == null) {
            throw RevolverException.builder().status(Response.Status.NOT_FOUND.getStatusCode())
                    .message("Not found").errorCode("R002").build();
        }
        return RevolverRequestStateResponse.builder().requestId(requestId).state(state.name()).build();
    } catch (Exception e) {
        log.error("Error getting request state", e);
        throw RevolverException.builder().status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
                .errorCode("R001").message(ExceptionUtils.getRootCause(e).getMessage()).build();
    }
}

From source file:ch.cyberduck.core.ssl.SSLExceptionMappingService.java

/**
 * close_notify(0),//from w ww .j  a va2s .  co m
 * unexpected_message(10),
 * bad_record_mac(20),
 * decryption_failed_RESERVED(21),
 * record_overflow(22),
 * decompression_failure(30),
 * handshake_failure(40),
 * no_certificate_RESERVED(41),
 * bad_certificate(42),
 * unsupported_certificate(43),
 * certificate_revoked(44),
 * certificate_expired(45),
 * certificate_unknown(46),
 * illegal_parameter(47),
 * unknown_ca(48),
 * access_denied(49),
 * decode_error(50),
 * decrypt_error(51),
 * export_restriction_RESERVED(60),
 * protocol_version(70),
 * insufficient_security(71),
 * internal_error(80),
 * user_canceled(90),
 * no_renegotiation(100),
 * unsupported_extension(110),
 */
@Override
public BackgroundException map(final SSLException failure) {
    final StringBuilder buffer = new StringBuilder();
    for (Throwable cause : ExceptionUtils.getThrowableList(failure)) {
        if (cause instanceof SocketException) {
            // Map Connection has been shutdown: javax.net.ssl.SSLException: java.net.SocketException: Broken pipe
            return new DefaultSocketExceptionMappingService().map((SocketException) cause);
        }
    }
    final String message = failure.getMessage();
    for (Alert alert : Alert.values()) {
        if (StringUtils.contains(message, alert.name())) {
            this.append(buffer, alert.getDescription());
            break;
        }
    }
    if (failure instanceof SSLHandshakeException) {
        if (ExceptionUtils.getRootCause(failure) instanceof CertificateException) {
            log.warn(String.format("Ignore certificate failure %s and drop connection", failure.getMessage()));
            // Server certificate not accepted
            return new ConnectionCanceledException(failure);
        }
        return new SSLNegotiateException(buffer.toString(), failure);
    }
    if (ExceptionUtils.getRootCause(failure) instanceof GeneralSecurityException) {
        this.append(buffer, ExceptionUtils.getRootCause(failure).getMessage());
        return new InteroperabilityException(buffer.toString(), failure);
    }
    this.append(buffer, message);
    return new InteroperabilityException(buffer.toString(), failure);
}