Java Reference
In-Depth Information
Example 6−1: SafeServer.java (continued)
* or malicious on the local system. This allows us to safely run Service
* classes that come from untrusted sources.
**/
public class SafeServer {
public static void main(String[] args) {
try {
// Install a Security manager, if the user didn't already install
// one with the -Djava.security.manager argument
if (System.getSecurityManager() == null) {
System.out.println("Establishing a security manager");
System.setSecurityManager(new SecurityManager());
}
// Create a Server object
Server server = new Server(null, 5);
// Create the ClassLoader that we'll use to load Service classes.
// The classes should be stored in the JAR file or the directory
// specified as a URL by the first command-line argument
URL serviceURL = new URL(args[0]);
ClassLoader loader =
new java.net.URLClassLoader(new URL[] {serviceURL});
// Parse the argument list, which should contain Service name/port
// pairs. For each pair, load the named Service using the class
// loader, then instantiate it with newInstance(), then tell the
// server to start running it.
int i = 1;
while(i < args.length) {
// Dynamically load the Service class using the class loader
Class serviceClass = loader.loadClass(args[i++]);
// Dynamically instantiate the class.
Server.Service service =
(Server.Service)serviceClass.newInstance();
int port = Integer.parseInt(args[i++]); // Parse the port #
server.addService(service, port);
// Run service
}
}
catch (Exception e) { // Display a message if anything goes wrong
System.err.println(e);
System.err.println("Usage: java " + SafeServer.class.getName() +
" <url> <servicename> <port>\n" +
"\t[<servicename> <port> ... ]");
System.exit(1);
}
}
}
A Policy for SafeServer
The SafeServer class creates and establishes a SecurityManager even if the user
doesn't do this with the -Djava.security.manager argument. This means that the
program is not able to run without a security policy that grants it the permissions it
needs. Example 6-2 shows a policy file you can use to make it work.
There are a couple of things to note about the SafeServer.policy file. First, the pol-
icy file reads system properties named service.dir and service.tmp . These are
Search WWH ::




Custom Search