Example usage for java.security Permission getName

List of usage examples for java.security Permission getName

Introduction

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

Prototype


public final String getName() 

Source Link

Document

Returns the name of this Permission.

Usage

From source file:org.pepstock.jem.ant.tasks.AntBatchSecurityManager.java

@Override
public void checkPermission(Permission perm) {
    // checks if someone add a security manager
    if (perm instanceof RuntimePermission && "setSecurityManager".equalsIgnoreCase(perm.getName())) {
        if (!isAllowedSetSecurityManager()) {
            LogAppl.getInstance().emit(NodeMessage.JEMC274E);
            throw new SecurityException(NodeMessage.JEMC274E.toMessage().getMessage());
        }//from   w  w  w.j  a va 2s. c o m
        return;
    }
    // this check is necessary to avoid that someone
    // set jem properties, accessing outside of GFS
    if (perm instanceof PropertyPermission && "write".equalsIgnoreCase(perm.getActions())
            && perm.getName().startsWith("jem")) {
        LogAppl.getInstance().emit(NodeMessage.JEMC127E);
        throw new SecurityException(NodeMessage.JEMC127E.toMessage().getMessage());
    }
    // checks is administrator. if true return.
    if (isAdministrator() || isInternalAction()) {
        return;
    }
    // checks the file access
    // calling the right method, in according
    // with the action of permission
    if (perm instanceof FilePermission) {
        if ("read".equalsIgnoreCase(perm.getActions())) {
            checkRead(perm.getName());
        } else if ("write".equalsIgnoreCase(perm.getActions())) {
            checkWrite(perm.getName());
        } else if ("delete".equalsIgnoreCase(perm.getActions())) {
            checkDelete(perm.getName());
        } else {
            checkRead(perm.getName());
        }
    } else if (perm instanceof SocketPermission) {
        // checks the RMI access.
        // checks to RMI is not allowed if you're not a admin
        SocketPermission sperm = (SocketPermission) perm;
        int port = Parser.parseInt(StringUtils.substringAfter(sperm.getName(), ":"), Integer.MAX_VALUE);
        int portRmi = Parser.parseInt(System.getProperty(RmiKeys.JEM_RMI_PORT), Integer.MIN_VALUE);
        // if is going to RMI port and
        // is not executing JEM code and is not grantor
        if (port == portRmi && !isInternalAction() && !isGrantor()) {
            // extracts host name
            String hostname = StringUtils.substringBefore(sperm.getName(), ":");
            try {
                // gets hostname and localhost
                String resolved = InetAddress.getByName(hostname).getHostAddress();
                String localhost = InetAddress.getLocalHost().getHostAddress();
                // if they are equals and the user
                // desn't have the internal service permission
                // EXCEPTION!!
                if (resolved.equalsIgnoreCase(localhost)
                        && !checkBatchPermission(Permissions.INTERNAL_SERVICES)) {
                    LogAppl.getInstance().emit(NodeMessage.JEMC128E);
                    throw new SecurityException(NodeMessage.JEMC128E.toMessage().getMessage());
                }
            } catch (UnknownHostException e) {
                // if there is an error on resolving the hostname
                LogAppl.getInstance().emit(NodeMessage.JEMC128E);
                throw new SecurityException(NodeMessage.JEMC128E.toMessage().getMessage(), e);
            }
        }
    }
}

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

public Permission getPermission(Principal prpal, Class permClass, String permName) {
    PermissionCollection permCollection = getPermissions(prpal);
    if (permCollection != null) {
        Enumeration en = permCollection.elements();
        while (en.hasMoreElements()) {
            Permission perm = (Permission) en.nextElement();
            if (perm.getName().equals(permName) && perm.getClass().getName().equals(permClass.getName())) {
                return perm;
            }/*from   w  w w  . j a  v a2s . c o m*/
        }
    }
    return null;
}

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

public Map getPermissions(Object resource, Class permClass) throws Exception {
    final Map results = new HashMap();

    Method getResName = permClass.getMethod("getResourceName", new Class[] { Object.class });
    String resourceName = (String) getResName.invoke(permClass, new Object[] { resource });

    for (Iterator it = permissionMap.entrySet().iterator(); it.hasNext();) {
        Map.Entry entry = (Map.Entry) it.next();
        Permissions perms = (Permissions) entry.getValue();
        for (Enumeration en = perms.elements(); en.hasMoreElements();) {
            Permission perm = (Permission) en.nextElement();
            if (perm.getName().equals(resourceName) && permClass.equals(perm.getClass())) {
                results.put(entry.getKey(), perm);
            }// w w  w  .ja va 2s.c  o m
        }
    }
    return results;
}

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

public void removePermissions(Principal p, String resourceName) {

    Permissions prpalPermissions = (Permissions) permissionMap.get(p);
    if (prpalPermissions != null && resourceName != null) {

        // Search for permissions related with the specified resource.
        List toRemove = new ArrayList();
        Enumeration en = prpalPermissions.elements();
        DefaultPermission resPerm = new DefaultPermission(resourceName, null);
        DefaultPermission regPerm = new DefaultPermission(resourceName, null);
        while (en.hasMoreElements()) {
            Permission permission = (Permission) en.nextElement();
            regPerm.setResourceName(permission.getName());
            if (resPerm.implies(regPerm))
                toRemove.add(permission);
        }/*from  ww  w . j a va  2  s  . co  m*/

        // Remove permissions
        Iterator it = toRemove.iterator();
        while (it.hasNext())
            this.removePermission(p, (Permission) it.next());
    }
}

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

/**
 * <p>/*from   www. j ava2s  . c  om*/
 * Returns the {@link InternalPermission} from a Permission.
 * </p>
 * 
 * @param permission The permission.
 * @return The {@link InternalPermission}.
 */
InternalPermission getInternalPermission(Permission permission) {
    Criteria filter = new Criteria();
    filter.addEqualTo("classname", permission.getClass().getName());
    filter.addEqualTo("name", permission.getName());
    filter.addEqualTo("actions", permission.getActions());
    Query query = QueryFactory.newQuery(InternalPermissionImpl.class, filter);
    InternalPermission internalPermission = (InternalPermission) broker.getObjectByQuery(query);
    return internalPermission;
}

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

/**
 * @see org.apache.jetspeed.security.PermissionManager#addPermission(java.security.Permission)
 *///from   w  w  w  .j  a  v a 2 s.  c  om
public void addPermission(Permission permission) throws SecurityException {
    ArgUtil.notNull(new Object[] { permission }, new String[] { "permission" },
            "addPermission(java.security.Permission)");

    InternalPermission internalPermission = new InternalPermissionImpl(permission.getClass().getName(),
            permission.getName(), permission.getActions());
    try {
        broker.beginTransaction();
        broker.store(internalPermission);
        broker.commitTransaction();
    } catch (Exception e) {
        KeyedMessage msg = SecurityException.UNEXPECTED.create("PermissionManager.addPermission", "store",
                e.getMessage());
        log.error(msg, e);
        broker.abortTransaction();
        throw new SecurityException(msg, e);
    }
}

From source file:com.yeldi.yeldibazaar.AppDetails.java

private void startViews() {

    // Populate the list...
    ApkListAdapter la = (ApkListAdapter) getListAdapter();
    for (DB.Apk apk : app.apks)
        la.addItem(apk);//from  w w w . j a  v a  2s.  com
    la.notifyDataSetChanged();

    // Insert the 'infoView' (which contains the summary, various odds and
    // ends, and the description) into the appropriate place, if we're in
    // landscape mode. In portrait mode, we put it in the listview's
    // header..
    infoView = View.inflate(this, R.layout.appinfo, null);
    LinearLayout landparent = (LinearLayout) findViewById(R.id.landleft);
    headerView.removeAllViews();
    if (landparent != null) {
        landparent.addView(infoView);
        Log.d("FDroid", "Setting landparent infoview");
    } else {
        headerView.addView(infoView);
        Log.d("FDroid", "Setting header infoview");
    }

    // Set the icon...
    ImageView iv = (ImageView) findViewById(R.id.icon);
    File icon = new File(DB.getIconsPath(this), app.icon);
    if (icon.exists()) {
        iv.setImageDrawable(new BitmapDrawable(icon.getPath()));
    } else {
        iv.setImageResource(android.R.drawable.sym_def_app_icon);
    }

    // Set the title and other header details...
    TextView tv = (TextView) findViewById(R.id.title);
    tv.setText(app.name);
    tv = (TextView) findViewById(R.id.license);
    tv.setText(app.license);
    tv = (TextView) findViewById(R.id.status);

    tv = (TextView) infoView.findViewById(R.id.description);

    /*
     * The following is a quick solution to enable both text selection and
     * links. Causes glitches and crashes:
     * java.lang.IndexOutOfBoundsException: setSpan (-1 ... -1) starts
     * before 0
     * 
     * class CustomMovementMethod extends LinkMovementMethod {
     * 
     * @Override public boolean canSelectArbitrarily () { return true; } }
     * 
     * if (Utils.hasApi(11)) { tv.setTextIsSelectable(true);
     * tv.setMovementMethod(new CustomMovementMethod()); } else {
     * tv.setMovementMethod(LinkMovementMethod.getInstance()); }
     */

    tv.setMovementMethod(LinkMovementMethod.getInstance());

    // Need this to add the unimplemented support for ordered and unordered
    // lists to Html.fromHtml().
    class HtmlTagHandler implements TagHandler {
        int listNum;

        @Override
        public void handleTag(boolean opening, String tag, Editable output, XMLReader reader) {
            if (opening && tag.equals("ul")) {
                listNum = -1;
            } else if (opening && tag.equals("ol")) {
                listNum = 1;
            } else if (tag.equals("li")) {
                if (opening) {
                    if (listNum == -1) {
                        output.append("\t");
                    } else {
                        output.append("\t" + Integer.toString(listNum) + ". ");
                        listNum++;
                    }
                } else {
                    output.append('\n');
                }
            }
        }
    }
    tv.setText(Html.fromHtml(app.detail_description, null, new HtmlTagHandler()));

    tv = (TextView) infoView.findViewById(R.id.appid);
    tv.setText(app.id);

    tv = (TextView) infoView.findViewById(R.id.summary);
    tv.setText(app.summary);

    if (!app.apks.isEmpty()) {
        tv = (TextView) infoView.findViewById(R.id.permissions_list);

        CommaSeparatedList permsList = app.apks.get(0).detail_permissions;
        if (permsList == null) {
            tv.setText(getString(R.string.no_permissions) + '\n');
        } else {
            Iterator<String> permissions = permsList.iterator();
            StringBuilder sb = new StringBuilder();
            while (permissions.hasNext()) {
                String permissionName = permissions.next();
                try {
                    Permission permission = new Permission(this, permissionName);
                    sb.append("\t " + permission.getName() + '\n');
                } catch (NameNotFoundException e) {
                    Log.d("FDroid", "Can't find permission '" + permissionName + "'");
                }
            }
            tv.setText(sb.toString());
        }
        tv = (TextView) infoView.findViewById(R.id.permissions);
        tv.setText(getString(R.string.permissions_for_long, app.apks.get(0).version));
    }
}

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  ww w  .  j av  a  2s  . c o  m*/
 * 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:de.ingrid.usermanagement.jetspeed.IngridPermissionManager.java

/**
 * <p>// w w w  .ja v a  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:org.eclipse.wb.internal.core.DesignerPlugin.java

/**
 * We should not allow user code to terminate JVM.
 *//*from w  w w  .  j a  va 2  s  .c o  m*/
public static void installSecurityManager() {
    System.setSecurityManager(new SecurityManager() {
        @Override
        public void checkPermission(java.security.Permission perm) {
            if (isExitVM(perm)) {
                StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
                for (StackTraceElement element : stackTrace) {
                    String className = element.getClassName();
                    String methodName = element.getMethodName();
                    // ignore this class, because it has our class name prefix
                    if (className.equals(getClass().getName())) {
                        continue;
                    }
                    // ignore JFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    if (className.equals("javax.swing.JFrame")
                            && methodName.equals("setDefaultCloseOperation")) {
                        return;
                    }
                    // prevent exit() from user invoked by "designer"
                    if (className.startsWith("org.eclipse.wb.")
                            || className.startsWith("com.google.gdt.eclipse.designer.")
                            || className.startsWith("net.rim.ejde.designer.")
                            || className.startsWith("java.awt.EventQueue")) {
                        // we often use test_exit() method as point to stop tests, allow it
                        if (methodName.startsWith("test_") && methodName.endsWith("_exit")) {
                            return;
                        }
                        // prevent exit()
                        throw new SecurityException("Exit from within user-loaded code");
                    }
                }
            }
        }

        private boolean isExitVM(java.security.Permission perm) {
            return perm instanceof RuntimePermission && StringUtils.startsWith(perm.getName(), "exitVM");
        }
    });
}