Using SnakeYaml under OSGi?

1.6k views Asked by At

Does SnakeYaml work within an OSGi framework? I've modified the MANIFEST & such so that it deploys correctly, but but trying to load a document into a JavaBean object structure is failing with "Class not found" exceptions.

Thanks.

2

There are 2 answers

2
basszero On BEST ANSWER

Sometimes it is as simple as adding manifest headers to make a jar play nice in the OSGi sandbox. Sometimes jars/libraries do "naughty" things in the context of OSGi. A golden rule is to avoid using "Class.forName()" due to the way OSGi uses classloaders, otherwise perfectly valid in a single class loader environment. I pulled down the source to SnakeYaml and they're bean based loader makes use of Class.forName.

The good news is that there appears to be a constructor, CustomClassLoaderConstructor, that let's you use your own classloader and you use this when you make the core Yaml parser object. The key is getting the right class loader. You'll want to use the classloader of the bundle in which you're using Yaml BUT you'll need to make sure than ANY CLASS that will be created is imported into that bundle. The import will make sure all of the objects needed are in the classloader tree that OSGi creates.

See this question for created a classloader based on a bundle.

0
mkdev On

For anyone that stumbles across this, newer versions of snakeyaml are already a osgi bundle. No need to fiddle at file MANIFEST.MF.

You must just use a CustomClassLoaderConstructor like this:

import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.CustomClassLoaderConstructor;

CustomClassLoaderConstructor constructor = new CustomClassLoaderConstructor(this.getClass().getClassLoader());
Config config = new Yaml(constructor).loadAs(in, Config.class);

Code tested with org.yaml.snakeyaml;bundle-version="1.25.0"