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:edu.washington.cs.mystatus.odk.utilities.WebUtils.java

/**
 * Common method for returning a parsed xml document given a url and the
 * http context and client objects involved in the web connection.
 *
 * @param urlString/*from w ww .ja va  2 s . c o  m*/
 * @param localContext
 * @param httpclient
 * @return
 */
public static DocumentFetchResult getXmlDocument(String urlString, HttpContext localContext,
        HttpClient httpclient) {
    URI u = null;
    try {
        URL url = new URL(urlString);
        u = url.toURI();
    } catch (Exception e) {
        e.printStackTrace();
        return new DocumentFetchResult(e.getLocalizedMessage()
                // + app.getString(R.string.while_accessing) + urlString);
                + ("while accessing") + urlString, 0);
    }

    if (u.getHost() == null) {
        return new DocumentFetchResult("Invalid server URL (no hostname): " + urlString, 0);
    }

    // if https then enable preemptive basic auth...
    if (u.getScheme().equals("https")) {
        enablePreemptiveBasicAuth(localContext, u.getHost());
    }

    // set up request...
    HttpGet req = WebUtils.createOpenRosaHttpGet(u);

    HttpResponse response = null;
    try {
        response = httpclient.execute(req, localContext);
        int statusCode = response.getStatusLine().getStatusCode();

        HttpEntity entity = response.getEntity();

        if (statusCode != HttpStatus.SC_OK) {
            WebUtils.discardEntityBytes(response);
            if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
                // clear the cookies -- should not be necessary?
                MyStatus.getInstance().getCookieStore().clear();
            }
            String webError = response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")";

            return new DocumentFetchResult(u.toString() + " responded with: " + webError, statusCode);
        }

        if (entity == null) {
            String error = "No entity body returned from: " + u.toString();
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }

        if (!entity.getContentType().getValue().toLowerCase(Locale.ENGLISH)
                .contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML)) {
            WebUtils.discardEntityBytes(response);
            String error = "ContentType: " + entity.getContentType().getValue() + " returned from: "
                    + u.toString()
                    + " is not text/xml.  This is often caused a network proxy.  Do you need to login to your network?";
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }
        // parse response
        Document doc = null;
        try {
            InputStream is = null;
            InputStreamReader isr = null;
            try {
                is = entity.getContent();
                isr = new InputStreamReader(is, "UTF-8");
                doc = new Document();
                KXmlParser parser = new KXmlParser();
                parser.setInput(isr);
                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
                doc.parse(parser);
                isr.close();
                isr = null;
            } finally {
                if (isr != null) {
                    try {
                        // ensure stream is consumed...
                        final long count = 1024L;
                        while (isr.skip(count) == count)
                            ;
                    } catch (Exception e) {
                        // no-op
                    }
                    try {
                        isr.close();
                    } catch (Exception e) {
                        // no-op
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (Exception e) {
                        // no-op
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            String error = "Parsing failed with " + e.getMessage() + "while accessing " + u.toString();
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }

        boolean isOR = false;
        Header[] fields = response.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER);
        if (fields != null && fields.length >= 1) {
            isOR = true;
            boolean versionMatch = false;
            boolean first = true;
            StringBuilder b = new StringBuilder();
            for (Header h : fields) {
                if (WebUtils.OPEN_ROSA_VERSION.equals(h.getValue())) {
                    versionMatch = true;
                    break;
                }
                if (!first) {
                    b.append("; ");
                }
                first = false;
                b.append(h.getValue());
            }
            if (!versionMatch) {
                Log.w(t, WebUtils.OPEN_ROSA_VERSION_HEADER + " unrecognized version(s): " + b.toString());
            }
        }
        return new DocumentFetchResult(doc, isOR);
    } catch (Exception e) {
        clearHttpConnectionManager();
        e.printStackTrace();
        String cause;
        Throwable c = e;
        while (c.getCause() != null) {
            c = c.getCause();
        }
        cause = c.toString();
        String error = "Error: " + cause + " while accessing " + u.toString();

        Log.w(t, error);
        return new DocumentFetchResult(error, 0);
    }
}

From source file:hudson.UtilTest.java

/** Returns all classes in the exception hierarchy. */
private static Iterable<Class<?>> calcExceptionHierarchy(Throwable t) {
    final List<Class<?>> result = Lists.newArrayList();
    for (; t != null; t = t.getCause())
        result.add(t.getClass());//from   ww w. j a va2  s . c  om
    return result;
}

From source file:fr.cph.chicago.util.Util.java

public static void handleConnectOrParserException(@NonNull final Throwable throwable,
        @Nullable final Activity activity, @Nullable final View connectView, @NonNull final View parserView) {
    if (throwable.getCause() instanceof ConnectException) {
        if (activity != null) {
            showNetworkErrorMessage(activity);
        } else if (connectView != null) {
            showNetworkErrorMessage(connectView);
        }/*ww w.jav a  2 s  .c  o  m*/
    } else if (throwable.getCause() instanceof ParserException) {
        showOopsSomethingWentWrong(parserView);
    }
}

From source file:com.ibm.jaql.util.BaseUtil.java

public static Throwable getRootCause(Throwable e) {
    while (e.getCause() != null) {
        e = e.getCause();//from  ww  w  . java2s . c  o  m
    }
    return e;
}

From source file:com.almende.eve.protocol.jsonrpc.JSONRpc.java

/**
 * Retrieve a description of an error.//from  w ww .j  a v a2 s. com
 * 
 * @param error
 *            the error
 * @return message String with the error description of the cause
 */
private static String getMessage(final Throwable error) {
    Throwable cause = error;
    while (cause.getCause() != null) {
        cause = cause.getCause();
    }
    return cause.toString();
}

From source file:org.koboc.collect.android.utilities.WebUtils.java

/**
 * Common method for returning a parsed xml document given a url and the
 * http context and client objects involved in the web connection.
 *
 * @param urlString/* ww w .j a v a 2s  .  co m*/
 * @param localContext
 * @param httpclient
 * @return
 */
public static DocumentFetchResult getXmlDocument(String urlString, HttpContext localContext,
        HttpClient httpclient) {
    URI u = null;
    try {
        URL url = new URL(urlString);
        u = url.toURI();
    } catch (Exception e) {
        e.printStackTrace();
        return new DocumentFetchResult(e.getLocalizedMessage()
                // + app.getString(R.string.while_accessing) + urlString);
                + ("while accessing") + urlString, 0);
    }

    if (u.getHost() == null) {
        return new DocumentFetchResult("Invalid server URL (no hostname): " + urlString, 0);
    }

    // if https then enable preemptive basic auth...
    if (u.getScheme().equals("https")) {
        enablePreemptiveBasicAuth(localContext, u.getHost());
    }

    // set up request...
    HttpGet req = WebUtils.createOpenRosaHttpGet(u);

    HttpResponse response = null;
    try {

        response = httpclient.execute(req, localContext);
        int statusCode = response.getStatusLine().getStatusCode();

        HttpEntity entity = response.getEntity();

        if (statusCode != HttpStatus.SC_OK) {
            WebUtils.discardEntityBytes(response);
            if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
                // clear the cookies -- should not be necessary?
                Collect.getInstance().getCookieStore().clear();
            }
            String webError = response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")";

            return new DocumentFetchResult(u.toString() + " responded with: " + webError, statusCode);
        }

        if (entity == null) {
            String error = "No entity body returned from: " + u.toString();
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }

        if (!entity.getContentType().getValue().toLowerCase(Locale.ENGLISH)
                .contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML)) {
            WebUtils.discardEntityBytes(response);
            String error = "ContentType: " + entity.getContentType().getValue() + " returned from: "
                    + u.toString()
                    + " is not text/xml.  This is often caused a network proxy.  Do you need to login to your network?";
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }
        // parse response
        Document doc = null;
        try {
            InputStream is = null;
            InputStreamReader isr = null;
            try {
                is = entity.getContent();
                isr = new InputStreamReader(is, "UTF-8");
                doc = new Document();
                KXmlParser parser = new KXmlParser();
                parser.setInput(isr);
                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
                doc.parse(parser);
                isr.close();
                isr = null;
            } finally {
                if (isr != null) {
                    try {
                        // ensure stream is consumed...
                        final long count = 1024L;
                        while (isr.skip(count) == count)
                            ;
                    } catch (Exception e) {
                        // no-op
                    }
                    try {
                        isr.close();
                    } catch (Exception e) {
                        // no-op
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (Exception e) {
                        // no-op
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            String error = "Parsing failed with " + e.getMessage() + "while accessing " + u.toString();
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }

        boolean isOR = false;
        Header[] fields = response.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER);
        if (fields != null && fields.length >= 1) {
            isOR = true;
            boolean versionMatch = false;
            boolean first = true;
            StringBuilder b = new StringBuilder();
            for (Header h : fields) {
                if (WebUtils.OPEN_ROSA_VERSION.equals(h.getValue())) {
                    versionMatch = true;
                    break;
                }
                if (!first) {
                    b.append("; ");
                }
                first = false;
                b.append(h.getValue());
            }
            if (!versionMatch) {
                Log.w(t, WebUtils.OPEN_ROSA_VERSION_HEADER + " unrecognized version(s): " + b.toString());
            }
        }
        return new DocumentFetchResult(doc, isOR);
    } catch (Exception e) {
        clearHttpConnectionManager();
        e.printStackTrace();
        String cause;
        Throwable c = e;
        while (c.getCause() != null) {
            c = c.getCause();
        }
        cause = c.toString();
        String error = "Error: " + cause + " while accessing " + u.toString();

        Log.w(t, error);
        return new DocumentFetchResult(error, 0);
    }
}

From source file:cd.education.data.collector.android.utilities.WebUtils.java

/**
 * Common method for returning a parsed xml document given a url and the
 * http context and client objects involved in the web connection.
 *
 * @param urlString/*from  w w w.j a  v  a2  s  .  c o  m*/
 * @param localContext
 * @param httpclient
 * @return
 */
public static DocumentFetchResult getXmlDocument(String urlString, HttpContext localContext,
        HttpClient httpclient) {
    URI u = null;
    try {
        URL url = new URL(urlString);
        u = url.toURI();
    } catch (Exception e) {
        e.printStackTrace();
        return new DocumentFetchResult(e.getLocalizedMessage()
                // + app.getString(R.string.while_accessing) + urlString);
                + ("while accessing") + urlString, 0);
    }

    if (u.getHost() == null) {
        return new DocumentFetchResult("Invalid server URL (no hostname): " + urlString, 0);
    }

    // if https then enable preemptive basic auth...
    if (u.getScheme().equals("https")) {
        enablePreemptiveBasicAuth(localContext, u.getHost());
    }

    // set up request...
    HttpGet req = WebUtils.createOpenRosaHttpGet(u);
    req.addHeader(WebUtils.ACCEPT_ENCODING_HEADER, WebUtils.GZIP_CONTENT_ENCODING);

    HttpResponse response = null;
    try {
        response = httpclient.execute(req, localContext);
        int statusCode = response.getStatusLine().getStatusCode();

        HttpEntity entity = response.getEntity();

        if (statusCode != HttpStatus.SC_OK) {
            WebUtils.discardEntityBytes(response);
            if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
                // clear the cookies -- should not be necessary?
                Collect.getInstance().getCookieStore().clear();
            }
            String webError = response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")";

            return new DocumentFetchResult(u.toString() + " responded with: " + webError, statusCode);
        }

        if (entity == null) {
            String error = "No entity body returned from: " + u.toString();
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }

        if (!entity.getContentType().getValue().toLowerCase(Locale.ENGLISH)
                .contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML)) {
            WebUtils.discardEntityBytes(response);
            String error = "ContentType: " + entity.getContentType().getValue() + " returned from: "
                    + u.toString()
                    + " is not text/xml.  This is often caused a network proxy.  Do you need to login to your network?";
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }
        // parse response
        Document doc = null;
        try {
            InputStream is = null;
            InputStreamReader isr = null;
            try {
                is = entity.getContent();
                Header contentEncoding = entity.getContentEncoding();
                if (contentEncoding != null
                        && contentEncoding.getValue().equalsIgnoreCase(WebUtils.GZIP_CONTENT_ENCODING)) {
                    is = new GZIPInputStream(is);
                }
                isr = new InputStreamReader(is, "UTF-8");
                doc = new Document();
                KXmlParser parser = new KXmlParser();
                parser.setInput(isr);
                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
                doc.parse(parser);
                isr.close();
                isr = null;
            } finally {
                if (isr != null) {
                    try {
                        // ensure stream is consumed...
                        final long count = 1024L;
                        while (isr.skip(count) == count)
                            ;
                    } catch (Exception e) {
                        // no-op
                    }
                    try {
                        isr.close();
                    } catch (Exception e) {
                        // no-op
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (Exception e) {
                        // no-op
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            String error = "Parsing failed with " + e.getMessage() + "while accessing " + u.toString();
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }

        boolean isOR = false;
        Header[] fields = response.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER);
        if (fields != null && fields.length >= 1) {
            isOR = true;
            boolean versionMatch = false;
            boolean first = true;
            StringBuilder b = new StringBuilder();
            for (Header h : fields) {
                if (WebUtils.OPEN_ROSA_VERSION.equals(h.getValue())) {
                    versionMatch = true;
                    break;
                }
                if (!first) {
                    b.append("; ");
                }
                first = false;
                b.append(h.getValue());
            }
            if (!versionMatch) {
                Log.w(t, WebUtils.OPEN_ROSA_VERSION_HEADER + " unrecognized version(s): " + b.toString());
            }
        }
        return new DocumentFetchResult(doc, isOR);
    } catch (Exception e) {
        clearHttpConnectionManager();
        e.printStackTrace();
        String cause;
        Throwable c = e;
        while (c.getCause() != null) {
            c = c.getCause();
        }
        cause = c.toString();
        String error = "Error: " + cause + " while accessing " + u.toString();

        Log.w(t, error);
        return new DocumentFetchResult(error, 0);
    }
}

From source file:at.ac.univie.isc.asio.insight.VndError.java

/**
 * Create an ordered list of the causal chain of errors leading up to the given top level error.
 *
 * @param top top most exception in chain
 * @return full causal chain of exceptions
 *//*from   w w w.j  a  v a 2  s.c o m*/
private static List<ErrorChainElement> collectCausalChain(final Throwable top) {
    final Set<Throwable> seen = Sets.newIdentityHashSet();
    final ImmutableList.Builder<ErrorChainElement> chain = ImmutableList.builder();
    Throwable current = top;
    while (current != null) {
        if (!seen.add(current)) {
            final ErrorChainElement element = ErrorChainElement.from(circularPlaceholder(current));
            chain.add(element);
            break; // circular reference in chain
        }
        final ErrorChainElement element = ErrorChainElement.from(current);
        chain.add(element);
        current = current.getCause();
    }
    return chain.build();
}

From source file:org.LexGrid.LexBIG.caCore.client.proxy.LexEVSApplicationServiceProxy.java

public static Exception digOutRealExceptionAndThrowIt(Exception e) throws Exception {
    Throwable lbiEx = null;/*from  w ww  . j av  a  2  s  . c o m*/
    Throwable next = null;
    Throwable cur = e;
    boolean lexBigExceptionFound = false;
    boolean done = false;
    int i = 1;
    int max = 500; // a limit so we won't ever be in endless loop
    if (isLexBigException(cur) == true) {
        lexBigExceptionFound = true;
        lbiEx = cur;
    }
    while (!done) {
        next = cur.getCause();
        ++i;
        if (next == null) {
            done = true;
        } else {
            cur = next;
            if (isLexBigException(cur) == true) {
                lexBigExceptionFound = true;
                lbiEx = cur;
            }
            if (i == max) {
                done = true;
                log.error("digOutRealExceptionAndThrowIt: reached max depth of: " + max);
            }
        }
    }
    Exception returnException = null;
    if (lexBigExceptionFound == true) {
        returnException = new LBException(lbiEx.getMessage());
        returnException.setStackTrace(lbiEx.getStackTrace());
    } else {
        returnException = e;
    }
    return returnException;
}

From source file:com.cisco.dvbu.ps.common.util.CompositeLogger.java

/**
 * log information about the passed exception
 * //  w w  w. j  a va2  s.  c  om
 * @param e exception to be logged (ignore if null)
 * @param logMessage detailed message to be logged (can be null). Contain 
 * additional information about the issue to help the developer in diagnosing 
 * the problem
 */
public static void logException(Throwable ex, String logMessage) {
    String prependMsg = CommonConstants.applicationErrorPrependMessage;
    Throwable e = ex;
    if (e == null) {
        if (logger.isErrorEnabled()) {
            logger.error(prependMsg + logMessage);
        }
        return;
    }

    // if exception is a soap fault exception then extract error message from message entry

    // if the exception is a remote exception, extract with cause and work
    // with that
    if (e instanceof RemoteException) {
        Throwable remoteCause = e.getCause();
        if (remoteCause != null) {
            e = remoteCause;
        }
    }

    String message = e.getMessage();
    if (message == null) {
        message = prependMsg + defaultMessage;
    }
    if (logMessage != null) {
        message = prependMsg + message + "\n" + logMessage;
    }

    Throwable cause = e.getCause();
    if (e instanceof CompositeException) {
        if (e instanceof ApplicationException || (cause != null && cause instanceof ApplicationException)) {
            if (logger.isWarnEnabled()) {
                logger.warn(message, e);
            }
        } else {
            if (logger.isErrorEnabled()) {
                logger.error(message, e);
            }
        }
    } else {
        if (logger.isErrorEnabled()) {
            logger.error(message, e);
        }
    }

}