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:org.lol.reddit.cache.CacheDownload.java

private void performDownload(final HttpClient httpClient, final HttpRequestBase httpRequest) {

    if (mInitiator.isJson)
        httpRequest.setHeader("Accept-Encoding", "gzip");

    final HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, mInitiator.getCookies());

    final HttpResponse response;
    final StatusLine status;

    try {/*from ww  w . j a v a2s  . c om*/
        if (mCancelled) {
            mInitiator.notifyFailure(RequestFailureType.CANCELLED, null, null, "Cancelled");
            return;
        }
        response = httpClient.execute(httpRequest, localContext);
        status = response.getStatusLine();

    } catch (Throwable t) {

        if (t.getCause() != null && t.getCause() instanceof RedirectException
                && httpRequest.getURI().getHost().endsWith("reddit.com")) {

            mInitiator.notifyFailure(RequestFailureType.REDDIT_REDIRECT, t, null,
                    "Unable to open a connection");
        } else {
            mInitiator.notifyFailure(RequestFailureType.CONNECTION, t, null, "Unable to open a connection");
        }
        return;
    }

    if (status.getStatusCode() != 200) {
        mInitiator.notifyFailure(RequestFailureType.REQUEST, null, status,
                String.format("HTTP error %d (%s)", status.getStatusCode(), status.getReasonPhrase()));
        return;
    }

    if (mCancelled) {
        mInitiator.notifyFailure(RequestFailureType.CANCELLED, null, null, "Cancelled");
        return;
    }

    final HttpEntity entity = response.getEntity();

    if (entity == null) {
        mInitiator.notifyFailure(RequestFailureType.CONNECTION, null, status,
                "Did not receive a valid HTTP response");
        return;
    }

    final InputStream is;

    final String mimetype;
    try {
        is = entity.getContent();
        mimetype = entity.getContentType() == null ? null : entity.getContentType().getValue();
    } catch (Throwable t) {
        t.printStackTrace();
        mInitiator.notifyFailure(RequestFailureType.CONNECTION, t, status, "Could not open an input stream");
        return;
    }

    final NotifyOutputStream cacheOs;
    final CacheManager.WritableCacheFile cacheFile;
    if (mInitiator.cache) {
        try {
            cacheFile = manager.openNewCacheFile(mInitiator, session, mimetype);
            cacheOs = cacheFile.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
            mInitiator.notifyFailure(RequestFailureType.STORAGE, e, null, "Could not access the local cache");
            return;
        }
    } else {
        cacheOs = null;
        cacheFile = null;
    }

    final long contentLength = entity.getContentLength();

    if (mInitiator.isJson) {

        final InputStream bis;

        if (mInitiator.cache) {

            bis = new BufferedInputStream(
                    new CachingInputStream(is, cacheOs, new CachingInputStream.BytesReadListener() {
                        public void onBytesRead(final long total) {
                            mInitiator.notifyProgress(total, contentLength);
                        }
                    }), 8 * 1024);

        } else {
            bis = new BufferedInputStream(is, 8 * 1024);
        }

        final JsonValue value;

        try {
            value = new JsonValue(bis);

            synchronized (this) {
                mInitiator.notifyJsonParseStarted(value, RRTime.utcCurrentTimeMillis(), session, false);
            }

            value.buildInThisThread();

        } catch (Throwable t) {
            t.printStackTrace();
            mInitiator.notifyFailure(RequestFailureType.PARSE, t, null, "Error parsing the JSON stream");
            return;
        }

        if (mInitiator.cache && cacheFile != null) {
            try {
                mInitiator.notifySuccess(cacheFile.getReadableCacheFile(), RRTime.utcCurrentTimeMillis(),
                        session, false, mimetype);
            } catch (IOException e) {
                if (e.getMessage().contains("ENOSPC")) {
                    mInitiator.notifyFailure(RequestFailureType.DISK_SPACE, e, null, "Out of disk space");
                } else {
                    mInitiator.notifyFailure(RequestFailureType.STORAGE, e, null, "Cache file not found");
                }
            }
        }

    } else {

        if (!mInitiator.cache) {
            BugReportActivity.handleGlobalError(mInitiator.context, "Cache disabled for non-JSON request");
            return;
        }

        try {
            final byte[] buf = new byte[8 * 1024];

            int bytesRead;
            long totalBytesRead = 0;
            while ((bytesRead = is.read(buf)) > 0) {
                totalBytesRead += bytesRead;
                cacheOs.write(buf, 0, bytesRead);
                mInitiator.notifyProgress(totalBytesRead, contentLength);
            }

            cacheOs.flush();
            cacheOs.close();

            try {
                mInitiator.notifySuccess(cacheFile.getReadableCacheFile(), RRTime.utcCurrentTimeMillis(),
                        session, false, mimetype);
            } catch (IOException e) {
                if (e.getMessage().contains("ENOSPC")) {
                    mInitiator.notifyFailure(RequestFailureType.DISK_SPACE, e, null, "Out of disk space");
                } else {
                    mInitiator.notifyFailure(RequestFailureType.STORAGE, e, null, "Cache file not found");
                }
            }

        } catch (IOException e) {

            if (e.getMessage() != null && e.getMessage().contains("ENOSPC")) {
                mInitiator.notifyFailure(RequestFailureType.STORAGE, e, null, "Out of disk space");

            } else {
                e.printStackTrace();
                mInitiator.notifyFailure(RequestFailureType.CONNECTION, e, null,
                        "The connection was interrupted");
            }

        } catch (Throwable t) {
            t.printStackTrace();
            mInitiator.notifyFailure(RequestFailureType.CONNECTION, t, null, "The connection was interrupted");
        }
    }
}

From source file:airbrake.Backtrace.java

private void toBacktrace(final Throwable throwable) {
    if (throwable == null)
        return;/*ww w  .j a v a 2 s .  c  o  m*/

    backtrace.add(causedBy(throwable));
    for (final StackTraceElement element : throwable.getStackTrace()) {
        backtrace.add(toBacktrace(element));
    }

    toBacktrace(throwable.getCause());
}

From source file:net.sourceforge.vulcan.web.struts.MockApplicationContextStrutsTestCase.java

@Override
public final void actionPerform() {
    resultForward = null;/*from w  ww . j av a  2 s .  com*/
    try {
        super.actionPerform();
    } catch (UncaughtExceptionError e) {
        final Throwable cause = e.getCause();
        if (cause instanceof ServletException) {
            final Throwable seCause = cause.getCause();
            if (seCause instanceof RuntimeException) {
                throw (RuntimeException) seCause;
            } else if (seCause != null) {
                throw new RuntimeException(seCause);
            }
        } else if (cause instanceof RuntimeException) {
            throw (RuntimeException) cause;
        }
        throw e;
    }
}

From source file:com.evolveum.midpoint.web.component.search.Search.java

private String createErrorMessage(Exception ex) {
    StringBuilder sb = new StringBuilder();

    Throwable t = ex;
    while (t != null) {
        sb.append(t.getMessage()).append('\n');
        t = t.getCause();
    }/*  ww w  . ja v  a  2  s  . c  o m*/

    return sb.toString();
}

From source file:com.jkoolcloud.tnt4j.utils.Utils.java

/**
 * Generates a detailed description of an exception, including stack trace
 * of both the exception and the underlying root cause of the exception, if
 * any.//from www.  j  av  a 2  s  .  c o  m
 *
 * @param ex
 *            exception to process
 * @return String representation of exception
 * @see #getStackTrace(Throwable)
 */
public static String getExceptionDetail(Throwable ex) {
    if (ex == null)
        return "";

    String detail = getStackTrace(ex);

    // find the root cause of exception
    Throwable rootCause = null;
    for (;;) {
        Throwable cause = ex.getCause();
        if (cause == null) {
            try {
                Method method = ex.getClass().getMethod("getTargetException", (Class[]) null);
                Object target = method.invoke(ex, (Object[]) null);
                if (target instanceof Throwable)
                    cause = (Throwable) target;
            } catch (Exception exx) {
            }
        }

        if (cause == null)
            break;

        ex = cause;
        rootCause = cause;
    }

    if (rootCause != null)
        detail += LINE_FEED + "Root cause:" + LINE_FEED + getStackTrace(rootCause);

    return detail;
}

From source file:org.jetbrains.webdemo.executors.ThrowableSerializer.java

@Override
public void serialize(Throwable throwable, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
        throws IOException, JsonProcessingException {
    jsonGenerator.writeStartObject();/*from  ww  w  .j a v  a2s  .  c o  m*/
    jsonGenerator.writeStringField("message", throwable.getMessage());
    jsonGenerator.writeStringField("fullName", throwable.getClass().getName());
    jsonGenerator.writeObjectField("stackTrace", throwable.getStackTrace());
    jsonGenerator.writeObjectField("cause", throwable.getCause() != throwable ? throwable.getCause() : null);
    jsonGenerator.writeEndObject();
}

From source file:com.mm.yamingapp.core.MethodDescriptor.java

/**
 * Invokes the call that belongs to this object with the given parameters. Wraps the response
 * (possibly an exception) in a JSONObject.
 * /*from   w w  w.j  a  v  a2  s  .com*/
 * @param parameters
 *          {@code JSONArray} containing the parameters
 * @return result
 * @throws Throwable
 */
public Object invoke(Object obj, final JSONArray parameters) throws Throwable {
    final Type[] parameterTypes = getGenericParameterTypes();
    final Object[] args = new Object[parameterTypes.length];
    final Annotation annotations[][] = getParameterAnnotations();

    if (parameters.length() > args.length) {
        throw new RpcError("Too many parameters specified.");
    }

    for (int i = 0; i < args.length; i++) {
        final Type parameterType = parameterTypes[i];
        if (i < parameters.length()) {
            args[i] = convertParameter(parameters, i, parameterType);
        } else if (MethodDescriptor.hasDefaultValue(annotations[i])) {
            args[i] = MethodDescriptor.getDefaultValue(parameterType, annotations[i]);
        } else {
            throw new RpcError("Argument " + (i + 1) + " is not present");
        }
    }

    Object result = null;
    try {
        result = mMethod.invoke(obj, args);
    } catch (Throwable t) {
        throw t.getCause();
    }
    return result;
}

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

private boolean exceptionContainsText(Throwable ex, String text) {
    while (ex != null) {
        if (ex.getMessage() != null && ex.getMessage().contains(text)) {
            return true;
        }/*from   w  ww. j a v a2  s  . com*/
        ex = ex.getCause();
    }
    return false;
}

From source file:fedora.server.security.servletfilters.xmluserfile.ParserXmlUserfile.java

public ParserXmlUserfile(InputStream xmlStream) throws IOException {
    log.debug(this.getClass().getName() + ".init<> " + " begin");

    m_xmlStream = xmlStream;/*from  www. j  a v  a 2  s. c  om*/
    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        log.debug(this.getClass().getName() + ".init<> " + " after newInstance");
        spf.setNamespaceAware(true);
        log.debug(this.getClass().getName() + ".init<> " + " after setNamespaceAware");
        m_parser = spf.newSAXParser();
        log.debug(this.getClass().getName() + ".init<> " + " after newSAXParser");
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException("Error getting XML parser: " + e.getMessage());
    } catch (Throwable t) {
        log.fatal(this.getClass().getName() + ".init<> " + " caught me throwable");
        t.printStackTrace();
        log.fatal(this.getClass().getName() + ".populateCacheElement() " + t);
        log.fatal(this.getClass().getName() + ".populateCacheElement() " + t.getMessage() + " "
                + (t.getCause() == null ? "" : t.getCause().getMessage()));
    }
}

From source file:be.fgov.kszbcss.rhq.websphere.connector.FailFastInvocationHandler.java

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (lastConnectorNotAvailableException != -1
            && System.currentTimeMillis() - lastConnectorNotAvailableException > 120000) {
        log.debug("Resetting lastConnectorNotAvailableException");
        lastConnectorNotAvailableException = -1;
    }//from w ww .  j  a  va2 s . c o m
    if (lastConnectorNotAvailableException == -1) {
        try {
            return method.invoke(target, args);
        } catch (InvocationTargetException invocationTargetException) {
            Throwable exception = invocationTargetException.getCause();
            Throwable t = exception;
            do {
                if (log.isDebugEnabled()) {
                    log.debug("cause = " + t.getClass().getName());
                }
                if (t instanceof ConnectorNotAvailableException) {
                    lastConnectorNotAvailableException = System.currentTimeMillis();
                    break;
                }
                t = t.getCause();
            } while (t != null);
            if (log.isDebugEnabled()) {
                if (lastConnectorNotAvailableException == -1) {
                    log.debug("Not setting lastConnectorNotAvailableException");
                } else {
                    log.debug("Setting lastConnectorNotAvailableException");
                }
            }
            throw exception;
        }
    } else {
        throw new ConnectorNotAvailableException(
                "The connector has been temporarily marked as unavailable because of a previous ConnectorNotAvailableException");
    }
}