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.inmobi.conduit.distcp.tools.mapred.TestCopyMapper.java

@Test
public void testCopyReadableFiles() {
    try {//  ww w  .  j a v  a2  s .  c o  m
        deleteState();
        createSourceData();

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

        final CopyMapper copyMapper = new CopyMapper();

        final Mapper<Text, FileStatus, NullWritable, Text>.Context context = tmpUser
                .doAs(new PrivilegedAction<Mapper<Text, FileStatus, NullWritable, Text>.Context>() {
                    @Override
                    public Mapper<Text, FileStatus, NullWritable, Text>.Context run() {
                        try {
                            StatusReporter reporter = new StubStatusReporter();
                            InMemoryWriter writer = new InMemoryWriter();
                            return getMapperContext(copyMapper, reporter, writer);
                        } catch (Exception e) {
                            LOG.error("Exception encountered ", e);
                            throw new RuntimeException(e);
                        }
                    }
                });

        touchFile(SOURCE_PATH + "/src/file.gz");
        mkdirs(TARGET_PATH);
        cluster.getFileSystem().setPermission(new Path(SOURCE_PATH + "/src/file.gz"),
                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.gz"),
                            tmpFS.getFileStatus(new Path(SOURCE_PATH + "/src/file.gz")), 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.ranger.biz.KmsKeyMgr.java

public VXKmsKey getKeyFromUri(String provider, String name, boolean isKerberos, String repoName)
        throws Exception {
    Client c = getClient();/*from   ww  w.j  a v a2s  . c  o  m*/
    String keyRest = KMS_KEY_METADATA_URI.replaceAll(Pattern.quote("${alias}"), name);
    String currentUserLoginId = ContextUtil.getCurrentUserLoginId();
    String uri = provider + (provider.endsWith("/") ? keyRest : ("/" + keyRest));
    if (!isKerberos) {
        uri = uri.concat("?user.name=" + currentUserLoginId);
    } else {
        uri = uri.concat("?doAs=" + currentUserLoginId);
    }
    final WebResource r = c.resource(uri);
    String response = null;
    if (!isKerberos) {
        response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE)
                .get(String.class);
    } else {
        Subject sub = getSubjectForKerberos(repoName);
        response = Subject.doAs(sub, new PrivilegedAction<String>() {
            @Override
            public String run() {
                return r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE)
                        .get(String.class);
            }
        });
    }
    Gson gson = new GsonBuilder().create();
    logger.debug("RESPONSE: [" + response + "]");
    VXKmsKey key = gson.fromJson(response, VXKmsKey.class);
    return key;
}

From source file:corina.util.SimpleLog.java

private static InputStream getResourceAsStream(final String name) {
    return (InputStream) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            ClassLoader threadCL = getContextClassLoader();

            if (threadCL != null) {
                return threadCL.getResourceAsStream(name);
            } else {
                return ClassLoader.getSystemResourceAsStream(name);
            }// w  w w.jav a 2  s  . c o m
        }
    });
}

From source file:it.crs4.pydoop.mapreduce.pipes.CommandLineParser.java

public int run(String[] args) throws Exception {
    CommandLineParser cli = new CommandLineParser();
    if (args.length == 0) {
        cli.printUsage();/*from  w  ww .j  av a 2  s .  co  m*/
        return 1;
    }
    try {
        Job job = new Job(new Configuration());
        job.setJobName(getClass().getName());
        Configuration conf = job.getConfiguration();
        CommandLine results = cli.parse(conf, args);
        if (results.hasOption("input")) {
            Path path = new Path(results.getOptionValue("input"));
            FileInputFormat.setInputPaths(job, path);
        }
        if (results.hasOption("output")) {
            Path path = new Path(results.getOptionValue("output"));
            FileOutputFormat.setOutputPath(job, path);
        }
        if (results.hasOption("jar")) {
            job.setJar(results.getOptionValue("jar"));
        }
        if (results.hasOption("inputformat")) {
            explicitInputFormat = true;
            setIsJavaRecordReader(conf, true);
            job.setInputFormatClass(getClass(results, "inputformat", conf, InputFormat.class));
        }
        if (results.hasOption("javareader")) {
            setIsJavaRecordReader(conf, true);
        }
        if (results.hasOption("map")) {
            setIsJavaMapper(conf, true);
            job.setMapperClass(getClass(results, "map", conf, Mapper.class));
        }
        if (results.hasOption("partitioner")) {
            job.setPartitionerClass(getClass(results, "partitioner", conf, Partitioner.class));
        }
        if (results.hasOption("reduce")) {
            setIsJavaReducer(conf, true);
            job.setReducerClass(getClass(results, "reduce", conf, Reducer.class));
        }
        if (results.hasOption("reduces")) {
            job.setNumReduceTasks(Integer.parseInt(results.getOptionValue("reduces")));
        }
        if (results.hasOption("writer")) {
            explicitOutputFormat = true;
            setIsJavaRecordWriter(conf, true);
            job.setOutputFormatClass(getClass(results, "writer", conf, OutputFormat.class));
        }
        if (results.hasOption("lazyOutput")) {
            if (Boolean.parseBoolean(results.getOptionValue("lazyOutput"))) {
                LazyOutputFormat.setOutputFormatClass(job, job.getOutputFormatClass());
            }
        }
        if (results.hasOption("avroInput")) {
            avroInput = AvroIO.valueOf(results.getOptionValue("avroInput").toUpperCase());
        }
        if (results.hasOption("avroOutput")) {
            avroOutput = AvroIO.valueOf(results.getOptionValue("avroOutput").toUpperCase());
        }

        if (results.hasOption("program")) {
            setExecutable(conf, results.getOptionValue("program"));
        }
        // if they gave us a jar file, include it into the class path
        String jarFile = job.getJar();
        if (jarFile != null) {
            final URL[] urls = new URL[] { FileSystem.getLocal(conf).pathToFile(new Path(jarFile)).toURL() };
            // FindBugs complains that creating a URLClassLoader should be
            // in a doPrivileged() block.
            ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
                public ClassLoader run() {
                    return new URLClassLoader(urls);
                }
            });
            conf.setClassLoader(loader);
        }
        setupPipesJob(job);
        return job.waitForCompletion(true) ? 0 : 1;
    } catch (ParseException pe) {
        LOG.info("Error : " + pe);
        cli.printUsage();
        return 1;
    }
}

From source file:freemarker.log.Logger.java

/**
 * Don't use {@link freemarker.template.utility.SecurityUtilities#getSystemProperty(String, String)} here, as it
 * (might) depends on the logger, hence interfering with the initialization.
 */// www. ja va 2 s .co m
private static String getSystemProperty(final String key) {
    try {
        return (String) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                return System.getProperty(key, null);
            }
        });
    } catch (AccessControlException e) {
        logWarnInLogger("Insufficient permissions to read system property \"" + key + "\".");
        return null;
    } catch (Throwable e) {
        logErrorInLogger("Failed to read system property \"" + key + "\".", e);
        return null;
    }
}

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

/**
 * For setting up the password//from  www  .jav  a  2s.  c  o  m
 * 
 * @param password
 * @param session
 * @return String
 */
@RequestMapping(value = "/setpassword", method = RequestMethod.POST)
public String setPassword(@RequestParam(value = "password", required = true) final String password,
        HttpSession session) {
    {
        logger.debug(
                "###Entering setPassword (@RequestParam(value = password, required = true) final String password, HttpSession session,HttpServletRequest request) ");
        StringBuffer redirect = new StringBuffer();
        redirect.append("redirect:/portal/verify_email");
        final String userParam = (String) session.getAttribute("regParam");

        User user = privilegeService.runAsPortal(new PrivilegedAction<User>() {

            @Override
            public User run() {
                User user = userService.get(userParam);
                if (!config.getBooleanValue(
                        Configuration.Names.com_citrix_cpbm_portal_directory_service_enabled)) {
                    user.setClearPassword(password);
                } else if (config.getValue(Names.com_citrix_cpbm_directory_mode).equals("push")) {
                    user.setClearLdapPassword(password);
                }
                return user;
            }
        });
        userService.update(user, false);
        logger.debug(" AbstractRegistration  After Updating the user in DB password " + user.getPassword());
        return redirect.toString();
    }

}

From source file:org.apache.axis2.datasource.jaxb.JAXBDSContext.java

/**
 * The root element being read is defined by schema/JAXB; however its contents are known by
 * schema/JAXB. Therefore we use unmarshal by the declared type (This method is used to
 * unmarshal rpc elements)/*  w  w  w  .ja va  2s . c  o  m*/
 * 
 * @param u Unmarshaller
 * @param reader XMLStreamReader
 * @param type Class
 * @return Object
 * @throws WebServiceException
 */
public static Object unmarshalByType(final Unmarshaller u, final XMLStreamReader reader, final Class type,
        final boolean isList, final JAXBUtils.CONSTRUCTION_TYPE ctype) throws WebServiceException {

    if (DEBUG_ENABLED) {
        log.debug("Invoking unmarshalByType.");
        log.debug("  type = " + type);
        log.debug("  isList = " + isList);
        log.debug("  ctype = " + ctype);
    }

    return AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            try {
                // Unfortunately RPC is type based. Thus a
                // declared type must be used to unmarshal the xml.
                Object jaxb;

                if (!isList) {
                    // case: We are not unmarshalling an xsd:list but an Array.

                    if (type.isArray()) {
                        // If the context is created using package
                        // we will not have common arrays or type array in the context
                        // but there is not much we can do about it so seralize it as
                        // usual
                        if (ctype == JAXBUtils.CONSTRUCTION_TYPE.BY_CONTEXT_PATH) {
                            if (DEBUG_ENABLED) {
                                log.debug("Unmarshal Array via BY_CONTEXT_PATH approach");
                            }
                            jaxb = u.unmarshal(reader, type);
                        }
                        // list on client array on server, Can happen only in start from java
                        // case.
                        else if ((ctype == JAXBUtils.CONSTRUCTION_TYPE.BY_CLASS_ARRAY)) {
                            // The type could be any Object or primitive

                            //process primitives first
                            //first verify if we have a primitive type associated in the array.
                            //array could be single dimension or multi dimension.
                            Class cType = type.getComponentType();
                            while (cType.isArray()) {
                                cType = cType.getComponentType();
                            }
                            if (cType.isPrimitive()) {
                                if (DEBUG_ENABLED) {
                                    log.debug("Unmarshal Array of primitive via BY_CLASS_ARRAY approach");
                                }
                                jaxb = u.unmarshal(reader, type);
                            }
                            // process non primitive                          
                            // I will first unmarshall the xmldata to a String[]
                            // Then use the unmarshalled jaxbElement to create
                            // proper type Object Array.

                            else {
                                if (DEBUG_ENABLED) {
                                    log.debug("Unmarshal Array of non-primitive via BY_CLASS_ARRAY approach");
                                }
                                jaxb = unmarshalArray(reader, u, type);
                            }

                        } else {
                            if (DEBUG_ENABLED) {
                                log.debug("Unmarshal Array");
                            }
                            jaxb = u.unmarshal(reader, type);

                        }

                    } else if (type.isEnum()) {
                        // When JAXBContext is created using a context path, it will not 
                        // include Enum classes.
                        // These classes have @XmlEnum annotation but not @XmlType/@XmlElement,
                        // so the user will see MarshallingEx, class not known to ctxt.
                        // 
                        // This is a jax-b defect, for now this fix is in place to pass CTS.
                        // This only fixes the
                        // situation where the enum is the top-level object (e.g., message-part
                        // in rpc-lit scenario)
                        //
                        // Sample of what enum looks like:
                        // @XmlEnum public enum EnumString {
                        // @XmlEnumValue("String1") STRING_1("String1"),
                        // @XmlEnumValue("String2") STRING_2("String2");
                        //
                        // public static getValue(String){} <-- resolves a "value" to an emum
                        // object
                        // ... }
                        if (DEBUG_ENABLED) {
                            log.debug("Unmarshalling " + type.getName() + " as Enum");
                        }

                        JAXBElement<String> enumValue = u.unmarshal(reader,
                                XmlEnumUtils.getConversionType(type));

                        if (enumValue != null) {
                            jaxb = XmlEnumUtils.fromValue(type, enumValue.getValue());
                        } else {
                            jaxb = null;
                        }
                    }
                    //Normal case: We are not unmarshalling a xsd:list or Array
                    else {
                        if (DEBUG_ENABLED) {
                            log.debug("Unmarshalling normal case (not array, not xsd:list, not enum)");
                        }
                        jaxb = u.unmarshal(reader, type);
                    }

                } else {
                    // If this is an xsd:list, we need to return the appropriate
                    // list or array (see NOTE above)
                    // First unmarshal as a String
                    //Second convert the String into a list or array
                    if (DEBUG_ENABLED) {
                        log.debug("Unmarshalling xsd:list");
                    }
                    jaxb = unmarshalAsListOrArray(reader, u, type);

                }
                if (log.isDebugEnabled()) {
                    Class cls;
                    if (jaxb == null) {
                        if (DEBUG_ENABLED) {
                            log.debug("End unmarshalByType returning null object");
                        }

                    } else if (jaxb instanceof JAXBElement) {
                        JAXBElement jbe = (JAXBElement) jaxb;
                        if (DEBUG_ENABLED) {
                            log.debug("End unmarshalByType returning JAXBElement");
                            log.debug("  Class = " + jbe.getDeclaredType());
                            log.debug("  QName = " + jbe.getName());
                        }
                    } else {
                        if (DEBUG_ENABLED) {
                            log.debug("End unmarshalByType returning " + jaxb.getClass());
                        }
                    }
                }
                return jaxb;
            } catch (OMException e) {
                throw e;
            } catch (Throwable t) {
                throw new OMException(t);
            }
        }
    });
}

From source file:eu.europa.ejusticeportal.dss.applet.DssApplet.java

/**
 * DssApplet destroy ://from   ww  w .jav  a 2s.  co m
 * <ul>
 * <li>[1] Close the JRE instance which was running the DssApplet.</li>
 * </ul>
 *
 * {@inheritDoc}
 */
@Override
public void destroy() {
    LOG.info("Applet is destroying...");
    /*
     * The Java process created by the applet can take more than five minutes to exit, the System is required to
     * exit to bypass this behaviour.
     * All required operations are already done in stop() function.
     */
    AccessController.doPrivileged(new PrivilegedAction<Void>() {
        public Void run() {
            //TODO remove the System.exit(0). 
            //If the user has other applets running in his browser we also kill those.
            System.exit(0);
            return null;
        }
    });
}

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

/**
 * @param userName//from   w  w  w  . j a va 2  s.c o m
 * @param pickValFromReset
 * @param request
 * @return
 * @throws JsonGenerationException
 * @throws JsonMappingException
 * @throws IOException
 */
@RequestMapping(value = "/request_sms_by_user", method = RequestMethod.POST)
@ResponseBody
public Map<String, String> requestSMS(@RequestParam(value = "userName", required = false) final String userName,
        @RequestParam(value = "pickValFromReset", required = false) final String pickValFromReset,
        HttpServletRequest request) throws JsonGenerationException, JsonMappingException, IOException {
    String generatedPhoneVerificationPin = request.getSession().getAttribute("phoneVerificationPin").toString();
    final String userNameLoc;
    Map<String, String> returnResponse = new HashMap<String, String>();

    if (pickValFromReset != null && pickValFromReset.equals("pick")) {
        userNameLoc = (String) request.getSession().getAttribute(RESET_USER_KEY);
    } else if (userName != null) {
        userNameLoc = userName;
    } else {
        returnResponse.put("result", "failed");
        returnResponse.put("message",
                messageSource.getMessage("js.errors.register.textMessageFailed", null, request.getLocale()));
        return returnResponse;
    }

    request.getSession().setAttribute("userName", userNameLoc);
    User user = null;
    try {
        user = privilegeService.runAsPortal(new PrivilegedAction<User>() {

            @Override
            public User run() {
                User user = userService.getUserByParam("username", userNameLoc, false);
                return user;
            }
        });
    } catch (NoSuchUserException e) {
    }

    if (user == null) {
        returnResponse.put("result", "success"); // Returning success for security
        // reason.
        returnResponse.put("message",
                messageSource.getMessage("js.errors.register.textMessageRequested", null, request.getLocale()));
        return returnResponse;
    }

    try {
        String refId = ((TelephoneVerificationService) connectorManagementService
                .getOssServiceInstancebycategory(ConnectorType.PHONE_VERIFICATION)).requestSMS(
                        user.getCountryCode(), user.getPhoneWithoutIsdCode(), generatedPhoneVerificationPin);
        if (refId != null) {
            returnResponse.put("result", "success");
            returnResponse.put("message", messageSource.getMessage("js.errors.register.textMessageRequested",
                    null, request.getLocale()));
        } else {
            returnResponse.put("result", "failed");
            returnResponse.put("message", messageSource.getMessage("js.errors.register.textMessageFailed", null,
                    request.getLocale()));
        }
    } catch (TelephoneVerificationServiceException e) {
        returnResponse.put("result", "failed");
        returnResponse.put("message",
                messageSource.getMessage("js.errors.register.textMessageFailed", null, request.getLocale()));
    }

    return returnResponse;
}