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.threewks.thundr.injection.InjectionContextImpl.java

private String getRootMessage(Exception e) {
    Throwable rootCause = ExceptionUtils.getRootCause(e);
    String message = rootCause == null ? e.getMessage() : rootCause.getMessage();
    return message;
}

From source file:com.flipkart.poseidon.core.PoseidonServlet.java

private void processErrorResponse(int statusCode, PoseidonResponse response, HttpServletResponse httpResponse,
        Throwable throwable) throws IOException {
    setHeaders(response, httpResponse);//from  www  .  j  ava2s. com
    setCookies(response, httpResponse);

    Throwable generatedException = Optional.ofNullable(ExceptionUtils.getRootCause(throwable))
            .orElse(throwable);
    logger.error("{}: ", statusCode, generatedException);

    if (configuration.getExceptionMapper() == null
            || !configuration.getExceptionMapper().map(generatedException, httpResponse)) {
        MediaType contentType = application.getDefaultMediaType();
        String errorMsg = "";

        if (generatedException != null && generatedException instanceof DataSourceException) {
            DataSourceException dsException = (DataSourceException) generatedException;
            if (dsException.getResponse() != null) {
                errorMsg = configuration.getObjectMapper().writeValueAsString(dsException.getResponse());
            }
            if (dsException.getStatusCode() > 0) {
                statusCode = dsException.getStatusCode();
            }
        } else {
            errorMsg = throwable.getMessage();
        }
        httpResponse.setContentType(contentType.toString());
        httpResponse.setStatus(statusCode);
        httpResponse.getWriter().println(errorMsg);
    }
}

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

@Test
public void testInvalidOpenIdDiscoveryUrl() {
    String issuer = "https://invalid.issuer";
    Authenticator authenticator = createAuthenticator(Clock.SYSTEM, 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 ww w. j  a v  a  2s.c om*/
        authenticator.authenticate(httpRequest, authInfo, SERVICE_NAME);
        fail();
    } catch (UncheckedExecutionException exception) {
        assertTrue(ExceptionUtils.getRootCause(exception) instanceof UnknownHostException);
    }
}

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

@Test
public void testInvalidJwksUri() {
    Authenticator authenticator = createAuthenticator(Clock.SYSTEM, ISSUER, "https://invalid.jwks.uri");
    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 ww w.j  av  a  2  s.  c o  m*/
        authenticator.authenticate(httpRequest, authInfo, SERVICE_NAME);
        fail();
    } catch (UncheckedExecutionException exception) {
        assertTrue(ExceptionUtils.getRootCause(exception) instanceof UnknownHostException);
    }
}

From source file:gov.anl.aps.cdb.portal.controllers.extensions.ItemMultiEditController.java

private void processDatabaseOperationsException(Exception ex, Item item, MultiEditMode mode) {
    String actionWord = "";
    if (mode == MultiEditMode.create) {
        actionWord = "create";
    } else if (mode == MultiEditMode.update) {
        actionWord = "update";
    } else if (mode == MultiEditMode.delete) {
        actionWord = "delete";
    }// ww w  . j a v a2s  .co  m
    String exceptionMessage;
    if (ex instanceof RuntimeException) {
        Throwable t = ExceptionUtils.getRootCause(ex);
        if (t != null) {
            exceptionMessage = t.getMessage();
        } else {
            exceptionMessage = ex.getMessage();
        }
    } else {
        exceptionMessage = ex.getMessage();
    }

    logger.error("Error performing a " + actionWord + " on item: " + ex);
    addCdbEntityWarningSystemLog("Failed to " + actionWord, ex, item);
    SessionUtility.addErrorMessage("Error",
            "Could not " + actionWord + ": " + item.toString() + " - " + exceptionMessage);
}

From source file:com.thinkbiganalytics.feedmgr.service.ExportImportTemplateService.java

public ImportTemplate importZip(String fileName, InputStream inputStream, ImportOptions importOptions)
        throws IOException {
    this.accessController.checkPermission(AccessController.SERVICES, FeedsAccessControl.IMPORT_TEMPLATES);

    ImportTemplate importTemplate = openZip(fileName, inputStream);
    //verify options before proceeding
    if (importTemplate.hasConnectingReusableTemplate()
            && ImportOptions.IMPORT_CONNECTING_FLOW.NOT_SET.equals(importOptions.getImportConnectingFlow())) {
        //return to user to verify
        log.info(//from ww w. j av a2  s. co  m
                "Importing Zip file template {}. Found a connectingReusableFlow but user has not verified to replace. returning to user to verify",
                fileName);
        importTemplate.setVerificationToReplaceConnectingResuableTemplateNeeded(true);
        return importTemplate;
    }
    log.info("Importing Zip file template {}, overwrite: {}, reusableFlow: {}", fileName,
            importOptions.isOverwrite());
    List<ImportTemplate> connectingTemplates = new ArrayList<>();
    if (importTemplate.hasConnectingReusableTemplate()
            && ImportOptions.IMPORT_CONNECTING_FLOW.YES.equals(importOptions.getImportConnectingFlow())) {
        log.info("Importing Zip file template {}. first importing reusable flow from zip");
        for (String reusableTemplateXml : importTemplate.getNifiConnectingReusableTemplateXmls()) {
            ImportTemplate connectingTemplate = importNifiTemplateWithTemplateString(
                    importTemplate.getFileName(), reusableTemplateXml, importOptions.isOverwrite(), true,
                    false);
            if (!connectingTemplate.isSuccess()) {
                //return with exception
                return connectingTemplate;
            } else {
                connectingTemplates.add(connectingTemplate);
            }
        }
    }

    RegisteredTemplate template = ObjectMapperSerializer.deserialize(importTemplate.getTemplateJson(),
            RegisteredTemplate.class);

    //1 ensure this template doesnt already exist
    importTemplate.setTemplateName(template.getTemplateName());
    RegisteredTemplate existingTemplate = metadataService
            .getRegisteredTemplateByName(template.getTemplateName());
    if (existingTemplate != null) {
        if (!importOptions.isOverwrite()) {
            throw new UnsupportedOperationException("Unable to import the template "
                    + template.getTemplateName()
                    + " because it is already registered.  Please click the overwrite box and try again");
        }
        template.setId(existingTemplate.getId());
    } else {
        template.setId(null);
    }

    //Check to see if this template doesnt already exist in Nifi
    String templateName = null;
    String oldTemplateXml = null;

    try {
        templateName = NifiTemplateParser.getTemplateName(importTemplate.getNifiTemplateXml());
        importTemplate.setTemplateName(templateName);
        TemplateDTO templateDTO = nifiRestClient.getTemplateByName(templateName);
        if (templateDTO != null) {
            oldTemplateXml = nifiRestClient.getTemplateXml(templateDTO.getId());
            if (importOptions.isOverwrite()) {
                nifiRestClient.deleteTemplate(templateDTO.getId());
            } else {
                throw new UnsupportedOperationException("Unable to import Template " + templateName
                        + ".  It already exists in Nifi.  Please check that you wish to overwrite this template and try to import again.");
            }
        }
    } catch (ParserConfigurationException | XPathExpressionException | SAXException e) {
        throw new UnsupportedOperationException(
                "The Xml File you are trying to import is not a valid Nifi Template.  Please Try again. "
                        + e.getMessage());
    }

    log.info("Attempting to import Nifi Template: {} for file {}", templateName, fileName);
    TemplateDTO dto = nifiRestClient.importTemplate(template.getTemplateName(),
            importTemplate.getNifiTemplateXml());
    template.setNifiTemplateId(dto.getId());

    Map<String, Object> configProperties = propertyExpressionResolver.getStaticConfigProperties();
    NifiProcessGroup newTemplateInstance = nifiRestClient.createNewTemplateInstance(
            template.getNifiTemplateId(), configProperties, false,
            new NifiFlowCacheReusableTemplateCreationCallback(false));
    importTemplate.setTemplateResults(newTemplateInstance);
    if (newTemplateInstance.isSuccess()) {
        importTemplate.setSuccess(true);

        try {
            importTemplate.setNifiTemplateId(template.getNifiTemplateId());
            //register it in the system
            metadataService.registerTemplate(template);
            //get the new template
            if (StringUtils.isNotBlank(template.getId())) {
                template = metadataService.getRegisteredTemplate(template.getId());
            } else {
                template = metadataService.getRegisteredTemplateByName(template.getTemplateName());
            }
            importTemplate.setTemplateId(template.getId());

        } catch (Exception e) {
            importTemplate.setSuccess(false);
            Throwable root = ExceptionUtils.getRootCause(e);
            String msg = root != null ? root.getMessage() : e.getMessage();
            importTemplate.getTemplateResults().addError(NifiError.SEVERITY.WARN,
                    "Error registering the template " + template.getTemplateName() + " in the Kylo metadata. "
                            + msg,
                    "");
        }

    }
    if (!importTemplate.isSuccess()) {
        rollbackTemplateImportInNifi(importTemplate, dto, oldTemplateXml);
        //also restore existing registered template with metadata
        //restore old registered template
        if (existingTemplate != null) {
            try {
                metadataService.registerTemplate(existingTemplate);
            } catch (Exception e) {
                Throwable root = ExceptionUtils.getRootCause(e);
                String msg = root != null ? root.getMessage() : e.getMessage();
                importTemplate.getTemplateResults().addError(NifiError.SEVERITY.WARN,
                        "Error while restoring the template " + template.getTemplateName()
                                + " in the Kylo metadata. " + msg,
                        "");
            }
        }
    }

    //remove the temporary Process Group we created
    removeTemporaryProcessGroup(importTemplate);

    //if we also imported the reusable template make sure that is all running properly
    for (ImportTemplate connectingTemplate : connectingTemplates) {
        //enable it
        nifiRestClient
                .markConnectionPortsAsRunning(connectingTemplate.getTemplateResults().getProcessGroupEntity());
    }

    return importTemplate;
}

From source file:com.thinkbiganalytics.feedmgr.rest.controller.NifiIntegrationRestController.java

@POST
@Path("/controller-services/{serviceId}/query")
@Consumes(MediaType.WILDCARD)//w w  w.  jav a2  s  . c om
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Executes a SELECT query.", notes = "Connects to the database specified by the controller service using the password defined in Kylo's application.properties file.")
@ApiResponses({ @ApiResponse(code = 200, message = "Result of the query.", response = QueryResult.class),
        @ApiResponse(code = 404, message = "The controller service could not be found.", response = RestResponseStatus.class),
        @ApiResponse(code = 500, message = "NiFi is unavailable.", response = RestResponseStatus.class) })
public Response executeQuery(@PathParam("serviceId") final String serviceId, final String script) {
    log.debug("Execute query against service '{}': {}", serviceId, script);
    try {
        final QueryResult results = dbcpConnectionPoolTableInfo.executeQueryForControllerService(serviceId, "",
                script);
        return Response.ok(results).build();
    } catch (final DataAccessException e) {
        throw new BadRequestException(ExceptionUtils.getRootCause(e).getMessage(), e);
    } catch (final IllegalArgumentException e) {
        throw new NotFoundException("The controller service could not be found.", e);
    }
}

From source file:io.brooklyn.ambari.AmbariClusterImpl.java

@Override
public void deployCluster() throws AmbariApiException, ExtraServiceException {
    // Set the flag to true so the deployment won't happen multiple times
    setAttribute(CLUSTER_SERVICES_INITIALISE_CALLED, true);

    // Wait for the Ambari server to be up
    getMasterAmbariServer().waitForServiceUp();

    final Map<String, List<String>> componentsByNodeName = new MutableMap<String, List<String>>();

    RecommendationWrapper recommendationWrapper = null;

    if (isHostGroupsDeployment) {
        LOG.info("{} getting the recommendation from AmbariHostGroup configuration", this);
        recommendationWrapper = getRecommendationWrapperFromAmbariHostGroups();
    } else {//  w w w.  j a  va2 s  .c  om
        LOG.info("{} getting the recommendation from Ambari for the services: {}", this, services);
        recommendationWrapper = getRecommendationWrapperFromAmbariServer();
    }

    checkNotNull(recommendationWrapper);
    checkNotNull(recommendationWrapper.getRecommendation());
    checkNotNull(recommendationWrapper.getRecommendation().getBlueprint());
    checkNotNull(recommendationWrapper.getRecommendation().getBindings());

    for (HostGroup hostGroup : recommendationWrapper.getRecommendation().getBlueprint().getHostGroups()) {
        if (!componentsByNodeName.containsKey(hostGroup.getName())) {
            componentsByNodeName.put(hostGroup.getName(), new MutableList<String>());
        }
        final List<HostComponent> hostComponents = MutableList.copyOf(hostGroup.getComponents());
        for (HostComponent component : hostComponents) {
            componentsByNodeName.get(hostGroup.getName()).add(component.getName());
        }
    }

    for (HostGroup hostGroup : recommendationWrapper.getRecommendation().getBindings().getHostGroups()) {
        AmbariAgent ambariAgent = null;

        for (int i = 0; i < hostGroup.getHosts().size(); i++) {
            final Map<String, String> host = hostGroup.getHosts().get(i);
            final String fqdn = host.get("fqdn");
            if (StringUtils.isNotBlank(fqdn)) {
                final List<String> components = componentsByNodeName.get(hostGroup.getName());
                ambariAgent = getAmbariAgentByFqdn(fqdn);
                if (ambariAgent != null && components != null) {
                    ambariAgent.setComponents(components);
                }
            }
        }
    }

    Map<String, Map> configuration = MutableMap.copyOf(getConfig(AMBARI_CONFIGURATIONS));

    if (configuration.size() == 0) {
        configuration.putAll(DEFAULT_CONFIG_MAP);
    }

    for (ExtraService extraService : getExtraServices()) {
        configuration = mergeMaps(configuration, extraService.getAmbariConfig(this));
    }

    LOG.info("{} calling pre-cluster-deploy on all Ambari nodes", this);
    try {
        Task<List<?>> preClusterDeployTasks = createParallelTask("preClusterDeploy",
                new PreClusterDeployFunction());
        Entities.submit(this, preClusterDeployTasks).get();
    } catch (ExecutionException | InterruptedException ex) {
        // If something failed within an extra service, we propagate the exception for the cluster to handle it properly.
        Throwable rootCause = ExceptionUtils.getRootCause(ex);
        if (rootCause != null && rootCause instanceof ExtraServiceException) {
            throw (ExtraServiceException) rootCause;
        } else {
            throw new ExtraServiceException(ex.getMessage());
        }
    }

    LOG.info("{} calling cluster-deploy", this);
    try {
        Request request = getMasterAmbariServer().deployCluster(getConfig(AmbariCluster.CLUSTER_NAME),
                getConfig(AmbariCluster.BLUEPRINT_NAME), recommendationWrapper, configuration);
    } catch (AmbariApiException ex) {
        // If the cluster failed to deploy, we first put the server "ON FIRE" and throw again the exception for the
        // cluster to handle it properly.
        ServiceStateLogic.ServiceNotUpLogic.updateNotUpIndicator((EntityLocal) getMasterAmbariServer(),
                "ambari.api", ex.getMessage());
        throw ex;
    }
}

From source file:io.brooklyn.ambari.AmbariClusterImpl.java

@Override
public void postDeployCluster() throws ExtraServiceException {
    // Set the flag to true so the post deployment won't happen multiple times
    setAttribute(CLUSTER_SERVICES_INSTALLED, true);

    LOG.info("{} calling post-cluster-deploy on all Ambari nodes", this);
    try {//from w w w . ja  va  2s  .c  om
        Task<List<?>> postDeployClusterTasks = createParallelTask("postClusterDeploy",
                new PostClusterDeployFunction());
        Entities.submit(this, postDeployClusterTasks).get();
    } catch (ExecutionException | InterruptedException ex) {
        // If something failed within an extra service, we propagate the exception for the cluster to handle it properly.
        Throwable rootCause = ExceptionUtils.getRootCause(ex);
        if (rootCause != null && rootCause instanceof ExtraServiceException) {
            throw (ExtraServiceException) rootCause;
        } else {
            throw new ExtraServiceException(ex.getMessage());
        }
    }
}

From source file:com.thinkbiganalytics.feedmgr.rest.controller.ServiceLevelAgreementRestController.java

@POST
@Path("/send-test-email-template")
@Produces(MediaType.APPLICATION_JSON)//ww w  . ja v  a  2s . c o  m
@ApiOperation("Test sending the SLA email template.")
@ApiResponses({
        @ApiResponse(code = 200, message = "Test and send the email template to a test address.  If unable to send or an error occurs it will be indicated in the response.", response = VelocityEmailTemplate.class) })
public VelocityEmailTemplate sendTestTemplate(TestSlaVelocityEmail template) {
    accessController.checkPermission(AccessController.SERVICES,
            FeedServicesAccessControl.EDIT_SERVICE_LEVEL_AGREEMENT_EMAIL_TEMPLATE);
    VelocityEmailTemplate parsedTemplate = testTemplate(template);
    String subject = parsedTemplate.getSubject();
    String body = parsedTemplate.getBody();

    TestSlaVelocityEmail testSlaVelocityEmail = new TestSlaVelocityEmail(subject, body,
            template.getEmailAddress());

    //if we have the plugin then send it
    try {
        Object emailService = SpringApplicationContext.getBean("slaEmailService");
        if (emailService != null) {
            MethodUtils.invokeMethod(emailService, "sendMail", template.getEmailAddress(), subject, body);
            testSlaVelocityEmail.setSuccess(true);
        }
    } catch (Exception e) {
        String message = e.getMessage();
        Throwable root = ExceptionUtils.getRootCause(e);
        if (root != null) {
            message = root.getMessage();
        }
        log.error("unable to send preview/test email for SLA template {} ", message, e);
        testSlaVelocityEmail.setExceptionMessage(message);
    }
    return testSlaVelocityEmail;

}