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:com.citrix.cpbm.portal.fragment.controllers.AbstractProductsController.java

@RequestMapping(value = ("/listDiscriminators"), method = RequestMethod.GET)
@ResponseBody/*from w  ww.j  a  v a  2s .c  o  m*/
public Map<String, Object> listDiscriminators(
        @RequestParam(value = "serviceUsageTypeId", required = true) final Long usageTypeId,
        @RequestParam(value = "serviceInstanceUUID", required = true) final String serviceInstanceUUID) {

    Map<String, Object> finalMap = privilegeService.runAsPortal(new PrivilegedAction<Map<String, Object>>() {

        @Override
        public Map<String, Object> run() {
            Set<ServiceDiscriminator> serviceDiscriminators = new HashSet<ServiceDiscriminator>();
            ServiceInstance serviceInstance = serviceInstanceDao.getServiceInstance(serviceInstanceUUID);
            for (ServiceUsageType serviceUsageType : serviceInstance.getService().getServiceUsageTypes()) {
                if (serviceUsageType.getId().equals(usageTypeId)) {
                    serviceDiscriminators = serviceInstance.getService()
                            .getServiceUsageTypeDiscriminator(serviceUsageType);
                    break;
                }
            }
            Map<String, Object> finalMap = new HashMap<String, Object>();
            for (ServiceDiscriminator serviceDiscriminator : serviceDiscriminators) {
                String discriminatorName = serviceDiscriminator.getDiscriminatorName();
                Map<String, String> discriminatorValuesMap = new HashMap<String, String>();
                discriminatorValuesMap = ((CloudConnector) connectorManagementService
                        .getServiceInstance(serviceInstanceUUID)).getMetadataRegistry()
                                .getDiscriminatorValues(discriminatorName);
                Map<String, Object> discriminatorValMap = new HashMap<String, Object>();
                discriminatorValMap.put("name", discriminatorName);
                discriminatorValMap.put("discriminatorValues", discriminatorValuesMap);
                finalMap.put(serviceDiscriminator.getId().toString(), discriminatorValMap);
            }
            return finalMap;
        }
    });
    return finalMap;
}

From source file:com.inmobi.conduit.distcp.tools.mapred.TestCopyMapper.java

@Test
public void testFailCopyWithAccessControlException() {
    try {/*w  w w.  j a v a  2  s . c  o m*/
        deleteState();
        createSourceData();

        final InMemoryWriter writer = new InMemoryWriter();
        UserGroupInformation tmpUser = UserGroupInformation.createRemoteUser("guest");

        final CopyMapper copyMapper = new CopyMapper();

        final Mapper<Text, FileStatus, NullWritable, Text>.Context context = tmpUser
                .doAs(new PrivilegedAction<Mapper<Text, FileStatus, NullWritable, Text>.Context>() {
                    @Override
                    public Mapper<Text, FileStatus, NullWritable, Text>.Context run() {
                        try {
                            StatusReporter reporter = new StubStatusReporter();
                            return getMapperContext(copyMapper, reporter, writer);
                        } catch (Exception e) {
                            LOG.error("Exception encountered ", e);
                            throw new RuntimeException(e);
                        }
                    }
                });

        EnumSet<DistCpOptions.FileAttribute> preserveStatus = EnumSet.allOf(DistCpOptions.FileAttribute.class);

        context.getConfiguration().set(DistCpConstants.CONF_LABEL_PRESERVE_STATUS,
                DistCpUtils.packAttributes(preserveStatus));

        touchFile(SOURCE_PATH + "/src/file");
        OutputStream out = cluster.getFileSystem().create(new Path(TARGET_PATH + "/src/file"));
        out.write("hello world".getBytes());
        out.close();
        cluster.getFileSystem().setPermission(new Path(SOURCE_PATH + "/src/file"),
                new FsPermission(FsAction.READ, FsAction.READ, FsAction.READ));
        cluster.getFileSystem().setPermission(new Path(TARGET_PATH + "/src/file"),
                new FsPermission(FsAction.READ, FsAction.READ, FsAction.READ));

        final FileSystem tmpFS = tmpUser.doAs(new PrivilegedAction<FileSystem>() {
            @Override
            public FileSystem run() {
                try {
                    return FileSystem.get(configuration);
                } catch (IOException e) {
                    LOG.error("Exception encountered ", e);
                    Assert.fail("Test failed: " + e.getMessage());
                    throw new RuntimeException("Test ought to fail here");
                }
            }
        });

        tmpUser.doAs(new PrivilegedAction<Integer>() {
            @Override
            public Integer run() {
                try {
                    copyMapper.setup(context);
                    copyMapper.map(new Text("/src/file"),
                            tmpFS.getFileStatus(new Path(SOURCE_PATH + "/src/file")), context);
                    Assert.fail("Didn't expect the file to be copied");
                } catch (AccessControlException ignore) {
                } catch (Exception e) {
                    if (e.getCause() == null || !(e.getCause() instanceof AccessControlException)) {
                        throw new RuntimeException(e);
                    }
                }
                return null;
            }
        });
    } catch (Exception e) {
        LOG.error("Exception encountered ", e);
        Assert.fail("Test failed: " + e.getMessage());
    }
}

From source file:org.apache.axis2.jaxws.description.builder.JAXWSRIWSDLGenerator.java

static private Boolean fileExists(final File file) {
    Boolean exists = (Boolean) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return new Boolean(file.exists());
        }/*  www . j a  v a 2s  .c o m*/
    });
    return exists;
}

From source file:org.cruxframework.crux.tools.compile.AbstractCruxCompiler.java

/**
 * //from w  w w  .ja va  2s  .c  o m
 */
private void restoreSecurityManager() {
    AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
        public Boolean run() {
            System.setSecurityManager(originalSecurityManager);
            return true;
        }
    });
}

From source file:org.apache.openjpa.meta.AbstractCFMetaDataFactory.java

/**
 * Parse persistent type names.//from www . j ava2s.  co m
 */
protected Set<String> parsePersistentTypeNames(ClassLoader loader) throws IOException {
    ClassArgParser cparser = newClassArgParser();
    String[] clss;
    Set<String> names = new HashSet<String>();
    if (files != null) {
        File file;
        for (Iterator itr = files.iterator(); itr.hasNext();) {
            file = (File) itr.next();
            if ((AccessController.doPrivileged(J2DoPrivHelper.isDirectoryAction(file))).booleanValue()) {
                if (log.isTraceEnabled())
                    log.trace(_loc.get("scanning-directory", file));
                scan(new FileMetaDataIterator(file, newMetaDataFilter()), cparser, names, true, file);
            } else if (file.getName().endsWith(".jar")) {
                if (log.isTraceEnabled())
                    log.trace(_loc.get("scanning-jar", file));
                try {
                    ZipFile zFile = AccessController.doPrivileged(J2DoPrivHelper.newZipFileAction(file));
                    scan(new ZipFileMetaDataIterator(zFile, newMetaDataFilter()), cparser, names, true, file);
                } catch (PrivilegedActionException pae) {
                    throw (IOException) pae.getException();
                }
            } else {
                if (log.isTraceEnabled())
                    log.trace(_loc.get("scanning-file", file));
                clss = cparser.parseTypeNames(new FileMetaDataIterator(file));
                List<String> newNames = Arrays.asList(clss);
                if (log.isTraceEnabled())
                    log.trace(_loc.get("scan-found-names", newNames, file));
                names.addAll(newNames);
                File f = AccessController.doPrivileged(J2DoPrivHelper.getAbsoluteFileAction(file));
                try {
                    mapPersistentTypeNames(AccessController.doPrivileged(J2DoPrivHelper.toURLAction(f)), clss);
                } catch (PrivilegedActionException pae) {
                    throw (FileNotFoundException) pae.getException();
                }
            }
        }
    }
    URL url;
    if (urls != null) {
        for (Iterator itr = urls.iterator(); itr.hasNext();) {
            url = (URL) itr.next();
            if ("file".equals(url.getProtocol())) {
                File file = AccessController
                        .doPrivileged(J2DoPrivHelper.getAbsoluteFileAction(new File(url.getFile())));
                if (files != null && files.contains(file)) {
                    continue;
                } else if ((AccessController.doPrivileged(J2DoPrivHelper.isDirectoryAction(file)))
                        .booleanValue()) {
                    if (log.isTraceEnabled())
                        log.trace(_loc.get("scanning-directory", file));
                    scan(new FileMetaDataIterator(file, newMetaDataFilter()), cparser, names, true, file);
                    continue;
                }
            }
            if ("vfs".equals(url.getProtocol())) {
                if (log.isTraceEnabled()) {
                    log.trace(_loc.get("scanning-vfs-url", url));
                }

                final URLConnection conn = url.openConnection();
                final Object vfsContent = conn.getContent();
                final URL finalUrl = url;
                File file = AccessController.doPrivileged(new PrivilegedAction<File>() {
                    @SuppressWarnings({ "rawtypes", "unchecked" })
                    public File run() {
                        try {
                            Class virtualFileClass = Class.forName("org.jboss.vfs.VirtualFile");
                            Method getPhysicalFile = virtualFileClass.getDeclaredMethod("getPhysicalFile");
                            return (File) getPhysicalFile.invoke(vfsContent);
                        } catch (Exception e) {
                            log.error(_loc.get("while-scanning-vfs-url", finalUrl), e);
                        }
                        return null;
                    }
                });
                if (file != null)
                    scan(new FileMetaDataIterator(file, newMetaDataFilter()), cparser, names, true, file);

                continue;
            }
            if ("jar".equals(url.getProtocol())) {
                if (url.getPath().endsWith("!/")) {
                    if (log.isTraceEnabled())
                        log.trace(_loc.get("scanning-jar-url", url));
                    scan(new ZipFileMetaDataIterator(url, newMetaDataFilter()), cparser, names, true, url);
                } else {
                    if (log.isTraceEnabled())
                        log.trace(_loc.get("scanning-jar-url", url));
                    scan(new JarFileURLMetaDataIterator(url, newMetaDataFilter()), cparser, names, true, url);
                }
            } else if (url.getPath().endsWith(".jar")) {
                if (log.isTraceEnabled())
                    log.trace(_loc.get("scanning-jar-at-url", url));
                try {
                    InputStream is = (InputStream) AccessController
                            .doPrivileged(J2DoPrivHelper.openStreamAction(url));
                    scan(new ZipStreamMetaDataIterator(new ZipInputStream(is), newMetaDataFilter()), cparser,
                            names, true, url);
                } catch (PrivilegedActionException pae) {
                    throw (IOException) pae.getException();
                }
            } else {
                // Open an InputStream from the URL and sniff for a zip header.  If it is, then this is
                // a URL with a jar-formated InputStream, as per the JPA specification.  Otherwise, fall back
                // to URLMetaDataIterator.
                BufferedInputStream is = null;

                try {
                    is = new BufferedInputStream(
                            (InputStream) AccessController.doPrivileged(J2DoPrivHelper.openStreamAction(url)));
                } catch (PrivilegedActionException pae) {
                    throw (IOException) pae.getException();
                }

                // Check for zip header magic 0x50 0x4b 0x03 0x04
                is.mark(0);
                boolean zipHeaderMatch = is.read() == 0x50 && is.read() == 0x4b && is.read() == 0x03
                        && is.read() == 0x04;
                is.reset();

                if (zipHeaderMatch) {
                    // The URL provides a Jar-formatted InputStream, consume it with ZipStreamMetaDataIterator
                    if (log.isTraceEnabled())
                        log.trace(_loc.get("scanning-jar-at-url", url));
                    scan(new ZipStreamMetaDataIterator(new ZipInputStream(is), newMetaDataFilter()), cparser,
                            names, true, url);
                } else {
                    // Fall back to URLMetaDataIterator
                    if (log.isTraceEnabled())
                        log.trace(_loc.get("scanning-url", url));
                    clss = cparser.parseTypeNames(new URLMetaDataIterator(url));
                    List<String> newNames = Arrays.asList(clss);
                    if (log.isTraceEnabled())
                        log.trace(_loc.get("scan-found-names", newNames, url));
                    names.addAll(newNames);
                    mapPersistentTypeNames(url, clss);
                }
            }
        }
    }
    if (rsrcs != null) {
        String rsrc;
        MetaDataIterator mitr;
        for (Iterator itr = rsrcs.iterator(); itr.hasNext();) {
            rsrc = (String) itr.next();
            if (rsrc.endsWith(".jar")) {
                url = AccessController.doPrivileged(J2DoPrivHelper.getResourceAction(loader, rsrc));
                if (url != null) {
                    if (log.isTraceEnabled())
                        log.trace(_loc.get("scanning-jar-stream-url", url));
                    try {
                        InputStream is = (InputStream) AccessController
                                .doPrivileged(J2DoPrivHelper.openStreamAction(url));
                        scan(new ZipStreamMetaDataIterator(new ZipInputStream(is), newMetaDataFilter()),
                                cparser, names, true, url);
                    } catch (PrivilegedActionException pae) {
                        throw (IOException) pae.getException();
                    }
                }
            } else {
                if (log.isTraceEnabled())
                    log.trace(_loc.get("scanning-resource", rsrc));
                mitr = new ResourceMetaDataIterator(rsrc, loader);
                OpenJPAConfiguration conf = repos.getConfiguration();
                Map peMap = null;
                if (conf instanceof OpenJPAConfigurationImpl)
                    peMap = ((OpenJPAConfigurationImpl) conf).getPersistenceEnvironment();
                URL puUrl = peMap == null ? null : (URL) peMap.get(PERSISTENCE_UNIT_ROOT_URL);
                List<String> mappingFileNames = peMap == null ? null
                        : (List<String>) peMap.get(MAPPING_FILE_NAMES);
                List<URL> jars = peMap == null ? null : (List<URL>) peMap.get(JAR_FILE_URLS);
                String puUrlString = puUrl == null ? null : puUrl.toString();
                if (log.isTraceEnabled())
                    log.trace(_loc.get("pu-root-url", puUrlString));

                URL puORMUrl = null;
                try {
                    if (puUrlString != null) {
                        String puORMUrlStr = puUrlString + (puUrlString.endsWith("/") ? "" : "/") + rsrc;
                        puORMUrl = AccessController.doPrivileged(J2DoPrivHelper.createURL(puORMUrlStr));
                    }
                } catch (PrivilegedActionException e) {
                    throw new IOException("Error generating puORMUrlStr.", e.getCause());
                }

                List<URL> urls = new ArrayList<URL>(3);
                while (mitr.hasNext()) {
                    url = (URL) mitr.next();
                    String urlString = url.toString();
                    if (log.isTraceEnabled())
                        log.trace(_loc.get("resource-url", urlString));
                    if (peMap != null) {
                        //OPENJPA-2102: decode the URL to remove such things a spaces (' ') encoded as '%20'
                        if (puUrlString != null && decode(urlString).indexOf(decode(puUrlString)) != -1) {
                            urls.add(url);
                        } else if (puORMUrl != null && puORMUrl.equals(url)) {
                            // Check URL equality to support encapsulating URL protocols
                            urls.add(url);
                        }
                        if (mappingFileNames != null && mappingFileNames.size() != 0) {
                            for (String mappingFileName : mappingFileNames) {
                                if (log.isTraceEnabled())
                                    log.trace(_loc.get("mapping-file-name", mappingFileName));
                                if (urlString.indexOf(mappingFileName) != -1)
                                    urls.add(url);
                            }
                        }

                        if (jars != null && jars.size() != 0) {
                            for (URL jarUrl : jars) {
                                if (log.isTraceEnabled())
                                    log.trace(_loc.get("jar-file-url", jarUrl));
                                if (urlString.indexOf(jarUrl.toString()) != -1)
                                    urls.add(url);
                            }
                        }
                    } else {
                        urls.add(url);
                    }
                }
                mitr.close();

                for (Object obj : urls) {
                    url = (URL) obj;
                    clss = cparser.parseTypeNames(new URLMetaDataIterator(url));
                    List<String> newNames = Arrays.asList(clss);
                    if (log.isTraceEnabled())
                        log.trace(_loc.get("scan-found-names", newNames, rsrc));
                    names.addAll(newNames);
                    mapPersistentTypeNames(url, clss);
                }
            }
        }
    }
    if (cpath != null) {
        String[] dirs = (String[]) cpath.toArray(new String[cpath.size()]);
        scan(new ClasspathMetaDataIterator(dirs, newMetaDataFilter()), cparser, names, true, dirs);
    }
    if (types != null)
        names.addAll(types);

    if (log.isTraceEnabled())
        log.trace(_loc.get("parse-found-names", names));

    return names;
}

From source file:org.cruxframework.crux.tools.compile.AbstractCruxCompiler.java

/**
 * //  w  ww  .j ava 2  s.  c  o  m
 */
private void setSecurityManagerToAvoidSystemExit() {
    AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
        public Boolean run() {
            originalSecurityManager = System.getSecurityManager();
            System.setSecurityManager(new SecurityManager() {

                @Override
                public void checkExit(int status) {
                    if (status == 0) {
                        throw new DoNotExitException();
                    }
                    super.checkExit(status);
                }

                @Override
                public void checkPermission(Permission perm) {
                }

                @Override
                public void checkPermission(Permission perm, Object context) {
                }
            });
            return true;
        }
    });
}

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

@RequestMapping(value = "/reset_password", method = RequestMethod.GET, params = "a")
public String reset(@RequestParam(value = "a", required = true) final String auth,
        @RequestParam(value = "t", required = true) final long ts,
        @RequestParam(value = "i", required = true) final String userParam, HttpSession session, ModelMap map) {
    logger.debug("###Entering in reset(auth,ts,userId,session) method @GET");

    Random rnd = new Random();
    int n = 99999 - 1000;
    session.setAttribute("phoneVerificationPin", "" + rnd.nextInt(n));

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

        @Override//from   w w  w  .  j  av  a  2 s . c  o  m
        public User run() {
            User user = userService.get(userParam);
            userService.verifyAuthorization(user, auth, ts);
            return user;
        }
    });

    // Whether telesign is enabled and the user is master user?
    boolean isTelesignVerificationEnable = false;
    if ((TelephoneVerificationService) connectorManagementService
            .getOssServiceInstancebycategory(ConnectorType.PHONE_VERIFICATION) != null) {
        isTelesignVerificationEnable = ((TelephoneVerificationService) connectorManagementService
                .getOssServiceInstancebycategory(ConnectorType.PHONE_VERIFICATION)).isEnabled()
                && user.equals(user.getTenant().getOwner());
    }

    map.addAttribute("isTelesignVerificationEnable", isTelesignVerificationEnable);
    session.setAttribute(RESET_USER_KEY, user.getUsername());
    logger.debug("###Exiting in reset(auth,ts,userId,session) method @GET");
    return "auth.reset";
}

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

@RequestMapping(value = "/reset_password", method = RequestMethod.POST, params = "password")
public String reset(@RequestParam(value = "password", required = true) final String password,
        HttpSession session) {/*from   w  w  w  .ja  v a2  s .  c  o m*/
    logger.debug("###Entering in reset(password,session) method @POST");
    final String username = (String) session.getAttribute(RESET_USER_KEY);
    final int maxFailCount = config
            .getIntValue(Names.com_citrix_cpbm_accountManagement_security_logins_lockThreshold);

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

        @Override
        public User run() {
            User user = userService.getUserByParam("username", username, false);
            if (!config.getBooleanValue(Configuration.Names.com_citrix_cpbm_portal_directory_service_enabled)) {
                user.setClearPassword(password);
            } else if (config.getValue(Names.com_citrix_cpbm_directory_mode).equals("push")) {
                userService.updateUserPassword(password, user.getUuid());
            }
            if (!user.isEnabled() || user.getFailedLoginAttempts() >= maxFailCount) {
                user.setFailedLoginAttempts(0);
                user.setEnabled(true);
            }
            return user;
        }
    });
    // Looks out of place, but useful.
    if (user.getFailedLoginAttempts() >= config
            .getIntValue(Names.com_citrix_cpbm_accountManagement_security_logins_captchaThreshold)) {
        session.setAttribute(CaptchaAuthenticationFilter.CAPTCHA_REQUIRED, true);
    }

    session.removeAttribute(RESET_USER_KEY);
    logger.debug("###Exiting in reset(password,session) method @POST");
    return "redirect:/portal/login";
}

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

@RequestMapping(value = { "/getFilterComponents" }, method = RequestMethod.GET)
@ResponseBody//from   w  w  w  .j a va 2 s .  co  m
public List<FilterComponent> getFilterComponents(@ModelAttribute("currentTenant") Tenant currentTenant,
        @RequestParam(value = "tenant", required = false) String tenantParam,
        @RequestParam(value = "serviceInstanceUuid", required = true) final String serviceInstanceUuid,
        @RequestParam(value = "filterType", required = true) final String filterType,
        @RequestParam(value = "viewCatalog", required = false, defaultValue = "false") Boolean viewCatalog,
        HttpServletRequest request) throws ConnectorManagementServiceException {
    List<FilterComponent> filterComponents = new ArrayList<FilterComponent>();
    if (getCurrentUser() == null
            || (viewCatalog == true && getCurrentUser().getTenant().equals(tenantService.getSystemTenant()))) {
        filterComponents = privilegeService.runAsPortal(new PrivilegedAction<List<FilterComponent>>() {

            @Override
            public List<FilterComponent> run() {
                return ((CloudConnector) connectorManagementService.getServiceInstance(serviceInstanceUuid))
                        .getMetadataRegistry().getFilterValues(
                                tenantService.getTenantHandle(tenantService.getSystemTenant().getUuid(),
                                        serviceInstanceUuid).getHandle(),
                                userService.getUserHandleByServiceInstanceUuid(
                                        tenantService.getSystemUser(Handle.PORTAL).getUuid(),
                                        serviceInstanceUuid).getHandle(),
                                filterType);
            }
        });

    } else {

        User user = getCurrentUser();
        Tenant effectiveTenant = (Tenant) request.getAttribute(UserContextInterceptor.EFFECTIVE_TENANT_KEY);
        if ((Boolean) request.getAttribute("isSurrogatedTenant")) {
            user = effectiveTenant.getOwner();
        }

        String userHandle = userService.getUserHandleByServiceInstanceUuid(user.getUuid(), serviceInstanceUuid)
                .getHandle();

        filterComponents = ((CloudConnector) connectorManagementService.getServiceInstance(serviceInstanceUuid))
                .getMetadataRegistry().getFilterValues(tenantService
                        .getTenantHandle(effectiveTenant.getUuid(), serviceInstanceUuid).getHandle(),
                        userHandle, filterType);
    }
    return filterComponents;
}