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:org.apache.hadoop.mapred.gridmix.GridmixJob.java

public GridmixJob(final Configuration conf, long submissionMillis, final JobStory jobdesc, Path outRoot,
        UserGroupInformation ugi, final int seq) throws IOException {
    this.ugi = ugi;
    this.jobdesc = jobdesc;
    this.seq = seq;

    ((StringBuilder) nameFormat.get().out()).setLength(JOBNAME.length());
    try {//from ww w.  j ava2  s  . c  o  m
        job = this.ugi.doAs(new PrivilegedExceptionAction<Job>() {
            public Job run() throws IOException {
                Job ret = new Job(conf, nameFormat.get().format("%05d", seq).toString());
                ret.getConfiguration().setInt(GRIDMIX_JOB_SEQ, seq);
                ret.getConfiguration().set(ORIGNAME,
                        null == jobdesc.getJobID() ? "<unknown>" : jobdesc.getJobID().toString());
                if (conf.getBoolean(GRIDMIX_USE_QUEUE_IN_TRACE, false)) {
                    setJobQueue(ret, jobdesc.getQueueName());
                } else {
                    setJobQueue(ret, conf.get(GRIDMIX_DEFAULT_QUEUE));
                }

                return ret;
            }
        });
    } catch (InterruptedException e) {
        throw new IOException(e);
    }

    submissionTimeNanos = TimeUnit.NANOSECONDS.convert(submissionMillis, TimeUnit.MILLISECONDS);
    outdir = new Path(outRoot, "" + seq);
}

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

@Test
public void testAddLabels() throws Throwable {
    PrivilegedExceptionAction<VisibilityLabelsResponse> action = new PrivilegedExceptionAction<VisibilityLabelsResponse>() {
        public VisibilityLabelsResponse run() throws Exception {
            String[] labels = { "L1", SECRET, "L2", "invalid~", "L3" };
            VisibilityLabelsResponse response = null;
            try (Connection conn = ConnectionFactory.createConnection(conf)) {
                response = VisibilityClient.addLabels(conn, labels);
            } catch (Throwable e) {
                fail("Should not have thrown exception");
            }// ww  w.j  a  v  a2s . c om
            List<RegionActionResult> resultList = response.getResultList();
            assertEquals(5, resultList.size());
            assertTrue(resultList.get(0).getException().getValue().isEmpty());
            assertEquals("org.apache.hadoop.hbase.DoNotRetryIOException",
                    resultList.get(1).getException().getName());
            assertTrue(Bytes.toString(resultList.get(1).getException().getValue().toByteArray())
                    .contains("org.apache.hadoop.hbase.security.visibility.LabelAlreadyExistsException: "
                            + "Label 'secret' already exists"));
            assertTrue(resultList.get(2).getException().getValue().isEmpty());
            assertTrue(resultList.get(3).getException().getValue().isEmpty());
            assertTrue(resultList.get(4).getException().getValue().isEmpty());
            return null;
        }
    };
    SUPERUSER.runAs(action);
}

From source file:io.hops.tensorflow.TimelineHandler.java

public void publishContainerStartEvent(Container container) {
    final TimelineEntity entity = new TimelineEntity();
    entity.setEntityId(container.getId().toString());
    entity.setEntityType(ApplicationMaster.YarntfEntity.YARNTF_CONTAINER.toString());
    entity.setDomainId(domainId);/* w ww. jav a 2 s. c  om*/
    entity.addPrimaryFilter("user", ugi.getShortUserName());
    TimelineEvent event = new TimelineEvent();
    event.setTimestamp(System.currentTimeMillis());
    event.setEventType(ApplicationMaster.YarntfEvent.YARNTF_CONTAINER_START.toString());
    event.addEventInfo("Node", container.getNodeId().toString());
    event.addEventInfo("Resources", container.getResource().toString());
    entity.addEvent(event);

    try {
        ugi.doAs(new PrivilegedExceptionAction<TimelinePutResponse>() {
            @Override
            public TimelinePutResponse run() throws Exception {
                return timelineClient.putEntities(entity);
            }
        });
    } catch (Exception e) {
        LOG.error("Container start event could not be published for " + container.getId().toString(),
                e instanceof UndeclaredThrowableException ? e.getCause() : e);
    }
}

From source file:org.apache.hadoop.hdfs.server.datanode.BlockPoolManager.java

synchronized void startAll() throws IOException {
    try {/*from w  w  w. jav  a  2s .  co m*/
        UserGroupInformation.getLoginUser().doAs(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                for (BPOfferService bpos : offerServices) {
                    bpos.start();
                }
                return null;
            }
        });
    } catch (InterruptedException ex) {
        IOException ioe = new IOException();
        ioe.initCause(ex.getCause());
        throw ioe;
    }
}

From source file:CalendarController.java

private void startConsole(String dir) throws Exception {
    final String path = dir + "/" + CONSOLE_FILENAME;
    AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
        public Object run() throws Exception {
            log("Writing log to " + path);
            console = new PrintStream(new FileOutputStream(path));
            System.setOut(console);
            System.setErr(console);
            return null;
        }// w  ww  . j  av a  2s . c  o  m
    });
}

From source file:org.apache.atlas.web.filters.AtlasAuthenticationKerberosFilterTest.java

@Test(enabled = false)
public void testKerberosBasedLogin() throws Exception {
    String originalConf = System.getProperty("atlas.conf");

    setupKDCAndPrincipals();//ww w  . j  a v a 2s  .  co  m
    TestEmbeddedServer server = null;

    try {
        // setup the atlas-application.properties file
        String confDirectory = generateKerberosTestProperties();
        System.setProperty("atlas.conf", confDirectory);

        // need to create the web application programmatically in order to control the injection of the test
        // application properties
        server = new TestEmbeddedServer(23000, "webapp/target/apache-atlas");

        startEmbeddedServer(server.getServer());

        final URLConnectionFactory connectionFactory = URLConnectionFactory.DEFAULT_SYSTEM_CONNECTION_FACTORY;
        // attempt to hit server and get rejected
        URL url = new URL("http://localhost:23000/");
        HttpURLConnection connection = (HttpURLConnection) connectionFactory.openConnection(url, false);
        connection.setRequestMethod("GET");
        connection.connect();

        assertEquals(connection.getResponseCode(), 401);

        // need to populate the ticket cache with a local user, so logging in...
        Subject subject = loginTestUser();

        Subject.doAs(subject, new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                // attempt to hit server and get rejected
                URL url = new URL("http://localhost:23000/");
                HttpURLConnection connection = (HttpURLConnection) connectionFactory.openConnection(url, true);
                connection.setRequestMethod("GET");
                connection.connect();

                assertEquals(connection.getResponseCode(), 200);
                assertEquals(RequestContext.get().getUser(), TESTUSER);
                return null;
            }
        });
    } finally {
        server.getServer().stop();
        kdc.stop();

        if (originalConf != null) {
            System.setProperty("atlas.conf", originalConf);
        } else {
            System.clearProperty("atlas.conf");
        }

    }
}

From source file:org.apache.hadoop.mapred.gridmix.SleepJob.java

@Override
public Job call() throws IOException, InterruptedException, ClassNotFoundException {
    ugi.doAs(new PrivilegedExceptionAction<Job>() {
        public Job run() throws IOException, ClassNotFoundException, InterruptedException {
            job.setMapperClass(SleepMapper.class);
            job.setReducerClass(SleepReducer.class);
            job.setNumReduceTasks((mapTasksOnly) ? 0 : jobdesc.getNumberReduces());
            job.setMapOutputKeyClass(GridmixKey.class);
            job.setMapOutputValueClass(NullWritable.class);
            job.setSortComparatorClass(GridmixKey.Comparator.class);
            job.setGroupingComparatorClass(SpecGroupingComparator.class);
            job.setInputFormatClass(SleepInputFormat.class);
            job.setOutputFormatClass(NullOutputFormat.class);
            job.setPartitionerClass(DraftPartitioner.class);
            job.setJarByClass(SleepJob.class);
            job.getConfiguration().setBoolean("mapred.used.genericoptionsparser", true);
            job.submit();/*from   w w  w .j  av  a2 s .  co m*/
            return job;

        }
    });

    return job;
}

From source file:org.solmix.runtime.support.spring.ContainerXmlBeanDefinitionReader.java

@Override
public int loadBeanDefinitions(final EncodedResource encodedResource) throws BeanDefinitionStoreException {
    if (!noFastinfoset) {
        try {/*from  w  w w.j a  va  2s  .c o  m*/
            return fastInfosetLoadBeanDefinitions(encodedResource);
        } catch (BeanDefinitionStoreException bdse) {
            throw bdse;
        } catch (Throwable e) {
            //ignore - just call the super to load them
        }
    }
    try {
        return AccessController.doPrivileged(new PrivilegedExceptionAction<Integer>() {
            @Override
            public Integer run() throws Exception {
                return internalLoadBeanDefinitions(encodedResource);
            }

        });
    } catch (PrivilegedActionException e) {
        if (e.getException() instanceof RuntimeException) {
            throw (RuntimeException) e.getException();
        }
        throw (BeanDefinitionStoreException) e.getException();
    }
}

From source file:com.scoredev.scores.HighScore.java

/**
 * get the high score. return -1 if it hasn't been set.
 *
 *///from   ww w  .  j  a v  a  2s . com
public int getHighScore() throws IOException, ClassNotFoundException {
    //check permission first
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new HighScorePermission(gameName));
    }

    Integer score = null;

    // need a doPrivileged block to manipulate the file
    try {
        score = (Integer) AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws IOException, ClassNotFoundException {
                Hashtable scores = null;
                // try to open the existing file. Should have a locking
                // protocol (could use File.createNewFile).
                FileInputStream fis = new FileInputStream(highScoreFile);
                ObjectInputStream ois = new ObjectInputStream(fis);
                scores = (Hashtable) ois.readObject();

                // get the high score out
                return scores.get(gameName);
            }
        });
    } catch (PrivilegedActionException pae) {
        Exception e = pae.getException();
        if (e instanceof IOException)
            throw (IOException) e;
        else
            throw (ClassNotFoundException) e;
    }
    if (score == null)
        return -1;
    else
        return score.intValue();
}