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:net.opentsdb.tree.Branch.java

/**
 * Attempts to fetch the branch, it's leaves and all child branches.
 * The UID names for each leaf may also be loaded if configured.
 * @param tsdb The TSDB to use for storage access
 * @param branch_id ID of the branch to retrieve
 * @param load_leaf_uids Whether or not to load UID names for each leaf
 * @return A branch if found, null if it did not exist
 * @throws JSONException if the object could not be deserialized
 *///from  ww w. j  ava  2s. c  om
public static Deferred<Branch> fetchBranch(final TSDB tsdb, final byte[] branch_id,
        final boolean load_leaf_uids) {

    final Deferred<Branch> result = new Deferred<Branch>();
    final Scanner scanner = setupBranchScanner(tsdb, branch_id);

    // This is the branch that will be loaded with data from the scanner and
    // returned at the end of the process.
    final Branch branch = new Branch();

    // A list of deferreds to wait on for child leaf processing
    final ArrayList<Deferred<Object>> leaf_group = new ArrayList<Deferred<Object>>();

    /**
     * Exception handler to catch leaves with an invalid UID name due to a 
     * possible deletion. This will allow the scanner to keep loading valid
     * leaves and ignore problems. The fsck tool can be used to clean up
     * orphaned leaves. If we catch something other than an NSU, it will
     * re-throw the exception
     */
    final class LeafErrBack implements Callback<Object, Exception> {

        final byte[] qualifier;

        public LeafErrBack(final byte[] qualifier) {
            this.qualifier = qualifier;
        }

        @Override
        public Object call(final Exception e) throws Exception {
            Throwable ex = e;
            while (ex.getClass().equals(DeferredGroupException.class)) {
                ex = ex.getCause();
            }
            if (ex.getClass().equals(NoSuchUniqueId.class)) {
                LOG.debug("Invalid UID for leaf: " + idToString(qualifier) + " in branch: "
                        + idToString(branch_id), ex);
            } else {
                throw (Exception) ex;
            }
            return null;
        }

    }

    /**
     * Called after a leaf has been loaded successfully and adds the leaf
     * to the branch's leaf set. Also lazily initializes the leaf set if it 
     * hasn't been.
     */
    final class LeafCB implements Callback<Object, Leaf> {

        @Override
        public Object call(final Leaf leaf) throws Exception {
            if (leaf != null) {
                if (branch.leaves == null) {
                    branch.leaves = new HashMap<Integer, Leaf>();
                }
                branch.leaves.put(leaf.hashCode(), leaf);
            }
            return null;
        }

    }

    /**
     * Scanner callback executed recursively each time we get a set of data
     * from storage. This is responsible for determining what columns are 
     * returned and issuing requests to load leaf objects.
     * When the scanner returns a null set of rows, the method initiates the
     * final callback.
     */
    final class FetchBranchCB implements Callback<Object, ArrayList<ArrayList<KeyValue>>> {

        /**
         * Starts the scanner and is called recursively to fetch the next set of
         * rows from the scanner.
         * @return The branch if loaded successfully, null if the branch was not
         * found.
         */
        public Object fetchBranch() {
            return scanner.nextRows().addCallback(this);
        }

        /**
         * Loops through each row of the scanner results and parses out branch
         * definitions and child leaves.
         * @return The final branch callback if the scanner returns a null set
         */
        @Override
        public Object call(final ArrayList<ArrayList<KeyValue>> rows) throws Exception {
            if (rows == null) {
                if (branch.tree_id < 1 || branch.path == null) {
                    result.callback(null);
                } else {
                    result.callback(branch);
                }
                return null;
            }

            for (final ArrayList<KeyValue> row : rows) {
                for (KeyValue column : row) {

                    // matched a branch column
                    if (Bytes.equals(BRANCH_QUALIFIER, column.qualifier())) {
                        if (Bytes.equals(branch_id, column.key())) {

                            // it's *this* branch. We deserialize to a new object and copy
                            // since the columns could be in any order and we may get a 
                            // leaf before the branch
                            final Branch local_branch = JSON.parseToObject(column.value(), Branch.class);
                            branch.path = local_branch.path;
                            branch.display_name = local_branch.display_name;
                            branch.tree_id = Tree.bytesToId(column.key());

                        } else {
                            // it's a child branch
                            final Branch child = JSON.parseToObject(column.value(), Branch.class);
                            child.tree_id = Tree.bytesToId(column.key());
                            branch.addChild(child);
                        }
                        // parse out a leaf
                    } else if (Bytes.memcmp(Leaf.LEAF_PREFIX(), column.qualifier(), 0,
                            Leaf.LEAF_PREFIX().length) == 0) {
                        if (Bytes.equals(branch_id, column.key())) {
                            // process a leaf and skip if the UIDs for the TSUID can't be 
                            // found. Add an errback to catch NoSuchUniqueId exceptions
                            leaf_group.add(Leaf.parseFromStorage(tsdb, column, load_leaf_uids)
                                    .addCallbacks(new LeafCB(), new LeafErrBack(column.qualifier())));
                        } else {
                            // TODO - figure out an efficient way to increment a counter in 
                            // the child branch with the # of leaves it has
                        }
                    }
                }
            }

            // recursively call ourself to fetch more results from the scanner
            return fetchBranch();
        }
    }

    // start scanning
    new FetchBranchCB().fetchBranch();
    return result;
}

From source file:backtype.storm.utils.Utils.java

public static boolean exceptionCauseIsInstanceOf(Class klass, Throwable throwable) {
    Throwable t = throwable;
    while (t != null) {
        if (klass.isInstance(t)) {
            return true;
        }/*www  . j  a va2  s  .c o  m*/
        t = t.getCause();
    }
    return false;
}

From source file:main.java.vasolsim.common.GenericUtils.java

public static String exceptionToString(@Nonnull Throwable t) {
    StringBuilder out = new StringBuilder();
    out.append("Ex: ").append(t.toString()).append("\n");
    out.append("Cause: ").append(t.getCause()).append("\n");
    out.append("Message: ").append(t.getMessage()).append("\n\n");
    out.append("StackTrace:\n").append(ExceptionUtils.getStackTrace(t));
    out.append("---------- END ----------");

    return out.toString();
}

From source file:com.codelanx.codelanxlib.util.exception.Exceptions.java

/**
 * Recursive method for appending {@link Throwable] causes that are appended
 * to a {@link Throwable}//from  w  w w.ja v  a  2 s.c o m
 *
 * @since 0.1.0
 * @version 0.1.0
 *
 * @param sb The {@link StringBuilder} being appended to
 * @param t The {@link Throwable} root
 * @param causedTrace An array of already visited stack nodes
 */
private static void readableStackTraceAsCause(StringBuilder sb, Throwable t, StackTraceElement[] causedTrace) {
    // Compute number of frames in common between previous and caused
    StackTraceElement[] trace = t.getStackTrace();
    int m = trace.length - 1;
    int n = causedTrace.length - 1;
    while (m >= 0 && n >= 0 && trace[m].equals(causedTrace[n])) {
        m--;
        n--;
    }
    int common = trace.length - 1 - m;

    sb.append("Caused by: ").append(t).append('\n');
    for (int i = 0; i <= m; i++) {
        sb.append("\tat ").append(trace[i]).append('\n');
    }
    if (common != 0) {
        sb.append("\t... ").append(common).append(" more\n");
    }
    if (t.getCause() != null) {
        Exceptions.readableStackTraceAsCause(sb, t.getCause(), trace);
    }
}

From source file:cn.kk.exia.MangaDownloader.java

public static String download(final String url, final String to, final boolean overwrite, final Logger log)
        throws IOException {
    final File toFile = new File(to);
    // 925 -> forbidden file
    if (!overwrite && toFile.exists() && (toFile.length() > MangaDownloader.MIN_IMG_OK_BYTES)
            && (toFile.length() != 925)) {
        return null;
    } else {/*w  w  w .  j  a va  2 s  . c  om*/
        int retries = 0;
        DownloadThread test = null;
        while ((retries++ < 3) && !(test = new DownloadThread(to, url, log)).success) {
            try {
                test.start();
                test.join(60000);
                test.interrupt();
            } catch (final Throwable e) {
                try {
                    Thread.sleep((3 * MangaDownloader.sleepBase)
                            + (int) (Math.random() * 3 * MangaDownloader.sleepBase));
                } catch (InterruptedException e1) {
                    // ignore
                }
                if ((e instanceof RuntimeException) && (e.getCause() != null)) {
                    throw (IOException) e.getCause();
                }
            }
        }
        if ((test != null) && !test.success) {
            throw new IOException("" + to);
        }
        return to;
    }
}

From source file:de.codesourcery.eve.skills.market.impl.EveCentralMarketDataProvider.java

private static Map<InventoryType, PriceInfoQueryResult> runOnEventThread(final PriceCallable r)
        throws PriceInfoUnavailableException {
    if (SwingUtilities.isEventDispatchThread()) {
        return r.call();
    }/*from   w  ww . j  a  v  a2 s . c o  m*/

    final AtomicReference<Map<InventoryType, PriceInfoQueryResult>> result = new AtomicReference<Map<InventoryType, PriceInfoQueryResult>>();
    try {
        SwingUtilities.invokeAndWait(new Runnable() {

            @Override
            public void run() {
                try {
                    result.set(r.call());
                } catch (PriceInfoUnavailableException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    } catch (InvocationTargetException e) {
        Throwable wrapped = e.getTargetException();
        if (wrapped instanceof RuntimeException) {
            if (wrapped.getCause() instanceof PriceInfoUnavailableException) {
                throw (PriceInfoUnavailableException) wrapped.getCause();
            }
            throw (RuntimeException) wrapped;
        } else if (e.getTargetException() instanceof Error) {
            throw (Error) wrapped;
        }
        throw new RuntimeException(e.getTargetException());
    }
    return result.get();
}

From source file:com.amalto.webapp.core.util.Util.java

public static boolean causeIs(Throwable throwable, Class<?> cls) {
    Throwable currentCause = throwable;
    while (currentCause != null) {
        if (cls.isInstance(currentCause)) {
            return true;
        }/*from   w  w w  .  j a v  a2 s .  com*/
        currentCause = currentCause.getCause();
    }
    return false;
}

From source file:com.amalto.webapp.core.util.Util.java

public static <T> T cause(Throwable throwable, Class<T> cls) {
    Throwable currentCause = throwable;
    while (currentCause != null) {
        if (cls.isInstance(currentCause)) {
            return (T) currentCause;
        }/* ww  w. java  2s .  c o  m*/
        currentCause = currentCause.getCause();
    }
    return null;
}

From source file:cherry.sqlapp.controller.sqltool.LogicErrorUtil.java

private Throwable getRootCause(Throwable ex) {
    Throwable result = ex;
    while (result.getCause() != null) {
        result = result.getCause();// w ww.ja  v  a  2  s  .co  m
    }
    return result;
}

From source file:com.tesora.dve.mysqlapi.repl.MyReplicationVisitorDispatch.java

public static void executeLDR(ServerDBConnection serverDBConnection,
        final ChannelHandlerContext channelHandlerContext, final byte[] query) throws SQLException {
    final MysqlLoadDataInfileRequestCollector resultConsumer = new MysqlLoadDataInfileRequestCollector(
            channelHandlerContext);/*  w  w  w  .ja v a 2  s.c o m*/
    try {
        final NativeCharSet clientCharSet = MysqlNativeCharSet.UTF8;
        final SSConnection ssCon1 = serverDBConnection.getSSConn();
        Throwable t = ssCon1.executeInContext(new Callable<Throwable>() {
            public Throwable call() {
                try {
                    LoadDataRequestExecutor.execute(channelHandlerContext, ssCon1, resultConsumer,
                            clientCharSet.getJavaCharset(), query);
                } catch (Throwable e) {
                    return e;
                }
                return null;
            }
        });

        if (t != null && t.getCause() != null) {
            throw new PEException(t);
        }
        if (resultConsumer.getFileName() == null) {
            throw new SQLException(new PEException("Cannot handle load data statement: " + new String(query)));
        }
    } catch (Throwable t) {
        throw new SQLException(t);
    }
}