List of usage examples for java.security PrivilegedAction PrivilegedAction
PrivilegedAction
From source file:org.acmsl.commons.regexpplugin.RegexpManager.java
/** * Return a new instance of the specified <code>RegexpEngine</code> * implementation class, loaded by the specified class loader. * If that fails, try the class loader used to load the * RegexpEngine./* www . ja va 2 s . com*/ * @param engineClass Fully qualified name of the <code>RegexpEngine</code> * implementation class. * @param classLoader ClassLoader from which to load this class. * @throws RegexpEngineNotFoundException if a suitable instance * cannot be created. * @throws RegexpPluginMisconfiguredException if RegexpPlugin is * misconfigured. * @return the {@link RegexpEngine}. */ @SuppressWarnings("unchecked") @NotNull protected RegexpEngine createEngine(final String engineClass, final ClassLoader classLoader) throws RegexpEngineNotFoundException, RegexpPluginMisconfiguredException { @Nullable final RegexpEngine result = AccessController.doPrivileged(new PrivilegedAction<RegexpEngine>() { public RegexpEngine run() { RegexpEngine innerResult = null; final RegexpPluginMisconfiguredException exception; // This will be used to diagnose bad configurations // and allow a useful message to be sent to the user Class<RegexpEngine> t_RegexpEngineClass = null; try { if (classLoader != null) { try { // First the given class loader param // (thread class loader) // Warning: must typecast here & allow // exception to be generated/caught & // recast properly. t_RegexpEngineClass = (Class<RegexpEngine>) classLoader.loadClass(engineClass); innerResult = t_RegexpEngineClass.newInstance(); } catch (final ClassNotFoundException classNotFoundException) { if (classLoader == RegexpEngine.class.getClassLoader()) { // Nothing more to try, onwards. throw classNotFoundException; } // ignore exception, continue } catch (final NoClassDefFoundError noClassDefFoundException) { if (classLoader == RegexpEngine.class.getClassLoader()) { // Nothing more to try, onwards. throw noClassDefFoundException; } // ignore exception, continue } catch (final ClassCastException classCastException) { if (classLoader == RegexpEngine.class.getClassLoader()) { // Nothing more to try, onwards (bug in // loader implementation). throw classCastException; } // Ignore exception, continue } } if (innerResult == null) { /* At this point, either classLoader == null, OR * classLoader was unable to load engineClass. * Try the class loader that loaded this class: * RegexpEngine.getClassLoader(). * * Notes: * a) RegexpEngine.class.getClassLoader() may return * 'null' if RegexpEngine is loaded by the bootstrap * classloader. * b) The Java endorsed library mechanism is instead * Class.forName(engineClass); */ // Warning: must typecast here & allow exception // to be generated/caught & recast properly. t_RegexpEngineClass = (Class<RegexpEngine>) Class.forName(engineClass); innerResult = t_RegexpEngineClass.newInstance(); } } catch (final Exception otherException) { // Check to see if we've got a bad configuration if ((t_RegexpEngineClass != null) && (!RegexpEngine.class.isAssignableFrom(t_RegexpEngineClass))) { exception = new RegexpPluginMisconfiguredException( "implementation.does.not." + "implement.regexpegine", otherException); } else { exception = new RegexpPluginMisconfiguredException("unexpected.problem", otherException); } throw exception; } return innerResult; } }); if (result == null) { throw new RegexpEngineNotFoundException(engineClass); } return result; }
From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractRegistrationController.java
/** * @author amitpals: Call Flow- User Clicks on the link Emailed to him post registration * @param model//from ww w.j a va 2 s.c o m * @param request * @return :- Jsp Prompting user to enter password */ // verifyUser mapping is to have upgrade compatibility for email verifyUser @RequestMapping(value = { "/verify_user", "/verifyUser" }, method = RequestMethod.GET) public String updatePasswordAndVerifyEmail(@RequestParam(value = "a", required = true) final String auth, @RequestParam(value = "i", required = true) final String userParam, final HttpServletRequest request, ModelMap model, HttpSession session) { logger.debug("###Entering in checkPassword(auth,userId,request) method @GET"); String redirect = null; redirect = "/portal/login"; User user = privilegeService.runAsPortal(new PrivilegedAction<User>() { @Override public User run() { User user = userService.get(userParam); Locale locale = user.getLocale(); if (locale != null) { WebUtils.setSessionAttribute(request, SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, locale); } return user; } }); // needed in verifyemail session.setAttribute("regAuth", auth); session.setAttribute("regParam", userParam); if (user.getPassword() == null && (!config.getBooleanValue(Configuration.Names.com_citrix_cpbm_portal_directory_service_enabled) || config.getValue(Names.com_citrix_cpbm_directory_mode).equals("push"))) { return "register.setpassword"; } if (user.isEmailVerified()) { return "redirect:" + redirect; } else { return "redirect:" + "/portal/verify_email"; } }
From source file:org.apache.axis2.jaxws.util.WSDL4JWrapper.java
private boolean isAFile(final File f) { Boolean ret = (Boolean) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return new Boolean(f.exists() && !f.isDirectory()); }/* w w w .j ava 2 s . c o m*/ }); return ret.booleanValue(); }
From source file:org.apache.hadoop.mapred.pipes.Submitter.java
@Override public int run(String[] args) throws Exception { CommandLineParser cli = new CommandLineParser(); if (args.length == 0) { cli.printUsage();//w w w .j a va 2 s. co m return 1; } cli.addOption("input", false, "input path to the maps", "path"); cli.addOption("output", false, "output path from the reduces", "path"); cli.addOption("jar", false, "job jar file", "path"); cli.addOption("inputformat", false, "java classname of InputFormat", "class"); //cli.addArgument("javareader", false, "is the RecordReader in Java"); cli.addOption("map", false, "java classname of Mapper", "class"); cli.addOption("partitioner", false, "java classname of Partitioner", "class"); cli.addOption("reduce", false, "java classname of Reducer", "class"); cli.addOption("writer", false, "java classname of OutputFormat", "class"); cli.addOption("program", false, "URI to application executable", "class"); cli.addOption("reduces", false, "number of reduces", "num"); cli.addOption("jobconf", false, "\"n1=v1,n2=v2,..\" (Deprecated) Optional. Add or override a JobConf property.", "key=val"); Parser parser = cli.createParser(); try { GenericOptionsParser genericParser = new GenericOptionsParser(getConf(), args); CommandLine results = parser.parse(cli.options, genericParser.getRemainingArgs()); JobConf job = new JobConf(getConf()); if (results.hasOption("input")) { FileInputFormat.setInputPaths(job, (String) results.getOptionValue("input")); } if (results.hasOption("output")) { FileOutputFormat.setOutputPath(job, new Path((String) results.getOptionValue("output"))); } if (results.hasOption("jar")) { job.setJar((String) results.getOptionValue("jar")); } if (results.hasOption("inputformat")) { setIsJavaRecordReader(job, true); job.setInputFormat(getClass(results, "inputformat", job, InputFormat.class)); } if (results.hasOption("javareader")) { setIsJavaRecordReader(job, true); } if (results.hasOption("map")) { setIsJavaMapper(job, true); job.setMapperClass(getClass(results, "map", job, Mapper.class)); } if (results.hasOption("partitioner")) { job.setPartitionerClass(getClass(results, "partitioner", job, Partitioner.class)); } if (results.hasOption("reduce")) { setIsJavaReducer(job, true); job.setReducerClass(getClass(results, "reduce", job, Reducer.class)); } if (results.hasOption("reduces")) { job.setNumReduceTasks(Integer.parseInt((String) results.getOptionValue("reduces"))); } if (results.hasOption("writer")) { setIsJavaRecordWriter(job, true); job.setOutputFormat(getClass(results, "writer", job, OutputFormat.class)); } if (results.hasOption("program")) { setExecutable(job, (String) results.getOptionValue("program")); } if (results.hasOption("jobconf")) { LOG.warn("-jobconf option is deprecated, please use -D instead."); String options = (String) results.getOptionValue("jobconf"); StringTokenizer tokenizer = new StringTokenizer(options, ","); while (tokenizer.hasMoreTokens()) { String keyVal = tokenizer.nextToken().trim(); String[] keyValSplit = keyVal.split("=", 2); job.set(keyValSplit[0], keyValSplit[1]); } } // 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(job).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); } }); job.setClassLoader(loader); } runJob(job); return 0; } catch (ParseException pe) { LOG.info("Error : " + pe); cli.printUsage(); return 1; } }
From source file:org.eclipse.gemini.blueprint.extender.internal.dependencies.startup.DependencyServiceManager.java
protected void register() { final String filter = createDependencyFilter(); if (log.isDebugEnabled()) { log.debug(context.getDisplayName() + " has registered service dependency dependencyDetector with filter: " + filter); }//from w w w . j a va2s .co m // send dependency event before registering the filter sendInitialBootstrappingEvents(getUnsatisfiedDependencies().keySet()); if (System.getSecurityManager() != null) { AccessControlContext acc = getAcc(); AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { OsgiListenerUtils.addServiceListener(bundleContext, listener, filter); return null; } }, acc); } else { OsgiListenerUtils.addServiceListener(bundleContext, listener, filter); } }
From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractAuthenticationController.java
/** * @param userName/*from w ww .jav a 2s . c om*/ * @param pickValFromReset * @param request * @return * @throws JsonGenerationException * @throws JsonMappingException * @throws IOException */ @RequestMapping(value = "/request_call_by_user", method = RequestMethod.POST) @ResponseBody public Map<String, String> requestCall( @RequestParam(value = "userName", required = false) final String userName, @RequestParam(value = "pickValFromReset", required = false) final String pickValFromReset, HttpServletRequest request) throws JsonGenerationException, JsonMappingException, IOException { Map<String, String> returnResponse = new HashMap<String, String>(); String generatedPhoneVerificationPin = request.getSession().getAttribute("phoneVerificationPin").toString(); final String userNameLoc; 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.callFailed", 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", "failed"); returnResponse.put("message", messageSource.getMessage("js.errors.register.callFailed", null, request.getLocale())); return returnResponse; } try { String refId = ((TelephoneVerificationService) connectorManagementService .getOssServiceInstancebycategory(ConnectorType.PHONE_VERIFICATION)).requestCall( user.getCountryCode(), user.getPhoneWithoutIsdCode(), generatedPhoneVerificationPin); if (refId != null) { returnResponse.put("result", "success"); returnResponse.put("message", messageSource.getMessage("js.errors.register.callRequested", null, request.getLocale())); } else { returnResponse.put("result", "failed"); returnResponse.put("message", messageSource.getMessage("js.errors.register.callFailed", null, request.getLocale())); } } catch (TelephoneVerificationServiceException e) { returnResponse.put("result", "failed"); returnResponse.put("message", messageSource.getMessage("js.errors.register.callFailed", null, request.getLocale())); } return returnResponse; }
From source file:org.apache.ranger.biz.KmsKeyMgr.java
public VXKmsKey getKey(String provider, String name) throws Exception { String providers[] = null;//from w w w . j a va 2s .c om try { providers = getKMSURL(provider); } catch (Exception e) { logger.error("getKey(" + 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 keyRest = KMS_KEY_METADATA_URI.replaceAll(Pattern.quote("${alias}"), name); String currentUserLoginId = ContextUtil.getCurrentUserLoginId(); String uri = providers[i] + (providers[i].endsWith("/") ? keyRest : ("/" + keyRest)); 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.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE) .get(String.class); } else { Subject sub = getSubjectForKerberos(provider); 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; } catch (Exception e) { if (e instanceof UniformInterfaceException || i == providers.length - 1) throw e; else continue; } } } return null; }
From source file:org.apache.hama.pipes.Submitter.java
@Override public int run(String[] args) throws Exception { CommandLineParser cli = new CommandLineParser(); if (args.length == 0) { cli.printUsage();/*from w w w . ja v a 2 s. c o m*/ return 1; } LOG.debug("Hama pipes Submitter started!"); cli.addOption("input", false, "input path for bsp", "path"); cli.addOption("output", false, "output path from bsp", "path"); cli.addOption("jar", false, "job jar file", "path"); cli.addOption("inputformat", false, "java classname of InputFormat", "class"); // cli.addArgument("javareader", false, "is the RecordReader in Java"); cli.addOption("partitioner", false, "java classname of Partitioner", "class"); cli.addOption("outputformat", false, "java classname of OutputFormat", "class"); cli.addOption("cachefiles", false, "additional cache files to add", "space delimited paths"); cli.addOption("interpreter", false, "interpreter, like python or bash", "executable"); cli.addOption("jobname", false, "the jobname", "name"); cli.addOption("programArgs", false, "program arguments", "arguments"); cli.addOption("bspTasks", false, "how many bsp tasks to launch", "number"); cli.addOption("streaming", false, "if supplied, streaming is used instead of pipes", ""); cli.addOption("jobconf", false, "\"n1=v1,n2=v2,..\" (Deprecated) Optional. Add or override a JobConf property.", "key=val"); cli.addOption("program", false, "URI to application executable", "class"); Parser parser = cli.createParser(); try { // check generic arguments -conf GenericOptionsParser genericParser = new GenericOptionsParser(getConf(), args); // get other arguments CommandLine results = parser.parse(cli.options, genericParser.getRemainingArgs()); BSPJob job = new BSPJob(getConf()); if (results.hasOption("input")) { FileInputFormat.setInputPaths(job, results.getOptionValue("input")); } if (results.hasOption("output")) { FileOutputFormat.setOutputPath(job, new Path(results.getOptionValue("output"))); } if (results.hasOption("jar")) { job.setJar(results.getOptionValue("jar")); } if (results.hasOption("jobname")) { job.setJobName(results.getOptionValue("jobname")); } if (results.hasOption("inputformat")) { job.setInputFormat(getClass(results, "inputformat", conf, InputFormat.class)); } if (results.hasOption("partitioner")) { job.setPartitioner(getClass(results, "partitioner", conf, Partitioner.class)); } if (results.hasOption("outputformat")) { job.setOutputFormat(getClass(results, "outputformat", conf, OutputFormat.class)); } if (results.hasOption("streaming")) { LOG.info("Streaming enabled!"); job.set("hama.streaming.enabled", "true"); } if (results.hasOption("jobconf")) { LOG.warn("-jobconf option is deprecated, please use -D instead."); String options = results.getOptionValue("jobconf"); StringTokenizer tokenizer = new StringTokenizer(options, ","); while (tokenizer.hasMoreTokens()) { String keyVal = tokenizer.nextToken().trim(); String[] keyValSplit = keyVal.split("=", 2); job.set(keyValSplit[0], keyValSplit[1]); } } if (results.hasOption("bspTasks")) { int optionValue = Integer.parseInt(results.getOptionValue("bspTasks")); conf.setInt("bsp.local.tasks.maximum", optionValue); conf.setInt("bsp.peers.num", optionValue); } if (results.hasOption("program")) { String executablePath = results.getOptionValue("program"); setExecutable(job.getConfiguration(), executablePath); DistributedCache.addCacheFile(new Path(executablePath).toUri(), conf); } if (results.hasOption("interpreter")) { job.getConfiguration().set("hama.pipes.executable.interpretor", results.getOptionValue("interpreter")); } if (results.hasOption("programArgs")) { job.getConfiguration().set("hama.pipes.executable.args", Joiner.on(" ").join(results.getOptionValues("programArgs"))); // job.getConfiguration().set("hama.pipes.resolve.executable.args", // "true"); } if (results.hasOption("cachefiles")) { FileSystem fs = FileSystem.get(getConf()); String[] optionValues = results.getOptionValues("cachefiles"); for (String s : optionValues) { Path path = new Path(s); FileStatus[] globStatus = fs.globStatus(path); for (FileStatus f : globStatus) { if (!f.isDir()) { DistributedCache.addCacheFile(f.getPath().toUri(), job.getConfiguration()); } else { LOG.info("Ignoring directory " + f.getPath() + " while globbing."); } } } } // if they gave us a jar file, include it into the class path String jarFile = job.getJar(); if (jarFile != null) { @SuppressWarnings("deprecation") 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>() { @Override public ClassLoader run() { return new URLClassLoader(urls); } }); conf.setClassLoader(loader); } runJob(job); return 0; } catch (ParseException pe) { LOG.info("Error : " + pe); cli.printUsage(); return 1; } }
From source file:org.apache.zeppelin.submarine.hadoop.YarnClient.java
public HttpResponse callRestUrl(final String url, final String userId, HTTP operation) { if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format("Calling YarnClient %s %s %s", this.principal, this.keytab, url)); }/*from ww w . ja va2 s. c om*/ javax.security.auth.login.Configuration config = new javax.security.auth.login.Configuration() { @SuppressWarnings("serial") @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { return new AppConfigurationEntry[] { new AppConfigurationEntry( "com.sun.security.auth.module.Krb5LoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, new HashMap<String, Object>() { { put("useTicketCache", "false"); put("useKeyTab", "true"); put("keyTab", keytab); // Krb5 in GSS API needs to be refreshed so it does not throw the error // Specified version of key is not available put("refreshKrb5Config", "true"); put("principal", principal); put("storeKey", "true"); put("doNotPrompt", "true"); put("isInitiator", "true"); if (LOGGER.isDebugEnabled()) { put("debug", "true"); } } }) }; } }; Set<Principal> principals = new HashSet<Principal>(1); principals.add(new KerberosPrincipal(userId)); Subject sub = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>()); try { // Authentication module: Krb5Login LoginContext loginContext = new LoginContext("Krb5Login", sub, null, config); loginContext.login(); Subject serviceSubject = loginContext.getSubject(); return Subject.doAs(serviceSubject, new PrivilegedAction<HttpResponse>() { HttpResponse httpResponse = null; @Override public HttpResponse run() { try { HttpUriRequest request = null; switch (operation) { case DELETE: request = new HttpDelete(url); break; case POST: request = new HttpPost(url); break; default: request = new HttpGet(url); break; } HttpClient spengoClient = buildSpengoHttpClient(); httpResponse = spengoClient.execute(request); return httpResponse; } catch (IOException e) { LOGGER.error(e.getMessage(), e); } return httpResponse; } }); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return null; }
From source file:org.apache.hadoop.yarn.server.resourcemanager.TestClientRMTokens.java
private ApplicationClientProtocol getClientRMProtocolWithDT(org.apache.hadoop.yarn.api.records.Token token, final InetSocketAddress rmAddress, String user, final Configuration conf) { // Maybe consider converting to Hadoop token, serialize de-serialize etc // before trying to renew the token. UserGroupInformation ugi = UserGroupInformation.createRemoteUser(user); ugi.addToken(ConverterUtils.convertFromYarn(token, rmAddress)); final YarnRPC rpc = YarnRPC.create(conf); ApplicationClientProtocol clientRMWithDT = ugi.doAs(new PrivilegedAction<ApplicationClientProtocol>() { @Override/*w ww . ja va2s. c om*/ public ApplicationClientProtocol run() { return (ApplicationClientProtocol) rpc.getProxy(ApplicationClientProtocol.class, rmAddress, conf); } }); return clientRMWithDT; }