views:

1013

answers:

2

I have a Java application and I would like to make it extensible. To create an extension, developers within our company will write a Java class that implements a certain interface. They may also wish to write associated helper classes. I would like to load these extensions into the application without an outage.

I would like to limit what this class can do to the following:

  1. Call methods in the application's API (this will be a parameter to the constructor)
  2. Create instances of other objects within the same package (so the author of the extension class can use other classes to get the job done).

When the class is invoked the API object that is passed in will already have a "customer" defined and stored as a member variable. It will use this to limit access via the API to that customer's data.

I do not want these classes doing things such as accessing the database, writing to disk, or otherwise doing things etc. This is mostly an effort at dependency management and encapsulation as the same team of developers will have access to write both extensions and the core system.

Is there a pattern for this? Am I on the right track?

+2  A: 

I don't know the implementation details, but it seems what you have in mind comes close to what the Apache Tomcat server already does. Individual webapps in Tomcat are kept separated having different individual class loaders. Maybe it's worth having a look at the code there.

mkoeller
+7  A: 

You don't need to look for anything exotic. Handling this scenario is a fundamental feature of the Java security architecture.

Every class has a "codebase", the location from which it was loaded. So if you package each extension in a separate JAR (or exploded in a separate directory), you'll be able tailor the permissions granted to that codebase.

In your case, it sounds even simpler. If I understand correctly, all extensions will have the same privileges, which are less than those of the parent application. Thus, they can all share a codebase.

Here's an example of a policy file:

grant codeBase "file:/path/to/app/lib/*" {
  permission java.io.FilePermission "/path/to/app/-", "read";
  permission java.io.FilePermission "/path/to/app/data/-", "read,write,delete";
};

grant codeBase "file:/path/to/app/ext/*" {
  permission java.util.PropertyPermission "java.io.tmpdir", "read";
  permission java.io.FilePermission "${java.io.tmpdir}/myapp/-", "read,write,delete";
};

This simple example should work in any version of Java. Newer versions have extended policy syntax to grant permissions to a subject authenticated by JAAS.

erickson