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.joyent.manta.http.InstrumentedMantaHttpRequestExecutor.java

/**
 * Get a reference to (or create) a {@link Meter} based on the supplied exception.
 *
 * @param e exception type to be tracked
 * @return a meter within the registry/*from w w  w  . j  av  a2s.c o m*/
 */
private Meter meter(final Exception e) {
    final Throwable rootEx = ObjectUtils.firstNonNull(ExceptionUtils.getRootCause(e), e);

    return registry.meter("exceptions-" + rootEx.getClass().getSimpleName());
}

From source file:fr.paris.lutece.portal.service.util.AppException.java

private void writeToLogs() {
    StringBuilder sb = new StringBuilder("Critical AppException");

    Throwable strRootCause = ExceptionUtils.getRootCause(this);
    if (strRootCause != null) {
        sb.append(", root cause: ");
        String strShortName = strRootCause.getClass().getSimpleName();
        sb.append(strShortName);/*from w w  w  .  java2s.  c o  m*/
    }

    Throwable throwableForMessage = strRootCause == null ? this : strRootCause;
    String strMessage = throwableForMessage.getMessage();
    if (strMessage != null) {
        sb.append(": ");
        sb.append(strMessage);
    }

    String strHeader = sb.toString();
    AppLogService.error(strHeader, this);
}

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

@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback)
        throws BackgroundException {
    try {/*from  ww w  .  java2  s  .  co m*/
        final CloudBlob blob = session.getClient()
                .getContainerReference(containerService.getContainer(file).getName())
                .getBlobReferenceFromServer(containerService.getKey(file));
        final BlobRequestOptions options = new BlobRequestOptions();
        options.setConcurrentRequestCount(1);
        final BlobInputStream in = blob.openInputStream(AccessCondition.generateEmptyCondition(), options,
                context);
        if (status.isAppend()) {
            try {
                return StreamCopier.skip(in, status.getOffset());
            } catch (IndexOutOfBoundsException e) {
                // If offset is invalid
                throw new DefaultExceptionMappingService().map(e);
            }
        }
        return new ProxyInputStream(in) {
            @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("Download {0} failed", e, file);
    } catch (URISyntaxException e) {
        throw new NotfoundException(e.getMessage(), e);
    }
}

From source file:com.thorpora.module.core.error.ErrorLogger.java

private String resolveMessage(Throwable throwable) {
    Throwable rootCause = ExceptionUtils.getRootCause(throwable);
    String message = throwable.getMessage();
    if (message == null) {
        message = "An exception without message has been thrown";
    }//from  ww w .jav a 2 s.  c  o m
    if (rootCause != null && rootCause != throwable) {
        message += " with root cause : " + rootCause.getMessage();
    }
    return message;
}

From source file:io.dropwizard.revolver.core.RevolverCommand.java

@SuppressWarnings("unchecked")
public ResponseType execute(final RequestType request) throws RevolverExecutionException, TimeoutException {
    final CommandHandlerConfigType apiConfiguration = this.apiConfigurations.get(request.getApi());
    if (null == apiConfiguration) {
        throw new RevolverExecutionException(RevolverExecutionException.Type.BAD_REQUEST,
                "No api spec defined for key: " + request.getApi());
    }/*from   w ww  .j a v  a  2  s . c o  m*/
    final RequestType normalizedRequest = RevolverCommandHelper.normalize(request);
    final TraceInfo traceInfo = normalizedRequest.getTrace();
    addContextInfo(request, traceInfo);
    final Stopwatch watch = Stopwatch.createStarted();
    String errorMessage = null;
    try {
        ResponseType response = (ResponseType) new RevolverCommandHandler(
                RevolverCommandHelper.setter(this, request.getApi()), this.context, this, normalizedRequest)
                        .execute();
        log.debug("Command response: " + response);
        return response;
    } catch (Throwable t) {
        val rootCause = ExceptionUtils.getRootCause(t);
        if (rootCause instanceof TimeoutException) {
            throw (TimeoutException) rootCause;
        }
        errorMessage = rootCause.getLocalizedMessage();
        throw new RevolverExecutionException(RevolverExecutionException.Type.SERVICE_ERROR, rootCause);
    } finally {
        publishTrace(Trace.builder().caller(this.clientConfiguration.getClientName())
                .service(this.serviceConfiguration.getService()).api(apiConfiguration.getApi())
                .duration(watch.stop().elapsed(TimeUnit.MILLISECONDS))
                .transactionId(traceInfo.getTransactionId()).requestId(traceInfo.getRequestId())
                .parentRequestId(traceInfo.getParentRequestId()).timestamp(traceInfo.getTimestamp())
                .attributes(traceInfo.getAttributes()).error(!Strings.isNullOrEmpty(errorMessage))
                .errorReason(errorMessage).build());
    }
}

From source file:ch.cyberduck.core.udt.UDTProxyConfiguratorTest.java

@Test(expected = ConnectionRefusedException.class)
public void testConnectNoServer() throws Exception {
    final Host host = new Host(new S3Protocol(), "s3.amazonaws.com", new Credentials(
            System.getProperties().getProperty("s3.key"), System.getProperties().getProperty("s3.secret")));
    final UDTProxyConfigurator proxy = new UDTProxyConfigurator(
            new S3LocationFeature.S3Region("ap-northeast-1"), new LocalhostProxyProvider() {
                @Override//from  w  ww . j a  v  a 2 s  .c om
                public Host find(final Location.Name region, final boolean tls) {
                    // No server here
                    return new Host(new UDTProtocol(), "test-us-east-1-cyberduck", Scheme.udt.getPort());
                }
            }, new DefaultX509TrustManager(), new DefaultX509KeyManager());
    final S3Session tunneled = new S3Session(host);
    proxy.configure(tunneled);
    try {
        assertNotNull(tunneled.open(new DisabledHostKeyCallback()));
        tunneled.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    } catch (BackgroundException e) {
        final Throwable cause = ExceptionUtils.getRootCause(e);
        if (cause instanceof ExceptionUDT) {
            throw new UDTExceptionMappingService().map((ExceptionUDT) cause);
        }
        throw e;
    }
}

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

@Path("/v1/request/ack/{requestId}")
@POST/*from ww w .ja  va 2s  .c  om*/
@Metered
@ApiOperation(value = "Send ack for a request so that the mailbox message can be marked as read")
@Produces({ MediaType.APPLICATION_JSON, MsgPackMediaType.APPLICATION_MSGPACK, MediaType.APPLICATION_XML,
        MediaType.TEXT_HTML })
public Response ack(@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();
        }
        switch (state) {
        case RESPONDED:
        case ERROR:
            persistenceProvider.setRequestState(requestId, RevolverRequestState.READ);
            return Response.accepted().build();
        default:
            return Response.status(Response.Status.BAD_REQUEST).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.s3.S3ThresholdDownloadService.java

@Override
public void download(final Path file, final 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");
                }//www  . j  a v a  2s .  c  o  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());
                try {
                    new DefaultDownloadFeature(new S3ReadFeature(tunneled)).download(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;
                }
                return;
            }
        }
    }
    super.download(file, local, throttle, listener, status, prompt);
}

From source file:com.thinkbiganalytics.metadata.upgrade.v081.EnsureTemplateFeedRelationshipsUpgradeAction.java

private void ensureFeedTemplateFeedRelationships() {
    //ensure the templates have the feed relationships
    List<Feed> feeds = feedProvider.findAll();
    if (feeds != null) {
        feeds.stream().forEach(feed -> {
            FeedManagerTemplate template = feed.getTemplate();
            if (template != null) {
                //ensure the template has feeds.
                List<Feed> templateFeeds = null;
                try {
                    templateFeeds = template.getFeeds();
                } catch (MetadataRepositoryException e) {
                    //templateFeeds are weak references.
                    //if the template feeds return itemNotExists we need to reset it
                    Throwable rootCause = ExceptionUtils.getRootCause(e);
                    if (rootCause != null && rootCause instanceof ItemNotFoundException) {
                        //reset the reference collection.  It will be rebuilt in the subsequent call
                        JcrPropertyUtil.removeAllFromSetProperty(((JcrFeedTemplate) template).getNode(),
                                JcrFeedTemplate.FEEDS);
                    }//  www  .  j  a va 2  s. co m
                }
                if (templateFeeds == null || !templateFeeds.contains(feed)) {
                    log.info("Updating relationship temlate: {} -> feed: {}", template.getName(),
                            feed.getName());
                    template.addFeed(feed);
                    feedManagerTemplateProvider.update(template);
                }
            }
        });

    }

    feedProvider.populateInverseFeedDependencies();
}

From source file:com.francetelecom.clara.cloud.presentation.tools.PopulateDatasService.java

private Application createApp(String beanName, SampleAppFactory appFactory)
        throws BusinessException, MalformedURLException {

    // create app
    String appLabel = appFactory.getAppLabel();
    String appCode = appFactory.getAppCode();
    String appDescription = appFactory.getAppDescription();
    String appVersionControl = appFactory.getApplicationVersionControl();

    if (appLabel == null) {
        appLabel = beanName.substring(0, beanName.indexOf("LogicalModelCatalog"));
    }/*  w  ww  .j  a  va  2 s  .  co  m*/
    if (appCode == null) {
        appCode = appLabel.substring(0, 4) + 1;
    }
    if (appDescription == null) {
        appDescription = "Sample app description for " + appLabel;
    }
    if (appVersionControl == null) {
        appVersionControl = "http://default.version.control.url";
    }

    String applicationUID;
    try {
        applicationUID = manageApplication.createPublicApplication(appCode, appLabel, appDescription,
                new URL(appVersionControl), WicketSession.get().getPaasUser().getSsoId());
        return manageApplication.findApplicationByUID(applicationUID);
    } catch (DataIntegrityViolationException dataException) {
        logger.error(dataException.getMessage());
        throw new BusinessException(dataException);
    } catch (BusinessException be) {
        throw be;
    } catch (Exception e) {
        Throwable rootCauseException = ExceptionUtils.getRootCause(e);
        if (rootCauseException instanceof ConstraintViolationException) {
            logger.error(rootCauseException.getMessage());
            throw new BusinessException(rootCauseException);
        }
        logger.error(e.getMessage());
        throw new TechnicalException(e);
    }
}