以前没有关注java的里面的SecurityManager这个类,最近看动态代理顺便记录下此类的使用。
其实很多时候都用到SecurityManager,只是平时没太关注而已,FileInputStream的构造方法:
public FileInputStream(File file) throws FileNotFoundException {
String name = (file != null ? file.getPath() : null);
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(name);
}
if (name == null) {
throw new NullPointerException();
}
if (file.isInvalid()) {
throw new FileNotFoundException(“Invalid file path”);
}
fd = new FileDescriptor();
fd.incrementAndGetUseCount();
this.path = name;
open(name);
}
就有SecurityManager的用武之地。借用这个例子,有以下测试类:
import java.io.*;
/**
* Created by
*/
public class SecurityManageTest {
public static void main(String args[]) {
try {
System.setSecurityManager(new PasswordSecurityManager("a"));
System.setSecurityManager(new PasswordSecurityManager("a"));
} catch (SecurityException se) {
System.err.println("Exception already set!");
}
try {
System.out.println("start1");
BufferedReader fis = new BufferedReader(new FileReader("test.txt"));
System.out.println("start2");
BufferedWriter fos = new BufferedWriter(new FileWriter("test.txt"));
System.out.println("start3");
String inputString;
while ((inputString = fis.readLine()) != null) {
fos.write(inputString);
fos.write('\n');
}
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private static class PasswordSecurityManager extends SecurityManager {
private String password;
PasswordSecurityManager(String password) {
super();
this.password = password;
}
private boolean accessOK() {
int c;
BufferedReader dis = new BufferedReader(new InputStreamReader(System.in));
String response;
System.out.println("What's the secret password?");
try {
response = dis.readLine();
if (response.equals(password))
return true;
else
return false;
} catch (IOException e) {
return false;
}
}
public void checkRead(FileDescriptor filedescriptor) {
if (!accessOK())
throw new SecurityException("no read permission!");
}
public void checkRead(String filename) {
if (!accessOK())
throw new SecurityException("no read permission!");
}
public void checkRead(String filename, Object executionContext) {
if (!accessOK())
throw new SecurityException("no read permission!");
}
public void checkWrite(FileDescriptor filedescriptor) {
if (!accessOK())
throw new SecurityException("no write permission!");
}
public void checkWrite(String filename) {
if (!accessOK())
throw new SecurityException("has no write permission!");
}
}
}
运行结果如下:
start1
What’s the secret password?
a
start2
What’s the secret password?
a
start3