1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.util;
18
19 import org.apache.logging.log4j.Logger;
20 import org.apache.logging.log4j.spi.Provider;
21 import org.apache.logging.log4j.status.StatusLogger;
22
23 import java.io.IOException;
24 import java.net.URL;
25 import java.util.ArrayList;
26 import java.util.Enumeration;
27 import java.util.Iterator;
28 import java.util.List;
29 import java.util.Properties;
30
31
32
33
34 public final class ProviderUtil {
35
36 private static final String PROVIDER_RESOURCE = "META-INF/log4j-provider.properties";
37 private static final String API_VERSION = "Log4jAPIVersion";
38
39 private static final String[] COMPATIBLE_API_VERSIONS = {
40 "2.0.0"
41 };
42
43 private static final Logger LOGGER = StatusLogger.getLogger();
44
45 private static final List<Provider> PROVIDERS = new ArrayList<Provider>();
46
47 private ProviderUtil() {
48 }
49
50 static {
51 final ClassLoader cl = findClassLoader();
52 Enumeration<URL> enumResources = null;
53 try {
54 enumResources = cl.getResources(PROVIDER_RESOURCE);
55 } catch (final IOException e) {
56 LOGGER.fatal("Unable to locate " + PROVIDER_RESOURCE, e);
57 }
58
59 if (enumResources != null) {
60 while (enumResources.hasMoreElements()) {
61 final Properties props = new Properties();
62 final URL url = enumResources.nextElement();
63 try {
64 props.load(url.openStream());
65 } catch (final IOException ioe) {
66 LOGGER.error("Unable to read " + url.toString(), ioe);
67 }
68 if (!validVersion(props.getProperty(API_VERSION))) {
69 continue;
70 }
71 PROVIDERS.add(new Provider(props, url));
72 }
73 }
74 }
75
76 public static Iterator<Provider> getProviders() {
77 return PROVIDERS.iterator();
78 }
79
80 public static boolean hasProviders() {
81 return PROVIDERS.size() > 0;
82 }
83
84 public static ClassLoader findClassLoader() {
85 ClassLoader cl;
86 if (System.getSecurityManager() == null) {
87 cl = Thread.currentThread().getContextClassLoader();
88 } else {
89 cl = java.security.AccessController.doPrivileged(
90 new java.security.PrivilegedAction<ClassLoader>() {
91 public ClassLoader run() {
92 return Thread.currentThread().getContextClassLoader();
93 }
94 }
95 );
96 }
97 if (cl == null) {
98 cl = ProviderUtil.class.getClassLoader();
99 }
100
101 return cl;
102 }
103
104 private static boolean validVersion(final String version) {
105 for (final String v : COMPATIBLE_API_VERSIONS) {
106 if (version.startsWith(v)) {
107 return true;
108 }
109 }
110 return false;
111 }
112 }