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.reelfx.model.ScreenRecorder.java

public static void deleteOutput() {
    AccessController.doPrivileged(new PrivilegedAction<Object>() {

        @Override//from   ww  w  . jav a 2s .  c  o  m
        public Object run() {
            try {
                if (OUTPUT_FILE.exists() && !OUTPUT_FILE.delete())
                    throw new Exception("Can't delete the old video file!");
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
            return null;
        }
    });
}

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

public void removeAttribute(final String name, final int scope) {

    if (name == null) {
        throw new NullPointerException(Localizer.getMessage("jsp.error.attribute.null_name"));
    }//from  ww  w  . j a va 2 s . co  m
    if (SecurityUtil.isPackageProtectionEnabled()) {
        AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                doRemoveAttribute(name, scope);
                return null;
            }
        });
    } else {
        doRemoveAttribute(name, scope);
    }
}

From source file:org.apache.axis.AxisProperties.java

/**
 * !WARNING!//from   w  ww . j a  v  a 2s.  c  o m
 * SECURITY issue.
 *
 * See bug 11874
 *
 * The solution to both is to move doPrivilege UP within AXIS to a
 * class that is either private (cannot be reached by code outside
 * AXIS) or that represents a secure public interface...
 *
 * This is going to require analysis and (probably) rearchitecting.
 * So, I'm taking taking the easy way out until we are at a point
 * where we can reasonably rearchitect for security.
 */
private static Object newInstance(final SPInterface spi, final DefaultClassHolder defaultClass) {
    return AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            try {
                return DiscoverClass.newInstance(null, spi, (PropertiesHolder) null, defaultClass);
            } catch (Exception e) {
                log.error(Messages.getMessage("exception00"), e);
            }
            return null;
        }
    });
}

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

public List<String> getTableList(final String tableNameMatching, final List<String> existingTableList)
        throws HadoopException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> HbaseClient.getTableList()  tableNameMatching " + tableNameMatching
                + " ExisitingTableList " + existingTableList);
    }//w  ww.j a v a2  s  . 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) {
        ret = Subject.doAs(subj, new PrivilegedAction<List<String>>() {

            @Override
            public List<String> run() {

                List<String> tableList = new ArrayList<String>();
                HBaseAdmin admin = null;
                try {
                    LOG.info("getTableList: setting config values from client");
                    setClientConfigValues(conf);
                    LOG.info("getTableList: checking HbaseAvailability with the new config");
                    HBaseAdmin.checkHBaseAvailable(conf);
                    LOG.info("getTableList: no exception: HbaseAvailability true");
                    admin = new HBaseAdmin(conf);
                    HTableDescriptor[] htds = admin.listTables(tableNameMatching);
                    if (htds != null) {
                        for (HTableDescriptor htd : admin.listTables(tableNameMatching)) {
                            String tableName = htd.getNameAsString();
                            if (existingTableList != null && existingTableList.contains(tableName)) {
                                continue;
                            } else {
                                tableList.add(htd.getNameAsString());
                            }
                        }
                    } else {
                        LOG.error("getTableList: null HTableDescription received from HBaseAdmin.listTables");
                    }
                } catch (ZooKeeperConnectionException zce) {
                    String msgDesc = "getTableList: 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 = "getTableList: 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 = "getTableList: Unable to get HBase table List for [repository:"
                            + getConfigHolder().getDatasourceName() + ",table-match:" + tableNameMatching
                            + "].";
                    HadoopException hdpException = new HadoopException(msgDesc, io);
                    hdpException.generateResponseDataMap(false, getMessage(io), msgDesc + errMsg, null, null);
                    LOG.error(msgDesc + io);
                    throw hdpException;
                } catch (Throwable e) {
                    String msgDesc = "getTableList : Unable to get HBase table List for [repository:"
                            + getConfigHolder().getDatasourceName() + ",table-match:" + tableNameMatching
                            + "].";
                    LOG.error(msgDesc + e);
                    HadoopException hdpException = new HadoopException(msgDesc, e);
                    hdpException.generateResponseDataMap(false, getMessage(e), msgDesc + errMsg, null, null);
                    throw hdpException;
                } finally {
                    if (admin != null) {
                        try {
                            admin.close();
                        } catch (IOException e) {
                            LOG.error("Unable to close HBase connection ["
                                    + getConfigHolder().getDatasourceName() + "]", e);
                        }
                    }
                }
                return tableList;
            }

        });
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("<== HbaseClient.getTableList() " + ret);
    }
    return ret;
}

From source file:org.apache.cxf.common.logging.LogUtils.java

private static void setContextClassLoader(final ClassLoader classLoader) {
    final SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        AccessController.doPrivileged(new PrivilegedAction<Object>() {
            public Object run() {
                Thread.currentThread().setContextClassLoader(classLoader);
                return null;
            }/*from  ww w.j a  va  2 s  .  c o  m*/
        });
    } else {
        Thread.currentThread().setContextClassLoader(classLoader);
    }
}

From source file:com.dragome.callbackevictor.serverside.ContinuationClassLoader.java

/**
 * Define a class given its bytes//from ww  w .j  a  v a 2 s.co m
 *
 * @param classData the bytecode data for the class
 * @param classname the name of the class
 *
 * @return the Class instance created from the given data
 */
protected Class<?> defineClassFromData(final byte[] classData, final String classname) {
    return AccessController.doPrivileged(new PrivilegedAction<Class<?>>() {
        public Class<?> run() {
            // define a package if necessary.
            int i = classname.lastIndexOf('.');
            if (i > 0) {
                final String packageName = classname.substring(0, i);
                final Package pkg = getPackage(packageName);
                if (pkg == null) {
                    definePackage(packageName, null, null, null, null, null, null, null);
                }
            }

            final byte[] newData = transformer.transform(classData);
            final ProtectionDomain domain = this.getClass().getProtectionDomain();
            return defineClass(classname, newData, 0, newData.length, domain);
        }
    }, acc);
}

From source file:org.jboss.as.forge.util.Files.java

static String getProperty(final String key) {
    if (System.getSecurityManager() == null) {
        return System.getProperty(key);
    }/*from w w w  . ja v  a2  s . co  m*/
    return AccessController.doPrivileged(new PrivilegedAction<String>() {
        @Override
        public String run() {
            return System.getProperty(key);
        }
    });
}

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

@Test
public void testPreserve() {
    try {//from w  ww  .  j  a va 2 s . c  om
        deleteState();
        createSourceData();

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

        final CopyMapper copyMapper = new CopyMapper();

        final Mapper<Text, FileStatus, Text, Text>.Context context = tmpUser
                .doAs(new PrivilegedAction<Mapper<Text, FileStatus, Text, Text>.Context>() {
                    @Override
                    public Mapper<Text, FileStatus, 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);

        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"),
                            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:com.aliyun.odps.local.common.utils.LocalRunUtils.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static Collection<File> listFiles(final File dir, final String relativePath) throws IOException {
    // privileged code, for this method may be invoked by user code
    try {/*from w ww  .ja v a 2  s.c o  m*/
        return (Collection<File>) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                File relativeDir = new File(dir, relativePath);
                checkParent(dir, relativePath);
                if (relativeDir.isDirectory()) {
                    return FileUtils.listFiles(relativeDir, new InternalIOFilter(), new InternalIOFilter());
                } else {
                    Collection<File> files = new java.util.LinkedList<File>();
                    files.add(relativeDir);
                    return files;
                }
            }
        });
    } catch (RuntimeException e) {
        if (e.getCause() instanceof IOException) {
            throw (IOException) e.getCause();
        } else {
            throw e;
        }
    }
}

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

/**
 * Get the most recent WebPageSnapshotModel from HBase
 *
 * @param url The URL to get the snapshotted page from HBase
 * @return The WebPageSnapshotModel, or null if there are no fetches for this
 * URL//  www .j  ava  2 s.  co m
 */
private WebPageSnapshotModel getMostRecentWebPageSnapshot(String url, final String user) throws IOException {
    WebPageSnapshotModel snapshot = null;
    final String normalizedUrl = normalizeUrl(url, user);

    UserGroupInformation ugi = UserGroupInformation.createProxyUser(user, UserGroupInformation.getLoginUser());

    LOG.error("Created proxy user " + ugi.getShortUserName() + " ugi: " + ugi);

    snapshot = ugi.doAs(new PrivilegedAction<WebPageSnapshotModel>() {

        @Override
        public WebPageSnapshotModel run() {
            DatasetReader<WebPageSnapshotModel> reader = null;
            try {
                // we don't know the exact timestamp in the key, but we know since keys
                // are in timestamp descending order that the first row for an URL will be
                // the most recent.
                reader = webPageSnapshotModels(user).from("url", normalizedUrl).from("fetchedAtRevTs", 0L)
                        .to("url", normalizedUrl).to("fetchedAtRevTs", Long.MAX_VALUE).newReader();
                if (reader.hasNext()) {
                    return reader.next();
                } else {
                    return null;
                }
            } finally {
                if (reader != null) {
                    reader.close();
                }
            }
        }

    });

    return snapshot;
}