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.enhance.PCEnhancer.java

/**
 * Helper method to get the code for the class initializer method,
 * creating the method if it does not already exist.
 *//* w  w w.j a v a 2s . co  m*/
private Code getOrCreateClassInitCode(boolean replaceLast) {
    BCMethod clinit = _pc.getDeclaredMethod("<clinit>");
    Code code;
    if (clinit != null) {
        code = clinit.getCode(true);
        if (replaceLast) {
            Code template = AccessController.doPrivileged(J2DoPrivHelper.newCodeAction());
            code.searchForward(template.vreturn());
            code.previous();
            code.set(template.nop());
            code.next();
        }
        return code;
    }

    // add static initializer method if non exists
    clinit = _pc.declareMethod("<clinit>", void.class, null);
    clinit.makePackage();
    clinit.setStatic(true);
    clinit.setFinal(true);

    code = clinit.getCode(true);
    if (!replaceLast) {
        code.vreturn();
        code.previous();
    }
    return code;
}

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

/**
 * Adds bytecode modifying the cloning behavior of the class being
 * enhanced to correctly replace the <code>pcStateManager</code> 
 * instance fields of any clone created with their default values. 
 * Also, if this class is the base PC type and does not declared 
 * a clone method, one will be added. Also, if _pc is a synthetic
 * subclass, create the clone() method that clears the state manager
 * that may have been initialized in a super's clone() method.
 *//*from  w w w. j  a  va2s .  c o  m*/
private void addCloningCode() {
    if (_meta.getPCSuperclass() != null && !getCreateSubclass())
        return;

    // add the clone method if necessary
    BCMethod clone = _pc.getDeclaredMethod("clone", (String[]) null);
    String superName = _managedType.getSuperclassName();
    Code code = null;
    if (clone == null) {
        // add clone support for base classes
        // which also implement cloneable
        boolean isCloneable = Cloneable.class.isAssignableFrom(_managedType.getType());
        boolean extendsObject = superName.equals(Object.class.getName());
        if (!isCloneable || (!extendsObject && !getCreateSubclass()))
            return;

        if (!getCreateSubclass())
            if (_log.isTraceEnabled())
                _log.trace(_loc.get("enhance-cloneable", _managedType.getName()));

        // add clone method
        // protected Object clone () throws CloneNotSupportedException
        clone = _pc.declareMethod("clone", Object.class, null);
        if (!setVisibilityToSuperMethod(clone))
            clone.makeProtected();
        clone.getExceptions(true).addException(CloneNotSupportedException.class);
        code = clone.getCode(true);

        // return super.clone ();
        loadManagedInstance(code, false);
        code.invokespecial().setMethod(superName, "clone", Object.class.getName(), null);
        code.areturn();
    } else {
        // get the clone method code
        code = clone.getCode(false);
        if (code == null)
            return;
    }

    // create template super.clone () instruction to match against
    Instruction template = (AccessController.doPrivileged(J2DoPrivHelper.newCodeAction())).invokespecial()
            .setMethod(superName, "clone", Object.class.getName(), null);

    // find calls to the template instruction; on match
    // clone will be on stack
    code.beforeFirst();
    if (code.searchForward(template)) {
        // ((<type>) clone).pcStateManager = null;
        code.dup();
        code.checkcast().setType(_pc);
        code.constant().setNull();
        code.putfield().setField(SM, SMTYPE);

        // if modified, increase stack
        code.calculateMaxStack();
        code.calculateMaxLocals();
    }
}

From source file:org.apache.openjpa.kernel.BrokerImpl.java

public Object newInstance(Class cls) {
    assertOpen();//www.ja va 2 s .  c o  m

    if (!cls.isInterface() && Modifier.isAbstract(cls.getModifiers()))
        throw new UnsupportedOperationException(_loc.get("new-abstract", cls).getMessage());

    // 1.5 doesn't initialize classes without a true Class.forName
    if (!PCRegistry.isRegistered(cls)) {
        try {
            Class.forName(cls.getName(), true,
                    AccessController.doPrivileged(J2DoPrivHelper.getClassLoaderAction(cls)));
        } catch (Throwable t) {
        }
    }

    if (_repo.getMetaData(cls, getClassLoader(), false) == null)
        throw new IllegalArgumentException(_loc.get("no-interface-metadata", cls.getName()).getMessage());

    try {
        return PCRegistry.newInstance(cls, null, false);
    } catch (IllegalStateException ise) {
        IllegalArgumentException iae = new IllegalArgumentException(ise.getMessage());
        iae.setStackTrace(ise.getStackTrace());
        throw iae;
    }
}

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

/**
 * Adds to <code>code</code> the instructions to get field
 * <code>attrName</code> declared in type <code>declarer</code>
 * onto the top of the stack./*  ww w .j ava  2s . c  o m*/
 *
 * The instance to access must already be on the top of the
 * stack when this is invoked.
 */
private void getfield(Code code, BCClass declarer, String attrName) {
    if (declarer == null)
        declarer = _managedType;

    // first, see if we can convert the attribute name to a field name
    String fieldName = toBackingFieldName(attrName);

    // next, find the field in the managed type hierarchy
    BCField field = null;
    outer: for (BCClass bc = _pc; bc != null; bc = bc.getSuperclassBC()) {
        BCField[] fields = AccessController.doPrivileged(J2DoPrivHelper.getBCClassFieldsAction(bc, fieldName));
        for (int i = 0; i < fields.length; i++) {
            field = fields[i];
            // if we reach a field declared in this type, then this is the
            // most-masking field, and is the one that we want.
            if (fields[i].getDeclarer() == declarer) {
                break outer;
            }
        }
    }

    if (getCreateSubclass() && code.getMethod().getDeclarer() == _pc && (field == null || !field.isPublic())) {
        // we're creating the subclass, not redefining the user type.

        // Reflection.getXXX(this, Reflection.findField(...));
        code.classconstant().setClass(declarer);
        code.constant().setValue(fieldName);
        code.constant().setValue(true);
        code.invokestatic().setMethod(Reflection.class, "findField", Field.class,
                new Class[] { Class.class, String.class, boolean.class });
        Class type = _meta.getField(attrName).getDeclaredType();
        try {
            code.invokestatic().setMethod(getReflectionGetterMethod(type, Field.class));
        } catch (NoSuchMethodException e) {
            // should never happen
            throw new InternalException(e);
        }
        if (!type.isPrimitive() && type != Object.class)
            code.checkcast().setType(type);
    } else {
        code.getfield().setField(declarer.getName(), fieldName, field.getType().getName());
    }
}

From source file:org.apache.openjpa.kernel.BrokerImpl.java

/**
 * Return the given instance as a {@link PersistenceCapable}.
 * If the instance is not manageable throw the proper exception.
 *///  w ww  .  j  a v  a 2s  .  c o m
protected PersistenceCapable assertPersistenceCapable(Object obj) {
    if (obj == null)
        return null;
    if (ImplHelper.isManageable(obj))
        return ImplHelper.toPersistenceCapable(obj, _conf);

    // check for different instances of the PersistenceCapable interface
    // and throw a better error that mentions the class loaders
    Class<?>[] intfs = obj.getClass().getInterfaces();
    for (int i = 0; intfs != null && i < intfs.length; i++) {
        if (intfs[i].getName().equals(PersistenceCapable.class.getName())) {
            throw new UserException(_loc.get("pc-loader-different", Exceptions.toString(obj),
                    AccessController
                            .doPrivileged(J2DoPrivHelper.getClassLoaderAction(PersistenceCapable.class)),
                    AccessController.doPrivileged(J2DoPrivHelper.getClassLoaderAction(intfs[i]))))
                            .setFailedObject(obj);
        }
    }

    // not enhanced
    throw new UserException(_loc.get("pc-cast", Exceptions.toString(obj))).setFailedObject(obj);
}

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

/**
 * Enhance the given classes.//w ww .ja va2  s .  c o  m
 */
public static boolean run(OpenJPAConfiguration conf, String[] args, Flags flags, MetaDataRepository repos,
        BytecodeWriter writer, ClassLoader loader) throws IOException {
    if (loader == null)
        loader = conf.getClassResolverInstance().getClassLoader(PCEnhancer.class, null);
    if (flags.tmpClassLoader)
        loader = AccessController.doPrivileged(J2DoPrivHelper.newTemporaryClassLoaderAction(loader));

    if (repos == null) {
        repos = conf.newMetaDataRepositoryInstance();
        repos.setSourceMode(MetaDataRepository.MODE_META);
    }

    Log log = conf.getLog(OpenJPAConfiguration.LOG_TOOL);
    Collection classes;
    if (args == null || args.length == 0) {
        classes = repos.getPersistentTypeNames(true, loader);
        if (classes == null) {
            log.warn(_loc.get("no-class-to-enhance"));
            return false;
        }
    } else {
        ClassArgParser cap = conf.getMetaDataRepositoryInstance().getMetaDataFactory().newClassArgParser();
        cap.setClassLoader(loader);
        classes = new HashSet();
        for (int i = 0; i < args.length; i++)
            classes.addAll(Arrays.asList(cap.parseTypes(args[i])));
    }

    Project project = new Project();
    BCClass bc;
    PCEnhancer enhancer;
    Collection persAwareClasses = new HashSet();

    int status;
    for (Iterator itr = classes.iterator(); itr.hasNext();) {
        Object o = itr.next();
        if (log.isInfoEnabled())
            log.info(_loc.get("enhance-running", o));

        if (o instanceof String)
            bc = project.loadClass((String) o, loader);
        else
            bc = project.loadClass((Class) o);
        enhancer = new PCEnhancer(conf, bc, repos, loader);
        if (writer != null)
            enhancer.setBytecodeWriter(writer);
        enhancer.setDirectory(flags.directory);
        enhancer.setAddDefaultConstructor(flags.addDefaultConstructor);
        status = enhancer.run();
        if (status == ENHANCE_NONE) {
            if (log.isTraceEnabled())
                log.trace(_loc.get("enhance-norun"));
        } else if (status == ENHANCE_INTERFACE) {
            if (log.isTraceEnabled())
                log.trace(_loc.get("enhance-interface"));
        } else if (status == ENHANCE_AWARE) {
            persAwareClasses.add(o);
            enhancer.record();
        } else {
            enhancer.record();
        }
        project.clear();
    }
    if (log.isInfoEnabled() && !persAwareClasses.isEmpty()) {
        log.info(_loc.get("pers-aware-classes", persAwareClasses.size(), persAwareClasses));
    }
    return true;
}