views:

917

answers:

1

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 ;-)

+6  A: 

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");
Tom Hawtin - tackline
@Tom, "The doPrivileged asserts the privileges of the calling class irrespective of how it was called." What does that mean? Can you give an example?
Gili
I think I meant irrespective of the permissions of the current access control context. So usually when you call a trusted method, the permissions available to that method are those that it was called with. `doPrivileged` starts afresh (although it does include the permission restrictions of the immediate caller).
Tom Hawtin - tackline