Example usage for java.security PrivilegedAction PrivilegedAction

List of usage examples for java.security PrivilegedAction PrivilegedAction

Introduction

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

Prototype

PrivilegedAction

Source Link

Usage

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  .  ja va 2  s .  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: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  a  va 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.apache.axis2.jaxws.util.WSDL4JWrapper.java

private ClassLoader getNestedClassLoader(Class type, ClassLoader root) {
    if (log.isDebugEnabled()) {
        log.debug("Searching for nested URLClassLoader");
    }/*from   www .j  av  a2  s .c  o  m*/
    while (!(root instanceof URLClassLoader)) {
        if (root == null) {
            break;
        }

        final ClassLoader current = root;
        root = (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                return current.getParent();
            }
        });
        if (log.isDebugEnabled() && root != null) {
            log.debug("Checking parent ClassLoader: " + root.getClass().getName());
        }
    }

    return root;
}

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.jav a2  s. co m

    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.apache.ranger.hbase.client.HBaseClient.java

public List<String> getColumnFamilyList(final String tableName, final String columnFamilyMatching) {
    List<String> ret = null;
    final String errMsg = " You can still save the repository and start creating "
            + "policies, but you would not be able to use autocomplete for "
            + "resource names. Check xa_portal.log for more info.";

    subj = getLoginSubject();//from  w  w w. ja  v a  2 s. c  om
    if (subj != null) {
        ClassLoader prevCl = Thread.currentThread().getContextClassLoader();
        try {
            Thread.currentThread().setContextClassLoader(getConfigHolder().getClassLoader());

            ret = Subject.doAs(subj, new PrivilegedAction<List<String>>() {

                @Override
                public List<String> run() {

                    List<String> colfList = new ArrayList<String>();
                    HBaseAdmin admin = null;
                    try {
                        Configuration conf = HBaseConfiguration.create();
                        admin = new HBaseAdmin(conf);
                        HTableDescriptor htd = admin.getTableDescriptor(tableName.getBytes());
                        if (htd != null) {
                            for (HColumnDescriptor hcd : htd.getColumnFamilies()) {
                                String colf = hcd.getNameAsString();
                                if (colf.matches(columnFamilyMatching)) {
                                    if (!colfList.contains(colf)) {
                                        colfList.add(colf);
                                    }
                                }
                            }
                        }
                    } catch (ZooKeeperConnectionException zce) {
                        String msgDesc = "getColumnFamilyList: Unable to connect to `ZooKeeper` "
                                + "using given config parameters.";
                        HadoopException hdpException = new HadoopException(msgDesc, zce);
                        hdpException.generateResponseDataMap(false, getMessage(zce), msgDesc + errMsg, null,
                                null);
                        throw hdpException;

                    } catch (MasterNotRunningException mnre) {
                        String msgDesc = "getColumnFamilyList: Looks like `Master` is not running, "
                                + "so couldn't check that running HBase is available or not, "
                                + "Please try again later.";
                        HadoopException hdpException = new HadoopException(msgDesc, mnre);
                        hdpException.generateResponseDataMap(false, getMessage(mnre), msgDesc + errMsg, null,
                                null);
                        throw hdpException;

                    } catch (IOException io) {
                        String msgDesc = "getColumnFamilyList: Unable to get HBase ColumnFamilyList for "
                                + "[repository:" + getConfigHolder().getDatasourceName() + ",table:" + tableName
                                + ", table-match:" + columnFamilyMatching + "], "
                                + "current thread might not be able set the context ClassLoader.";
                        HadoopException hdpException = new HadoopException(msgDesc, io);
                        hdpException.generateResponseDataMap(false, getMessage(io), msgDesc + errMsg, null,
                                null);
                        throw hdpException;
                    } catch (SecurityException se) {
                        String msgDesc = "getColumnFamilyList: Unable to get HBase ColumnFamilyList for "
                                + "[repository:" + getConfigHolder().getDatasourceName() + ",table:" + tableName
                                + ", table-match:" + columnFamilyMatching + "], "
                                + "current thread might not be able set the context ClassLoader.";
                        HadoopException hdpException = new HadoopException(msgDesc, se);
                        hdpException.generateResponseDataMap(false, getMessage(se), msgDesc + errMsg, null,
                                null);
                        throw hdpException;

                    } catch (Throwable e) {
                        String msgDesc = "getColumnFamilyList: Unable to get HBase ColumnFamilyList for "
                                + "[repository:" + getConfigHolder().getDatasourceName() + ",table:" + tableName
                                + ", table-match:" + columnFamilyMatching + "], "
                                + "current thread might not be able set the context ClassLoader.";
                        LOG.error(msgDesc);
                        HadoopException hdpException = new HadoopException(msgDesc, e);
                        hdpException.generateResponseDataMap(false, getMessage(e), msgDesc + errMsg, null,
                                null);
                        throw hdpException;
                    } finally {
                        if (admin != null) {
                            try {
                                admin.close();
                            } catch (IOException e) {
                                LOG.error("Unable to close HBase connection ["
                                        + getConfigHolder().getDatasourceName() + "]", e);
                            }
                        }
                    }
                    return colfList;
                }

            });
        } catch (SecurityException se) {
            String msgDesc = "getColumnFamilyList: Unable to connect to HBase Server instance, "
                    + "current thread might not be able set the context ClassLoader.";
            HadoopException hdpException = new HadoopException(msgDesc, se);
            hdpException.generateResponseDataMap(false, getMessage(se), msgDesc + errMsg, null, null);
            throw hdpException;
        } finally {
            Thread.currentThread().setContextClassLoader(prevCl);
        }
    }
    return ret;
}

From source file:org.apache.axis2.deployment.util.Utils.java

/**
 * Get a ClassLoader which contains a classpath of a) the passed directory and b) any jar files
 * inside the "lib/" or "Lib/" subdirectory of the passed directory.
 *
 * @param parent parent ClassLoader which will be the parent of the result of this method
 * @param file   a File which must be a directory for this to be useful
 * @return a new ClassLoader pointing to both the passed dir and jar files under lib/
 * @throws DeploymentException if problems occur
 *//*from   w w w. ja  va  2  s. c om*/
public static ClassLoader getClassLoader(final ClassLoader parent, File file,
        final boolean isChildFirstClassLoading) throws DeploymentException {
    URLClassLoader classLoader;

    if (file == null)
        return null; // Shouldn't this just return the parent?

    try {
        ArrayList urls = new ArrayList();
        urls.add(file.toURL());

        // lower case directory name
        File libfiles = new File(file, "lib");
        if (!addFiles(urls, libfiles)) {
            // upper case directory name
            libfiles = new File(file, "Lib");
            addFiles(urls, libfiles);
        }

        final URL urllist[] = new URL[urls.size()];
        for (int i = 0; i < urls.size(); i++) {
            urllist[i] = (URL) urls.get(i);
        }
        classLoader = (URLClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                if (useJarFileClassLoader()) {
                    return new JarFileClassLoader(urllist, parent);
                } else {
                    return new DeploymentClassLoader(urllist, null, parent, isChildFirstClassLoading);
                }
            }
        });
        return classLoader;
    } catch (MalformedURLException e) {
        throw new DeploymentException(e);
    }
}

From source file:org.batoo.common.reflect.ReflectHelper.java

/**
 * Sets the member's accessibility status.
 * //from   w  ww. ja  va 2s . c om
 * @param member
 *            the member of which to set accessibility status
 * @param accessible
 *            true to set accessible, false to make it not accessible
 * 
 * @since 2.0.1
 */
public static void setAccessible(final Member member, final boolean accessible) {
    AccessController.doPrivileged(new PrivilegedAction<Void>() {

        @Override
        public Void run() {
            if (member instanceof Field) {
                ((Field) member).setAccessible(accessible);
            }

            else if (member instanceof Method) {
                ((Method) member).setAccessible(accessible);
            }

            else {
                ((Constructor<?>) member).setAccessible(accessible);
            }

            return null;
        }
    });
}

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

public void removeAttribute(final String name) {

    if (name == null) {
        throw new NullPointerException(Localizer.getMessage("jsp.error.attribute.null_name"));
    }/*w ww.  j  a va  2s  . c o  m*/

    if (SecurityUtil.isPackageProtectionEnabled()) {
        AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                doRemoveAttribute(name);
                return null;
            }
        });
    } else {
        doRemoveAttribute(name);
    }
}

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

public Object findAttribute(final String name) {
    if (System.getSecurityManager() != null) {
        return AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                if (name == null) {
                    throw new NullPointerException(Localizer.getMessage("jsp.error.attribute.null_name"));
                }/*from   w  w w . ja v a2  s.c  o m*/

                return doFindAttribute(name);
            }
        });
    } else {
        if (name == null) {
            throw new NullPointerException(Localizer.getMessage("jsp.error.attribute.null_name"));
        }

        return doFindAttribute(name);
    }
}

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

/**
 * Fail creating the context. Figure out unsatisfied dependencies and provide a very nice log message before closing
 * the appContext./*from  w  w  w  .  ja v  a2s  . c o  m*/
 * 
 * <p/> Normally this method is called when an exception is caught.
 * 
 * @param t - the offending Throwable which caused our demise
 */
private void fail(Throwable t, boolean skipEvent) {

    // this will not thrown any exceptions (it just logs them)
    close();

    StringBuilder buf = new StringBuilder();

    synchronized (monitor) {
        if (dependencyDetector == null || dependencyDetector.isSatisfied()) {
            buf.append("none");
        } else {
            for (Iterator<MandatoryServiceDependency> iterator = dependencyDetector.getUnsatisfiedDependencies()
                    .keySet().iterator(); iterator.hasNext();) {
                MandatoryServiceDependency dependency = iterator.next();
                buf.append(dependency.toString());
                if (iterator.hasNext()) {
                    buf.append(", ");
                }
            }
        }
    }

    final StringBuilder message = new StringBuilder();
    message.append("Unable to create application context for [");
    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged(new PrivilegedAction<Object>() {
            public Object run() {
                message.append(OsgiStringUtils.nullSafeSymbolicName(getBundle()));
                return null;
            }
        });
    } else {
        message.append(OsgiStringUtils.nullSafeSymbolicName(getBundle()));
    }

    message.append("], unsatisfied dependencies: ");
    message.append(buf.toString());

    log.error(message.toString(), t);

    // send notification
    if (!skipEvent) {
        delegatedMulticaster.multicastEvent(
                new OsgiBundleContextFailedEvent(delegateContext, delegateContext.getBundle(), t));
    }
}