Example usage for java.security PrivilegedAction PrivilegedAction

List of usage examples for java.security PrivilegedAction PrivilegedAction

Introduction

In this page you can find the example usage for java.security PrivilegedAction PrivilegedAction.

Prototype

PrivilegedAction

Source Link

Usage

From source file:groovyx.osgi.test.LocalFileSystemIvyRepository.java

public static File getFileFromPath(String path) {
    // use privileged action to get user home
    String userHome = AccessController.doPrivileged(new PrivilegedAction<String>() {

        public String run() {
            return System.getProperty(USER_HOME_PROPERTY);
        }/*from w w  w . j  a  v  a 2s.c  om*/
    });

    File home = new File(userHome);
    return new File(home, path);
}

From source file:SecuritySupport.java

static ClassLoader getSystemClassLoader() {
    return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            ClassLoader cl = null;
            try {
                cl = ClassLoader.getSystemClassLoader();
            } catch (SecurityException ex) {
            }//from ww w .ja v a  2  s .  co  m
            return cl;
        }
    });
}

From source file:com.mgreau.jboss.as7.cli.CliLauncher.java

public static void main(String[] args) throws Exception {
    int exitCode = 0;
    CommandContext cmdCtx = null;/* w w  w  . j  a  v  a2s  .c  o  m*/
    boolean gui = false;
    String appName = "";
    try {
        String argError = null;
        List<String> commands = null;
        File file = null;
        boolean connect = false;
        String defaultControllerProtocol = "http-remoting";
        String defaultControllerHost = null;
        int defaultControllerPort = -1;
        boolean version = false;
        String username = null;
        char[] password = null;
        int connectionTimeout = -1;

        //App deployment
        boolean isAppDeployment = false;
        final Properties props = new Properties();

        for (String arg : args) {
            if (arg.startsWith("--controller=") || arg.startsWith("controller=")) {
                final String fullValue;
                final String value;
                if (arg.startsWith("--")) {
                    fullValue = arg.substring(13);
                } else {
                    fullValue = arg.substring(11);
                }
                final int protocolEnd = fullValue.lastIndexOf("://");
                if (protocolEnd == -1) {
                    value = fullValue;
                } else {
                    value = fullValue.substring(protocolEnd + 3);
                    defaultControllerProtocol = fullValue.substring(0, protocolEnd);
                }

                String portStr = null;
                int colonIndex = value.lastIndexOf(':');
                if (colonIndex < 0) {
                    // default port
                    defaultControllerHost = value;
                } else if (colonIndex == 0) {
                    // default host
                    portStr = value.substring(1);
                } else {
                    final boolean hasPort;
                    int closeBracket = value.lastIndexOf(']');
                    if (closeBracket != -1) {
                        //possible ip v6
                        if (closeBracket > colonIndex) {
                            hasPort = false;
                        } else {
                            hasPort = true;
                        }
                    } else {
                        //probably ip v4
                        hasPort = true;
                    }
                    if (hasPort) {
                        defaultControllerHost = value.substring(0, colonIndex).trim();
                        portStr = value.substring(colonIndex + 1).trim();
                    } else {
                        defaultControllerHost = value;
                    }
                }

                if (portStr != null) {
                    int port = -1;
                    try {
                        port = Integer.parseInt(portStr);
                        if (port < 0) {
                            argError = "The port must be a valid non-negative integer: '" + args + "'";
                        } else {
                            defaultControllerPort = port;
                        }
                    } catch (NumberFormatException e) {
                        argError = "The port must be a valid non-negative integer: '" + arg + "'";
                    }
                }
            } else if ("--connect".equals(arg) || "-c".equals(arg)) {
                connect = true;
            } else if ("--version".equals(arg)) {
                version = true;
            } else if ("--gui".equals(arg)) {
                gui = true;
            } else if (arg.startsWith("--appDeployment=") || arg.startsWith("appDeployment=")) {
                isAppDeployment = true;
                appName = arg.startsWith("--") ? arg.substring(16) : arg.substring(14);
            } else if (arg.startsWith("--file=") || arg.startsWith("file=")) {
                if (file != null) {
                    argError = "Duplicate argument '--file'.";
                    break;
                }
                if (commands != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
                    break;
                }

                final String fileName = arg.startsWith("--") ? arg.substring(7) : arg.substring(5);
                if (!fileName.isEmpty()) {
                    file = new File(fileName);
                    if (!file.exists()) {
                        argError = "File " + file.getAbsolutePath() + " doesn't exist.";
                        break;
                    }
                } else {
                    argError = "Argument '--file' is missing value.";
                    break;
                }
            } else if (arg.startsWith("--commands=") || arg.startsWith("commands=")) {
                if (file != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
                    break;
                }
                if (commands != null) {
                    argError = "Duplicate argument '--command'/'--commands'.";
                    break;
                }
                final String value = arg.startsWith("--") ? arg.substring(11) : arg.substring(9);
                commands = Util.splitCommands(value);
            } else if (arg.startsWith("--command=") || arg.startsWith("command=")) {
                if (file != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
                    break;
                }
                if (commands != null) {
                    argError = "Duplicate argument '--command'/'--commands'.";
                    break;
                }
                final String value = arg.startsWith("--") ? arg.substring(10) : arg.substring(8);
                commands = Collections.singletonList(value);
            } else if (arg.startsWith("--user=")) {
                username = arg.startsWith("--") ? arg.substring(7) : arg.substring(5);
            } else if (arg.startsWith("--password=")) {
                password = (arg.startsWith("--") ? arg.substring(11) : arg.substring(9)).toCharArray();
            } else if (arg.startsWith("--timeout=")) {
                if (connectionTimeout > 0) {
                    argError = "Duplicate argument '--timeout'";
                    break;
                }
                final String value = arg.substring(10);
                try {
                    connectionTimeout = Integer.parseInt(value);
                } catch (final NumberFormatException e) {
                    //
                }
                if (connectionTimeout <= 0) {
                    argError = "The timeout must be a valid positive integer: '" + value + "'";
                }
            } else if (arg.equals("--help") || arg.equals("-h")) {
                commands = Collections.singletonList("help");
            } else if (arg.startsWith("--properties=")) {
                final String value = arg.substring(13);
                final File propertiesFile = new File(value);
                if (!propertiesFile.exists()) {
                    argError = "File doesn't exist: " + propertiesFile.getAbsolutePath();
                    break;
                }

                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(propertiesFile);
                    props.load(fis);
                } catch (FileNotFoundException e) {
                    argError = e.getLocalizedMessage();
                    break;
                } catch (java.io.IOException e) {
                    argError = "Failed to load properties from " + propertiesFile.getAbsolutePath() + ": "
                            + e.getLocalizedMessage();
                    break;
                } finally {
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (java.io.IOException e) {
                        }
                    }
                }
                for (final Object prop : props.keySet()) {
                    AccessController.doPrivileged(new PrivilegedAction<Object>() {
                        public Object run() {
                            System.setProperty((String) prop, (String) props.get(prop));
                            return null;
                        }
                    });
                }
            } else if (!(arg.startsWith("-D") || arg.equals("-XX:"))) {// skip system properties and jvm options
                // assume it's commands
                if (file != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time: "
                            + arg;
                    break;
                }
                if (commands != null) {
                    argError = "Duplicate argument '--command'/'--commands'.";
                    break;
                }
                commands = Util.splitCommands(arg);
            }
        }

        if (argError != null) {
            System.err.println(argError);
            exitCode = 1;
            return;
        }

        if (version) {
            cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                    username, password, false, connect, connectionTimeout);
            VersionHandler.INSTANCE.handle(cmdCtx);
            return;
        }

        if (file != null) {
            cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                    username, password, false, connect, connectionTimeout);
            processFile(file, cmdCtx, isAppDeployment, appName, props);
            return;
        }

        if (commands != null) {
            cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                    username, password, false, connect, connectionTimeout);
            processCommands(commands, cmdCtx);
            return;
        }

        // Interactive mode
        cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                username, password, true, connect, connectionTimeout);
        cmdCtx.interact();
    } catch (Throwable t) {
        t.printStackTrace();
        exitCode = 1;
    } finally {
        if (cmdCtx != null && cmdCtx.getExitCode() != 0) {
            exitCode = cmdCtx.getExitCode();
        }
        if (!gui) {
            System.exit(exitCode);
        }
    }
    System.exit(exitCode);
}

From source file:SecurityActions.java

static ClassLoader getClassLoader(final Class<?> clazz) {
    if (System.getSecurityManager() == null) {
        return clazz.getClassLoader();
    } else {/*from  w ww.  j av a  2  s.  co m*/
        return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
            public ClassLoader run() {
                return clazz.getClassLoader();
            }
        });
    }

}

From source file:org.eclipse.gemini.blueprint.util.LogUtils.java

/**
 * Set the TCCL of the bundle before creating the logger. This helps if commons-logging is used since it looks at
 * the existing TCCL before associating a LogFactory with it and since the TCCL can be the
 * BundleDelegatingClassLoader, loading a LogFactory using the BundleDelegatingClassLoader will result in an
 * infinite cycle or chained failures that would be swallowed.
 * /*from   w w w  . ja  va  2 s  . c o  m*/
 * <p/> Create the logger using LogFactory but use a simple implementation if something goes wrong.
 * 
 * @param logName log name
 * @return logger implementation
 */
public static Log createLogger(final Class<?> logName) {
    if (System.getSecurityManager() != null) {
        return AccessController.doPrivileged(new PrivilegedAction<Log>() {
            public Log run() {
                return doCreateLogger(logName);
            }
        });
    }
    return doCreateLogger(logName);
}

From source file:org.apache.hadoop.yarn.client.AHSProxy.java

protected static <T> T getProxy(final Configuration conf, final Class<T> protocol,
        final InetSocketAddress rmAddress) throws IOException {
    return UserGroupInformation.getCurrentUser().doAs(new PrivilegedAction<T>() {
        @Override//  w  w w  . java 2  s.  co m
        public T run() {
            return (T) YarnRPC.create(conf).getProxy(protocol, rmAddress, conf);
        }
    });
}

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

/**
 * Factory method for creating a class loader over the given bundle and with
 * a given class loader as fall-back. In case the bundle cannot find a class
 * or locate a resource, the given class loader will be used as fall back.
 * //from   www.j a  va  2s . c om
 * @param bundle
 *            bundle used for class loading and resource acquisition
 * @param bridge
 *            class loader used as fall back in case the bundle cannot load
 *            a class or find a resource. Can be <code>null</code>
 * @return class loader adapter over the given bundle and class loader
 */
public static BundleDelegatingClassLoader createBundleClassLoaderFor(final Bundle bundle,
        final ClassLoader bridge) {
    return AccessController.doPrivileged(new PrivilegedAction<BundleDelegatingClassLoader>() {

        public BundleDelegatingClassLoader run() {
            return new BundleDelegatingClassLoader(bundle, bridge);
        }
    });
}

From source file:org.apache.axis2.jaxws.utility.XmlEnumUtils.java

/**
 * @param e Class of enum /*  w ww  . j av a  2 s  . c o m*/
 * @return a base type that can be used for constructing the enum
 */
public static Class getConversionType(final Class e) {
    Class cls = null;
    if (log.isDebugEnabled()) {
        log.debug("getConversionType for " + e);
    }
    try {
        cls = (Class) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                // Look for forName method that is generated by JAXB.
                Method m = fromValueMethod(e, String.class);
                if (m != null) {
                    return String.class;
                }

                // If we cannot find forName(String) then look for @XmlEnum value
                // and then look for a forName with the indicated base type
                if (log.isDebugEnabled()) {
                    log.debug("try looking for @XmlEnum ");
                }
                XmlEnum xmlEnum = (XmlEnum) e.getAnnotation(XmlEnum.class);
                if (xmlEnum != null) {
                    Class argClass = xmlEnum.value();
                    m = fromValueMethod(e, argClass);
                    if (m != null) {
                        return argClass;
                    }
                    Class primitiveClass = getPrimitiveClass(argClass);
                    if (primitiveClass != null) {
                        m = fromValueMethod(e, primitiveClass);
                        if (m != null) {
                            return argClass;
                        }
                    }
                }

                // If still not found look for valueOf(String) method
                if (log.isDebugEnabled()) {
                    log.debug("try looking for valueOf method ");
                }
                m = valueOfMethod(e);
                if (m != null) {
                    return String.class;
                }

                throw ExceptionFactory.makeWebServiceException(new IllegalArgumentException());
            }
        });
    } finally {
        if (log.isDebugEnabled()) {
            log.debug("getConversionType is" + cls);
        }
    }
    return cls;
}

From source file:Main.java

/**
 * Get the Thread context class loader./*  w  w w.jav a 2  s  . co m*/
 * <p/>
 *
 * @return the Thread context class loader
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 */
public static ClassLoader getTCL() throws IllegalAccessException, InvocationTargetException {
    return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return Thread.currentThread().getContextClassLoader();
        }
    });
}

From source file:SecuritySupport.java

static ClassLoader getParentClassLoader(final ClassLoader cl) {
    return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            ClassLoader parent = null;
            try {
                parent = cl.getParent();
            } catch (SecurityException ex) {
            }//  ww w  .  j  a v  a  2  s  . c  o m

            // eliminate loops in case of the boot
            // ClassLoader returning itself as a parent
            return (parent == cl) ? null : parent;
        }
    });
}