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.ellychou.todo.rest.service.SpringContextJerseyTest.java

/**
* Returns an instance of {@link TestContainerFactory} class. This instance can be set by a constructor ({@link
* #JerseyTest(org.glassfish.jersey.test.spi.TestContainerFactory)}, as an application {@link Providers Provider} or the
* {@link TestContainerFactory} class can be set as a {@value org.glassfish.jersey.test.TestProperties#CONTAINER_FACTORY}
* property.//ww  w .j a v  a2  s. co m
*
* @return an instance of {@link TestContainerFactory} class.
* @throws TestContainerException if the initialization of {@link TestContainerFactory} instance is not successful.
*/
protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
    if (testContainerFactory == null) {
        if (testContainerFactoryClass == null) {

            final String tcfClassName = getProperty(TestProperties.CONTAINER_FACTORY);
            if ((tcfClassName == null)) {
                Set<TestContainerFactory> testContainerFactories = Providers
                        .getProviders(application.getServiceLocator(), TestContainerFactory.class);

                if (testContainerFactories.size() >= 1) {
                    // if default factory is present, use it.
                    for (TestContainerFactory tcFactory : testContainerFactories) {

                        if (tcFactory.getClass().getName().equals(TestProperties.DEFAULT_CONTAINER_FACTORY)) {
                            LOGGER.log(Level.CONFIG,
                                    "Found multiple TestContainerFactory implementations, using default {0}",
                                    tcFactory.getClass().getName());

                            testContainerFactoryClass = tcFactory.getClass(); // is this necessary?
                            return tcFactory;
                        }
                    }

                    if (testContainerFactories.size() != 1) {
                        LOGGER.log(Level.WARNING,
                                "Found multiple TestContainerFactory implementations, using {0}",
                                testContainerFactories.iterator().next().getClass().getName());
                    }

                    testContainerFactoryClass = testContainerFactories.iterator().next().getClass();
                    return testContainerFactories.iterator().next();

                }
            } else {
                final Class<Object> tfClass = AccessController
                        .doPrivileged(ReflectionHelper.classForNamePA(tcfClassName, null));
                if (tfClass == null) {
                    throw new TestContainerException("The default test container factory class name, "
                            + tcfClassName + ", cannot be loaded");
                }
                try {
                    testContainerFactoryClass = tfClass.asSubclass(TestContainerFactory.class);
                } catch (ClassCastException ex) {
                    throw new TestContainerException("The default test container factory class, " + tcfClassName
                            + ", is not an instance of TestContainerFactory", ex);
                }
            }
        }

        try {
            return testContainerFactoryClass.newInstance();
        } catch (Exception ex) {
            throw new TestContainerException("The default test container factory, " + testContainerFactoryClass
                    + ", could not be instantiated", ex);
        }
    }

    return testContainerFactory;
}

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

public void initialize(AbstractBrokerFactory factory, DelegatingStoreManager sm, boolean managed, int connMode,
        boolean fromDeserialization, boolean fromWriteBehindCallback) {
    _fromWriteBehindCallback = fromWriteBehindCallback;
    _initializeWasInvoked = true;//from  ww  w. j a v  a2 s .c o m
    _loader = AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction());
    if (!fromDeserialization) {
        _conf = factory.getConfiguration();
        _repo = _conf.getMetaDataRepositoryInstance();
    }
    _compat = _conf.getCompatibilityInstance();
    _factory = factory;
    _log = _conf.getLog(OpenJPAConfiguration.LOG_RUNTIME);
    if (!fromDeserialization)
        _cache = new ManagedCache(this);
    // Force creation of a new operating set
    _operatingDirty = true;
    initializeOperatingSet();

    _connRetainMode = connMode;
    _managed = managed;
    if (managed)
        _runtime = _conf.getManagedRuntimeInstance();
    else
        _runtime = new LocalManagedRuntime(this);

    if (!fromDeserialization) {
        _lifeEventManager = _conf.getLifecycleEventManagerInstance();
        _transEventManager = new TransactionEventManager();
        int cmode = _repo.getMetaDataFactory().getDefaults().getCallbackMode();
        setLifecycleListenerCallbackMode(cmode);
        setTransactionListenerCallbackMode(cmode);

        // setup default options
        _factory.configureBroker(this);
    }

    // make sure to do this after configuring broker so that store manager
    // can look to broker configuration; we set both store and lock managers
    // before initializing them because they may each try to access the
    // other in their initialization
    _store = sm;
    _lm = _conf.newLockManagerInstance();
    _im = _conf.newInverseManagerInstance();
    _spm = _conf.getSavepointManagerInstance();
    _store.setContext(this);
    _lm.setContext(this);

    if (_connRetainMode == CONN_RETAIN_ALWAYS)
        retainConnection();
    if (!fromDeserialization) {
        _fc = _store.newFetchConfiguration();
        _fc.setContext(this);
    }

    _instm = _conf.getInstrumentationManagerInstance();
    if (_instm != null) {
        _instm.start(InstrumentationLevel.BROKER, this);
    }

    _dmLite = new DetachManagerLite(_conf);
    _printParameters = Boolean
            .parseBoolean(Configurations.parseProperties(_conf.getConnectionFactoryProperties())
                    .getProperty(PRINT_PARAMETERS_CONFIG_STR, "false"));
    // synch with the global transaction in progress, if any
    if (_factory.syncWithManagedTransaction(this, false))
        beginInternal();
}

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

public void removeAttribute(final String name) {

    if (name == null) {
        throw new NullPointerException(Localizer.getMessage("jsp.error.attribute.null_name"));
    }/*w w  w.ja va  2s  .co  m*/

    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                doRemoveAttribute(name);
                return null;
            }
        });
    } else {
        doRemoveAttribute(name);
    }
}

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

/**
 * Return a new instance of the specified <code>RegexpEngine</code>
 * implementation class, loaded by the specified class loader.
 * If that fails, try the class loader used to load the
 * RegexpEngine.//from   w ww.  j ava2 s  .c om
 * @param engineClass Fully qualified name of the <code>RegexpEngine</code>
 * implementation class.
 * @param classLoader ClassLoader from which to load this class.
 * @throws RegexpEngineNotFoundException if a suitable instance
 * cannot be created.
 * @throws RegexpPluginMisconfiguredException if RegexpPlugin is
 * misconfigured.
 * @return the {@link RegexpEngine}.
 */
@SuppressWarnings("unchecked")
@NotNull
protected RegexpEngine createEngine(final String engineClass, final ClassLoader classLoader)
        throws RegexpEngineNotFoundException, RegexpPluginMisconfiguredException {
    @Nullable
    final RegexpEngine result = AccessController.doPrivileged(new PrivilegedAction<RegexpEngine>() {
        public RegexpEngine run() {
            RegexpEngine innerResult = null;

            final RegexpPluginMisconfiguredException exception;

            // This will be used to diagnose bad configurations
            // and allow a useful message to be sent to the user
            Class<RegexpEngine> t_RegexpEngineClass = null;

            try {
                if (classLoader != null) {
                    try {
                        // First the given class loader param
                        // (thread class loader)
                        // Warning: must typecast here & allow
                        // exception to be generated/caught &
                        // recast properly.
                        t_RegexpEngineClass = (Class<RegexpEngine>) classLoader.loadClass(engineClass);

                        innerResult = t_RegexpEngineClass.newInstance();

                    } catch (final ClassNotFoundException classNotFoundException) {
                        if (classLoader == RegexpEngine.class.getClassLoader()) {
                            // Nothing more to try, onwards.
                            throw classNotFoundException;
                        }
                        // ignore exception, continue
                    } catch (final NoClassDefFoundError noClassDefFoundException) {
                        if (classLoader == RegexpEngine.class.getClassLoader()) {
                            // Nothing more to try, onwards.
                            throw noClassDefFoundException;
                        }
                        // ignore exception, continue
                    } catch (final ClassCastException classCastException) {
                        if (classLoader == RegexpEngine.class.getClassLoader()) {
                            // Nothing more to try, onwards (bug in
                            // loader implementation).
                            throw classCastException;
                        }
                        // Ignore exception, continue
                    }
                }

                if (innerResult == null) {
                    /* At this point, either classLoader == null, OR
                     * classLoader was unable to load engineClass.
                     * Try the class loader that loaded this class:
                     * RegexpEngine.getClassLoader().
                     *
                     * Notes:
                     * a) RegexpEngine.class.getClassLoader() may return
                     *    'null' if RegexpEngine is loaded by the bootstrap
                     *    classloader.
                     * b) The Java endorsed library mechanism is instead
                     *    Class.forName(engineClass);
                     */

                    // Warning: must typecast here & allow exception
                    // to be generated/caught & recast properly.
                    t_RegexpEngineClass = (Class<RegexpEngine>) Class.forName(engineClass);

                    innerResult = t_RegexpEngineClass.newInstance();
                }
            } catch (final Exception otherException) {
                // Check to see if we've got a bad configuration
                if ((t_RegexpEngineClass != null)
                        && (!RegexpEngine.class.isAssignableFrom(t_RegexpEngineClass))) {
                    exception = new RegexpPluginMisconfiguredException(
                            "implementation.does.not." + "implement.regexpegine", otherException);
                } else {
                    exception = new RegexpPluginMisconfiguredException("unexpected.problem", otherException);
                }

                throw exception;
            }

            return innerResult;
        }
    });

    if (result == null) {
        throw new RegexpEngineNotFoundException(engineClass);
    }

    return result;
}

From source file:org.apache.myfaces.shared_ext202patch.util.StateUtils.java

/**
 * Performs deserialization with the serialization provider created from the
 * SerialFactory.//from  w ww  .java2 s . co m
 * 
 * @param bytes
 * @param ctx
 * @return
 */

public static final Object getAsObject(byte[] bytes, ExternalContext ctx) {
    ByteArrayInputStream input = null;

    try {
        input = new ByteArrayInputStream(bytes);

        // get the Factory that was instantiated @ startup
        SerialFactory serialFactory = (SerialFactory) ctx.getApplicationMap().get(SERIAL_FACTORY);

        if (serialFactory == null)
            throw new NullPointerException("serialFactory");

        ObjectInputStream s = null;
        Exception pendingException = null;
        try {
            s = serialFactory.getObjectInputStream(input);
            Object object = null;
            if (System.getSecurityManager() != null) {
                final ObjectInputStream ois = s;
                object = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                    //Put IOException and ClassNotFoundException as "checked" exceptions,
                    //so AccessController wrap them in a PrivilegedActionException
                    public Object run() throws PrivilegedActionException, IOException, ClassNotFoundException {
                        return ois.readObject();
                    }
                });
                // Since s has the same instance as ois,
                // we don't need to close it here, rather
                // close it on the finally block related to s
                // and avoid duplicate close exceptions
                // finally
                // {
                //    ois.close();
                // }
            } else {
                object = s.readObject();
            }
            return object;
        } catch (Exception e) {
            pendingException = e;
            throw new FacesException(e);
        } finally {
            if (s != null) {
                try {
                    s.close();
                } catch (IOException e) {
                    // If a previous exception is thrown 
                    // ignore this, but if not, wrap it in a
                    // FacesException and throw it. In this way
                    // we preserve the original semantic of this
                    // method, but we handle correctly the case
                    // when we close a stream. Obviously, the 
                    // information about this exception is lost,
                    // but note that the interesting information 
                    // is always on pendingException, since we
                    // only do a readObject() on the outer try block.
                    if (pendingException == null) {
                        throw new FacesException(e);
                    }
                } finally {
                    s = null;
                }
            }
        }
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                //ignore it, because ByteArrayInputStream.close has
                //no effect, but it is better to call close and preserve
                //semantic from previous code.
            } finally {
                input = null;
            }
        }
    }
}

From source file:org.apache.myfaces.shared.util.StateUtils.java

/**
 * Performs deserialization with the serialization provider created from the
 * SerialFactory./*from w ww .ja  v a2 s . co  m*/
 * 
 * @param bytes
 * @param ctx
 * @return
 */

public static final Object getAsObject(byte[] bytes, ExternalContext ctx) {
    ByteArrayInputStream input = null;

    try {
        input = new ByteArrayInputStream(bytes);

        // get the Factory that was instantiated @ startup
        SerialFactory serialFactory = (SerialFactory) ctx.getApplicationMap().get(SERIAL_FACTORY);

        if (serialFactory == null) {
            throw new NullPointerException("serialFactory");
        }

        ObjectInputStream s = null;
        Exception pendingException = null;
        try {
            s = serialFactory.getObjectInputStream(input);
            Object object = null;
            if (System.getSecurityManager() != null) {
                final ObjectInputStream ois = s;
                object = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                    //Put IOException and ClassNotFoundException as "checked" exceptions,
                    //so AccessController wrap them in a PrivilegedActionException
                    public Object run() throws PrivilegedActionException, IOException, ClassNotFoundException {
                        return ois.readObject();
                    }
                });
                // Since s has the same instance as ois,
                // we don't need to close it here, rather
                // close it on the finally block related to s
                // and avoid duplicate close exceptions
                // finally
                // {
                //    ois.close();
                // }
            } else {
                object = s.readObject();
            }
            return object;
        } catch (Exception e) {
            pendingException = e;
            throw new FacesException(e);
        } finally {
            if (s != null) {
                try {
                    s.close();
                } catch (IOException e) {
                    // If a previous exception is thrown 
                    // ignore this, but if not, wrap it in a
                    // FacesException and throw it. In this way
                    // we preserve the original semantic of this
                    // method, but we handle correctly the case
                    // when we close a stream. Obviously, the 
                    // information about this exception is lost,
                    // but note that the interesting information 
                    // is always on pendingException, since we
                    // only do a readObject() on the outer try block.
                    if (pendingException == null) {
                        throw new FacesException(e);
                    }
                } finally {
                    s = null;
                }
            }
        }
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                //ignore it, because ByteArrayInputStream.close has
                //no effect, but it is better to call close and preserve
                //semantic from previous code.
            } finally {
                input = null;
            }
        }
    }
}

From source file:org.apache.catalina.core.ApplicationDispatcher.java

/**
 * Include the response from another resource in the current response.
 * Any runtime exception, IOException, or ServletException thrown by the
 * called servlet will be propogated to the caller.
 *
 * @param request The servlet request that is including this one
 * @param response The servlet response to be appended to
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet exception occurs
 *//*from ww w.j  a  v  a 2 s  . c  o  m*/
public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    if (System.getSecurityManager() != null) {
        try {
            PrivilegedInclude dp = new PrivilegedInclude(request, response);
            AccessController.doPrivileged(dp);
        } catch (PrivilegedActionException pe) {
            Exception e = pe.getException();

            if (e instanceof ServletException)
                throw (ServletException) e;
            throw (IOException) e;
        }
    } else {
        doInclude(request, response);
    }
}

From source file:org.apache.openjpa.lib.util.Options.java

/**
 * Converts the given string into an object of the given type, or its
 * wrapper type if it is primitive.//  w ww .j ava2 s . co  m
 */
private Object stringToObject(String str, Class<?> type) throws Exception {
    // special case for null and for strings
    if (str == null || type == String.class)
        return str;

    // special case for creating Class instances
    if (type == Class.class)
        return Class.forName(str, false, getClass().getClassLoader());

    // special case for numeric types that end in .0; strip the decimal
    // places because it can kill int, short, long parsing
    if (type.isPrimitive() || Number.class.isAssignableFrom(type))
        if (str.length() > 2 && str.endsWith(".0"))
            str = str.substring(0, str.length() - 2);

    // for primitives, recurse on wrapper type
    if (type.isPrimitive())
        for (int i = 0; i < _primWrappers.length; i++)
            if (type == _primWrappers[i][0])
                return stringToObject(str, (Class<?>) _primWrappers[i][1]);

    // look for a string constructor
    Exception err = null;
    try {
        Constructor<?> cons = type.getConstructor(new Class[] { String.class });
        if (type == Boolean.class && "t".equalsIgnoreCase(str))
            str = "true";
        return cons.newInstance(new Object[] { str });
    } catch (Exception e) {
        err = new ParseException(_loc.get("conf-no-constructor", str, type), e);
    }

    // special case: the argument value is a subtype name and a new instance
    // of that type should be set as the object
    Class<?> subType = null;
    try {
        subType = Class.forName(str);
    } catch (Exception e) {
        err = e;
        throw new ParseException(_loc.get("conf-no-type", str, type), e);
    }
    if (!type.isAssignableFrom(subType))
        throw err;
    try {
        return AccessController.doPrivileged(J2DoPrivHelper.newInstanceAction(subType));
    } catch (PrivilegedActionException pae) {
        throw pae.getException();
    }
}

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

/**
 * Execute the given script of the given language.
 *
 * @param lang     language identifier/*from w w  w.  j a v  a2s . c  om*/
 * @param source   (context info) the source of this expression
 (e.g., filename)
 * @param lineNo   (context info) the line number in source for expr
 * @param columnNo (context info) the column number in source for expr
 * @param script   the script to execute
 *
 * @exception BSFException if anything goes wrong while running the script
 */
public void exec(String lang, String source, int lineNo, int columnNo, Object script) throws BSFException {
    logger.debug("BSFManager:exec");

    final BSFEngine e = loadScriptingEngine(lang);
    final String sourcef = source;
    final int lineNof = lineNo, columnNof = columnNo;
    final Object scriptf = script;

    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws Exception {
                e.exec(sourcef, lineNof, columnNof, scriptf);
                return null;
            }
        });
    } catch (PrivilegedActionException prive) {

        logger.error("Exception :", prive);
        throw (BSFException) prive.getException();
    }
}

From source file:kieker.tools.bridge.cli.CLIServerMain.java

/**
 * Read the CLI server Kieker classes to id mapping file.
 *
 * @param libraries//from   w  ww.  j av a  2 s  .c  om
 *            array representing a list of library files (*.jar)
 * @param filename
 *            the path of the mapping file.
 *
 * @return a complete IMonitoringRecord to id mapping
 * @throws IOException
 *             If one or more of the given library URLs is somehow invalid or one of the given files could not be accessed.
 */
@SuppressWarnings("unchecked")
private static ConcurrentMap<Integer, Class<? extends IMonitoringRecord>> readMapping(final String[] libraries,
        final String filename) throws IOException {
    final ConcurrentMap<Integer, Class<? extends IMonitoringRecord>> map = new ConcurrentHashMap<Integer, Class<? extends IMonitoringRecord>>();
    final URL[] urls = new URL[libraries.length];
    for (int i = 0; i < libraries.length; i++) {
        urls[i] = new File(libraries[i]).toURI().toURL();
    }

    final PrivilegedClassLoaderAction action = new PrivilegedClassLoaderAction(urls);
    classLoader = AccessController.doPrivileged(action);

    BufferedReader in = null;
    try {
        in = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "UTF-8"));
        String line = null;
        do {
            try {
                line = in.readLine();
                if (line != null) {
                    final String[] pair = line.split("=");
                    if (pair.length == 2) {
                        // loadClass returns objects of type Class<?> while we only accept Class<? extends IMonitoringRecord> at the moment. This causes an
                        // warning which
                        // is suppressed by the SuppressWarning annotation.
                        map.put(Integer.parseInt(pair[0]),
                                (Class<IMonitoringRecord>) classLoader.loadClass(pair[1]));
                    }
                }
            } catch (final ClassNotFoundException e) {
                CLIServerMain.getLog().warn("Could not load class", e);
            }
        } while (line != null);
    } finally {
        if (in != null) {
            in.close();
        }
    }

    return map;
}