I'd like to implement a dynamic plugin feature in a Java application. Ideally:
The application would define an interface Plugin with a method like getCapabilities().
A plugin would be a JAR pluginX.jar containing a class PluginXImpl implementing Plugin (and maybe some others).
The user would put pluginX.jar in a special directory or set a configuration parameter pointing to it. The user should not necessarily have to include pluginX.jar in their classpath.
The application would find PluginXImpl (maybe via the JAR manifest, maybe by reflection) and add it to a registry.
The client could get an instance of PluginXImpl, e.g., by invoking a method like getPluginWithCapabilities("X"). The user should not necessarily have to know the name of the plugin.
I've got a sense I should be able to do this with peaberry, but I can't make any sense of the documentation. I've invested some time in learning Guice, so my preferred answer would not be "use Spring Dynamic Modules."
Can anybody give me a simple idea of how to go about doing this using Guice/peaberry, OSGi, or just plain Java?
This is actually quite easy using plain Java means:
Since you don't want the user to configure the classpath before starting the application, I would first create a URLClassLoader with an array of URLs to the files in your plugin directory. Use File.listFiles to find all plugin jars and then File.toURI().toURL() to get a URL to each file. You should pass the system classloader (ClassLoader.getSystemClassLoader()) as a parent to your URLClassLoader.
If the plugin jars contain a configuration file in META-INF/services as described in the API documentation for java.util.ServiceLoader, you can now use ServiceLoader.load(Plugin.class, myUrlClassLoader) to obatin a service loader for your Plugin interface and call iterator() on it to get instances of all configured Plugin implementations.
You still have to provide your own wrapper around this to filter plugin capabilites, but that shouldn't be too much trouble, I suppose.
OSGI would be fine if you want to replace the plugins during runtime i.g. for bugfixes in a 24/7 environment. I played a while with OSGI but it took too much time, because it wasn't a requirement, and you need a plan b if you remove a bundle.
My humble solution then was, providing a properties files with the class names of plugin descriptor classes and let the server call them to register (including quering their capabilities).
This is obvious suboptimal but I can't wait to read the accepted answer.
Any chance you can leverage the Service Provider Interface?
The best way to implement plug-ins with Guice is with Multibindings. The linked page goes into detail on how to use multibindings to host plugins.
Apologize if you know this, but check out the forName method of Class. It is used at least in JDBC to dynamically load the DBMS-specific driver classes runtime by class name.
Then I guess it would not be difficult to enumerate all class/jar files in a directory, load each of them, and define an interface for a static method getCapabilities() (or any name you choose) that returns their capabilities/description in whatever terms and format that makes sense for your system.
Related
I have a game written in Java and a whish to write a generic ModLoader/AddonLoader application. A separate application/api that would allow you to create mods/addons for my projects that add extra implementation that I do not want in the main application.
However I am not sure how to go about this, i've done some research and im not too sure how to make the mod/addon interact with a loader which interacts with the main application to add new features/modify old
Many Thanks
Elliott
Since you're looking for some basic guidance I'll suggest the following:
You need a way to pull in classes after the core application is running. That means you will need these classes on the classpath. The simplest way to do that is probably to have your classpath include a folder like "addons" so that all the jars in that folder are automatically on your application's classpath.
Once you have your classpath set up you will need to somehow make use of the appropriate class(es). This part is hard to speak generically about because it depends heavily on how you intend your addons to work. Some tools use annotations to help with this and you can probably look at some open source projects for examples. One that comes to mind is Maven, it makes use of annotations in its plugin system. The general concept is that you need to decide how many different kinds of addons you have and how you will identify them and make use of them.
Typically making use of an addon involves instantiating that addon which is why it can be tricky. Some plugin systems require that addons be written such that they use a specific package name. They do this so that they can make use of reflection to find all classes in a given package and then process them.
Hope that helps to get you started!
I've been developing OSGi modules but so far I've come across a number of issues when I've had to wrap existing jars. An example of this is the use of the Oracle database driver which, even though I've wrapped the jar as bundle, just refuses to work (cannot find the driver class even though its present). This is just a single example but I've had issues with other 3rd party libraries and was wondering if there's a best practice approach to using 3rd party libraries which works every time?
Jlove
The problem in your case is that jdbc uses a class from the java runtime to find the database driver (DriverManager.getConnection). This can not work as the database driver is not accessible from the system classloader (that loaded the DriverManager class).
A way that works in OSGi is to use a DataSource instead: http://docs.oracle.com/javase/tutorial/jdbc/basics/sqldatasources.html . There you simply create the data source using new and this of course works. The problem is that it makes your user bundle depend on the specific DB driver. So the best practice is to create the DataSource centrally and publish it as service.
You can find some more details in my Apache Karaf DB Tutorial (http://www.liquid-reality.de/display/liquid/2012/01/13/Apache+Karaf+Tutorial+Part+6+-+Database+Access).
Btw. In general this kind of factories are tpyically where libraries fail in OSGi. Every lib invents another and different factory system and most of the are incompatible with the restricted classloaders of OSGi. Luckily most libs are made OSGi ready nowadays. Most times this simply means that you can also call the factory with a concrete object that you can retrieve using an OSGi service.
My preferred approach is not to wrap the library, but to unjar it, add a manifest, and re-jar it. Jars-inside-jars tend to cause issues that are hard to debug. Unjar and re-jar can be automated with a simple ant script.
Also, I like to write MANIFEST.MF manually. If the library being wrapped is small, then it's easy enough to do that. Tools like bnd that generate MANIFEST.MF for you do not always give the right results, and if you rely on them too much you don't know what is going on under the hood.
Java's ServiceLoader needs those entries to be present inside the JAR file. Is there a way to programatically add those service entries at runtime time for unit testing, when inside the IDE? Especially when the JARs are not built yet.
Don't get too hung up focusing on JAR files. They are the preferred way to encapsulate services, but they aren't required. The key is really ClassLoader.getResources(String) - where the String arg effectively becomes ("META-INF/services/" + serviceClass.getName()). One other bit of information to keep in mind is that ServiceLoader.load(Class) makes use of the context class loader (of course, you can also make use of ServiceLoader.load(Class, ClassLoader)). So...what you really need to do is manipulate the classpath or configure the context class loader in such a way as to make ServiceLoader happy.
I have a Java project that expects external modules to be registered with it. These modules:
Implement a particular interface in the main project
Are packaged into a uni-jar (along with any dependencies)
Contain some human-readable meta-information (like the module name).
My main project needs to be able to load at runtime (e.g. using its own classloader) any of these external modules. My question is: what's the best way of registering these modules with the main project (I'd prefer to keep this vanilla Java, and not use any third-party frameworks/libraries for this isolated issue)?
My current solution is to keep a single .properties file in the main project with key=name, value=class |delimiter| human-readable-name (or coordinate two .properties files in order to avoid the delimiter parsing). At runtime, the main project loads in the .properties file and uses any entries it finds to drive the classloader.
This feels hokey to me. Is there a better way to this?
The standard approach in Java is to define a Service Provider.
Let all module express their metadata via a standard xml file. Call it "my-module-data.xml".
On your main container startup it looks for a classpath*:my-module-data.xml" (which can have a FrontController class) and delegates to the individual modules FrontController class to do whatever it wants :)
Also google for Spring-OSGI and their doco can be helpful here.
Expanding on #ZZ Coder...
The Service Provider pattern mentioned, and used internally within the JDK is now a little more formalized in JDK 6 with ServiceLoader. The concept is further expanded up by the Netbeans Lookup API.
The underlying infrastructure is identical. That is, both API use the same artifacts, the same way. The NetBeans version is just a more flexible and robust API (allowing alternative lookup services, for example, as well as the default one).
Of course, it would be remiss to not mention the dominant, more "heavyweight" standards of EJB, Spring, and OSGi.
Inside my host application I tried implement a simple pushService, which
shall be used to transfer an instance of a class named Vehicle to the OSGi
world, by providing a set and get method. To be able to use the service I
exported both the service interface and the Vehicle class to a jar file and
imported that file within the bundle, which should use the service.
Everytime I tried to use the Vehicle class within my host application,
which instanciates the felix framework, and the bundle, I got a linkage
error. After reading the following blog entry
(http://frankkieviet.blogspot.com/2009/03/javalanglinkageerror-loader-constraint.html)
I understood why this error occurs. But I have no clue how to solve my problem.
Is it possible to share a class between the host application and an OSGi
instance? Maybe I have to use reflection instead of import the jar file? I had a look at that library (http://code.google.com/p/transloader/) and I'm don't really sure whether this lib is able to solve my problem or not ...
BR,
Markus
At one time I was using Felix to do EXACTLY what you're asking in a custom client-server application. I've since switched to Equinox (they correctly implement framework fragments which I needed for swing LAF as osgi bundles). I THINK the following will work in Felix, I KNOW it works in Equinox.
UPDATE: I started down a very similar path with my host application. I realized early that I needed to move as much code as possible into real OSGi bundles to truly take advantage of the platform. My host application sets up client/server comms and synchronizes bundles; that's it. The few classes I used to share have been moved into bundle and I haven't look back. If you design/application can support having the majority of code in bundles I would definitely go that route. Even if some redesign is required, it's worth it.
Before initializing the OSGi runtime, set this property "org.osgi.framework.system.packages" to include you packages (no wildcards) separated by semi-colons ";". You may additionally need to include the base osgi packages, "org.osgi.framework" and the base services "org.osgi.packageadmin", "org.osgi.startlevel", "org.osgi.url".
I just dug through my version control and found a snippet when I was still using Felix (the setup is almost the same for Equinox)
Map<String, String> configMap = new HashMap<String, String();
configMap.put(Constants.FRAMEWORK_SYSTEMPACKAGES,
"your.package;other.package;org.osgi.framework");
// setup other properties
Bundle systemBundle = new Felix(configMap, null);
systemBundle.start();
// Now you can use classes from "your.package" with explicity
// declaring them as imports in bundles