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.helpers;
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 class Throwables {
032
033    /**
034     * Converts a Throwable into a List of Strings
035     * 
036     * @param throwable
037     *            the Throwable
038     * @return a List of Strings
039     */
040    public static List<String> toStringList(final Throwable throwable) {
041        final StringWriter sw = new StringWriter();
042        final PrintWriter pw = new PrintWriter(sw);
043        try {
044            throwable.printStackTrace(pw);
045        } catch (final RuntimeException ex) {
046            // Ignore any exceptions.
047        }
048        pw.flush();
049        final LineNumberReader reader = new LineNumberReader(new StringReader(sw.toString()));
050        final ArrayList<String> lines = new ArrayList<String>();
051        try {
052            String line = reader.readLine();
053            while (line != null) {
054                lines.add(line);
055                line = reader.readLine();
056            }
057        } catch (final IOException ex) {
058            if (ex instanceof InterruptedIOException) {
059                Thread.currentThread().interrupt();
060            }
061            lines.add(ex.toString());
062        }
063        return lines;
064    }
065
066}