Example usage for java.lang System getSecurityManager

List of usage examples for java.lang System getSecurityManager

Introduction

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

Prototype

public static SecurityManager getSecurityManager() 

Source Link

Document

Gets the system-wide security manager.

Usage

From source file:com.sshtools.j2ssh.util.DynamicClassLoader.java

private boolean securityAllowsClass(String className) {
    try {// w  ww  . java2  s.  c o  m
        SecurityManager security = System.getSecurityManager();

        if (security == null) {
            // if there's no security manager then all classes
            // are allowed to be loaded
            return true;
        }

        int lastDot = className.lastIndexOf('.');

        // Check if we are allowed to load the class' package
        security.checkPackageDefinition((lastDot > -1) ? className.substring(0, lastDot) : "");

        // Throws if not allowed
        return true;
    } catch (SecurityException e) {
        return false;
    }
}

From source file:org.apache.jasper.runtime.PageContextImpl.java

public void removeAttribute(final String name, final int scope) {

    if (name == null) {
        throw new NullPointerException(Localizer.getMessage("jsp.error.attribute.null_name"));
    }/*from www. ja va 2  s  .  c  o m*/
    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                doRemoveAttribute(name, scope);
                return null;
            }
        });
    } else {
        doRemoveAttribute(name, scope);
    }
}

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

public void init(SshToolsApplication application) throws SshToolsApplicationException {
    super.init(application);
    boolean kerb_support = false;
    if (PreferencesStore.get(PREF_KRB5_MYPROXY_USE, "NONE").indexOf("true") >= 0)
        kerb_support = true;/*from  w  w w  . j a  va2  s. co  m*/

    //  Additional connection tabs
    if (kerb_support == true) {
        additionalTabs = new SshToolsConnectionTab[] { new SshTermCommandTab(), new SshTermTerminalTab(),
                new GSIAuthTab(), new XForwardingTab(), new SshToolsConnectionKerberosTab() };
        SshTerminalPanel.PREF_KRB5_MYPROXY_ENABLED = true;
    } else {
        additionalTabs = new SshToolsConnectionTab[] { new SshTermCommandTab(), new SshTermTerminalTab(),
                new GSIAuthTab(), new XForwardingTab() };
        SshTerminalPanel.PREF_KRB5_MYPROXY_ENABLED = false;

    }
    //
    //portForwardingPane = new PortForwardingPane();

    //  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[] {});
                    SshTerminalPanel.this.scrollBar.setValue(SshTerminalPanel.this.scrollBar.getValue()
                            + (SshTerminalPanel.this.scrollBar.getUnitIncrement()
                                    * ((Integer) m.invoke(evt, new Object[] {})).intValue()
                                    * PreferencesStore.getInt(PREF_MOUSE_WHEEL_INCREMENT, 1)));

                } catch (Throwable t) {
                    //   In theory, this should never happen
                }
            } 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((getCurrentConnectionFile() == null) ? getApplication().getApplicationName()
                                : getCurrentConnectionFile().getName());
                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();
}

From source file:de.fosd.jdime.Main.java

/**
 * Dumps the given <code>FileArtifact</code> using the <code>mode</code>.
 *
 * @param artifact//from   w  w w .j a v  a2  s .  c  o m
 *         the <code>Artifact</code> to dump
 * @param mode
 *         the dump format
 */
private static void dump(FileArtifact artifact, DumpMode mode) {

    if (mode == DumpMode.NONE) {
        return;
    }

    if (mode == DumpMode.FILE_DUMP || artifact.isDirectory()) {
        System.out.println(artifact.dump(mode));
    } else {
        SecurityManager prevSecManager = System.getSecurityManager();
        SecurityManager noExitManager = new SecurityManager() {
            @Override
            public void checkPermission(Permission perm) {
                // allow anything.
            }

            @Override
            public void checkPermission(Permission perm, Object context) {
                // allow anything.
            }

            @Override
            public void checkExit(int status) {
                super.checkExit(status);
                throw new SecurityException("Captured attempt to exit JVM.");
            }
        };

        ASTNodeArtifact astArtifact;

        System.setSecurityManager(noExitManager);

        try {
            astArtifact = new ASTNodeArtifact(artifact);
        } catch (RuntimeException e) {
            LOG.log(Level.WARNING, e, () -> "Could not parse " + artifact + " to an ASTNodeArtifact.");
            return;
        } finally {
            System.setSecurityManager(prevSecManager);
        }

        System.out.println(astArtifact.dump(mode));
    }
}

From source file:org.beangle.model.persist.hibernate.internal.ClassUtils.java

/**
 * Returns the first matching class from the given array, that doens't
 * belong to common libraries such as the JDK or OSGi API. Useful for
 * filtering OSGi services by type to prevent class cast problems.
 * <p/>/*from w  w  w  . j av  a  2s .  c  o m*/
 * No sanity checks are done on the given array class.
 * 
 * @param classes
 *            array of classes
 * @return a 'particular' (non JDK/OSGi) class if one is found. Else the
 *         first available entry is returned.
 */
public static Class<?> getParticularClass(Class<?>[] classes) {
    boolean hasSecurity = (System.getSecurityManager() != null);
    for (int i = 0; i < classes.length; i++) {
        final Class<?> clazz = classes[i];
        ClassLoader loader = null;
        if (hasSecurity) {
            loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
                public ClassLoader run() {
                    return clazz.getClassLoader();
                }
            });
        } else {
            loader = clazz.getClassLoader();
        }
        // quick boot/system check
        if (loader != null) {
            // consider known loaders
            if (!knownNonOsgiLoadersSet.contains(loader)) {
                return clazz;
            }
        }
    }

    return (ObjectUtils.isEmpty(classes) ? null : classes[0]);
}

From source file:org.kawanfw.file.servlet.ServerFileDispatch.java

/**
 * NOT USED ANYMORE/*from w  w w  .  ja va 2 s  . c o m*/
 * Install the Security Manager that restricts FileFilter and FilenameFilter
 * to write/delete files.
 * @param fileConfigurator the file configurator in use
 */
@SuppressWarnings("unused")
private void installSecurityManager(FileConfigurator fileConfigurator) {
    // Ok, install our security manager
    if (System.getSecurityManager() == null) {
        securityManager = new KawanfwSecurityManager();
        System.setSecurityManager(securityManager);
    }
}

From source file:org.echocat.nodoodle.classloading.FileClassLoader.java

/**
 * This is a copy of {@link URLClassLoader#getPermissions(CodeSource)}.
 *
 * Returns the permissions for the given codesource object.
 * The implementation of this method first calls super.getPermissions
 * and then adds permissions based on the URL of the codesource.
 * <p>/*from  w  w w .  j  a  va  2 s .  c  om*/
 * If the protocol of this URL is "jar", then the permission granted
 * is based on the permission that is required by the URL of the Jar
 * file.
 * <p>
 * If the protocol is "file"
 * and the path specifies a file, then permission to read that
 * file is granted. If protocol is "file" and the path is
 * a directory, permission is granted to read all files
 * and (recursively) all files and subdirectories contained in
 * that directory.
 * <p>
 * If the protocol is not "file", then
 * to connect to and accept connections from the URL's host is granted.
 * @param codesource the codesource
 * @return the permissions granted to the codesource
 */
@Override
protected PermissionCollection getPermissions(CodeSource codesource) {
    final PermissionCollection perms = super.getPermissions(codesource);
    final URL url = codesource.getLocation();
    Permission p;
    URLConnection urlConnection;
    try {
        urlConnection = url.openConnection();
        p = urlConnection.getPermission();
    } catch (IOException ignored) {
        p = null;
        urlConnection = null;
    }
    if (p instanceof FilePermission) {
        // if the permission has a separator char on the end,
        // it means the codebase is a directory, and we need
        // to add an additional permission to read recursively
        String path = p.getName();
        if (path.endsWith(File.separator)) {
            path += "-";
            p = new FilePermission(path, SecurityConstants.FILE_READ_ACTION);
        }
    } else if ((p == null) && (url.getProtocol().equals("file"))) {
        String path = url.getFile().replace('/', File.separatorChar);
        path = ParseUtil.decode(path);
        if (path.endsWith(File.separator)) {
            path += "-";
        }
        p = new FilePermission(path, SecurityConstants.FILE_READ_ACTION);
    } else {
        URL locUrl = url;
        if (urlConnection instanceof JarURLConnection) {
            locUrl = ((JarURLConnection) urlConnection).getJarFileURL();
        }
        final String host = locUrl.getHost();
        if (host != null && (host.length() > 0)) {
            p = new SocketPermission(host, SecurityConstants.SOCKET_CONNECT_ACCEPT_ACTION);
        }
    }
    // make sure the person that created this class loader
    // would have this permission

    if (p != null) {
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            final Permission fp = p;
            doPrivileged(new PrivilegedAction<Void>() {
                @Override
                public Void run() throws SecurityException {
                    sm.checkPermission(fp);
                    return null;
                }
            }, _acc);
        }
        perms.add(p);
    }
    return perms;
}

From source file:catalina.startup.Catalina.java

/**
 * Start a new server instance./*from w w  w  .  java  2  s. c om*/
 */
protected void start() {

    // Create and execute our Digester
    Digester digester = createStartDigester();
    File file = configFile();
    try {
        InputSource is = new InputSource("file://" + file.getAbsolutePath());
        FileInputStream fis = new FileInputStream(file);
        is.setByteStream(fis);
        digester.push(this);
        digester.parse(is);
        fis.close();
    } catch (Exception e) {
        System.out.println("Catalina.start: " + e);
        e.printStackTrace(System.out);
        System.exit(1);
    }

    // Setting additional variables
    if (!useNaming) {
        System.setProperty("catalina.useNaming", "false");
    } else {
        System.setProperty("catalina.useNaming", "true");
        String value = "org.apache.naming";
        String oldValue = System.getProperty(javax.naming.Context.URL_PKG_PREFIXES);
        if (oldValue != null) {
            value = value + ":" + oldValue;
        }
        System.setProperty(javax.naming.Context.URL_PKG_PREFIXES, value);
        value = System.getProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY);
        if (value == null) {
            System.setProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY,
                    "org.apache.naming.java.javaURLContextFactory");
        }
    }

    // If a SecurityManager is being used, set properties for
    // checkPackageAccess() and checkPackageDefinition
    if (System.getSecurityManager() != null) {
        String access = Security.getProperty("package.access");
        if (access != null && access.length() > 0)
            access += ",";
        else
            access = "sun.,";
        Security.setProperty("package.access", access + "org.apache.catalina.,org.apache.jasper.");
        String definition = Security.getProperty("package.definition");
        if (definition != null && definition.length() > 0)
            definition += ",";
        else
            definition = "sun.,";
        Security.setProperty("package.definition",
                // FIX ME package "javax." was removed to prevent HotSpot
                // fatal internal errors
                definition + "java.,org.apache.catalina.,org.apache.jasper.");
    }

    // Replace System.out and System.err with a custom PrintStream
    SystemLogHandler log = new SystemLogHandler(System.out);
    System.setOut(log);
    System.setErr(log);

    Thread shutdownHook = new CatalinaShutdownHook();

    // Start the new server
    if (server instanceof Lifecycle) {
        try {
            server.initialize();
            ((Lifecycle) server).start();
            try {
                // Register shutdown hook
                Runtime.getRuntime().addShutdownHook(shutdownHook);
            } catch (Throwable t) {
                // This will fail on JDK 1.2. Ignoring, as Tomcat can run
                // fine without the shutdown hook.
            }
            // Wait for the server to be told to shut down
            server.await();
        } catch (LifecycleException e) {
            System.out.println("Catalina.start: " + e);
            e.printStackTrace(System.out);
            if (e.getThrowable() != null) {
                System.out.println("----- Root Cause -----");
                e.getThrowable().printStackTrace(System.out);
            }
        }
    }

    // Shut down the server
    if (server instanceof Lifecycle) {
        try {
            try {
                // Remove the ShutdownHook first so that server.stop()
                // doesn't get invoked twice
                Runtime.getRuntime().removeShutdownHook(shutdownHook);
            } catch (Throwable t) {
                // This will fail on JDK 1.2. Ignoring, as Tomcat can run
                // fine without the shutdown hook.
            }
            ((Lifecycle) server).stop();
        } catch (LifecycleException e) {
            System.out.println("Catalina.stop: " + e);
            e.printStackTrace(System.out);
            if (e.getThrowable() != null) {
                System.out.println("----- Root Cause -----");
                e.getThrowable().printStackTrace(System.out);
            }
        }
    }

}

From source file:org.apache.jasper.runtime.PageContextImpl.java

public int getAttributesScope(final String name) {

    if (name == null) {
        throw new NullPointerException(Localizer.getMessage("jsp.error.attribute.null_name"));
    }//from   w w  w.  j ava  2 s.com

    if (System.getSecurityManager() != null) {
        return ((Integer) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                return new Integer(doGetAttributeScope(name));
            }
        })).intValue();
    } else {
        return doGetAttributeScope(name);
    }
}

From source file:org.codice.ddf.cxf.client.impl.SecureCxfClientFactoryImpl.java

/**
 * Clients produced by this method will be secured with two-way ssl and the provided security
 * subject.//from   www.j  a v a2 s  . co m
 *
 * <p>The returned client should NOT be reused between requests! This method should be called for
 * each new request in order to ensure that the security token is up-to-date each time.
 */
public final T getClientForSubject(Subject subject) {
    final java.lang.SecurityManager security = System.getSecurityManager();

    if (security != null) {
        security.checkPermission(CREATE_CLIENT_PERMISSION);
    }

    return AccessController.doPrivileged((PrivilegedAction<T>) () -> {
        String asciiString = clientFactory.getAddress();

        T newClient = getNewClient();

        if (!basicAuth && StringUtils.startsWithIgnoreCase(asciiString, HTTPS)) {
            if (subject instanceof ddf.security.Subject) {
                RestSecurity.setSubjectOnClient((ddf.security.Subject) subject, WebClient.client(newClient));
            }
        }

        auditRemoteConnection(asciiString);

        return newClient;
    });
}