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:org.apache.openjpa.jdbc.sql.PostgresDictionary.java

/**
 * Get the delegated connection from the given DBCP connection.
 * /*w w w.ja va 2s . com*/
 * @param conn must be a DBCP connection
 * @return connection the DBCP connection delegates to
 */
protected Connection getDbcpDelegate(Connection conn) {
    Connection delegate = null;
    try {
        if (dbcpGetDelegate == null) {
            Class<?> dbcpConnectionClass = Class.forName("org.apache.commons.dbcp.DelegatingConnection", true,
                    AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction()));
            Class<?> poolingDataSource = Class.forName("org.apache.commons.dbcp.PoolingDataSource", true,
                    AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction()));
            Method setAccessToUnderlyingConnectionAllowed = poolingDataSource
                    .getMethod("setAccessToUnderlyingConnectionAllowed", boolean.class);

            Field this$0 = conn.getClass().getDeclaredField("this$0");
            this$0.setAccessible(true);
            Object poolingDataSourceObj = this$0.get(conn);
            setAccessToUnderlyingConnectionAllowed.invoke(poolingDataSourceObj, true);

            dbcpGetDelegate = dbcpConnectionClass.getMethod("getInnermostDelegate");
        }
        delegate = (Connection) dbcpGetDelegate.invoke(conn);
    } catch (Exception e) {
        throw new InternalException(_loc.get("dbcp-unwrap-failed"), e);
    }
    if (delegate == null) {
        throw new InternalException(_loc.get("dbcp-unwrap-failed"));
    }
    return delegate;
}

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

private static DeploymentClassLoader createDeploymentClassLoader(final URL[] urls,
        final ClassLoader serviceClassLoader, final List embeddedJars, final boolean isChildFirstClassLoading) {
    return (DeploymentClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return new DeploymentClassLoader(urls, embeddedJars, serviceClassLoader, isChildFirstClassLoading);
        }//from   w  w  w . j  av a  2 s.c  o m
    });
}

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

/**
 * Parse callback methods into the given array, and return that array,
 * creating one if null. Each index into the array is a collection of
 * callback adapters for that numeric event type.
 *
 * @param sups whether to scan superclasses
 * @param listener whether this is a listener or not
 *//*from   ww w. j ava2s .c  o m*/
public static Collection<LifecycleCallbacks>[] parseCallbackMethods(Class<?> cls,
        Collection<LifecycleCallbacks>[] callbacks, boolean sups, boolean listener, MetaDataRepository repos) {

    if (cls == null)
        throw new IllegalArgumentException("cls cannot be null");

    // first sort / filter based on inheritance
    Set<Method> methods = new TreeSet<Method>(MethodComparator.getInstance());

    int mods;
    Class<?> sup = cls;
    MethodKey key;
    Set<MethodKey> seen = new HashSet<MethodKey>();
    do {
        for (Method m : (Method[]) AccessController
                .doPrivileged(J2DoPrivHelper.getDeclaredMethodsAction(sup))) {
            mods = m.getModifiers();
            if (Modifier.isStatic(mods) || Modifier.isFinal(mods) || Object.class.equals(m.getDeclaringClass()))
                continue;

            key = new MethodKey(m);
            if (!seen.contains(key)) {
                methods.add(m);
                seen.add(key);
            }
        }
        sup = sup.getSuperclass();
    } while (sups && !Object.class.equals(sup));

    OpenJPAConfiguration conf = repos.getConfiguration();
    for (Method m : methods) {
        for (Annotation anno : (Annotation[]) AccessController
                .doPrivileged(J2DoPrivHelper.getDeclaredAnnotationsAction(m))) {
            MetaDataTag tag = _tags.get(anno.annotationType());
            if (tag == null)
                continue;
            int[] events = MetaDataParsers.getEventTypes(tag, conf);
            if (events == null)
                continue;

            if (callbacks == null)
                callbacks = (Collection<LifecycleCallbacks>[]) new Collection[LifecycleEvent.ALL_EVENTS.length];

            for (int i = 0; i < events.length; i++) {
                int e = events[i];
                if (callbacks[e] == null)
                    callbacks[e] = new ArrayList<LifecycleCallbacks>(3);
                MetaDataParsers.validateMethodsForSameCallback(cls, callbacks[e], m, tag, conf, repos.getLog());
                if (listener) {
                    callbacks[e].add(new BeanLifecycleCallbacks(cls, m, false));
                } else {
                    callbacks[e].add(new MethodLifecycleCallbacks(m, false));
                }
            }
        }
    }
    return callbacks;
}

From source file:org.codice.solr.factory.impl.SolrClientAdapter.java

private static ScheduledExecutorService createExecutor() throws NumberFormatException {
    return Executors.newScheduledThreadPool(
            NumberUtils.toInt(//from  w  w  w. ja  v  a2 s .  co  m
                    AccessController.doPrivileged((PrivilegedAction<String>) () -> System
                            .getProperty("org.codice.ddf.system.threadPoolSize")),
                    SolrClientAdapter.THREAD_POOL_DEFAULT_SIZE),
            StandardThreadFactoryBuilder.newThreadFactory("SolrClientAdapter"));
}

From source file:org.apache.ws.scout.registry.RegistryImpl.java

/**
 * //w w  w  . java2s .co  m
 * @param name
 * @return The class object for the name given
 * @throws ClassNotFoundException
 * @throws NoClassDefFoundError
 */
public static Class getClassForName(String name) throws ClassNotFoundException, NoClassDefFoundError {
    Class clazz = null;

    try {
        // log.info("Using the Context ClassLoader");
        ClassLoader ccl = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
            public ClassLoader run() {
                return Thread.currentThread().getContextClassLoader();
            }
        });

        clazz = Class.forName(name, true, ccl);
    } catch (Exception e) {
        log.debug("Failed to load the class " + name + " with context class loader " + e);
    }

    if (null == clazz) {
        ClassLoader scl = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
            public ClassLoader run() {
                return ClassLoader.getSystemClassLoader();
            }
        });

        try {
            clazz = Class.forName(name, true, scl);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    return clazz;
}

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

/**
 * Replaced all direct access to managed fields with the appropriate
 * pcGet/pcSet method. Note that this includes access to fields
 * owned by PersistenceCapable classes other than this one.
 *//*from w  ww .java  2  s. c om*/
private void replaceAndValidateFieldAccess() throws NoSuchMethodException {
    // create template putfield/getfield instructions to search for
    Code template = AccessController.doPrivileged(J2DoPrivHelper.newCodeAction());
    Instruction put = template.putfield();
    Instruction get = template.getfield();
    Instruction stat = template.invokestatic();

    // look through all methods; this is done before any methods are added
    // so we don't need to worry about excluding synthetic methods.
    BCMethod[] methods = _managedType.getDeclaredMethods();
    Code code;
    for (int i = 0; i < methods.length; i++) {
        code = methods[i].getCode(false);

        // don't modify the methods specified by the auxiliary enhancers
        if (code != null && !skipEnhance(methods[i])) {
            replaceAndValidateFieldAccess(code, get, true, stat);
            replaceAndValidateFieldAccess(code, put, false, stat);
        }
    }
}

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

public void serialize(File file, int flags) throws IOException {
    try {/*from ww  w  .j a v a2 s.c o m*/
        FileWriter out = new FileWriter(
                AccessController.doPrivileged(J2DoPrivHelper.getCanonicalPathAction(file)),
                (flags & APPEND) > 0);
        serialize(out, flags);
        out.close();
    } catch (PrivilegedActionException pae) {
        throw (IOException) pae.getException();
    }
}

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

/**
 * Replaces all instructions matching the given template in the given
 * code block with calls to the appropriate generated getter/setter.
 *
 * @param code the code block to modify; the code iterator will
 * be placed before the first instruction on method start,
 * and will be after the last instruction on method completion
 * @param ins the template instruction to search for; either a
 * getfield or putfield instruction/*  w  ww.  ja v  a2 s  .c  o  m*/
 * @param get boolean indicating if this is a get instruction
 * @param stat template invokestatic instruction to replace with
 */
private void replaceAndValidateFieldAccess(Code code, Instruction ins, boolean get, Instruction stat)
        throws NoSuchMethodException {
    code.beforeFirst();

    FieldInstruction fi;
    MethodInstruction mi;
    ClassMetaData owner;
    String name, typeName, methodName;
    while (code.searchForward(ins)) {
        // back up to the matched instruction
        fi = (FieldInstruction) code.previous();
        name = fi.getFieldName();
        typeName = fi.getFieldTypeName();
        owner = getPersistenceCapableOwner(name, fi.getFieldDeclarerType());
        FieldMetaData fmd = owner == null ? null : owner.getField(name);
        if (isPropertyAccess(fmd)) {
            // if we're directly accessing a field in another class
            // hierarchy that uses property access, something is wrong
            if (owner != _meta && owner.getDeclaredField(name) != null && _meta != null
                    && !owner.getDescribedType().isAssignableFrom(_meta.getDescribedType()))
                throw new UserException(_loc.get("property-field-access",
                        new Object[] { _meta, owner, name, code.getMethod().getName() }));

            // if we're directly accessing a property-backing field outside
            // the property in our own class, notify user
            if (isBackingFieldOfAnotherProperty(name, code))
                addViolation("property-field-access",
                        new Object[] { _meta, owner, name, code.getMethod().getName() }, false);
        }

        if (owner == null || owner.getDeclaredField(fromBackingFieldName(name)) == null) {
            // not persistent field?
            code.next();
            continue;
        } else if (!getRedefine() && !getCreateSubclass() && isFieldAccess(fmd)) {
            // replace the instruction with a call to the generated access
            // method
            mi = (MethodInstruction) code.set(stat);

            // invoke the proper access method, whether getter or setter
            String prefix = (get) ? PRE + "Get" : PRE + "Set";
            methodName = prefix + name;
            if (get) {
                mi.setMethod(getType(owner).getName(), methodName, typeName,
                        new String[] { getType(owner).getName() });
            } else {
                mi.setMethod(getType(owner).getName(), methodName, "void",
                        new String[] { getType(owner).getName(), typeName });
            }
            code.next();
        } else if (getRedefine()) {
            name = fromBackingFieldName(name);
            if (get) {
                addNotifyAccess(code, owner.getField(name));
                code.next();
            } else {
                // insert the set operations after the field mutation, but
                // first load the old value for use in the
                // StateManager.settingXXX method.
                loadManagedInstance(code, false);
                final FieldInstruction fFi = fi;
                code.getfield().setField(
                        AccessController.doPrivileged(J2DoPrivHelper.getFieldInstructionFieldAction(fFi)));
                int val = code.getNextLocalsIndex();
                code.xstore().setLocal(val).setType(fi.getFieldType());

                // move past the putfield
                code.next();
                addNotifyMutation(code, owner.getField(name), val, -1);
            }
        } else {
            code.next();
        }
        code.calculateMaxLocals();
        code.calculateMaxStack();
    }
}

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

/**
 * Read annotations for the given member.
 *//*from w w  w  .  jav a2 s.co m*/
private void parseMemberAnnotations(FieldMetaData fmd) {
    // look for persistence strategy in annotation table
    Member member = getRepository().getMetaDataFactory().getDefaults().getBackingMember(fmd);
    PersistenceStrategy pstrat = PersistenceMetaDataDefaults.getPersistenceStrategy(fmd, member);
    if (pstrat == null)
        return;
    fmd.setExplicit(true);

    AnnotatedElement el = (AnnotatedElement) member;
    boolean lob = (AccessController.doPrivileged(J2DoPrivHelper.isAnnotationPresentAction(el, Lob.class)))
            .booleanValue();
    if (isMetaDataMode()) {
        switch (pstrat) {
        case BASIC:
            parseBasic(fmd, (Basic) el.getAnnotation(Basic.class), lob);
            break;
        case MANY_ONE:
            parseManyToOne(fmd, (ManyToOne) el.getAnnotation(ManyToOne.class));
            break;
        case ONE_ONE:
            parseOneToOne(fmd, (OneToOne) el.getAnnotation(OneToOne.class));
            break;
        case EMBEDDED:
            parseEmbedded(fmd, (Embedded) el.getAnnotation(Embedded.class));
            break;
        case ONE_MANY:
            parseOneToMany(fmd, (OneToMany) el.getAnnotation(OneToMany.class));
            break;
        case MANY_MANY:
            parseManyToMany(fmd, (ManyToMany) el.getAnnotation(ManyToMany.class));
            break;
        case PERS:
            parsePersistent(fmd, (Persistent) el.getAnnotation(Persistent.class));
            break;
        case PERS_COLL:
            parsePersistentCollection(fmd, (PersistentCollection) el.getAnnotation(PersistentCollection.class));
            break;
        case ELEM_COLL:
            parseElementCollection(fmd, (ElementCollection) el.getAnnotation(ElementCollection.class));
            break;
        case PERS_MAP:
            parsePersistentMap(fmd, (PersistentMap) el.getAnnotation(PersistentMap.class));
            break;
        case TRANSIENT:
            break;
        default:
            throw new InternalException();
        }
    }

    if (isMappingOverrideMode() && lob)
        parseLobMapping(fmd);

    // extensions
    MetaDataTag tag;
    for (Annotation anno : el.getDeclaredAnnotations()) {
        tag = _tags.get(anno.annotationType());
        if (tag == null) {
            handleUnknownMemberAnnotation(fmd, anno);
            continue;
        }

        switch (tag) {
        case ACCESS:
            parseAccess(fmd, (Access) anno);
            break;
        case FLUSH_MODE:
            if (isMetaDataMode())
                warnFlushMode(fmd);
            break;
        case GENERATED_VALUE:
            if (isMappingOverrideMode())
                parseGeneratedValue(fmd, (GeneratedValue) anno);
            break;
        case ID:
        case EMBEDDED_ID:
            fmd.setPrimaryKey(true);
            break;
        case MAPPED_BY_ID:
            parseMapsId(fmd, (MapsId) anno);
            break;
        case MAP_KEY:
            if (isMappingOverrideMode())
                parseMapKey(fmd, (MapKey) anno);
            break;
        case MAP_KEY_CLASS:
            if (isMappingOverrideMode())
                parseMapKeyClass(fmd, (MapKeyClass) anno);
            break;
        case ORDER_BY:
            parseOrderBy(fmd, (OrderBy) el.getAnnotation(OrderBy.class));
            break;
        case SEQ_GENERATOR:
            if (isMappingOverrideMode())
                parseSequenceGenerator(el, (SequenceGenerator) anno);
            break;
        case VERSION:
            fmd.setVersion(true);
            break;
        case DEPENDENT:
            if (isMetaDataMode() && ((Dependent) anno).value())
                fmd.setCascadeDelete(ValueMetaData.CASCADE_AUTO);
            break;
        case ELEM_DEPENDENT:
            if (isMetaDataMode() && ((ElementDependent) anno).value())
                fmd.getElement().setCascadeDelete(ValueMetaData.CASCADE_AUTO);
            break;
        case ELEM_TYPE:
            if (isMetaDataMode())
                fmd.getElement().setTypeOverride(toOverrideType(((ElementType) anno).value()));
            break;
        case EXTERNAL_VALS:
            if (isMetaDataMode())
                fmd.setExternalValues(Strings.join(((ExternalValues) anno).value(), ","));
            break;
        case EXTERNALIZER:
            if (isMetaDataMode())
                fmd.setExternalizer(((Externalizer) anno).value());
            break;
        case FACTORY:
            if (isMetaDataMode())
                fmd.setFactory(((Factory) anno).value());
            break;
        case INVERSE_LOGICAL:
            if (isMetaDataMode())
                fmd.setInverse(((InverseLogical) anno).value());
            break;
        case KEY_DEPENDENT:
            if (isMetaDataMode() && ((KeyDependent) anno).value())
                fmd.getKey().setCascadeDelete(ValueMetaData.CASCADE_AUTO);
            break;
        case KEY_TYPE:
            if (isMetaDataMode())
                fmd.getKey().setTypeOverride(toOverrideType(((KeyType) anno).value()));
            break;
        case LOAD_FETCH_GROUP:
            if (isMetaDataMode())
                fmd.setLoadFetchGroup(((LoadFetchGroup) anno).value());
            break;
        case LRS:
            if (isMetaDataMode())
                fmd.setLRS(((LRS) anno).value());
            break;
        case READ_ONLY:
            if (isMetaDataMode())
                parseReadOnly(fmd, (ReadOnly) anno);
            break;
        case TYPE:
            if (isMetaDataMode())
                fmd.setTypeOverride(toOverrideType(((Type) anno).value()));
            break;
        default:
            throw new UnsupportedException(_loc.get("unsupported", fmd, anno.toString()));
        }
    }
}

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

/**
 * Return the result of passing the given external value through the
 * factory to get the field value. If no factory is present,
 * the given value is returned as-is.//w  ww .  j ava 2  s. co m
 */
public Object getFieldValue(Object val, StoreContext ctx) {
    Map fieldValues = getFieldValueMap();
    if (fieldValues != null)
        return fieldValues.get(val);

    Member factory = getFactoryMethod();
    if (factory == null)
        return val;

    try {
        if (val == null && getNullValue() == NULL_DEFAULT)
            return AccessController.doPrivileged(J2DoPrivHelper.newInstanceAction(getDeclaredType()));

        // invoke either the constructor for the field type,
        // or the static type.toField(val[, ctx]) method
        if (factory instanceof Constructor) {
            if (val == null)
                return null;
            return ((Constructor) factory).newInstance(new Object[] { val });
        }

        Method meth = (Method) factory;
        if (meth.getParameterTypes().length == 1)
            return meth.invoke(null, new Object[] { val });
        return meth.invoke(null, new Object[] { val, ctx });
    } catch (Exception e) {
        // unwrap cause
        if (e instanceof InvocationTargetException) {
            Throwable t = ((InvocationTargetException) e).getTargetException();
            if (t instanceof Error)
                throw (Error) t;
            e = (Exception) t;

            // allow null values to cause NPEs and illegal arg exceptions
            // without error
            if (val == null && (e instanceof NullPointerException || e instanceof IllegalArgumentException))
                return null;
        }

        if (e instanceof OpenJPAException)
            throw (OpenJPAException) e;
        if (e instanceof PrivilegedActionException)
            e = ((PrivilegedActionException) e).getException();
        throw new MetaDataException(_loc.get("factory-err", this, Exceptions.toString(val), e.toString()))
                .setCause(e);
    }
}