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.glassfish.common.util.admin.MapInjectionResolver.java

/**
 * Get the value of the field.  This value is defined in the
 * annotated Param declaration.  For example:
 * <code>/*from   ww  w  . j  a  v  a2 s . co  m*/
 * @Param(optional=true)
 * String name="server"
 * </code>
 * The Field, name's value, "server" is returned.
 *
 * @param component command class object
 * @param annotated annotated element
 * @return the annotated Field value
 */
// package-private, for testing
static Object getParamField(final Object component, final AnnotatedElement annotated) {
    try {
        if (annotated instanceof Field) {
            final Field field = (Field) annotated;
            AccessController.doPrivileged(new PrivilegedAction<Object>() {
                @Override
                public Object run() {
                    field.setAccessible(true);
                    return null;
                }
            });
            return ((Field) annotated).get(component);
        }
    } catch (Exception e) {
        // unable to get the field value, may not be defined
        // return null instead.
        return null;
    }
    return null;
}

From source file:org.apache.hadoop.tools.mapred.TestCopyMapper.java

@Test(timeout = 40000)
public void testPreserve() {
    try {// ww  w .  j a  va 2  s .c  o m
        deleteState();
        createSourceData();

        try {
            UsersGroups.addUser("guest");
        } catch (UserAlreadyExistsException e) {
        }
        UserGroupInformation tmpUser = UserGroupInformation.createRemoteUser("guest");

        final CopyMapper copyMapper = new CopyMapper();

        final Mapper<Text, CopyListingFileStatus, Text, Text>.Context context = tmpUser
                .doAs(new PrivilegedAction<Mapper<Text, CopyListingFileStatus, Text, Text>.Context>() {
                    @Override
                    public Mapper<Text, CopyListingFileStatus, Text, Text>.Context run() {
                        try {
                            StubContext stubContext = new StubContext(getConfiguration(), null, 0);
                            return stubContext.getContext();
                        } catch (Exception e) {
                            LOG.error("Exception encountered ", e);
                            throw new RuntimeException(e);
                        }
                    }
                });

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

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

        touchFile(SOURCE_PATH + "/src/file");
        mkdirs(TARGET_PATH);
        cluster.getFileSystem().setPermission(new Path(TARGET_PATH), new FsPermission((short) 511));

        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"),
                            new CopyListingFileStatus(tmpFS.getFileStatus(new Path(SOURCE_PATH + "/src/file"))),
                            context);
                    Assert.fail("Expected copy to fail");
                } catch (AccessControlException e) {
                    Assert.assertTrue("Got exception: " + e.getMessage(), true);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                return null;
            }
        });
    } catch (Exception e) {
        LOG.error("Exception encountered ", e);
        Assert.fail("Test failed: " + e.getMessage());
    }
}

From source file:org.kitesdk.spring.hbase.example.service.WebPageSnapshotService.java

/**
 * Return a WebPageRedirectModel if an URL is one that redirects to a
 * different source. Otherwise, returns null.
 *
 * @return The WebPageRedirectModel/*from w  ww.  ja va2  s .  co m*/
 */
private WebPageRedirectModel getRedirect(final String url, final String user) throws IOException {
    UserGroupInformation ugi = UserGroupInformation.createProxyUser(user, UserGroupInformation.getLoginUser());

    return ugi.doAs(new PrivilegedAction<WebPageRedirectModel>() {

        @Override
        public WebPageRedirectModel run() {
            Key key = new Key.Builder(webPageRedirectModels(user)).add("url", url).build();
            return webPageRedirectModels(user).get(key);
        }
    });
}

From source file:org.apache.ranger.biz.KmsKeyMgr.java

public VXKmsKey createKey(String provider, VXKmsKey vXKey) throws Exception {
    String providers[] = null;//from   w  w w  .  j  ava  2 s .co m
    try {
        providers = getKMSURL(provider);
    } catch (Exception e) {
        logger.error("createKey(" + provider + ", " + vXKey.getName() + ") failed", e);
    }
    VXKmsKey ret = null;
    boolean isKerberos = false;
    try {
        isKerberos = checkKerberos();
    } catch (Exception e1) {
        logger.error("checkKerberos(" + provider + ") failed", e1);
    }
    if (providers != null) {
        for (int i = 0; i < providers.length; i++) {
            Client c = getClient();
            String currentUserLoginId = ContextUtil.getCurrentUserLoginId();
            String uri = providers[i]
                    + (providers[i].endsWith("/") ? KMS_ADD_KEY_URI : ("/" + KMS_ADD_KEY_URI));
            if (!isKerberos) {
                uri = uri.concat("?user.name=" + currentUserLoginId);
            } else {
                uri = uri.concat("?doAs=" + currentUserLoginId);
            }
            final WebResource r = c.resource(uri);
            Gson gson = new GsonBuilder().create();
            final String jsonString = gson.toJson(vXKey);
            try {
                String response = null;
                if (!isKerberos) {
                    response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE)
                            .post(String.class, jsonString);
                } else {
                    Subject sub = getSubjectForKerberos(provider);
                    response = Subject.doAs(sub, new PrivilegedAction<String>() {
                        @Override
                        public String run() {
                            return r.accept(MediaType.APPLICATION_JSON_TYPE)
                                    .type(MediaType.APPLICATION_JSON_TYPE).post(String.class, jsonString);
                        }
                    });
                }
                logger.debug("Create RESPONSE: [" + response + "]");
                ret = gson.fromJson(response, VXKmsKey.class);
                return ret;
            } catch (Exception e) {
                if (e instanceof UniformInterfaceException || i == providers.length - 1)
                    throw e;
                else
                    continue;
            }
        }
    }
    return ret;
}

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

/**
 * @param username//from w  w  w. j a v a2  s .  c o m
 * @return
 */
private boolean isValidUserName(final String username) {
    try {
        privilegeService.runAsPortal(new PrivilegedAction<Void>() {

            @Override
            public Void run() {
                userService.getUserByParam("username", username, false);
                return null;
            }
        });
    } catch (NoSuchUserException ex) {
        return Boolean.TRUE;
    }
    return Boolean.FALSE;
}

From source file:org.apache.ranger.services.hbase.client.HBaseClient.java

public List<String> getColumnFamilyList(final String columnFamilyMatching, final List<String> tableList,
        final List<String> existingColumnFamilies) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> HbaseClient.getColumnFamilyList()  columnFamilyMatching " + columnFamilyMatching
                + " ExisitingTableList " + tableList + "existingColumnFamilies " + existingColumnFamilies);
    }//from  w ww.  ja  v a  2s .c  o  m

    List<String> ret = null;
    final String errMsg = " You can still save the repository and start creating "
            + "policies, but you would not be able to use autocomplete for "
            + "resource names. Check ranger_admin.log for more info.";

    subj = getLoginSubject();
    if (subj != null) {
        try {

            ret = Subject.doAs(subj, new PrivilegedAction<List<String>>() {
                String tblName = null;

                @Override
                public List<String> run() {
                    List<String> colfList = new ArrayList<String>();
                    HBaseAdmin admin = null;
                    try {
                        LOG.info("getColumnFamilyList: setting config values from client");
                        setClientConfigValues(conf);
                        LOG.info("getColumnFamilyList: checking HbaseAvailability with the new config");
                        HBaseAdmin.checkHBaseAvailable(conf);
                        LOG.info("getColumnFamilyList: no exception: HbaseAvailability true");
                        admin = new HBaseAdmin(conf);
                        if (tableList != null) {
                            for (String tableName : tableList) {
                                tblName = tableName;
                                HTableDescriptor htd = admin.getTableDescriptor(tblName.getBytes());
                                if (htd != null) {
                                    for (HColumnDescriptor hcd : htd.getColumnFamilies()) {
                                        String colf = hcd.getNameAsString();
                                        if (colf.matches(columnFamilyMatching)) {
                                            if (existingColumnFamilies != null
                                                    && existingColumnFamilies.contains(colf)) {
                                                continue;
                                            } else {
                                                colfList.add(colf);
                                            }

                                        }
                                    }
                                }
                            }
                        }
                    } catch (ZooKeeperConnectionException zce) {
                        String msgDesc = "getColumnFamilyList: Unable to connect to `ZooKeeper` "
                                + "using given config parameters.";
                        HadoopException hdpException = new HadoopException(msgDesc, zce);
                        hdpException.generateResponseDataMap(false, getMessage(zce), msgDesc + errMsg, null,
                                null);
                        LOG.error(msgDesc + zce);
                        throw hdpException;

                    } catch (MasterNotRunningException mnre) {
                        String msgDesc = "getColumnFamilyList: Looks like `Master` is not running, "
                                + "so couldn't check that running HBase is available or not, "
                                + "Please try again later.";
                        HadoopException hdpException = new HadoopException(msgDesc, mnre);
                        hdpException.generateResponseDataMap(false, getMessage(mnre), msgDesc + errMsg, null,
                                null);
                        LOG.error(msgDesc + mnre);
                        throw hdpException;

                    } catch (IOException io) {
                        String msgDesc = "getColumnFamilyList: Unable to get HBase ColumnFamilyList for "
                                + "[repository:" + getConfigHolder().getDatasourceName() + ",table:" + tblName
                                + ", table-match:" + columnFamilyMatching + "] ";
                        HadoopException hdpException = new HadoopException(msgDesc, io);
                        hdpException.generateResponseDataMap(false, getMessage(io), msgDesc + errMsg, null,
                                null);
                        LOG.error(msgDesc + io);
                        throw hdpException;
                    } catch (SecurityException se) {
                        String msgDesc = "getColumnFamilyList: Unable to get HBase ColumnFamilyList for "
                                + "[repository:" + getConfigHolder().getDatasourceName() + ",table:" + tblName
                                + ", table-match:" + columnFamilyMatching + "] ";
                        HadoopException hdpException = new HadoopException(msgDesc, se);
                        hdpException.generateResponseDataMap(false, getMessage(se), msgDesc + errMsg, null,
                                null);
                        LOG.error(msgDesc + se);
                        throw hdpException;

                    } catch (Throwable e) {
                        String msgDesc = "getColumnFamilyList: Unable to get HBase ColumnFamilyList for "
                                + "[repository:" + getConfigHolder().getDatasourceName() + ",table:" + tblName
                                + ", table-match:" + columnFamilyMatching + "] ";
                        LOG.error(msgDesc);
                        HadoopException hdpException = new HadoopException(msgDesc, e);
                        hdpException.generateResponseDataMap(false, getMessage(e), msgDesc + errMsg, null,
                                null);
                        LOG.error(msgDesc + e);
                        throw hdpException;
                    } finally {
                        if (admin != null) {
                            try {
                                admin.close();
                            } catch (IOException e) {
                                LOG.error("Unable to close HBase connection ["
                                        + getConfigHolder().getDatasourceName() + "]", e);
                            }
                        }
                    }
                    return colfList;
                }

            });
        } catch (SecurityException se) {
            String msgDesc = "getColumnFamilyList: Unable to connect to HBase Server instance ";
            HadoopException hdpException = new HadoopException(msgDesc, se);
            hdpException.generateResponseDataMap(false, getMessage(se), msgDesc + errMsg, null, null);
            LOG.error(msgDesc + se);
            throw hdpException;
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("<== HbaseClient.getColumnFamilyList() " + ret);
    }
    return ret;
}

From source file:org.apache.axis2.deployment.util.Utils.java

private static boolean addFiles(ArrayList urls, final File libfiles) throws MalformedURLException {
    Boolean exists = (Boolean) org.apache.axis2.java.security.AccessController
            .doPrivileged(new PrivilegedAction() {
                public Object run() {
                    return libfiles.exists();
                }//  w  ww.ja v  a  2 s . co  m
            });
    if (exists) {
        urls.add(libfiles.toURL());
        File jarfiles[] = (File[]) org.apache.axis2.java.security.AccessController
                .doPrivileged(new PrivilegedAction() {
                    public Object run() {
                        return libfiles.listFiles();
                    }
                });
        int i = 0;
        while (i < jarfiles.length) {
            File jarfile = jarfiles[i];
            if (jarfile.getName().endsWith(".jar")) {
                urls.add(jarfile.toURL());
            }
            i++;
        }
    }
    return exists;
}

From source file:org.apache.ranger.admin.client.RangerAdminRESTClient.java

@Override
public List<String> getTagTypes(String pattern) throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> RangerAdminRESTClient.getTagTypes(" + pattern + "): ");
    }// w ww.  j  a  va2 s. c o  m

    List<String> ret = null;
    String emptyString = "";
    UserGroupInformation user = MiscUtil.getUGILoginUser();
    boolean isSecureMode = user != null && UserGroupInformation.isSecurityEnabled();

    final WebResource webResource = createWebResource(RangerRESTUtils.REST_URL_LOOKUP_TAG_NAMES)
            .queryParam(RangerRESTUtils.SERVICE_NAME_PARAM, serviceName)
            .queryParam(RangerRESTUtils.PATTERN_PARAM, pattern);

    ClientResponse response = null;
    if (isSecureMode) {
        PrivilegedAction<ClientResponse> action = new PrivilegedAction<ClientResponse>() {
            public ClientResponse run() {
                return webResource.accept(RangerRESTUtils.REST_MIME_TYPE_JSON).get(ClientResponse.class);
            };
        };
        if (LOG.isDebugEnabled()) {
            LOG.debug("getTagTypes as user " + user);
        }
        response = user.doAs(action);
    } else {
        response = webResource.accept(RangerRESTUtils.REST_MIME_TYPE_JSON).get(ClientResponse.class);
    }

    if (response != null && response.getStatus() == 200) {
        ret = response.getEntity(getGenericType(emptyString));
    } else {
        RESTResponse resp = RESTResponse.fromClientResponse(response);
        LOG.error("Error getting taggedResources. request=" + webResource.toString() + ", response="
                + resp.toString() + ", serviceName=" + serviceName + ", " + "pattern=" + pattern);
        throw new Exception(resp.getMessage());
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== RangerAdminRESTClient.getTagTypes(" + pattern + "): " + ret);
    }

    return ret;
}

From source file:org.apache.jasper.runtime.PageContextImpl.java

public Enumeration getAttributeNamesInScope(final int scope) {
    if (System.getSecurityManager() != null) {
        return (Enumeration) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                return doGetAttributeNamesInScope(scope);
            }//w  ww . j  a  va 2s.co m
        });
    } else {
        return doGetAttributeNamesInScope(scope);
    }
}

From source file:org.apache.hadoop.tools.distcp2.mapred.TestCopyMapper.java

@Test
public void testSkipCopyNoPerms() {
    try {//from   w  w w  . j a  va  2s .  c o m
        deleteState();
        createSourceData();

        UserGroupInformation tmpUser = UserGroupInformation.createRemoteUser("guest");

        final CopyMapper copyMapper = new CopyMapper();

        final StubContext stubContext = tmpUser.doAs(new PrivilegedAction<StubContext>() {
            @Override
            public StubContext run() {
                try {
                    return new StubContext(getConfiguration(), null, 0);
                } catch (Exception e) {
                    LOG.error("Exception encountered ", e);
                    throw new RuntimeException(e);
                }
            }
        });

        final Mapper<Text, FileStatus, Text, Text>.Context context = stubContext.getContext();
        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");
        touchFile(TARGET_PATH + "/src/file");
        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.assertEquals(stubContext.getWriter().values().size(), 1);
                    Assert.assertTrue(stubContext.getWriter().values().get(0).toString().startsWith("SKIP"));
                    Assert.assertTrue(stubContext.getWriter().values().get(0).toString()
                            .contains(SOURCE_PATH + "/src/file"));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                return null;
            }
        });
    } catch (Exception e) {
        LOG.error("Exception encountered ", e);
        Assert.fail("Test failed: " + e.getMessage());
    }
}