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:com.mirth.connect.connectors.jdbc.DatabaseDispatcher.java

@Override
public Response send(ConnectorProperties connectorProperties, ConnectorMessage message)
        throws InterruptedException {
    DatabaseDispatcherProperties databaseDispatcherProperties = (DatabaseDispatcherProperties) connectorProperties;
    String info = "URL: " + databaseDispatcherProperties.getUrl();
    eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
            getDestinationName(), ConnectionStatusEventType.READING, info));

    try {// w w w .  j  a v  a 2  s  .c o  m
        Response response = delegate.send(databaseDispatcherProperties, message);
        response.setValidate(
                databaseDispatcherProperties.getDestinationConnectorProperties().isValidateResponse());
        return response;
    } catch (InterruptedException e) {
        throw e;
    } catch (DatabaseDispatcherException e) {
        String logMessage = "An error occurred in channel \""
                + ChannelController.getInstance().getDeployedChannelById(getChannelId()).getName() + "\": "
                + e.getMessage();
        if (isQueueEnabled()) {
            logger.warn(logMessage, ExceptionUtils.getRootCause(e));
        } else {
            logger.error(logMessage, ExceptionUtils.getRootCause(e));
        }

        eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), message.getMessageId(),
                ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(), connectorProperties.getName(),
                e.getMessage(), e));
        return new Response(Status.QUEUED, null,
                ErrorMessageBuilder.buildErrorResponse("Error writing to database.", e),
                ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), e.getMessage(), e));
    } finally {
        eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getDestinationName(), ConnectionStatusEventType.IDLE));
    }
}

From source file:co.runrightfast.core.application.event.AppEvent.java

private void addException(final JsonObjectBuilder json) {
    if (exception != null) {
        final JsonObjectBuilder exBuilder = Json.createObjectBuilder()
                .add("class", exception.getClass().getName())
                .add("stacktrace", ExceptionUtils.getStackTrace(exception));
        final Throwable rootCause = ExceptionUtils.getRootCause(exception);
        if (rootCause != null) {
            exBuilder.add("rootCause", rootCause.getClass().getName());
        }//from w ww  . j a v  a  2  s.  c  o  m
        json.add("exception", exBuilder);
    }
}

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

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

    }
}

From source file:com.mirth.connect.connectors.jdbc.DatabaseReceiver.java

@SuppressWarnings("unchecked")
@Override//  w w w.j  a  va2s  . c o m
protected void poll() throws InterruptedException {
    eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getSourceName(),
            ConnectionStatusEventType.POLLING));
    Object result = null;

    try {
        result = delegate.poll();

        if (isTerminated()) {
            return;
        }

        eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getSourceName(), ConnectionStatusEventType.READING));

        // the result object will be a ResultSet or if JavaScript is used, we also allow the user to return a List<Map<String, Object>>
        if (result instanceof ResultSet) {
            processResultSet((ResultSet) result);
        } else if (result instanceof List) {
            // if the result object is a List, then assume it is a list of maps representing a row to process
            processResultList((List<Map<String, Object>>) result);
        } else {
            throw new DatabaseReceiverException("Unrecognized result: " + result.toString());
        }
    } catch (InterruptedException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Failed to poll for messages from the database in channel \""
                + ChannelController.getInstance().getDeployedChannelById(getChannelId()).getName() + "\"", e);
        eventController.dispatchEvent(
                new ErrorEvent(getChannelId(), getMetaDataId(), null, ErrorEventType.SOURCE_CONNECTOR,
                        getSourceName(), connectorProperties.getName(), null, e.getCause()));
        return;
    } finally {
        if (result instanceof ResultSet) {
            DbUtils.closeQuietly((ResultSet) result);
        }

        try {
            delegate.afterPoll();
        } catch (DatabaseReceiverException e) {
            logger.error("Error in channel \""
                    + ChannelController.getInstance().getDeployedChannelById(getChannelId()).getName() + "\": "
                    + e.getMessage(), ExceptionUtils.getRootCause(e));
            eventController.dispatchEvent(
                    new ErrorEvent(getChannelId(), getMetaDataId(), null, ErrorEventType.SOURCE_CONNECTOR,
                            getSourceName(), connectorProperties.getName(), null, e.getCause()));
        }

        eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getSourceName(), ConnectionStatusEventType.IDLE));
    }
}

From source file:com.francetelecom.clara.cloud.presentation.ExecutionHandlerRequestCycle.java

@Override
/*//  ww w . ja v  a 2s .c  o  m
 * * This method is executed when an exception is caught by wicket
 */
public IRequestHandler onException(RequestCycle cycle, Exception e) {
    logger.error("RunTimeException {}", e);
    cleanMDC();
    //get the required anemic view to display exception
    ExceptionView view = new ExceptionViewFactory(webPageFactory).newView(e);
    //create a specific presenter to inject error details into the view
    ExceptionPresenter presenter = new ExceptionPresenter(view);
    presenter.onException(ExceptionUtils.getRootCause(e));
    //return the view with injected error details
    return new RenderPageRequestHandler(new PageProvider(view.asPage()));
}

From source file:ch.cyberduck.core.azure.AzureWriteFeature.java

@Override
public StatusOutputStream<Void> write(final Path file, final TransferStatus status,
        final ConnectionCallback callback) throws BackgroundException {
    try {//ww  w . jav  a 2  s  .  c  om
        final CloudAppendBlob blob = session.getClient()
                .getContainerReference(containerService.getContainer(file).getName())
                .getAppendBlobReference(containerService.getKey(file));
        if (StringUtils.isNotBlank(status.getMime())) {
            blob.getProperties().setContentType(status.getMime());
        }
        final HashMap<String, String> headers = new HashMap<>();
        // Add previous metadata when overwriting file
        headers.putAll(status.getMetadata());
        blob.setMetadata(headers);
        // Remove additional headers not allowed in metadata and move to properties
        if (headers.containsKey(HttpHeaders.CACHE_CONTROL)) {
            blob.getProperties().setCacheControl(headers.get(HttpHeaders.CACHE_CONTROL));
            headers.remove(HttpHeaders.CACHE_CONTROL);
        }
        if (headers.containsKey(HttpHeaders.CONTENT_TYPE)) {
            blob.getProperties().setCacheControl(headers.get(HttpHeaders.CONTENT_TYPE));
            headers.remove(HttpHeaders.CONTENT_TYPE);
        }
        final Checksum checksum = status.getChecksum();
        if (Checksum.NONE != checksum) {
            switch (checksum.algorithm) {
            case md5:
                try {
                    blob.getProperties().setContentMD5(
                            Base64.toBase64String(Hex.decodeHex(status.getChecksum().hash.toCharArray())));
                    headers.remove(HttpHeaders.CONTENT_MD5);
                } catch (DecoderException e) {
                    // Ignore
                }
                break;
            }
        }
        final BlobRequestOptions options = new BlobRequestOptions();
        options.setConcurrentRequestCount(1);
        options.setStoreBlobContentMD5(preferences.getBoolean("azure.upload.md5"));
        final BlobOutputStream out;
        if (status.isAppend()) {
            options.setStoreBlobContentMD5(false);
            out = blob.openWriteExisting(AccessCondition.generateEmptyCondition(), options, context);
        } else {
            out = blob.openWriteNew(AccessCondition.generateEmptyCondition(), options, context);
        }
        return new VoidStatusOutputStream(out) {
            @Override
            protected void handleIOException(final IOException e) throws IOException {
                if (StringUtils.equals(SR.STREAM_CLOSED, e.getMessage())) {
                    log.warn(String.format("Ignore failure %s", e));
                    return;
                }
                final Throwable cause = ExceptionUtils.getRootCause(e);
                if (cause instanceof StorageException) {
                    throw new IOException(e.getMessage(),
                            new AzureExceptionMappingService().map((StorageException) cause));
                }
                throw e;
            }
        };
    } catch (StorageException e) {
        throw new AzureExceptionMappingService().map("Upload {0} failed", e, file);
    } catch (URISyntaxException e) {
        throw new NotfoundException(e.getMessage(), e);
    }
}

From source file:com.thinkbiganalytics.feedmgr.sla.ServiceLevelAgreementModelTransform.java

public static com.thinkbiganalytics.metadata.rest.model.sla.ServiceLevelAgreement toModel(
        ServiceLevelAgreement domain, boolean deep) {

    com.thinkbiganalytics.metadata.rest.model.sla.ServiceLevelAgreement sla = new com.thinkbiganalytics.metadata.rest.model.sla.ServiceLevelAgreement(
            domain.getId().toString(), domain.getName(), domain.getDescription());
    if (domain.getSlaChecks() != null) {
        List<ServiceLevelAgreementCheck> checks = new ArrayList<>();
        sla.setSlaChecks(checks);/*  ww  w.  ja v a  2  s.co m*/
        for (com.thinkbiganalytics.metadata.sla.spi.ServiceLevelAgreementCheck check : domain.getSlaChecks()) {
            ServiceLevelAgreementCheck restModel = new ServiceLevelAgreementCheck();
            restModel.setCronSchedule(check.getCronSchedule());
            if (deep) {
                try {
                    restModel.setActionConfigurations(check.getActionConfigurations());
                } catch (Exception e) {
                    if (ExceptionUtils.getRootCause(e) instanceof ClassNotFoundException) {
                        String msg = ExceptionUtils.getRootCauseMessage(e);
                        //get just the simpleClassName stripping the package info
                        msg = StringUtils.substringAfterLast(msg, ".");
                        sla.addSlaCheckError("Unable to find the SLA Action Configurations of type: " + msg
                                + ". Check with an administrator to ensure the correct plugin is installed with this SLA configuration. ");
                    } else {
                        throw new RuntimeException(e);
                    }
                }
            }
            checks.add(restModel);
        }
    }

    if (deep) {
        if (domain.getObligationGroups().size() == 1
                && domain.getObligationGroups().get(0).getCondition() == ObligationGroup.Condition.REQUIRED) {
            for (Obligation domainOb : domain.getObligations()) {
                com.thinkbiganalytics.metadata.rest.model.sla.Obligation ob = toModel(domainOb, true);
                sla.addObligation(ob);
            }
        } else {
            for (ObligationGroup domainGroup : domain.getObligationGroups()) {
                com.thinkbiganalytics.metadata.rest.model.sla.ObligationGroup group = new com.thinkbiganalytics.metadata.rest.model.sla.ObligationGroup(
                        domainGroup.getCondition().toString());
                for (Obligation domainOb : domainGroup.getObligations()) {
                    com.thinkbiganalytics.metadata.rest.model.sla.Obligation ob = toModel(domainOb, true);
                    group.addObligation(ob);
                }

                sla.addGroup(group);
            }
        }
    }

    return sla;
}

From source file:ch.cyberduck.core.s3.S3ThresholdUploadService.java

@Override
public StorageObject upload(final Path file, Local local, final BandwidthThrottle throttle,
        final StreamListener listener, final TransferStatus status, final ConnectionCallback prompt)
        throws BackgroundException {
    final Host bookmark = session.getHost();
    if (bookmark.getHostname().endsWith(preferences.getProperty("s3.hostname.default"))) {
        // Only for AWS given threshold
        if (status.getLength() > udtThreshold) {
            // Prompt user
            if (udtTransferOption.prompt(bookmark, status, prompt)) {
                final Location.Name location = session.getFeature(Location.class).getLocation(file);
                if (Location.unknown.equals(location)) {
                    throw new AccessDeniedException("Cannot read bucket location");
                }/*from  w  ww . j a  va 2 s .co m*/
                final S3Session tunneled = new S3Session(session.getHost(), trust, key);
                final UDTProxyConfigurator configurator = new UDTProxyConfigurator(location,
                        udtTransferOption.provider(), trust, key);
                configurator.configure(tunneled);
                final RequestEntityRestStorageService client = tunneled.open(new DisabledHostKeyCallback(),
                        session);
                // Swap credentials. No login required
                client.setProviderCredentials(session.getClient().getProviderCredentials());
                if (!preferences.getBoolean("s3.upload.multipart")) {
                    // Disabled by user
                    if (status.getLength() < preferences.getLong("s3.upload.multipart.required.threshold")) {
                        log.warn("Multipart upload is disabled with property s3.upload.multipart");
                        final S3SingleUploadService single = new S3SingleUploadService(tunneled);
                        return single.upload(file, local, throttle, listener, status, prompt);
                    }
                }
                final Upload<StorageObject> service = new S3MultipartUploadService(tunneled);
                try {
                    return service.upload(file, local, throttle, listener, status, prompt);
                } catch (BackgroundException e) {
                    final Throwable cause = ExceptionUtils.getRootCause(e);
                    if (cause instanceof ExceptionUDT) {
                        throw new UDTExceptionMappingService().map((ExceptionUDT) cause);
                    }
                    throw e;
                }
            }
        }
    }
    if (status.getLength() > multipartThreshold) {
        if (!preferences.getBoolean("s3.upload.multipart")) {
            // Disabled by user
            if (status.getLength() < preferences.getLong("s3.upload.multipart.required.threshold")) {
                log.warn("Multipart upload is disabled with property s3.upload.multipart");
                return singleUploadService.upload(file, local, throttle, listener, status, prompt);
            }
        }
        try {
            return multipartUploadService.upload(file, local, throttle, listener, status, prompt);
        } catch (NotfoundException | InteroperabilityException e) {
            log.warn(String.format("Failure using multipart upload %s. Fallback to single upload.",
                    e.getMessage()));
        }
    }
    return singleUploadService.upload(file, local, throttle, listener, status, prompt);
}

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

@Path("/v1/response/{requestId}")
@GET/*  w ww.  j  a  va  2 s . c  o m*/
@Metered
@ApiOperation(value = "Get the response for a request in the mailbox")
@Produces({ MediaType.APPLICATION_JSON, MsgPackMediaType.APPLICATION_MSGPACK, MediaType.APPLICATION_XML,
        MediaType.TEXT_HTML })
public Response response(@PathParam("requestId") final String requestId) throws RevolverException {
    try {
        RevolverCallbackResponse callbackResponse = persistenceProvider.response(requestId);
        if (callbackResponse == null) {
            throw RevolverException.builder().status(Response.Status.NOT_FOUND.getStatusCode())
                    .message("Not found").errorCode("R002").build();
        }
        val response = Response.status(callbackResponse.getStatusCode()).entity(callbackResponse.getBody());
        callbackResponse.getHeaders().forEach((k, v) -> v.stream().forEach(h -> response.header(k, h)));
        return response.build();
    } catch (Exception e) {
        log.error("Error getting response", e);
        throw RevolverException.builder().status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
                .errorCode("R001").message(ExceptionUtils.getRootCause(e).getMessage()).build();
    }
}

From source file:com.google.api.auth.IntegrationTest.java

@Test
public void testFailedOpenIdDiscovery() {
    Authenticator authenticator = createAuthenticator(Clock.SYSTEM, "https://unknow.issuer", null);
    String authToken = TestUtils.generateAuthToken(Optional.<Collection<String>>of(AUDIENCES),
            Optional.of(EMAIL), Optional.of(ISSUER), Optional.of(SUBJECT), RSA_JSON_WEB_KEY);
    when(httpRequest.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn("Bearer " + authToken);
    try {/*from   w  ww .  j  ava 2  s.  co m*/
        authenticator.authenticate(httpRequest, authInfo, SERVICE_NAME);
        fail();
    } catch (UncheckedExecutionException exception) {
        assertTrue(ExceptionUtils.getRootCause(exception) instanceof UnauthenticatedException);
    }
}