package com.pictc.utils;

import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description TODO(这里用一句话描述这个类的作用)
 * @author zhangfucai
 * @Date 2023年1月8日 下午6:29:01
 * @version 1.0.0
 */
@Slf4j
public class ScanFile {
	
	
	private static final String FILE_PROCOTOL="file";
	
	private static final String JAR_PROCOTOL="jar";
	
	public static void scan(String name,ScanFileFilter filter) {
		try {
			Enumeration<URL> dirs = getDefaultClassLoader().getResources(name);
			if(dirs!=null) {
				while(dirs.hasMoreElements()) {
					URL url = dirs.nextElement();
					if(FILE_PROCOTOL.equals(url.getProtocol())) {
						filter.accept(url.openStream());
					}else if(JAR_PROCOTOL.equals(url.getProtocol())) {
						JarFile jarFile = ((JarURLConnection)url.openConnection()).getJarFile();
						ZipEntry entry = jarFile.getEntry(name);
						if(entry!=null) {
							filter.accept(jarFile.getInputStream(entry));
						}
					}
				}
			}else {
				log.info("没有扫描到任何东西！");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private static ClassLoader getDefaultClassLoader() {
		ClassLoader cl = null;
		try {
			cl = Thread.currentThread().getContextClassLoader();
		} catch (Throwable ex) {
		}
		if (cl == null) {
			cl = ScanFile.class.getClassLoader();
			if (cl == null) {
				try {
					cl = ClassLoader.getSystemClassLoader();
				} catch (Throwable ex) {
				}
			}
		}
		return cl;
	}

}

