package org.apache.logging.log4j.util;

import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Properties;
import java.util.concurrent.CopyOnWriteArraySet;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.spi.Provider;
import org.apache.logging.log4j.status.StatusLogger;

public final class ProviderUtil {
   protected static final String PROVIDER_RESOURCE = "META-INF/log4j-provider.properties";
   private static final String API_VERSION = "Log4jAPIVersion";
   private static final String[] COMPATIBLE_API_VERSIONS = new String[]{"2.0.0"};
   private static final Logger LOGGER = StatusLogger.getLogger();
   private static final Collection<Provider> PROVIDERS = new CopyOnWriteArraySet();

   private ProviderUtil() {
   }

   protected static void loadProviders(Enumeration<URL> enumResources, ClassLoader cl) {
      if (enumResources != null) {
         while(enumResources.hasMoreElements()) {
            URL url = (URL)enumResources.nextElement();
            loadProvider(url, cl);
         }
      }

   }

   protected static void loadProvider(URL url, ClassLoader cl) {
      try {
         Properties props = PropertiesUtil.loadClose(url.openStream(), url);
         if (validVersion(props.getProperty("Log4jAPIVersion"))) {
            PROVIDERS.add(new Provider(props, url, cl));
         }
      } catch (IOException var3) {
         LOGGER.error("Unable to open {}", url, var3);
      }

   }

   public static Iterable<Provider> getProviders() {
      return PROVIDERS;
   }

   public static boolean hasProviders() {
      return !PROVIDERS.isEmpty();
   }

   public static ClassLoader findClassLoader() {
      return LoaderUtil.getThreadContextClassLoader();
   }

   private static boolean validVersion(String version) {
      String[] arr$ = COMPATIBLE_API_VERSIONS;
      int len$ = arr$.length;

      for(int i$ = 0; i$ < len$; ++i$) {
         String v = arr$[i$];
         if (version.startsWith(v)) {
            return true;
         }
      }

      return false;
   }

   static {
      ClassLoader cl = findClassLoader();
      Enumeration enumResources = null;

      try {
         enumResources = cl.getResources("META-INF/log4j-provider.properties");
      } catch (IOException var3) {
         LOGGER.fatal("Unable to locate {}", "META-INF/log4j-provider.properties", var3);
      }

      loadProviders(enumResources, cl);
   }
}
