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:com.frameworkset.commons.dbcp2.BasicDataSource.java

/**
 * Create (if necessary) and return a connection to the database.
 *
 * @throws SQLException if a database access error occurs
 * @return a database connection//from   w w  w .  j av  a2 s. com
 */
@Override
public Connection getConnection() throws SQLException {
    if (Utils.IS_SECURITY_ENABLED) {
        PrivilegedExceptionAction<Connection> action = new PaGetConnection();
        try {
            return AccessController.doPrivileged(action);
        } catch (PrivilegedActionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof SQLException) {
                throw (SQLException) cause;
            }
            throw new SQLException(e);
        }
    }
    return createDataSource().getConnection();
}

From source file:org.apache.openjpa.persistence.jdbc.AnnotationPersistenceMappingParser.java

/**
 * Parse @Column(s)./*from ww w .j  a v  a2s .c om*/
 */
protected void parseColumns(FieldMapping fm, javax.persistence.Column... pcols) {
    if (pcols.length == 0)
        return;

    // might already have some column information from mapping annotation
    List<Column> cols = fm.getValueInfo().getColumns();
    if (!cols.isEmpty() && cols.size() != pcols.length)
        throw new MetaDataException(
                _loc.get("num-cols-mismatch", fm, String.valueOf(cols.size()), String.valueOf(pcols.length)));

    // cache the JAXB XmlRootElement class if it is present so we do not
    // have a hard-wired dependency on JAXB here
    Class xmlRootElementClass = null;
    try {
        xmlRootElementClass = Class.forName("javax.xml.bind.annotation.XmlRootElement");
    } catch (Exception e) {
    }

    int unique = 0;
    DBIdentifier sSecondary = DBIdentifier.NULL;
    for (int i = 0; i < pcols.length; i++) {
        if (cols.size() > i)
            setupColumn((Column) cols.get(i), pcols[i], delimit());
        else {
            if (cols.isEmpty())
                cols = new ArrayList<Column>(pcols.length);
            cols.add(newColumn(pcols[i], delimit()));
        }
        if (xmlRootElementClass != null && StringUtils.isEmpty(pcols[i].columnDefinition())
                && (AccessController.doPrivileged(
                        J2DoPrivHelper.isAnnotationPresentAction(fm.getDeclaredType(), xmlRootElementClass)))
                                .booleanValue()) {
            DBDictionary dict = ((MappingRepository) getRepository()).getDBDictionary();
            if (dict.supportsXMLColumn)
                // column maps to xml type
                ((Column) cols.get(i)).setTypeIdentifier(DBIdentifier.newColumnDefinition(dict.xmlTypeName));
        }

        unique |= (pcols[i].unique()) ? TRUE : FALSE;
        DBIdentifier sSecTable = DBIdentifier.newTable(pcols[i].table(), delimit());
        sSecondary = trackSecondaryTable(fm, sSecondary, sSecTable, i);
    }

    if (fm.isElementCollection())
        setColumns(fm, fm.getElementMapping().getValueInfo(), cols, unique);
    else
        setColumns(fm, fm.getValueInfo(), cols, unique);
    if (!DBIdentifier.isNull(sSecondary))
        fm.getMappingInfo().setTableIdentifier(sSecondary);
}

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

/**
 * Updates our datastructures with the latest registered classes.
 *///  w ww  .ja v  a 2 s .com
Class<?>[] processRegisteredClasses(ClassLoader envLoader) {
    if (_registered.isEmpty())
        return EMPTY_CLASSES;

    // copy into new collection to avoid concurrent mod errors on reentrant
    // registrations
    Class<?>[] reg;
    synchronized (_registered) {
        reg = _registered.toArray(new Class[_registered.size()]);
        _registered.clear();
    }

    Collection<String> pcNames = getPersistentTypeNames(false, envLoader);
    Collection<Class<?>> failed = null;
    for (int i = 0; i < reg.length; i++) {
        // Don't process types that aren't listed by the user; it may belong to a different persistence unit.
        if (pcNames != null && !pcNames.isEmpty() && !pcNames.contains(reg[i].getName())) {
            continue;
        }

        // If the compatibility option "filterPCRegistryClasses" is enabled, then verify that the type is
        // accessible to the envLoader/Thread Context ClassLoader
        if (_filterRegisteredClasses) {
            Log log = (_conf == null) ? null : _conf.getLog(OpenJPAConfiguration.LOG_RUNTIME);
            ClassLoader loadCL = (envLoader != null) ? envLoader
                    : AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction());

            try {
                Class<?> classFromAppClassLoader = Class.forName(reg[i].getName(), true, loadCL);

                if (!reg[i].equals(classFromAppClassLoader)) {
                    // This is a class that belongs to a ClassLoader not associated with the Application,
                    // so it should be processed.
                    if (log != null && log.isTraceEnabled()) {
                        log.trace("Metadata Repository will ignore Class " + reg[i].getName()
                                + ", since it originated from a ClassLoader not associated with the application.");
                    }
                    continue;
                }
            } catch (ClassNotFoundException cnfe) {
                // Catch exception and log its occurrence, and permit MDR processing to continue to preserve
                // original behavior.
                if (log != null && log.isTraceEnabled()) {
                    log.trace("The Class " + reg[i].getName() + " was identified as a persistent class "
                            + "by configuration, but the Class could not be found.");
                }
            }
        }

        checkEnhancementLevel(reg[i]);
        try {
            processRegisteredClass(reg[i]);
        } catch (Throwable t) {
            if (!_conf.getRetryClassRegistration())
                throw new MetaDataException(_loc.get("error-registered", reg[i]), t);

            if (_log.isWarnEnabled())
                _log.warn(_loc.get("failed-registered", reg[i]), t);
            if (failed == null)
                failed = new ArrayList<Class<?>>();
            failed.add(reg[i]);
        }
    }
    if (failed != null) {
        if (_locking) {
            synchronized (_registered) {
                _registered.addAll(failed);
            }
        } else {
            _registered.addAll(failed);
        }
    }
    return reg;
}

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

/**
 * Adds the 'stock' methods to the bytecode; these include methods
 * like {@link PersistenceCapable#pcFetchObjectId}
 * and {@link PersistenceCapable#pcIsTransactional}.
 *//*from  w  w w.  ja  va  2 s . c  o m*/
private void addStockMethods() throws NoSuchMethodException {
    try {
        // pcGetGenericContext
        translateFromStateManagerMethod(
                AccessController.doPrivileged(
                        J2DoPrivHelper.getDeclaredMethodAction(SMTYPE, "get" + CONTEXTNAME, (Class[]) null)),
                false);

        // pcFetchObjectId
        translateFromStateManagerMethod(
                AccessController.doPrivileged(
                        J2DoPrivHelper.getDeclaredMethodAction(SMTYPE, "fetchObjectId", (Class[]) null)),
                false);

        // pcIsDeleted
        translateFromStateManagerMethod(AccessController.doPrivileged(
                J2DoPrivHelper.getDeclaredMethodAction(SMTYPE, "isDeleted", (Class[]) null)), false);

        // pcIsDirty
        translateFromStateManagerMethod(AccessController
                .doPrivileged(J2DoPrivHelper.getDeclaredMethodAction(SMTYPE, "isDirty", (Class[]) null)), true);

        // pcIsNew
        translateFromStateManagerMethod(AccessController
                .doPrivileged(J2DoPrivHelper.getDeclaredMethodAction(SMTYPE, "isNew", (Class[]) null)), false);

        // pcIsPersistent
        translateFromStateManagerMethod(AccessController.doPrivileged(
                J2DoPrivHelper.getDeclaredMethodAction(SMTYPE, "isPersistent", (Class[]) null)), false);

        // pcIsTransactional
        translateFromStateManagerMethod(
                AccessController.doPrivileged(
                        J2DoPrivHelper.getDeclaredMethodAction(SMTYPE, "isTransactional", (Class[]) null)),
                false);

        // pcSerializing
        translateFromStateManagerMethod(AccessController.doPrivileged(
                J2DoPrivHelper.getDeclaredMethodAction(SMTYPE, "serializing", (Class[]) null)), false);

        // pcDirty
        translateFromStateManagerMethod(
                AccessController.doPrivileged(
                        J2DoPrivHelper.getDeclaredMethodAction(SMTYPE, "dirty", new Class[] { String.class })),
                false);

        // pcGetStateManager
        BCMethod meth = _pc.declareMethod(PRE + "GetStateManager", StateManager.class, null);
        Code code = meth.getCode(true);
        loadManagedInstance(code, false);
        code.getfield().setField(SM, StateManager.class);
        code.areturn();
        code.calculateMaxStack();
        code.calculateMaxLocals();
    } catch (PrivilegedActionException pae) {
        throw (NoSuchMethodException) pae.getException();
    }
}

From source file:org.apache.openjpa.jdbc.meta.ReverseMappingTool.java

/**
 * Run the tool. Returns false if invalid options were given.
 *
 * @see #main/*  w w w.ja v  a2 s. c om*/
 */
public static boolean run(JDBCConfiguration conf, String[] args, Options opts)
        throws IOException, SQLException {
    // flags
    Flags flags = new Flags();
    flags.packageName = opts.removeProperty("package", "pkg", flags.packageName);
    flags.directory = Files.getFile(opts.removeProperty("directory", "d", null), null);
    flags.useSchemaName = opts.removeBooleanProperty("useSchemaName", "sn", flags.useSchemaName);
    flags.useForeignKeyName = opts.removeBooleanProperty("useForeignKeyName", "fkn", flags.useForeignKeyName);
    flags.nullableAsObject = opts.removeBooleanProperty("nullableAsObject", "no", flags.nullableAsObject);
    flags.blobAsObject = opts.removeBooleanProperty("blobAsObject", "bo", flags.blobAsObject);
    flags.useGenericCollections = opts.removeBooleanProperty("useGenericCollections", "gc",
            flags.useGenericCollections);
    flags.primaryKeyOnJoin = opts.removeBooleanProperty("primaryKeyOnJoin", "pkj", flags.primaryKeyOnJoin);
    flags.useDataStoreIdentity = opts.removeBooleanProperty("useDatastoreIdentity", "ds",
            flags.useDataStoreIdentity);
    flags.useBuiltinIdentityClass = opts.removeBooleanProperty("useBuiltinIdentityClass", "bic",
            flags.useBuiltinIdentityClass);
    flags.innerIdentityClasses = opts.removeBooleanProperty("innerIdentityClasses", "inn",
            flags.innerIdentityClasses);
    flags.identityClassSuffix = opts.removeProperty("identityClassSuffix", "is", flags.identityClassSuffix);
    flags.inverseRelations = opts.removeBooleanProperty("inverseRelations", "ir", flags.inverseRelations);
    flags.detachable = opts.removeBooleanProperty("detachable", "det", flags.detachable);
    flags.discriminatorStrategy = opts.removeProperty("discriminatorStrategy", "ds",
            flags.discriminatorStrategy);
    flags.versionStrategy = opts.removeProperty("versionStrategy", "vs", flags.versionStrategy);
    flags.metaDataLevel = opts.removeProperty("metadata", "md", flags.metaDataLevel);
    flags.generateAnnotations = opts.removeBooleanProperty("annotations", "ann", flags.generateAnnotations);
    flags.accessType = opts.removeProperty("accessType", "access", flags.accessType);

    String typeMap = opts.removeProperty("typeMap", "typ", null);
    if (typeMap != null)
        flags.typeMap = Configurations.parseProperties(typeMap);

    // remap the -s shortcut to the "schemas" property name so that it
    // gets set into the configuration
    if (opts.containsKey("s"))
        opts.put("schemas", opts.get("s"));

    // customizer
    String customCls = opts.removeProperty("customizerClass", "cc",
            PropertiesReverseCustomizer.class.getName());
    File customFile = Files.getFile(opts.removeProperty("customizerProperties", "cp", null), null);
    Properties customProps = new Properties();
    if (customFile != null
            && (AccessController.doPrivileged(J2DoPrivHelper.existsAction(customFile))).booleanValue()) {
        FileInputStream fis = null;
        try {
            fis = AccessController.doPrivileged(J2DoPrivHelper.newFileInputStreamAction(customFile));
        } catch (PrivilegedActionException pae) {
            throw (FileNotFoundException) pae.getException();
        }
        customProps.load(fis);
    }

    // separate the properties for the customizer and code format
    Options customOpts = new Options();
    Options formatOpts = new Options();
    Map.Entry entry;
    String key;
    for (Iterator itr = opts.entrySet().iterator(); itr.hasNext();) {
        entry = (Map.Entry) itr.next();
        key = (String) entry.getKey();
        if (key.startsWith("customizer.")) {
            customOpts.put(key.substring(11), entry.getValue());
            itr.remove();
        } else if (key.startsWith("c.")) {
            customOpts.put(key.substring(2), entry.getValue());
            itr.remove();
        } else if (key.startsWith("codeFormat.")) {
            formatOpts.put(key.substring(11), entry.getValue());
            itr.remove();
        } else if (key.startsWith("cf.")) {
            formatOpts.put(key.substring(3), entry.getValue());
            itr.remove();
        }
    }

    // code format
    if (!formatOpts.isEmpty()) {
        flags.format = new CodeFormat();
        formatOpts.setInto(flags.format);
    }

    // setup a configuration instance with cmd-line info
    Configurations.populateConfiguration(conf, opts);
    ClassLoader loader = conf.getClassResolverInstance().getClassLoader(ReverseMappingTool.class, null);

    // customizer
    flags.customizer = (ReverseCustomizer) Configurations.newInstance(customCls, loader);
    if (flags.customizer != null) {
        Configurations.configureInstance(flags.customizer, conf, customOpts);
        flags.customizer.setConfiguration(customProps);
    }

    run(conf, args, flags, loader);
    return true;
}

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

/**
 * Gets the meta class corresponding to the given class. If load is false, returns the meta
 * class if has been set for the given persistent class earlier. If the load is true then also
 * attempts to apply the current naming policy to derive meta class name and attempts to load
 * the meta class./*w  w  w.  j a v  a2s  .  com*/
 */
public Class<?> getMetaModel(Class<?> entity, boolean load) {
    if (_metamodel.containsKey(entity))
        return _metamodel.get(entity);
    String m2 = _factory.getMetaModelClassName(entity.getName());
    try {
        ClassLoader loader = AccessController.doPrivileged(J2DoPrivHelper.getClassLoaderAction(entity));
        Class<?> m2cls = AccessController.doPrivileged(J2DoPrivHelper.getForNameAction(m2, true, loader));
        _metamodel.put(entity, m2cls);
        return m2cls;
    } catch (Throwable t) {
        if (_log.isTraceEnabled())
            _log.warn(_loc.get("meta-no-model", m2, entity, t));
    }
    return null;
}

From source file:javazoom.jlgui.player.amp.PlayerApplet.java

/**
 * Simulates "Play" selection.//from   w  w  w  .j  a va 2 s  .  c  o  m
 */
public void pressStart() {
    AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            acPlay.fireEvent();
            return null;
        }
    });
}

From source file:javazoom.jlgui.player.amp.PlayerApplet.java

/**
 * Simulates "Pause" selection./*from  w  ww.j a va  2  s.  c  om*/
 */
public void pressPause() {
    AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            acPause.fireEvent();
            return null;
        }
    });
}

From source file:javazoom.jlgui.player.amp.PlayerApplet.java

/**
 * Simulates "Stop" selection.//from ww  w.  j  av  a  2 s  .  c o  m
 */
public void pressStop() {
    AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            acStop.fireEvent();
            return null;
        }
    });
}

From source file:javazoom.jlgui.player.amp.PlayerApplet.java

/**
 * Simulates "Next" selection./*from w w w  .  j  a  v a2  s . co m*/
 */
public void pressNext() {
    AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            acNext.fireEvent();
            return null;
        }
    });
}