Example usage for java.security Permissions add

List of usage examples for java.security Permissions add

Introduction

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

Prototype

@Override
public void add(Permission permission) 

Source Link

Document

Adds a permission object to the PermissionCollection for the class the permission belongs to.

Usage

From source file:org.pegadi.client.ApplicationLauncher.java

private static void setAllPermissions() {
    // give all permissions. needed when run from java web start, because
    // the rmi classloaders don't heed the security settings in the .jnlp
    // file.//w  ww.j a  v  a 2s .co m
    try {
        Policy.setPolicy(new Policy() {
            public PermissionCollection getPermissions(CodeSource codesource) {
                Permissions perms = new Permissions();
                perms.add(new AllPermission());
                return (perms);
            }

            public void refresh() {
            }
        });
    } catch (Exception wse) {
        LoggerFactory.getLogger(ApplicationLauncher.class).error("Error setting policies", wse);
        System.exit(-1);
    }
}

From source file:de.innovationgate.wgpublisher.expressions.tmlscript.IsolatedJARLoader.java

@Override
protected PermissionCollection getPermissions(CodeSource arg0) {
    Permissions permissions = new Permissions();
    permissions.add(new AllPermission());
    return permissions;
}

From source file:com.jaspersoft.jasperserver.api.engine.jasperreports.util.PermissionsListProtectionDomainProvider.java

protected PermissionCollection getPermissionCollection() {
    Permissions permissionCollection = new Permissions();
    if (permissions != null) {
        for (Permission permission : permissions) {
            permissionCollection.add(permission);
        }/* w  w w  .  j  a v  a  2 s  .c  om*/
    }
    return permissionCollection;
}

From source file:com.googlecode.onevre.utils.ServerClassLoader.java

/**
 *
 * @see java.security.SecureClassLoader#getPermissions(
 *     java.security.CodeSource)//from w w  w  . j  a v  a2 s. co  m
 */
protected PermissionCollection getPermissions(CodeSource codesource) {
    boolean isAcceptable = false;
    if (!CHECKED.containsKey(codesource.getLocation())) {
        Certificate[] certs = codesource.getCertificates();
        if (certs == null || certs.length == 0) {
            JOptionPane.showMessageDialog(null, "The jar at " + codesource.getLocation() + " is not signed!",
                    "Security Error", JOptionPane.ERROR_MESSAGE);
            isAcceptable = false;
        } else {
            isAcceptable = true;
            for (int i = 0; (i < certs.length) && isAcceptable; i++) {
                if (!verifyCertificate((X509Certificate) certs[i])) {
                    isAcceptable = false;
                }
            }
        }
        CHECKED.put(codesource.getLocation(), isAcceptable);
    } else {
        isAcceptable = CHECKED.get(codesource.getLocation());
    }

    Permissions permissions = new Permissions();
    if (isAcceptable) {
        permissions.add(new AllPermission());
        return permissions;
    }
    throw new SecurityException("Access denied to " + codesource.getLocation());
}

From source file:com.sun.socialsite.business.impl.JPAPermissionManagerImpl.java

private Permissions getPermissions(SecurityToken token) throws SocialSiteException {

    try {/* w ww.  ja v a2s. co  m*/

        Permissions permissions = new Permissions();
        List<PermissionGrant> permissionGrants = new ArrayList<PermissionGrant>();

        if (token != null) {
            if (token instanceof SocialSiteToken && ((SocialSiteToken) token).isForContainerPage()) {
                permissions.add(new FeaturePermission("*"));
            }
            if (token.getAppId() != null) {
                App app = Factory.getSocialSite().getAppManager().getApp(token.getAppId());
                permissionGrants.addAll(getPermissionGrants(app, 0, -1));
                permissionGrants.addAll(getPermissionGrants(app.getURL().getHost(), 0, -1));
            }
            if (token.getViewerId() != null) {
                Profile viewer = Factory.getSocialSite().getProfileManager()
                        .getProfileByUserId(token.getViewerId());
                permissionGrants.addAll(getPermissionGrants(viewer, 0, -1));
            }
        }

        for (PermissionGrant permissionGrant : permissionGrants) {
            String type = permissionGrant.getType();
            String name = permissionGrant.getName();
            String actions = permissionGrant.getActions();
            try {
                Class<?> clazz = Class.forName(type);
                Permission permission = null;
                if (actions == null) {
                    Constructor constructor = clazz.getConstructor(String.class);
                    permission = (Permission) (constructor.newInstance(name));
                } else {
                    Constructor constructor = clazz.getConstructor(String.class, String.class);
                    permission = (Permission) (constructor.newInstance(name, actions));
                }
                permissions.add(permission);
            } catch (Exception e) {
                String msg = String.format("Failed to construct Permission(type=%s,name=%s,actions=%s)", type,
                        name, actions);
                log.error(msg, e);
            }
        }

        return permissions;

    } catch (Exception e) {
        log.error("token=" + token);
        throw (SocialSiteException) ((e instanceof SocialSiteException) ? e : new SocialSiteException(e));
    }

}

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 {//from   ww w . ja v  a 2s  . c  om
        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:de.ingrid.usermanagement.jetspeed.IngridPermissionManager.java

/**
 * <p>//from   ww w. j a  va 2  s.c  om
 * Iterate through a collection of {@link InternalPermission}and build a
 * unique collection of {@link java.security.Permission}.
 * </p>
 * 
 * @param omPermissions The collection of {@link InternalPermission}.
 * @return The collection of {@link java.security.Permission}.
 */
private Permissions appendSecurityPermissions(Collection omPermissions, Permissions permissions) {
    Iterator internalPermissionsIter = omPermissions.iterator();
    while (internalPermissionsIter.hasNext()) {
        InternalPermission internalPermission = (InternalPermission) internalPermissionsIter.next();
        Permission permission = null;
        try {
            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) permissionConstructor.newInstance(initArgs);
            if (!Collections.list(permissions.elements()).contains(permission)) {
                if (log.isDebugEnabled()) {
                    log.debug("Adding permimssion: [class, " + permission.getClass().getName() + "], "
                            + "[name, " + permission.getName() + "], " + "[actions, " + permission.getActions()
                            + "]");
                }
                permissions.add(permission);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return permissions;
}

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 o m*/
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: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/* ww w.j a v  a 2s . com*/
 * @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.jboss.dashboard.security.UIPolicy.java

public synchronized void addPermission(Principal prpal, Permission perm) {
    try {//from  ww  w. j a  va  2 s .c om

        // 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);
    }
}