001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.classic.util;
015
016import java.lang.reflect.InvocationTargetException;
017import java.lang.reflect.Method;
018
019public class TestHelper {
020
021    private static final Method ADD_SUPPRESSED_METHOD;
022
023    static {
024        Method method = null;
025        try {
026            method = Throwable.class.getMethod("addSuppressed", Throwable.class);
027        } catch (NoSuchMethodException e) {
028            // ignore, will get thrown in Java < 7
029        }
030        ADD_SUPPRESSED_METHOD = method;
031    }
032
033    public static boolean suppressedSupported() {
034        return ADD_SUPPRESSED_METHOD != null;
035    }
036
037    public static void addSuppressed(Throwable outer, Throwable suppressed) throws InvocationTargetException, IllegalAccessException {
038        if (suppressedSupported()) {
039            ADD_SUPPRESSED_METHOD.invoke(outer, suppressed);
040        }
041    }
042
043    static public Throwable makeNestedException(int level) {
044        if (level == 0) {
045            return new Exception("nesting level=" + level);
046        }
047        Throwable cause = makeNestedException(level - 1);
048        return new Exception("nesting level =" + level, cause);
049    }
050
051    /**
052     * Usage:
053     * <pre>
054     * String s = "123";
055     * positionOf("1").in(s) < positionOf("3").in(s)
056     * </pre>
057     *
058     * @param pattern Plain text to be found
059     * @return StringPosition fluent interface
060     */
061    public static StringPosition positionOf(String pattern) {
062        return new StringPosition(pattern);
063    }
064
065    public static class StringPosition {
066        private final String pattern;
067
068        public StringPosition(String pattern) {
069            this.pattern = pattern;
070        }
071
072        public int in(String s) {
073            final int position = s.indexOf(pattern);
074            if (position < 0)
075                throw new IllegalArgumentException("String '" + pattern + "' not found in: '" + s + "'");
076            return position;
077        }
078
079    }
080
081}