001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache license, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the license for the specific language governing permissions and
015 * limitations under the license.
016 */
017package org.apache.logging.log4j.core.util;
018
019import java.io.IOException;
020import java.io.InterruptedIOException;
021import java.io.LineNumberReader;
022import java.io.PrintWriter;
023import java.io.StringReader;
024import java.io.StringWriter;
025import java.util.ArrayList;
026import java.util.List;
027
028/**
029 * Helps with Throwable objects.
030 */
031public final class Throwables {
032
033    private Throwables() {
034    }
035
036    /**
037     * Returns the deepest cause of the given {@code throwable}.
038     *
039     * @param throwable the throwable to navigate
040     * @return the deepest throwable or the given throwable
041     */
042    public static Throwable getRootCause(final Throwable throwable) {
043
044        // Keep a second pointer that slowly walks the causal chain. If the fast
045        // pointer ever catches the slower pointer, then there's a loop.
046        Throwable slowPointer = throwable;
047        boolean advanceSlowPointer = false;
048
049        Throwable parent = throwable;
050        Throwable cause;
051        while ((cause = parent.getCause()) != null) {
052            parent = cause;
053            if (parent == slowPointer) {
054                throw new IllegalArgumentException("loop in causal chain");
055            }
056            if (advanceSlowPointer) {
057                slowPointer = slowPointer.getCause();
058            }
059            advanceSlowPointer = !advanceSlowPointer; // only advance every other iteration
060        }
061        return parent;
062
063    }
064
065    /**
066     * Converts a Throwable stack trace into a List of Strings.
067     *
068     * @param throwable the Throwable
069     * @return a List of Strings
070     */
071    public static List<String> toStringList(final Throwable throwable) {
072        final StringWriter sw = new StringWriter();
073        final PrintWriter pw = new PrintWriter(sw);
074        try {
075            throwable.printStackTrace(pw);
076        } catch (final RuntimeException ex) {
077            // Ignore any exceptions.
078        }
079        pw.flush();
080        final List<String> lines = new ArrayList<>();
081        final LineNumberReader reader = new LineNumberReader(new StringReader(sw.toString()));
082        try {
083            String line = reader.readLine();
084            while (line != null) {
085                lines.add(line);
086                line = reader.readLine();
087            }
088        } catch (final IOException ex) {
089            if (ex instanceof InterruptedIOException) {
090                Thread.currentThread().interrupt();
091            }
092            lines.add(ex.toString());
093        } finally {
094            Closer.closeSilently(reader);
095        }
096        return lines;
097    }
098
099    /**
100     * Rethrows a {@link Throwable}.
101     *
102     * @param t the Throwable to throw.
103     * @since 2.1
104     */
105    public static void rethrow(final Throwable t) {
106        Throwables.<RuntimeException>rethrow0(t);
107    }
108
109    @SuppressWarnings("unchecked")
110    private static <T extends Throwable> void rethrow0(final Throwable t) throws T {
111        throw (T) t;
112    }
113}