Java 类java.security.AccessController 实例源码

项目:uavstack    文件:HttpRequest.java   
/**
 * Set property to given value.
 * <p>
 * Specifying a null value will cause the property to be cleared
 *
 * @param name
 * @param value
 * @return previous value
 */
private static String setProperty(final String name, final String value) {

    final PrivilegedAction<String> action;
    if (value != null)
        action = new PrivilegedAction<String>() {

            @Override
            public String run() {

                return System.setProperty(name, value);
            }
        };
    else
        action = new PrivilegedAction<String>() {

            @Override
            public String run() {

                return System.clearProperty(name);
            }
        };
    return AccessController.doPrivileged(action);
}
项目:tomcat7    文件:ApplicationContextFacade.java   
/**
 * Executes the method of the specified <code>ApplicationContext</code>
 * @param method The method object to be invoked.
 * @param context The AppliationContext object on which the method
 *                   will be invoked
 * @param params The arguments passed to the called method.
 */
private Object executeMethod(final Method method, 
                             final ApplicationContext context,
                             final Object[] params) 
        throws PrivilegedActionException, 
               IllegalAccessException,
               InvocationTargetException {

    if (SecurityUtil.isPackageProtectionEnabled()){
       return AccessController.doPrivileged(new PrivilegedExceptionAction<Object>(){
            @Override
            public Object run() throws IllegalAccessException, InvocationTargetException{
                return method.invoke(context,  params);
            }
        });
    } else {
        return method.invoke(context, params);
    }        
}
项目:trashjam2017    文件:Log.java   
/**
 * Check if the system property org.newdawn.slick.verboseLog is set to true.
 * If this is the case we activate the verbose logging mode
 */
public static void checkVerboseLogSetting() {
    try {
        AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                String val = System.getProperty(Log.forceVerboseProperty);
                if ((val != null) && (val.equalsIgnoreCase(Log.forceVerbosePropertyOnValue))) {
                    Log.setForcedVerboseOn();
                }

                return null;
            }
        });
    } catch (Throwable e) {
        // ignore, security failure - probably an applet
    }
}
项目:openjdk-jdk10    文件:URL.java   
private static URLStreamHandler lookupViaProviders(final String protocol) {
    if (gate.get() != null)
        throw new Error("Circular loading of URL stream handler providers detected");

    gate.set(gate);
    try {
        return AccessController.doPrivileged(
            new PrivilegedAction<>() {
                public URLStreamHandler run() {
                    Iterator<URLStreamHandlerProvider> itr = providers();
                    while (itr.hasNext()) {
                        URLStreamHandlerProvider f = itr.next();
                        URLStreamHandler h = f.createURLStreamHandler(protocol);
                        if (h != null)
                            return h;
                    }
                    return null;
                }
            });
    } finally {
        gate.set(null);
    }
}
项目:tomcat7    文件:PersistentManagerBase.java   
/**
 * Clear all sessions from the Store.
 */
public void clearStore() {

    if (store == null)
        return;

    try {     
        if (SecurityUtil.isPackageProtectionEnabled()){
            try{
                AccessController.doPrivileged(new PrivilegedStoreClear());
            }catch(PrivilegedActionException ex){
                Exception exception = ex.getException();
                log.error("Exception clearing the Store: " + exception,
                        exception);
            }
        } else {
            store.clear();
        }
    } catch (IOException e) {
        log.error("Exception clearing the Store: " + e, e);
    }

}
项目:OpenJSharp    文件:InputContext.java   
/**
 * Initializes the input method selection key definition in preference trees
 */
private void initializeInputMethodSelectionKey() {
    AccessController.doPrivileged(new PrivilegedAction<Object>() {
        public Object run() {
            // Look in user's tree
            Preferences root = Preferences.userRoot();
            inputMethodSelectionKey = getInputMethodSelectionKeyStroke(root);

            if (inputMethodSelectionKey == null) {
                // Look in system's tree
                root = Preferences.systemRoot();
                inputMethodSelectionKey = getInputMethodSelectionKeyStroke(root);
            }
            return null;
        }
    });
}
项目:lazycat    文件:PageContextImpl.java   
@Override
public Object getAttribute(final String name, final int scope) {

    if (name == null) {
        throw new NullPointerException(Localizer.getMessage("jsp.error.attribute.null_name"));
    }

    if (SecurityUtil.isPackageProtectionEnabled()) {
        return AccessController.doPrivileged(new PrivilegedAction<Object>() {
            @Override
            public Object run() {
                return doGetAttribute(name, scope);
            }
        });
    } else {
        return doGetAttribute(name, scope);
    }

}
项目:openjdk-jdk10    文件:ObjectStreamClassUtil_1_3.java   
private static Method getDeclaredMethod(final Class cl, final String methodName, final Class[] args,
                                 final int requiredModifierMask,
                                 final int disallowedModifierMask) {
    return (Method) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            Method method = null;
            try {
                method =
                    cl.getDeclaredMethod(methodName, args);
                    int mods = method.getModifiers();
                    if ((mods & disallowedModifierMask) != 0 ||
                        (mods & requiredModifierMask) != requiredModifierMask) {
                        method = null;
                    }
                    //if (!Modifier.isPrivate(mods) ||
                    //    Modifier.isStatic(mods)) {
                    //    method = null;
                    //}
            } catch (NoSuchMethodException e) {
            // Since it is alright if methodName does not exist,
            // no need to do anything special here.
            }
            return method;
        }
    });
}
项目:jdk8u-jdk    文件:LoginContext.java   
public void handle(final Callback[] callbacks)
        throws java.io.IOException, UnsupportedCallbackException {
    try {
        java.security.AccessController.doPrivileged
            (new java.security.PrivilegedExceptionAction<Void>() {
            public Void run() throws java.io.IOException,
                                UnsupportedCallbackException {
                ch.handle(callbacks);
                return null;
            }
        }, acc);
    } catch (java.security.PrivilegedActionException pae) {
        if (pae.getException() instanceof java.io.IOException) {
            throw (java.io.IOException)pae.getException();
        } else {
            throw (UnsupportedCallbackException)pae.getException();
        }
    }
}
项目:apache-tomcat-7.0.73-with-comment    文件:ClassLoaderLogManager.java   
/**
 * Retrieve the configuration associated with the specified classloader. If
 * it does not exist, it will be created.
 * 
 * @param classLoader The classloader for which we will retrieve or build the 
 *                    configuration
 */
protected synchronized ClassLoaderLogInfo getClassLoaderInfo(ClassLoader classLoader) {

    if (classLoader == null) {
        classLoader = ClassLoader.getSystemClassLoader();
    }
    ClassLoaderLogInfo info = classLoaderLoggers.get(classLoader);
    if (info == null) {
        final ClassLoader classLoaderParam = classLoader;
        AccessController.doPrivileged(new PrivilegedAction<Void>() {
            @Override
            public Void run() {
                try {
                    readConfiguration(classLoaderParam);
                } catch (IOException e) {
                    // Ignore
                }
                return null;
            }
        });
        info = classLoaderLoggers.get(classLoader);
    }
    return info;
}
项目:tomcat7    文件:ConnectionPool.java   
private static synchronized void registerCleaner(PoolCleaner cleaner) {
    unregisterCleaner(cleaner);
    cleaners.add(cleaner);
    if (poolCleanTimer == null) {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        try {
            Thread.currentThread().setContextClassLoader(ConnectionPool.class.getClassLoader());
            // Create the timer thread in a PrivilegedAction so that a
            // reference to the web application class loader is not created
            // via Thread.inheritedAccessControlContext
            PrivilegedAction<Timer> pa = new PrivilegedNewTimer();
            poolCleanTimer = AccessController.doPrivileged(pa);
        } finally {
            Thread.currentThread().setContextClassLoader(loader);
        }
    }
    poolCleanTimer.schedule(cleaner, cleaner.sleepTime,cleaner.sleepTime);
}
项目:jdk8u-jdk    文件:AppContext.java   
private final static void initMainAppContext() {
    // On the main Thread, we get the ThreadGroup, make a corresponding
    // AppContext, and instantiate the Java EventQueue.  This way, legacy
    // code is unaffected by the move to multiple AppContext ability.
    AccessController.doPrivileged(new PrivilegedAction<Void>() {
        public Void run() {
            ThreadGroup currentThreadGroup =
                    Thread.currentThread().getThreadGroup();
            ThreadGroup parentThreadGroup = currentThreadGroup.getParent();
            while (parentThreadGroup != null) {
                // Find the root ThreadGroup to construct our main AppContext
                currentThreadGroup = parentThreadGroup;
                parentThreadGroup = currentThreadGroup.getParent();
            }

            mainAppContext = SunToolkit.createNewAppContext(currentThreadGroup);
            return null;
        }
    });
}
项目:openjdk-jdk10    文件:Util.java   
/**
 * Registers a target for a tie. Adds the tie to an internal table and calls
 * {@link Tie#setTarget} on the tie object.
 * @param tie the tie to register.
 * @param target the target for the tie.
 */
public void registerTarget(javax.rmi.CORBA.Tie tie, java.rmi.Remote target)
{
    synchronized (exportedServants) {
        // Do we already have this target registered?
        if (lookupTie(target) == null) {
            // No, so register it and set the target...
            exportedServants.put(target,tie);
            tie.setTarget(target);

            // Do we need to instantiate our keep-alive thread?
            if (keepAlive == null) {
                // Yes. Instantiate our keep-alive thread and start
                // it up...
                keepAlive = (KeepAlive)AccessController.doPrivileged(new PrivilegedAction() {
                    public java.lang.Object run() {
                        return new KeepAlive();
                    }
                });
                keepAlive.start();
            }
        }
    }
}
项目:jdk8u-jdk    文件:WindowsFileSystem.java   
WindowsFileSystem(WindowsFileSystemProvider provider,
                  String dir)
{
    this.provider = provider;

    // parse default directory and check it is absolute
    WindowsPathParser.Result result = WindowsPathParser.parse(dir);

    if ((result.type() != WindowsPathType.ABSOLUTE) &&
        (result.type() != WindowsPathType.UNC))
        throw new AssertionError("Default directory is not an absolute path");
    this.defaultDirectory = result.path();
    this.defaultRoot = result.root();

    PrivilegedAction<String> pa = new GetPropertyAction("os.version");
    String osversion = AccessController.doPrivileged(pa);
    String[] vers = Util.split(osversion, '.');
    int major = Integer.parseInt(vers[0]);
    int minor = Integer.parseInt(vers[1]);

    // symbolic links available on Vista and newer
    supportsLinks = (major >= 6);

    // enumeration of data streams available on Windows Server 2003 and newer
    supportsStreamEnumeration = (major >= 6) || (major == 5 && minor >= 2);
}
项目:OpenJSharp    文件:JSSecurityManager.java   
/** Load properties from a file.
    This method tries to load properties from the filename give into
    the passed properties object.
    If the file cannot be found or something else goes wrong,
    the method silently fails.
    @param properties The properties bundle to store the values of the
    properties file.
    @param filename The filename of the properties file to load. This
    filename is interpreted as relative to the subdirectory "lib" in
    the JRE directory.
 */
static void loadProperties(final Properties properties,
                           final String filename) {
    if(hasSecurityManager()) {
        try {
            // invoke the privileged action using 1.2 security
            PrivilegedAction<Void> action = new PrivilegedAction<Void>() {
                    public Void run() {
                        loadPropertiesImpl(properties, filename);
                        return null;
                    }
                };
            AccessController.doPrivileged(action);
            if(Printer.debug)Printer.debug("Loaded properties with JDK 1.2 security");
        } catch (Exception e) {
            if(Printer.debug)Printer.debug("Exception loading properties with JDK 1.2 security");
            // try without using JDK 1.2 security
            loadPropertiesImpl(properties, filename);
        }
    } else {
        // not JDK 1.2 security, assume we already have permission
        loadPropertiesImpl(properties, filename);
    }
}
项目:OpenJSharp    文件:AppContext.java   
private final static void initMainAppContext() {
    // On the main Thread, we get the ThreadGroup, make a corresponding
    // AppContext, and instantiate the Java EventQueue.  This way, legacy
    // code is unaffected by the move to multiple AppContext ability.
    AccessController.doPrivileged(new PrivilegedAction<Void>() {
        public Void run() {
            ThreadGroup currentThreadGroup =
                    Thread.currentThread().getThreadGroup();
            ThreadGroup parentThreadGroup = currentThreadGroup.getParent();
            while (parentThreadGroup != null) {
                // Find the root ThreadGroup to construct our main AppContext
                currentThreadGroup = parentThreadGroup;
                parentThreadGroup = currentThreadGroup.getParent();
            }

            mainAppContext = SunToolkit.createNewAppContext(currentThreadGroup);
            return null;
        }
    });
}
项目:openjdk-jdk10    文件:ObjectStreamClassUtil_1_3.java   
private static Long getSerialVersion(final long csuid, final Class cl)
{
    return (Long) AccessController.doPrivileged(new PrivilegedAction() {
      public Object run() {
        long suid;
        try {
            final Field f = cl.getDeclaredField("serialVersionUID");
            int mods = f.getModifiers();
            if (Modifier.isStatic(mods) &&
                Modifier.isFinal(mods) && Modifier.isPrivate(mods)) {
                suid = csuid;
             } else {
                suid = _computeSerialVersionUID(cl);
             }
          } catch (NoSuchFieldException ex) {
              suid = _computeSerialVersionUID(cl);
          //} catch (IllegalAccessException ex) {
          //     suid = _computeSerialVersionUID(cl);
          }
          return new Long(suid);
       }
    });
}
项目:jdk8u-jdk    文件:Socket.java   
/**
 * Returns an output stream for this socket.
 *
 * <p> If this socket has an associated channel then the resulting output
 * stream delegates all of its operations to the channel.  If the channel
 * is in non-blocking mode then the output stream's {@code write}
 * operations will throw an {@link
 * java.nio.channels.IllegalBlockingModeException}.
 *
 * <p> Closing the returned {@link java.io.OutputStream OutputStream}
 * will close the associated socket.
 *
 * @return     an output stream for writing bytes to this socket.
 * @exception  IOException  if an I/O error occurs when creating the
 *               output stream or if the socket is not connected.
 * @revised 1.4
 * @spec JSR-51
 */
public OutputStream getOutputStream() throws IOException {
    if (isClosed())
        throw new SocketException("Socket is closed");
    if (!isConnected())
        throw new SocketException("Socket is not connected");
    if (isOutputShutdown())
        throw new SocketException("Socket output is shutdown");
    final Socket s = this;
    OutputStream os = null;
    try {
        os = AccessController.doPrivileged(
            new PrivilegedExceptionAction<OutputStream>() {
                public OutputStream run() throws IOException {
                    return impl.getOutputStream();
                }
            });
    } catch (java.security.PrivilegedActionException e) {
        throw (IOException) e.getException();
    }
    return os;
}
项目:lams    文件:DefaultInstanceManager.java   
protected Class<?> loadClassMaybePrivileged(final String className, final ClassLoader classLoader) throws ClassNotFoundException {
    Class<?> clazz;
    if (SecurityUtil.isPackageProtectionEnabled()) {
        try {
            clazz = AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>() {

                public Class<?> run() throws Exception {
                    return loadClass(className, classLoader);
                }
            });
        } catch (PrivilegedActionException e) {
            Throwable t = e.getCause();
            if (t instanceof ClassNotFoundException) {
                throw (ClassNotFoundException) t;
            }
            throw new RuntimeException(t);
        }
    } else {
        clazz = loadClass(className, classLoader);
    }
    checkAccess(clazz);
    return clazz;
}
项目:openjdk-jdk10    文件:Util.java   
private static void initDBBConstructor() {
    AccessController.doPrivileged(new PrivilegedAction<Void>() {
            public Void run() {
                try {
                    Class<?> cl = Class.forName("java.nio.DirectByteBuffer");
                    Constructor<?> ctor = cl.getDeclaredConstructor(
                        new Class<?>[] { int.class,
                                         long.class,
                                         FileDescriptor.class,
                                         Runnable.class });
                    ctor.setAccessible(true);
                    directByteBufferConstructor = ctor;
                } catch (ClassNotFoundException   |
                         NoSuchMethodException    |
                         IllegalArgumentException |
                         ClassCastException x) {
                    throw new InternalError(x);
                }
                return null;
            }});
}
项目:jdk8u-jdk    文件:ExtensionDependency.java   
/**
 * <p>
 * @return the java.ext.dirs property as a list of directory
 * </p>
 */
private static File[] getExtDirs() {
    String s = java.security.AccessController.doPrivileged(
            new sun.security.action.GetPropertyAction("java.ext.dirs"));

    File[] dirs;
    if (s != null) {
        StringTokenizer st =
            new StringTokenizer(s, File.pathSeparator);
        int count = st.countTokens();
        debug("getExtDirs count " + count);
        dirs = new File[count];
        for (int i = 0; i < count; i++) {
            dirs[i] = new File(st.nextToken());
            debug("getExtDirs dirs["+i+"] "+ dirs[i]);
        }
    } else {
        dirs = new File[0];
        debug("getExtDirs dirs " + dirs);
    }
    debug("getExtDirs dirs.length " + dirs.length);
    return dirs;
}
项目:BaseClient    文件:Log.java   
/**
 * Check if the system property org.newdawn.slick.verboseLog is set to true.
 * If this is the case we activate the verbose logging mode
 */
public static void checkVerboseLogSetting() {
    try {
        AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                String val = System.getProperty(Log.forceVerboseProperty);
                if ((val != null) && (val.equalsIgnoreCase(Log.forceVerbosePropertyOnValue))) {
                    Log.setForcedVerboseOn();
                }

                return null;
            }
        });
    } catch (Throwable e) {
        // ignore, security failure - probably an applet
    }
}
项目:javafx-qiniu-tinypng-client    文件:ReflectionUtils.java   
/**
 * Helper method to execute a callback on a given field. This method encapsulates the error handling logic and the
 * handling of accessibility of the field. The difference to
 * {@link ReflectionUtils#accessField(Field, Callable, String)} is that this method takes a callback that doesn't
 * return anything but only creates a sideeffect.
 *
 * After the callback is executed the accessibility of the field will be reset to the originally state.
 *
 * @param field
 *            the field that is made accessible to run the callback
 * @param sideEffect
 *            the callback that will be executed.
 * @param errorMessage
 *            the error message that is used in the exception when something went wrong.
 *          
 * @throws IllegalStateException
 *             when something went wrong.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
   public static void accessField(final Field field, final SideEffect sideEffect, String errorMessage) {
    if (sideEffect == null) {
        return;
    }
    AccessController.doPrivileged((PrivilegedAction) () -> {
        boolean wasAccessible = field.isAccessible();
        try {
            field.setAccessible(true);
            sideEffect.call();
        } catch (Exception exception) {
            throw new IllegalStateException(errorMessage, exception);
        } finally {
            field.setAccessible(wasAccessible);
        }
        return null;
    });
}
项目:rosette-elasticsearch-plugin    文件:SentimentProcessor.java   
@Override
public void processDocument(String inputText, IngestDocument ingestDocument) throws Exception {
    // call /sentiment endpoint and set the top result in the field
    DocumentRequest<SentimentOptions> request = new DocumentRequest.Builder<SentimentOptions>().content(inputText).build();
    SentimentResponse response;
    try {
        // RosApi client binding's Jackson needs elevated privilege
        response = AccessController.doPrivileged((PrivilegedAction<SentimentResponse>) () ->
                rosAPI.getHttpRosetteAPI().perform(HttpRosetteAPI.SENTIMENT_SERVICE_PATH, request, SentimentResponse.class)
        );
    } catch (HttpRosetteAPIException ex) {
        LOGGER.error(ex.getErrorResponse().getMessage());
        throw new ElasticsearchException(ex.getErrorResponse().getMessage(), ex);
    }

    if (response.getDocument() != null
            && !Strings.isNullOrEmpty(response.getDocument().getLabel())) {
        ingestDocument.setFieldValue(targetField, response.getDocument().getLabel());
    } else {
        throw new ElasticsearchException(TYPE + " ingest processor failed to determine sentiment of document.");
    }
}
项目:OpenJSharp    文件:Options.java   
/**
 * Convenience function for getting system properties in a safe way
 *
 * @param name of integer property
 * @param defValue the default value if unset
 * @return integer property if set or default value
 */
public static int getIntProperty(final String name, final int defValue) {
    name.getClass(); // null check
    if (! name.startsWith("nashorn.")) {
        throw new IllegalArgumentException(name);
    }

    return AccessController.doPrivileged(
            new PrivilegedAction<Integer>() {
                @Override
                public Integer run() {
                    try {
                        return Integer.getInteger(name, defValue);
                    } catch (final SecurityException e) {
                        // if no permission to read, assume the default value
                        return defValue;
                    }
                }
            }, READ_PROPERTY_ACC_CTXT);
}
项目:OpenJSharp    文件:Util.java   
/**
 * Registers a target for a tie. Adds the tie to an internal table and calls
 * {@link Tie#setTarget} on the tie object.
 * @param tie the tie to register.
 * @param target the target for the tie.
 */
public void registerTarget(javax.rmi.CORBA.Tie tie, java.rmi.Remote target)
{
    synchronized (exportedServants) {
        // Do we already have this target registered?
        if (lookupTie(target) == null) {
            // No, so register it and set the target...
            exportedServants.put(target,tie);
            tie.setTarget(target);

            // Do we need to instantiate our keep-alive thread?
            if (keepAlive == null) {
                // Yes. Instantiate our keep-alive thread and start
                // it up...
                keepAlive = (KeepAlive)AccessController.doPrivileged(new PrivilegedAction() {
                    public java.lang.Object run() {
                        return new KeepAlive();
                    }
                });
                keepAlive.start();
            }
        }
    }
}
项目:arquillian-reporter    文件:SecurityActions.java   
static String getProperty(final String key) {
   try {
       String value = AccessController.doPrivileged(new PrivilegedExceptionAction<String>() {
           public String run() {
               return System.getProperty(key);
           }
       });
       return value;
   }
   // Unwrap
   catch (final PrivilegedActionException pae) {
       final Throwable t = pae.getCause();
       // Rethrow
       if (t instanceof SecurityException) {
           throw (SecurityException) t;
       }
       if (t instanceof NullPointerException) {
           throw (NullPointerException) t;
       } else if (t instanceof IllegalArgumentException) {
           throw (IllegalArgumentException) t;
       } else {
           // No other checked Exception thrown by System.getProperty
           try {
               throw (RuntimeException) t;
           }
           // Just in case we've really messed up
           catch (final ClassCastException cce) {
               throw new RuntimeException("Obtained unchecked Exception; this code should never be reached", t);
           }
       }
   }
}
项目:OpenJSharp    文件:ContextClassloaderLocal.java   
private static ClassLoader getContextClassLoader() {
    return (ClassLoader)
            AccessController.doPrivileged(new PrivilegedAction() {
                public Object run() {
                    ClassLoader cl = null;
                    try {
                        cl = Thread.currentThread().getContextClassLoader();
                    } catch (SecurityException ex) {
                    }
                    return cl;
                }
            });
}
项目:OpenJSharp    文件:XToolkit.java   
/**
 * Returns the value of "sun.awt.disableGtkFileDialogs" property. Default
 * value is {@code false}.
 */
public synchronized static boolean getSunAwtDisableGtkFileDialogs() {
    if (sunAwtDisableGtkFileDialogs == null) {
        sunAwtDisableGtkFileDialogs = AccessController.doPrivileged(
                                          new GetBooleanAction("sun.awt.disableGtkFileDialogs"));
    }
    return sunAwtDisableGtkFileDialogs.booleanValue();
}
项目:OpenJSharp    文件:SunFontManager.java   
private static boolean maybeMultiAppContext() {
    Boolean appletSM = (Boolean)
        java.security.AccessController.doPrivileged(
            new java.security.PrivilegedAction() {
                    public Object run() {
                        SecurityManager sm = System.getSecurityManager();
                        return new Boolean
                            (sm instanceof sun.applet.AppletSecurity);
                    }
                });
    return appletSM.booleanValue();
}
项目:openjdk-jdk10    文件:SecuritySupport.java   
public static boolean getFileExists(final File f) {
    return ((Boolean) AccessController.doPrivileged(new PrivilegedAction() {
                public Object run() {
                    return f.exists() ? Boolean.TRUE : Boolean.FALSE;
                }
            })).booleanValue();
}
项目:openjdk-jdk10    文件:Executors.java   
PrivilegedThreadFactory() {
    super();
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        // Calls to getContextClassLoader from this class
        // never trigger a security check, but we check
        // whether our callers have this permission anyways.
        sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);

        // Fail fast
        sm.checkPermission(new RuntimePermission("setContextClassLoader"));
    }
    this.acc = AccessController.getContext();
    this.ccl = Thread.currentThread().getContextClassLoader();
}
项目:openjdk-jdk10    文件:HttpURLConnection.java   
private static boolean hostsEqual(URL u1, URL u2) {
    final String h1 = u1.getHost();
    final String h2 = u2.getHost();

    if (h1 == null) {
        return h2 == null;
    } else if (h2 == null) {
        return false;
    } else if (h1.equalsIgnoreCase(h2)) {
        return true;
    }
    // Have to resolve addresses before comparing, otherwise
    // names like tachyon and tachyon.eng would compare different
    final boolean result[] = {false};

    java.security.AccessController.doPrivileged(
        new java.security.PrivilegedAction<>() {
            public Void run() {
            try {
                InetAddress a1 = InetAddress.getByName(h1);
                InetAddress a2 = InetAddress.getByName(h2);
                result[0] = a1.equals(a2);
            } catch(UnknownHostException | SecurityException e) {
            }
            return null;
        }
    });

    return result[0];
}
项目:OpenJSharp    文件:UNIXProcess.java   
String helperPath() {
    return AccessController.doPrivileged(
        (PrivilegedAction<String>) () ->
            helperPath(System.getProperty("java.home"),
                       System.getProperty("os.arch"))
    );
}
项目:lazycat    文件:JspWriterImpl.java   
private String getLocalizeMessage(final String message) {
    if (SecurityUtil.isPackageProtectionEnabled()) {
        return AccessController.doPrivileged(new PrivilegedAction<String>() {
            @Override
            public String run() {
                return Localizer.getMessage(message);
            }
        });
    } else {
        return Localizer.getMessage(message);
    }
}
项目:aws-sdk-java-v2    文件:AbstractErrorUnmarshaller.java   
protected static void makeAccessible(AccessibleObject object) {
    if (!object.isAccessible()) {
        AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
            object.setAccessible(true);
            return null;
        });
    }
}
项目:jerrydog    文件:WebappClassLoader.java   
/**
 * Find the specified resource in our local repository, and return a
 * <code>URL</code> refering to it, or <code>null</code> if this resource
 * cannot be found.
 *
 * @param name Name of the resource to be found
 */
public URL findResource(final String name) {

    if (debug >= 3)
        log("    findResource(" + name + ")");

    URL url = null;

    ResourceEntry entry = (ResourceEntry) resourceEntries.get(name);
    if (entry == null) {
        if (securityManager != null) {
            PrivilegedAction dp =
                new PrivilegedFindResource(name, name);
            entry = (ResourceEntry)AccessController.doPrivileged(dp);
        } else {
            entry = findResourceInternal(name, name);
        }
    }
    if (entry != null) {
        url = entry.source;
    }

    if ((url == null) && hasExternalRepositories)
        url = super.findResource(name);

    if (debug >= 3) {
        if (url != null)
            log("    --> Returning '" + url.toString() + "'");
        else
            log("    --> Resource not found, returning null");
    }
    return (url);

}
项目:OpenJSharp    文件:Container.java   
private void startListeningForOtherDrags() {
    //System.out.println("Adding AWTEventListener");
    java.security.AccessController.doPrivileged(
        new java.security.PrivilegedAction<Object>() {
            public Object run() {
                nativeContainer.getToolkit().addAWTEventListener(
                    LightweightDispatcher.this,
                    AWTEvent.MOUSE_EVENT_MASK |
                    AWTEvent.MOUSE_MOTION_EVENT_MASK);
                return null;
            }
        }
    );
}
项目:OpenJSharp    文件:SecuritySupport.java   
public static String getSystemProperty(final String propName) {
    return (String) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return System.getProperty(propName);
        }
    });
}
项目:openjdk-jdk10    文件:LdapPoolManager.java   
private static final String getProperty(final String propName,
    final String defVal) {
    return AccessController.doPrivileged(
        new PrivilegedAction<String>() {
        public String run() {
            try {
                return System.getProperty(propName, defVal);
            } catch (SecurityException e) {
                return defVal;
            }
        }
    });
}