com.github.yoojia.halo.utils.Scanner Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of halo-core Show documentation
Show all versions of halo-core Show documentation
A FAST && THIN && HIGH SCALABLE Java web framework
package com.github.yoojia.halo.utils;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
/**
* @author YOOJIA.CHEN ([email protected])
*/
public final class Scanner {
private final Logger mLogger = LoggerFactory.getLogger(Scanner.class);
private ArrayList mClasses;
public enum ConsumeResult {
CONSUMED, SKIP
}
public interface Visitor {
ConsumeResult visit(String className) throws Exception;
}
public interface PrepareHandler {
void prepare(String root, T module, Class> hostType, Method method);
}
public void start(){
mClasses = Lists.newArrayList();
final long scanTime = System.nanoTime();
final URL url = this.getClass().getResource("/");
// 1. 当前项目下的类文件
try {
final Path base = Paths.get(url.toURI());
mLogger.debug("Searching path: {}", base);
final FileVisitor visitor = new SimpleFileVisitor() {
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attr) throws IOException {
final Path clazz = base.relativize(path);
final String className = clazz.toString();
if (className.endsWith(".class")){
final String resolvedClassName = className.replace(".class", "").replace(File.separator, ".");
mClasses.add(resolvedClassName);
}
return FileVisitResult.CONTINUE;
}
};
Files.walkFileTree(base, visitor);
} catch (Exception e) {
throw new RuntimeException(e);
}
// 2. TODO 扫描 Jar 文件内的 class 文件
SystemTime.log(scanTime, "Scan classes:" + mClasses.size());
}
public void walkClasses(Visitor visitor){
if(mClasses == null) {
throw new IllegalStateException("Cannot walk classes after scanner closed!");
}
final int max = mClasses.size() - 1;
final List deleteRef = Lists.newArrayList();
try{
for (int i = 0;i <= max; ++i){
final String item = mClasses.get(i);
if (ConsumeResult.CONSUMED.equals(visitor.visit(item))){
deleteRef.add(item);
}
}
}catch (Throwable e){
throw new RuntimeException(e);
}
mClasses.removeAll(deleteRef);
}
public void clean(){
mClasses.clear();
mClasses = null;
}
}