java.security.AccessController#getContext ( )源码实例Demo

下面列出了java.security.AccessController#getContext ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: dragonwell8_jdk   文件: SimpleStandard.java
/**
 * Check that the principal contained in the Subject is of
 * type JMXPrincipal and refers to the principalName identity.
 */
private void checkSubject(String op) {
    AccessControlContext acc = AccessController.getContext();
    Subject subject = Subject.getSubject(acc);
    Set principals = subject.getPrincipals();
    Principal principal = (Principal) principals.iterator().next();
    if (!(principal instanceof JMXPrincipal))
        throw new SecurityException(op+": Authenticated subject contains " +
                                    "invalid principal type = " +
                                    principal.getClass().getName());
    String identity = principal.getName();
    if (!identity.equals(principalName))
        throw new SecurityException(op+": Authenticated subject contains " +
                                    "invalid principal name = " + identity);
}
 
源代码2 项目: TencentKona-8   文件: SimpleStandard.java
/**
 * Check that the principal contained in the Subject is of
 * type JMXPrincipal and refers to the principalName identity.
 */
private void checkSubject(String op) {
    AccessControlContext acc = AccessController.getContext();
    Subject subject = Subject.getSubject(acc);
    Set principals = subject.getPrincipals();
    Principal principal = (Principal) principals.iterator().next();
    if (!(principal instanceof JMXPrincipal))
        throw new SecurityException(op+": Authenticated subject contains " +
                                    "invalid principal type = " +
                                    principal.getClass().getName());
    String identity = principal.getName();
    if (!identity.equals(principalName))
        throw new SecurityException(op+": Authenticated subject contains " +
                                    "invalid principal name = " + identity);
}
 
源代码3 项目: openjdk-jdk8u   文件: URLClassLoader.java
/**
 * Creates a new instance of URLClassLoader for the specified
 * URLs and parent class loader. If a security manager is
 * installed, the {@code loadClass} method of the URLClassLoader
 * returned by this method will invoke the
 * {@code SecurityManager.checkPackageAccess} method before
 * loading the class.
 *
 * @param urls the URLs to search for classes and resources
 * @param parent the parent class loader for delegation
 * @exception  NullPointerException if {@code urls} is {@code null}.
 * @return the resulting class loader
 */
public static URLClassLoader newInstance(final URL[] urls,
                                         final ClassLoader parent) {
    // Save the caller's context
    final AccessControlContext acc = AccessController.getContext();
    // Need a privileged block to create the class loader
    URLClassLoader ucl = AccessController.doPrivileged(
        new PrivilegedAction<URLClassLoader>() {
            public URLClassLoader run() {
                return new FactoryURLClassLoader(urls, parent, acc);
            }
        });
    return ucl;
}
 
源代码4 项目: openjdk-jdk8u   文件: SimpleStandard.java
/**
 * Check that the principal contained in the Subject is of
 * type JMXPrincipal and refers to the principalName identity.
 */
private void checkSubject(String op) {
    AccessControlContext acc = AccessController.getContext();
    Subject subject = Subject.getSubject(acc);
    Set principals = subject.getPrincipals();
    Principal principal = (Principal) principals.iterator().next();
    if (!(principal instanceof JMXPrincipal))
        throw new SecurityException(op+": Authenticated subject contains " +
                                    "invalid principal type = " +
                                    principal.getClass().getName());
    String identity = principal.getName();
    if (!identity.equals(principalName))
        throw new SecurityException(op+": Authenticated subject contains " +
                                    "invalid principal name = " + identity);
}
 
源代码5 项目: dragonwell8_jdk   文件: MenuComponent.java
/**
 * Reads the menu component from an object input stream.
 *
 * @param s the <code>ObjectInputStream</code> to read
 * @exception HeadlessException if
 *   <code>GraphicsEnvironment.isHeadless</code> returns
 *   <code>true</code>
 * @serial
 * @see java.awt.GraphicsEnvironment#isHeadless
 */
private void readObject(ObjectInputStream s)
    throws ClassNotFoundException, IOException, HeadlessException
{
    GraphicsEnvironment.checkHeadless();

    acc = AccessController.getContext();

    s.defaultReadObject();

    appContext = AppContext.getAppContext();
}
 
源代码6 项目: JDKSourceCode1.8   文件: EventQueue.java
/**
 * Dispatches an event. The manner in which the event is
 * dispatched depends upon the type of the event and the
 * type of the event's source object:
 *
 * <table border=1 summary="Event types, source types, and dispatch methods">
 * <tr>
 *     <th>Event Type</th>
 *     <th>Source Type</th>
 *     <th>Dispatched To</th>
 * </tr>
 * <tr>
 *     <td>ActiveEvent</td>
 *     <td>Any</td>
 *     <td>event.dispatch()</td>
 * </tr>
 * <tr>
 *     <td>Other</td>
 *     <td>Component</td>
 *     <td>source.dispatchEvent(AWTEvent)</td>
 * </tr>
 * <tr>
 *     <td>Other</td>
 *     <td>MenuComponent</td>
 *     <td>source.dispatchEvent(AWTEvent)</td>
 * </tr>
 * <tr>
 *     <td>Other</td>
 *     <td>Other</td>
 *     <td>No action (ignored)</td>
 * </tr>
 * </table>
 * <p>
 * @param event an instance of <code>java.awt.AWTEvent</code>,
 *          or a subclass of it
 * @throws NullPointerException if <code>event</code> is <code>null</code>
 * @since           1.2
 */
protected void dispatchEvent(final AWTEvent event) {
    final Object src = event.getSource();
    final PrivilegedAction<Void> action = new PrivilegedAction<Void>() {
        public Void run() {
            // In case fwDispatcher is installed and we're already on the
            // dispatch thread (e.g. performing DefaultKeyboardFocusManager.sendMessage),
            // dispatch the event straight away.
            if (fwDispatcher == null || isDispatchThreadImpl()) {
                dispatchEventImpl(event, src);
            } else {
                fwDispatcher.scheduleDispatch(new Runnable() {
                    @Override
                    public void run() {
                        if (dispatchThread.filterAndCheckEvent(event)) {
                            dispatchEventImpl(event, src);
                        }
                    }
                });
            }
            return null;
        }
    };

    final AccessControlContext stack = AccessController.getContext();
    final AccessControlContext srcAcc = getAccessControlContextFrom(src);
    final AccessControlContext eventAcc = event.getAccessControlContext();
    if (srcAcc == null) {
        javaSecurityAccess.doIntersectionPrivilege(action, stack, eventAcc);
    } else {
        javaSecurityAccess.doIntersectionPrivilege(
            new PrivilegedAction<Void>() {
                public Void run() {
                    javaSecurityAccess.doIntersectionPrivilege(action, eventAcc);
                    return null;
                }
            }, stack, srcAcc);
    }
}
 
源代码7 项目: JDKSourceCode1.8   文件: RequiredModelMBean.java
private Class<?> loadClass(final String className)
    throws ClassNotFoundException {
    AccessControlContext stack = AccessController.getContext();
    final ClassNotFoundException[] caughtException = new ClassNotFoundException[1];

    Class c = javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<Class<?>>() {

        @Override
        public Class<?> run() {
            try {
                ReflectUtil.checkPackageAccess(className);
                return Class.forName(className);
            } catch (ClassNotFoundException e) {
                final ClassLoaderRepository clr =
                    getClassLoaderRepository();
                try {
                    if (clr == null) throw new ClassNotFoundException(className);
                    return clr.loadClass(className);
                } catch (ClassNotFoundException ex) {
                    caughtException[0] = ex;
                }
            }
            return null;
        }
    }, stack, acc);

    if (caughtException[0] != null) {
        throw caughtException[0];
    }

    return c;
}
 
源代码8 项目: dragonwell8_jdk   文件: PlatformRecording.java
PlatformRecording(PlatformRecorder recorder, long id) {
    // Typically the access control context is taken
    // when you call dump(Path) or setDdestination(Path),
    // but if no destination is set and dumponexit=true
    // the control context of the recording is taken when the
    // Recording object is constructed.  This works well for
    // -XX:StartFlightRecording and JFR.dump
    this.noDestinationDumpOnExitAccessControlContext = AccessController.getContext();
    this.id = id;
    this.recorder = recorder;
    this.name = String.valueOf(id);
}
 
源代码9 项目: TencentKona-8   文件: ServerNotifForwarder.java
static void checkMBeanPermission(
        final MBeanServer mbs, final ObjectName name, final String actions)
        throws InstanceNotFoundException, SecurityException {

    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        AccessControlContext acc = AccessController.getContext();
        ObjectInstance oi;
        try {
            oi = AccessController.doPrivileged(
                new PrivilegedExceptionAction<ObjectInstance>() {
                    public ObjectInstance run()
                    throws InstanceNotFoundException {
                        return mbs.getObjectInstance(name);
                    }
            });
        } catch (PrivilegedActionException e) {
            throw (InstanceNotFoundException) extractException(e);
        }
        String classname = oi.getClassName();
        MBeanPermission perm = new MBeanPermission(
            classname,
            null,
            name,
            actions);
        sm.checkPermission(perm, acc);
    }
}
 
源代码10 项目: dragonwell8_jdk   文件: Krb5InitCredential.java
private static KerberosTicket getTgt(GSSCaller caller, Krb5NameElement name,
                                             int initLifetime)
    throws GSSException {

    final String clientPrincipal;

    /*
     * Find the TGT for the realm that the client is in. If the client
     * name is not available, then use the default realm.
     */
    if (name != null) {
        clientPrincipal = (name.getKrb5PrincipalName()).getName();
    } else {
        clientPrincipal = null;
    }

    final AccessControlContext acc = AccessController.getContext();

    try {
        final GSSCaller realCaller = (caller == GSSCaller.CALLER_UNKNOWN)
                               ? GSSCaller.CALLER_INITIATE
                               : caller;
        return AccessController.doPrivileged(
            new PrivilegedExceptionAction<KerberosTicket>() {
            public KerberosTicket run() throws Exception {
                // It's OK to use null as serverPrincipal. TGT is almost
                // the first ticket for a principal and we use list.
                return Krb5Util.getInitialTicket(
                    realCaller,
                    clientPrincipal, acc);
                    }});
    } catch (PrivilegedActionException e) {
        GSSException ge =
            new GSSException(GSSException.NO_CRED, -1,
                "Attempt to obtain new INITIATE credentials failed!" +
                " (" + e.getMessage() + ")");
        ge.initCause(e.getException());
        throw ge;
    }
}
 
源代码11 项目: JDKSourceCode1.8   文件: ServerNotifForwarder.java
static void checkMBeanPermission(
        final MBeanServer mbs, final ObjectName name, final String actions)
        throws InstanceNotFoundException, SecurityException {

    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        AccessControlContext acc = AccessController.getContext();
        ObjectInstance oi;
        try {
            oi = AccessController.doPrivileged(
                new PrivilegedExceptionAction<ObjectInstance>() {
                    public ObjectInstance run()
                    throws InstanceNotFoundException {
                        return mbs.getObjectInstance(name);
                    }
            });
        } catch (PrivilegedActionException e) {
            throw (InstanceNotFoundException) extractException(e);
        }
        String classname = oi.getClassName();
        MBeanPermission perm = new MBeanPermission(
            classname,
            null,
            name,
            actions);
        sm.checkPermission(perm, acc);
    }
}
 
源代码12 项目: jdk1.8-source-analysis   文件: RepaintManager.java
private void paintDirtyRegions(
    final Map<Component,Rectangle> tmpDirtyComponents)
{
    if (tmpDirtyComponents.isEmpty()) {
        return;
    }

    final java.util.List<Component> roots =
        new ArrayList<Component>(tmpDirtyComponents.size());
    for (Component dirty : tmpDirtyComponents.keySet()) {
        collectDirtyComponents(tmpDirtyComponents, dirty, roots);
    }

    final AtomicInteger count = new AtomicInteger(roots.size());
    painting = true;
    try {
        for (int j=0 ; j < count.get(); j++) {
            final int i = j;
            final Component dirtyComponent = roots.get(j);
            AccessControlContext stack = AccessController.getContext();
            AccessControlContext acc =
                AWTAccessor.getComponentAccessor().getAccessControlContext(dirtyComponent);
            javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<Void>() {
                public Void run() {
                    Rectangle rect = tmpDirtyComponents.get(dirtyComponent);
                    // Sometimes when RepaintManager is changed during the painting
                    // we may get null here, see #6995769 for details
                    if (rect == null) {
                        return null;
                    }

                    int localBoundsH = dirtyComponent.getHeight();
                    int localBoundsW = dirtyComponent.getWidth();
                    SwingUtilities.computeIntersection(0,
                                                       0,
                                                       localBoundsW,
                                                       localBoundsH,
                                                       rect);
                    if (dirtyComponent instanceof JComponent) {
                        ((JComponent)dirtyComponent).paintImmediately(
                            rect.x,rect.y,rect.width, rect.height);
                    }
                    else if (dirtyComponent.isShowing()) {
                        Graphics g = JComponent.safelyGetGraphics(
                                dirtyComponent, dirtyComponent);
                        // If the Graphics goes away, it means someone disposed of
                        // the window, don't do anything.
                        if (g != null) {
                            g.setClip(rect.x, rect.y, rect.width, rect.height);
                            try {
                                dirtyComponent.paint(g);
                            } finally {
                                g.dispose();
                            }
                        }
                    }
                    // If the repaintRoot has been set, service it now and
                    // remove any components that are children of repaintRoot.
                    if (repaintRoot != null) {
                        adjustRoots(repaintRoot, roots, i + 1);
                        count.set(roots.size());
                        paintManager.isRepaintingRoot = true;
                        repaintRoot.paintImmediately(0, 0, repaintRoot.getWidth(),
                                                     repaintRoot.getHeight());
                        paintManager.isRepaintingRoot = false;
                        // Only service repaintRoot once.
                        repaintRoot = null;
                    }

                    return null;
                }
            }, stack, acc);
        }
    } finally {
        painting = false;
    }

    updateWindows(tmpDirtyComponents);

    tmpDirtyComponents.clear();
}
 
@Override
Future<AsynchronousSocketChannel> implAccept(Object attachment,
    final CompletionHandler<AsynchronousSocketChannel,Object> handler)
{
    if (!isOpen()) {
        Throwable exc = new ClosedChannelException();
        if (handler == null)
            return CompletedFuture.withFailure(exc);
        Invoker.invokeIndirectly(this, handler, attachment, null, exc);
        return null;
    }
    if (isAcceptKilled())
        throw new RuntimeException("Accept not allowed due to cancellation");

    // ensure channel is bound to local address
    if (localAddress == null)
        throw new NotYetBoundException();

    // create the socket that will be accepted. The creation of the socket
    // is enclosed by a begin/end for the listener socket to ensure that
    // we check that the listener is open and also to prevent the I/O
    // port from being closed as the new socket is registered.
    WindowsAsynchronousSocketChannelImpl ch = null;
    IOException ioe = null;
    try {
        begin();
        ch = new WindowsAsynchronousSocketChannelImpl(iocp, false);
    } catch (IOException x) {
        ioe = x;
    } finally {
        end();
    }
    if (ioe != null) {
        if (handler == null)
            return CompletedFuture.withFailure(ioe);
        Invoker.invokeIndirectly(this, handler, attachment, null, ioe);
        return null;
    }

    // need calling context when there is security manager as
    // permission check may be done in a different thread without
    // any application call frames on the stack
    AccessControlContext acc = (System.getSecurityManager() == null) ?
        null : AccessController.getContext();

    PendingFuture<AsynchronousSocketChannel,Object> result =
        new PendingFuture<AsynchronousSocketChannel,Object>(this, handler, attachment);
    AcceptTask task = new AcceptTask(ch, acc, result);
    result.setContext(task);

    // check and set flag to prevent concurrent accepting
    if (!accepting.compareAndSet(false, true))
        throw new AcceptPendingException();

    // initiate I/O
    if (Iocp.supportsThreadAgnosticIo()) {
        task.run();
    } else {
        Invoker.invokeOnThreadInThreadPool(this, task);
    }
    return result;
}
 
源代码14 项目: openjdk-jdk8u   文件: SettingControl.java
/**
 * Constructor for invocation by subclass constructors.
 */
protected SettingControl() {
    super(AccessController.getContext());

}
 
源代码15 项目: dragonwell8_jdk   文件: Subject.java
/**
 * Perform work as a particular {@code Subject}.
 *
 * <p> This method first retrieves the current Thread's
 * {@code AccessControlContext} via
 * {@code AccessController.getContext},
 * and then instantiates a new {@code AccessControlContext}
 * using the retrieved context along with a new
 * {@code SubjectDomainCombiner} (constructed using
 * the provided {@code Subject}).
 * Finally, this method invokes {@code AccessController.doPrivileged},
 * passing it the provided {@code PrivilegedAction},
 * as well as the newly constructed {@code AccessControlContext}.
 *
 * <p>
 *
 * @param subject the {@code Subject} that the specified
 *                  {@code action} will run as.  This parameter
 *                  may be {@code null}. <p>
 *
 * @param <T> the type of the value returned by the PrivilegedAction's
 *                  {@code run} method.
 *
 * @param action the code to be run as the specified
 *                  {@code Subject}. <p>
 *
 * @return the value returned by the PrivilegedAction's
 *                  {@code run} method.
 *
 * @exception NullPointerException if the {@code PrivilegedAction}
 *                  is {@code null}. <p>
 *
 * @exception SecurityException if the caller does not have permission
 *                  to invoke this method.
 */
public static <T> T doAs(final Subject subject,
                    final java.security.PrivilegedAction<T> action) {

    java.lang.SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(AuthPermissionHolder.DO_AS_PERMISSION);
    }
    if (action == null)
        throw new NullPointerException
            (ResourcesMgr.getString("invalid.null.action.provided"));

    // set up the new Subject-based AccessControlContext
    // for doPrivileged
    final AccessControlContext currentAcc = AccessController.getContext();

    // call doPrivileged and push this new context on the stack
    return java.security.AccessController.doPrivileged
                                    (action,
                                    createContext(subject, currentAcc));
}
 
private synchronized void checkAccess(AccessType requiredAccess, String arg) {
    final AccessControlContext acc = AccessController.getContext();
    final Subject s =
        AccessController.doPrivileged(new PrivilegedAction<Subject>() {
                public Subject run() {
                    return Subject.getSubject(acc);
                }
            });
    if (s == null) return; /* security has not been enabled */
    final Set principals = s.getPrincipals();
    String newPropertyValue = null;
    for (Iterator i = principals.iterator(); i.hasNext(); ) {
        final Principal p = (Principal) i.next();
        Access access = accessMap.get(p.getName());
        if (access != null) {
            boolean ok;
            switch (requiredAccess) {
                case READ:
                    ok = true;  // all access entries imply read
                    break;
                case WRITE:
                    ok = access.write;
                    break;
                case UNREGISTER:
                    ok = access.unregister;
                    if (!ok && access.write)
                        newPropertyValue = "unregister";
                    break;
                case CREATE:
                    ok = checkCreateAccess(access, arg);
                    if (!ok && access.write)
                        newPropertyValue = "create " + arg;
                    break;
                default:
                    throw new AssertionError();
            }
            if (ok)
                return;
        }
    }
    SecurityException se = new SecurityException("Access denied! Invalid " +
            "access level for requested MBeanServer operation.");
    // Add some more information to help people with deployments that
    // worked before we required explicit create clauses. We're not giving
    // any information to the bad guys, other than that the access control
    // is based on a file, which they could have worked out from the stack
    // trace anyway.
    if (newPropertyValue != null) {
        SecurityException se2 = new SecurityException("Access property " +
                "for this identity should be similar to: " + READWRITE +
                " " + newPropertyValue);
        se.initCause(se2);
    }
    throw se;
}
 
源代码17 项目: openjdk-jdk8u   文件: GSSUtil.java
/**
 * Searches the private credentials of current Subject with the
 * specified criteria and returns the matching GSSCredentialSpi
 * object out of Sun's impl of GSSCredential. Returns null if
 * no Subject present or a Vector which contains 0 or more
 * matching GSSCredentialSpi objects.
 */
public static <T extends GSSCredentialSpi> Vector<T>
        searchSubject(final GSSNameSpi name,
                      final Oid mech,
                      final boolean initiate,
                      final Class<? extends T> credCls) {
    debug("Search Subject for " + getMechStr(mech) +
          (initiate? " INIT" : " ACCEPT") + " cred (" +
          (name == null? "<<DEF>>" : name.toString()) + ", " +
          credCls.getName() + ")");
    final AccessControlContext acc = AccessController.getContext();
    try {
        Vector<T> creds =
            AccessController.doPrivileged
            (new PrivilegedExceptionAction<Vector<T>>() {
                public Vector<T> run() throws Exception {
                    Subject accSubj = Subject.getSubject(acc);
                    Vector<T> result = null;
                    if (accSubj != null) {
                        result = new Vector<T>();
                        Iterator<GSSCredentialImpl> iterator =
                            accSubj.getPrivateCredentials
                            (GSSCredentialImpl.class).iterator();
                        while (iterator.hasNext()) {
                            GSSCredentialImpl cred = iterator.next();
                            debug("...Found cred" + cred);
                            try {
                                GSSCredentialSpi ce =
                                    cred.getElement(mech, initiate);
                                debug("......Found element: " + ce);
                                if (ce.getClass().equals(credCls) &&
                                    (name == null ||
                                     name.equals((Object) ce.getName()))) {
                                    result.add(credCls.cast(ce));
                                } else {
                                    debug("......Discard element");
                                }
                            } catch (GSSException ge) {
                                debug("...Discard cred (" + ge + ")");
                            }
                        }
                    } else debug("No Subject");
                    return result;
                }
            });
        return creds;
    } catch (PrivilegedActionException pae) {
        debug("Unexpected exception when searching Subject:");
        if (DEBUG) pae.printStackTrace();
        return null;
    }
}
 
源代码18 项目: JDKSourceCode1.8   文件: RMIIIOPServerImpl.java
/**
 * <p>Creates a new {@link RMIServerImpl}.</p>
 *
 * @param env the environment containing attributes for the new
 * <code>RMIServerImpl</code>.  Can be null, which is equivalent
 * to an empty Map.
 *
 * @exception IOException if the RMI object cannot be created.
 */
public RMIIIOPServerImpl(Map<String,?> env)
        throws IOException {
    super(env);

    this.env = (env == null) ? Collections.<String, Object>emptyMap() : env;

    callerACC = AccessController.getContext();
}
 
源代码19 项目: jdk1.8-source-analysis   文件: URLClassLoader.java
/**
 * Constructs a new URLClassLoader for the given URLs. The URLs will be
 * searched in the order specified for classes and resources after first
 * searching in the specified parent class loader. Any URL that ends with
 * a '/' is assumed to refer to a directory. Otherwise, the URL is assumed
 * to refer to a JAR file which will be downloaded and opened as needed.
 *
 * <p>If there is a security manager, this method first
 * calls the security manager's {@code checkCreateClassLoader} method
 * to ensure creation of a class loader is allowed.
 *
 * @param urls the URLs from which to load classes and resources
 * @param parent the parent class loader for delegation
 * @exception  SecurityException  if a security manager exists and its
 *             {@code checkCreateClassLoader} method doesn't allow
 *             creation of a class loader.
 * @exception  NullPointerException if {@code urls} is {@code null}.
 * @see SecurityManager#checkCreateClassLoader
 */
public URLClassLoader(URL[] urls, ClassLoader parent) {
    super(parent);
    // this is to make the stack depth consistent with 1.1
    SecurityManager security = System.getSecurityManager();
    if (security != null) {
        security.checkCreateClassLoader();
    }
    this.acc = AccessController.getContext();
    ucp = new URLClassPath(urls, acc);
}
 
/**
 * Return the security context for this bean factory. If a security manager
 * is set, interaction with the user code will be executed using the privileged
 * of the security context returned by this method.
 * @see AccessController#getContext()
 */
protected AccessControlContext getAccessControlContext() {
	return AccessController.getContext();
}