Example usage for java.security AccessController checkPermission

List of usage examples for java.security AccessController checkPermission

Introduction

In this page you can find the example usage for java.security AccessController checkPermission.

Prototype


public static void checkPermission(Permission perm) throws AccessControlException 

Source Link

Document

Determines whether the access request indicated by the specified permission should be allowed or denied, based on the current AccessControlContext and security policy.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    AccessController.checkPermission(new FilePermission("/tmp/*", "read,write"));

}

From source file:Main.java

public static void main(String args[]) throws Exception {

    AWTPermission ap = new AWTPermission("accessClipboard");
    AccessController.checkPermission(ap);
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    FilePermission fp = new FilePermission("c:\\autoexec.bat", "read");
    AccessController.checkPermission(fp);

}

From source file:AccessTest.java

public static void main(String[] a) {
    SocketPermission sp = new SocketPermission("www.java2s.com", "connect");
    try {/*from  w w w .j  a v a  2  s  . co  m*/
        AccessController.checkPermission(sp);
        System.out.println("Ok to open socket");
    } catch (AccessControlException ace) {
        System.out.println(ace);
    }
}

From source file:com.sshtools.common.ui.ResourceIcon.java

/**
 *
 *
 * @param imageName/*from www . ja  v a 2s  .  c o  m*/
 */
protected void loadImage(String imageName) {
    Image image = null;
    URL url = cls.getResource(imageName);

    if (url != null) {
        log.debug(url.toString());
        image = Toolkit.getDefaultToolkit().getImage(url);
    } else {
        try {
            if (System.getSecurityManager() != null) {
                AccessController.checkPermission(new FilePermission(imageName, "read"));
            }

            image = Toolkit.getDefaultToolkit().getImage(imageName);
        } catch (AccessControlException ace) {
            log.error("Icon " + imageName + " could not be located as a "
                    + "resource, and the current security manager will not "
                    + "allow checking for a local file.");
        }
    }

    if (image != null) {
        this.setImage(image);
    }
}

From source file:com.sshtools.j2ssh.transport.AbstractKnownHostsKeyVerification.java

/**
 * <p>//from ww w.  j  av  a 2  s .co m
 * Constructs a host key verification instance reading the specified
 * known_hosts file.
 * </p>
 *
 * @param knownhosts the path of the known_hosts file
 *
 * @throws InvalidHostFileException if the known_hosts file is invalid
 *
 * @since 0.2.0
 */
public AbstractKnownHostsKeyVerification(String knownhosts) throws InvalidHostFileException {
    InputStream in = null;

    try {
        //  If no host file is supplied, or there is not enough permission to load
        //  the file, then just create an empty list.
        if (knownhosts != null) {
            if (System.getSecurityManager() != null) {
                AccessController.checkPermission(new FilePermission(knownhosts, "read"));
            }

            //  Load the hosts file. Do not worry if fle doesnt exist, just disable
            //  save of
            File f = new File(knownhosts);

            if (f.exists()) {
                in = new FileInputStream(f);

                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                String line;

                while ((line = reader.readLine()) != null) {
                    StringTokenizer tokens = new StringTokenizer(line, " ");
                    String host = (String) tokens.nextElement();
                    String algorithm = (String) tokens.nextElement();
                    String key = (String) tokens.nextElement();

                    SshPublicKey pk = SshKeyPairFactory.decodePublicKey(Base64.decode(key));

                    /*if (host.indexOf(",") > -1) {
                       host = host.substring(0, host.indexOf(","));
                     }*/
                    putAllowedKey(host, pk);

                    //allowedHosts.put(host + "#" + pk.getAlgorithmName(), pk);
                }

                reader.close();

                hostFileWriteable = f.canWrite();
            } else {
                // Try to create the file and its parents if necersary
                f.getParentFile().mkdirs();

                if (f.createNewFile()) {
                    FileOutputStream out = new FileOutputStream(f);
                    out.write(toString().getBytes());
                    out.close();
                    hostFileWriteable = true;
                } else {
                    hostFileWriteable = false;
                }
            }

            if (!hostFileWriteable) {
                log.warn("Host file is not writeable.");
            }

            this.knownhosts = knownhosts;
        }
    } catch (AccessControlException ace) {
        hostFileWriteable = false;
        log.warn("Not enough permission to load a hosts file, so just creating an empty list");
    } catch (IOException ioe) {
        hostFileWriteable = false;
        log.info("Could not open or read " + knownhosts + ": " + ioe.getMessage());
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ioe) {
            }
        }
    }
}

From source file:com.sshtools.j2ssh.configuration.ConfigurationLoader.java

/**
 *
 *
 * @param property//from  w ww .j  a  v  a  2  s  .  co  m
 * @param defaultValue
 *
 * @return
 */
public static String checkAndGetProperty(String property, String defaultValue) {
    //  Check for access to sshtools.platform
    try {
        if (System.getSecurityManager() != null) {
            AccessController.checkPermission(new PropertyPermission(property, "read"));
        }

        return System.getProperty(property, defaultValue);
    } catch (AccessControlException ace) {
        return defaultValue;
    }
}

From source file:com.sshtools.common.hosts.AbstractHostKeyVerification.java

/**
 * Creates a new AbstractHostKeyVerification object.
 *
 * @param hostFileName//w  w  w . jav a 2  s  . com
 *
 * @throws InvalidHostFileException
 */
public AbstractHostKeyVerification(String hostFileName) throws InvalidHostFileException {
    InputStream in = null;

    try {
        //  If no host file is supplied, or there is not enough permission to load
        //  the file, then just create an empty list.
        if (hostFileName != null) {
            if (System.getSecurityManager() != null) {
                AccessController.checkPermission(new FilePermission(hostFileName, "read"));
            }

            //  Load the hosts file. Do not worry if fle doesnt exist, just disable
            //  save of
            File f = new File(hostFileName);

            if (f.exists()) {
                in = new FileInputStream(f);
                hostFile = hostFileName;

                SAXParserFactory saxFactory = SAXParserFactory.newInstance();
                SAXParser saxParser = saxFactory.newSAXParser();
                saxParser.parse(in, this);
                hostFileWriteable = f.canWrite();
            } else {
                // Try to create the file
                if (f.createNewFile()) {
                    FileOutputStream out = new FileOutputStream(f);
                    out.write(toString().getBytes());
                    out.close();
                    hostFileWriteable = true;
                } else {
                    hostFileWriteable = false;
                }
            }

            if (!hostFileWriteable) {
                log.warn("Host file is not writeable.");
            }
        }
    } catch (AccessControlException ace) {
        log.warn("Not enough permission to load a hosts file, so just creating an empty list");
    } catch (IOException ioe) {
        throw new InvalidHostFileException("Could not open or read " + hostFileName);
    } catch (SAXException sax) {
        throw new InvalidHostFileException("Failed XML parsing: " + sax.getMessage());
    } catch (ParserConfigurationException pce) {
        throw new InvalidHostFileException("Failed to initialize xml parser: " + pce.getMessage());
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ioe) {
            }
        }
    }
}

From source file:com.sshtools.common.ui.SshToolsApplication.java

/**
 * Creates a new SshToolsApplication object.
 *
 * @param panelClass/*  w  w w .  ja v  a  2  s.  c om*/
 * @param defaultContainerClass
 */
public SshToolsApplication(Class panelClass, Class defaultContainerClass) {
    this.panelClass = panelClass;
    this.defaultContainerClass = defaultContainerClass;
    additionalOptionsTabs = new java.util.ArrayList();

    try {
        if (System.getSecurityManager() != null) {
            AccessController.checkPermission(new FilePermission("<<ALL FILES>>", "write"));
        }

        File a = getApplicationPreferencesDirectory();

        if (a == null) {
            throw new AccessControlException("Application preferences directory not specified.");
        }

        InputStream in = null;
        MRUList mru = new MRUList();

        try {
            File f = new File(a, getApplicationName() + ".mru");

            if (f.exists()) {
                if (log.isDebugEnabled()) {
                    log.debug("Loading MRU from " + f.getAbsolutePath());
                }

                in = new FileInputStream(f);
                mru.reload(in);
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("MRU file " + f.getAbsolutePath() + " doesn't exist, creating empty list");
                }
            }
        } catch (Exception e) {
            log.error("Could not load MRU list.", e);
        } finally {
            IOUtil.closeStream(in);
        }

        mruModel = new MRUListModel();
        mruModel.setMRUList(mru);
    } catch (AccessControlException ace) {
        log.error("Could not load MRU.", ace);
    }
}

From source file:com.sshtools.sshterm.SshTermSessionPanel.java

/**
 *
 *
 * @param application//from   w  w  w  .j a  va 2 s  .c o m
 *
 * @throws SshToolsApplicationException
 */
public void init(SshToolsApplication application) throws SshToolsApplicationException {
    super.init(application);

    //  Additional connection tabs
    additionalTabs = new SshToolsConnectionTab[] { new SshTermTerminalTab() };

    //  Printing page format
    try {
        if (System.getSecurityManager() != null) {
            AccessController.checkPermission(new RuntimePermission("queuePrintJob"));
        }

        try {
            PrinterJob job = PrinterJob.getPrinterJob();

            if (job == null) {
                throw new IOException("Could not get print page format.");
            }

            pageFormat = job.defaultPage();

            if (PreferencesStore.preferenceExists(PREF_PAGE_FORMAT_ORIENTATION)) {
                pageFormat.setOrientation(
                        PreferencesStore.getInt(PREF_PAGE_FORMAT_ORIENTATION, PageFormat.LANDSCAPE));

                Paper paper = new Paper();
                paper.setImageableArea(PreferencesStore.getDouble(PREF_PAGE_FORMAT_IMAGEABLE_X, 0),
                        PreferencesStore.getDouble(PREF_PAGE_FORMAT_IMAGEABLE_Y, 0),
                        PreferencesStore.getDouble(PREF_PAGE_FORMAT_IMAGEABLE_W, 0),
                        PreferencesStore.getDouble(PREF_PAGE_FORMAT_IMAGEABLE_H, 0));
                paper.setSize(PreferencesStore.getDouble(PREF_PAGE_FORMAT_SIZE_W, 0),
                        PreferencesStore.getDouble(PREF_PAGE_FORMAT_SIZE_H, 0));
                pageFormat.setPaper(paper);
            }
        } catch (Exception e) {
            showExceptionMessage("Error", e.getMessage());
        }
    } catch (AccessControlException ace) {
        ace.printStackTrace();
    }

    enableEvents(VDU_EVENTS);

    // Set up the actions
    initActions();

    // Create the status bar
    statusBar = new StatusBar();

    dataListener = new DataNotificationListener(statusBar);

    // Create our terminal emulation object
    try {
        emulation = createEmulation();
    } catch (IOException ioe) {
        throw new SshToolsApplicationException(ioe);
    }

    emulation.addTerminalListener(this);

    // Set a scrollbar for the terminal - doesn't seem to be as simple as this
    scrollBar = new JScrollBar(JScrollBar.VERTICAL);
    emulation.setBufferSize(1000);

    // Create our swing terminal and add it to the main frame
    terminal = new TerminalPanel(emulation) {

        public void processEvent(AWTEvent evt) {
            /** We can't add a MouseWheelListener because it was not available in 1.3, so direct processing of events is necessary */
            if (evt instanceof MouseEvent && evt.getID() == 507) {
                try {
                    Method m = evt.getClass().getMethod("getWheelRotation", new Class[] {});
                    SshTermSessionPanel.this.scrollBar.setValue(SshTermSessionPanel.this.scrollBar.getValue()
                            + (SshTermSessionPanel.this.scrollBar.getUnitIncrement()
                                    * ((Integer) m.invoke(evt, new Object[] {})).intValue()
                                    * PreferencesStore.getInt(PREF_MOUSE_WHEEL_INCREMENT, 1)));

                } catch (Throwable t) {
                }
            } else {
                super.processEvent(evt);
            }
        }

        public void copyNotify() {
            copyAction.actionPerformed(null);
        }

    };
    terminal.requestFocus();
    terminal.setScrollbar(scrollBar);
    terminal.addMouseMotionListener(this);

    //terminal.addMouseWheelListener(this);
    // Center panel with terminal and scrollbar
    JPanel center = new JPanel(new BorderLayout());
    center.setBackground(Color.red);
    center.add(terminal, BorderLayout.CENTER);
    center.add(scrollBar, BorderLayout.EAST);

    // Show the context menu on mouse button 3 (right click)
    terminal.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent evt) {
            if ((evt.getModifiers() & MouseEvent.BUTTON3_MASK) > 0) {
                getContextMenu().setLabel(getApplication().getApplicationName());
                getContextMenu().show(terminal, evt.getX(), evt.getY());
            } else if ((evt.getModifiers() & MouseEvent.BUTTON2_MASK) > 0) {
                pasteAction.actionPerformed(null);
            }
        }
    });

    //
    //        JPanel top = new JPanel(new BorderLayout());
    //        top.add(getJMenuBar(), BorderLayout.NORTH);
    //        top.add(north, BorderLayout.SOUTH);
    setLayout(new BorderLayout());
    add(center, BorderLayout.CENTER);

    //        add(top, BorderLayout.NORTH);
    // Make sure that the swing terminal has focus
    terminal.requestFocus();
}