List of usage examples for java.security PrivilegedExceptionAction PrivilegedExceptionAction
PrivilegedExceptionAction
From source file:org.apache.atlas.web.filters.MetadataAuthenticationKerberosFilterIT.java
@Test(enabled = false) public void testKerberosBasedLogin() throws Exception { String originalConf = System.getProperty("metadata.conf"); System.setProperty("metadata.conf", System.getProperty("user.dir")); setupKDCAndPrincipals();//w w w. jav a 2 s . co m TestEmbeddedServer server = null; try { // setup the application.properties file generateKerberosTestProperties(); // 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(); Assert.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(); Assert.assertEquals(connection.getResponseCode(), 200); return null; } }); } finally { server.getServer().stop(); kdc.stop(); if (originalConf != null) { System.setProperty("metadata.conf", originalConf); } else { System.clearProperty("metadata.conf"); } } }
From source file:org.apache.hadoop.io.crypto.tool.kerberos.SpnegoRestCli.java
public StringBuffer getResult() throws Exception { AccessControlContext context = AccessController.getContext(); Subject subject = Subject.getSubject(context); if (subject == null) { subject = new Subject(); LoginContext login = new LoginContext("", subject, null, new KerberosConfiguration()); login.login();/*from ww w.jav a 2 s . c o m*/ } Subject.doAs(subject, new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { sb = new RestClient(url).getResult(); return null; } }); return sb; }
From source file:io.undertow.server.security.SpnegoAuthenticationTestCase.java
@Test public void testSpnegoSuccess() throws Exception { final TestHttpClient client = new TestHttpClient(); HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL()); HttpResponse result = client.execute(get); assertEquals(StatusCodes.UNAUTHORIZED, result.getStatusLine().getStatusCode()); Header[] values = result.getHeaders(WWW_AUTHENTICATE.toString()); String header = getAuthHeader(NEGOTIATE, values); assertEquals(NEGOTIATE.toString(), header); HttpClientUtils.readResponse(result); Subject clientSubject = login("jduke", "theduke".toCharArray()); Subject.doAs(clientSubject, new PrivilegedExceptionAction<Void>() { @Override//from w w w . j a va 2 s. co m public Void run() throws Exception { GSSManager gssManager = GSSManager.getInstance(); GSSName serverName = gssManager .createName("HTTP/" + DefaultServer.getDefaultServerAddress().getHostString(), null); GSSContext context = gssManager.createContext(serverName, SPNEGO, null, GSSContext.DEFAULT_LIFETIME); byte[] token = new byte[0]; boolean gotOur200 = false; while (!context.isEstablished()) { token = context.initSecContext(token, 0, token.length); if (token != null && token.length > 0) { HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL()); get.addHeader(AUTHORIZATION.toString(), NEGOTIATE + " " + FlexBase64.encodeString(token, false)); HttpResponse result = client.execute(get); Header[] headers = result.getHeaders(WWW_AUTHENTICATE.toString()); if (headers.length > 0) { String header = getAuthHeader(NEGOTIATE, headers); byte[] headerBytes = header.getBytes(StandardCharsets.US_ASCII); // FlexBase64.decode() returns byte buffer, which can contain backend array of greater size. // when on such ByteBuffer is called array(), it returns the underlying byte array including the 0 bytes // at the end, which makes the token invalid. => using Base64 mime decoder, which returnes directly properly sized byte[]. token = Base64.getMimeDecoder().decode(ArrayUtils.subarray(headerBytes, NEGOTIATE.toString().length() + 1, headerBytes.length)); } if (result.getStatusLine().getStatusCode() == StatusCodes.OK) { Header[] values = result.getHeaders("ProcessedBy"); assertEquals(1, values.length); assertEquals("ResponseHandler", values[0].getValue()); HttpClientUtils.readResponse(result); assertSingleNotificationType(EventType.AUTHENTICATED); gotOur200 = true; } else if (result.getStatusLine().getStatusCode() == StatusCodes.UNAUTHORIZED) { assertTrue("We did get a header.", headers.length > 0); HttpClientUtils.readResponse(result); } else { fail(String.format("Unexpected status code %d", result.getStatusLine().getStatusCode())); } } } assertTrue(gotOur200); assertTrue(context.isEstablished()); return null; } }); }
From source file:org.apache.axis2.jaxws.lifecycle.BaseLifecycleManager.java
protected void invokeMethod(final Method m, final Object[] params) throws LifecycleException { try {/* ww w . j a v a 2s .c o m*/ AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws InvocationTargetException, IllegalAccessException { return m.invoke(instance, params); } }); } catch (PrivilegedActionException e) { throw new LifecycleException(e.getException()); } }
From source file:org.kitesdk.spring.hbase.example.service.WebPageSnapshotService.java
/** * Take a snapshot of an URL. This WebPageSnapshot is stored in HBase. Returns * the WebPageSnapshotMeta/*ww w . j ava2s. c o m*/ * * If the URL is a redirect, the snapshot is stored under the final URL * destination. A WebPageRedirectModel is stored in the redirect table so when * fetching snapshots, we can follow the proper redirect path. * * @param url The URL to take a snapshot of * @param contentKey The key used to store the content * @param user The user taking a snapshot * @return The WebPageSnapshotMeta for the page that we snapshotted. * @throws IOException */ public WebPageSnapshotMeta takeSnapshot(final String url, final String contentKey, final String user) throws IOException { WebPageSnapshotMeta meta = null; UserGroupInformation ugi = UserGroupInformation.createProxyUser(user, UserGroupInformation.getLoginUser()); try { meta = ugi.doAs(new PrivilegedExceptionAction<WebPageSnapshotMeta>() { @Override public WebPageSnapshotMeta run() throws Exception { WebPageSnapshotModel webPageSnapshotModel = fetchWebPage(url, contentKey); if (!webPageSnapshotModel.getUrl().equals(url)) { // Url is different, so must have redirected. Store the redirect model WebPageRedirectModel redirectModel = WebPageRedirectModel.newBuilder().setUrl(url) .setDestinationUrl(webPageSnapshotModel.getUrl()).build(); webPageRedirectModels(user).put(redirectModel); } else { // If redirect exists, remove it since this URL no longer redirects Key key = new Key.Builder(webPageRedirectModels(user)).add("url", url).build(); WebPageRedirectModel redirectModel = webPageRedirectModels(user).get(key); if (redirectModel != null) { webPageRedirectModels(user).delete(key); } } webPageSnapshotModels(user).put(webPageSnapshotModel); return conversionService.convert(webPageSnapshotModel, WebPageSnapshotMeta.class); } }); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); if (meta == null) { throw new IOException("Interrupted trying to save the snapshot", ex); } } return meta; }
From source file:com.netspective.commons.io.UriAddressableUniqueFileLocator.java
/** * Creates a new file resource locator that will use the specified directory * as the base directory for loading templates. * * @param baseDir the base directory for loading templates *//*from w w w.ja va2 s .co m*/ public UriAddressableUniqueFileLocator(final String rootUrl, final File baseDir, final boolean cacheLocations) throws IOException { this.rootUrl = rootUrl; this.cacheLocations = cacheLocations; try { Object[] retval = (Object[]) AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws IOException { if (!baseDir.exists()) { throw new FileNotFoundException(baseDir + " does not exist."); } if (!baseDir.isDirectory()) { throw new IOException(baseDir + " is not a directory."); } Object[] retval = new Object[2]; retval[0] = baseDir.getCanonicalFile(); retval[1] = ((File) retval[0]).getPath() + File.separatorChar; return retval; } }); this.baseDir = (File) retval[0]; this.canonicalPath = (String) retval[1]; } catch (PrivilegedActionException e) { throw (IOException) e.getException(); } }
From source file:org.solmix.runtime.support.spring.ContainerApplicationContext.java
public ContainerApplicationContext(String[] cfgFiles, ApplicationContext parent, boolean includeDefault, NamespaceHandlerResolver nshResolver) { super(new String[0], false, parent); this.cfgFiles = cfgFiles; this.nshResolver = nshResolver; this.includeDefault = includeDefault; try {// ww w.j a v a2 s.com AccessController.doPrivileged(new PrivilegedExceptionAction<Boolean>() { @Override public Boolean run() throws Exception { refresh(); return Boolean.TRUE; } }); } catch (PrivilegedActionException e) { if (e.getException() instanceof RuntimeException) { throw (RuntimeException) e.getException(); } } }
From source file:org.apache.atlas.security.SecureClientUtils.java
public static URLConnectionClientHandler getClientConnectionHandler(DefaultClientConfig config, org.apache.commons.configuration.Configuration clientConfig, String doAsUser, final UserGroupInformation ugi) { config.getProperties().put(URLConnectionClientHandler.PROPERTY_HTTP_URL_CONNECTION_SET_METHOD_WORKAROUND, true);/*from w w w . j a va2s . c om*/ Configuration conf = new Configuration(); conf.addResource(conf.get(SSLFactory.SSL_CLIENT_CONF_KEY, SecurityProperties.SSL_CLIENT_PROPERTIES)); UserGroupInformation.setConfiguration(conf); final ConnectionConfigurator connConfigurator = newConnConfigurator(conf); Authenticator authenticator = new KerberosDelegationTokenAuthenticator(); authenticator.setConnectionConfigurator(connConfigurator); final DelegationTokenAuthenticator finalAuthenticator = (DelegationTokenAuthenticator) authenticator; final DelegationTokenAuthenticatedURL.Token token = new DelegationTokenAuthenticatedURL.Token(); HttpURLConnectionFactory httpURLConnectionFactory = null; try { UserGroupInformation ugiToUse = ugi != null ? ugi : UserGroupInformation.getCurrentUser(); final UserGroupInformation actualUgi = (ugiToUse .getAuthenticationMethod() == UserGroupInformation.AuthenticationMethod.PROXY) ? ugiToUse.getRealUser() : ugiToUse; LOG.info("Real User: {}, is from ticket cache? {}", actualUgi, actualUgi.isLoginTicketBased()); if (StringUtils.isEmpty(doAsUser)) { doAsUser = actualUgi.getShortUserName(); } LOG.info("doAsUser: {}", doAsUser); final String finalDoAsUser = doAsUser; httpURLConnectionFactory = new HttpURLConnectionFactory() { @Override public HttpURLConnection getHttpURLConnection(final URL url) throws IOException { try { return actualUgi.doAs(new PrivilegedExceptionAction<HttpURLConnection>() { @Override public HttpURLConnection run() throws Exception { try { return new DelegationTokenAuthenticatedURL(finalAuthenticator, connConfigurator) .openConnection(url, token, finalDoAsUser); } catch (Exception e) { throw new IOException(e); } } }); } catch (Exception e) { if (e instanceof IOException) { throw (IOException) e; } else { throw new IOException(e); } } } }; } catch (IOException e) { LOG.warn("Error obtaining user", e); } return new URLConnectionClientHandler(httpURLConnectionFactory); }
From source file:org.apache.hadoop.mapred.TestCluster.java
public void testFileStatus() throws Exception { UserGroupInformation ugi = UserGroupInformation .createRemoteUser(cluster.getJTClient().getProxy().getDaemonUser()); ugi.doAs(new PrivilegedExceptionAction<Void>() { @Override/*ww w.j a va 2 s . c om*/ public Void run() throws Exception { MRCluster myCluster = null; try { myCluster = MRCluster.createCluster(cluster.getConf()); myCluster.connect(); JTClient jt = myCluster.getJTClient(); String dir = "."; checkFileStatus(jt.getFileStatus(dir, true)); checkFileStatus(jt.listStatus(dir, false, true), dir); for (TTClient tt : myCluster.getTTClients()) { String[] localDirs = tt.getMapredLocalDirs(); for (String localDir : localDirs) { checkFileStatus(tt.listStatus(localDir, true, false), localDir); checkFileStatus(tt.listStatus(localDir, true, true), localDir); } } String systemDir = jt.getClient().getSystemDir().toString(); checkFileStatus(jt.listStatus(systemDir, false, true), systemDir); checkFileStatus(jt.listStatus(jt.getLogDir(), true, true), jt.getLogDir()); } finally { if (myCluster != null) { myCluster.disconnect(); } } return null; } }); }
From source file:com.marmalade.studio.android.gcm.s3eGCMClientBroadcastReceiver.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private void doRegistrationCallback(String reg_id) { try {/* w w w . jav a 2s . c o m*/ // Get context final Context context = m_Context; // Get registration identifier final String registration_id = reg_id; // Get extension class final Class extension_class = Class.forName("s3eGCMClient"); // Get registration method final Method registration_method = extension_class.getMethod("s3eGCMClientRegistrationReceived", new Class[] { Context.class, String.class }); // Access method AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws Exception { // Set accessible if (!registration_method.isAccessible()) { registration_method.setAccessible(true); } // Invoke registration_method.invoke(extension_class.newInstance(), context, registration_id); return null; } }); } catch (Exception e) { // Do nothing // e.printStackTrace(); } }