I am trying to figure out what some legacy code is doing. What exactly is this line doing, and why would I need it this way?
String lineSeparator = (String) java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("line.separator"));
I found it in the logger implementation of the web/ejb application running on Weblogic 8. There are no special security policies enabled as far as I know. (I do not like imports from sun.* packages, so I want to get rid of this line ;-)
AccessController class is part of Java's security mechanism; it is responsible for enforcing the applicable security policy. This class's static doPrivileged() method executes a code block with a relaxed security policy. The doPrivileged() method stops permissions from being checked further down the call chain.
checkPermission method first checks if the method System. getSecurityManager returns null. Marking code as privileged enables a piece of trusted code to temporarily enable access to more resources than are available directly to the code that called it. This is necessary in some situations.
More specifically, the AccessController class is used for three purposes: to decide whether an access to a critical system resource is to be allowed or denied, based on the security policy currently in effect, to mark code as being "privileged", thus affecting subsequent access determinations, and.
doPrivileged method takes an object of type java. security. PrivilegedAction and invokes its run method in privileged mode. The implementation guarantees that privileges will be revoked after the run method is executed, even if execution of doPrivileged is interrupted by an asynchronous exception.
It is just getting a system property. Retrieving system properties requires permissions which the calling code may not have. The doPrivileged
asserts the privileges of the calling class irrespective of how it was called. Clearly, doPrivileged
is something you need to be careful with.
The code quoted is the equivalent of:
String lineSeparator = java.security.AccessController.doPrivileged( new java.security.PrivilegedAction<String>() { public String run() { return System.getProperty("line.separator"); } } );
(Don't you just love the conciseness of Java's syntax?)
Without asserting privileges, this can be rewritten as:
String lineSeparator = System.getProperty("line.separator");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With