View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.classic.util;
15  
16  import java.lang.reflect.InvocationTargetException;
17  import java.lang.reflect.Method;
18  
19  public class TestHelper {
20  
21      private static final Method ADD_SUPPRESSED_METHOD;
22  
23      static {
24          Method method = null;
25          try {
26              method = Throwable.class.getMethod("addSuppressed", Throwable.class);
27          } catch (NoSuchMethodException e) {
28              // ignore, will get thrown in Java < 7
29          }
30          ADD_SUPPRESSED_METHOD = method;
31      }
32  
33      public static boolean suppressedSupported() {
34          return ADD_SUPPRESSED_METHOD != null;
35      }
36  
37      public static void addSuppressed(Throwable outer, Throwable suppressed) throws InvocationTargetException, IllegalAccessException {
38          if (suppressedSupported()) {
39              ADD_SUPPRESSED_METHOD.invoke(outer, suppressed);
40          }
41      }
42  
43      static public Throwable makeNestedException(int level) {
44          if (level == 0) {
45              return new Exception("nesting level=" + level);
46          }
47          Throwable cause = makeNestedException(level - 1);
48          return new Exception("nesting level =" + level, cause);
49      }
50  
51      /**
52       * Usage:
53       * <pre>
54       * String s = "123";
55       * positionOf("1").in(s) < positionOf("3").in(s)
56       * </pre>
57       *
58       * @param pattern Plain text to be found
59       * @return StringPosition fluent interface
60       */
61      public static StringPosition positionOf(String pattern) {
62          return new StringPosition(pattern);
63      }
64  
65      public static class StringPosition {
66          private final String pattern;
67  
68          public StringPosition(String pattern) {
69              this.pattern = pattern;
70          }
71  
72          public int in(String s) {
73              final int position = s.indexOf(pattern);
74              if (position < 0)
75                  throw new IllegalArgumentException("String '" + pattern + "' not found in: '" + s + "'");
76              return position;
77          }
78  
79      }
80  
81  }