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.util.ProxyManagerImpl.java

/**
 * Generate the bytecode for a map proxy for the given type.
 *///w  w  w.ja va  2 s  .c o  m
protected BCClass generateProxyMapBytecode(Class type, boolean runtime) {
    assertNotFinal(type);
    Project project = new Project();
    BCClass bc = AccessController
            .doPrivileged(J2DoPrivHelper.loadProjectClassAction(project, getProxyClassName(type, runtime)));
    bc.setSuperclass(type);
    bc.declareInterface(ProxyMap.class);

    delegateConstructors(bc, type);
    addProxyMethods(bc, false);
    addProxyMapMethods(bc, type);
    Class<? extends ProxyMaps> mapProxyClassType = ConcurrentMap.class.isAssignableFrom(type)
            ? ProxyConcurrentMaps.class
            : ProxyMaps.class;
    proxyRecognizedMethods(bc, type, mapProxyClassType, ProxyMap.class);
    proxySetters(bc, type);
    addWriteReplaceMethod(bc, runtime);
    return bc;
}

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

/**
 * Internal method to get the metadata for the given class, without resolving it.
 *//*ww  w  .j a  va  2  s.  c o m*/
private ClassMetaData getMetaDataInternal(Class<?> cls, ClassLoader envLoader) {
    if (cls == null)
        return null;

    // check cache for existing metadata, or give up if no metadata and
    // our list of configured persistent types doesn't include the class
    ClassMetaData meta = (ClassMetaData) _metas.get(cls);
    if (meta != null && ((meta.getSourceMode() & MODE_META) != 0 || (_sourceMode & MODE_META) == 0))
        return meta;

    // if runtime, cut off search if not in pc list. we don't do this at
    // dev time so that user can manipulate persistent classes he's writing
    // before adding them to the list
    if ((_validate & VALIDATE_RUNTIME) != 0) {
        Set<String> pcNames = getPersistentTypeNames(false, envLoader);
        if (pcNames != null && !pcNames.contains(cls.getName()))
            return meta;
    }

    if (meta == null) {
        // check to see if maybe we know this class has no metadata
        if (_metas.containsKey(cls))
            return null;

        // make sure this isn't an obviously bad class
        if (cls.isPrimitive() || cls.getName().startsWith("java.") || cls == PersistenceCapable.class)
            return null;

        // designed to get around jikes 1.17 / JDK1.5 issue where static
        // initializers are not invoked when a class is referenced, so the
        // class never registers itself with the system
        if ((_validate & VALIDATE_RUNTIME) != 0) {
            try {
                Class.forName(cls.getName(), true,
                        AccessController.doPrivileged(J2DoPrivHelper.getClassLoaderAction(cls)));
            } catch (Throwable t) {
            }
        }
    }

    // not in cache: load metadata or mappings depending on source mode.
    // loading metadata might also load mappings, but doesn't have to
    int mode = 0;
    if ((_sourceMode & MODE_META) != 0)
        mode = _sourceMode & ~MODE_MAPPING;
    else if ((_sourceMode & MODE_MAPPING) == 0)
        mode = _sourceMode;
    if (mode != MODE_NONE) {
        if (_log.isTraceEnabled())
            _log.trace(_loc.get("load-cls", cls, toModeString(mode)));
        _factory.load(cls, mode, envLoader);
    }

    // check cache again
    if (meta == null)
        meta = (ClassMetaData) _metas.get(cls);
    if (meta != null && ((meta.getSourceMode() & MODE_META) != 0 || (_sourceMode & MODE_META) == 0))
        return meta;

    // record that this class has no metadata; checking for this later
    // speeds things up in environments with slow class loading
    // like appservers
    if (meta != null)
        removeMetaData(meta);
    _metas.put(cls, null);
    return null;
}

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

protected boolean isDefaultPersistent(ClassMetaData meta, Member member, String name, boolean ignoreTransient) {
    int mods = member.getModifiers();
    if (Modifier.isTransient(mods))
        return false;
    int access = meta.getAccessType();

    if (member instanceof Field) {
        // If mixed or unknown, default property access, keep explicit 
        // field members
        if (AccessCode.isProperty(access)) {
            if (!isAnnotatedAccess(member, AccessType.FIELD))
                return false;
        }//from  w  ww . ja v  a  2 s  .  c  o  m
    } else if (member instanceof Method) {
        // If mixed or unknown, field default access, keep explicit property
        // members
        if (AccessCode.isField(access)) {
            if (!isAnnotatedAccess(member, AccessType.PROPERTY))
                return false;
        }
        try {
            // check for setters for methods
            Method setter = (Method) AccessController.doPrivileged(J2DoPrivHelper.getDeclaredMethodAction(
                    meta.getDescribedType(), "set" + StringUtils.capitalize(name),
                    new Class[] { ((Method) member).getReturnType() }));
            if (setter == null && !isAnnotatedTransient(member)) {
                logNoSetter(meta, name, null);
                return false;
            }
        } catch (Exception e) {
            // e.g., NoSuchMethodException
            if (!isAnnotatedTransient(member))
                logNoSetter(meta, name, e);
            return false;
        }
    }

    PersistenceStrategy strat = getPersistenceStrategy(null, member, ignoreTransient);
    if (strat == null) {
        warn(meta, _loc.get("no-pers-strat", name));
        return false;
    } else if (strat == PersistenceStrategy.TRANSIENT) {
        return false;
    } else {
        return true;
    }
}

From source file:org.apache.catalina.session.PersistentManagerBase.java

/**
 * Look for a session in the Store and, if found, restore
 * it in the Manager's list of active sessions if appropriate.
 * The session will be removed from the Store after swapping
 * in, but will not be added to the active session list if it
 * is invalid or past its expiration.//from  ww w.  j  a v  a  2s . c om
 */
protected Session swapIn(String id) throws IOException {

    if (store == null)
        return null;

    Session session = null;
    try {
        if (System.getSecurityManager() != null) {
            try {
                session = (Session) AccessController.doPrivileged(new PrivilegedStoreLoad(id));
            } catch (PrivilegedActionException ex) {
                Exception exception = ex.getException();
                log.error("Exception clearing the Store: " + exception);
                if (exception instanceof IOException) {
                    throw (IOException) exception;
                } else if (exception instanceof ClassNotFoundException) {
                    throw (ClassNotFoundException) exception;
                }
            }
        } else {
            session = store.load(id);
        }
    } catch (ClassNotFoundException e) {
        log.error(sm.getString("persistentManager.deserializeError", id, e));
        throw new IllegalStateException(sm.getString("persistentManager.deserializeError", id, e));
    }

    if (session == null)
        return (null);

    if (!session.isValid()) {
        log.error("session swapped in is invalid or expired");
        session.expire();
        removeSession(id);
        return (null);
    }

    if (log.isDebugEnabled())
        log.debug(sm.getString("persistentManager.swapIn", id));

    session.setManager(this);
    // make sure the listeners know about it.
    ((StandardSession) session).tellNew();
    add(session);
    ((StandardSession) session).activate();

    return (session);

}

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

/**
 * Parse persistent type names./*  www .j a  v a2  s .c  o  m*/
 */
protected Set<String> parsePersistentTypeNames(ClassLoader loader) throws IOException {
    ClassArgParser cparser = newClassArgParser();
    String[] clss;
    Set<String> names = new HashSet<String>();
    if (files != null) {
        File file;
        for (Iterator itr = files.iterator(); itr.hasNext();) {
            file = (File) itr.next();
            if ((AccessController.doPrivileged(J2DoPrivHelper.isDirectoryAction(file))).booleanValue()) {
                if (log.isTraceEnabled())
                    log.trace(_loc.get("scanning-directory", file));
                scan(new FileMetaDataIterator(file, newMetaDataFilter()), cparser, names, true, file);
            } else if (file.getName().endsWith(".jar")) {
                if (log.isTraceEnabled())
                    log.trace(_loc.get("scanning-jar", file));
                try {
                    ZipFile zFile = AccessController.doPrivileged(J2DoPrivHelper.newZipFileAction(file));
                    scan(new ZipFileMetaDataIterator(zFile, newMetaDataFilter()), cparser, names, true, file);
                } catch (PrivilegedActionException pae) {
                    throw (IOException) pae.getException();
                }
            } else {
                if (log.isTraceEnabled())
                    log.trace(_loc.get("scanning-file", file));
                clss = cparser.parseTypeNames(new FileMetaDataIterator(file));
                List<String> newNames = Arrays.asList(clss);
                if (log.isTraceEnabled())
                    log.trace(_loc.get("scan-found-names", newNames, file));
                names.addAll(newNames);
                File f = AccessController.doPrivileged(J2DoPrivHelper.getAbsoluteFileAction(file));
                try {
                    mapPersistentTypeNames(AccessController.doPrivileged(J2DoPrivHelper.toURLAction(f)), clss);
                } catch (PrivilegedActionException pae) {
                    throw (FileNotFoundException) pae.getException();
                }
            }
        }
    }
    URL url;
    if (urls != null) {
        for (Iterator itr = urls.iterator(); itr.hasNext();) {
            url = (URL) itr.next();
            if ("file".equals(url.getProtocol())) {
                File file = AccessController
                        .doPrivileged(J2DoPrivHelper.getAbsoluteFileAction(new File(url.getFile())));
                if (files != null && files.contains(file)) {
                    continue;
                } else if ((AccessController.doPrivileged(J2DoPrivHelper.isDirectoryAction(file)))
                        .booleanValue()) {
                    if (log.isTraceEnabled())
                        log.trace(_loc.get("scanning-directory", file));
                    scan(new FileMetaDataIterator(file, newMetaDataFilter()), cparser, names, true, file);
                    continue;
                }
            }
            if ("vfs".equals(url.getProtocol())) {
                if (log.isTraceEnabled()) {
                    log.trace(_loc.get("scanning-vfs-url", url));
                }

                final URLConnection conn = url.openConnection();
                final Object vfsContent = conn.getContent();
                final URL finalUrl = url;
                File file = AccessController.doPrivileged(new PrivilegedAction<File>() {
                    @SuppressWarnings({ "rawtypes", "unchecked" })
                    public File run() {
                        try {
                            Class virtualFileClass = Class.forName("org.jboss.vfs.VirtualFile");
                            Method getPhysicalFile = virtualFileClass.getDeclaredMethod("getPhysicalFile");
                            return (File) getPhysicalFile.invoke(vfsContent);
                        } catch (Exception e) {
                            log.error(_loc.get("while-scanning-vfs-url", finalUrl), e);
                        }
                        return null;
                    }
                });
                if (file != null)
                    scan(new FileMetaDataIterator(file, newMetaDataFilter()), cparser, names, true, file);

                continue;
            }
            if ("jar".equals(url.getProtocol())) {
                if (url.getPath().endsWith("!/")) {
                    if (log.isTraceEnabled())
                        log.trace(_loc.get("scanning-jar-url", url));
                    scan(new ZipFileMetaDataIterator(url, newMetaDataFilter()), cparser, names, true, url);
                } else {
                    if (log.isTraceEnabled())
                        log.trace(_loc.get("scanning-jar-url", url));
                    scan(new JarFileURLMetaDataIterator(url, newMetaDataFilter()), cparser, names, true, url);
                }
            } else if (url.getPath().endsWith(".jar")) {
                if (log.isTraceEnabled())
                    log.trace(_loc.get("scanning-jar-at-url", url));
                try {
                    InputStream is = (InputStream) AccessController
                            .doPrivileged(J2DoPrivHelper.openStreamAction(url));
                    scan(new ZipStreamMetaDataIterator(new ZipInputStream(is), newMetaDataFilter()), cparser,
                            names, true, url);
                } catch (PrivilegedActionException pae) {
                    throw (IOException) pae.getException();
                }
            } else {
                // Open an InputStream from the URL and sniff for a zip header.  If it is, then this is
                // a URL with a jar-formated InputStream, as per the JPA specification.  Otherwise, fall back
                // to URLMetaDataIterator.
                BufferedInputStream is = null;

                try {
                    is = new BufferedInputStream(
                            (InputStream) AccessController.doPrivileged(J2DoPrivHelper.openStreamAction(url)));
                } catch (PrivilegedActionException pae) {
                    throw (IOException) pae.getException();
                }

                // Check for zip header magic 0x50 0x4b 0x03 0x04
                is.mark(0);
                boolean zipHeaderMatch = is.read() == 0x50 && is.read() == 0x4b && is.read() == 0x03
                        && is.read() == 0x04;
                is.reset();

                if (zipHeaderMatch) {
                    // The URL provides a Jar-formatted InputStream, consume it with ZipStreamMetaDataIterator
                    if (log.isTraceEnabled())
                        log.trace(_loc.get("scanning-jar-at-url", url));
                    scan(new ZipStreamMetaDataIterator(new ZipInputStream(is), newMetaDataFilter()), cparser,
                            names, true, url);
                } else {
                    // Fall back to URLMetaDataIterator
                    if (log.isTraceEnabled())
                        log.trace(_loc.get("scanning-url", url));
                    clss = cparser.parseTypeNames(new URLMetaDataIterator(url));
                    List<String> newNames = Arrays.asList(clss);
                    if (log.isTraceEnabled())
                        log.trace(_loc.get("scan-found-names", newNames, url));
                    names.addAll(newNames);
                    mapPersistentTypeNames(url, clss);
                }
            }
        }
    }
    if (rsrcs != null) {
        String rsrc;
        MetaDataIterator mitr;
        for (Iterator itr = rsrcs.iterator(); itr.hasNext();) {
            rsrc = (String) itr.next();
            if (rsrc.endsWith(".jar")) {
                url = AccessController.doPrivileged(J2DoPrivHelper.getResourceAction(loader, rsrc));
                if (url != null) {
                    if (log.isTraceEnabled())
                        log.trace(_loc.get("scanning-jar-stream-url", url));
                    try {
                        InputStream is = (InputStream) AccessController
                                .doPrivileged(J2DoPrivHelper.openStreamAction(url));
                        scan(new ZipStreamMetaDataIterator(new ZipInputStream(is), newMetaDataFilter()),
                                cparser, names, true, url);
                    } catch (PrivilegedActionException pae) {
                        throw (IOException) pae.getException();
                    }
                }
            } else {
                if (log.isTraceEnabled())
                    log.trace(_loc.get("scanning-resource", rsrc));
                mitr = new ResourceMetaDataIterator(rsrc, loader);
                OpenJPAConfiguration conf = repos.getConfiguration();
                Map peMap = null;
                if (conf instanceof OpenJPAConfigurationImpl)
                    peMap = ((OpenJPAConfigurationImpl) conf).getPersistenceEnvironment();
                URL puUrl = peMap == null ? null : (URL) peMap.get(PERSISTENCE_UNIT_ROOT_URL);
                List<String> mappingFileNames = peMap == null ? null
                        : (List<String>) peMap.get(MAPPING_FILE_NAMES);
                List<URL> jars = peMap == null ? null : (List<URL>) peMap.get(JAR_FILE_URLS);
                String puUrlString = puUrl == null ? null : puUrl.toString();
                if (log.isTraceEnabled())
                    log.trace(_loc.get("pu-root-url", puUrlString));

                URL puORMUrl = null;
                try {
                    if (puUrlString != null) {
                        String puORMUrlStr = puUrlString + (puUrlString.endsWith("/") ? "" : "/") + rsrc;
                        puORMUrl = AccessController.doPrivileged(J2DoPrivHelper.createURL(puORMUrlStr));
                    }
                } catch (PrivilegedActionException e) {
                    throw new IOException("Error generating puORMUrlStr.", e.getCause());
                }

                List<URL> urls = new ArrayList<URL>(3);
                while (mitr.hasNext()) {
                    url = (URL) mitr.next();
                    String urlString = url.toString();
                    if (log.isTraceEnabled())
                        log.trace(_loc.get("resource-url", urlString));
                    if (peMap != null) {
                        //OPENJPA-2102: decode the URL to remove such things a spaces (' ') encoded as '%20'
                        if (puUrlString != null && decode(urlString).indexOf(decode(puUrlString)) != -1) {
                            urls.add(url);
                        } else if (puORMUrl != null && puORMUrl.equals(url)) {
                            // Check URL equality to support encapsulating URL protocols
                            urls.add(url);
                        }
                        if (mappingFileNames != null && mappingFileNames.size() != 0) {
                            for (String mappingFileName : mappingFileNames) {
                                if (log.isTraceEnabled())
                                    log.trace(_loc.get("mapping-file-name", mappingFileName));
                                if (urlString.indexOf(mappingFileName) != -1)
                                    urls.add(url);
                            }
                        }

                        if (jars != null && jars.size() != 0) {
                            for (URL jarUrl : jars) {
                                if (log.isTraceEnabled())
                                    log.trace(_loc.get("jar-file-url", jarUrl));
                                if (urlString.indexOf(jarUrl.toString()) != -1)
                                    urls.add(url);
                            }
                        }
                    } else {
                        urls.add(url);
                    }
                }
                mitr.close();

                for (Object obj : urls) {
                    url = (URL) obj;
                    clss = cparser.parseTypeNames(new URLMetaDataIterator(url));
                    List<String> newNames = Arrays.asList(clss);
                    if (log.isTraceEnabled())
                        log.trace(_loc.get("scan-found-names", newNames, rsrc));
                    names.addAll(newNames);
                    mapPersistentTypeNames(url, clss);
                }
            }
        }
    }
    if (cpath != null) {
        String[] dirs = (String[]) cpath.toArray(new String[cpath.size()]);
        scan(new ClasspathMetaDataIterator(dirs, newMetaDataFilter()), cparser, names, true, dirs);
    }
    if (types != null)
        names.addAll(types);

    if (log.isTraceEnabled())
        log.trace(_loc.get("parse-found-names", names));

    return names;
}

From source file:org.apache.openjpa.util.ProxyManagerImpl.java

/**
 * Generate the bytecode for a date proxy for the given type.
 *///ww  w.  j  a  v  a2 s . c o m
protected BCClass generateProxyDateBytecode(Class type, boolean runtime) {
    assertNotFinal(type);
    Project project = new Project();
    BCClass bc = AccessController
            .doPrivileged(J2DoPrivHelper.loadProjectClassAction(project, getProxyClassName(type, runtime)));
    bc.setSuperclass(type);
    bc.declareInterface(ProxyDate.class);

    delegateConstructors(bc, type);
    addProxyMethods(bc, true);
    addProxyDateMethods(bc, type);
    proxySetters(bc, type);
    addWriteReplaceMethod(bc, runtime);
    return bc;
}

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

private boolean isAnnotatedTransient(Member member) {
    return member instanceof AnnotatedElement && (AccessController.doPrivileged(
            J2DoPrivHelper.isAnnotationPresentAction(((AnnotatedElement) member), Transient.class)))
                    .booleanValue();//from w  ww.  ja  v  a  2  s. c om
}

From source file:org.apache.openjpa.util.ProxyManagerImpl.java

/**
 * Generate the bytecode for a calendar proxy for the given type.
 */// ww w.  j a v a  2 s . c  om
protected BCClass generateProxyCalendarBytecode(Class type, boolean runtime) {
    assertNotFinal(type);
    Project project = new Project();
    BCClass bc = AccessController
            .doPrivileged(J2DoPrivHelper.loadProjectClassAction(project, getProxyClassName(type, runtime)));
    bc.setSuperclass(type);
    bc.declareInterface(ProxyCalendar.class);

    delegateConstructors(bc, type);
    addProxyMethods(bc, true);
    addProxyCalendarMethods(bc, type);
    proxySetters(bc, type);
    addWriteReplaceMethod(bc, runtime);
    return bc;
}

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

public void handlePageException(final Throwable t) throws IOException, ServletException {
    if (t == null)
        throw new NullPointerException("null Throwable");

    if (System.getSecurityManager() != null) {
        try {/*from  w  w w . j  av  a  2s . c o m*/
            AccessController.doPrivileged(new PrivilegedExceptionAction() {
                public Object run() throws Exception {
                    doHandlePageException(t);
                    return null;
                }
            });
        } catch (PrivilegedActionException e) {
            Exception ex = e.getException();
            if (ex instanceof IOException) {
                throw (IOException) ex;
            } else {
                throw (ServletException) ex;
            }
        }
    } else {
        doHandlePageException(t);
    }

}

From source file:org.apache.bsf.BSFManager.java

/**
 * Load a scripting engine based on the lang string identifying it.
 *
 * @param lang string identifying language
 * @exception BSFException if the language is unknown (i.e., if it
 *            has not been registered) with a reason of
 *            REASON_UNKNOWN_LANGUAGE. If the language is known but
 *            if the interface can't be created for some reason, then
 *            the reason is set to REASON_OTHER_ERROR and the actual
 *            exception is passed on as well.
 *///from ww w .  j a va  2  s .  c  o m
public BSFEngine loadScriptingEngine(String lang) throws BSFException {
    logger.debug("BSFManager:loadScriptingEngine");

    // if its already loaded return that
    BSFEngine eng = (BSFEngine) loadedEngines.get(lang);
    if (eng != null) {
        return eng;
    }

    // is it a registered language?
    String engineClassName = (String) registeredEngines.get(lang);
    if (engineClassName == null) {
        logger.error("unsupported language: " + lang);
        throw new BSFException(BSFException.REASON_UNKNOWN_LANGUAGE, "unsupported language: " + lang);
    }

    // create the engine and initialize it. if anything goes wrong
    // except.
    try {
        Class engineClass = (classLoader == null) ? Class.forName(engineClassName)
                : classLoader.loadClass(engineClassName);
        final BSFEngine engf = (BSFEngine) engineClass.newInstance();
        final BSFManager thisf = this;
        final String langf = lang;
        final Vector dbf = declaredBeans;
        AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws Exception {
                engf.initialize(thisf, langf, dbf);
                return null;
            }
        });
        eng = engf;
        loadedEngines.put(lang, eng);
        pcs.addPropertyChangeListener(eng);
        return eng;
    } catch (PrivilegedActionException prive) {

        logger.error("Exception :", prive);
        throw (BSFException) prive.getException();
    } catch (Throwable t) {

        logger.error("Exception :", t);
        throw new BSFException(BSFException.REASON_OTHER_ERROR, "unable to load language: " + lang, t);
    }
}