BAEL-3732: Move core-java-security-manager into core-java-security (#8460)
* BAEL-3732: Move core-java-security-manager into core-java-security * BAEL-3732: Teardown the security manager to not interfere with other tests
This commit is contained in:
committed by
Grzegorz Piwowarek
parent
8c77986e6a
commit
04a571ea02
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.securitymanager;
|
||||
|
||||
import java.security.BasicPermission;
|
||||
|
||||
public class CustomPermission extends BasicPermission {
|
||||
public CustomPermission(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
public CustomPermission(String name, String actions) {
|
||||
super(name, actions);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.securitymanager;
|
||||
|
||||
public class Service {
|
||||
|
||||
public static final String OPERATION = "my-operation";
|
||||
|
||||
public void operation() {
|
||||
SecurityManager securityManager = System.getSecurityManager();
|
||||
if (securityManager != null) {
|
||||
securityManager.checkPermission(new CustomPermission(OPERATION));
|
||||
}
|
||||
System.out.println("Operation is executed");
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
new Service().operation();
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.java.md5;
|
||||
package com.baeldung.java.md5;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.securitymanager;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.security.AccessControlException;
|
||||
|
||||
public class SecurityManagerUnitTest {
|
||||
|
||||
private static final String TESTING_SECURITY_POLICY = "file:src/test/resources/testing.policy";
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
System.setProperty("java.security.policy", TESTING_SECURITY_POLICY);
|
||||
System.setSecurityManager(new SecurityManager());
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
System.setSecurityManager(null);
|
||||
}
|
||||
|
||||
@Test(expected = AccessControlException.class)
|
||||
public void whenSecurityManagerIsActive_thenNetworkIsNotAccessibleByDefault() throws IOException {
|
||||
new URL("http://www.google.com").openConnection().connect();
|
||||
}
|
||||
|
||||
@Test(expected = AccessControlException.class)
|
||||
public void whenUnauthorizedClassTriesToAccessProtectedOperation_thenAnExceptionIsThrown() {
|
||||
new Service().operation();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
grant {
|
||||
// This is for testing purposes only.
|
||||
// It allows us to properly reset the security manager after the unit test completes.
|
||||
permission java.lang.RuntimePermission "setSecurityManager";
|
||||
};
|
||||
Reference in New Issue
Block a user