CustomSecurityManager.java Source code

Java tutorial

Introduction

Here is the source code for CustomSecurityManager.java

Source

class CustomSecurityManager extends SecurityManager {
    public CustomSecurityManager() {
        super();
    }

    public void checkRead(String fileName) {
        if (fileName != null && fileName.endsWith(".java")) {
            throw new SecurityException(" You are not allowed to read " + " file names ending with .java");
        }
        super.checkRead(fileName);
    }

    public void checkWrite(String fileName) {
        if (fileName != null && fileName.endsWith(".java")) {
            throw new SecurityException(" You are not allowed to write " + " file names ending with .java");
        }
        super.checkWrite(fileName);
    }

    public void checkDelete(String fileName) {
        if (fileName != null && fileName.endsWith(".java")) {
            throw new SecurityException(" You are not allowed to delete " + " file names ending with .java");
        }
        super.checkDelete(fileName);
    }
}

public class MainClass {
    public static void main() {
        System.setSecurityManager(new CustomSecurityManager());
        SecurityManager secMgr = System.getSecurityManager();
        if (secMgr != null) {
            secMgr.checkRead("fileName");
        }
    }
}