Example usage for java.security PrivilegedExceptionAction PrivilegedExceptionAction

List of usage examples for java.security PrivilegedExceptionAction PrivilegedExceptionAction

Introduction

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

Prototype

PrivilegedExceptionAction

Source Link

Usage

From source file:net.yasion.common.core.bean.wrapper.impl.ExtendedBeanWrapperImpl.java

@SuppressWarnings("unchecked")
private Object getPropertyValue(PropertyTokenHolder tokens) throws BeansException {
    String propertyName = tokens.canonicalName;
    String actualName = tokens.actualName;
    PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
    if (pd == null || pd.getReadMethod() == null) {
        throw new NotReadablePropertyException(getRootClass(), this.nestedPath + propertyName);
    }//ww  w.  j  a  va2  s  .  co  m
    final Method readMethod = pd.getReadMethod();
    try {
        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers()) && !readMethod.isAccessible()) {
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged(new PrivilegedAction<Object>() {
                    @Override
                    public Object run() {
                        readMethod.setAccessible(true);
                        return null;
                    }
                });
            } else {
                readMethod.setAccessible(true);
            }
        }

        Object value;
        if (System.getSecurityManager() != null) {
            try {
                value = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                    @Override
                    public Object run() throws Exception {
                        return readMethod.invoke(object, (Object[]) null);
                    }
                }, acc);
            } catch (PrivilegedActionException pae) {
                throw pae.getException();
            }
        } else {
            value = readMethod.invoke(object, (Object[]) null);
        }

        if (tokens.keys != null) {
            if (value == null) {
                if (isAutoGrowNestedPaths()) {
                    value = setDefaultValue(tokens.actualName);
                } else {
                    throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                            "Cannot access indexed value of property referenced in indexed " + "property path '"
                                    + propertyName + "': returned null");
                }
            }
            String indexedPropertyName = tokens.actualName;
            // apply indexes and map keys
            for (int i = 0; i < tokens.keys.length; i++) {
                String key = tokens.keys[i];
                if (value == null) {
                    throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                            "Cannot access indexed value of property referenced in indexed " + "property path '"
                                    + propertyName + "': returned null");
                } else if (value.getClass().isArray()) {
                    int index = Integer.parseInt(key);
                    value = growArrayIfNecessary(value, index, indexedPropertyName);
                    value = Array.get(value, index);
                } else if (value instanceof List) {
                    int index = Integer.parseInt(key);
                    List<Object> list = (List<Object>) value;
                    growCollectionIfNecessary(list, index, indexedPropertyName, pd, i + 1);
                    value = list.get(index);
                } else if (value instanceof Set) {
                    // Apply index to Iterator in case of a Set.
                    Set<Object> set = (Set<Object>) value;
                    int index = Integer.parseInt(key);
                    if (index < 0 || index >= set.size()) {
                        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                                "Cannot get element with index " + index + " from Set of size " + set.size()
                                        + ", accessed using property path '" + propertyName + "'");
                    }
                    Iterator<Object> it = set.iterator();
                    for (int j = 0; it.hasNext(); j++) {
                        Object elem = it.next();
                        if (j == index) {
                            value = elem;
                            break;
                        }
                    }
                } else if (value instanceof Map) {
                    Map<Object, Object> map = (Map<Object, Object>) value;
                    Class<?> mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(),
                            i + 1);
                    // IMPORTANT: Do not pass full property name in here - property editors
                    // must not kick in for map keys but rather only for map values.
                    TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(mapKeyType);
                    Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, typeDescriptor);
                    value = map.get(convertedMapKey);
                } else {
                    throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                            "Property referenced in indexed property path '" + propertyName
                                    + "' is neither an array nor a List nor a Set nor a Map; returned value was ["
                                    + value + "]");
                }
                indexedPropertyName += PROPERTY_KEY_PREFIX + key + PROPERTY_KEY_SUFFIX;
            }
        }
        return value;
    } catch (IndexOutOfBoundsException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Index of out of bounds in property path '" + propertyName + "'", ex);
    } catch (NumberFormatException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Invalid index in property path '" + propertyName + "'", ex);
    } catch (TypeMismatchException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Invalid index in property path '" + propertyName + "'", ex);
    } catch (InvocationTargetException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Getter for property '" + actualName + "' threw exception", ex);
    } catch (Exception ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Illegal attempt to get property '" + actualName + "' threw exception", ex);
    }
}

From source file:org.apache.axis2.jaxws.client.proxy.JAXWSProxyHandler.java

private static ClassLoader getContextClassLoader() {
    // NOTE: This method must remain private because it uses AccessController
    ClassLoader cl = null;//from  w  ww  .  ja  v  a  2s  . com
    try {
        cl = (ClassLoader) AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws ClassNotFoundException {
                return Thread.currentThread().getContextClassLoader();
            }
        });
    } catch (PrivilegedActionException e) {
        if (log.isDebugEnabled()) {
            log.debug("Exception thrown from AccessController: " + e);
        }
        throw ExceptionFactory.makeWebServiceException(e.getException());
    }

    return cl;
}

From source file:org.apache.axis2.jaxws.spi.ServiceDelegate.java

/**
 * Return the class for this name/*from w w  w.  j  av a 2s.  co  m*/
 *
 * @return Class
 */
private static Class forName(final String className, final boolean initialize, final ClassLoader classLoader)
        throws ClassNotFoundException {
    // NOTE: This method must remain protected because it uses AccessController
    Class cl = null;
    try {
        cl = (Class) AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws ClassNotFoundException {
                return Class.forName(className, initialize, classLoader);
            }
        });
    } catch (PrivilegedActionException e) {
        if (log.isDebugEnabled()) {
            log.debug("Exception thrown from AccessController: " + e);
        }
        throw (ClassNotFoundException) e.getException();
    }

    return cl;
}

From source file:com.cloudera.beeswax.BeeswaxServiceImpl.java

/**
 * Submit a query and return a handle (QueryHandle). The query runs asynchronously.
 * Queries can be long-lasting, so we push the execution into a new state.
 * Compiling happens in the current context so we report errors early.
 *///ww  w  .j av a 2 s  .  c  o m
@Override
public QueryHandle query(final Query query) throws BeeswaxException {
    // First, create an id and reset the LogContext
    String uuid = UUID.randomUUID().toString();
    final QueryHandle handle = new QueryHandle(uuid, uuid);
    final LogContext lc = LogContext.registerCurrentThread(handle.log_context);
    lc.resetLog();

    // Make an administrative record
    final RunningQueryState state = new RunningQueryState(query, lc);

    // acquire delegation token if needed
    try {
        state.setDelegationToken(getDelegationTokenFromMetaStore(query.hadoop_user));
    } catch (UnsupportedOperationException e) {
        // If delegationToken is not support in this environment, then ignore it
    } catch (HiveException e) {
        throw new BeeswaxException(e.getMessage(), handle.log_context, handle);
    } catch (MetaException e) {
        throw new BeeswaxException(e.getMessage(), handle.log_context, handle);
    } catch (TException e) {
        throw new BeeswaxException(e.getMessage(), handle.log_context, handle);
    }

    try {
        return doWithState(state, new PrivilegedExceptionAction<QueryHandle>() {
            public QueryHandle run() throws Exception {
                state.setQueryHandle(handle);
                runningQueries.put(handle.id, state);
                state.initialize();
                // All kinds of things can go wrong when we compile it. So catch all.
                try {
                    state.compile();
                } catch (BeeswaxException perr) {
                    state.saveException(perr);
                    throw perr;
                } catch (Throwable t) {
                    state.saveException(t);
                    throw new BeeswaxException(t.toString(), handle.log_context, handle);
                }
                // Now spin off the query.
                state.submitTo(executor, lc);
                return handle;
            }
        });
    } catch (BeeswaxException e) {
        throw e;
    }
}

From source file:org.apache.hadoop.fs.TestCopyFiles.java

public void testHftpAccessControl() throws Exception {
    MiniDFSCluster cluster = null;//from www . j av  a2s. c o  m
    try {
        final UserGroupInformation DFS_UGI = createUGI("dfs", true);
        final UserGroupInformation USER_UGI = createUGI("user", false);

        //start cluster by DFS_UGI
        final Configuration dfsConf = new Configuration();
        cluster = new MiniDFSCluster(dfsConf, 2, true, null);
        cluster.waitActive();

        final String httpAdd = dfsConf.get("dfs.http.address");
        final URI nnURI = FileSystem.getDefaultUri(dfsConf);
        final String nnUri = nnURI.toString();
        FileSystem fs1 = DFS_UGI.doAs(new PrivilegedExceptionAction<FileSystem>() {
            public FileSystem run() throws IOException {
                return FileSystem.get(nnURI, dfsConf);
            }
        });
        final Path home = createHomeDirectory(fs1, USER_UGI);

        //now, login as USER_UGI
        final Configuration userConf = new Configuration();
        final FileSystem fs = USER_UGI.doAs(new PrivilegedExceptionAction<FileSystem>() {
            public FileSystem run() throws IOException {
                return FileSystem.get(nnURI, userConf);
            }
        });

        final Path srcrootpath = new Path(home, "src_root");
        final String srcrootdir = srcrootpath.toString();
        final Path dstrootpath = new Path(home, "dst_root");
        final String dstrootdir = dstrootpath.toString();
        final DistCp distcp = USER_UGI.doAs(new PrivilegedExceptionAction<DistCp>() {
            public DistCp run() {
                return new DistCp(userConf);
            }
        });

        FileSystem.mkdirs(fs, srcrootpath, new FsPermission((short) 0700));
        final String[] args = { "hftp://" + httpAdd + srcrootdir, nnUri + dstrootdir };

        { //copy with permission 000, should fail
            fs.setPermission(srcrootpath, new FsPermission((short) 0));
            USER_UGI.doAs(new PrivilegedExceptionAction<Void>() {
                public Void run() throws Exception {
                    assertEquals(-3, ToolRunner.run(distcp, args));
                    return null;
                }
            });
        }
    } finally {
        if (cluster != null) {
            cluster.shutdown();
        }
    }
}

From source file:com.streamsets.pipeline.stage.destination.hdfs.HdfsTargetConfigBean.java

private FileSystem getFileSystemForInitDestroy() throws Exception {
    try {/*from   www .java2 s  .  co m*/
        return getUGI().doAs(new PrivilegedExceptionAction<FileSystem>() {
            @Override
            public FileSystem run() throws Exception {
                return FileSystem.get(new URI(hdfsUri), hdfsConfiguration);
            }
        });
    } catch (IOException ex) {
        throw ex;
    } catch (RuntimeException ex) {
        Throwable cause = ex.getCause();
        if (cause instanceof Exception) {
            throw (Exception) cause;
        }
        throw ex;
    }
}

From source file:org.apache.hadoop.hbase.security.visibility.TestVisibilityLabelsWithDeletes.java

@Test
public void testDeleteFamiliesWithAndWithoutVisibilityLabels() throws Exception {
    final TableName tableName = TableName.valueOf(TEST_NAME.getMethodName());
    Admin hBaseAdmin = TEST_UTIL.getAdmin();
    HColumnDescriptor colDesc = new HColumnDescriptor(fam);
    HTableDescriptor desc = new HTableDescriptor(tableName);
    desc.addFamily(colDesc);/* w w w. ja v a 2 s.  co m*/
    hBaseAdmin.createTable(desc);
    try (Table table = TEST_UTIL.getConnection().getTable(tableName)) {
        Put put = new Put(row1);
        put.addColumn(fam, qual, value);
        put.setCellVisibility(new CellVisibility(CONFIDENTIAL));
        table.put(put);
        Delete d = new Delete(row1);
        d.setCellVisibility(new CellVisibility(CONFIDENTIAL));
        // with visibility
        d.addFamily(fam);
        table.delete(d);
        PrivilegedExceptionAction<Void> scanAction = new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() throws Exception {
                try (Connection connection = ConnectionFactory.createConnection(conf);
                        Table table = connection.getTable(tableName)) {
                    Scan s = new Scan();
                    ResultScanner scanner = table.getScanner(s);
                    Result[] next = scanner.next(3);
                    assertEquals(next.length, 0);
                } catch (Throwable t) {
                    throw new IOException(t);
                }
                return null;
            }
        };
        SUPERUSER.runAs(scanAction);
        d = new Delete(row1);
        // without visibility
        d.addFamily(fam);
        table.delete(d);
        scanAction = new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() throws Exception {
                try (Connection connection = ConnectionFactory.createConnection(conf);
                        Table table = connection.getTable(tableName)) {
                    Scan s = new Scan();
                    ResultScanner scanner = table.getScanner(s);
                    Result[] next = scanner.next(3);
                    assertEquals(next.length, 0);
                } catch (Throwable t) {
                    throw new IOException(t);
                }
                return null;
            }
        };
        SUPERUSER.runAs(scanAction);
    }
}

From source file:org.apache.hadoop.hbase.regionserver.wal.TestWALReplay.java

/**
 * Create an HRegion with the result of a HLog split and test we only see the
 * good edits/* w  w w .  j a va 2  s.c o  m*/
 * @throws Exception
 */
@Test
public void testReplayEditsWrittenIntoWAL() throws Exception {
    final TableName tableName = TableName.valueOf("testReplayEditsWrittenIntoWAL");
    final HRegionInfo hri = createBasic3FamilyHRegionInfo(tableName);
    final Path basedir = FSUtils.getTableDir(hbaseRootDir, tableName);
    deleteDir(basedir);

    final HTableDescriptor htd = createBasic3FamilyHTD(tableName);
    HRegion region2 = HRegion.createHRegion(hri, hbaseRootDir, this.conf, htd);
    HRegion.closeHRegion(region2);
    final HLog wal = createWAL(this.conf);
    final byte[] rowName = tableName.getName();
    final byte[] regionName = hri.getEncodedNameAsBytes();
    final AtomicLong sequenceId = new AtomicLong(1);

    // Add 1k to each family.
    final int countPerFamily = 1000;
    for (HColumnDescriptor hcd : htd.getFamilies()) {
        addWALEdits(tableName, hri, rowName, hcd.getName(), countPerFamily, ee, wal, htd, sequenceId);
    }

    // Add a cache flush, shouldn't have any effect
    wal.startCacheFlush(regionName);
    wal.completeCacheFlush(regionName);

    // Add an edit to another family, should be skipped.
    WALEdit edit = new WALEdit();
    long now = ee.currentTimeMillis();
    edit.add(new KeyValue(rowName, Bytes.toBytes("another family"), rowName, now, rowName));
    wal.append(hri, tableName, edit, now, htd, sequenceId);

    // Delete the c family to verify deletes make it over.
    edit = new WALEdit();
    now = ee.currentTimeMillis();
    edit.add(new KeyValue(rowName, Bytes.toBytes("c"), null, now, KeyValue.Type.DeleteFamily));
    wal.append(hri, tableName, edit, now, htd, sequenceId);

    // Sync.
    wal.sync();
    // Set down maximum recovery so we dfsclient doesn't linger retrying something
    // long gone.
    HBaseTestingUtility.setMaxRecoveryErrorCount(((FSHLog) wal).getOutputStream(), 1);
    // Make a new conf and a new fs for the splitter to run on so we can take
    // over old wal.
    final Configuration newConf = HBaseConfiguration.create(this.conf);
    User user = HBaseTestingUtility.getDifferentUser(newConf, ".replay.wal.secondtime");
    user.runAs(new PrivilegedExceptionAction() {
        public Object run() throws Exception {
            runWALSplit(newConf);
            FileSystem newFS = FileSystem.get(newConf);
            // 100k seems to make for about 4 flushes during HRegion#initialize.
            newConf.setInt(HConstants.HREGION_MEMSTORE_FLUSH_SIZE, 1024 * 100);
            // Make a new wal for new region.
            HLog newWal = createWAL(newConf);
            final AtomicInteger flushcount = new AtomicInteger(0);
            try {
                final HRegion region = new HRegion(basedir, newWal, newFS, newConf, hri, htd, null) {
                    protected FlushResult internalFlushcache(final HLog wal, final long myseqid,
                            MonitoredTask status) throws IOException {
                        LOG.info("InternalFlushCache Invoked");
                        FlushResult fs = super.internalFlushcache(wal, myseqid,
                                Mockito.mock(MonitoredTask.class));
                        flushcount.incrementAndGet();
                        return fs;
                    };
                };
                long seqid = region.initialize();
                // We flushed during init.
                assertTrue("Flushcount=" + flushcount.get(), flushcount.get() > 0);
                assertTrue(seqid - 1 == sequenceId.get());

                Get get = new Get(rowName);
                Result result = region.get(get);
                // Make sure we only see the good edits
                assertEquals(countPerFamily * (htd.getFamilies().size() - 1), result.size());
                region.close();
            } finally {
                newWal.closeAndDelete();
            }
            return null;
        }
    });
}

From source file:org.apache.axis2.jaxws.client.proxy.JAXWSProxyHandler.java

/**
 * @param cls//from   ww w .  j  ava2  s.  c  o m
 * @return ClassLoader or null if cannot be obtained
 */
private static ClassLoader getClassLoader(final Class cls) {
    // NOTE: This method must remain private because it uses AccessController
    if (cls == null) {
        return null;
    }
    ClassLoader cl = null;
    try {
        cl = (ClassLoader) AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws ClassNotFoundException {
                return cls.getClassLoader();
            }
        });
    } catch (PrivilegedActionException e) {
        if (log.isDebugEnabled()) {
            log.debug("Exception thrown from AccessController: " + e);
        }
    }

    return cl;
}

From source file:org.apache.hadoop.hdfs.qjournal.server.Journal.java

/**
 * Synchronize a log segment from another JournalNode. The log is
 * downloaded from the provided URL into a temporary location on disk,
 * which is named based on the current request's epoch.
 *
 * @return the temporary location of the downloaded file
 *///from w ww.j a  v a 2  s  .c  o m
private File syncLog(RequestInfo reqInfo, final SegmentStateProto segment, final URL url) throws IOException {
    final File tmpFile = storage.getSyncLogTemporaryFile(segment.getStartTxId(), reqInfo.getEpoch());
    final List<File> localPaths = ImmutableList.of(tmpFile);

    LOG.info("Synchronizing log " + TextFormat.shortDebugString(segment) + " from " + url);
    SecurityUtil.doAsLoginUser(new PrivilegedExceptionAction<Void>() {
        @Override
        public Void run() throws IOException {
            // We may have lost our ticket since last checkpoint, log in again, just in case
            if (UserGroupInformation.isSecurityEnabled()) {
                UserGroupInformation.getCurrentUser().checkTGTAndReloginFromKeytab();
            }

            boolean success = false;
            try {
                TransferFsImage.doGetUrl(url, localPaths, storage, true);
                assert tmpFile.exists();
                success = true;
            } finally {
                if (!success) {
                    if (!tmpFile.delete()) {
                        LOG.warn("Failed to delete temporary file " + tmpFile);
                    }
                }
            }
            return null;
        }
    });
    return tmpFile;
}