Example usage for java.lang SecurityManager SecurityManager

List of usage examples for java.lang SecurityManager SecurityManager

Introduction

In this page you can find the example usage for java.lang SecurityManager SecurityManager.

Prototype

public SecurityManager() 

Source Link

Document

Constructs a new SecurityManager.

Usage

From source file:Main.java

public static boolean deleteFile(String fileName) {
    boolean status;
    SecurityManager checker = new SecurityManager();

    if (!fileName.equals("")) {

        File path = Environment.getExternalStorageDirectory();
        File newPath = new File(path.toString() + fileName);
        checker.checkDelete(newPath.toString());
        if (newPath.isFile()) {
            try {
                Log.i("DirectoryManager deleteFile", fileName);
                newPath.delete();//w ww  . ja v a  2  s  .c o  m
                status = true;
            } catch (SecurityException se) {
                se.printStackTrace();
                status = false;
            }
        } else
            status = false;
    } else
        status = false;
    return status;
}

From source file:Main.java

public static boolean deleteDirectory(String fileName) {
    boolean status;
    SecurityManager checker = new SecurityManager();

    if (!fileName.equals("")) {

        File path = Environment.getExternalStorageDirectory();
        File newPath = new File(path.toString() + fileName);
        checker.checkDelete(newPath.toString());
        if (newPath.isDirectory()) {
            String[] listfile = newPath.list();
            // delete all files within the specified directory and then
            // delete the directory
            try {
                for (int i = 0; i < listfile.length; i++) {
                    File deletedFile = new File(newPath.toString() + "/" + listfile[i].toString());
                    deletedFile.delete();
                }/* w  w  w .ja  v  a  2 s.c o  m*/
                newPath.delete();
                Log.i("DirectoryManager deleteDirectory", fileName);
                status = true;
            } catch (Exception e) {
                e.printStackTrace();
                status = false;
            }

        } else
            status = false;
    } else
        status = false;
    return status;
}

From source file:Main.java

public static boolean deleteDirectory(String fileName) {
    boolean status;
    SecurityManager checker = new SecurityManager();

    if (!fileName.equals("")) {

        File path = Environment.getExternalStorageDirectory();
        File newPath = new File(path.toString() + fileName);
        checker.checkDelete(newPath.toString());
        if (newPath.isDirectory()) {
            String[] listfile = newPath.list();
            // delete all files within the specified directory and then
            // delete the directory
            try {
                for (int i = 0; i < listfile.length; i++) {
                    File deletedFile = new File(newPath.toString() + "/" + listfile[i].toString());
                    deletedFile.delete();
                }/*from ww w .j av a 2s  .c  o m*/
                newPath.delete();
                Log.d(TAG, "DirectoryManager deleteDirectory" + fileName);
                status = true;
            } catch (Exception e) {
                e.printStackTrace();
                status = false;
            }

        } else
            status = false;
    } else
        status = false;
    return status;
}

From source file:security.SecurityAdvice.java

public SecurityAdvice() {
    this.manager = new SecurityManager();
}

From source file:org.digidoc4j.testutils.RestrictedFileWritingRule.java

@Override
protected void before() throws Throwable {
    super.before();
    System.setSecurityManager(new SecurityManager() {

        @Override// www. j a v  a 2  s .  c om
        public void checkWrite(String file) {
            if (!isAllowedToWrite(file)) {
                throw new FileWritingRestrictedException();
            }
        }

        @Override
        public void checkPermission(Permission perm) {
            return;
        }
    });
}

From source file:SecureService.java

public void serve(InputStream i, OutputStream o) throws IOException {
    PrintWriter out = new PrintWriter(o);

    // Try to install our own security manager. If we can do this,
    // we can defeat any access control.
    out.println("Trying to create and install a security manager...");
    try {/*from ww w .  j a v a2 s .  c o  m*/
        System.setSecurityManager(new SecurityManager());
        out.println("Success!");
    } catch (Exception e) {
        out.println("Failed: " + e);
    }

    // Try to make the Server and the Java VM exit.
    // This is a denial of service attack, and it should not succeed!
    out.println();
    out.println("Trying to exit...");
    try {
        System.exit(-1);
    } catch (Exception e) {
        out.println("Failed: " + e);
    }

    // The default system policy allows this property to be read
    out.println();
    out.println("Attempting to find java version...");
    try {
        out.println(System.getProperty("java.version"));
    } catch (Exception e) {
        out.println("Failed: " + e);
    }

    // The default system policy does not allow this property to be read
    out.println();
    out.println("Attempting to find home directory...");
    try {
        out.println(System.getProperty("user.home"));
    } catch (Exception e) {
        out.println("Failed: " + e);
    }

    // Our custom policy explicitly allows this property to be read
    out.println();
    out.println("Attempting to read service.tmp property...");
    try {
        String tmpdir = System.getProperty("service.tmp");
        out.println(tmpdir);
        File dir = new File(tmpdir);
        File f = new File(dir, "testfile");

        // Check whether we've been given permission to write files to
        // the tmpdir directory
        out.println();
        out.println("Attempting to write a file in " + tmpdir + "...");
        try {
            new FileOutputStream(f);
            out.println("Opened file for writing: " + f);
        } catch (Exception e) {
            out.println("Failed: " + e);
        }

        // Check whether we've been given permission to read files from
        // the tmpdir directory
        out.println();
        out.println("Attempting to read from " + tmpdir + "...");
        try {
            FileReader in = new FileReader(f);
            out.println("Opened file for reading: " + f);
        } catch (Exception e) {
            out.println("Failed: " + e);
        }
    } catch (Exception e) {
        out.println("Failed: " + e);
    }

    // Close the Service sockets
    out.close();
    i.close();
}

From source file:ma.glasnost.orika.test.converter.CloneableConverterNoSetAccessibleTestCase.java

@Test
public void cloneableConverterWithoutSetAccessible() throws DatatypeConfigurationException {

    final SecurityManager initialSm = System.getSecurityManager();
    try {/*  w  w  w . ja  v a2  s.  co  m*/
        System.setSecurityManager(new SecurityManager() {
            public void checkPermission(java.security.Permission perm) {
                if ("suppressAccessChecks".equals(perm.getName())) {
                    for (StackTraceElement ste : new Throwable().getStackTrace()) {
                        if (ste.getClassName().equals(CloneableConverter.class.getCanonicalName())) {
                            throw new SecurityException("not permitted");
                        }
                    }
                }
            }
        });

        CloneableConverter cc = new CloneableConverter(SampleCloneable.class);

        MapperFactory factory = MappingUtil.getMapperFactory();
        factory.getConverterFactory().registerConverter(cc);

        GregorianCalendar cal = new GregorianCalendar();
        cal.add(Calendar.YEAR, 10);
        XMLGregorianCalendar xmlCal = DatatypeFactory.newInstance()
                .newXMLGregorianCalendar((GregorianCalendar) cal);
        cal.add(Calendar.MONTH, 3);

        ClonableHolder source = new ClonableHolder();
        source.value = new SampleCloneable();
        source.value.id = 5L;
        source.date = new Date(System.currentTimeMillis() + 100000);
        source.timestamp = new Timestamp(System.currentTimeMillis() + 50000);
        source.calendar = cal;
        source.xmlCalendar = xmlCal;

        ClonableHolder dest = factory.getMapperFacade().map(source, ClonableHolder.class);
        Assert.assertEquals(source.value, dest.value);
        Assert.assertNotSame(source.value, dest.value);
        Assert.assertEquals(source.date, dest.date);
        Assert.assertNotSame(source.date, dest.date);
        Assert.assertEquals(source.timestamp, dest.timestamp);
        Assert.assertNotSame(source.timestamp, dest.timestamp);
        Assert.assertEquals(source.calendar, dest.calendar);
        Assert.assertNotSame(source.calendar, dest.calendar);
        Assert.assertEquals(source.xmlCalendar, dest.xmlCalendar);
        Assert.assertNotSame(source.xmlCalendar, dest.xmlCalendar);
    } finally {
        System.setSecurityManager(initialSm);
    }
}

From source file:engine.Pi.java

public static void main(String[] args) {
        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new SecurityManager());
        }// ww  w.j  a  va2 s  . com
        try {
            String name = "Compute";
            Compute engine = new ComputeEngine();
            Compute stub = (Compute) UnicastRemoteObject.exportObject(engine, 0);
            Registry registry = LocateRegistry.getRegistry();
            registry.rebind(name, stub);
            System.out.println("ComputeEngine bound");
        } catch (Exception e) {
            System.err.println("ComputeEngine exception:");
            e.printStackTrace();
        }
    }

From source file:org.springframework.data.hadoop.mapreduce.ExecutionUtils.java

static void disableSystemExitCall() {
    final SecurityManager securityManager = new SecurityManager() {

        @Override/*from www  .j  av a 2  s  .c o  m*/
        public void checkPermission(Permission permission) {
            String name = permission.getName();
            if (name.startsWith("exitVM")) {
                throw new ExitTrapped(name);
            }
        }
    };

    oldSM = System.getSecurityManager();
    System.setSecurityManager(securityManager);
}

From source file:com.samczsun.helios.Helios.java

public static void main(String[] args, Shell shell, Splash splashScreen) {
    System.setSecurityManager(new SecurityManager() {
        @Override// w w  w .j  a v a2 s.c o  m
        public void checkPermission(Permission perm) {
        }

        @Override
        public void checkPermission(Permission perm, Object context) {
        }

        @Override
        public void checkCreateClassLoader() {
        }

        @Override
        public void checkAccess(Thread t) {
        }

        @Override
        public void checkAccess(ThreadGroup g) {
        }

        @Override
        public void checkExit(int status) {
            if (!getClassContext()[3].getCanonicalName().startsWith("com.samczsun")) {
                throw new SecurityException(); //Baksmali
            }
        }

        @Override
        public void checkExec(String cmd) {
        }

        @Override
        public void checkLink(String lib) {
        }

        @Override
        public void checkRead(FileDescriptor fd) {
        }

        @Override
        public void checkRead(String file) {
        }

        @Override
        public void checkRead(String file, Object context) {
        }

        @Override
        public void checkWrite(FileDescriptor fd) {
        }

        @Override
        public void checkWrite(String file) {
        }

        @Override
        public void checkDelete(String file) {
        }

        @Override
        public void checkConnect(String host, int port) {
        }

        @Override
        public void checkConnect(String host, int port, Object context) {
        }

        @Override
        public void checkListen(int port) {
        }

        @Override
        public void checkAccept(String host, int port) {
        }

        @Override
        public void checkMulticast(InetAddress maddr) {
        }

        @Override
        public void checkMulticast(InetAddress maddr, byte ttl) {
        }

        @Override
        public void checkPropertiesAccess() {
        }

        @Override
        public void checkPropertyAccess(String key) {
        }

        @Override
        public boolean checkTopLevelWindow(Object window) {
            return true;
        }

        @Override
        public void checkPrintJobAccess() {
        }

        @Override
        public void checkSystemClipboardAccess() {
        }

        @Override
        public void checkAwtEventQueueAccess() {
        }

        @Override
        public void checkPackageAccess(String pkg) {
        }

        @Override
        public void checkPackageDefinition(String pkg) {
        }

        @Override
        public void checkSetFactory() {
        }

        @Override
        public void checkMemberAccess(Class<?> clazz, int which) {
        }

        @Override
        public void checkSecurityAccess(String target) {
        }
    });
    try {
        if (!System.getProperty("os.name").toLowerCase().contains("linux")) {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
    } catch (Exception exception) { //Not important. No point notifying the user
    }
    splashScreen.updateState(BootSequence.LOADING_SETTINGS);
    Settings.loadSettings();
    backgroundTaskGui = new BackgroundTaskGui();
    backgroundTaskHandler = new BackgroundTaskHandler();
    splashScreen.updateState(BootSequence.LOADING_ADDONS);
    AddonHandler.registerPreloadedAddons();
    for (File file : Constants.ADDONS_DIR.listFiles()) {
        AddonHandler.getAllHandlers().stream().filter(handler -> handler.accept(file)).findFirst()
                .ifPresent(handler -> {
                    handler.run(file);
                });
    }
    splashScreen.updateState(BootSequence.SETTING_UP_GUI);
    gui = new GUI(shell);
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        Settings.saveSettings();
        getBackgroundTaskHandler().shutdown();
        processes.forEach(Process::destroy);
    }));
    splashScreen.updateState(BootSequence.COMPLETE);
    while (!splashScreen.isDisposed())
        ;
    Display.getDefault().syncExec(() -> getGui().getShell().open());

    List<File> open = new ArrayList<>();

    for (String name : args) {
        File file = new File(name);
        if (file.exists()) {
            open.add(file);
        }
    }

    submitBackgroundTask(() -> {
        Map<String, LoadedFile> newPath = new HashMap<>();
        for (String strFile : Sets.newHashSet(Settings.PATH.get().asString().split(";"))) {
            File file = new File(strFile);
            if (file.exists()) {
                try {
                    LoadedFile loadedFile = new LoadedFile(file);
                    newPath.put(loadedFile.getName(), loadedFile);
                } catch (IOException e1) {
                    ExceptionHandler.handle(e1);
                }
            }
        }
        synchronized (Helios.class) {
            path.clear();
            path.putAll(newPath);
        }
    });

    if (open.size() > 0) {
        openFiles(open.toArray(new File[open.size()]), true);
    }
}