List of usage examples for java.security PrivilegedAction PrivilegedAction
PrivilegedAction
From source file:org.apache.accumulo.tserver.replication.AccumuloReplicaSystem.java
@Override public Status replicate(final Path p, final Status status, final ReplicationTarget target, final ReplicaSystemHelper helper) { final Instance localInstance = HdfsZooInstance.getInstance(); final AccumuloConfiguration localConf = new ServerConfigurationFactory(localInstance).getConfiguration(); final String principal = getPrincipal(localConf, target); final File keytab; final String password; if (localConf.getBoolean(Property.INSTANCE_RPC_SASL_ENABLED)) { String keytabPath = getKeytab(localConf, target); keytab = new File(keytabPath); if (!keytab.exists() || !keytab.isFile()) { log.error("{} is not a regular file. Cannot login to replicate", keytabPath); return status; }//from w w w. ja va 2 s .co m password = null; } else { keytab = null; password = getPassword(localConf, target); } if (null != keytab) { try { final UserGroupInformation accumuloUgi = UserGroupInformation.getCurrentUser(); // Get a UGI with the principal + keytab UserGroupInformation ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(principal, keytab.getAbsolutePath()); // Run inside a doAs to avoid nuking the Tserver's user return ugi.doAs(new PrivilegedAction<Status>() { @Override public Status run() { KerberosToken token; try { // Do *not* replace the current user token = new KerberosToken(principal, keytab, false); } catch (IOException e) { log.error("Failed to create KerberosToken", e); return status; } ClientContext peerContext = getContextForPeer(localConf, target, principal, token); return _replicate(p, status, target, helper, localConf, peerContext, accumuloUgi); } }); } catch (IOException e) { // Can't log in, can't replicate log.error("Failed to perform local login", e); return status; } } else { // Simple case: make a password token, context and then replicate PasswordToken token = new PasswordToken(password); ClientContext peerContext = getContextForPeer(localConf, target, principal, token); return _replicate(p, status, target, helper, localConf, peerContext, null); } }
From source file:org.apache.ranger.services.kms.client.KMSClient.java
public List<String> getKeyList(final String keyNameMatching, final List<String> existingKeyList) { String providers[] = null;//from ww w. ja v a2 s. c o m try { providers = createProvider(provider); } catch (IOException | URISyntaxException e) { return null; } final String errMsg = errMessage; List<String> lret = null; for (int i = 0; i < providers.length; i++) { lret = new ArrayList<String>(); if (LOG.isDebugEnabled()) { LOG.debug("Getting Kms Key list for keyNameMatching : " + keyNameMatching); } String uri = providers[i] + (providers[i].endsWith("/") ? KMS_LIST_API_ENDPOINT : ("/" + KMS_LIST_API_ENDPOINT)); Client client = null; ClientResponse response = null; boolean isKerberos = false; try { ClientConfig cc = new DefaultClientConfig(); cc.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true); client = Client.create(cc); if (authType != null && authType.equalsIgnoreCase(AUTH_TYPE_KERBEROS)) { isKerberos = true; } Subject sub = new Subject(); if (!isKerberos) { uri = uri.concat("?user.name=" + username); WebResource webResource = client.resource(uri); response = webResource.accept(EXPECTED_MIME_TYPE).get(ClientResponse.class); LOG.info("Init Login: security not enabled, using username"); sub = SecureClientLogin.login(username); } else { if (!StringUtils.isEmpty(rangerPrincipal) && !StringUtils.isEmpty(rangerKeytab)) { LOG.info("Init Lookup Login: security enabled, using rangerPrincipal/rangerKeytab"); if (StringUtils.isEmpty(nameRules)) { nameRules = "DEFAULT"; } String shortName = new HadoopKerberosName(rangerPrincipal).getShortName(); uri = uri.concat("?doAs=" + shortName); sub = SecureClientLogin.loginUserFromKeytab(rangerPrincipal, rangerKeytab, nameRules); } else { LOG.info("Init Login: using username/password"); String shortName = new HadoopKerberosName(username).getShortName(); uri = uri.concat("?doAs=" + shortName); String decryptedPwd = PasswordUtils.decryptPassword(password); sub = SecureClientLogin.loginUserWithPassword(username, decryptedPwd); } } final WebResource webResource = client.resource(uri); response = Subject.doAs(sub, new PrivilegedAction<ClientResponse>() { @Override public ClientResponse run() { return webResource.accept(EXPECTED_MIME_TYPE).get(ClientResponse.class); } }); if (LOG.isDebugEnabled()) { LOG.debug("getKeyList():calling " + uri); } if (response != null) { if (LOG.isDebugEnabled()) { LOG.debug("getKeyList():response.getStatus()= " + response.getStatus()); } if (response.getStatus() == 200) { String jsonString = response.getEntity(String.class); Gson gson = new GsonBuilder().setPrettyPrinting().create(); @SuppressWarnings("unchecked") List<String> keys = gson.fromJson(jsonString, List.class); if (keys != null) { for (String key : keys) { if (existingKeyList != null && existingKeyList.contains(key)) { continue; } if (keyNameMatching == null || keyNameMatching.isEmpty() || key.startsWith(keyNameMatching)) { if (LOG.isDebugEnabled()) { LOG.debug("getKeyList():Adding kmsKey " + key); } lret.add(key); } } return lret; } } else if (response.getStatus() == 401) { LOG.info("getKeyList():response.getStatus()= " + response.getStatus() + " for URL " + uri + ", so returning null list"); String msgDesc = response.getEntity(String.class); HadoopException hdpException = new HadoopException(msgDesc); hdpException.generateResponseDataMap(false, msgDesc, msgDesc + errMsg, null, null); lret = null; throw hdpException; } else if (response.getStatus() == 403) { LOG.info("getKeyList():response.getStatus()= " + response.getStatus() + " for URL " + uri + ", so returning null list"); String msgDesc = response.getEntity(String.class); HadoopException hdpException = new HadoopException(msgDesc); hdpException.generateResponseDataMap(false, msgDesc, msgDesc + errMsg, null, null); lret = null; throw hdpException; } else { LOG.info("getKeyList():response.getStatus()= " + response.getStatus() + " for URL " + uri + ", so returning null list"); String jsonString = response.getEntity(String.class); LOG.info(jsonString); lret = null; } } else { String msgDesc = "Unable to get a valid response for " + "expected mime type : [" + EXPECTED_MIME_TYPE + "] URL : " + uri + " - got null response."; LOG.error(msgDesc); HadoopException hdpException = new HadoopException(msgDesc); hdpException.generateResponseDataMap(false, msgDesc, msgDesc + errMsg, null, null); lret = null; throw hdpException; } } catch (HadoopException he) { lret = null; throw he; } catch (Throwable t) { String msgDesc = "Exception while getting Kms Key List. URL : " + uri; HadoopException hdpException = new HadoopException(msgDesc, t); LOG.error(msgDesc, t); hdpException.generateResponseDataMap(false, BaseClient.getMessage(t), msgDesc + errMsg, null, null); lret = null; throw hdpException; } finally { if (response != null) { response.close(); } if (client != null) { client.destroy(); } if (lret == null) { if (i != providers.length - 1) continue; } } } return lret; }
From source file:org.apache.maven.plugin.checkstyle.exec.DefaultCheckstyleExecutor.java
public CheckstyleResults executeCheckstyle(CheckstyleExecutorRequest request) throws CheckstyleExecutorException, CheckstyleException { // Checkstyle will always use the context classloader in order // to load resources (dtds), // so we have to fix it // olamy this hack is not anymore needed in Maven 3.x ClassLoader checkstyleClassLoader = PackageNamesLoader.class.getClassLoader(); Thread.currentThread().setContextClassLoader(checkstyleClassLoader); if (getLogger().isDebugEnabled()) { getLogger().debug("executeCheckstyle start headerLocation : " + request.getHeaderLocation()); }/*from w w w .jav a 2s . c o m*/ MavenProject project = request.getProject(); configureResourceLocator(locator, request, null); configureResourceLocator(licenseLocator, request, request.getLicenseArtifacts()); // Config is less critical than License, locator can still be used. // configureResourceLocator( configurationLocator, request, request.getConfigurationArtifacts() ); List<File> files; try { files = getFilesToProcess(request); } catch (IOException e) { throw new CheckstyleExecutorException("Error getting files to process", e); } final String suppressionsFilePath = getSuppressionsFilePath(request); FilterSet filterSet = getSuppressionsFilterSet(suppressionsFilePath); Checker checker = new Checker(); // setup classloader, needed to avoid "Unable to get class information for ..." errors List<String> classPathStrings = new ArrayList<String>(); List<String> outputDirectories = new ArrayList<String>(); // stand-alone Collection<File> sourceDirectories = null; Collection<File> testSourceDirectories = request.getTestSourceDirectories(); // aggregator Map<MavenProject, Collection<File>> sourceDirectoriesByProject = new HashMap<MavenProject, Collection<File>>(); Map<MavenProject, Collection<File>> testSourceDirectoriesByProject = new HashMap<MavenProject, Collection<File>>(); if (request.isAggregate()) { for (MavenProject childProject : request.getReactorProjects()) { sourceDirectories = new ArrayList<File>(childProject.getCompileSourceRoots().size()); List<String> compileSourceRoots = childProject.getCompileSourceRoots(); for (String compileSourceRoot : compileSourceRoots) { sourceDirectories.add(new File(compileSourceRoot)); } sourceDirectoriesByProject.put(childProject, sourceDirectories); testSourceDirectories = new ArrayList<File>(childProject.getTestCompileSourceRoots().size()); List<String> testCompileSourceRoots = childProject.getTestCompileSourceRoots(); for (String testCompileSourceRoot : testCompileSourceRoots) { testSourceDirectories.add(new File(testCompileSourceRoot)); } testSourceDirectoriesByProject.put(childProject, testSourceDirectories); prepareCheckstylePaths(request, childProject, classPathStrings, outputDirectories, sourceDirectories, testSourceDirectories); } } else { sourceDirectories = request.getSourceDirectories(); prepareCheckstylePaths(request, project, classPathStrings, outputDirectories, sourceDirectories, testSourceDirectories); } final List<URL> urls = new ArrayList<URL>(classPathStrings.size()); for (String path : classPathStrings) { try { urls.add(new File(path).toURL()); } catch (MalformedURLException e) { throw new CheckstyleExecutorException(e.getMessage(), e); } } for (String outputDirectoryString : outputDirectories) { try { if (outputDirectoryString != null) { File outputDirectoryFile = new File(outputDirectoryString); if (outputDirectoryFile.exists()) { URL outputDirectoryUrl = outputDirectoryFile.toURL(); getLogger().debug("Adding the outputDirectory " + outputDirectoryUrl.toString() + " to the Checkstyle class path"); urls.add(outputDirectoryUrl); } } } catch (MalformedURLException e) { throw new CheckstyleExecutorException(e.getMessage(), e); } } URLClassLoader projectClassLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() { public URLClassLoader run() { return new URLClassLoader(urls.toArray(new URL[urls.size()]), null); } }); checker.setClassloader(projectClassLoader); checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader()); if (filterSet != null) { checker.addFilter(filterSet); } Configuration configuration = getConfiguration(request); checker.configure(configuration); AuditListener listener = request.getListener(); if (listener != null) { checker.addListener(listener); } if (request.isConsoleOutput()) { checker.addListener(request.getConsoleListener()); } CheckstyleCheckerListener checkerListener = new CheckstyleCheckerListener(configuration); if (request.isAggregate()) { for (MavenProject childProject : request.getReactorProjects()) { sourceDirectories = sourceDirectoriesByProject.get(childProject); testSourceDirectories = testSourceDirectoriesByProject.get(childProject); addSourceDirectory(checkerListener, sourceDirectories, testSourceDirectories, childProject.getResources(), request); } } else { addSourceDirectory(checkerListener, sourceDirectories, testSourceDirectories, request.getResources(), request); } checker.addListener(checkerListener); int nbErrors = checker.process(files); checker.destroy(); if (projectClassLoader instanceof Closeable) { try { ((Closeable) projectClassLoader).close(); } catch (IOException ex) { // Nothing we can do - and not detrimental to the build (save running out of file handles). getLogger().info("Failed to close custom Classloader - this indicated a bug in the code.", ex); } } if (request.getStringOutputStream() != null) { String message = request.getStringOutputStream().toString().trim(); if (message.length() > 0) { getLogger().info(message); } } if (nbErrors > 0) { String message = "There are " + nbErrors + " checkstyle errors."; if (request.isFailsOnError()) { // TODO: should be a failure, not an error. Report is not meant to // throw an exception here (so site would // work regardless of config), but should record this information throw new CheckstyleExecutorException(message); } else { getLogger().info(message); } } return checkerListener.getResults(); }
From source file:org.apache.axis2.jaxws.client.async.AsyncResponse.java
ClassLoader getParentClassLoader(final ClassLoader cl) { return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return cl.getParent(); }/*from w ww . java2s .c om*/ }); }
From source file:org.eclipse.gemini.blueprint.config.internal.adapter.OsgiServiceRegistrationListenerAdapter.java
public void unregistered(final Object service, final Map serviceProperties) { boolean trace = log.isTraceEnabled(); if (trace)/*w w w . j av a 2s .c o m*/ log.trace("Invoking unregistered method with props=" + serviceProperties); if (!initialized) retrieveTarget(); boolean isSecurityEnabled = System.getSecurityManager() != null; AccessControlContext acc = null; if (isSecurityEnabled) { acc = SecurityUtils.getAccFrom(beanFactory); } // first call interface method (if it exists) if (isListener) { if (trace) log.trace("Invoking listener interface methods"); try { if (isSecurityEnabled) { AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { ((OsgiServiceRegistrationListener) target).unregistered(service, serviceProperties); return null; } }, acc); } else { ((OsgiServiceRegistrationListener) target).unregistered(service, serviceProperties); } } catch (Exception ex) { log.warn("Standard unregistered method on [" + target.getClass().getName() + "] threw exception", ex); } } if (isSecurityEnabled) { AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { CustomListenerAdapterUtils.invokeCustomMethods(target, unregistrationMethods, service, serviceProperties); return null; } }, acc); } else { CustomListenerAdapterUtils.invokeCustomMethods(target, unregistrationMethods, service, serviceProperties); } }
From source file:org.solmix.runtime.support.spring.ContainerApplicationContext.java
static String getSpringValidationMode() { return AccessController.doPrivileged(new PrivilegedAction<String>() { @Override//w w w . ja va2 s.co m public String run() { String mode = System.getProperty("solmix.spring.validation.mode"); if (mode == null) { mode = System.getProperty("spring.validation.mode"); } return mode; } }); }
From source file:org.apache.axis2.engine.AxisConfiguration.java
/** * Constructor AxisConfiguration.//from w ww . j a v a2 s. c o m */ public AxisConfiguration() { moduleConfigmap = new HashMap<String, ModuleConfiguration>(); globalModuleList = new ArrayList<String>(); messageReceivers = new HashMap<String, MessageReceiver>(); messageBuilders = new HashMap<String, Builder>(); messageFormatters = new HashMap<String, MessageFormatter>(); outPhases = new ArrayList<Phase>(); inFaultPhases = new ArrayList<Phase>(); outFaultPhases = new ArrayList<Phase>(); faultyServices = new Hashtable<String, String>(); faultyModules = new Hashtable<String, String>(); observerSet = new CopyOnWriteArraySet<AxisObserver>(); inPhasesUptoAndIncludingPostDispatch = new ArrayList<Phase>(); systemClassLoader = org.apache.axis2.java.security.AccessController .doPrivileged(new PrivilegedAction<ClassLoader>() { public ClassLoader run() { return Thread.currentThread().getContextClassLoader(); } }); serviceClassLoader = systemClassLoader; moduleClassLoader = systemClassLoader; this.phasesinfo = new PhasesInfo(); targetResolvers = new ArrayList<TargetResolver>(); }
From source file:com.reelfx.controller.WindowsController.java
public static void deleteOutput() { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override//from w w w . j a va 2 s .c o m public Object run() { try { if (MERGED_OUTPUT_FILE.exists() && !MERGED_OUTPUT_FILE.delete()) throw new Exception("Can't delete the old preview file on Windows!"); } catch (Exception e) { e.printStackTrace(); } return null; } }); }
From source file:org.apache.hadoop.hbase.util.CoprocessorClassLoader.java
/** * Get a CoprocessorClassLoader for a coprocessor jar path from cache. * If not in cache, create one.// www . jav a 2 s . com * * @param path the path to the coprocessor jar file to load classes from * @param parent the parent class loader for exempted classes * @param pathPrefix a prefix used in temp path name to store the jar file locally * @param conf the configuration used to create the class loader, if needed * @return a CoprocessorClassLoader for the coprocessor jar path * @throws IOException */ public static CoprocessorClassLoader getClassLoader(final Path path, final ClassLoader parent, final String pathPrefix, final Configuration conf) throws IOException { CoprocessorClassLoader cl = getIfCached(path); String pathStr = path.toString(); if (cl != null) { LOG.debug("Found classloader " + cl + " for " + pathStr); return cl; } if (!pathStr.endsWith(".jar")) { throw new IOException(pathStr + ": not a jar file?"); } Lock lock = locker.acquireLock(pathStr); try { cl = getIfCached(path); if (cl != null) { LOG.debug("Found classloader " + cl + " for " + pathStr); return cl; } cl = AccessController.doPrivileged(new PrivilegedAction<CoprocessorClassLoader>() { @Override public CoprocessorClassLoader run() { return new CoprocessorClassLoader(parent); } }); cl.init(path, pathPrefix, conf); // Cache class loader as a weak value, will be GC'ed when no reference left CoprocessorClassLoader prev = classLoadersCache.putIfAbsent(path, cl); if (prev != null) { // Lost update race, use already added class loader LOG.warn("THIS SHOULD NOT HAPPEN, a class loader" + " is already cached for " + pathStr); cl = prev; } return cl; } finally { lock.unlock(); } }
From source file:org.apache.axis2.jaxws.client.async.AsyncResponse.java
protected void onComplete(MessageContext mc, ClassLoader cl) { ClassLoader contextCL = (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return Thread.currentThread().getContextClassLoader(); }/*w w w . j ava2 s .c om*/ }); onComplete(mc); checkClassLoader(cl, contextCL); }