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.util.Iterator;
17  import java.util.ServiceLoader;
18  
19  import ch.qos.logback.core.util.Loader;
20  
21  /**
22   * @author Ceki Gülcü
23   */
24  public class EnvUtil {
25  
26      /*
27       * Used to replace the ClassLoader that the ServiceLoader uses for unit testing. We need this to mock the resources
28       * the ServiceLoader attempts to load from /META-INF/services thus keeping the projects src/test/resources clean
29       * (see src/test/resources/README.txt).
30       */
31      static ClassLoader testServiceLoaderClassLoader = null;
32  
33      static public boolean isGroovyAvailable() {
34          ClassLoader classLoader = Loader.getClassLoaderOfClass(EnvUtil.class);
35          try {
36              Class<?> bindingClass = classLoader.loadClass("groovy.lang.Binding");
37              return (bindingClass != null);
38          } catch (ClassNotFoundException e) {
39              return false;
40          }
41      }
42  
43      private static ClassLoader getServiceLoaderClassLoader() {
44          return testServiceLoaderClassLoader == null ? Loader.getClassLoaderOfClass(EnvUtil.class) : testServiceLoaderClassLoader;
45      }
46  
47      public static <T> T loadFromServiceLoader(Class<T> c) {
48          ServiceLoader<T> loader = ServiceLoader.load(c, getServiceLoaderClassLoader());
49          Iterator<T> it = loader.iterator();
50          if (it.hasNext())
51              return it.next();
52          return null;
53      }
54  
55  }