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.apache.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  av a 2s .  c  o  m*/
    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                doRemoveAttribute(name, scope);
                return null;
            }
        });
    } else {
        doRemoveAttribute(name, scope);
    }
}

From source file:org.codehaus.groovy.grails.web.pages.GroovyPageMetaInfo.java

public Resource checkIfReloadableResourceHasChanged(final PrivilegedAction<Resource> resourceCallable) {
    PrivilegedAction<Resource> checkerCallable = new PrivilegedAction<Resource>() {
        public Resource run() {
            Resource resource = resourceCallable.run();
            if (resource != null && resource.exists()) {
                long currentLastmodified = establishLastModified(resource);
                // granularity is required since lastmodified information is rounded some where in copying & war (zip) file information
                // usually the lastmodified time is 1000L apart in files and in files extracted from the zip (war) file
                if (currentLastmodified > 0
                        && Math.abs(currentLastmodified - lastModified) > LASTMODIFIED_CHECK_GRANULARITY) {
                    return resource;
                }//from w w w .ja va2 s . c  o m
            }
            return null;
        }
    };
    return shouldReloadCacheEntry.getValue(LASTMODIFIED_CHECK_INTERVAL, checkerCallable);
}

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

public void deleteKey(String provider, String name) throws Exception {
    String providers[] = null;/*from  w  ww  . java 2  s.  c  o m*/
    try {
        providers = getKMSURL(provider);
    } catch (Exception e) {
        logger.error("deleteKey(" + provider + ", " + name + ") failed", e);
    }
    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 deleteRest = KMS_DELETE_KEY_URI.replaceAll(Pattern.quote("${alias}"), name);
            String currentUserLoginId = ContextUtil.getCurrentUserLoginId();
            String uri = providers[i] + (providers[i].endsWith("/") ? deleteRest : ("/" + deleteRest));
            if (!isKerberos) {
                uri = uri.concat("?user.name=" + currentUserLoginId);
            } else {
                uri = uri.concat("?doAs=" + currentUserLoginId);
            }
            final WebResource r = c.resource(uri);
            try {
                String response = null;
                if (!isKerberos) {
                    response = r.delete(String.class);
                } else {
                    Subject sub = getSubjectForKerberos(provider);
                    response = Subject.doAs(sub, new PrivilegedAction<String>() {
                        @Override
                        public String run() {
                            return r.delete(String.class);
                        }
                    });
                }
                logger.debug("delete RESPONSE: [" + response + "]");
                break;
            } catch (Exception e) {
                if (e instanceof UniformInterfaceException || i == providers.length - 1)
                    throw e;
                else
                    continue;
            }
        }
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.MockRM.java

public RMApp submitApp(int masterMemory, String name, String user, Map<ApplicationAccessType, String> acls,
        boolean unmanaged, String queue, int maxAppAttempts, Credentials ts, String appType,
        boolean waitForAccepted, boolean keepContainers, boolean isAppIdProvided, ApplicationId applicationId)
        throws Exception {
    ApplicationId appId = isAppIdProvided ? applicationId : null;
    ApplicationClientProtocol client = getClientRMService();
    if (!isAppIdProvided) {
        GetNewApplicationResponse resp = client
                .getNewApplication(Records.newRecord(GetNewApplicationRequest.class));
        appId = resp.getApplicationId();
    }/*from  w w  w .  j a  v  a 2  s.  co  m*/
    SubmitApplicationRequest req = Records.newRecord(SubmitApplicationRequest.class);
    ApplicationSubmissionContext sub = Records.newRecord(ApplicationSubmissionContext.class);
    sub.setKeepContainersAcrossApplicationAttempts(keepContainers);
    sub.setApplicationId(appId);
    sub.setApplicationName(name);
    sub.setMaxAppAttempts(maxAppAttempts);
    if (unmanaged) {
        sub.setUnmanagedAM(true);
    }
    if (queue != null) {
        sub.setQueue(queue);
    }
    sub.setApplicationType(appType);
    ContainerLaunchContext clc = Records.newRecord(ContainerLaunchContext.class);
    final Resource capability = Records.newRecord(Resource.class);
    capability.setMemory(masterMemory);
    sub.setResource(capability);
    clc.setApplicationACLs(acls);
    if (ts != null && UserGroupInformation.isSecurityEnabled()) {
        DataOutputBuffer dob = new DataOutputBuffer();
        ts.writeTokenStorageToStream(dob);
        ByteBuffer securityTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength());
        clc.setTokens(securityTokens);
    }
    sub.setAMContainerSpec(clc);
    req.setApplicationSubmissionContext(sub);
    UserGroupInformation fakeUser = UserGroupInformation.createUserForTesting(user,
            new String[] { "someGroup" });
    PrivilegedAction<SubmitApplicationResponse> action = new PrivilegedAction<SubmitApplicationResponse>() {
        ApplicationClientProtocol client;
        SubmitApplicationRequest req;

        @Override
        public SubmitApplicationResponse run() {
            try {
                return client.submitApplication(req);
            } catch (YarnException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        PrivilegedAction<SubmitApplicationResponse> setClientReq(ApplicationClientProtocol client,
                SubmitApplicationRequest req) {
            this.client = client;
            this.req = req;
            return this;
        }
    }.setClientReq(client, req);
    fakeUser.doAs(action);
    // make sure app is immediately available after submit
    if (waitForAccepted) {
        waitForState(appId, RMAppState.ACCEPTED);
    }
    return getRMContext().getRMApps().get(appId);
}

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

/**
 * Define a class given its bytes//from w ww . j a v  a2 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
 */
public Class defineClassFromData(final byte[] classData, final String classname) {
    return (Class) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            // define a package if necessary.
            int i = classname.lastIndexOf('.');
            if (i > 0) {
                String packageName = classname.substring(0, i);
                Package pkg = getPackage(packageName);
                if (pkg == null) {
                    definePackage(packageName, null, null, null, null, null, null, null);
                }
            }

            byte[] newData;
            if (!bytecodeTransformer.requiresTransformation(classname) || loadingClass.contains(classname))
                newData = classData;
            else {
                loadingClass.add(classname);
                Thread.currentThread().setContextClassLoader(last);
                newData = transformer.transform(classData);
                Thread.currentThread().setContextClassLoader(DragomeContinuationClassLoader.this);
            }

            ProtectionDomain domain = this.getClass().getProtectionDomain();
            return defineClass(classname, newData, 0, newData.length, domain);
        }
    }, acc);
}

From source file:com.reelfx.model.PostProcessor.java

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

        @Override//ww w . j a  v a  2 s .c o m
        public Object run() {
            try {
                if (DEFAULT_OUTPUT_FILE.exists() && !DEFAULT_OUTPUT_FILE.delete())
                    throw new Exception("Can't delete the old audio file!");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    });
}

From source file:com.ibm.liberty.starter.service.swagger.api.v1.ProviderEndpoint.java

private int generateCode(String javaHome, String swaggerCodeGenJarPath, String javaClientTemplates,
        String codeGenLanguage, String filePath, String outputDir) throws java.io.IOException {

    try {//  w w w  .  ja v a  2s . co  m
        final ArrayList<String> commandList = new ArrayList<String>();

        if (javaHome == null || javaHome.trim().isEmpty()) {
            //Get java home
            javaHome = AccessController.doPrivileged(new PrivilegedAction<String>() {
                @Override
                public String run() {
                    return System.getProperty("java.home");
                }

            });
            if (!javaHome.endsWith("/")) {
                javaHome += "/";
            }
            log.fine("Retrieved Java home location from System property : " + javaHome);
        }

        commandList.add(javaHome + "bin/java");
        commandList.add("-jar");
        commandList.add(swaggerCodeGenJarPath);

        commandList.add("generate");
        commandList.add("-l");
        commandList.add(codeGenLanguage);

        if (javaClientTemplates != null && !javaClientTemplates.trim().isEmpty()) {
            commandList.add("-t");
            commandList.add(javaClientTemplates);
        }

        commandList.add("-i");
        commandList.add(filePath);
        commandList.add("-o");
        commandList.add(outputDir);

        StringBuilder sb = new StringBuilder();
        for (String command : commandList) {
            sb.append(command);
            sb.append(" ");
        }

        log.finer("Swagger code gen commands:\n" + sb.toString());

        //Run the command
        ProcessBuilder builder = new ProcessBuilder(commandList);
        builder.redirectErrorStream(true); //merge error and output together

        Process codeGenProc = builder.start();
        int exitVal = codeGenProc.waitFor();

        log.finer("Exit values: " + exitVal);

        if (exitVal != 0) {
            log.fine("Error : exit value is not 0. exitVal=" + exitVal);
            log.finer("output=" + getOutput(codeGenProc));
        } else {
            log.finer("Successfully generated code using SwaggerCodegen");
        }

        return exitVal;
    } catch (Exception e) {
        log.fine("Exception occurred while executing SwaggerCodegen : e=" + e);
        return -1;
    }
}

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

/**
 * Get WebPageSnapshotModels for an URL from HBase since the since param.
 *
 * @param url The URL of the page to fetch
 * @param since The models to fetch since
 * @return The list of models that have been fetched for an URL since the
 * since param.//from www. ja v  a2s .co m
 */
private List<WebPageSnapshotModel> getWebPageSnapshotsSince(String url, final long since, final String user)
        throws IOException {
    List<WebPageSnapshotModel> snapshots = null;
    final String normalizedUrl = normalizeUrl(url, user);

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

    ugi.doAs(new PrivilegedAction<List<WebPageSnapshotModel>>() {

        @Override
        public List<WebPageSnapshotModel> run() {
            List<WebPageSnapshotModel> models = new ArrayList<WebPageSnapshotModel>();
            DatasetReader<WebPageSnapshotModel> reader = null;
            try {
                reader = webPageSnapshotModels(user).from("url", normalizedUrl).from("fetchedAtRevTs", 0L)
                        .to("url", normalizedUrl).to("fetchedAtRevTs", since).newReader();
                while (reader.hasNext()) {
                    models.add(reader.next());
                }
            } finally {
                if (reader != null) {
                    reader.close();
                }
            }
            return models;
        }
    });

    return snapshots;
}

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

@Test
public void testCopyReadableFiles() {
    try {//from  w  ww .  j  a  va 2  s .  c o m
        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);
                        }
                    }
                });

        touchFile(SOURCE_PATH + "/src/file");
        mkdirs(TARGET_PATH);
        cluster.getFileSystem().setPermission(new Path(SOURCE_PATH + "/src/file"),
                new FsPermission(FsAction.READ, FsAction.READ, FsAction.READ));
        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);
                } 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.apache.struts2.jasper.runtime.PageContextImpl.java

public Enumeration getAttributeNamesInScope(final int scope) {
    if (SecurityUtil.isPackageProtectionEnabled()) {
        return (Enumeration) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                return doGetAttributeNamesInScope(scope);
            }/*from   w ww. j a  v  a  2  s .c  om*/
        });
    } else {
        return doGetAttributeNamesInScope(scope);
    }
}