package com.walker.security.util;
|
|
import java.io.FileNotFoundException;
|
import java.io.IOException;
|
import java.io.InputStream;
|
import java.net.URL;
|
|
/**
|
* 类路径资源加载器,借鉴 spring <code>ClassPathResource</code>
|
*/
|
public class ClassPathResource {
|
|
private String path;
|
|
private ClassLoader classLoader;
|
private Class<?> clazz;
|
|
public ClassPathResource(String path) {
|
this(path, (ClassLoader)null);
|
}
|
|
public ClassPathResource(String path, ClassLoader classLoader) {
|
// Assert.notNull(path, "Path must not be null");
|
String pathToUse = StringUtils.cleanPath(path);
|
if (pathToUse.startsWith("/")) {
|
pathToUse = pathToUse.substring(1);
|
}
|
|
this.path = pathToUse;
|
this.classLoader = classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader();
|
}
|
|
public InputStream getInputStream() throws IOException {
|
InputStream is;
|
if (this.clazz != null) {
|
is = this.clazz.getResourceAsStream(this.path);
|
} else if (this.classLoader != null) {
|
is = this.classLoader.getResourceAsStream(this.path);
|
} else {
|
is = ClassLoader.getSystemResourceAsStream(this.path);
|
}
|
|
if (is == null) {
|
throw new FileNotFoundException(this.getDescription() + " cannot be opened because it does not exist");
|
} else {
|
return is;
|
}
|
}
|
|
public String getDescription() {
|
StringBuilder builder = new StringBuilder("class path resource [");
|
String pathToUse = this.path;
|
if (this.clazz != null && !pathToUse.startsWith("/")) {
|
builder.append(com.walker.security.util.ClassUtils.classPackageAsResourcePath(this.clazz));
|
builder.append('/');
|
}
|
|
if (pathToUse.startsWith("/")) {
|
pathToUse = pathToUse.substring(1);
|
}
|
|
builder.append(pathToUse);
|
builder.append(']');
|
return builder.toString();
|
}
|
|
public boolean exists() {
|
return this.resolveURL() != null;
|
}
|
|
protected URL resolveURL() {
|
try {
|
if (this.clazz != null) {
|
return this.clazz.getResource(this.path);
|
} else {
|
return this.classLoader != null ? this.classLoader.getResource(this.path) : ClassLoader.getSystemResource(this.path);
|
}
|
} catch (IllegalArgumentException var2) {
|
return null;
|
}
|
}
|
}
|