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.thinkbiganalytics.metadata.modeshape.common.mixin.PropertiedMixin.java

/**
 * Merges any new properties in with the other Extra Properties
 *//*from  w w w  .j av a2s  .c  om*/
@Override
default Map<String, Object> mergeProperties(Map<String, Object> props) {
    Map<String, Object> newProps = new HashMap<>();
    Map<String, Object> origProps = getProperties();
    if (origProps != null) {
        newProps.putAll(origProps);
    }
    if (props != null) {
        newProps.putAll(props);
    }
    JcrProperties properties = getPropertiesObject();
    for (Map.Entry<String, Object> entry : newProps.entrySet()) {
        try {
            properties.setProperty(entry.getKey(), entry.getValue());
        } catch (MetadataRepositoryException e) {
            if (ExceptionUtils.getRootCause(e) instanceof ConstraintViolationException) {
                //this is ok
            } else {
                throw e;
            }
        }
    }
    return newProps;
}

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

@Test
public void testAuthenticateWithMalformedJwt() {
    Authenticator authenticator = createAuthenticator(Clock.SYSTEM, ISSUER, null);
    when(httpRequest.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn("Bearer malformed-jwt-token");
    try {// w  w  w  .  j av a  2  s. c  o  m
        authenticator.authenticate(httpRequest, authInfo, SERVICE_NAME);
        fail();
    } catch (UncheckedExecutionException exception) {
        assertTrue(ExceptionUtils.getRootCause(exception) instanceof JoseException);
    }
}

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

@Path("/v1/requests")
@GET//from   w  ww  .  ja  v a  2  s .c om
@Metered
@ApiOperation(value = "Get all the requests in the mailbox")
@Produces({ MediaType.APPLICATION_JSON, MsgPackMediaType.APPLICATION_MSGPACK, MediaType.APPLICATION_XML,
        MediaType.TEXT_HTML })
public List<RevolverCallbackRequest> requests(
        @HeaderParam(RevolversHttpHeaders.MAILBOX_ID_HEADER) final String mailboxId) throws RevolverException {
    try {
        List<RevolverCallbackRequest> callbackRequests = persistenceProvider.requests(mailboxId);
        if (callbackRequests == null) {
            throw RevolverException.builder().status(Response.Status.NOT_FOUND.getStatusCode())
                    .message("Not found").errorCode("R002").build();
        }
        return callbackRequests;
    } catch (Exception e) {
        log.error("Error getting requests", 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 testAuthenticateWithUnknownIssuer() {
    Authenticator authenticator = createAuthenticator(Clock.SYSTEM, ISSUER, null);
    String authToken = TestUtils.generateAuthToken(Optional.<Collection<String>>of(AUDIENCES),
            Optional.of(EMAIL), Optional.of("https://unknown.issuer.com"), Optional.of(SUBJECT),
            RSA_JSON_WEB_KEY);//from w  w  w  .j a  v  a 2s.  co  m
    when(httpRequest.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn("Bearer " + authToken);
    try {
        authenticator.authenticate(httpRequest, authInfo, SERVICE_NAME);
        fail();
    } catch (UncheckedExecutionException exception) {
        Throwable rootCause = ExceptionUtils.getRootCause(exception);
        assertTrue(rootCause instanceof UnauthenticatedException);
        assertTrue(rootCause.getMessage().contains("the issuer is unknown"));
    }
}

From source file:com.flipkart.poseidon.serviceclients.FutureTaskResultToDomainObjectPromiseWrapper.java

/**
 * If root cause of ExecutionException is ServiceClientException, just throw it.
 * Ex: ServiceResponseDecoder throwing ServiceClientException for 5xx responses.
 *
 * @param exception//from   w  ww .  j  a  va  2  s  . c o m
 * @throws PromiseBrokenException
 */
private void checkAndThrowServiceClientException(ExecutionException exception) throws ServiceClientException {
    Throwable generatedException = Optional.ofNullable(ExceptionUtils.getRootCause(exception))
            .orElse(exception);
    if (generatedException instanceof ServiceClientException) {
        throw (ServiceClientException) generatedException;
    }
}

From source file:com.thinkbiganalytics.metadata.upgrade.UpgradeKyloService.java

private void ensureFeedTemplateFeedRelationships() {
    metadataAccess.commit(() -> {//from   www .j a va2s .  co m

        //ensure the templates have the feed relationships
        List<FeedManagerFeed> feeds = feedManagerFeedProvider.findAll();
        Map<String, FeedManagerTemplate> templateMap = new HashMap<>();
        if (feeds != null) {
            feeds.stream().forEach(feed -> {
                FeedManagerTemplate template = feed.getTemplate();
                if (template != null) {
                    //ensure the template has feeds.
                    List<FeedManagerFeed> 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);
                        }
                    }
                    if (templateFeeds == null || !templateFeeds.contains(feed)) {
                        template.addFeed(feed);
                        feedManagerTemplateProvider.update(template);
                    }
                }
            });

        }

        feedProvider.populateInverseFeedDependencies();

        return null;
    }, MetadataAccess.SERVICE);
}

From source file:com.thinkbiganalytics.metadata.modeshape.common.JcrPropertiesEntity.java

/**
 * Merges any new properties in with the other Extra Properties
 *//*from w  w  w .  j a  v  a2  s.  c  om*/
@Override
public Map<String, Object> mergeProperties(Map<String, Object> props) {
    Map<String, Object> newProps = new HashMap<>();
    Map<String, Object> origProps = getProperties();
    if (origProps != null) {
        newProps.putAll(origProps);
    }
    if (props != null) {
        newProps.putAll(props);
    }

    Optional<JcrProperties> propsObj = ensurePropertiesObject();

    if (propsObj.isPresent()) {
        for (Map.Entry<String, Object> entry : newProps.entrySet()) {
            try {
                propsObj.get().setProperty(entry.getKey(), entry.getValue());
            } catch (MetadataRepositoryException e) {
                if (ExceptionUtils.getRootCause(e) instanceof ConstraintViolationException) {
                    //this is ok
                } else {
                    throw e;
                }
            }
        }
    } else {
        log.debug("Unable to set property: \"{}\" on node: {}", getNode(), this.node);
        throw new AccessControlException("You do not have the permission to set properties");
    }
    return newProps;
}

From source file:com.thinkbiganalytics.metadata.modeshape.support.JcrPropertyUtil.java

private static <T> T readJsonValue(String name, Class<T> type, String json) {
    try {/*from   w ww. j a  v  a2s.  c  o  m*/
        return reader.forType(type).readValue(json);
    } catch (IOException e) {
        if (ExceptionUtils.getRootCause(e) instanceof ClassNotFoundException) {
            //attempt to find the old class name and replace it with the new one
            ClassNotFoundException classNotFoundException = (ClassNotFoundException) ExceptionUtils
                    .getRootCause(e);
            String msg = classNotFoundException.getMessage();
            msg = StringUtils.remove(msg, "java.lang.ClassNotFound:");
            String oldName = StringUtils.trim(msg);
            try {
                Class newName = ClassNameChangeRegistry.findClass(oldName);
                String newNameString = newName.getName();
                if (StringUtils.contains(json, oldName)) {
                    //replace and try again
                    json = StringUtils.replace(json, oldName, newNameString);
                    return readJsonValue(name, type, json);
                }
            } catch (ClassNotFoundException c) {

            }

        }
        throw new MetadataRepositoryException("Failed to deserialize JSON property: " + name, e);
    }
}

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

@Path("/v1/responses")
@GET/*from w  ww. jav  a 2s.co  m*/
@Metered
@ApiOperation(value = "Get all the responses in the mailbox")
@Produces({ MediaType.APPLICATION_JSON, MsgPackMediaType.APPLICATION_MSGPACK, MediaType.APPLICATION_XML,
        MediaType.TEXT_HTML })
public List<RevolverCallbackResponse> responses(
        @HeaderParam(RevolversHttpHeaders.MAILBOX_ID_HEADER) final String mailboxId) throws RevolverException {
    try {
        if (Strings.isNullOrEmpty(mailboxId)) {
            throw RevolverException.builder().status(Response.Status.BAD_REQUEST.getStatusCode())
                    .message("Invalid Mailbox Id").errorCode("R003").build();
        }
        List<RevolverCallbackResponse> callbackResponses = persistenceProvider.responses(mailboxId);
        if (callbackResponses == null) {
            throw RevolverException.builder().status(Response.Status.NOT_FOUND.getStatusCode())
                    .message("Not found").errorCode("R002").build();
        }
        return callbackResponses;
    } catch (Exception e) {
        log.error("Error getting responses", 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.jms.JmsDispatcher.java

@Override
public Response send(ConnectorProperties connectorProperties, ConnectorMessage connectorMessage)
        throws InterruptedException {
    eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
            getDestinationName(), ConnectionStatusEventType.SENDING));
    JmsDispatcherProperties jmsDispatcherProperties = (JmsDispatcherProperties) connectorProperties;

    String responseError = null;/*from  w w  w  . j a v a2 s .co  m*/
    String responseStatusMessage = "Message sent successfully.";
    Status responseStatus = Status.SENT; // Always set the status to QUEUED

    // Only one connection is allowed to be created per message so keep track of whether a connection was created.
    boolean connectionCreated = false;

    long dispatcherId = getDispatcherId();
    String connectionKey = getConnectionKey(jmsDispatcherProperties);

    // Retrieve the connection from the cache
    JmsConnection jmsConnection = jmsConnections.get(connectionKey);

    try {
        try {
            if (jmsConnection == null) {
                /*
                 * If the connection was not in the cache, create it and indicate that a
                 * connection was created for this message.
                 */
                connectionCreated = true;
                jmsConnection = getJmsConnection(jmsDispatcherProperties, connectionKey, dispatcherId, false);
            }

            // Retrieve the session for this dispatcherId 
            JmsSession jmsSession = getJmsSession(jmsConnection, dispatcherId);

            /*
             * Get the destination, create the text message, and send it.
             */
            jmsSession.getProducer().send(
                    getDestination(jmsDispatcherProperties, jmsSession, jmsConnection.getInitialContext()),
                    jmsSession.getSession().createTextMessage(jmsDispatcherProperties.getTemplate()));
        } catch (Exception e) {
            if (!connectionCreated) {
                /*
                 * If a connection was not already created for this attempt, create a new
                 * connection and attempt to send the message again. This would typically occur
                 * if a connection was lost prior to the message being sent.
                 */
                try {
                    jmsConnection = getJmsConnection(jmsDispatcherProperties, connectionKey, dispatcherId,
                            true);

                    JmsSession jmsSession = getJmsSession(jmsConnection, dispatcherId);

                    jmsSession.getProducer().send(
                            getDestination(jmsDispatcherProperties, jmsSession,
                                    jmsConnection.getInitialContext()),
                            jmsSession.getSession().createTextMessage(jmsDispatcherProperties.getTemplate()));
                } catch (Exception e2) {
                    // If the message fails to send again, throw the exception which will set the response status to ERROR
                    throw e2;
                }
            } else {
                // Otherwise throw the exception which will set the response status to ERROR
                throw e;
            }
        }
    } catch (Exception 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(),
                connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                connectorProperties.getName(), "Error occurred when attempting to send JMS message.", e));
        responseStatus = Status.QUEUED;
        responseStatusMessage = ErrorMessageBuilder
                .buildErrorResponse("Error occurred when attempting to send JMS message.", e);
        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                "Error occurred when attempting to send JMS message.", e);
    } finally {
        eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getDestinationName(), ConnectionStatusEventType.IDLE));
    }

    return new Response(responseStatus, null, responseStatusMessage, responseError);
}