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:org.eclipse.ebr.maven.BundleMojo.java

private void publishP2Metadata() throws MojoExecutionException {
    // copy into output directory
    getLog().debug("Publishing p2 metadata...");
    try {//  w w  w .java  2  s .co m
        // @formatter:off
        executeMojo(
                plugin(groupId("org.eclipse.tycho"), artifactId("tycho-p2-plugin"),
                        version(detectPluginVersion(
                                "org.eclipse.tycho", "tycho-p2-plugin", tychoPluginVersionFallback))),
                goal("p2-metadata"),
                configuration(element("supportedProjectTypes",
                        element("supportedProjectType", "eclipse-bundle-recipe"))),
                executionEnvironment(project, session, pluginManager));
        // @formatter:on
    } catch (final MojoExecutionException e) {
        // check for http://eclip.se/428950
        final Throwable rootCause = ExceptionUtils.getRootCause(e);
        if ((rootCause instanceof IllegalArgumentException) && StringUtils.isBlank(rootCause.getMessage())) {
            final String[] trace = ExceptionUtils.getRootCauseStackTrace(e);
            if ((trace.length > 1) && (trace[1].indexOf("P2GeneratorImpl.getCanonicalArtifact") > 0)) {
                getLog().debug(e);
                throw new MojoExecutionException(
                        "The generated bundle manifest is broken. Unfortunately, the error is hard to discover (see http://eclip.se/428950). Try running Maven with '-Dosgi.logfile=/tmp/tycho-eclipse.log' to get a log file of the embedded Equinox OSGi framework.");
            }
        }
        throw new MojoExecutionException(format(
                "Unable to generate p2 metadata. Please check the generated bundle manifest and any bnd instructions. Try running Maven with '-Dosgi.logfile=/tmp/tycho-eclipse.log' to get a log file of the embedded Equinox OSGi framework. %s",
                e.getMessage()), e);
    }

}

From source file:org.elasticwarehouse.core.parsers.ElasticWarehouseFileParserAuto.java

public boolean parse() throws IOException {
    boolean ret = false;
    InputStream is = null;//ww w  . j a  va  2  s .c  o  m
    file.statParse();
    try {
        LOGGER.info("Parsing " + file.getOrginalFname() + " (" + file.getUploadedFilename() + ")");
        is = new BufferedInputStream(new FileInputStream(new File(file.getUploadedFilename())));

        Parser parser = new AutoDetectParser();
        OutputStream output = new OutputStringStream();
        ContentHandler handler = new BodyContentHandler(output);//System.out);
        //ContentHandler h2 = new EmbeddedContentHandler(handler);
        Metadata metadata = new Metadata();
        //ExtractParser extractParser = new ExtractParser(parser);
        //ParseContext context = new ParseContext();
        //context.set(Parser.class, extractParser);
        //context.set(EmbeddedDocumentExtractor.class, new FileEmbeddedDocumentExtractor());
        ParseContext parseContext = new ParseContext();
        //parseContext.set(Parser.class, new TikaImageExtractingParser());
        parseContext.set(Parser.class, new ElasticWarehouseParserAll(parser, file, conf_));

        parser.parse(is, handler/*handler*/, metadata, parseContext);

        file.fill(metadata, output.toString());
        ret = true;

    } catch (IOException e) {
        EWLogger.logerror(e);
        e.printStackTrace();
    } catch (java.lang.ExceptionInInitializerError e) {
        EWLogger.logerror(e);
        e.printStackTrace();
    } catch (TikaException e) {
        Exception e2 = (Exception) ExceptionUtils.getRootCause(e);
        if (e2 instanceof UnsupportedZipFeatureException) {
            //do nothing, format unsupported
            ret = true;
        } else if (e2 instanceof EncryptedPowerPointFileException) {
            //do nothing, format unsupported
            ret = true;
        } else if (e instanceof org.apache.tika.exception.EncryptedDocumentException) {
            //do nothing, format unsupported
            ret = true;
        } else if (e2 instanceof org.apache.poi.EncryptedDocumentException) {
            //do nothing, format unsupported
            ret = true;
        } else if (e2 instanceof org.apache.tika.exception.EncryptedDocumentException) {
            //do nothing, format unsupported
            ret = true;
        } else {
            EWLogger.logerror(e);
            e.printStackTrace();

            //i.e. for org.apache.tika.exception.TikaException: cannot parse detached pkcs7 signature (no signed data to parse)
            ret = true;
        }
    } catch (SAXException e) {
        EWLogger.logerror(e);
        e.printStackTrace();
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                EWLogger.logerror(e);
                e.printStackTrace();
            }
        }
    }

    //add metadata supporoit to teh mapping
    file.endParse();
    LOGGER.info("Parsing " + file.getOrginalFname() + " took " + file.getParsingTime() + " ms");
    /*if( file == null )
       return false;
    InputStream is = null;
     try {
       is = new FileInputStream(file.getFilename());
       ContentHandler contenthandler = new BodyContentHandler();
       Metadata metadata = new Metadata();
       PDFParser pdfparser = new PDFParser();
       pdfparser.parse(is, contenthandler, metadata, new ParseContext());
       System.out.println(contenthandler.toString());
     }
     catch (Exception e) {
       e.printStackTrace();
     }
     finally {
         if (is != null) is.close();
     }*/
    return ret;
}

From source file:org.finra.dm.service.helper.DmErrorInformationExceptionHandler.java

/**
 * Gets the root cause of the given exception. If the given exception does not have any causes (that is, is already root), returns the given exception.
 *
 * @param throwable - the exception to get the root cause
 *
 * @return the root cause exception/*  w  w w  .  ja  v a 2  s .c o m*/
 */
private Throwable getRootCause(Exception throwable) {
    Throwable rootThrowable = ExceptionUtils.getRootCause(throwable);
    if (rootThrowable == null) {
        // Use the original exception if there are no causes.
        rootThrowable = throwable;
    }
    return rootThrowable;
}

From source file:org.fit.cssbox.scriptbox.dom.Html5DocumentImpl.java

/**
 * Reports document's script error.//from  w  w w  .  ja  v  a2 s .  co m
 * 
 * @see <a href=http://www.w3.org/html/wg/drafts/html/CR/webappapis.html#runtime-script-errors-in-documents">Runtime script errors in documents</a>
 */
public void reportScriptError(Script<?, ?, ?> script) {
    if (errorReportingMode) {
        return;
    }
    ScriptException scriptException = script.getException();
    Throwable rootException = ExceptionUtils.getRootCause(scriptException);

    if (scriptException == null) {
        return;
    }

    errorReportingMode = true;

    int lineno = scriptException.getLineNumber();
    int colno = scriptException.getColumnNumber();
    ;
    String message = rootException.getMessage();
    String location = _address.toExternalForm();
    Object errorObject = rootException; // TODO: Here should be an Error object

    if (script.hasMutedErros()) {
        message = "Script error.";
    }

    ErrorEvent errorEvent = new ErrorEvent();

    errorEvent.initEvent("error", false, true, message, location, lineno, colno, errorObject);

    errorReportingMode = false;

    _window.dispatchEvent(errorEvent);
}

From source file:org.flowable.engine.impl.bpmn.behavior.ScriptTaskActivityBehavior.java

public void execute(DelegateExecution execution) {

    ScriptingEngines scriptingEngines = Context.getProcessEngineConfiguration().getScriptingEngines();

    if (Context.getProcessEngineConfiguration().isEnableProcessDefinitionInfoCache()) {
        ObjectNode taskElementProperties = Context.getBpmnOverrideElementProperties(scriptTaskId,
                execution.getProcessDefinitionId());
        if (taskElementProperties != null
                && taskElementProperties.has(DynamicBpmnConstants.SCRIPT_TASK_SCRIPT)) {
            String overrideScript = taskElementProperties.get(DynamicBpmnConstants.SCRIPT_TASK_SCRIPT).asText();
            if (StringUtils.isNotEmpty(overrideScript) && overrideScript.equals(script) == false) {
                script = overrideScript;
            }/*from   ww w .  j  a v a 2s.co m*/
        }
    }

    boolean noErrors = true;
    try {
        Object result = scriptingEngines.evaluate(script, language, execution, storeScriptVariables);

        if (resultVariable != null) {
            execution.setVariable(resultVariable, result);
        }

    } catch (FlowableException e) {

        LOGGER.warn("Exception while executing {} : {}", execution.getCurrentFlowElement().getId(),
                e.getMessage());

        noErrors = false;
        Throwable rootCause = ExceptionUtils.getRootCause(e);
        if (rootCause instanceof BpmnError) {
            ErrorPropagation.propagateError((BpmnError) rootCause, execution);
        } else {
            throw e;
        }
    }
    if (noErrors) {
        leave(execution);
    }
}

From source file:org.flowable.scripting.secure.behavior.SecureJavascriptTaskActivityBehavior.java

@Override
public void execute(DelegateExecution execution) {
    boolean noErrors = true;
    try {/*from w w  w .  j av  a  2s .  com*/
        Object result = SecureJavascriptUtil.evaluateScript(execution, script);

        if (resultVariable != null) {
            execution.setVariable(resultVariable, result);
        }

    } catch (FlowableException e) {
        noErrors = false;
        Throwable rootCause = ExceptionUtils.getRootCause(e);
        if (rootCause instanceof BpmnError) {
            ErrorPropagation.propagateError((BpmnError) rootCause, execution);
        } else {
            throw e;
        }
    }
    if (noErrors) {
        leave(execution);
    }
}

From source file:org.jbpm.workflow.instance.node.RuleSetNodeInstance.java

private void handleException(Throwable e) {
    ExceptionScopeInstance exceptionScopeInstance = getExceptionScopeInstance(e);
    if (exceptionScopeInstance != null) {
        exceptionScopeInstance.handleException(e.getClass().getName(), e);

        return;//from w  w  w .j  ava2s  . co m
    } else {
        Throwable rootCause = ExceptionUtils.getRootCause(e);
        if (rootCause != null) {
            exceptionScopeInstance = getExceptionScopeInstance(rootCause);
            if (exceptionScopeInstance != null) {
                exceptionScopeInstance.handleException(rootCause.getClass().getName(), rootCause);

                return;
            }
        }
        throw new WorkflowRuntimeException(this, getProcessInstance(),
                "Unable to execute Action: " + e.getMessage(), e);

    }
}

From source file:org.kie.server.remote.rest.jbpm.QueryDataResource.java

@ApiOperation(value = "Returns the results of a specified custom query and filters the results based on a provided builder or filter request body.", response = Object.class, code = 200)
@ApiResponses(value = { @ApiResponse(code = 500, message = "Unexpected error"),
        @ApiResponse(code = 400, message = "Query parameters or filter spec provide invalid conditions"),
        @ApiResponse(code = 200, message = "Successfull response", examples = @Example(value = {
                @ExampleProperty(mediaType = JSON, value = GET_PROCESS_INSTANCES_RESPONSE_JSON) })) })
@POST//from  w  ww. jav a2s. c  om
@Path(RUN_FILTERED_QUERY_DEF_POST_URI)
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response runQueryFiltered(@Context HttpHeaders headers,
        @ApiParam(value = "identifier of the query definition to be used for query", required = true, example = "customQuery") @PathParam("queryName") String queryName,
        @ApiParam(value = "identifier of the query mapper to be used when transforming results", required = true) @QueryParam("mapper") String mapper,
        @ApiParam(value = "optional identifier of the query builder to be used for query conditions", required = false) @QueryParam("builder") String builder,
        @ApiParam(value = "optional pagination - at which page to start, defaults to 0 (meaning first)", required = false) @QueryParam("page") @DefaultValue("0") Integer page,
        @ApiParam(value = "optional pagination - size of the result, defaults to 10", required = false) @QueryParam("pageSize") @DefaultValue("10") Integer pageSize,
        @ApiParam(value = "optional query filter specification represented as QueryFilterSpec", required = false, examples = @Example(value = {
                @ExampleProperty(mediaType = JSON, value = QUERY_FILTER_SPEC_JSON),
                @ExampleProperty(mediaType = XML, value = QUERY_FILTER_SPEC_XML) })) String payload) {

    String type = getContentType(headers);
    // no container id available so only used to transfer conversation id if
    // given by client
    Header conversationIdHeader = buildConversationIdHeader("", context, headers);
    Object result = null;

    try {
        if (builder != null && !builder.isEmpty()) {
            result = queryDataServiceBase.queryFilteredWithBuilder(queryName, mapper, builder, page, pageSize,
                    payload, type);
        } else {
            result = queryDataServiceBase.queryFiltered(queryName, mapper, page, pageSize, payload, type);
        }
        logger.debug("Returning result of process instance search: {}", result);

        return createCorrectVariant(result, headers, Response.Status.OK, conversationIdHeader);
    } catch (Exception e) {
        Throwable root = ExceptionUtils.getRootCause(e);
        if (root == null) {
            root = e;
        }
        if (HttpStatusCodeException.BAD_REQUEST.contains(root.getClass())
                || e instanceof DataSetLookupException) {

            logger.error("{}", MessageFormat.format(BAD_REQUEST, root.getMessage()), e);

            return badRequest(MessageFormat.format(BAD_REQUEST, root.getMessage()), getVariant(headers),
                    conversationIdHeader);
        } else {
            logger.error("{}", MessageFormat.format(UNEXPECTED_ERROR, e.getMessage()), e);

            return internalServerError(MessageFormat.format(UNEXPECTED_ERROR, e.getMessage()),
                    getVariant(headers), conversationIdHeader);
        }
    }
}

From source file:org.kie.server.remote.rest.jbpm.QueryDataResource.java

@ApiOperation(value = "Returns the results of a specified custom query on a specified KIE container and filters the results based on a provided builder or filter request body.", response = Object.class, code = 200)
@ApiResponses(value = { @ApiResponse(code = 500, message = "Unexpected error"),
        @ApiResponse(code = 400, message = "Query parameters or filter spec provide invalid conditions"),
        @ApiResponse(code = 200, message = "Successfull response", examples = @Example(value = {
                @ExampleProperty(mediaType = JSON, value = GET_PROCESS_INSTANCES_RESPONSE_JSON) })) })
@POST//w ww.j a  v  a 2s .c  o m
@Path(RUN_FILTERED_QUERY_DEF_BY_CONTAINER_POST_URI)
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response runQueryFilteredByDeploymentId(@Context HttpHeaders headers,
        @ApiParam(value = "container id to filter queries", required = true, example = "evaluation_1.0.0-SNAPSHOT") @PathParam(CONTAINER_ID) String containerId,
        @ApiParam(value = "identifier of the query definition to be used for query", required = true, example = "customQuery") @PathParam("queryName") String queryName,
        @ApiParam(value = "identifier of the query mapper to be used when transforming results", required = true) @QueryParam("mapper") String mapper,
        @ApiParam(value = "optional identifier of the query builder to be used for query conditions", required = false) @QueryParam("builder") String builder,
        @ApiParam(value = "optional pagination - at which page to start, defaults to 0 (meaning first)", required = false) @QueryParam("page") @DefaultValue("0") Integer page,
        @ApiParam(value = "optional pagination - size of the result, defaults to 10", required = false) @QueryParam("pageSize") @DefaultValue("10") Integer pageSize,
        @ApiParam(value = "optional query filter specification represented as QueryFilterSpec", required = false, examples = @Example(value = {
                @ExampleProperty(mediaType = JSON, value = QUERY_FILTER_SPEC_JSON),
                @ExampleProperty(mediaType = XML, value = QUERY_FILTER_SPEC_XML) })) String payload) {

    String type = getContentType(headers);
    Header conversationIdHeader = buildConversationIdHeader(containerId, context, headers);
    Object result = null;

    try {
        if (builder != null && !builder.isEmpty()) {
            result = queryDataServiceBase.queryFilteredWithBuilder(containerId, queryName, mapper, builder,
                    page, pageSize, payload, type);
        } else {
            result = queryDataServiceBase.queryFiltered(containerId, queryName, mapper, page, pageSize, payload,
                    type);
        }
        logger.debug("Returning result of process instance search: {}", result);

        return createCorrectVariant(result, headers, Response.Status.OK, conversationIdHeader);
    } catch (Exception e) {
        Throwable root = ExceptionUtils.getRootCause(e);
        if (root == null) {
            root = e;
        }
        if (HttpStatusCodeException.BAD_REQUEST.contains(root.getClass())
                || e instanceof DataSetLookupException) {

            logger.error("{}", MessageFormat.format(BAD_REQUEST, root.getMessage()), e);

            return badRequest(MessageFormat.format(BAD_REQUEST, root.getMessage()), getVariant(headers),
                    conversationIdHeader);
        } else {
            logger.error("{}", MessageFormat.format(UNEXPECTED_ERROR, e.getMessage()), e);

            return internalServerError(MessageFormat.format(UNEXPECTED_ERROR, e.getMessage()),
                    getVariant(headers), conversationIdHeader);
        }
    }
}

From source file:org.kie.server.remote.rest.jbpm.search.ProcessInstanceSearchResource.java

@POST
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response getProcessInstancesWithFilters(@Context HttpHeaders headers,
        @QueryParam("page") @DefaultValue("0") Integer page,
        @QueryParam("pageSize") @DefaultValue("10") Integer pageSize, String payload) {

    String type = getContentType(headers);
    // no container id available so only  used to transfer conversation id if given by client.
    Header conversationIdHeader = buildConversationIdHeader("", context, headers);

    try {/*from   w w  w . j av a 2 s .  c om*/
        ProcessInstanceList result = processInstanceQueryServiceBase.getProcessInstancesWithFilters(page,
                pageSize, payload, type);

        logger.debug("Returning result of process instance search: {}", result);

        return createCorrectVariant(result, headers, Response.Status.OK, conversationIdHeader);
    } catch (Exception e) {
        Throwable root = ExceptionUtils.getRootCause(e);
        if (root == null) {
            root = e;
        }
        if (HttpStatusCodeException.BAD_REQUEST.contains(root.getClass())
                || e instanceof DataSetLookupException) {

            logger.error("{}", MessageFormat.format(BAD_REQUEST, root.getMessage()), e);
            return badRequest(MessageFormat.format(BAD_REQUEST, root.getMessage()), getVariant(headers),
                    conversationIdHeader);
        } else {

            logger.error("{}", MessageFormat.format(UNEXPECTED_ERROR, e.getMessage()), e);
            return internalServerError(MessageFormat.format(UNEXPECTED_ERROR, e.getMessage()),
                    getVariant(headers), conversationIdHeader);
        }
    }
}