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.daemon.vfs.VirtualFileSystem.java

/**
 *
 *
 * @param path// w  w w  . j  a v  a 2  s.  c  om
 *
 * @return
 *
 * @throws IOException
 * @throws FileNotFoundException
 */
public FileAttributes getFileAttributes(String path) throws IOException, FileNotFoundException {
    log.debug("Getting file attributes for " + path);
    path = translateVFSPath(path);

    // Look up the VFS mount attributes
    File f = new File(path);
    path = f.getCanonicalPath();

    if (!f.exists()) {
        throw new FileNotFoundException(path + " doesn't exist");
    }

    VFSPermission permissions = getVFSPermission(path);

    if (permissions == null) {
        throw new IOException("No default permissions set");
    }

    FileAttributes attrs = new FileAttributes();
    attrs.setSize(new UnsignedInteger64(String.valueOf(f.length())));
    attrs.setTimes(new UnsignedInteger32(f.lastModified() / 1000),
            new UnsignedInteger32(f.lastModified() / 1000));

    boolean canExec = true;

    try {
        if (System.getSecurityManager() != null) {
            System.getSecurityManager().checkExec(f.getCanonicalPath());
        }
    } catch (SecurityException ex1) {
        canExec = false;
    }

    attrs.setPermissions((((f.canRead() && permissions.canRead()) ? "r" : "-")
            + ((f.canWrite() && permissions.canWrite()) ? "w" : "-")
            + ((canExec && permissions.canExecute()) ? "x" : "-")));

    attrs.setPermissions(new UnsignedInteger32(attrs.getPermissions().longValue()
            | (f.isDirectory() ? FileAttributes.S_IFDIR : FileAttributes.S_IFREG)));

    return attrs;
}

From source file:jag.sftp.VirtualFileSystem.java

/**
*
*
* @param path/*from  w  w  w  .  j a  v  a2 s. co m*/
*
* @return
*
* @throws IOException
* @throws FileNotFoundException
*/
public FileAttributes getFileAttributes(String path) throws IOException, FileNotFoundException {
    log.debug("Getting file attributes for " + path);
    path = translateVFSPath(path);

    // Look up the VFS mount attributes
    File f = new File(path);
    path = f.getCanonicalPath();

    if (!f.exists()) {
        throw new FileNotFoundException(path + " doesn't exist");
    }

    VFSPermission permissions = getVFSPermission(path);

    if (permissions == null) {
        throw new IOException("No default permissions set");
    }

    FileAttributes attrs = new FileAttributes();
    attrs.setSize(new UnsignedInteger64(String.valueOf(f.length())));
    attrs.setTimes(new UnsignedInteger32(f.lastModified() / 1000),
            new UnsignedInteger32(f.lastModified() / 1000));

    boolean canExec = true;

    try {
        if (System.getSecurityManager() != null) {
            System.getSecurityManager().checkExec(f.getCanonicalPath());
        }
    } catch (SecurityException ex1) {
        canExec = false;
    }

    attrs.setPermissions((((f.canRead() && permissions.canRead()) ? "r" : "-")
            + ((f.canWrite() && permissions.canWrite()) ? "w" : "-")
            + ((canExec && permissions.canExecute()) ? "x" : "-")));
    attrs.setPermissions(new UnsignedInteger32(attrs.getPermissions().longValue()
            | (f.isDirectory() ? FileAttributes.S_IFDIR : FileAttributes.S_IFREG)));

    return attrs;
}

From source file:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java

@Override
public Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException {
    // Use non-singleton bean definition, to avoid registering bean as dependent bean.
    final RootBeanDefinition bd = new RootBeanDefinition(beanClass, autowireMode, dependencyCheck);
    bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
    if (bd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR) {
        return autowireConstructor(beanClass.getName(), bd, null, null).getWrappedInstance();
    } else {/*  w ww  . j av a2s  . com*/
        Object bean;
        final BeanFactory parent = this;
        if (System.getSecurityManager() != null) {
            bean = AccessController.doPrivileged(
                    (PrivilegedAction<Object>) () -> getInstantiationStrategy().instantiate(bd, null, parent),
                    getAccessControlContext());
        } else {
            bean = getInstantiationStrategy().instantiate(bd, null, parent);
        }
        populateBean(beanClass.getName(), bd, new BeanWrapperImpl(bean));
        return bean;
    }
}

From source file:org.eclipse.gemini.blueprint.extender.internal.dependencies.startup.DependencyServiceManager.java

protected void register() {
    final String filter = createDependencyFilter();
    if (log.isDebugEnabled()) {
        log.debug(context.getDisplayName()
                + " has registered service dependency dependencyDetector with filter: " + filter);
    }//from w  w w. ja  v a 2 s.  c  o m

    // send dependency event before registering the filter
    sendInitialBootstrappingEvents(getUnsatisfiedDependencies().keySet());

    if (System.getSecurityManager() != null) {
        AccessControlContext acc = getAcc();
        AccessController.doPrivileged(new PrivilegedAction<Object>() {
            public Object run() {
                OsgiListenerUtils.addServiceListener(bundleContext, listener, filter);
                return null;
            }
        }, acc);
    } else {
        OsgiListenerUtils.addServiceListener(bundleContext, listener, filter);
    }
}

From source file:org.apache.hadoop.hbase.mapreduce.TestImportExport.java

/**
 * test main method. Import should print help and call System.exit
 *///www .ja v  a  2  s  .  c  o m
@Test
public void testImportMain() throws Exception {
    PrintStream oldPrintStream = System.err;
    SecurityManager SECURITY_MANAGER = System.getSecurityManager();
    LauncherSecurityManager newSecurityManager = new LauncherSecurityManager();
    System.setSecurityManager(newSecurityManager);
    ByteArrayOutputStream data = new ByteArrayOutputStream();
    String[] args = {};
    System.setErr(new PrintStream(data));
    try {
        System.setErr(new PrintStream(data));
        Import.main(args);
        fail("should be SecurityException");
    } catch (SecurityException e) {
        assertEquals(-1, newSecurityManager.getExitCode());
        assertTrue(data.toString().contains("Wrong number of arguments:"));
        assertTrue(data.toString().contains("-Dimport.bulk.output=/path/for/output"));
        assertTrue(data.toString().contains("-Dimport.filter.class=<name of filter class>"));
        assertTrue(data.toString().contains("-Dimport.bulk.output=/path/for/output"));
        assertTrue(data.toString().contains("-Dmapreduce.reduce.speculative=false"));
    } finally {
        System.setErr(oldPrintStream);
        System.setSecurityManager(SECURITY_MANAGER);
    }
}

From source file:at.irian.myfaces.wscope.renderkit.html.WsServerSideStateCacheImpl.java

protected Object deserializeView(Object state) {
    if (log.isLoggable(Level.FINEST)) {
        log.finest("Entering deserializeView");
    }/*from   ww w  . j a va 2  s  .c  o  m*/

    if (state instanceof byte[]) {
        if (log.isLoggable(Level.FINEST)) {
            log.finest("Processing deserializeView - deserializing serialized state. Bytes : "
                    + ((byte[]) state).length);
        }

        try {
            ByteArrayInputStream bais = new ByteArrayInputStream((byte[]) state);
            InputStream is = bais;
            if (is.read() == COMPRESSED_FLAG) {
                is = new GZIPInputStream(is);
            }
            ObjectInputStream ois = null;
            try {
                final ObjectInputStream in = new MyFacesObjectInputStream(is);
                ois = in;
                Object object = null;
                if (System.getSecurityManager() != null) {
                    object = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                        public Object run()
                                throws PrivilegedActionException, IOException, ClassNotFoundException {
                            //return new Object[] {in.readObject(), in.readObject()};
                            return in.readObject();
                        }
                    });
                } else {
                    //object = new Object[] {in.readObject(), in.readObject()};
                    object = in.readObject();
                }
                return object;
            } finally {
                if (ois != null) {
                    ois.close();
                    ois = null;
                }
            }
        } catch (PrivilegedActionException e) {
            log.log(Level.SEVERE, "Exiting deserializeView - Could not deserialize state: " + e.getMessage(),
                    e);
            return null;
        } catch (IOException e) {
            log.log(Level.SEVERE, "Exiting deserializeView - Could not deserialize state: " + e.getMessage(),
                    e);
            return null;
        } catch (ClassNotFoundException e) {
            log.log(Level.SEVERE, "Exiting deserializeView - Could not deserialize state: " + e.getMessage(),
                    e);
            return null;
        }
    } else if (state instanceof Object[]) {
        if (log.isLoggable(Level.FINEST)) {
            log.finest("Exiting deserializeView - state not serialized.");
        }

        return state;
    } else if (state == null) {
        log.severe("Exiting deserializeView - this method should not be called with a null-state.");
        return null;
    } else {
        log.severe("Exiting deserializeView - this method should not be called with a state of type : "
                + state.getClass());
        return null;
    }
}

From source file:org.apache.catalina.cluster.session.DeltaSession.java

/**
 * Return the <code>HttpSession</code> for which this object
 * is the facade./*from   w  w w . java 2 s  .co  m*/
 */
public HttpSession getSession() {

    if (facade == null) {
        if (System.getSecurityManager() != null) {
            final DeltaSession fsession = this;
            facade = (DeltaSessionFacade) AccessController.doPrivileged(new PrivilegedAction() {
                public Object run() {
                    return new DeltaSessionFacade(fsession);
                }
            });
        } else {
            facade = new DeltaSessionFacade(this);
        }
    }
    return (facade);

}

From source file:org.apache.hadoop.hbase.mapreduce.TestImportExport.java

/**
 * test main method. Export should print help and call System.exit
 *///from www.  j av a 2 s .  com
@Test
public void testExportMain() throws Exception {
    PrintStream oldPrintStream = System.err;
    SecurityManager SECURITY_MANAGER = System.getSecurityManager();
    LauncherSecurityManager newSecurityManager = new LauncherSecurityManager();
    System.setSecurityManager(newSecurityManager);
    ByteArrayOutputStream data = new ByteArrayOutputStream();
    String[] args = {};
    System.setErr(new PrintStream(data));
    try {
        System.setErr(new PrintStream(data));
        Export.main(args);
        fail("should be SecurityException");
    } catch (SecurityException e) {
        assertEquals(-1, newSecurityManager.getExitCode());
        assertTrue(data.toString().contains("Wrong number of arguments:"));
        assertTrue(data.toString()
                .contains("Usage: Export [-D <property=value>]* <tablename> <outputdir> [<versions> "
                        + "[<starttime> [<endtime>]] [^[regex pattern] or [Prefix] to filter]]"));
        assertTrue(data.toString().contains("-D hbase.mapreduce.scan.column.family=<familyName>"));
        assertTrue(data.toString().contains("-D hbase.mapreduce.include.deleted.rows=true"));
        assertTrue(data.toString().contains("-Dhbase.client.scanner.caching=100"));
        assertTrue(data.toString().contains("-Dmapreduce.map.speculative=false"));
        assertTrue(data.toString().contains("-Dmapreduce.reduce.speculative=false"));
        assertTrue(data.toString().contains("-Dhbase.export.scanner.batch=10"));
    } finally {
        System.setErr(oldPrintStream);
        System.setSecurityManager(SECURITY_MANAGER);
    }
}

From source file:org.apache.log4j.chainsaw.LogUI.java

/**
 * Creates, activates, and then shows the Chainsaw GUI, optionally showing
 * the splash screen, and using the passed shutdown action when the user
 * requests to exit the application (if null, then Chainsaw will exit the vm)
 *
 * @param model//from ww  w  .j  ava2  s .c o  m
 * @param newShutdownAction
 *                    DOCUMENT ME!
 */
public static void createChainsawGUI(ApplicationPreferenceModel model, Action newShutdownAction) {

    if (model.isOkToRemoveSecurityManager()) {
        MessageCenter.getInstance()
                .addMessage("User has authorised removal of Java Security Manager via preferences");
        System.setSecurityManager(null);
        // this SHOULD set the Policy/Permission stuff for any
        // code loaded from our custom classloader.  
        // crossing fingers...
        Policy.setPolicy(new Policy() {

            public void refresh() {
            }

            public PermissionCollection getPermissions(CodeSource codesource) {
                Permissions perms = new Permissions();
                perms.add(new AllPermission());
                return (perms);
            }
        });
    }

    final LogUI logUI = new LogUI();
    logUI.applicationPreferenceModel = model;

    if (model.isShowSplash()) {
        showSplash(logUI);
    }
    logUI.cyclicBufferSize = model.getCyclicBufferSize();
    logUI.pluginRegistry = repositoryExImpl.getPluginRegistry();

    logUI.handler = new ChainsawAppenderHandler();
    logUI.handler.addEventBatchListener(logUI.new NewTabEventBatchReceiver());

    /**
     * TODO until we work out how JoranConfigurator might be able to have
     * configurable class loader, if at all.  For now we temporarily replace the
     * TCCL so that Plugins that need access to resources in 
     * the Plugins directory can find them (this is particularly
     * important for the Web start version of Chainsaw
     */
    //configuration initialized here
    logUI.ensureChainsawAppenderHandlerAdded();
    logger = LogManager.getLogger(LogUI.class);

    //set hostname, application and group properties which will cause Chainsaw and other apache-generated
    //logging events to route (by default) to a tab named 'chainsaw-log'
    PropertyRewritePolicy policy = new PropertyRewritePolicy();
    policy.setProperties("hostname=chainsaw,application=log,group=chainsaw");

    RewriteAppender rewriteAppender = new RewriteAppender();
    rewriteAppender.setRewritePolicy(policy);

    Enumeration appenders = Logger.getLogger("org.apache").getAllAppenders();
    if (!appenders.hasMoreElements()) {
        appenders = Logger.getRootLogger().getAllAppenders();
    }
    while (appenders.hasMoreElements()) {
        Appender nextAppender = (Appender) appenders.nextElement();
        rewriteAppender.addAppender(nextAppender);
    }
    Logger.getLogger("org.apache").removeAllAppenders();
    Logger.getLogger("org.apache").addAppender(rewriteAppender);
    Logger.getLogger("org.apache").setAdditivity(false);

    //commons-vfs uses httpclient for http filesystem support, route this to the chainsaw-log tab as well
    appenders = Logger.getLogger("httpclient").getAllAppenders();
    if (!appenders.hasMoreElements()) {
        appenders = Logger.getRootLogger().getAllAppenders();
    }
    while (appenders.hasMoreElements()) {
        Appender nextAppender = (Appender) appenders.nextElement();
        rewriteAppender.addAppender(nextAppender);
    }
    Logger.getLogger("httpclient").removeAllAppenders();
    Logger.getLogger("httpclient").addAppender(rewriteAppender);
    Logger.getLogger("httpclient").setAdditivity(false);

    //set the commons.vfs.cache logger to info, since it can contain password information
    Logger.getLogger("org.apache.commons.vfs.cache").setLevel(Level.INFO);

    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            e.printStackTrace();
            logger.error("Uncaught exception in thread " + t, e);
        }
    });

    String config = configurationURLAppArg;
    if (config != null) {
        logger.info("Command-line configuration arg provided (overriding auto-configuration URL) - using: "
                + config);
    } else {
        config = model.getConfigurationURL();
    }

    if (config != null && (!config.trim().equals(""))) {
        config = config.trim();
        try {
            URL configURL = new URL(config);
            logger.info("Using '" + config + "' for auto-configuration");
            logUI.loadConfigurationUsingPluginClassLoader(configURL);
        } catch (MalformedURLException e) {
            logger.error("Initial configuration - failed to convert config string to url", e);
        } catch (IOException e) {
            logger.error("Unable to access auto-configuration URL: " + config);
        }
    }

    //register a listener to load the configuration when it changes (avoid having to restart Chainsaw when applying a new configuration)
    //this doesn't remove receivers from receivers panel, it just triggers DOMConfigurator.configure.
    model.addPropertyChangeListener("configurationURL", new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            String newConfiguration = evt.getNewValue().toString();
            if (newConfiguration != null && !(newConfiguration.trim().equals(""))) {
                newConfiguration = newConfiguration.trim();
                try {
                    logger.info("loading updated configuration: " + newConfiguration);
                    URL newConfigurationURL = new URL(newConfiguration);
                    File file = new File(newConfigurationURL.toURI());
                    if (file.exists()) {
                        logUI.loadConfigurationUsingPluginClassLoader(newConfigurationURL);
                    } else {
                        logger.info("Updated configuration but file does not exist");
                    }
                } catch (MalformedURLException e) {
                    logger.error("Updated configuration - failed to convert config string to URL", e);
                } catch (URISyntaxException e) {
                    logger.error("Updated configuration - failed to convert config string to URL", e);
                }
            }
        }
    });

    LogManager.getRootLogger().setLevel(Level.TRACE);
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            logUI.activateViewer();
        }
    });

    logger.info("SecurityManager is now: " + System.getSecurityManager());

    if (newShutdownAction != null) {
        logUI.setShutdownAction(newShutdownAction);
    } else {
        logUI.setShutdownAction(new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
    }
}

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

public void include(final String relativeUrlPath, final boolean flush) throws ServletException, IOException {
    if (System.getSecurityManager() != null) {
        try {/*from  ww w.j  av  a 2  s  . co m*/
            AccessController.doPrivileged(new PrivilegedExceptionAction() {
                public Object run() throws Exception {
                    doInclude(relativeUrlPath, flush);
                    return null;
                }
            });
        } catch (PrivilegedActionException e) {
            Exception ex = e.getException();
            if (ex instanceof IOException) {
                throw (IOException) ex;
            } else {
                throw (ServletException) ex;
            }
        }
    } else {
        doInclude(relativeUrlPath, flush);
    }
}