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

ClassLoader getContextClassLoader() {
    return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            ClassLoader cl = null;
            try {
                cl = Thread.currentThread().getContextClassLoader();
            } catch (SecurityException ex) {
            }//from ww  w.j  a  va  2 s.c o m
            return cl;
        }
    });
}

From source file:com.googlecode.jsonschema2pojo.ant.Jsonschema2PojoTask.java

/**
 * Build a classloader using the additional elements specified in
 * <code>classpath</code> and <code>classpathRef</code>.
 * //from w ww .j  av a  2s  .c  o  m
 * @return a new classloader that includes the extra path elements found in
 *         the <code>classpath</code> and <code>classpathRef</code> config
 *         values
 */
private ClassLoader buildExtendedClassloader() {
    final List<URL> classpathUrls = new ArrayList<URL>();
    for (String pathElement : getClasspath().list()) {
        try {
            classpathUrls.add(new File(pathElement).toURI().toURL());
        } catch (MalformedURLException e) {
            throw new BuildException(
                    "Unable to use classpath entry as it could not be understood as a valid URL: "
                            + pathElement,
                    e);
        }
    }

    final ClassLoader parentClassloader = Thread.currentThread().getContextClassLoader();

    return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
        @Override
        public ClassLoader run() {
            return new URLClassLoader(classpathUrls.toArray(new URL[classpathUrls.size()]), parentClassloader);
        }
    });
}

From source file:org.apache.axiom.attachments.lifecycle.impl.LifecycleManagerImpl.java

private VMShutdownHook RegisterVMShutdownHook() throws RuntimeException {
    if (log.isDebugEnabled()) {
        log.debug("Start RegisterVMShutdownHook()");
    }/* w w w  .j  ava2  s  . c o  m*/
    try {
        hook = (VMShutdownHook) AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws SecurityException, IllegalStateException, IllegalArgumentException {
                VMShutdownHook hook = VMShutdownHook.hook();
                if (!hook.isRegistered()) {
                    Runtime.getRuntime().addShutdownHook(hook);
                    hook.setRegistered(true);
                }
                return hook;
            }
        });
    } catch (PrivilegedActionException e) {
        if (log.isDebugEnabled()) {
            log.debug("Exception thrown from AccessController: " + e);
            log.debug("VM Shutdown Hook not registered.");
        }
        throw new RuntimeException(e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Exit RegisterVMShutdownHook()");
    }
    return hook;
}

From source file:org.eclipse.gemini.blueprint.extender.internal.blueprint.event.EventAdminDispatcher.java

public void afterRefresh(final BlueprintEvent event) {
    if (dispatcher != null) {
        try {//from w  w w. ja v  a 2 s.c  o m
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged(new PrivilegedAction<Object>() {
                    public Object run() {
                        dispatcher.afterRefresh(event);
                        return null;
                    }
                });
            } else {
                dispatcher.afterRefresh(event);
            }
        } catch (Throwable th) {
            log.warn("Cannot dispatch event " + event, th);
        }
    }
}

From source file:Main.java

/**
 * Writes a DOM document to a stream. The precise output format is not
 * guaranteed but this method will attempt to indent it sensibly.
 *
 * <p class="nonnormative"><b>Important</b>: There might be some problems
 * with <code>&lt;![CDATA[ ]]&gt;</code> sections in the DOM tree you pass
 * into this method. Specifically, some CDATA sections my not be written as
 * CDATA section or may be merged with other CDATA section at the same
 * level. Also if plain text nodes are mixed with CDATA sections at the same
 * level all text is likely to end up in one big CDATA section.
 * <br>/*from w  w  w .  j  av a 2s . c om*/
 * For nodes that only have one CDATA section this method should work fine.
 * </p>
 *
 * @param doc DOM document to be written
 * @param out data sink
 * @param enc XML-defined encoding name (for example, "UTF-8")
 * @throws IOException if JAXP fails or the stream cannot be written to
 */
public static void write(Document doc, OutputStream out, String enc) throws IOException {
    if (enc == null) {
        throw new NullPointerException(
                "You must set an encoding; use \"UTF-8\" unless you have a good reason not to!"); // NOI18N
    }
    Document doc2 = normalize(doc);
    ClassLoader orig = Thread.currentThread().getContextClassLoader();
    Thread.currentThread()
            .setContextClassLoader(AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { // #195921
                @Override
                public ClassLoader run() {
                    return new ClassLoader(ClassLoader.getSystemClassLoader().getParent()) {
                        @Override
                        public InputStream getResourceAsStream(String name) {
                            if (name.startsWith("META-INF/services/")) {
                                return new ByteArrayInputStream(new byte[0]); // JAXP #6723276
                            }
                            return super.getResourceAsStream(name);
                        }
                    };
                }
            }));
    try {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer(new StreamSource(new StringReader(IDENTITY_XSLT_WITH_INDENT)));
        DocumentType dt = doc2.getDoctype();
        if (dt != null) {
            String pub = dt.getPublicId();
            if (pub != null) {
                t.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, pub);
            }
            String sys = dt.getSystemId();
            if (sys != null) {
                t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, sys);
            }
        }
        t.setOutputProperty(OutputKeys.ENCODING, enc);
        try {
            t.setOutputProperty(ORACLE_IS_STANDALONE, "yes");
        } catch (IllegalArgumentException x) {
            // fine, introduced in JDK 7u4
        }

        // See #123816
        Set<String> cdataQNames = new HashSet<String>();
        collectCDATASections(doc2, cdataQNames);
        if (cdataQNames.size() > 0) {
            StringBuilder cdataSections = new StringBuilder();
            for (String s : cdataQNames) {
                cdataSections.append(s).append(' '); //NOI18N
            }
            t.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, cdataSections.toString());
        }

        Source source = new DOMSource(doc2);
        Result result = new StreamResult(out);
        t.transform(source, result);
    } catch (javax.xml.transform.TransformerException | RuntimeException e) { // catch anything that happens
        throw new IOException(e);
    } finally {
        Thread.currentThread().setContextClassLoader(orig);
    }
}

From source file:com.netspective.commons.io.UriAddressableUniqueFileLocator.java

public UriAddressableFile findUriAddressableFile(final String name) throws IOException {
    final boolean logging = log.isDebugEnabled();
    if (logging)/*w w w .  j  a  v  a  2 s . c om*/
        log.debug("SingleUriAddressableFileLocator searching for " + name);

    if (cacheLocations) {
        UriAddressableFile resource = (UriAddressableFile) cache.get(name);
        if (resource != null) {
            if (logging)
                log.debug("SingleUriAddressableFileLocator cache hit for " + resource);
            return resource;
        }
    }

    try {
        return (UriAddressableFile) AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws IOException {
                File source = new File(baseDir, SEP_IS_SLASH ? name : name.replace(File.separatorChar, '/'));
                // Security check for inadvertently returning something outside the
                // resource directory.
                String normalized = source.getCanonicalPath();
                if (!normalized.startsWith(canonicalPath)) {
                    throw new SecurityException();
                }

                if (logging)
                    log.debug("SingleUriAddressableFileLocator looking for '" + name + "' as " + source);
                UriAddressableFile result = source.exists() ? new UriAddressableFile(rootUrl, name, source)
                        : null;
                if (result != null) {
                    if (logging)
                        log.debug("SingleUriAddressableFileLocator found " + result);
                    if (cacheLocations)
                        cache.put(name, result);
                }
                return result;
            }
        });
    } catch (PrivilegedActionException e) {
        throw (IOException) e.getException();
    }
}

From source file:org.beangle.model.persist.hibernate.internal.ChainedClassLoader.java

/**
 * Adds a class loader defining the given class, to the chained class loader
 * space./*w  w w .  ja  v  a  2 s. c o m*/
 * 
 * @param clazz
 */
public void addClassLoader(final Class<?> clazz) {
    Validate.notNull(clazz, "a non-null class required");
    if (System.getSecurityManager() != null) {
        addClassLoader(AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
            public ClassLoader run() {
                return ClassUtils.getClassLoader(clazz);
            }
        }));
    } else {
        addClassLoader(ClassUtils.getClassLoader(clazz));
    }
}

From source file:com.reelfx.controller.WindowsController.java

public void startRecording(AudioRecorder selectedAudio) {
    audioSource = selectedAudio;/*ww w . j  a  v a 2 s .c o  m*/
    listener = this;

    recordingDone = false;

    AccessController.doPrivileged(new PrivilegedAction<Object>() {

        @Override
        public Object run() {

            deleteOutput();
            AudioRecorder.deleteOutput();
            stopped = false;
            if (audioSource != null) {
                mic = audioSource;
                mic.addProcessListener(listener);
                mic.startRecording();

                /*
                Mixer systemMixer = null;
                for(Mixer.Info info : AudioSystem.getMixerInfo())
                   // select the "stereo mix" on Windows
                    if(!info.getName().toLowerCase().contains("port")
                   && info.getName().toLowerCase().contains("stereo mix")
                   && AudioSystem.getMixer(info).getTargetLineInfo().length != 0)
                systemMixer = AudioSystem.getMixer(info);
                        
                if(systemMixer != null) {
                   systemAudio = new AudioRecorder(systemMixer);
                   //systemAudio.addProcessListener(listener);
                   systemAudio.startRecording();
                }
                */
            } else {
                logger.info("No audio source specified.");
                mic = null;
                systemAudio = null;
            }
            // start up ffmpeg
            screen.start();

            return null;
        }
    });
}

From source file:jenkins.scm.api.SCMHeadMixinEqualityGenerator.java

/**
 * Get the {@link SCMHeadMixin.Equality} instance to use.
 *
 * @param type the {@link SCMHead} type.
 * @return the {@link SCMHeadMixin.Equality} instance.
 *//* w ww .ja  v  a2s .  com*/
@NonNull
static SCMHeadMixin.Equality getOrCreate(@NonNull Class<? extends SCMHead> type) {
    lock.readLock().lock();
    try {
        SCMHeadMixin.Equality result = mixinEqualities.get(type);
        if (result != null) {
            return result;
        }
    } finally {
        lock.readLock().unlock();
    }
    lock.writeLock().lock();
    try {
        SCMHeadMixin.Equality result = mixinEqualities.get(type);
        if (result != null) {
            // somebody else created it while we were waiting for the write lock
            return result;
        }
        final ClassLoader loader = type.getClassLoader();
        SCMHeadMixinEqualityGenerator generator;
        generator = generators.get(loader);
        if (generator == null) {
            generator = AccessController.doPrivileged(new PrivilegedAction<SCMHeadMixinEqualityGenerator>() {
                @Override
                public SCMHeadMixinEqualityGenerator run() {
                    return new SCMHeadMixinEqualityGenerator(loader);
                }
            });
            generators.put(loader, generator);
        }
        result = generator.create(type);
        mixinEqualities.put(type, result);
        return result;
    } finally {
        lock.writeLock().unlock();
    }
}

From source file:tools.xor.util.ClassUtil.java

/** 
 * Invoke the given method as a privileged action, if necessary. 
 * @param target the object on which the method needs to be invoked
 * @param field we are reading or writing
 * @param value to set in the field//from   ww  w . j a va2 s.c  om
 * @param read true if this a read operation
 * @return result of the invocation
 * @throws InvocationTargetException while invoking the method
 * @throws IllegalAccessException when accessing the meta data
 */
public static Object invokeFieldAsPrivileged(final Object target, final Field field, final Object value,
        final boolean read) throws InvocationTargetException, IllegalAccessException {

    if (Modifier.isPublic(field.getModifiers())) {
        Object readValue = null;
        if (read)
            readValue = field.get(target);
        else
            field.set(target, value);
        return readValue;
    } else {
        return AccessController.doPrivileged(new PrivilegedAction<Object>() {
            public Object run() {
                field.setAccessible(true);
                Object readValue = null;
                try {
                    if (read)
                        readValue = field.get(target);
                    else
                        field.set(target, value);
                } catch (Exception e) {
                    throw wrapRun(e);
                }
                return readValue;
            }
        });
    }
}