Example usage for java.security Permissions Permissions

List of usage examples for java.security Permissions Permissions

Introduction

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

Prototype

public Permissions() 

Source Link

Document

Creates a new Permissions object containing no PermissionCollections.

Usage

From source file:de.ingrid.usermanagement.jetspeed.IngridPermissionManager.java

public Permissions getPermissions(String classname, String resource) {
    Criteria filter = new Criteria();
    filter.addEqualTo("classname", classname);
    filter.addEqualTo("name", resource);
    Query query = QueryFactory.newQuery(InternalPermissionImpl.class, filter);
    Collection internalPermissions = broker.getCollectionByQuery(query);
    Permissions permissions = new Permissions();
    Iterator iter = internalPermissions.iterator();
    try {// ww w. j  a  v a 2 s  .  co m
        while (iter.hasNext()) {
            InternalPermission internalPermission = (InternalPermission) iter.next();
            Class permissionClass = Class.forName(internalPermission.getClassname());
            Class[] parameterTypes = { String.class, String.class };
            Constructor permissionConstructor = permissionClass.getConstructor(parameterTypes);
            Object[] initArgs = { internalPermission.getName(), internalPermission.getActions() };
            Permission permission = (Permission) permissionConstructor.newInstance(initArgs);
            permissions.add(permission);
        }
    } catch (Exception e) {
        log.error("Failed to retrieve permissions", e);
    }
    return permissions;
}

From source file:com.stratuscom.harvester.deployer.StarterServiceDeployer.java

private static Permission[] expandUmbrella(Permission[] perms) {
    PermissionCollection pc = new Permissions();

    for (Permission p : perms) {
        pc.add(p);//from  www  .  ja  v a 2 s.c  o  m
    }
    if (pc.implies(new UmbrellaGrantPermission())) {
        List l = Collections.list(pc.elements());
        pc.add(new GrantPermission((Permission[]) l.toArray(new Permission[l.size()])));
    }
    List<Permission> permList = new ArrayList<Permission>();

    for (Enumeration<Permission> en = pc.elements(); en.hasMoreElements();) {
        permList.add(en.nextElement());
    }
    return permList.toArray(new Permission[0]);
}

From source file:com.threerings.getdown.data.Application.java

/**
 * Runs this application directly in the current VM.
 *//*from w w w.j  a v  a 2  s  . c  om*/
public void invokeDirect(JApplet applet) throws IOException {
    ClassPath classPath = ClassPaths.buildClassPath(this);
    URL[] jarUrls = classPath.asUrls();

    // create custom class loader
    URLClassLoader loader = new URLClassLoader(jarUrls, ClassLoader.getSystemClassLoader()) {
        @Override
        protected PermissionCollection getPermissions(CodeSource code) {
            Permissions perms = new Permissions();
            perms.add(new AllPermission());
            return perms;
        }
    };
    Thread.currentThread().setContextClassLoader(loader);

    log.info("Configured URL class loader:");
    for (URL url : jarUrls)
        log.info("  " + url);

    // configure any system properties that we can
    for (String jvmarg : _jvmargs) {
        if (jvmarg.startsWith("-D")) {
            jvmarg = processArg(jvmarg.substring(2));
            int eqidx = jvmarg.indexOf("=");
            if (eqidx == -1) {
                log.warning("Bogus system property: '" + jvmarg + "'?");
            } else {
                System.setProperty(jvmarg.substring(0, eqidx), jvmarg.substring(eqidx + 1));
            }
        }
    }

    // pass along any pass-through arguments
    Map<String, String> passProps = new HashMap<String, String>();
    for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
        String key = (String) entry.getKey();
        if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
            key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
            passProps.put(key, (String) entry.getValue());
        }
    }
    // we can't set these in the above loop lest we get a ConcurrentModificationException
    for (Map.Entry<String, String> entry : passProps.entrySet()) {
        System.setProperty(entry.getKey(), entry.getValue());
    }

    // make a note that we're running in "applet" mode
    System.setProperty("applet", "true");

    // prepare our app arguments
    String[] args = new String[_appargs.size()];
    for (int ii = 0; ii < args.length; ii++)
        args[ii] = processArg(_appargs.get(ii));

    try {
        log.info("Loading " + _class);
        Class<?> appclass = loader.loadClass(_class);
        Method main;
        try {
            // first see if the class has a special applet-aware main
            main = appclass.getMethod("main", JApplet.class, SA_PROTO.getClass());
            log.info("Invoking main(JApplet, {" + StringUtil.join(args, ", ") + "})");
            main.invoke(null, new Object[] { applet, args });
        } catch (NoSuchMethodException nsme) {
            main = appclass.getMethod("main", SA_PROTO.getClass());
            log.info("Invoking main({" + StringUtil.join(args, ", ") + "})");
            main.invoke(null, new Object[] { args });
        }
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}

From source file:net.lightbody.bmp.proxy.jetty.http.HttpContext.java

/** Add a permission to this context.
 * The collection of permissions set here are used for all classes
 * loaded by this context.  This is simpler that creating a
 * security policy file, as not all code sources may be statically
 * known.//  w ww  .  j  a  v  a 2 s  .  c  o m
 * @param permission
 */
public void addPermission(Permission permission) {
    if (_permissions == null)
        _permissions = new Permissions();
    _permissions.add(permission);
}

From source file:org.apache.geronimo.tomcat.deployment.TomcatModuleBuilderTest.java

private WebModuleInfo deployWar(String warName) throws Exception {
    File outputPath = new File(BASEDIR, "target/test-resources/deployables/" + warName);
    recursiveDelete(outputPath);//from   w ww .  ja va2s .  c o m
    outputPath.mkdirs();
    File path = new File(BASEDIR, "src/test/resources/deployables/" + warName);
    //File dest = new File(BASEDIR, "target/test-resources/deployables/" + warName + "/war");
    File dest = new File(BASEDIR, "target/test-resources/deployables/" + warName);
    recursiveCopy(path, dest);
    UnpackedJarFile jarFile = new UnpackedJarFile(path);
    Module module = builder.createModule(null, jarFile, kernel.getNaming(), new ModuleIDBuilder());
    Repository repository = null;

    AbstractName moduleName = module.getModuleName();
    EARContext earContext = createEARContext(outputPath, defaultEnvironment, repository, configStore,
            moduleName);
    AbstractName jaccBeanName = kernel.getNaming().createChildName(moduleName, "foo",
            SecurityNames.JACC_MANAGER);
    GBeanData jaccBeanData = new GBeanData(jaccBeanName, ApplicationPolicyConfigurationManager.GBEAN_INFO);
    PermissionCollection excludedPermissions = new Permissions();
    PermissionCollection uncheckedPermissions = new Permissions();
    ComponentPermissions componentPermissions = new ComponentPermissions(excludedPermissions,
            uncheckedPermissions, new HashMap());
    Map contextIDToPermissionsMap = new HashMap();
    contextIDToPermissionsMap.put(
            "test_J2EEApplication=null_J2EEServer=bar_j2eeType=WebModule_name=geronimo/test/1.0/war",
            componentPermissions);
    jaccBeanData.setAttribute("contextIdToPermissionsMap", contextIDToPermissionsMap);
    //        jaccBeanData.setAttribute("principalRoleMap", new HashMap());
    jaccBeanData.setAttribute("roleDesignates", new HashMap());
    earContext.addGBean(jaccBeanData);
    earContext.getGeneralData().put(GeronimoSecurityBuilderImpl.ROLE_MAPPER_DATA_NAME, jaccBeanName);
    module.setEarContext(earContext);
    module.setRootEarContext(earContext);
    builder.initContext(earContext, module, bundle);
    builder.addGBeans(earContext, module, bundle, null);
    ConfigurationData configurationData = earContext.getConfigurationData();
    earContext.close();
    module.close();

    Artifact configurationId = configurationData.getId();
    configurationManager.loadConfiguration(configurationData);
    Configuration configuration = configurationManager.getConfiguration(configurationId);
    configurationManager.startConfiguration(configurationId);

    return new WebModuleInfo(moduleName, configuration);
}

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/*  w w  w.ja va  2  s  . c om*/
 * @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.echocat.nodoodle.classloading.FileClassLoader.java

private Class<?> defineClass(String name, Resource resource) throws IOException {
    final int i = name.lastIndexOf('.');
    final URL packageUrl = resource.getPackageUrl();
    if (i != -1) {
        final String packageName = name.substring(0, i);
        // Check if package already loaded.
        final Package pkg = getPackage(packageName);
        final Manifest man = resource.getManifest();
        if (pkg != null) {
            // Package found, so check package sealing.
            if (pkg.isSealed()) {
                // Verify that code source URL is the same.
                if (!pkg.isSealed(packageUrl)) {
                    throw new SecurityException("sealing violation: package " + packageName + " is sealed");
                }/*  w  ww  .  ja v a  2 s .  c om*/
            } else {
                // Make sure we are not attempting to seal the package
                // at this code source URL.
                if ((man != null) && isSealed(packageName, man)) {
                    throw new SecurityException(
                            "sealing violation: can't seal package " + packageName + ": already loaded");
                }
            }
        } else {
            if (man != null) {
                definePackage(packageName, man, packageUrl);
            } else {
                definePackage(packageName, null, null, null, null, null, null, null);
            }
        }
    }
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final InputStream inputStream = resource.openStream();
    try {
        IOUtils.copy(inputStream, baos);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
    final byte[] bytes = baos.toByteArray();
    final CodeSigner[] signers = resource.getCodeSigners();
    final CodeSource cs = new CodeSource(packageUrl, signers);
    return defineClass(name, bytes, 0, bytes.length, new ProtectionDomain(cs, new Permissions()));
}

From source file:org.jboss.dashboard.security.UIPolicy.java

public synchronized void addPermission(Principal prpal, Permission perm) {
    try {/*  w ww.  ja  v a2 s .c  o  m*/

        // No principal specified then use unspecified principal
        Principal key = prpal;
        if (key == null)
            key = UNSPECIFIED_PRINCIPAL;

        log.debug("Adding permission " + perm + " for principal " + prpal);
        Permissions prpalPermissions = (Permissions) permissionMap.get(key);
        if (prpalPermissions == null) {
            prpalPermissions = new Permissions();
            permissionMap.put(key, prpalPermissions);
        }
        // If the permission is already granted then the new permission will be ignored when calling the following method,
        // So we don't have to implement any redundancy control.
        prpalPermissions.add(perm);

        // Update the persistent descriptor.
        PermissionDescriptor pd = PermissionManager.lookup().find(key, perm);
        if (pd == null)
            pd = PermissionManager.lookup().createNewItem();
        pd.setPrincipal(key);
        pd.setPermission(perm);
        pd.setReadonly(((UIPermission) perm).isReadOnly());

        // If the update buffer already contains the permission descriptor then remove it.
        int pos = updateBuffer.indexOf(pd);
        if (pos != -1)
            updateBuffer.remove(pos);
        updateBuffer.add(pd);
    } catch (Exception e) {
        log.error("Error: ", e);
    }
}

From source file:org.jboss.dashboard.security.UIPolicy.java

public synchronized void removePermission(Principal p, Permission perm) {
    // Update buffers
    PermissionDescriptor pd = PermissionManager.lookup().find(p, perm);
    if (pd != null && !pd.isReadonly()) {
        int pos = updateBuffer.indexOf(pd);
        if (pos != -1)
            updateBuffer.remove(pos);/*from w ww  . j a v  a  2  s  . c  o m*/
        pos = deleteBuffer.indexOf(pd);
        if (pos == -1)
            deleteBuffer.add(pd);

        // Remove the permission from memory
        if (log.isDebugEnabled())
            log.debug("Removing permission " + perm + " for principal " + p);
        Permissions prpalPermissions = (Permissions) permissionMap.get(p);
        if (prpalPermissions != null) {
            Permissions newPermissions = new Permissions();
            Enumeration en = prpalPermissions.elements();
            while (en.hasMoreElements()) {
                Permission permission = (Permission) en.nextElement();
                if (!perm.equals(permission))
                    newPermissions.add(permission);
            }
            permissionMap.put(p, newPermissions);
        }
    }
}

From source file:org.jboss.dashboard.security.UIPolicy.java

public PermissionCollection getPermissions(Subject usr) {
    Permissions userPermissions = new Permissions();
    Iterator it = usr.getPrincipals().iterator();
    while (it.hasNext()) {
        Principal principal = (Principal) it.next();
        Permissions permissions = (Permissions) permissionMap.get(principal);
        if (permissions != null) {
            Enumeration permEnum = permissions.elements();
            while (permEnum.hasMoreElements()) {
                Permission perm = (Permission) permEnum.nextElement();
                userPermissions.add(perm);
            }//from ww  w .j av a 2s  . c om
        }
    }

    // Also retrieve permission assigned to the unspecified principal
    Permissions permissions = (Permissions) permissionMap.get(UNSPECIFIED_PRINCIPAL);
    if (permissions != null) {
        Enumeration permEnum = permissions.elements();
        while (permEnum.hasMoreElements()) {
            Permission perm = (Permission) permEnum.nextElement();
            userPermissions.add(perm);
        }
    }

    return userPermissions;
}