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:SecuritySupport.java

String getSystemProperty(final String propName) {
    return (String) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return System.getProperty(propName);
        }/*from   w ww .j  a v a 2  s .  c o m*/
    });
}

From source file:org.apache.sandesha2.workers.SandeshaThread.java

/**
 * Ensure that the worker thread is aware of the given sequence. As source sequences
 * do not have a proper sequence id at the time they are bootstrapped, the caller
 * must pass in the internal sequence id when rmSource is true.
 *//* w  w  w.j a v  a  2 s . co m*/
public synchronized void runThreadForSequence(ConfigurationContext context, String sequenceID,
        boolean rmSource) {
    if (log.isDebugEnabled())
        log.debug("Entry: SandeshaThread::runThreadForSequence, " + this + ", " + sequenceID + ", " + rmSource);

    SequenceEntry entry = new SequenceEntry(sequenceID, rmSource);
    if (!workingSequences.contains(entry))
        workingSequences.add(entry);

    if (!isThreadStarted() && !stopRequested) {
        if (log.isDebugEnabled())
            log.debug("Starting thread");

        this.context = context;

        // Get the axis2 thread pool
        threadPool = context.getThreadPool();

        runThread = true; // so that isStarted()=true.

        super.start();

        // Set the SandeshaThread to have the same context classloader as the application
        try {
            AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                public Object run() throws Exception {
                    SandeshaThread.this.setContextClassLoader(Thread.currentThread().getContextClassLoader());
                    return null;
                }
            });
        } catch (Exception e) {
            log.error(e);
            throw new RuntimeException(e);
        }

    } else if (!stopRequested) {
        if (log.isDebugEnabled())
            log.debug("Waking thread");
        wakeThread();
    } else if (stopRequested) {
        if (log.isDebugEnabled())
            log.debug("Can't start thread as it has been stopped");
    }

    if (log.isDebugEnabled())
        log.debug("Exit: SandeshaThread::runThreadForSequence");
}

From source file:org.eclipse.gemini.blueprint.extender.internal.support.NamespacePlugins.java

public InputSource resolveEntity(final String publicId, final String systemId)
        throws SAXException, IOException {
    if (System.getSecurityManager() != null) {
        try {/*w  w w .ja  va 2s.  c o m*/
            return AccessController.doPrivileged(new PrivilegedExceptionAction<InputSource>() {

                public InputSource run() throws Exception {
                    return doResolveEntity(publicId, systemId);
                }
            });
        } catch (PrivilegedActionException pae) {
            Exception cause = pae.getException();
            handleInputSourceException(cause);
        }
    } else {
        try {
            return doResolveEntity(publicId, systemId);
        } catch (Exception ex) {
            handleInputSourceException(ex);
        }
    }

    return null;
}

From source file:org.eclipse.gemini.blueprint.io.internal.resolver.PackageAdminResolver.java

private PackageAdmin getPackageAdmin() {

    return AccessController.doPrivileged(new PrivilegedAction<PackageAdmin>() {

        public PackageAdmin run() {
            ServiceReference ref = bundleContext.getServiceReference(PackageAdmin.class.getName());
            if (ref == null)
                throw new IllegalStateException(PackageAdmin.class.getName() + " service is required");
            // don't do any proxying since PackageAdmin is normally a framework service
            // we can assume for now that it will always be available
            return (PackageAdmin) bundleContext.getService(ref);
        }/*  w  ww  .jav a 2s.c om*/
    });
}

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

/**
 * Convenience method to return the given method / arg.
 *//*  w  w  w  .ja  va2 s  . co  m*/
private static Method getMethodSafe(Class<?> iface, String name, Class<?> arg) {
    try {
        return AccessController.doPrivileged(
                J2DoPrivHelper.getDeclaredMethodAction(iface, name, arg == null ? null : new Class[] { arg }));
    } catch (PrivilegedActionException pae) {
        throw new InternalException(_loc.get("interface-mismatch", name));
    }
}

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

/**
 * Invokes <code>cls.getDeclaredMethods()</code>, and returns the method
 * that matches the <code>name</code> and <code>param</code> arguments.
 * Avoids the exception thrown by <code>Class.getDeclaredMethod()</code>
 * for performance reasons. <code>param</code> may be null. Additionally,
 * if there are multiple methods with different return types, this will
 * return the method defined in the least-derived class.
 *
 * @since 0.9.8/*from  w w  w . ja va2s.  c  om*/
 */
static Method getDeclaredMethod(Class cls, String name, Class param) {
    Method[] methods = (Method[]) AccessController.doPrivileged(J2DoPrivHelper.getDeclaredMethodsAction(cls));
    Method candidate = null;
    for (int i = 0; i < methods.length; i++) {
        if (name.equals(methods[i].getName())) {
            Class[] methodParams = methods[i].getParameterTypes();
            if (param == null && methodParams.length == 0)
                candidate = mostDerived(methods[i], candidate);
            else if (param != null && methodParams.length == 1 && param.equals(methodParams[0]))
                candidate = mostDerived(methods[i], candidate);
        }
    }
    return candidate;
}

From source file:org.nebulaframework.deployment.classloading.GridNodeClassLoader.java

/**
  * Attempts to find the class definition for the given class name, by first
  * searching the local cache, and then through the remote
  * {@link ClassLoadingService}.// w  w w .j  a  va 2s  .c  om
  *
  * @param name
  *            binary name of the class
  *
  * @return The {@code Class<?>} object for requested class, if found
  *
  * @throws ClassNotFoundException
  *             if unable to find the class
  */
@Override
protected Class<?> findClass(final String name) throws ClassNotFoundException {

    log.debug("[GridNodeClassLoader] Finding Class : " + name);

    Class<?> cls = null;
    // Attempt remote load
    try {
        log.debug("[GridNodeClassLoader] Attempt Remote Loading : " + name);

        // Get bytes for class from remote service
        byte[] bytes = AccessController.doPrivileged(new PrivilegedExceptionAction<byte[]>() {

            @Override
            public byte[] run() throws ClassNotFoundException {

                // If we don't know owner
                if (ownerId == null) {
                    return classLoadingService.findClass(jobId, name);
                } else { // If we know owner
                    return classLoadingService.findClass(ownerId, name);
                }
            }

        });

        cls = defineClass(name, bytes, 0, bytes.length, REMOTE_CODESOURCE);
        log.debug("[GridNodeClassLoader] Remote Loaded : " + name);

        return cls;

    } catch (Exception ex) {
        log.warn("[GridNodeClassLoader] Exception while Remote Loading ", ex);
        throw new ClassNotFoundException("Class not found due to Exception", ex);
    }
}

From source file:org.elasticsearch.xpack.qa.sql.security.SqlSecurityTestCase.java

@Before
public void setInitialAuditLogOffset() {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new SpecialPermission());
    }// www  .  java2  s.com
    AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
        if (false == Files.exists(AUDIT_LOG_FILE)) {
            auditLogWrittenBeforeTestStart = 0;
            return null;
        }
        if (false == Files.isRegularFile(AUDIT_LOG_FILE)) {
            throw new IllegalStateException(
                    "expected tests.audit.logfile [" + AUDIT_LOG_FILE + "]to be a plain file but wasn't");
        }
        try {
            auditLogWrittenBeforeTestStart = Files.size(AUDIT_LOG_FILE);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    });
}

From source file:com.fitbur.testify.junit.system.internal.SpringBootInterceptor.java

public EmbeddedServletContainerFactory getEmbeddedServletContainerFactory(
        @SuperCall Callable<EmbeddedServletContainerFactory> zuper, @This Object object) throws Exception {
    EmbeddedServletContainerFactory containerFactory = zuper.call();
    ConfigurableEmbeddedServletContainer configurableServletContainer = (ConfigurableEmbeddedServletContainer) containerFactory;
    configurableServletContainer.setPort(0);

    SpringBootDescriptor descriptor = getDescriptor(object);
    descriptor.setContainerFactory(containerFactory);
    descriptor.setConfigurableServletContainer(configurableServletContainer);
    TestContext testContext = descriptor.getTestContext();

    testContext.getConfigMethod(ConfigurableEmbeddedServletContainer.class).map(m -> m.getMethod())
            .ifPresent(m -> {/*from  w w  w  . ja  v a2 s.co m*/
                AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                    try {
                        m.setAccessible(true);
                        m.invoke(testContext.getTestInstance(), configurableServletContainer);
                    } catch (Exception e) {
                        checkState(false, "Call to config method '%s' in test class '%s' failed.", m.getName(),
                                testContext.getTestClassName());
                        throw Throwables.propagate(e);
                    }

                    return null;
                });
            });

    return containerFactory;
}

From source file:SecuritySupport.java

FileInputStream getFileInputStream(final File file) throws FileNotFoundException {
    try {//from w w  w .j a va2 s . c o  m
        return (FileInputStream) AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws FileNotFoundException {
                return new FileInputStream(file);
            }
        });
    } catch (PrivilegedActionException e) {
        throw (FileNotFoundException) e.getException();
    }
}