Example usage for java.lang Throwable getCause

List of usage examples for java.lang Throwable getCause

Introduction

In this page you can find the example usage for java.lang Throwable getCause.

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:com.polyvi.xface.exceptionReporter.XCrashInfo.java

/**
 * ?/*from  w  w w  . j  a  va 2  s  .c  o  m*/
 * @param ex
 * @return ?
 */
private JSONObject getExceptionInfo(Throwable ex) {
    JSONObject exceptionInfo = new JSONObject();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream printStream = new PrintStream(baos);
    ex.printStackTrace(printStream);
    byte[] data = baos.toByteArray();
    String info = new String(data);
    Throwable cause = ex.getCause();
    try {
        exceptionInfo.put(TAG_EXCEPTION_NAME, ex.getClass().getSimpleName());
        exceptionInfo.put(TAG_EXCEPTION_REASON, null == cause ? "unknown cause" : cause.toString());
        exceptionInfo.put(TAG_STACK_TRACE, info);
    } catch (JSONException e) {
        XLog.e(CLASS_NAME, "JSONException:", e.getMessage());
        return null;
    }
    return exceptionInfo;
}

From source file:de.hybris.platform.atddimpex.keywords.ImpexKeywordLibrary.java

private void importImpExFromInputStream(final String resourceName, final InputStream inputStream,
        final String expectedException) throws IOException {
    Throwable exception = null;

    try {//from ww w. j av a  2 s .c  o  m
        importImpExFromInputStream(resourceName, inputStream);
    } catch (final Exception e) {
        exception = e;
        while (exception.getCause() != null) {
            exception = exception.getCause();
        }
        if (exception.getClass().getSimpleName().equals(expectedException)) {
            LOG.info("Expected [" + expectedException + "] caught: " + exception.getMessage());
        } else {
            LOG.error(exception.getMessage(), exception);
        }
    } finally {
        IOUtils.closeQuietly(inputStream);
    }

    if (expectedException == null) {
        assertNull("Import of resource " + resourceName + " failed: "
                + (exception == null ? "" : exception.getMessage()), exception);
    } else {
        assertNotNull("Expected [" + expectedException + "] not thrown", exception);
        assertEquals("Type of thrown exception does not match type of expected exception", expectedException,
                exception.getClass().getSimpleName());
    }
}

From source file:freemarker.log.Logger.java

private static void logInLogger(boolean error, String message, Throwable exception) {
    boolean canUseRealLogger;
    synchronized (Logger.class) {
        canUseRealLogger = loggerFactory != null && !(loggerFactory instanceof _NullLoggerFactory);
    }//  w  w w .  j a va  2 s . c om

    if (canUseRealLogger) {
        try {
            final Logger logger = Logger.getLogger("freemarker.logger");
            if (error) {
                logger.error(message);
            } else {
                logger.warn(message);
            }
        } catch (Throwable e) {
            canUseRealLogger = false;
        }
    }

    if (!canUseRealLogger) {
        System.err.println((error ? "ERROR" : "WARN") + " " + LoggerFactory.class.getName() + ": " + message);
        if (exception != null) {
            System.err.println("\tException: " + tryToString(exception));
            while (exception.getCause() != null) {
                exception = exception.getCause();
                System.err.println("\tCaused by: " + tryToString(exception));
            }
        }
    }
}

From source file:com.adaptris.core.MarshallingBaseCase.java

private void assertRootCause(String errMsg, Exception e) {
    Throwable rootCause = e;
    while (rootCause.getCause() != null) {
        rootCause = rootCause.getCause();
    }/*from   w  w  w . j a  v  a  2 s  .  c om*/
    assertEquals(errMsg, rootCause.getMessage());
}

From source file:com.evolveum.midpoint.repo.sql.helpers.BaseHelper.java

public SQLException findSqlException(Throwable ex) {
    while (ex != null) {
        if (ex instanceof SQLException) {
            return (SQLException) ex;
        }//  ww w.  j  ava  2 s  .c  o  m
        ex = ex.getCause();
    }
    return null;
}

From source file:com.mgmtp.jfunk.core.reporting.CsvReporter.java

@Override
public void addResult(final ReportContext context) {
    if (!(TestModule.class.isAssignableFrom(context.getTestObjectType()))) {
        // we are only interested in the data for each module
        return;/*from  w ww .ja va2 s.  com*/
    }

    log.debug("Adding result to reporter '{}'", getName());

    synchronized (this) {
        if (columns == null) {
            initColumns();
        }

        Map<String, DataSet> dataSets = currentDataSetsProvider.get();
        StrBuilder sb = new StrBuilder(256);
        for (Column column : columns) {
            String dsKey = column.dataSetKey;
            String value;

            if (StringUtils.isNotBlank(dsKey)) {
                // get value from data set
                DataSet ds = dataSets.get(dsKey);
                checkNotNull(ds, "No data set available for key: " + dsKey);
                value = ds.getValue(column.key);
            } else {
                // get property
                value = configProvider.get().get(column.key);
            }

            appendEscapedAndQuoted(sb, value);
        }

        // additional result column
        appendEscapedAndQuoted(sb, context.getTestObjectName());
        appendEscapedAndQuoted(sb, context.isSuccess() ? JFunkConstants.OK : JFunkConstants.ERROR);

        if (context.isSuccess()) {
            appendEscapedAndQuoted(sb, "");
        } else {
            Throwable th = context.getThrowable();
            String msg = th.getMessage();

            Throwable root = th;
            while (root.getCause() != null) {
                root = root.getCause();
            }

            String rootMsg = root.getMessage();
            if (rootMsg != null && !rootMsg.equals(msg)) {
                msg += " - Root Message: " + rootMsg;
            }

            if (isBlank(msg)) {
                msg = th.getClass().getName();
            }
            appendEscapedAndQuoted(sb, msg);
        }

        if (sb.isEmpty()) {
            log.info("Ignoring empty row in report");
        } else {
            String line = sb.toString();
            reportLines.add(line);
        }
    }
}

From source file:org.biokoframework.http.exception.impl.ExceptionResponseBuilderImpl.java

private String descriptionOf(Throwable throwable) {
    StringBuilder message = new StringBuilder().append(throwable.getClass().getName());
    if (!StringUtils.isEmpty(throwable.getMessage())) {
        message.append(" with message '").append(throwable.getMessage()).append("'");
    }/* ww w. ja  v  a 2s. c o m*/
    message.append(" [").append(throwable.getStackTrace()[0]).append("]");
    if (throwable.getCause() != null) {
        message.append(" Caused by " + descriptionOf(throwable.getCause()));
    }
    return message.toString();
}

From source file:com.bstek.dorado.view.resolver.ViewServiceResolver.java

@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    XmlEscapeWriter writer = new XmlEscapeWriter(getWriter(request, response));

    JsonBuilder jsonBuilder = new JsonBuilder(writer);
    ServletInputStream in = request.getInputStream();
    DoradoContext context = DoradoContext.getCurrent();
    try {/*from  ww w. jav  a2s .  c o  m*/
        String contentType = request.getContentType();
        if (contentType != null && contentType.contains(JAVASCRIPT_TOKEN)) {
            Reader reader = new InputStreamReader(in, Constants.DEFAULT_CHARSET);
            StringBuffer buf = new StringBuffer();
            char[] cs = new char[BUFFER_SIZE];
            for (int n; (n = reader.read(cs)) > 0;) {
                buf.append(new String(cs, 0, n));
            }

            ObjectNode objectNode = (ObjectNode) JsonUtils.getObjectMapper().readTree(buf.toString());

            processTask(writer, objectNode, context);
        } else if (contentType != null && contentType.contains(XML_TOKEN)) {
            Document document = getXmlDocumentBuilder(context)
                    .loadDocument(new InputStreamResource(in, request.getRequestURI()));

            writer.append("<?xml version=\"1.0\" encoding=\"" + Constants.DEFAULT_CHARSET + "\"?>\n");
            writer.append("<result>\n");

            Writer escapeWriter = new XmlEscapeWriter(writer);
            for (Element element : DomUtils.getChildElements(document.getDocumentElement())) {
                writer.append("<request>\n");
                writer.append("<response type=\"json\"><![CDATA[\n");
                writer.setEscapeEnabled(true);

                String textContent = DomUtils.getTextContent(element);

                ObjectNode objectNode = (ObjectNode) JsonUtils.getObjectMapper().readTree(textContent);
                try {
                    processTask(escapeWriter, objectNode, context);
                    writer.setEscapeEnabled(false);

                    writer.append("\n]]></response>\n");
                } catch (Exception e) {
                    Throwable t = e;
                    while (t.getCause() != null) {
                        t = t.getCause();
                    }
                    writer.setEscapeEnabled(false);

                    writer.append("\n]]></response>\n");
                    if (t instanceof ClientRunnableException) {
                        writer.append("<exception type=\"runnable\"><![CDATA[");
                        writer.setEscapeEnabled(true);
                        writer.append("(function(){").append(((ClientRunnableException) t).getScript())
                                .append("})");
                    } else {
                        writer.append("<exception><![CDATA[\n");
                        writer.setEscapeEnabled(true);
                        outputException(jsonBuilder, e);
                    }
                    writer.setEscapeEnabled(false);
                    writer.append("\n]]></exception>\n");
                    logger.error(e, e);
                }
                writer.append("</request>\n");
            }

            writer.append("</result>");
        }
    } catch (Exception e) {
        in.close();

        Throwable t = e;
        while (t.getCause() != null) {
            t = t.getCause();
        }

        if (t instanceof ClientRunnableException) {
            response.setContentType("text/runnable");
            writer.append("(function(){").append(((ClientRunnableException) t).getScript()).append("})");
        } else {
            response.setContentType("text/dorado-exception");
            outputException(jsonBuilder, e);
        }

        logger.error(e, e);
    } finally {
        writer.flush();
        writer.close();
    }
}

From source file:haven.Utils.java

public static <C> C hascause(Throwable t, Class<C> c) {
    while (t != null) {
        if (c.isInstance(t))
            return (c.cast(t));
        t = t.getCause();
    }//from w  ww  .j av a2s  .  c o m
    return (null);
}

From source file:hudson.Util.java

/**
 * Extracts the Win32 error message from {@link Throwable} if possible.
 *
 * @return/* w ww. j a v a 2 s  .c  o m*/
 *      null if there seems to be no error code or if the platform is not Win32.
 */
public static String getWin32ErrorMessage(Throwable e) {
    String msg = e.getMessage();
    if (msg != null) {
        Matcher m = errorCodeParser.matcher(msg);
        if (m.matches()) {
            try {
                ResourceBundle rb = ResourceBundle.getBundle("/hudson/win32errors");
                return rb.getString("error" + m.group(1));
            } catch (Exception _) {
                // silently recover from resource related failures
            }
        }
    }

    if (e.getCause() != null)
        return getWin32ErrorMessage(e.getCause());
    return null; // no message
}