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:org.apache.hadoop.ha.ZKFailoverController.java

public int run(final String[] args) throws Exception {
    if (!localTarget.isAutoFailoverEnabled()) {
        LOG.fatal("Automatic failover is not enabled for " + localTarget + "."
                + " Please ensure that automatic failover is enabled in the "
                + "configuration before running the ZK failover controller.");
        return ERR_CODE_AUTO_FAILOVER_NOT_ENABLED;
    }//from  ww w.  jav a  2s  .c  o m
    loginAsFCUser();
    try {
        return SecurityUtil.doAsLoginUserOrFatal(new PrivilegedAction<Integer>() {
            @Override
            public Integer run() {
                try {
                    return doRun(args);
                } catch (Exception t) {
                    throw new RuntimeException(t);
                } finally {
                    if (elector != null) {
                        elector.terminateConnection();
                    }
                }
            }
        });
    } catch (RuntimeException rte) {
        LOG.fatal("The failover controller encounters runtime error: " + rte);
        throw (Exception) rte.getCause();
    }
}

From source file:graphql.servlet.GraphQLServlet.java

private void query(String query, String operationName, Map<String, Object> variables, GraphQLSchema schema,
        HttpServletRequest req, HttpServletResponse resp, GraphQLContext context) throws IOException {
    if (Subject.getSubject(AccessController.getContext()) == null && context.getSubject().isPresent()) {
        Subject.doAs(context.getSubject().get(), new PrivilegedAction<Void>() {
            @Override//from   w w w  . j  a v  a2  s.  c o m
            @SneakyThrows
            public Void run() {
                query(query, operationName, variables, schema, req, resp, context);
                return null;
            }
        });
    } else {
        Map<String, Object> vars = transformVariables(schema, query, variables);
        operationListeners.forEach(l -> l.beforeGraphQLOperation(context, operationName, query, vars));

        ExecutionResult result = new GraphQL(schema, getExecutionStrategy()).execute(query, operationName,
                context, vars);
        resp.setContentType("application/json;charset=utf-8");
        if (result.getErrors().isEmpty()) {
            Map<String, Object> dict = new HashMap<>();
            dict.put("data", result.getData());
            resp.getWriter().write(new ObjectMapper().writeValueAsString(dict));
            operationListeners.forEach(
                    l -> l.onSuccessfulGraphQLOperation(context, operationName, query, vars, result.getData()));
        } else {
            resp.setStatus(500);
            List<GraphQLError> errors = getGraphQLErrors(result);
            Map<String, Object> dict = new HashMap<>();
            dict.put("errors", errors);

            resp.getWriter().write(new ObjectMapper().writeValueAsString(dict));
            operationListeners.forEach(
                    l -> l.onFailedGraphQLOperation(context, operationName, query, vars, result.getErrors()));
        }
    }
}

From source file:SecuritySupport.java

boolean getFileExists(final File f) {
    return ((Boolean) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return new Boolean(f.exists());
        }//from  w  w  w  .java 2s . c  o  m
    })).booleanValue();
}

From source file:org.perfcake.util.ObjectFactory.java

/**
 * Gets a dedicated class loader for loading plugins.
 *
 * @return Plugin class loader./*  w w  w.  j ava  2  s.co m*/
 */
protected static ClassLoader getPluginClassLoader() {
    if (pluginClassLoader == null) {
        final ClassLoader currentClassLoader = ObjectFactory.class.getClassLoader();
        final String pluginsDirProp = Utils.getProperty(PerfCakeConst.PLUGINS_DIR_PROPERTY);
        if (pluginsDirProp == null) {
            return currentClassLoader;
        }

        final File pluginsDir = new File(pluginsDirProp);
        final File[] plugins = pluginsDir.listFiles(new FileExtensionFilter(".jar"));

        if ((plugins == null) || (plugins.length == 0)) {
            return currentClassLoader;
        }

        final URL[] pluginURLs = new URL[plugins.length];
        for (int i = 0; i < plugins.length; i++) {
            try {
                pluginURLs[i] = plugins[i].toURI().toURL();
            } catch (final MalformedURLException e) {
                log.warn(String.format("Cannot resolve path to plugin '%s', skipping this file", plugins[i]));
            }
        }

        AccessController.doPrivileged(new PrivilegedAction<Void>() {
            public Void run() {
                pluginClassLoader = new URLClassLoader(pluginURLs, currentClassLoader);
                return null;
            }
        });
    }

    return pluginClassLoader;
}

From source file:org.nebulaframework.grid.cluster.node.services.job.execution.TaskExecutor.java

/**
 * Creates the ClassLoader to be used for remote class loading.
 * //  w  ww  .j a v  a  2s  .co  m
 * @param jobId JobId
 * @param classLoadingService Remote Class Loading Service Proxy
 * @param archive GridArchive, if available (or null)
 * @return ClassLoader instance
 */
private static ClassLoader createClassLoader(final String jobId, final ClassLoadingService classLoadingService,
        final GridArchive archive) {

    ClassLoader classLoader = null;

    // Configure Thread Context Class Loader to use
    // GridNodeClassLoader

    final ClassLoader nodeClassLoader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {

        public ClassLoader run() {
            ClassLoader current = Thread.currentThread().getContextClassLoader();
            return new GridNodeClassLoader(jobId, classLoadingService, current);
        }
    });

    classLoader = nodeClassLoader;

    // If its an archived Job, configure to use
    // GridArchvieClassLoader
    // chained to GridNodeClassLoader
    if (archive != null) {

        ClassLoader archiveLoader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {

            public ClassLoader run() {
                // Archive Class Loader
                return new GridArchiveClassLoader(archive, nodeClassLoader);
            }
        });
        classLoader = archiveLoader;
    }

    return classLoader;
}

From source file:com.tmind.framework.pub.utils.MethodUtils.java

private static synchronized Method[] getPublicDeclaredMethods(Class clz) {
    // Looking up Class.getDeclaredMethods is relatively expensive,
    // so we cache the results.
    final Class fclz = clz;
    Method[] result = (Method[]) declaredMethodCache.get(fclz);
    if (result != null) {
        return result;
    }//  w  w  w. j  a v  a2  s . c o m

    // We have to raise privilege for getDeclaredMethods
    result = (Method[]) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            try {

                return fclz.getDeclaredMethods();

            } catch (SecurityException ex) {
                // this means we're in a limited security environment
                // so let's try going through the public methods
                // and null those those that are not from the declaring
                // class
                Method[] methods = fclz.getMethods();
                for (int i = 0, size = methods.length; i < size; i++) {
                    Method method = methods[i];
                    if (!(fclz.equals(method.getDeclaringClass()))) {
                        methods[i] = null;
                    }
                }
                return methods;
            }
        }
    });

    // Null out any non-public methods.
    for (int i = 0; i < result.length; i++) {
        Method method = result[i];
        if (method != null) {
            int mods = method.getModifiers();
            if (!Modifier.isPublic(mods)) {
                result[i] = null;
            }
        }
    }

    // Add it to the cache.
    declaredMethodCache.put(clz, result);
    return result;
}

From source file:org.apache.axis2.jaxws.util.WSDL4JWrapper.java

private void commonPartsURLConstructor(URL wsdlURL, ConfigurationContext configContext)
        throws FileNotFoundException, UnknownHostException, ConnectException, IOException, WSDLException {
    this.configContext = configContext;
    // debugMemoryParms(configContext);
    if (log.isDebugEnabled()) {
        log.debug("WSDL4JWrapper(URL,ConfigurationContext) - Looking for wsdl file on client: "
                + (wsdlURL != null ? wsdlURL.getPath() : null));
    }//from   ww  w  .jav a2s  .c  om
    ClassLoader classLoader = (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return Thread.currentThread().getContextClassLoader();
        }
    });
    this.wsdlURL = wsdlURL;

    URLConnection urlCon;
    try {

        urlCon = getPrivilegedURLConnection(this.wsdlURL);

        InputStream is = null;

        try {
            is = getInputStream(urlCon);
        } catch (IOException e) {
            if (log.isDebugEnabled()) {
                log.debug("Could not open url connection. Trying to use " + "classloader to get another URL.");
            }
            String filePath = wsdlURL != null ? wsdlURL.getPath() : null;
            if (filePath != null) {
                URL url = getAbsoluteURL(classLoader, filePath);
                if (url == null) {
                    if (log.isDebugEnabled()) {
                        log.debug("Could not locate URL for wsdl. Reporting error");
                    }
                    throw new WSDLException("WSDL4JWrapper : ", e.getMessage(), e);
                } else {
                    urlCon = openConnection(url);
                    if (log.isDebugEnabled()) {
                        log.debug("Found URL for WSDL from jar");
                    }
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Could not get URL from classloader. Reporting " + "error due to no file path.");
                }
                throw new WSDLException("WSDL4JWrapper : ", e.getMessage(), e);
            }
        }
        if (is != null) {
            is.close();
        }
        this.wsdlExplicitURL = urlCon.getURL().toString();
        getDefinition();
    } catch (FileNotFoundException ex) {
        throw ex;
    } catch (UnknownHostException ex) {
        throw ex;
    } catch (ConnectException ex) {
        throw ex;
    } catch (IOException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new WSDLException("WSDL4JWrapper : ", ex.getMessage(), ex);
    }
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractAuthenticationController.java

@RequestMapping({ "/login", "/portal", "/" })
public String login(HttpServletRequest request, ModelMap map, HttpSession session) {
    logger.debug("###Entering in login(req,map,session) method");

    boolean loginFailed = request.getParameter(LOGIN_FAILED_PARAM) != null;

    if (!loginFailed && request.getUserPrincipal() != null) {
        map.clear();//from   w  w  w.  j a va  2 s . com
        return "redirect:/portal/home";
    }

    if (session.getAttribute("email_verified") != null) {
        map.addAttribute("email_verified", session.getAttribute("email_verified"));
        session.removeAttribute("email_verified");
    }
    String showSuffixControl = "false";
    String suffixControlType = "textbox";
    List<String> suffixList = null;
    if (config.getValue(Names.com_citrix_cpbm_username_duplicate_allowed).equals("true")) {
        showSuffixControl = "true";
        if (config.getValue(Names.com_citrix_cpbm_login_screen_tenant_suffix_dropdown_enabled).equals("true")) {
            suffixControlType = "dropdown";
            suffixList = tenantService.getSuffixList();
        }
    }
    map.addAttribute("showSuffixControl", showSuffixControl);
    map.addAttribute("suffixControlType", suffixControlType);
    map.addAttribute("suffixList", suffixList);
    if (config.getBooleanValue(Configuration.Names.com_citrix_cpbm_portal_directory_service_enabled)
            && config.getValue(Names.com_citrix_cpbm_directory_mode).equals("pull")) {
        map.addAttribute("directoryServiceAuthenticationEnabled", "true");
    }
    if (config.getValue(Names.com_citrix_cpbm_public_catalog_display).equals("true")
            && channelService.getDefaultServiceProviderChannel() != null) {
        map.addAttribute("showAnonymousCatalogBrowsing", "true");
    }
    map.addAttribute("showLanguageSelection", "true");
    map.addAttribute("supportedLocaleList", this.getLocaleDisplayName(listSupportedLocales()));
    map.addAttribute("selected_language", request.getParameter("lang"));
    String redirect = null;
    boolean loggedOut = request.getParameter(LOGOUT_PARAM) != null;
    final Throwable ex = (Throwable) session.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);

    // capture previous CAPTCHA position
    Boolean captchaRequiredSessionObj = (Boolean) session
            .getAttribute(CaptchaAuthenticationFilter.CAPTCHA_REQUIRED);

    // Get last user
    String username = (String) session
            .getAttribute(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_LAST_USERNAME_KEY);

    // this as spring does a text-escape when it saves this attribute
    final String uUsername = HtmlUtils.htmlUnescape(username);

    if (loginFailed) {
        String error = " "
                + messageSource.getMessage("error.auth.username.password.invalid", null, request.getLocale());

        try {
            User user = privilegeService.runAsPortal(new PrivilegedAction<User>() {

                @Override
                public User run() {
                    User user = userService.getUserByParam("username", uUsername, false);

                    // All user writes here.
                    // Every time there is a login failure but not invalid CAPTCHA,
                    // we update failed login attempts for the user
                    if (!(ex instanceof CaptchaValidationException) && !(ex instanceof LockedException)
                            && !(ex instanceof IpRangeValidationException)) {
                        user.setFailedLoginAttempts(user.getFailedLoginAttempts() + 1);
                    }

                    int attempts = user.getFailedLoginAttempts();

                    // Also locking the root user and quite easily too. Clearly this
                    // needs an eye!
                    if (attempts >= config.getIntValue(
                            Names.com_citrix_cpbm_accountManagement_security_logins_lockThreshold)) {
                        user.setEnabled(false);
                    }

                    return user;
                }
            });

            int attempts = user.getFailedLoginAttempts();
            if (attempts >= config
                    .getIntValue(Names.com_citrix_cpbm_accountManagement_security_logins_captchaThreshold)) {
                session.setAttribute(CaptchaAuthenticationFilter.CAPTCHA_REQUIRED, true);
            }
        } catch (NoSuchUserException e) {
            // map.addAttribute("showCaptcha", true);
        }

        captchaRequiredSessionObj = (Boolean) session
                .getAttribute(CaptchaAuthenticationFilter.CAPTCHA_REQUIRED);

        map.addAttribute("loginFailed", loginFailed);
        String lastUsername = uUsername;

        if (config.getValue(Names.com_citrix_cpbm_username_duplicate_allowed).equals("true")) {
            if (!lastUsername.equals("root") && !lastUsername.equals("")) {
                lastUsername = lastUsername.substring(0, lastUsername.lastIndexOf('@'));
            }
        }
        map.addAttribute("lastUser", lastUsername);

        // Compose error string
        if (ex instanceof DisabledException) {
            error = " " + messageSource.getMessage("error.auth.username.password.invalid", null,
                    request.getLocale());
        } else if (ex instanceof CaptchaValidationException) {
            error = " " + messageSource.getMessage("error.auth.captcha.invalid", null, request.getLocale());
        } else if (ex instanceof IpRangeValidationException) {
            error = " " + messageSource.getMessage("error.auth.username.password.invalid", null,
                    request.getLocale());
        } else if (ex instanceof LockedException) {
            error = " " + messageSource.getMessage("error.auth.username.password.invalid", null,
                    request.getLocale());
        } else if (ex instanceof BadCredentialsException) {
            if (ex.getMessage() != null && ex.getMessage().length() > 0) {
                // error = " " + ex.getMessage();
                error = " " + messageSource.getMessage("error.auth.username.password.invalid", null,
                        request.getLocale());
            }
        } else if (ex instanceof AuthenticationException) {
            error = " " + messageSource.getMessage("error.auth.username.password.invalid", null,
                    request.getLocale());
        } else {
            logger.error("Error occurred in authentication", ex);
            error = " " + messageSource.getMessage("error.auth.unknown", null, request.getLocale());
        }

        if (captchaRequiredSessionObj != null && captchaRequiredSessionObj == true
                && !(ex instanceof CaptchaValidationException) && !(ex instanceof LockedException)) {
            error += " " + messageSource.getMessage("error.auth.account.may.locked", null, request.getLocale());
        }

        map.addAttribute("error", error);

    }

    if (loggedOut) {
        map.addAttribute("logout", loggedOut);
    }

    // This could come from session or from user
    if (captchaRequiredSessionObj != null && captchaRequiredSessionObj.booleanValue()
            && !Boolean.valueOf(config.getValue(Names.com_citrix_cpbm_use_intranet_only))) {
        map.addAttribute("showCaptcha", true);
        map.addAttribute("recaptchaPublicKey", config.getRecaptchaPublicKey());
    }

    map.addAttribute(TIME_OUT, request.getParameter(TIME_OUT) != null);
    map.addAttribute(VERIFY, request.getParameter(VERIFY) != null);
    logger.debug("###Exiting login(req,map,session) method");

    if (config.getAuthenticationService().compareToIgnoreCase(CAS) == 0) {
        try {
            redirect = StringUtils.isEmpty(config.getCasLoginUrl()) ? null
                    : config.getCasLoginUrl() + "?service="
                            + URLEncoder.encode(config.getCasServiceUrl(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("Exception encoding: " + redirect, e);
        }
        if (redirect == null) {
            throw new InternalError("CAS authentication required, but login url not set");
        }
    }
    return redirect == null ? "auth.login" : "redirect:" + redirect;
}

From source file:org.mule.util.ClassUtils.java

/**
 * Load a class with a given name. <p/> It will try to load the class in the
 * following order:/*from  w w w.ja  v a 2 s  . c o m*/
 * <ul>
 * <li>From
 * {@link Thread#getContextClassLoader() Thread.currentThread().getContextClassLoader()}
 * <li>Using the basic {@link Class#forName(java.lang.String) }
 * <li>From
 * {@link Class#getClassLoader() ClassLoaderUtil.class.getClassLoader()}
 * <li>From the {@link Class#getClassLoader() callingClass.getClassLoader() }
 * </ul>
 *
 * @param className    The name of the class to load
 * @param callingClass The Class object of the calling object
 * @param type the class type to expect to load
 * @return The Class instance
 * @throws ClassNotFoundException If the class cannot be found anywhere.
 */
public static <T extends Class> T loadClass(final String className, final Class<?> callingClass, T type)
        throws ClassNotFoundException {
    if (className.length() <= 8) {
        // Could be a primitive - likely.
        if (primitiveTypeNameMap.containsKey(className)) {
            return (T) primitiveTypeNameMap.get(className);
        }
    }

    Class<?> clazz = AccessController.doPrivileged(new PrivilegedAction<Class<?>>() {
        public Class<?> run() {
            try {
                final ClassLoader cl = Thread.currentThread().getContextClassLoader();
                return cl != null ? cl.loadClass(className) : null;

            } catch (ClassNotFoundException e) {
                return null;
            }
        }
    });

    if (clazz == null) {
        clazz = AccessController.doPrivileged(new PrivilegedAction<Class<?>>() {
            public Class<?> run() {
                try {
                    return Class.forName(className);
                } catch (ClassNotFoundException e) {
                    return null;
                }
            }
        });
    }

    if (clazz == null) {
        clazz = AccessController.doPrivileged(new PrivilegedAction<Class<?>>() {
            public Class<?> run() {
                try {
                    return ClassUtils.class.getClassLoader().loadClass(className);
                } catch (ClassNotFoundException e) {
                    return null;
                }
            }
        });
    }

    if (clazz == null) {
        clazz = AccessController.doPrivileged(new PrivilegedAction<Class<?>>() {
            public Class<?> run() {
                try {
                    return callingClass.getClassLoader().loadClass(className);
                } catch (ClassNotFoundException e) {
                    return null;
                }
            }
        });
    }

    if (clazz == null) {
        throw new ClassNotFoundException(className);
    }

    if (type.isAssignableFrom(clazz)) {
        return (T) clazz;
    } else {
        throw new IllegalArgumentException(String.format("Loaded class '%s' is not assignable from type '%s'",
                clazz.getName(), type.getName()));
    }
}

From source file:org.apache.axis2.receivers.AbstractMessageReceiver.java

protected void restoreThreadContext(final ThreadContextDescriptor tc) {
    org.apache.axis2.java.security.AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            Thread.currentThread().setContextClassLoader(tc.oldClassLoader);
            return null;
        }//  w  ww  .j  a v a2s .c  o  m
    });
    MessageContext.currentMessageContext.set(tc.oldMessageContext);
}