Example usage for java.security AccessController doPrivileged

List of usage examples for java.security AccessController doPrivileged

Introduction

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

Prototype

@CallerSensitive
public static <T> T doPrivileged(PrivilegedExceptionAction<T> action) throws PrivilegedActionException 

Source Link

Document

Performs the specified PrivilegedExceptionAction with privileges enabled.

Usage

From source file:de.erdesignerng.util.ApplicationPreferences.java

public ClassLoader createDriverClassLoader() {

    final URL[] theUrls = new URL[classpathfiles.size()];
    for (int i = 0; i < classpathfiles.size(); i++) {
        try {/*ww  w  .  ja  va2  s.  c  om*/
            theUrls[i] = classpathfiles.get(i).toURI().toURL();
        } catch (MalformedURLException e) {
            // This will never happen
        }
    }

    return AccessController.doPrivileged((PrivilegedAction<ClassLoader>) () -> new URLClassLoader(theUrls,
            Thread.currentThread().getContextClassLoader()));
}

From source file:org.apache.openjpa.meta.MetaDataRepository.java

/**
* If the openjpa.MetaDataRepository plugin value Preload=true is set, this method will load all
* MetaData for all persistent classes and will remove locking from this class. 
*///from www  . j ava  2 s . com
public synchronized void preload() {
    if (_preload == false) {
        return;
    }
    // If pooling EMFs, this method may be invoked more than once. Only perform this work once.
    if (_preloadComplete == true) {
        return;
    }

    MultiClassLoader multi = AccessController.doPrivileged(J2DoPrivHelper.newMultiClassLoaderAction());
    multi.addClassLoader(AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction()));
    multi.addClassLoader(
            AccessController.doPrivileged(J2DoPrivHelper.getClassLoaderAction(MetaDataRepository.class)));
    // If a ClassLoader was passed into Persistence.createContainerEntityManagerFactory on the PersistenceUnitInfo
    // we need to add that loader to the chain of classloaders
    ClassResolver resolver = _conf.getClassResolverInstance();
    if (resolver != null) {
        ClassLoader cl = resolver.getClassLoader(null, null);
        if (cl != null) {
            multi.addClassLoader(cl);
        }
    }

    Set<String> classes = getPersistentTypeNames(false, multi);
    if (classes == null || classes.size() == 0) {
        throw new MetaDataException(_loc.get("repos-initializeEager-none"));
    }
    if (_log.isTraceEnabled() == true) {
        _log.trace(_loc.get("repos-initializeEager-found", classes));
    }

    List<Class<?>> loaded = new ArrayList<Class<?>>();
    for (String c : classes) {
        try {
            Class<?> cls = AccessController.doPrivileged((J2DoPrivHelper.getForNameAction(c, true, multi)));
            loaded.add(cls);
            // This call may be unnecessary?
            _factory.load(cls, MODE_ALL, multi);
        } catch (PrivilegedActionException pae) {
            throw new MetaDataException(_loc.get("repos-initializeEager-error"), pae);
        }
    }
    resolveAll(multi);

    // Preload XML MetaData
    for (Class<?> cls : loaded) {
        ClassMetaData cmd = getCachedMetaData(cls);
        if (cmd != null) {
            getXMLMetaData(cls);
            for (FieldMetaData fmd : cmd.getFields()) {
                getXMLMetaData(fmd.getDeclaredType());
            }
        }
    }

    // Hook in this class as a listener and process registered classes list to populate _aliases
    // list.
    PCRegistry.addRegisterClassListener(this);
    processRegisteredClasses(multi);
    _locking = false;
    _preloadComplete = true;
}

From source file:Classes.java

/**
 * Get a system property//w  w w .  jav  a 2  s  .  co m
 * 
 * @param name
 *          the property name
 * @param defaultValue
 *          the default value
 */
private static String getProperty(final String name, final String defaultValue) {
    return (String) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return System.getProperty(name, defaultValue);
        }
    });
}

From source file:org.apache.openjpa.enhance.PCEnhancer.java

/**
 * Constructor. Supply configuration and type to enhance. This will look
 * up the metadata for <code>meta</code> by converting back to a class
 * and then loading from <code>conf</code>'s repository.
 *//*from w  ww.jav  a2s.  c  om*/
public PCEnhancer(OpenJPAConfiguration conf, ClassMetaData meta) {
    this(conf,
            AccessController.doPrivileged(
                    J2DoPrivHelper.loadProjectClassAction(new Project(), meta.getDescribedType())),
            meta.getRepository());
}

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

public void removeAttribute(final String name, final int scope) {

    if (name == null) {
        throw new NullPointerException(Localizer.getMessage("jsp.error.attribute.null_name"));
    }//www  . j a va2 s .  c  o  m
    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                doRemoveAttribute(name, scope);
                return null;
            }
        });
    } else {
        doRemoveAttribute(name, scope);
    }
}

From source file:com.ellychou.todo.rest.service.SpringContextJerseyTest.java

private String getProperty(String propertyName) {
    if (forcedPropertyMap.containsKey(propertyName)) {
        return forcedPropertyMap.get(propertyName);
    }//from   w w w .  jav a  2s.c o m

    final Properties systemProperties = AccessController.doPrivileged(PropertiesHelper.getSystemProperties());
    if (systemProperties.containsKey(propertyName)) {
        return systemProperties.getProperty(propertyName);
    }

    if (propertyMap.containsKey(propertyName)) {
        return propertyMap.get(propertyName);
    }

    return null;
}

From source file:org.apache.openjpa.persistence.PersistenceMetaDataDefaults.java

/**
 * Determines the access type for the given class by placement of 
 * annotations on field or getter method. Does not consult the
 * super class./*from   w w w  . j  ava 2s. com*/
 * 
 * Annotation can be placed on either fields or getters but not on both.
 * If no field or getter is annotated then UNKNOWN access code is returned.
 */
private int determineImplicitAccessType(Class<?> cls, OpenJPAConfiguration conf) {
    if (cls.isInterface()) // Managed interfaces
        return AccessCode.PROPERTY;
    Field[] allFields = AccessController.doPrivileged(J2DoPrivHelper.getDeclaredFieldsAction(cls));
    Method[] methods = AccessController.doPrivileged(J2DoPrivHelper.getDeclaredMethodsAction(cls));
    List<Field> fields = filter(allFields, new TransientFilter(true));
    /*
     * OpenJPA 1.x permitted private properties to be persistent.  This is
     * contrary to the JPA 1.0 specification, which states that persistent
     * properties must be public or protected. OpenJPA 2.0+ will adhere
     * to the specification by default, but provides a compatibility
     * option to provide pre-2.0 behavior.
     */
    getterFilter.setIncludePrivate(conf.getCompatibilityInstance().getPrivatePersistentProperties());
    List<Method> getters = filter(methods, getterFilter);
    if (fields.isEmpty() && getters.isEmpty())
        return AccessCode.EMPTY;

    fields = filter(fields, annotatedFilter);
    getters = filter(getters, annotatedFilter);

    List<Method> setters = filter(methods, setterFilter);
    getters = matchGetterAndSetter(getters, setters);

    boolean mixed = !fields.isEmpty() && !getters.isEmpty();
    if (mixed)
        throw new UserException(_loc.get("access-mixed", cls, toFieldNames(fields), toMethodNames(getters)));
    if (!fields.isEmpty()) {
        return AccessCode.FIELD;
    }
    if (!getters.isEmpty()) {
        return AccessCode.PROPERTY;
    }
    return AccessCode.UNKNOWN;
}

From source file:org.apache.openjpa.lib.util.Options.java

/**
 * Matches a key to an object/setter pair.
 *
 * @param key the key given at the command line; may be of the form
 * 'foo.bar' to signify the 'bar' property of the 'foo' owned object
 * @param match an array of length 2, where the first index is set
 * to the object to retrieve the setter for
 * @return true if a match was made, false otherwise; additionally,
 * the first index of the match array will be set to
 * the matching object and the second index will be
 * set to the setter method or public field for the
 * property named by the key/*  ww w  . j  av a2s  . c  o m*/
 */
private static boolean matchOptionToMember(String key, Object[] match) throws Exception {
    if (StringUtils.isEmpty(key))
        return false;

    // unfortunately we can't use bean properties for setters; any
    // setter with more than 1 argument is ignored; calculate setter and getter
    // name to look for
    String[] find = Strings.split(key, ".", 2);
    String base = StringUtils.capitalize(find[0]);
    String set = "set" + base;
    String get = "get" + base;

    // look for a setter/getter matching the key; look for methods first
    Class<? extends Object> type = match[0].getClass();
    Method[] meths = type.getMethods();
    Method setMeth = null;
    Method getMeth = null;
    Class[] params;
    for (int i = 0; i < meths.length; i++) {
        if (meths[i].getName().equals(set)) {
            params = meths[i].getParameterTypes();
            if (params.length == 0)
                continue;
            if (params[0].isArray())
                continue;

            // use this method if we haven't found any other setter, if
            // it has less parameters than any other setter, or if it uses
            // string parameters
            if (setMeth == null)
                setMeth = meths[i];
            else if (params.length < setMeth.getParameterTypes().length)
                setMeth = meths[i];
            else if (params.length == setMeth.getParameterTypes().length && params[0] == String.class)
                setMeth = meths[i];
        } else if (meths[i].getName().equals(get))
            getMeth = meths[i];
    }

    // if no methods found, check for public field
    Member setter = setMeth;
    Member getter = getMeth;
    if (setter == null) {
        Field[] fields = type.getFields();
        String uncapBase = StringUtils.uncapitalize(find[0]);
        for (int i = 0; i < fields.length; i++) {
            if (fields[i].getName().equals(base) || fields[i].getName().equals(uncapBase)) {
                setter = fields[i];
                getter = fields[i];
                break;
            }
        }
    }

    // if no way to access property, give up
    if (setter == null && getter == null)
        return false;

    // recurse on inner object with remainder of key?
    if (find.length > 1) {
        Object inner = null;
        if (getter != null)
            inner = invoke(match[0], getter, null);

        // if no getter or current inner is null, try to create a new
        // inner instance and set it in object
        if (inner == null && setter != null) {
            Class<?> innerType = getType(setter)[0];
            try {
                inner = AccessController.doPrivileged(J2DoPrivHelper.newInstanceAction(innerType));
            } catch (PrivilegedActionException pae) {
                throw pae.getException();
            }
            invoke(match[0], setter, new Object[] { inner });
        }
        match[0] = inner;
        return matchOptionToMember(find[1], match);
    }

    // got match; find setter for property
    match[1] = setter;
    return match[1] != null;
}

From source file:org.apache.openjpa.persistence.validation.ValidatorImpl.java

private ValidatorFactory getDefaultValidatorFactory() {
    ValidatorFactory factory = null;//from ww w . j  a  v  a2  s  . com
    try {
        factory = AccessController.doPrivileged(J2DoPrivHelper.buildDefaultValidatorFactoryAction());
    } catch (javax.validation.ValidationException e) {
        if (_log != null && _log.isTraceEnabled())
            _log.trace(_loc.get("factory-create-failed"), e);
    }
    return factory;
}

From source file:com.reelfx.model.PostProcessor.java

public static void deleteOutput() {
    AccessController.doPrivileged(new PrivilegedAction<Object>() {

        @Override//from  w  w  w  . j  a  va 2 s. co  m
        public Object run() {
            try {
                if (DEFAULT_OUTPUT_FILE.exists() && !DEFAULT_OUTPUT_FILE.delete())
                    throw new Exception("Can't delete the old audio file!");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    });
}