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:freemarker.log.Logger.java

/**
 * Don't use {@link freemarker.template.utility.SecurityUtilities#getSystemProperty(String, String)} here, as it
 * (might) depends on the logger, hence interfering with the initialization.
 *///from w  w  w  .ja va 2s .c  o  m
private static String getSystemProperty(final String key) {
    try {
        return (String) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                return System.getProperty(key, null);
            }
        });
    } catch (AccessControlException e) {
        logWarnInLogger("Insufficient permissions to read system property \"" + key + "\".");
        return null;
    } catch (Throwable e) {
        logErrorInLogger("Failed to read system property \"" + key + "\".", e);
        return null;
    }
}

From source file:eu.europa.ejusticeportal.dss.applet.DssApplet.java

/**
 * DssApplet destroy :/* ww  w . ja v  a  2 s  .  c o  m*/
 * <ul>
 * <li>[1] Close the JRE instance which was running the DssApplet.</li>
 * </ul>
 *
 * {@inheritDoc}
 */
@Override
public void destroy() {
    LOG.info("Applet is destroying...");
    /*
     * The Java process created by the applet can take more than five minutes to exit, the System is required to
     * exit to bypass this behaviour.
     * All required operations are already done in stop() function.
     */
    AccessController.doPrivileged(new PrivilegedAction<Void>() {
        public Void run() {
            //TODO remove the System.exit(0). 
            //If the user has other applets running in his browser we also kill those.
            System.exit(0);
            return null;
        }
    });
}

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

/**
 * Read annotations for the current type.
 *//*from  ww w  .  ja va2s . c o  m*/
private ClassMetaData parseClassAnnotations() {
    // Check to see if there is cached metadata for the class that we are currently parsing. It
    // is possible that one of the annotations (Entity, Embeddable, MappedSuperclass) is in the
    // orm.xml. We still need to look at these files for other annotations and more importantly
    // setup defaults (ie: Basic fields).
    ClassMetaData m = getRepository().getCachedMetaData(_cls);
    if (m == null) {
        if (!(AccessController.doPrivileged(J2DoPrivHelper.isAnnotationPresentAction(_cls, Entity.class)))
                .booleanValue()
                && !(AccessController
                        .doPrivileged(J2DoPrivHelper.isAnnotationPresentAction(_cls, Embeddable.class)))
                                .booleanValue()
                && !(AccessController
                        .doPrivileged(J2DoPrivHelper.isAnnotationPresentAction(_cls, MappedSuperclass.class)))
                                .booleanValue())
            return null;
    }
    // find / create metadata
    ClassMetaData meta = (m == null) ? getMetaData() : m;
    if (meta == null)
        return null;

    Entity entity = _cls.getAnnotation(Entity.class);
    MappedSuperclass mapped = _cls.getAnnotation(MappedSuperclass.class);
    Embeddable embeddable = _cls.getAnnotation(Embeddable.class);
    if (isMetaDataMode()) {
        meta.setAbstract(mapped != null);
        if (embeddable != null)
            meta.setEmbeddable();
        // while the spec only provides for embedded exclusive, it doesn't
        // seem hard to support otherwise
        if (entity == null)
            meta.setEmbeddedOnly(true);
        else {
            meta.setEmbeddedOnly(false);
            if (!StringUtils.isEmpty(entity.name()))
                meta.setTypeAlias(entity.name());
        }
    }

    // track fetch groups to parse them after fields, since they
    // rely on field metadata
    FetchGroup[] fgs = null;
    DetachedState detached = null;

    // track listeners since we need to merge them with entity callbacks
    Collection<LifecycleCallbacks>[] listeners = null;
    MetaDataTag tag;
    for (Annotation anno : _cls.getDeclaredAnnotations()) {
        tag = _tags.get(anno.annotationType());
        if (tag == null) {
            handleUnknownClassAnnotation(meta, anno);
            continue;
        }

        switch (tag) {
        case ENTITY_LISTENERS:
            if (isMetaDataMode())
                listeners = parseEntityListeners(meta, (EntityListeners) anno);
            break;
        case EXCLUDE_DEFAULT_LISTENERS:
            if (isMetaDataMode())
                meta.getLifecycleMetaData().setIgnoreSystemListeners(true);
            break;
        case EXCLUDE_SUPERCLASS_LISTENERS:
            if (isMetaDataMode())
                meta.getLifecycleMetaData().setIgnoreSuperclassCallbacks(LifecycleMetaData.IGNORE_HIGH);
            break;
        case FLUSH_MODE:
            if (isMetaDataMode())
                warnFlushMode(meta);
            break;
        case ID_CLASS:
            if (isMetaDataMode())
                meta.setObjectIdType(((IdClass) anno).value(), true);
            break;
        case NATIVE_QUERIES:
            if (isQueryMode() && (meta.getSourceMode() & MODE_QUERY) == 0)
                parseNamedNativeQueries(_cls, ((NamedNativeQueries) anno).value());
            break;
        case NATIVE_QUERY:
            if (isQueryMode() && (meta.getSourceMode() & MODE_QUERY) == 0)
                parseNamedNativeQueries(_cls, (NamedNativeQuery) anno);
            break;
        case QUERIES:
            if (isQueryMode() && (meta.getSourceMode() & MODE_QUERY) == 0)
                parseNamedQueries(_cls, ((NamedQueries) anno).value());
            break;
        case QUERY:
            if (isQueryMode() && (meta.getSourceMode() & MODE_QUERY) == 0)
                parseNamedQueries(_cls, (NamedQuery) anno);
            break;
        case SEQ_GENERATOR:
            if (isMappingOverrideMode())
                parseSequenceGenerator(_cls, (SequenceGenerator) anno);
            break;
        case DATA_CACHE:
            if (isMetaDataMode())
                parseDataCache(meta, (DataCache) anno);
            break;
        case DATASTORE_ID:
            if (isMetaDataMode())
                parseDataStoreId(meta, (DataStoreId) anno);
            break;
        case DETACHED_STATE:
            detached = (DetachedState) anno;
            break;
        case FETCH_GROUP:
            if (isMetaDataMode())
                fgs = new FetchGroup[] { (FetchGroup) anno };
            break;
        case FETCH_GROUPS:
            if (isMetaDataMode())
                fgs = ((FetchGroups) anno).value();
            break;
        case MANAGED_INTERFACE:
            if (isMetaDataMode())
                parseManagedInterface(meta, (ManagedInterface) anno);
            break;
        case ACCESS:
            if (isMetaDataMode())
                parseAccess(meta, (Access) anno);
            break;
        case CACHEABLE:
            if (isMetaDataMode()) {
                parseCache(meta, (Cacheable) anno);
            }
            break;
        default:
            throw new UnsupportedException(_loc.get("unsupported", _cls, anno.toString()));
        }
    }

    if (isMetaDataMode()) {
        parseDetachedState(meta, detached);

        // merge callback methods with declared listeners
        int[] highs = null;
        if (listeners != null) {
            highs = new int[listeners.length];
            for (int i = 0; i < listeners.length; i++)
                if (listeners[i] != null)
                    highs[i] = listeners[i].size();
        }
        recordCallbacks(meta, parseCallbackMethods(_cls, listeners, false, false, getRepository()), highs,
                false);

        // scan possibly non-PC hierarchy for callbacks.
        // redundant for PC superclass but we don't know that yet
        // so let LifecycleMetaData determine that
        if (_cls.getSuperclass() != null && !Object.class.equals(_cls.getSuperclass())) {
            recordCallbacks(meta,
                    parseCallbackMethods(_cls.getSuperclass(), null, true, false, getRepository()), null, true);
        }
    }

    for (FieldMetaData fmd : meta.getDeclaredFields())
        if (fmd.getManagement() == FieldMetaData.MANAGE_PERSISTENT)
            parseMemberAnnotations(fmd);
    // parse fetch groups after fields
    if (fgs != null)
        parseFetchGroups(meta, fgs);

    // always parse mapping after metadata in case there are dependencies
    if (isMappingOverrideMode()) {
        parseClassMappingAnnotations(meta);
        for (FieldMetaData fmd : meta.getDeclaredFields())
            if (fmd.getManagement() == FieldMetaData.MANAGE_PERSISTENT)
                parseMemberMappingAnnotations(fmd);
    }
    return meta;
}

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

/**
 * Remove this Session from the active Sessions for this Manager,
 * and from the Store./* w  w w  . j  a v  a 2  s . c o m*/
 *
 * @param is Session's id to be removed
 */
protected void removeSession(String id) {
    try {
        if (System.getSecurityManager() != null) {
            try {
                AccessController.doPrivileged(new PrivilegedStoreRemove(id));
            } catch (PrivilegedActionException ex) {
                Exception exception = ex.getException();
                log.error("Exception clearing the Store: " + exception);
                exception.printStackTrace();
            }
        } else {
            store.remove(id);
        }
    } catch (IOException e) {
        log.error("Exception removing session  " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:ddf.catalog.history.Historian.java

/**
 * Caution should be used with this, as it elevates the permissions to the System user.
 *
 * @param func What to execute as the System
 * @param <T> Generic return type of func
 * @return result of the callable func/*from  w ww. java 2  s  .  c om*/
 */
private <T> T executeAsSystem(Callable<T> func) {
    if (security == null) {
        security = Security.getInstance();
    }

    Subject systemSubject = AccessController
            .doPrivileged((PrivilegedAction<Subject>) () -> security.runAsAdmin(security::getSystemSubject));

    if (systemSubject == null) {
        throw new IllegalStateException("Could not get systemSubject to version metacards.");
    }

    return systemSubject.execute(func);
}

From source file:org.acmsl.commons.regexpplugin.RegexpManager.java

/**
 * Retrieves the stream associated to the resource
 * whose name is given, using a concrete class loader.
 * @param loader the class loader.//from  www  .j a  va 2  s.c o m
 * @param name the resource name.
 * @return the stream.
 */
@Nullable
protected InputStream getResourceAsStream(@Nullable final ClassLoader loader, @NotNull final String name) {
    return AccessController.doPrivileged(new PrivilegedAction<InputStream>() {
        public InputStream run() {
            final InputStream result;

            if (loader != null) {
                result = loader.getResourceAsStream(name);
            } else {
                result = ClassLoader.getSystemResourceAsStream(name);
            }

            return result;
        }
    });
}

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

/**
 * This method will provide the logic needed to retrieve an Object's classloader
 * in a Java 2 Security compliant manner.
 *///from   w  w  w  .  ja v a2s. c  o  m
public static ClassLoader getObjectClassLoader(final Object object) {
    if (object == null) {
        return null;
    } else {
        return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                return object.getClass().getClassLoader();
            }
        });
    }
}

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

/**
* Get the port to be used for test application deployments.
*
* @return The HTTP port of the URI// w  ww .jav a 2 s .c o  m
*/
protected final int getPort() {
    final String value = AccessController
            .doPrivileged(PropertiesHelper.getSystemProperty(TestProperties.CONTAINER_PORT));
    if (value != null) {

        try {
            final int i = Integer.parseInt(value);
            if (i <= 0) {
                throw new NumberFormatException("Value not positive.");
            }
            return i;
        } catch (NumberFormatException e) {
            LOGGER.log(Level.CONFIG,
                    "Value of " + TestProperties.CONTAINER_PORT + " property is not a valid positive integer ["
                            + value + "]." + " Reverting to default [" + TestProperties.DEFAULT_CONTAINER_PORT
                            + "].",
                    e);
        }
    }
    return TestProperties.DEFAULT_CONTAINER_PORT;
}

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

/**
 * Perform bytecode enhancements.//w w  w . java  2s .c  om
 *
 * @return <code>ENHANCE_*</code> constant
 */
public int run() {
    Class<?> type = _managedType.getType();
    try {
        // if managed interface, skip
        if (_pc.isInterface())
            return ENHANCE_INTERFACE;

        // check if already enhanced
        ClassLoader loader = AccessController.doPrivileged(J2DoPrivHelper.getClassLoaderAction(type));
        for (String iface : _managedType.getDeclaredInterfaceNames()) {
            if (iface.equals(PCTYPE.getName())) {
                if (_log.isTraceEnabled()) {
                    _log.trace(_loc.get("pc-type", type, loader));
                }
                return ENHANCE_NONE;
            }
        }
        if (_log.isTraceEnabled()) {
            _log.trace(_loc.get("enhance-start", type, loader));
        }

        configureBCs();

        // validate properties before replacing field access so that
        // we build up a record of backing fields, etc
        if (isPropertyAccess(_meta)) {
            validateProperties();
            if (getCreateSubclass())
                addAttributeTranslation();
        }
        replaceAndValidateFieldAccess();
        processViolations();

        if (_meta != null) {
            enhanceClass();
            addFields();
            addStaticInitializer();
            addPCMethods();
            addAccessors();
            addAttachDetachCode();
            addSerializationCode();
            addCloningCode();
            runAuxiliaryEnhancers();
            return ENHANCE_PC;
        }
        return ENHANCE_AWARE;
    } catch (OpenJPAException ke) {
        throw ke;
    } catch (Exception e) {
        throw new GeneralException(_loc.get("enhance-error", type.getName(), e.getMessage()), e);
    }
}

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

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

    if (SecurityUtil.isPackageProtectionEnabled()) {
        try {//from   w  w w.  j  a  v a 2 s.  co 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);
    }

}