You are viewing a plain text version of this content. The canonical link for it is here.
Posted to users@felix.apache.org by ad...@bt.com on 2011/04/04 13:35:05 UTC

NoClassDefFoundError when embedding felix

Hopefully someone can help me with this problem that is stopping me from progressing with Felix ?

I have a simple bundle based on the example DictionaryBundle in the examples with the added complexity of an embedded jar file, is this case commons-lang.jar.

I can install and start the bundle into Felix when it is run from the command line (java -jar bin/felix.jar) and I can see the embedded jar being extracted in the felix-cache directory etc. In by Activator.start() method I also invoke the bundle code to prove that it works OK.

If I write some other code, closely following the patterns described at http://felix.apache.org/site/apache-felix-framework-launching-and-embedding.html#ApacheFelixFrameworkLaunchingandEmbedding-embedding, I find that, when the bundle is started, I get an error:

Could not create framework: org.osgi.framework.BundleException: Activator start error in bundle [5].
     [java] org.osgi.framework.BundleException: Activator start error in bundle [5].
     [java]               at org.apache.felix.framework.Felix.activateBundle(Felix.java:1899)
     [java]               at org.apache.felix.framework.Felix.startBundle(Felix.java:1769)
     [java]               at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:927)
     [java]               at com.bt.test.Main.main(Main.java:298)
     [java] Caused by: java.lang.NoClassDefFoundError: org/apache/commons/lang/StringUtils
     [java]               at com.bt.test.DictionaryImpl.checkWord(DictionaryImpl.java:24)
     [java]               at com.bt.test.DictionaryActivator.start(DictionaryActivator.java:33)
     [java]               at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:629)
     [java]               at org.apache.felix.framework.Felix.activateBundle(Felix.java:1852)
     [java]               ... 3 more
     [java]

I have studied the Main class from the Felix jar for differences to my code and cannot find anything obvious. Any clues appreciated.

Thanks

Adrian Smith
BT Group


RE: NoClassDefFoundError when embedding felix

Posted by ad...@bt.com.
Thanks Richard, that is the answer, see other emails in the thread.

-----Original Message-----
From: Richard S. Hall [mailto:heavy@ungoverned.org] 
Sent: 04 April 2011 23:09
To: users@felix.apache.org
Subject: Re: NoClassDefFoundError when embedding felix

On 4/4/11 9:29, adrian.p.smith@bt.com wrote:
> Absolutely....
>
> The bundle manifest:
>
> Bundle-Name: English dictionary
> Bundle-Description: A bundle that registers an English dictionary service
> Bundle-Vendor: Apache Felix
> Bundle-ClassPath: commons-lang-2.3.jar, .
> Bundle-Version: 1.0.0
> Bundle-Activator: com.bt.test.DictionaryActivator
> Export-Package: com.bt.test
> Import-Package: org.osgi.framework
>
> adrian@adrian-small-laptop:/tmp/bundles$ jar tvf dictionaryBundle.jar
>       0 Mon Apr 04 12:57:10 BST 2011 META-INF/
>     424 Mon Apr 04 12:57:08 BST 2011 META-INF/MANIFEST.MF
>       0 Mon Apr 04 12:57:08 BST 2011 com/
>       0 Mon Apr 04 12:57:08 BST 2011 com/bt/
>       0 Mon Apr 04 12:57:08 BST 2011 com/bt/test/
>    1744 Mon Apr 04 12:57:08 BST 2011 com/bt/test/DictionaryActivator.class
>     882 Mon Apr 04 12:57:08 BST 2011 com/bt/test/DictionaryImpl.class
>     171 Mon Apr 04 12:57:08 BST 2011 com/bt/test/DictionaryService.class
> 245274 Tue Feb 13 18:32:02 GMT 2007 commons-lang-2.3.jar
>
>
>
> The Main code:
>
> package com.bt.test;
>
> import java.io.BufferedReader;
> import java.io.File;
> import java.io.FileNotFoundException;
> import java.io.IOException;
> import java.io.InputStream;
> import java.io.InputStreamReader;
> import java.net.MalformedURLException;
> import java.net.URL;
> import java.util.ArrayList;
> import java.util.Enumeration;
> import java.util.List;
> import java.util.Properties;
>
> import org.apache.felix.framework.util.FelixConstants;
> import org.apache.felix.framework.util.Util;
> import org.apache.felix.main.AutoProcessor;
> import org.osgi.framework.Bundle;
> import org.osgi.framework.Constants;
> import org.osgi.framework.ServiceReference;
> import org.osgi.framework.launch.Framework;
> import org.osgi.framework.launch.FrameworkFactory;
>
> public class Main {
> 	public static final String BUNDLE_DIR_SWITCH = "-b";
> 	public static final String SHUTDOWN_HOOK_PROP = "felix.shutdown.hook";
> 	public static final String SYSTEM_PROPERTIES_PROP = "felix.system.properties";
> 	public static final String SYSTEM_PROPERTIES_FILE_VALUE = "system.properties";
> 	public static final String CONFIG_PROPERTIES_PROP = "felix.config.properties";
> 	public static final String CONFIG_PROPERTIES_FILE_VALUE = "config.properties";
> 	public static final String CONFIG_DIRECTORY = "conf";
> 	private static Framework m_fwk = null;
>
> 	public static void main(String[] args) throws Exception {
> 		String bundleDir = null;
> 		String cacheDir = null;
> 		boolean expectBundleDir = false;
> 		for (int i = 0; i<  args.length; i++) {
> 			if (args[i].equals(BUNDLE_DIR_SWITCH)) {
> 				expectBundleDir = true;
> 			} else if (expectBundleDir) {
> 				bundleDir = args[i];
> 				expectBundleDir = false;
> 			} else {
> 				cacheDir = args[i];
> 			}
> 		}
>
> 		if ((args.length>  3) || (expectBundleDir&&  bundleDir == null)) {
> 			System.out.println("Usage: [-b<bundle-deploy-dir>] [<bundle-cache-dir>]");
> 			System.exit(0);
> 		}
>
> 		Main.loadSystemProperties();
>
> 		// Read configuration properties.
> 		Properties configProps = Main.loadConfigProperties();
> 		if (configProps == null) {
> 			System.err.println("No " + CONFIG_PROPERTIES_FILE_VALUE + " found.");
> 			configProps = new Properties();
> 		}
>
> 		Main.copySystemProperties(configProps);
>
> 		if (bundleDir != null) {
> 			configProps.setProperty(AutoProcessor.AUTO_DEPLOY_DIR_PROPERY, bundleDir);
> 		}
>
> 		if (cacheDir != null) {
> 			configProps.setProperty(Constants.FRAMEWORK_STORAGE, cacheDir);
> 		}
>
> 		String enableHook = configProps.getProperty(SHUTDOWN_HOOK_PROP);
> 		if ((enableHook == null) || !enableHook.equalsIgnoreCase("false")) {
> 			Runtime.getRuntime().addShutdownHook(
> 					new Thread("Felix Shutdown Hook") {
> 						public void run() {
> 							try {
> 								if (m_fwk != null) {
> 									m_fwk.stop();
> 									m_fwk.waitForStop(0);
> 								}
> 							} catch (Exception ex) {
> 								System.err.println("Error stopping framework: "	+ ex);
> 							}
> 						}
> 					});
> 		}
> 		
> 			
> 		configProps.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "com.bt.test; version=1.0.0");

If this package is being provided by the system bundle (i.e., on the 
class path) and your bundle activator is in the same package, then it is 
possible you are getting into some strange error because of a split 
package. Perhaps you are getting some stuff from the class path and some 
from the bundle.

Could you try using different packages for your bundle and your launcher 
(e.g., com.bt.test.bundle and com.bt.test.launcher)?

-> richard

> 		
>
> 		try {
> 			HostActivator m_activator = new HostActivator();
> 			List list = new ArrayList();
> 			list.add(m_activator);
> 			configProps.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list);
>
> 			FrameworkFactory factory = getFrameworkFactory();
> 			m_fwk = factory.newFramework(configProps);
> 			m_fwk.init();
> 			AutoProcessor.process(configProps, m_fwk.getBundleContext());
> 			m_fwk.start();
> 			
> 			Bundle installBundle = m_activator.getContext().installBundle(new File("/tmp/bundles/dictionaryBundle.jar").toURL().toString());
>
> 			installBundle.start();
>
> 			ServiceReference serviceReference = m_activator.getContext().getServiceReference(DictionaryService.class.getName());
> 			Object object = m_fwk.getBundleContext().getService(serviceReference);
> 			DictionaryService service = (DictionaryService) object;
> 			System.out.println("############################# " + service.checkWord("osgi"));
> 			System.out.println("############################# " + service.checkWord("fred"));
>
> 			m_fwk.waitForStop(0);
>
> 			//System.exit(0);
> 		} catch (Exception ex) {
> 			System.err.println("Could not create framework: " + ex);
> 			ex.printStackTrace();
> 			System.exit(0);
> 		}
> 	}
>
> 	private static FrameworkFactory getFrameworkFactory() throws Exception {
> 		URL url = Main.class.getClassLoader().getResource("META-INF/services/org.osgi.framework.launch.FrameworkFactory");
> 		if (url != null) {
> 			BufferedReader br = new BufferedReader(new InputStreamReader(
> 					url.openStream()));
> 			try {
> 				for (String s = br.readLine(); s != null; s = br.readLine()) {
> 					s = s.trim();
> 					if ((s.length()>  0)&&  (s.charAt(0) != '#')) {
> 						return (FrameworkFactory) Class.forName(s).newInstance();
> 					}
> 				}
> 			} finally {
> 				if (br != null)
> 					br.close();
> 			}
> 		}
>
> 		throw new Exception("Could not find framework factory.");
> 	}
>
> 	public static void loadSystemProperties() {
> 		URL propURL = null;
> 		String custom = System.getProperty(SYSTEM_PROPERTIES_PROP);
> 		if (custom != null) {
> 			try {
> 				propURL = new URL(custom);
> 			} catch (MalformedURLException ex) {
> 				System.err.print("Main: " + ex);
> 				return;
> 			}
> 		} else {
> 			File confDir = null;
> 			String classpath = System.getProperty("java.class.path");
> 			int index = classpath.toLowerCase().indexOf("felix.jar");
> 			int start = classpath.lastIndexOf(File.pathSeparator, index) + 1;
> 			if (index>= start) {
> 				String jarLocation = classpath.substring(start, index);
> 				confDir = new File(new File(new File(jarLocation).getAbsolutePath()).getParent(), CONFIG_DIRECTORY);
> 			} else {
> 				confDir = new File(System.getProperty("user.dir"), CONFIG_DIRECTORY);
> 			}
>
> 			try {
> 				propURL = new File(confDir, SYSTEM_PROPERTIES_FILE_VALUE).toURL();
> 			} catch (MalformedURLException ex) {
> 				System.err.print("Main: " + ex);
> 				return;
> 			}
> 		}
>
> 		Properties props = new Properties();
> 		InputStream is = null;
> 		try {
> 			is = propURL.openConnection().getInputStream();
> 			props.load(is);
> 			is.close();
> 		} catch (FileNotFoundException ex) {
> 			// Ignore file not found.
> 		} catch (Exception ex) {
> 			System.err.println("Main: Error loading system properties from "	+ propURL);
> 			System.err.println("Main: " + ex);
> 			try {
> 				if (is != null)
> 					is.close();
> 			} catch (IOException ex2) {
> 				// Nothing we can do.
> 			}
> 			return;
> 		}
>
> 		// Perform variable substitution on specified properties.
> 		for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
> 			String name = (String) e.nextElement();
> 			System.setProperty(name, Util.substVars(props.getProperty(name), name, null, null));
> 		}
> 	}
>
> 	public static Properties loadConfigProperties() {
> 		URL propURL = null;
> 		String custom = System.getProperty(CONFIG_PROPERTIES_PROP);
> 		if (custom != null) {
> 			try {
> 				propURL = new URL(custom);
> 			} catch (MalformedURLException ex) {
> 				System.err.print("Main: " + ex);
> 				return null;
> 			}
> 		} else {
> 			File confDir = null;
> 			String classpath = System.getProperty("java.class.path");
> 			int index = classpath.toLowerCase().indexOf("felix.jar");
> 			int start = classpath.lastIndexOf(File.pathSeparator, index) + 1;
> 			if (index>= start) {
> 				String jarLocation = classpath.substring(start, index);
> 				confDir = new File(new File(
> 						new File(jarLocation).getAbsolutePath()).getParent(),
> 						CONFIG_DIRECTORY);
> 				System.err.println(confDir.getAbsolutePath());
> 			} else {
> 				confDir = new File(System.getProperty("user.dir"),
> 						CONFIG_DIRECTORY);
> 			}
>
> 			try {
> 				propURL = new File(confDir, CONFIG_PROPERTIES_FILE_VALUE)
> 						.toURL();
> 			} catch (MalformedURLException ex) {
> 				System.err.print("Main: " + ex);
> 				return null;
> 			}
> 		}
>
> 		Properties props = new Properties();
> 		InputStream is = null;
> 		try {
> 			// Try to load config.properties.
> 			is = propURL.openConnection().getInputStream();
> 			props.load(is);
> 			is.close();
> 		} catch (Exception ex) {
> 			// Try to close input stream if we have one.
> 			try {
> 				if (is != null)
> 					is.close();
> 			} catch (IOException ex2) {
> 				// Nothing we can do.
> 			}
>
> 			return null;
> 		}
>
> 		for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
> 			String name = (String) e.nextElement();
> 			props.setProperty(name,
> 					Util.substVars(props.getProperty(name), name, null, props));
> 		}
>
> 		return props;
> 	}
>
> 	public static void copySystemProperties(Properties configProps) {
> 		for (Enumeration e = System.getProperties().propertyNames(); e
> 				.hasMoreElements();) {
> 			String key = (String) e.nextElement();
> 			if (key.startsWith("felix.")
> 					|| key.startsWith("org.osgi.framework.")) {
> 				configProps.setProperty(key, System.getProperty(key));
> 			}
> 		}
> 	}
> }
>
> -----Original Message-----
> From: Richard S. Hall [mailto:heavy@ungoverned.org]
> Sent: 04 April 2011 13:24
> To: users@felix.apache.org
> Subject: Re: NoClassDefFoundError when embedding felix
>
> You're not really giving enough information. How about showing us your
> manifest file and the contents of your bundle JAR file?
>
> ->  richard
>
> On 4/4/11 7:35, adrian.p.smith@bt.com wrote:
>> Hopefully someone can help me with this problem that is stopping me from progressing with Felix ?
>>
>> I have a simple bundle based on the example DictionaryBundle in the examples with the added complexity of an embedded jar file, is this case commons-lang.jar.
>>
>> I can install and start the bundle into Felix when it is run from the command line (java -jar bin/felix.jar) and I can see the embedded jar being extracted in the felix-cache directory etc. In by Activator.start() method I also invoke the bundle code to prove that it works OK.
>>
>> If I write some other code, closely following the patterns described at http://felix.apache.org/site/apache-felix-framework-launching-and-embedding.html#ApacheFelixFrameworkLaunchingandEmbedding-embedding, I find that, when the bundle is started, I get an error:
>>
>> Could not create framework: org.osgi.framework.BundleException: Activator start error in bundle [5].
>>        [java] org.osgi.framework.BundleException: Activator start error in bundle [5].
>>        [java]               at org.apache.felix.framework.Felix.activateBundle(Felix.java:1899)
>>        [java]               at org.apache.felix.framework.Felix.startBundle(Felix.java:1769)
>>        [java]               at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:927)
>>        [java]               at com.bt.test.Main.main(Main.java:298)
>>        [java] Caused by: java.lang.NoClassDefFoundError: org/apache/commons/lang/StringUtils
>>        [java]               at com.bt.test.DictionaryImpl.checkWord(DictionaryImpl.java:24)
>>        [java]               at com.bt.test.DictionaryActivator.start(DictionaryActivator.java:33)
>>        [java]               at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:629)
>>        [java]               at org.apache.felix.framework.Felix.activateBundle(Felix.java:1852)
>>        [java]               ... 3 more
>>        [java]
>>
>> I have studied the Main class from the Felix jar for differences to my code and cannot find anything obvious. Any clues appreciated.
>>
>> Thanks
>>
>> Adrian Smith
>> BT Group
>>
>>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe@felix.apache.org
> For additional commands, e-mail: users-help@felix.apache.org
>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe@felix.apache.org
> For additional commands, e-mail: users-help@felix.apache.org
>

---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@felix.apache.org
For additional commands, e-mail: users-help@felix.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@felix.apache.org
For additional commands, e-mail: users-help@felix.apache.org


Re: NoClassDefFoundError when embedding felix

Posted by "Richard S. Hall" <he...@ungoverned.org>.
On 4/4/11 9:29, adrian.p.smith@bt.com wrote:
> Absolutely....
>
> The bundle manifest:
>
> Bundle-Name: English dictionary
> Bundle-Description: A bundle that registers an English dictionary service
> Bundle-Vendor: Apache Felix
> Bundle-ClassPath: commons-lang-2.3.jar, .
> Bundle-Version: 1.0.0
> Bundle-Activator: com.bt.test.DictionaryActivator
> Export-Package: com.bt.test
> Import-Package: org.osgi.framework
>
> adrian@adrian-small-laptop:/tmp/bundles$ jar tvf dictionaryBundle.jar
>       0 Mon Apr 04 12:57:10 BST 2011 META-INF/
>     424 Mon Apr 04 12:57:08 BST 2011 META-INF/MANIFEST.MF
>       0 Mon Apr 04 12:57:08 BST 2011 com/
>       0 Mon Apr 04 12:57:08 BST 2011 com/bt/
>       0 Mon Apr 04 12:57:08 BST 2011 com/bt/test/
>    1744 Mon Apr 04 12:57:08 BST 2011 com/bt/test/DictionaryActivator.class
>     882 Mon Apr 04 12:57:08 BST 2011 com/bt/test/DictionaryImpl.class
>     171 Mon Apr 04 12:57:08 BST 2011 com/bt/test/DictionaryService.class
> 245274 Tue Feb 13 18:32:02 GMT 2007 commons-lang-2.3.jar
>
>
>
> The Main code:
>
> package com.bt.test;
>
> import java.io.BufferedReader;
> import java.io.File;
> import java.io.FileNotFoundException;
> import java.io.IOException;
> import java.io.InputStream;
> import java.io.InputStreamReader;
> import java.net.MalformedURLException;
> import java.net.URL;
> import java.util.ArrayList;
> import java.util.Enumeration;
> import java.util.List;
> import java.util.Properties;
>
> import org.apache.felix.framework.util.FelixConstants;
> import org.apache.felix.framework.util.Util;
> import org.apache.felix.main.AutoProcessor;
> import org.osgi.framework.Bundle;
> import org.osgi.framework.Constants;
> import org.osgi.framework.ServiceReference;
> import org.osgi.framework.launch.Framework;
> import org.osgi.framework.launch.FrameworkFactory;
>
> public class Main {
> 	public static final String BUNDLE_DIR_SWITCH = "-b";
> 	public static final String SHUTDOWN_HOOK_PROP = "felix.shutdown.hook";
> 	public static final String SYSTEM_PROPERTIES_PROP = "felix.system.properties";
> 	public static final String SYSTEM_PROPERTIES_FILE_VALUE = "system.properties";
> 	public static final String CONFIG_PROPERTIES_PROP = "felix.config.properties";
> 	public static final String CONFIG_PROPERTIES_FILE_VALUE = "config.properties";
> 	public static final String CONFIG_DIRECTORY = "conf";
> 	private static Framework m_fwk = null;
>
> 	public static void main(String[] args) throws Exception {
> 		String bundleDir = null;
> 		String cacheDir = null;
> 		boolean expectBundleDir = false;
> 		for (int i = 0; i<  args.length; i++) {
> 			if (args[i].equals(BUNDLE_DIR_SWITCH)) {
> 				expectBundleDir = true;
> 			} else if (expectBundleDir) {
> 				bundleDir = args[i];
> 				expectBundleDir = false;
> 			} else {
> 				cacheDir = args[i];
> 			}
> 		}
>
> 		if ((args.length>  3) || (expectBundleDir&&  bundleDir == null)) {
> 			System.out.println("Usage: [-b<bundle-deploy-dir>] [<bundle-cache-dir>]");
> 			System.exit(0);
> 		}
>
> 		Main.loadSystemProperties();
>
> 		// Read configuration properties.
> 		Properties configProps = Main.loadConfigProperties();
> 		if (configProps == null) {
> 			System.err.println("No " + CONFIG_PROPERTIES_FILE_VALUE + " found.");
> 			configProps = new Properties();
> 		}
>
> 		Main.copySystemProperties(configProps);
>
> 		if (bundleDir != null) {
> 			configProps.setProperty(AutoProcessor.AUTO_DEPLOY_DIR_PROPERY, bundleDir);
> 		}
>
> 		if (cacheDir != null) {
> 			configProps.setProperty(Constants.FRAMEWORK_STORAGE, cacheDir);
> 		}
>
> 		String enableHook = configProps.getProperty(SHUTDOWN_HOOK_PROP);
> 		if ((enableHook == null) || !enableHook.equalsIgnoreCase("false")) {
> 			Runtime.getRuntime().addShutdownHook(
> 					new Thread("Felix Shutdown Hook") {
> 						public void run() {
> 							try {
> 								if (m_fwk != null) {
> 									m_fwk.stop();
> 									m_fwk.waitForStop(0);
> 								}
> 							} catch (Exception ex) {
> 								System.err.println("Error stopping framework: "	+ ex);
> 							}
> 						}
> 					});
> 		}
> 		
> 			
> 		configProps.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "com.bt.test; version=1.0.0");

If this package is being provided by the system bundle (i.e., on the 
class path) and your bundle activator is in the same package, then it is 
possible you are getting into some strange error because of a split 
package. Perhaps you are getting some stuff from the class path and some 
from the bundle.

Could you try using different packages for your bundle and your launcher 
(e.g., com.bt.test.bundle and com.bt.test.launcher)?

-> richard

> 		
>
> 		try {
> 			HostActivator m_activator = new HostActivator();
> 			List list = new ArrayList();
> 			list.add(m_activator);
> 			configProps.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list);
>
> 			FrameworkFactory factory = getFrameworkFactory();
> 			m_fwk = factory.newFramework(configProps);
> 			m_fwk.init();
> 			AutoProcessor.process(configProps, m_fwk.getBundleContext());
> 			m_fwk.start();
> 			
> 			Bundle installBundle = m_activator.getContext().installBundle(new File("/tmp/bundles/dictionaryBundle.jar").toURL().toString());
>
> 			installBundle.start();
>
> 			ServiceReference serviceReference = m_activator.getContext().getServiceReference(DictionaryService.class.getName());
> 			Object object = m_fwk.getBundleContext().getService(serviceReference);
> 			DictionaryService service = (DictionaryService) object;
> 			System.out.println("############################# " + service.checkWord("osgi"));
> 			System.out.println("############################# " + service.checkWord("fred"));
>
> 			m_fwk.waitForStop(0);
>
> 			//System.exit(0);
> 		} catch (Exception ex) {
> 			System.err.println("Could not create framework: " + ex);
> 			ex.printStackTrace();
> 			System.exit(0);
> 		}
> 	}
>
> 	private static FrameworkFactory getFrameworkFactory() throws Exception {
> 		URL url = Main.class.getClassLoader().getResource("META-INF/services/org.osgi.framework.launch.FrameworkFactory");
> 		if (url != null) {
> 			BufferedReader br = new BufferedReader(new InputStreamReader(
> 					url.openStream()));
> 			try {
> 				for (String s = br.readLine(); s != null; s = br.readLine()) {
> 					s = s.trim();
> 					if ((s.length()>  0)&&  (s.charAt(0) != '#')) {
> 						return (FrameworkFactory) Class.forName(s).newInstance();
> 					}
> 				}
> 			} finally {
> 				if (br != null)
> 					br.close();
> 			}
> 		}
>
> 		throw new Exception("Could not find framework factory.");
> 	}
>
> 	public static void loadSystemProperties() {
> 		URL propURL = null;
> 		String custom = System.getProperty(SYSTEM_PROPERTIES_PROP);
> 		if (custom != null) {
> 			try {
> 				propURL = new URL(custom);
> 			} catch (MalformedURLException ex) {
> 				System.err.print("Main: " + ex);
> 				return;
> 			}
> 		} else {
> 			File confDir = null;
> 			String classpath = System.getProperty("java.class.path");
> 			int index = classpath.toLowerCase().indexOf("felix.jar");
> 			int start = classpath.lastIndexOf(File.pathSeparator, index) + 1;
> 			if (index>= start) {
> 				String jarLocation = classpath.substring(start, index);
> 				confDir = new File(new File(new File(jarLocation).getAbsolutePath()).getParent(), CONFIG_DIRECTORY);
> 			} else {
> 				confDir = new File(System.getProperty("user.dir"), CONFIG_DIRECTORY);
> 			}
>
> 			try {
> 				propURL = new File(confDir, SYSTEM_PROPERTIES_FILE_VALUE).toURL();
> 			} catch (MalformedURLException ex) {
> 				System.err.print("Main: " + ex);
> 				return;
> 			}
> 		}
>
> 		Properties props = new Properties();
> 		InputStream is = null;
> 		try {
> 			is = propURL.openConnection().getInputStream();
> 			props.load(is);
> 			is.close();
> 		} catch (FileNotFoundException ex) {
> 			// Ignore file not found.
> 		} catch (Exception ex) {
> 			System.err.println("Main: Error loading system properties from "	+ propURL);
> 			System.err.println("Main: " + ex);
> 			try {
> 				if (is != null)
> 					is.close();
> 			} catch (IOException ex2) {
> 				// Nothing we can do.
> 			}
> 			return;
> 		}
>
> 		// Perform variable substitution on specified properties.
> 		for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
> 			String name = (String) e.nextElement();
> 			System.setProperty(name, Util.substVars(props.getProperty(name), name, null, null));
> 		}
> 	}
>
> 	public static Properties loadConfigProperties() {
> 		URL propURL = null;
> 		String custom = System.getProperty(CONFIG_PROPERTIES_PROP);
> 		if (custom != null) {
> 			try {
> 				propURL = new URL(custom);
> 			} catch (MalformedURLException ex) {
> 				System.err.print("Main: " + ex);
> 				return null;
> 			}
> 		} else {
> 			File confDir = null;
> 			String classpath = System.getProperty("java.class.path");
> 			int index = classpath.toLowerCase().indexOf("felix.jar");
> 			int start = classpath.lastIndexOf(File.pathSeparator, index) + 1;
> 			if (index>= start) {
> 				String jarLocation = classpath.substring(start, index);
> 				confDir = new File(new File(
> 						new File(jarLocation).getAbsolutePath()).getParent(),
> 						CONFIG_DIRECTORY);
> 				System.err.println(confDir.getAbsolutePath());
> 			} else {
> 				confDir = new File(System.getProperty("user.dir"),
> 						CONFIG_DIRECTORY);
> 			}
>
> 			try {
> 				propURL = new File(confDir, CONFIG_PROPERTIES_FILE_VALUE)
> 						.toURL();
> 			} catch (MalformedURLException ex) {
> 				System.err.print("Main: " + ex);
> 				return null;
> 			}
> 		}
>
> 		Properties props = new Properties();
> 		InputStream is = null;
> 		try {
> 			// Try to load config.properties.
> 			is = propURL.openConnection().getInputStream();
> 			props.load(is);
> 			is.close();
> 		} catch (Exception ex) {
> 			// Try to close input stream if we have one.
> 			try {
> 				if (is != null)
> 					is.close();
> 			} catch (IOException ex2) {
> 				// Nothing we can do.
> 			}
>
> 			return null;
> 		}
>
> 		for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
> 			String name = (String) e.nextElement();
> 			props.setProperty(name,
> 					Util.substVars(props.getProperty(name), name, null, props));
> 		}
>
> 		return props;
> 	}
>
> 	public static void copySystemProperties(Properties configProps) {
> 		for (Enumeration e = System.getProperties().propertyNames(); e
> 				.hasMoreElements();) {
> 			String key = (String) e.nextElement();
> 			if (key.startsWith("felix.")
> 					|| key.startsWith("org.osgi.framework.")) {
> 				configProps.setProperty(key, System.getProperty(key));
> 			}
> 		}
> 	}
> }
>
> -----Original Message-----
> From: Richard S. Hall [mailto:heavy@ungoverned.org]
> Sent: 04 April 2011 13:24
> To: users@felix.apache.org
> Subject: Re: NoClassDefFoundError when embedding felix
>
> You're not really giving enough information. How about showing us your
> manifest file and the contents of your bundle JAR file?
>
> ->  richard
>
> On 4/4/11 7:35, adrian.p.smith@bt.com wrote:
>> Hopefully someone can help me with this problem that is stopping me from progressing with Felix ?
>>
>> I have a simple bundle based on the example DictionaryBundle in the examples with the added complexity of an embedded jar file, is this case commons-lang.jar.
>>
>> I can install and start the bundle into Felix when it is run from the command line (java -jar bin/felix.jar) and I can see the embedded jar being extracted in the felix-cache directory etc. In by Activator.start() method I also invoke the bundle code to prove that it works OK.
>>
>> If I write some other code, closely following the patterns described at http://felix.apache.org/site/apache-felix-framework-launching-and-embedding.html#ApacheFelixFrameworkLaunchingandEmbedding-embedding, I find that, when the bundle is started, I get an error:
>>
>> Could not create framework: org.osgi.framework.BundleException: Activator start error in bundle [5].
>>        [java] org.osgi.framework.BundleException: Activator start error in bundle [5].
>>        [java]               at org.apache.felix.framework.Felix.activateBundle(Felix.java:1899)
>>        [java]               at org.apache.felix.framework.Felix.startBundle(Felix.java:1769)
>>        [java]               at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:927)
>>        [java]               at com.bt.test.Main.main(Main.java:298)
>>        [java] Caused by: java.lang.NoClassDefFoundError: org/apache/commons/lang/StringUtils
>>        [java]               at com.bt.test.DictionaryImpl.checkWord(DictionaryImpl.java:24)
>>        [java]               at com.bt.test.DictionaryActivator.start(DictionaryActivator.java:33)
>>        [java]               at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:629)
>>        [java]               at org.apache.felix.framework.Felix.activateBundle(Felix.java:1852)
>>        [java]               ... 3 more
>>        [java]
>>
>> I have studied the Main class from the Felix jar for differences to my code and cannot find anything obvious. Any clues appreciated.
>>
>> Thanks
>>
>> Adrian Smith
>> BT Group
>>
>>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe@felix.apache.org
> For additional commands, e-mail: users-help@felix.apache.org
>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe@felix.apache.org
> For additional commands, e-mail: users-help@felix.apache.org
>

---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@felix.apache.org
For additional commands, e-mail: users-help@felix.apache.org


Re: NoClassDefFoundError when embedding felix

Posted by Angelo van der Sijpt <an...@luminis.eu>.
Hi Adrian,

Hm, I'm not entirely sure what the problem is, but it it seems very likely that the Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA="com.bt.test; version=1.0.0" you set has something to do with it, especially because the problem goes away when your bundle has its own package set to something else. Does your fixed version still have this, and if so, why?

However, even with this fix, I'm at a loss why this all of a sudden works. Do you mean the activator exception goes away, or does your test code (where you get the service) actually work? If so, something else is going on: your service interface is inside your dictionary bundle, and cannot be seen by the Main class, not even when you put it on the classpath (again, something with importing and exporting). In this situation, I would expect a classcastexception.

As a general tip, I would try stripping out as much code as possible to find your problem. To do your testing, you can probably get away with about five lines of code, something like
        FrameworkFactory factory = (FrameworkFactory) Class.forName("org.apache.felix.framework.FrameworkFactory").newInstance();
        Bundle framework = factory.newFramework(null);
        framework.start();
        Bundle bundle = framework.getBundleContext().installBundle(new File("/tmp/bundles/dictionaryBundle.jar").toURL().toString());
        bundle.start();

This allows you to study the embedding behavior quite well.

By the way, you are right about the do-not-import-when-on-bundle-classpath: there is no need to import anything you have in your own bundle (unless you also export it).

Angelo


On Apr 4, 2011, at 4:00 PM, <ad...@bt.com> <ad...@bt.com> wrote:

> OK, so my colleague seems to have a resolution;
> 
> 1. We have separated the packages of the bundle and the host application and amended the manifest accordingly:
> 
> Bundle-Name: English dictionary
> Bundle-Description: A bundle that registers an English dictionary service
> Bundle-Vendor: Apache Felix
> Bundle-ClassPath: commons-lang-2.3.jar, .
> Bundle-Version: 1.0.0
> Bundle-Activator: com.bt.test.dictionary.DictionaryActivator
> Export-Package: com.bt.test.dictionary
> Import-Package: org.osgi.framework, com.bt.test
> 
> 
> package com.bt.test;
> 
> public interface Service {
> 	public boolean checkWord(String word);
> }
> 
> 
> package com.bt.test.dictionary;
> 
> import com.bt.test.Service;
> 
> public interface DictionaryService extends Service
> {
> 	
> }
> 
> Why this works, I don't fully understand and why the original worked inside the command line Felix is also a mystery!
> 
> 
> -----Original Message-----
> From: adrian.p.smith@bt.com [mailto:adrian.p.smith@bt.com] 
> Sent: 04 April 2011 14:29
> To: users@felix.apache.org
> Subject: RE: NoClassDefFoundError when embedding felix
> 
> Absolutely....
> 
> The bundle manifest:
> 
> Bundle-Name: English dictionary
> Bundle-Description: A bundle that registers an English dictionary service
> Bundle-Vendor: Apache Felix
> Bundle-ClassPath: commons-lang-2.3.jar, .
> Bundle-Version: 1.0.0
> Bundle-Activator: com.bt.test.DictionaryActivator
> Export-Package: com.bt.test
> Import-Package: org.osgi.framework
> 
> adrian@adrian-small-laptop:/tmp/bundles$ jar tvf dictionaryBundle.jar 
>     0 Mon Apr 04 12:57:10 BST 2011 META-INF/
>   424 Mon Apr 04 12:57:08 BST 2011 META-INF/MANIFEST.MF
>     0 Mon Apr 04 12:57:08 BST 2011 com/
>     0 Mon Apr 04 12:57:08 BST 2011 com/bt/
>     0 Mon Apr 04 12:57:08 BST 2011 com/bt/test/
>  1744 Mon Apr 04 12:57:08 BST 2011 com/bt/test/DictionaryActivator.class
>   882 Mon Apr 04 12:57:08 BST 2011 com/bt/test/DictionaryImpl.class
>   171 Mon Apr 04 12:57:08 BST 2011 com/bt/test/DictionaryService.class
> 245274 Tue Feb 13 18:32:02 GMT 2007 commons-lang-2.3.jar
> 
> 
> 
> The Main code:
> 
> package com.bt.test;
> 
> import java.io.BufferedReader;
> import java.io.File;
> import java.io.FileNotFoundException;
> import java.io.IOException;
> import java.io.InputStream;
> import java.io.InputStreamReader;
> import java.net.MalformedURLException;
> import java.net.URL;
> import java.util.ArrayList;
> import java.util.Enumeration;
> import java.util.List;
> import java.util.Properties;
> 
> import org.apache.felix.framework.util.FelixConstants;
> import org.apache.felix.framework.util.Util;
> import org.apache.felix.main.AutoProcessor;
> import org.osgi.framework.Bundle;
> import org.osgi.framework.Constants;
> import org.osgi.framework.ServiceReference;
> import org.osgi.framework.launch.Framework;
> import org.osgi.framework.launch.FrameworkFactory;
> 
> public class Main {
> 	public static final String BUNDLE_DIR_SWITCH = "-b";
> 	public static final String SHUTDOWN_HOOK_PROP = "felix.shutdown.hook";
> 	public static final String SYSTEM_PROPERTIES_PROP = "felix.system.properties";
> 	public static final String SYSTEM_PROPERTIES_FILE_VALUE = "system.properties";
> 	public static final String CONFIG_PROPERTIES_PROP = "felix.config.properties";
> 	public static final String CONFIG_PROPERTIES_FILE_VALUE = "config.properties";
> 	public static final String CONFIG_DIRECTORY = "conf";
> 	private static Framework m_fwk = null;
> 
> 	public static void main(String[] args) throws Exception {
> 		String bundleDir = null;
> 		String cacheDir = null;
> 		boolean expectBundleDir = false;
> 		for (int i = 0; i < args.length; i++) {
> 			if (args[i].equals(BUNDLE_DIR_SWITCH)) {
> 				expectBundleDir = true;
> 			} else if (expectBundleDir) {
> 				bundleDir = args[i];
> 				expectBundleDir = false;
> 			} else {
> 				cacheDir = args[i];
> 			}
> 		}
> 
> 		if ((args.length > 3) || (expectBundleDir && bundleDir == null)) {
> 			System.out.println("Usage: [-b <bundle-deploy-dir>] [<bundle-cache-dir>]");
> 			System.exit(0);
> 		}
> 
> 		Main.loadSystemProperties();
> 
> 		// Read configuration properties.
> 		Properties configProps = Main.loadConfigProperties();
> 		if (configProps == null) {
> 			System.err.println("No " + CONFIG_PROPERTIES_FILE_VALUE + " found.");
> 			configProps = new Properties();
> 		}
> 
> 		Main.copySystemProperties(configProps);
> 
> 		if (bundleDir != null) {
> 			configProps.setProperty(AutoProcessor.AUTO_DEPLOY_DIR_PROPERY, bundleDir);
> 		}
> 
> 		if (cacheDir != null) {
> 			configProps.setProperty(Constants.FRAMEWORK_STORAGE, cacheDir);
> 		}
> 
> 		String enableHook = configProps.getProperty(SHUTDOWN_HOOK_PROP);
> 		if ((enableHook == null) || !enableHook.equalsIgnoreCase("false")) {
> 			Runtime.getRuntime().addShutdownHook(
> 					new Thread("Felix Shutdown Hook") {
> 						public void run() {
> 							try {
> 								if (m_fwk != null) {
> 									m_fwk.stop();
> 									m_fwk.waitForStop(0);
> 								}
> 							} catch (Exception ex) {
> 								System.err.println("Error stopping framework: "	+ ex);
> 							}
> 						}
> 					});
> 		}
> 		
> 			
> 		configProps.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "com.bt.test; version=1.0.0");
> 		
> 
> 		try {
> 			HostActivator m_activator = new HostActivator();
> 			List list = new ArrayList();
> 			list.add(m_activator);
> 			configProps.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list);
> 
> 			FrameworkFactory factory = getFrameworkFactory();
> 			m_fwk = factory.newFramework(configProps);
> 			m_fwk.init();
> 			AutoProcessor.process(configProps, m_fwk.getBundleContext());
> 			m_fwk.start();
> 			
> 			Bundle installBundle = m_activator.getContext().installBundle(new File("/tmp/bundles/dictionaryBundle.jar").toURL().toString());
> 
> 			installBundle.start();
> 
> 			ServiceReference serviceReference = m_activator.getContext().getServiceReference(DictionaryService.class.getName());
> 			Object object = m_fwk.getBundleContext().getService(serviceReference);
> 			DictionaryService service = (DictionaryService) object;
> 			System.out.println("############################# " + service.checkWord("osgi"));
> 			System.out.println("############################# " + service.checkWord("fred"));
> 
> 			m_fwk.waitForStop(0);
> 
> 			//System.exit(0);
> 		} catch (Exception ex) {
> 			System.err.println("Could not create framework: " + ex);
> 			ex.printStackTrace();
> 			System.exit(0);
> 		}
> 	}
> 
> 	private static FrameworkFactory getFrameworkFactory() throws Exception {
> 		URL url = Main.class.getClassLoader().getResource("META-INF/services/org.osgi.framework.launch.FrameworkFactory");
> 		if (url != null) {
> 			BufferedReader br = new BufferedReader(new InputStreamReader(
> 					url.openStream()));
> 			try {
> 				for (String s = br.readLine(); s != null; s = br.readLine()) {
> 					s = s.trim();
> 					if ((s.length() > 0) && (s.charAt(0) != '#')) {
> 						return (FrameworkFactory) Class.forName(s).newInstance();
> 					}
> 				}
> 			} finally {
> 				if (br != null)
> 					br.close();
> 			}
> 		}
> 
> 		throw new Exception("Could not find framework factory.");
> 	}
> 
> 	public static void loadSystemProperties() {
> 		URL propURL = null;
> 		String custom = System.getProperty(SYSTEM_PROPERTIES_PROP);
> 		if (custom != null) {
> 			try {
> 				propURL = new URL(custom);
> 			} catch (MalformedURLException ex) {
> 				System.err.print("Main: " + ex);
> 				return;
> 			}
> 		} else {
> 			File confDir = null;
> 			String classpath = System.getProperty("java.class.path");
> 			int index = classpath.toLowerCase().indexOf("felix.jar");
> 			int start = classpath.lastIndexOf(File.pathSeparator, index) + 1;
> 			if (index >= start) {
> 				String jarLocation = classpath.substring(start, index);
> 				confDir = new File(new File(new File(jarLocation).getAbsolutePath()).getParent(), CONFIG_DIRECTORY);
> 			} else {
> 				confDir = new File(System.getProperty("user.dir"), CONFIG_DIRECTORY);
> 			}
> 
> 			try {
> 				propURL = new File(confDir, SYSTEM_PROPERTIES_FILE_VALUE).toURL();
> 			} catch (MalformedURLException ex) {
> 				System.err.print("Main: " + ex);
> 				return;
> 			}
> 		}
> 
> 		Properties props = new Properties();
> 		InputStream is = null;
> 		try {
> 			is = propURL.openConnection().getInputStream();
> 			props.load(is);
> 			is.close();
> 		} catch (FileNotFoundException ex) {
> 			// Ignore file not found.
> 		} catch (Exception ex) {
> 			System.err.println("Main: Error loading system properties from "	+ propURL);
> 			System.err.println("Main: " + ex);
> 			try {
> 				if (is != null)
> 					is.close();
> 			} catch (IOException ex2) {
> 				// Nothing we can do.
> 			}
> 			return;
> 		}
> 
> 		// Perform variable substitution on specified properties.
> 		for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
> 			String name = (String) e.nextElement();
> 			System.setProperty(name, Util.substVars(props.getProperty(name), name, null, null));
> 		}
> 	}
> 
> 	public static Properties loadConfigProperties() {
> 		URL propURL = null;
> 		String custom = System.getProperty(CONFIG_PROPERTIES_PROP);
> 		if (custom != null) {
> 			try {
> 				propURL = new URL(custom);
> 			} catch (MalformedURLException ex) {
> 				System.err.print("Main: " + ex);
> 				return null;
> 			}
> 		} else {
> 			File confDir = null;
> 			String classpath = System.getProperty("java.class.path");
> 			int index = classpath.toLowerCase().indexOf("felix.jar");
> 			int start = classpath.lastIndexOf(File.pathSeparator, index) + 1;
> 			if (index >= start) {
> 				String jarLocation = classpath.substring(start, index);
> 				confDir = new File(new File(
> 						new File(jarLocation).getAbsolutePath()).getParent(),
> 						CONFIG_DIRECTORY);
> 				System.err.println(confDir.getAbsolutePath());
> 			} else {
> 				confDir = new File(System.getProperty("user.dir"),
> 						CONFIG_DIRECTORY);
> 			}
> 
> 			try {
> 				propURL = new File(confDir, CONFIG_PROPERTIES_FILE_VALUE)
> 						.toURL();
> 			} catch (MalformedURLException ex) {
> 				System.err.print("Main: " + ex);
> 				return null;
> 			}
> 		}
> 
> 		Properties props = new Properties();
> 		InputStream is = null;
> 		try {
> 			// Try to load config.properties.
> 			is = propURL.openConnection().getInputStream();
> 			props.load(is);
> 			is.close();
> 		} catch (Exception ex) {
> 			// Try to close input stream if we have one.
> 			try {
> 				if (is != null)
> 					is.close();
> 			} catch (IOException ex2) {
> 				// Nothing we can do.
> 			}
> 
> 			return null;
> 		}
> 
> 		for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
> 			String name = (String) e.nextElement();
> 			props.setProperty(name,
> 					Util.substVars(props.getProperty(name), name, null, props));
> 		}
> 
> 		return props;
> 	}
> 
> 	public static void copySystemProperties(Properties configProps) {
> 		for (Enumeration e = System.getProperties().propertyNames(); e
> 				.hasMoreElements();) {
> 			String key = (String) e.nextElement();
> 			if (key.startsWith("felix.")
> 					|| key.startsWith("org.osgi.framework.")) {
> 				configProps.setProperty(key, System.getProperty(key));
> 			}
> 		}
> 	}
> }
> 
> -----Original Message-----
> From: Richard S. Hall [mailto:heavy@ungoverned.org] 
> Sent: 04 April 2011 13:24
> To: users@felix.apache.org
> Subject: Re: NoClassDefFoundError when embedding felix
> 
> You're not really giving enough information. How about showing us your 
> manifest file and the contents of your bundle JAR file?
> 
> -> richard
> 
> On 4/4/11 7:35, adrian.p.smith@bt.com wrote:
>> Hopefully someone can help me with this problem that is stopping me from progressing with Felix ?
>> 
>> I have a simple bundle based on the example DictionaryBundle in the examples with the added complexity of an embedded jar file, is this case commons-lang.jar.
>> 
>> I can install and start the bundle into Felix when it is run from the command line (java -jar bin/felix.jar) and I can see the embedded jar being extracted in the felix-cache directory etc. In by Activator.start() method I also invoke the bundle code to prove that it works OK.
>> 
>> If I write some other code, closely following the patterns described at http://felix.apache.org/site/apache-felix-framework-launching-and-embedding.html#ApacheFelixFrameworkLaunchingandEmbedding-embedding, I find that, when the bundle is started, I get an error:
>> 
>> Could not create framework: org.osgi.framework.BundleException: Activator start error in bundle [5].
>>      [java] org.osgi.framework.BundleException: Activator start error in bundle [5].
>>      [java]               at org.apache.felix.framework.Felix.activateBundle(Felix.java:1899)
>>      [java]               at org.apache.felix.framework.Felix.startBundle(Felix.java:1769)
>>      [java]               at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:927)
>>      [java]               at com.bt.test.Main.main(Main.java:298)
>>      [java] Caused by: java.lang.NoClassDefFoundError: org/apache/commons/lang/StringUtils
>>      [java]               at com.bt.test.DictionaryImpl.checkWord(DictionaryImpl.java:24)
>>      [java]               at com.bt.test.DictionaryActivator.start(DictionaryActivator.java:33)
>>      [java]               at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:629)
>>      [java]               at org.apache.felix.framework.Felix.activateBundle(Felix.java:1852)
>>      [java]               ... 3 more
>>      [java]
>> 
>> I have studied the Main class from the Felix jar for differences to my code and cannot find anything obvious. Any clues appreciated.
>> 
>> Thanks
>> 
>> Adrian Smith
>> BT Group
>> 
>> 
> 
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe@felix.apache.org
> For additional commands, e-mail: users-help@felix.apache.org
> 
> 
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe@felix.apache.org
> For additional commands, e-mail: users-help@felix.apache.org
> 
> 
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe@felix.apache.org
> For additional commands, e-mail: users-help@felix.apache.org
> 


---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@felix.apache.org
For additional commands, e-mail: users-help@felix.apache.org


RE: NoClassDefFoundError when embedding felix

Posted by ad...@bt.com.
Hi Simon,

Thanks for the link which has some very concise information. Actually my code does basically follow that exact pattern.

WRT the NCDFE, as I understand it, there should be no need to import packages for embedded jars and this seems to be confirmed by the fact that the bundle works without the import.

I agree with the interface refactoring, and I'd like to understand that a little more, but it seems that packages are considered "first class citizens" in osgi? I have refactored again, and removed the extra interface in the bundle package, but still retained the fact that the "host" is in a different package to the bundle.

Regards,

Adrian


-----Original Message-----
From: Simon Chemouil [mailto:schemouil@gmail.com]
Sent: 04 April 2011 15:20
To: users@felix.apache.org
Subject: Re: NoClassDefFoundError when embedding felix

Hi,

Any reason you're not using the standard way to embed OSGi containers
as nicely described there:
http://njbartlett.name/2011/03/07/embedding-osgi.html ? Or are you
stuck with a Java version anterior to 1.6?

Regarding the NCDFE, the error you have says some bundle is trying to
load apache.commons.lang.StringUtils which is not in the available
bundle classloader, since it was not imported in your manifest. I saw
that you put the commons-lang jar in the Bundle-Classpath, but I
believe you must import it anyway (using Import-Package).

 Import-Package: org.osgi.framework, com.bt.test, org.apache.commons.lang

HTH,

PS: I don't really get why you refactored DictionaryService into
another Service interface. Sounds useless to me.

Simon


On Mon, Apr 4, 2011 at 4:00 PM,  <ad...@bt.com> wrote:
> OK, so my colleague seems to have a resolution;
>
> 1. We have separated the packages of the bundle and the host application and amended the manifest accordingly:
>
> Bundle-Name: English dictionary
> Bundle-Description: A bundle that registers an English dictionary service
> Bundle-Vendor: Apache Felix
> Bundle-ClassPath: commons-lang-2.3.jar, .
> Bundle-Version: 1.0.0
> Bundle-Activator: com.bt.test.dictionary.DictionaryActivator
> Export-Package: com.bt.test.dictionary
> Import-Package: org.osgi.framework, com.bt.test
>
>
> package com.bt.test;
>
> public interface Service {
>        public boolean checkWord(String word);
> }
>
>
> package com.bt.test.dictionary;
>
> import com.bt.test.Service;
>
> public interface DictionaryService extends Service
> {
>
> }
>
> Why this works, I don't fully understand and why the original worked inside the command line Felix is also a mystery!
>
>
> -----Original Message-----
> From: adrian.p.smith@bt.com [mailto:adrian.p.smith@bt.com]
> Sent: 04 April 2011 14:29
> To: users@felix.apache.org
> Subject: RE: NoClassDefFoundError when embedding felix
>
> Absolutely....
>
> The bundle manifest:
>
> Bundle-Name: English dictionary
> Bundle-Description: A bundle that registers an English dictionary service
> Bundle-Vendor: Apache Felix
> Bundle-ClassPath: commons-lang-2.3.jar, .
> Bundle-Version: 1.0.0
> Bundle-Activator: com.bt.test.DictionaryActivator
> Export-Package: com.bt.test
> Import-Package: org.osgi.framework
>
> adrian@adrian-small-laptop:/tmp/bundles$ jar tvf dictionaryBundle.jar
>     0 Mon Apr 04 12:57:10 BST 2011 META-INF/
>   424 Mon Apr 04 12:57:08 BST 2011 META-INF/MANIFEST.MF
>     0 Mon Apr 04 12:57:08 BST 2011 com/
>     0 Mon Apr 04 12:57:08 BST 2011 com/bt/
>     0 Mon Apr 04 12:57:08 BST 2011 com/bt/test/
>  1744 Mon Apr 04 12:57:08 BST 2011 com/bt/test/DictionaryActivator.class
>   882 Mon Apr 04 12:57:08 BST 2011 com/bt/test/DictionaryImpl.class
>   171 Mon Apr 04 12:57:08 BST 2011 com/bt/test/DictionaryService.class
> 245274 Tue Feb 13 18:32:02 GMT 2007 commons-lang-2.3.jar
>
>
>
> The Main code:
>
> package com.bt.test;
>
> import java.io.BufferedReader;
> import java.io.File;
> import java.io.FileNotFoundException;
> import java.io.IOException;
> import java.io.InputStream;
> import java.io.InputStreamReader;
> import java.net.MalformedURLException;
> import java.net.URL;
> import java.util.ArrayList;
> import java.util.Enumeration;
> import java.util.List;
> import java.util.Properties;
>
> import org.apache.felix.framework.util.FelixConstants;
> import org.apache.felix.framework.util.Util;
> import org.apache.felix.main.AutoProcessor;
> import org.osgi.framework.Bundle;
> import org.osgi.framework.Constants;
> import org.osgi.framework.ServiceReference;
> import org.osgi.framework.launch.Framework;
> import org.osgi.framework.launch.FrameworkFactory;
>
> public class Main {
>        public static final String BUNDLE_DIR_SWITCH = "-b";
>        public static final String SHUTDOWN_HOOK_PROP = "felix.shutdown.hook";
>        public static final String SYSTEM_PROPERTIES_PROP = "felix.system.properties";
>        public static final String SYSTEM_PROPERTIES_FILE_VALUE = "system.properties";
>        public static final String CONFIG_PROPERTIES_PROP = "felix.config.properties";
>        public static final String CONFIG_PROPERTIES_FILE_VALUE = "config.properties";
>        public static final String CONFIG_DIRECTORY = "conf";
>        private static Framework m_fwk = null;
>
>        public static void main(String[] args) throws Exception {
>                String bundleDir = null;
>                String cacheDir = null;
>                boolean expectBundleDir = false;
>                for (int i = 0; i < args.length; i++) {
>                        if (args[i].equals(BUNDLE_DIR_SWITCH)) {
>                                expectBundleDir = true;
>                        } else if (expectBundleDir) {
>                                bundleDir = args[i];
>                                expectBundleDir = false;
>                        } else {
>                                cacheDir = args[i];
>                        }
>                }
>
>                if ((args.length > 3) || (expectBundleDir && bundleDir == null)) {
>                        System.out.println("Usage: [-b <bundle-deploy-dir>] [<bundle-cache-dir>]");
>                        System.exit(0);
>                }
>
>                Main.loadSystemProperties();
>
>                // Read configuration properties.
>                Properties configProps = Main.loadConfigProperties();
>                if (configProps == null) {
>                        System.err.println("No " + CONFIG_PROPERTIES_FILE_VALUE + " found.");
>                        configProps = new Properties();
>                }
>
>                Main.copySystemProperties(configProps);
>
>                if (bundleDir != null) {
>                        configProps.setProperty(AutoProcessor.AUTO_DEPLOY_DIR_PROPERY, bundleDir);
>                }
>
>                if (cacheDir != null) {
>                        configProps.setProperty(Constants.FRAMEWORK_STORAGE, cacheDir);
>                }
>
>                String enableHook = configProps.getProperty(SHUTDOWN_HOOK_PROP);
>                if ((enableHook == null) || !enableHook.equalsIgnoreCase("false")) {
>                        Runtime.getRuntime().addShutdownHook(
>                                        new Thread("Felix Shutdown Hook") {
>                                                public void run() {
>                                                        try {
>                                                                if (m_fwk != null) {
>                                                                        m_fwk.stop();
>                                                                        m_fwk.waitForStop(0);
>                                                                }
>                                                        } catch (Exception ex) {
>                                                                System.err.println("Error stopping framework: " + ex);
>                                                        }
>                                                }
>                                        });
>                }
>
>
>                configProps.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "com.bt.test; version=1.0.0");
>
>
>                try {
>                        HostActivator m_activator = new HostActivator();
>                        List list = new ArrayList();
>                        list.add(m_activator);
>                        configProps.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list);
>
>                        FrameworkFactory factory = getFrameworkFactory();
>                        m_fwk = factory.newFramework(configProps);
>                        m_fwk.init();
>                        AutoProcessor.process(configProps, m_fwk.getBundleContext());
>                        m_fwk.start();
>
>                        Bundle installBundle = m_activator.getContext().installBundle(new File("/tmp/bundles/dictionaryBundle.jar").toURL().toString());
>
>                        installBundle.start();
>
>                        ServiceReference serviceReference = m_activator.getContext().getServiceReference(DictionaryService.class.getName());
>                        Object object = m_fwk.getBundleContext().getService(serviceReference);
>                        DictionaryService service = (DictionaryService) object;
>                        System.out.println("############################# " + service.checkWord("osgi"));
>                        System.out.println("############################# " + service.checkWord("fred"));
>
>                        m_fwk.waitForStop(0);
>
>                        //System.exit(0);
>                } catch (Exception ex) {
>                        System.err.println("Could not create framework: " + ex);
>                        ex.printStackTrace();
>                        System.exit(0);
>                }
>        }
>
>        private static FrameworkFactory getFrameworkFactory() throws Exception {
>                URL url = Main.class.getClassLoader().getResource("META-INF/services/org.osgi.framework.launch.FrameworkFactory");
>                if (url != null) {
>                        BufferedReader br = new BufferedReader(new InputStreamReader(
>                                        url.openStream()));
>                        try {
>                                for (String s = br.readLine(); s != null; s = br.readLine()) {
>                                        s = s.trim();
>                                        if ((s.length() > 0) && (s.charAt(0) != '#')) {
>                                                return (FrameworkFactory) Class.forName(s).newInstance();
>                                        }
>                                }
>                        } finally {
>                                if (br != null)
>                                        br.close();
>                        }
>                }
>
>                throw new Exception("Could not find framework factory.");
>        }
>
>        public static void loadSystemProperties() {
>                URL propURL = null;
>                String custom = System.getProperty(SYSTEM_PROPERTIES_PROP);
>                if (custom != null) {
>                        try {
>                                propURL = new URL(custom);
>                        } catch (MalformedURLException ex) {
>                                System.err.print("Main: " + ex);
>                                return;
>                        }
>                } else {
>                        File confDir = null;
>                        String classpath = System.getProperty("java.class.path");
>                        int index = classpath.toLowerCase().indexOf("felix.jar");
>                        int start = classpath.lastIndexOf(File.pathSeparator, index) + 1;
>                        if (index >= start) {
>                                String jarLocation = classpath.substring(start, index);
>                                confDir = new File(new File(new File(jarLocation).getAbsolutePath()).getParent(), CONFIG_DIRECTORY);
>                        } else {
>                                confDir = new File(System.getProperty("user.dir"), CONFIG_DIRECTORY);
>                        }
>
>                        try {
>                                propURL = new File(confDir, SYSTEM_PROPERTIES_FILE_VALUE).toURL();
>                        } catch (MalformedURLException ex) {
>                                System.err.print("Main: " + ex);
>                                return;
>                        }
>                }
>
>                Properties props = new Properties();
>                InputStream is = null;
>                try {
>                        is = propURL.openConnection().getInputStream();
>                        props.load(is);
>                        is.close();
>                } catch (FileNotFoundException ex) {
>                        // Ignore file not found.
>                } catch (Exception ex) {
>                        System.err.println("Main: Error loading system properties from "        + propURL);
>                        System.err.println("Main: " + ex);
>                        try {
>                                if (is != null)
>                                        is.close();
>                        } catch (IOException ex2) {
>                                // Nothing we can do.
>                        }
>                        return;
>                }
>
>                // Perform variable substitution on specified properties.
>                for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
>                        String name = (String) e.nextElement();
>                        System.setProperty(name, Util.substVars(props.getProperty(name), name, null, null));
>                }
>        }
>
>        public static Properties loadConfigProperties() {
>                URL propURL = null;
>                String custom = System.getProperty(CONFIG_PROPERTIES_PROP);
>                if (custom != null) {
>                        try {
>                                propURL = new URL(custom);
>                        } catch (MalformedURLException ex) {
>                                System.err.print("Main: " + ex);
>                                return null;
>                        }
>                } else {
>                        File confDir = null;
>                        String classpath = System.getProperty("java.class.path");
>                        int index = classpath.toLowerCase().indexOf("felix.jar");
>                        int start = classpath.lastIndexOf(File.pathSeparator, index) + 1;
>                        if (index >= start) {
>                                String jarLocation = classpath.substring(start, index);
>                                confDir = new File(new File(
>                                                new File(jarLocation).getAbsolutePath()).getParent(),
>                                                CONFIG_DIRECTORY);
>                                System.err.println(confDir.getAbsolutePath());
>                        } else {
>                                confDir = new File(System.getProperty("user.dir"),
>                                                CONFIG_DIRECTORY);
>                        }
>
>                        try {
>                                propURL = new File(confDir, CONFIG_PROPERTIES_FILE_VALUE)
>                                                .toURL();
>                        } catch (MalformedURLException ex) {
>                                System.err.print("Main: " + ex);
>                                return null;
>                        }
>                }
>
>                Properties props = new Properties();
>                InputStream is = null;
>                try {
>                        // Try to load config.properties.
>                        is = propURL.openConnection().getInputStream();
>                        props.load(is);
>                        is.close();
>                } catch (Exception ex) {
>                        // Try to close input stream if we have one.
>                        try {
>                                if (is != null)
>                                        is.close();
>                        } catch (IOException ex2) {
>                                // Nothing we can do.
>                        }
>
>                        return null;
>                }
>
>                for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
>                        String name = (String) e.nextElement();
>                        props.setProperty(name,
>                                        Util.substVars(props.getProperty(name), name, null, props));
>                }
>
>                return props;
>        }
>
>        public static void copySystemProperties(Properties configProps) {
>                for (Enumeration e = System.getProperties().propertyNames(); e
>                                .hasMoreElements();) {
>                        String key = (String) e.nextElement();
>                        if (key.startsWith("felix.")
>                                        || key.startsWith("org.osgi.framework.")) {
>                                configProps.setProperty(key, System.getProperty(key));
>                        }
>                }
>        }
> }
>
> -----Original Message-----
> From: Richard S. Hall [mailto:heavy@ungoverned.org]
> Sent: 04 April 2011 13:24
> To: users@felix.apache.org
> Subject: Re: NoClassDefFoundError when embedding felix
>
> You're not really giving enough information. How about showing us your
> manifest file and the contents of your bundle JAR file?
>
> -> richard
>
> On 4/4/11 7:35, adrian.p.smith@bt.com wrote:
>> Hopefully someone can help me with this problem that is stopping me from progressing with Felix ?
>>
>> I have a simple bundle based on the example DictionaryBundle in the examples with the added complexity of an embedded jar file, is this case commons-lang.jar.
>>
>> I can install and start the bundle into Felix when it is run from the command line (java -jar bin/felix.jar) and I can see the embedded jar being extracted in the felix-cache directory etc. In by Activator.start() method I also invoke the bundle code to prove that it works OK.
>>
>> If I write some other code, closely following the patterns described at http://felix.apache.org/site/apache-felix-framework-launching-and-embedding.html#ApacheFelixFrameworkLaunchingandEmbedding-embedding, I find that, when the bundle is started, I get an error:
>>
>> Could not create framework: org.osgi.framework.BundleException: Activator start error in bundle [5].
>>       [java] org.osgi.framework.BundleException: Activator start error in bundle [5].
>>       [java]               at org.apache.felix.framework.Felix.activateBundle(Felix.java:1899)
>>       [java]               at org.apache.felix.framework.Felix.startBundle(Felix.java:1769)
>>       [java]               at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:927)
>>       [java]               at com.bt.test.Main.main(Main.java:298)
>>       [java] Caused by: java.lang.NoClassDefFoundError: org/apache/commons/lang/StringUtils
>>       [java]               at com.bt.test.DictionaryImpl.checkWord(DictionaryImpl.java:24)
>>       [java]               at com.bt.test.DictionaryActivator.start(DictionaryActivator.java:33)
>>       [java]               at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:629)
>>       [java]               at org.apache.felix.framework.Felix.activateBundle(Felix.java:1852)
>>       [java]               ... 3 more
>>       [java]
>>
>> I have studied the Main class from the Felix jar for differences to my code and cannot find anything obvious. Any clues appreciated.
>>
>> Thanks
>>
>> Adrian Smith
>> BT Group
>>
>>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe@felix.apache.org
> For additional commands, e-mail: users-help@felix.apache.org
>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe@felix.apache.org
> For additional commands, e-mail: users-help@felix.apache.org
>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe@felix.apache.org
> For additional commands, e-mail: users-help@felix.apache.org
>
>

---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@felix.apache.org
For additional commands, e-mail: users-help@felix.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@felix.apache.org
For additional commands, e-mail: users-help@felix.apache.org


Re: NoClassDefFoundError when embedding felix

Posted by Simon Chemouil <sc...@gmail.com>.
Hi,

Any reason you're not using the standard way to embed OSGi containers
as nicely described there:
http://njbartlett.name/2011/03/07/embedding-osgi.html ? Or are you
stuck with a Java version anterior to 1.6?

Regarding the NCDFE, the error you have says some bundle is trying to
load apache.commons.lang.StringUtils which is not in the available
bundle classloader, since it was not imported in your manifest. I saw
that you put the commons-lang jar in the Bundle-Classpath, but I
believe you must import it anyway (using Import-Package).

 Import-Package: org.osgi.framework, com.bt.test, org.apache.commons.lang

HTH,

PS: I don't really get why you refactored DictionaryService into
another Service interface. Sounds useless to me.

Simon


On Mon, Apr 4, 2011 at 4:00 PM,  <ad...@bt.com> wrote:
> OK, so my colleague seems to have a resolution;
>
> 1. We have separated the packages of the bundle and the host application and amended the manifest accordingly:
>
> Bundle-Name: English dictionary
> Bundle-Description: A bundle that registers an English dictionary service
> Bundle-Vendor: Apache Felix
> Bundle-ClassPath: commons-lang-2.3.jar, .
> Bundle-Version: 1.0.0
> Bundle-Activator: com.bt.test.dictionary.DictionaryActivator
> Export-Package: com.bt.test.dictionary
> Import-Package: org.osgi.framework, com.bt.test
>
>
> package com.bt.test;
>
> public interface Service {
>        public boolean checkWord(String word);
> }
>
>
> package com.bt.test.dictionary;
>
> import com.bt.test.Service;
>
> public interface DictionaryService extends Service
> {
>
> }
>
> Why this works, I don't fully understand and why the original worked inside the command line Felix is also a mystery!
>
>
> -----Original Message-----
> From: adrian.p.smith@bt.com [mailto:adrian.p.smith@bt.com]
> Sent: 04 April 2011 14:29
> To: users@felix.apache.org
> Subject: RE: NoClassDefFoundError when embedding felix
>
> Absolutely....
>
> The bundle manifest:
>
> Bundle-Name: English dictionary
> Bundle-Description: A bundle that registers an English dictionary service
> Bundle-Vendor: Apache Felix
> Bundle-ClassPath: commons-lang-2.3.jar, .
> Bundle-Version: 1.0.0
> Bundle-Activator: com.bt.test.DictionaryActivator
> Export-Package: com.bt.test
> Import-Package: org.osgi.framework
>
> adrian@adrian-small-laptop:/tmp/bundles$ jar tvf dictionaryBundle.jar
>     0 Mon Apr 04 12:57:10 BST 2011 META-INF/
>   424 Mon Apr 04 12:57:08 BST 2011 META-INF/MANIFEST.MF
>     0 Mon Apr 04 12:57:08 BST 2011 com/
>     0 Mon Apr 04 12:57:08 BST 2011 com/bt/
>     0 Mon Apr 04 12:57:08 BST 2011 com/bt/test/
>  1744 Mon Apr 04 12:57:08 BST 2011 com/bt/test/DictionaryActivator.class
>   882 Mon Apr 04 12:57:08 BST 2011 com/bt/test/DictionaryImpl.class
>   171 Mon Apr 04 12:57:08 BST 2011 com/bt/test/DictionaryService.class
> 245274 Tue Feb 13 18:32:02 GMT 2007 commons-lang-2.3.jar
>
>
>
> The Main code:
>
> package com.bt.test;
>
> import java.io.BufferedReader;
> import java.io.File;
> import java.io.FileNotFoundException;
> import java.io.IOException;
> import java.io.InputStream;
> import java.io.InputStreamReader;
> import java.net.MalformedURLException;
> import java.net.URL;
> import java.util.ArrayList;
> import java.util.Enumeration;
> import java.util.List;
> import java.util.Properties;
>
> import org.apache.felix.framework.util.FelixConstants;
> import org.apache.felix.framework.util.Util;
> import org.apache.felix.main.AutoProcessor;
> import org.osgi.framework.Bundle;
> import org.osgi.framework.Constants;
> import org.osgi.framework.ServiceReference;
> import org.osgi.framework.launch.Framework;
> import org.osgi.framework.launch.FrameworkFactory;
>
> public class Main {
>        public static final String BUNDLE_DIR_SWITCH = "-b";
>        public static final String SHUTDOWN_HOOK_PROP = "felix.shutdown.hook";
>        public static final String SYSTEM_PROPERTIES_PROP = "felix.system.properties";
>        public static final String SYSTEM_PROPERTIES_FILE_VALUE = "system.properties";
>        public static final String CONFIG_PROPERTIES_PROP = "felix.config.properties";
>        public static final String CONFIG_PROPERTIES_FILE_VALUE = "config.properties";
>        public static final String CONFIG_DIRECTORY = "conf";
>        private static Framework m_fwk = null;
>
>        public static void main(String[] args) throws Exception {
>                String bundleDir = null;
>                String cacheDir = null;
>                boolean expectBundleDir = false;
>                for (int i = 0; i < args.length; i++) {
>                        if (args[i].equals(BUNDLE_DIR_SWITCH)) {
>                                expectBundleDir = true;
>                        } else if (expectBundleDir) {
>                                bundleDir = args[i];
>                                expectBundleDir = false;
>                        } else {
>                                cacheDir = args[i];
>                        }
>                }
>
>                if ((args.length > 3) || (expectBundleDir && bundleDir == null)) {
>                        System.out.println("Usage: [-b <bundle-deploy-dir>] [<bundle-cache-dir>]");
>                        System.exit(0);
>                }
>
>                Main.loadSystemProperties();
>
>                // Read configuration properties.
>                Properties configProps = Main.loadConfigProperties();
>                if (configProps == null) {
>                        System.err.println("No " + CONFIG_PROPERTIES_FILE_VALUE + " found.");
>                        configProps = new Properties();
>                }
>
>                Main.copySystemProperties(configProps);
>
>                if (bundleDir != null) {
>                        configProps.setProperty(AutoProcessor.AUTO_DEPLOY_DIR_PROPERY, bundleDir);
>                }
>
>                if (cacheDir != null) {
>                        configProps.setProperty(Constants.FRAMEWORK_STORAGE, cacheDir);
>                }
>
>                String enableHook = configProps.getProperty(SHUTDOWN_HOOK_PROP);
>                if ((enableHook == null) || !enableHook.equalsIgnoreCase("false")) {
>                        Runtime.getRuntime().addShutdownHook(
>                                        new Thread("Felix Shutdown Hook") {
>                                                public void run() {
>                                                        try {
>                                                                if (m_fwk != null) {
>                                                                        m_fwk.stop();
>                                                                        m_fwk.waitForStop(0);
>                                                                }
>                                                        } catch (Exception ex) {
>                                                                System.err.println("Error stopping framework: " + ex);
>                                                        }
>                                                }
>                                        });
>                }
>
>
>                configProps.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "com.bt.test; version=1.0.0");
>
>
>                try {
>                        HostActivator m_activator = new HostActivator();
>                        List list = new ArrayList();
>                        list.add(m_activator);
>                        configProps.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list);
>
>                        FrameworkFactory factory = getFrameworkFactory();
>                        m_fwk = factory.newFramework(configProps);
>                        m_fwk.init();
>                        AutoProcessor.process(configProps, m_fwk.getBundleContext());
>                        m_fwk.start();
>
>                        Bundle installBundle = m_activator.getContext().installBundle(new File("/tmp/bundles/dictionaryBundle.jar").toURL().toString());
>
>                        installBundle.start();
>
>                        ServiceReference serviceReference = m_activator.getContext().getServiceReference(DictionaryService.class.getName());
>                        Object object = m_fwk.getBundleContext().getService(serviceReference);
>                        DictionaryService service = (DictionaryService) object;
>                        System.out.println("############################# " + service.checkWord("osgi"));
>                        System.out.println("############################# " + service.checkWord("fred"));
>
>                        m_fwk.waitForStop(0);
>
>                        //System.exit(0);
>                } catch (Exception ex) {
>                        System.err.println("Could not create framework: " + ex);
>                        ex.printStackTrace();
>                        System.exit(0);
>                }
>        }
>
>        private static FrameworkFactory getFrameworkFactory() throws Exception {
>                URL url = Main.class.getClassLoader().getResource("META-INF/services/org.osgi.framework.launch.FrameworkFactory");
>                if (url != null) {
>                        BufferedReader br = new BufferedReader(new InputStreamReader(
>                                        url.openStream()));
>                        try {
>                                for (String s = br.readLine(); s != null; s = br.readLine()) {
>                                        s = s.trim();
>                                        if ((s.length() > 0) && (s.charAt(0) != '#')) {
>                                                return (FrameworkFactory) Class.forName(s).newInstance();
>                                        }
>                                }
>                        } finally {
>                                if (br != null)
>                                        br.close();
>                        }
>                }
>
>                throw new Exception("Could not find framework factory.");
>        }
>
>        public static void loadSystemProperties() {
>                URL propURL = null;
>                String custom = System.getProperty(SYSTEM_PROPERTIES_PROP);
>                if (custom != null) {
>                        try {
>                                propURL = new URL(custom);
>                        } catch (MalformedURLException ex) {
>                                System.err.print("Main: " + ex);
>                                return;
>                        }
>                } else {
>                        File confDir = null;
>                        String classpath = System.getProperty("java.class.path");
>                        int index = classpath.toLowerCase().indexOf("felix.jar");
>                        int start = classpath.lastIndexOf(File.pathSeparator, index) + 1;
>                        if (index >= start) {
>                                String jarLocation = classpath.substring(start, index);
>                                confDir = new File(new File(new File(jarLocation).getAbsolutePath()).getParent(), CONFIG_DIRECTORY);
>                        } else {
>                                confDir = new File(System.getProperty("user.dir"), CONFIG_DIRECTORY);
>                        }
>
>                        try {
>                                propURL = new File(confDir, SYSTEM_PROPERTIES_FILE_VALUE).toURL();
>                        } catch (MalformedURLException ex) {
>                                System.err.print("Main: " + ex);
>                                return;
>                        }
>                }
>
>                Properties props = new Properties();
>                InputStream is = null;
>                try {
>                        is = propURL.openConnection().getInputStream();
>                        props.load(is);
>                        is.close();
>                } catch (FileNotFoundException ex) {
>                        // Ignore file not found.
>                } catch (Exception ex) {
>                        System.err.println("Main: Error loading system properties from "        + propURL);
>                        System.err.println("Main: " + ex);
>                        try {
>                                if (is != null)
>                                        is.close();
>                        } catch (IOException ex2) {
>                                // Nothing we can do.
>                        }
>                        return;
>                }
>
>                // Perform variable substitution on specified properties.
>                for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
>                        String name = (String) e.nextElement();
>                        System.setProperty(name, Util.substVars(props.getProperty(name), name, null, null));
>                }
>        }
>
>        public static Properties loadConfigProperties() {
>                URL propURL = null;
>                String custom = System.getProperty(CONFIG_PROPERTIES_PROP);
>                if (custom != null) {
>                        try {
>                                propURL = new URL(custom);
>                        } catch (MalformedURLException ex) {
>                                System.err.print("Main: " + ex);
>                                return null;
>                        }
>                } else {
>                        File confDir = null;
>                        String classpath = System.getProperty("java.class.path");
>                        int index = classpath.toLowerCase().indexOf("felix.jar");
>                        int start = classpath.lastIndexOf(File.pathSeparator, index) + 1;
>                        if (index >= start) {
>                                String jarLocation = classpath.substring(start, index);
>                                confDir = new File(new File(
>                                                new File(jarLocation).getAbsolutePath()).getParent(),
>                                                CONFIG_DIRECTORY);
>                                System.err.println(confDir.getAbsolutePath());
>                        } else {
>                                confDir = new File(System.getProperty("user.dir"),
>                                                CONFIG_DIRECTORY);
>                        }
>
>                        try {
>                                propURL = new File(confDir, CONFIG_PROPERTIES_FILE_VALUE)
>                                                .toURL();
>                        } catch (MalformedURLException ex) {
>                                System.err.print("Main: " + ex);
>                                return null;
>                        }
>                }
>
>                Properties props = new Properties();
>                InputStream is = null;
>                try {
>                        // Try to load config.properties.
>                        is = propURL.openConnection().getInputStream();
>                        props.load(is);
>                        is.close();
>                } catch (Exception ex) {
>                        // Try to close input stream if we have one.
>                        try {
>                                if (is != null)
>                                        is.close();
>                        } catch (IOException ex2) {
>                                // Nothing we can do.
>                        }
>
>                        return null;
>                }
>
>                for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
>                        String name = (String) e.nextElement();
>                        props.setProperty(name,
>                                        Util.substVars(props.getProperty(name), name, null, props));
>                }
>
>                return props;
>        }
>
>        public static void copySystemProperties(Properties configProps) {
>                for (Enumeration e = System.getProperties().propertyNames(); e
>                                .hasMoreElements();) {
>                        String key = (String) e.nextElement();
>                        if (key.startsWith("felix.")
>                                        || key.startsWith("org.osgi.framework.")) {
>                                configProps.setProperty(key, System.getProperty(key));
>                        }
>                }
>        }
> }
>
> -----Original Message-----
> From: Richard S. Hall [mailto:heavy@ungoverned.org]
> Sent: 04 April 2011 13:24
> To: users@felix.apache.org
> Subject: Re: NoClassDefFoundError when embedding felix
>
> You're not really giving enough information. How about showing us your
> manifest file and the contents of your bundle JAR file?
>
> -> richard
>
> On 4/4/11 7:35, adrian.p.smith@bt.com wrote:
>> Hopefully someone can help me with this problem that is stopping me from progressing with Felix ?
>>
>> I have a simple bundle based on the example DictionaryBundle in the examples with the added complexity of an embedded jar file, is this case commons-lang.jar.
>>
>> I can install and start the bundle into Felix when it is run from the command line (java -jar bin/felix.jar) and I can see the embedded jar being extracted in the felix-cache directory etc. In by Activator.start() method I also invoke the bundle code to prove that it works OK.
>>
>> If I write some other code, closely following the patterns described at http://felix.apache.org/site/apache-felix-framework-launching-and-embedding.html#ApacheFelixFrameworkLaunchingandEmbedding-embedding, I find that, when the bundle is started, I get an error:
>>
>> Could not create framework: org.osgi.framework.BundleException: Activator start error in bundle [5].
>>       [java] org.osgi.framework.BundleException: Activator start error in bundle [5].
>>       [java]               at org.apache.felix.framework.Felix.activateBundle(Felix.java:1899)
>>       [java]               at org.apache.felix.framework.Felix.startBundle(Felix.java:1769)
>>       [java]               at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:927)
>>       [java]               at com.bt.test.Main.main(Main.java:298)
>>       [java] Caused by: java.lang.NoClassDefFoundError: org/apache/commons/lang/StringUtils
>>       [java]               at com.bt.test.DictionaryImpl.checkWord(DictionaryImpl.java:24)
>>       [java]               at com.bt.test.DictionaryActivator.start(DictionaryActivator.java:33)
>>       [java]               at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:629)
>>       [java]               at org.apache.felix.framework.Felix.activateBundle(Felix.java:1852)
>>       [java]               ... 3 more
>>       [java]
>>
>> I have studied the Main class from the Felix jar for differences to my code and cannot find anything obvious. Any clues appreciated.
>>
>> Thanks
>>
>> Adrian Smith
>> BT Group
>>
>>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe@felix.apache.org
> For additional commands, e-mail: users-help@felix.apache.org
>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe@felix.apache.org
> For additional commands, e-mail: users-help@felix.apache.org
>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe@felix.apache.org
> For additional commands, e-mail: users-help@felix.apache.org
>
>

---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@felix.apache.org
For additional commands, e-mail: users-help@felix.apache.org


RE: NoClassDefFoundError when embedding felix

Posted by ad...@bt.com.
OK, so my colleague seems to have a resolution;

1. We have separated the packages of the bundle and the host application and amended the manifest accordingly:

Bundle-Name: English dictionary
Bundle-Description: A bundle that registers an English dictionary service
Bundle-Vendor: Apache Felix
Bundle-ClassPath: commons-lang-2.3.jar, .
Bundle-Version: 1.0.0
Bundle-Activator: com.bt.test.dictionary.DictionaryActivator
Export-Package: com.bt.test.dictionary
Import-Package: org.osgi.framework, com.bt.test


package com.bt.test;

public interface Service {
	public boolean checkWord(String word);
}


package com.bt.test.dictionary;

import com.bt.test.Service;

public interface DictionaryService extends Service
{
	
}

Why this works, I don't fully understand and why the original worked inside the command line Felix is also a mystery!


-----Original Message-----
From: adrian.p.smith@bt.com [mailto:adrian.p.smith@bt.com] 
Sent: 04 April 2011 14:29
To: users@felix.apache.org
Subject: RE: NoClassDefFoundError when embedding felix

Absolutely....

The bundle manifest:

Bundle-Name: English dictionary
Bundle-Description: A bundle that registers an English dictionary service
Bundle-Vendor: Apache Felix
Bundle-ClassPath: commons-lang-2.3.jar, .
Bundle-Version: 1.0.0
Bundle-Activator: com.bt.test.DictionaryActivator
Export-Package: com.bt.test
Import-Package: org.osgi.framework

adrian@adrian-small-laptop:/tmp/bundles$ jar tvf dictionaryBundle.jar 
     0 Mon Apr 04 12:57:10 BST 2011 META-INF/
   424 Mon Apr 04 12:57:08 BST 2011 META-INF/MANIFEST.MF
     0 Mon Apr 04 12:57:08 BST 2011 com/
     0 Mon Apr 04 12:57:08 BST 2011 com/bt/
     0 Mon Apr 04 12:57:08 BST 2011 com/bt/test/
  1744 Mon Apr 04 12:57:08 BST 2011 com/bt/test/DictionaryActivator.class
   882 Mon Apr 04 12:57:08 BST 2011 com/bt/test/DictionaryImpl.class
   171 Mon Apr 04 12:57:08 BST 2011 com/bt/test/DictionaryService.class
245274 Tue Feb 13 18:32:02 GMT 2007 commons-lang-2.3.jar



The Main code:

package com.bt.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

import org.apache.felix.framework.util.FelixConstants;
import org.apache.felix.framework.util.Util;
import org.apache.felix.main.AutoProcessor;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.launch.Framework;
import org.osgi.framework.launch.FrameworkFactory;

public class Main {
	public static final String BUNDLE_DIR_SWITCH = "-b";
	public static final String SHUTDOWN_HOOK_PROP = "felix.shutdown.hook";
	public static final String SYSTEM_PROPERTIES_PROP = "felix.system.properties";
	public static final String SYSTEM_PROPERTIES_FILE_VALUE = "system.properties";
	public static final String CONFIG_PROPERTIES_PROP = "felix.config.properties";
	public static final String CONFIG_PROPERTIES_FILE_VALUE = "config.properties";
	public static final String CONFIG_DIRECTORY = "conf";
	private static Framework m_fwk = null;

	public static void main(String[] args) throws Exception {
		String bundleDir = null;
		String cacheDir = null;
		boolean expectBundleDir = false;
		for (int i = 0; i < args.length; i++) {
			if (args[i].equals(BUNDLE_DIR_SWITCH)) {
				expectBundleDir = true;
			} else if (expectBundleDir) {
				bundleDir = args[i];
				expectBundleDir = false;
			} else {
				cacheDir = args[i];
			}
		}

		if ((args.length > 3) || (expectBundleDir && bundleDir == null)) {
			System.out.println("Usage: [-b <bundle-deploy-dir>] [<bundle-cache-dir>]");
			System.exit(0);
		}

		Main.loadSystemProperties();

		// Read configuration properties.
		Properties configProps = Main.loadConfigProperties();
		if (configProps == null) {
			System.err.println("No " + CONFIG_PROPERTIES_FILE_VALUE + " found.");
			configProps = new Properties();
		}

		Main.copySystemProperties(configProps);

		if (bundleDir != null) {
			configProps.setProperty(AutoProcessor.AUTO_DEPLOY_DIR_PROPERY, bundleDir);
		}

		if (cacheDir != null) {
			configProps.setProperty(Constants.FRAMEWORK_STORAGE, cacheDir);
		}

		String enableHook = configProps.getProperty(SHUTDOWN_HOOK_PROP);
		if ((enableHook == null) || !enableHook.equalsIgnoreCase("false")) {
			Runtime.getRuntime().addShutdownHook(
					new Thread("Felix Shutdown Hook") {
						public void run() {
							try {
								if (m_fwk != null) {
									m_fwk.stop();
									m_fwk.waitForStop(0);
								}
							} catch (Exception ex) {
								System.err.println("Error stopping framework: "	+ ex);
							}
						}
					});
		}
		
			
		configProps.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "com.bt.test; version=1.0.0");
		

		try {
			HostActivator m_activator = new HostActivator();
			List list = new ArrayList();
			list.add(m_activator);
			configProps.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list);

			FrameworkFactory factory = getFrameworkFactory();
			m_fwk = factory.newFramework(configProps);
			m_fwk.init();
			AutoProcessor.process(configProps, m_fwk.getBundleContext());
			m_fwk.start();
			
			Bundle installBundle = m_activator.getContext().installBundle(new File("/tmp/bundles/dictionaryBundle.jar").toURL().toString());

			installBundle.start();

			ServiceReference serviceReference = m_activator.getContext().getServiceReference(DictionaryService.class.getName());
			Object object = m_fwk.getBundleContext().getService(serviceReference);
			DictionaryService service = (DictionaryService) object;
			System.out.println("############################# " + service.checkWord("osgi"));
			System.out.println("############################# " + service.checkWord("fred"));

			m_fwk.waitForStop(0);

			//System.exit(0);
		} catch (Exception ex) {
			System.err.println("Could not create framework: " + ex);
			ex.printStackTrace();
			System.exit(0);
		}
	}

	private static FrameworkFactory getFrameworkFactory() throws Exception {
		URL url = Main.class.getClassLoader().getResource("META-INF/services/org.osgi.framework.launch.FrameworkFactory");
		if (url != null) {
			BufferedReader br = new BufferedReader(new InputStreamReader(
					url.openStream()));
			try {
				for (String s = br.readLine(); s != null; s = br.readLine()) {
					s = s.trim();
					if ((s.length() > 0) && (s.charAt(0) != '#')) {
						return (FrameworkFactory) Class.forName(s).newInstance();
					}
				}
			} finally {
				if (br != null)
					br.close();
			}
		}

		throw new Exception("Could not find framework factory.");
	}

	public static void loadSystemProperties() {
		URL propURL = null;
		String custom = System.getProperty(SYSTEM_PROPERTIES_PROP);
		if (custom != null) {
			try {
				propURL = new URL(custom);
			} catch (MalformedURLException ex) {
				System.err.print("Main: " + ex);
				return;
			}
		} else {
			File confDir = null;
			String classpath = System.getProperty("java.class.path");
			int index = classpath.toLowerCase().indexOf("felix.jar");
			int start = classpath.lastIndexOf(File.pathSeparator, index) + 1;
			if (index >= start) {
				String jarLocation = classpath.substring(start, index);
				confDir = new File(new File(new File(jarLocation).getAbsolutePath()).getParent(), CONFIG_DIRECTORY);
			} else {
				confDir = new File(System.getProperty("user.dir"), CONFIG_DIRECTORY);
			}

			try {
				propURL = new File(confDir, SYSTEM_PROPERTIES_FILE_VALUE).toURL();
			} catch (MalformedURLException ex) {
				System.err.print("Main: " + ex);
				return;
			}
		}

		Properties props = new Properties();
		InputStream is = null;
		try {
			is = propURL.openConnection().getInputStream();
			props.load(is);
			is.close();
		} catch (FileNotFoundException ex) {
			// Ignore file not found.
		} catch (Exception ex) {
			System.err.println("Main: Error loading system properties from "	+ propURL);
			System.err.println("Main: " + ex);
			try {
				if (is != null)
					is.close();
			} catch (IOException ex2) {
				// Nothing we can do.
			}
			return;
		}

		// Perform variable substitution on specified properties.
		for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
			String name = (String) e.nextElement();
			System.setProperty(name, Util.substVars(props.getProperty(name), name, null, null));
		}
	}

	public static Properties loadConfigProperties() {
		URL propURL = null;
		String custom = System.getProperty(CONFIG_PROPERTIES_PROP);
		if (custom != null) {
			try {
				propURL = new URL(custom);
			} catch (MalformedURLException ex) {
				System.err.print("Main: " + ex);
				return null;
			}
		} else {
			File confDir = null;
			String classpath = System.getProperty("java.class.path");
			int index = classpath.toLowerCase().indexOf("felix.jar");
			int start = classpath.lastIndexOf(File.pathSeparator, index) + 1;
			if (index >= start) {
				String jarLocation = classpath.substring(start, index);
				confDir = new File(new File(
						new File(jarLocation).getAbsolutePath()).getParent(),
						CONFIG_DIRECTORY);
				System.err.println(confDir.getAbsolutePath());
			} else {
				confDir = new File(System.getProperty("user.dir"),
						CONFIG_DIRECTORY);
			}

			try {
				propURL = new File(confDir, CONFIG_PROPERTIES_FILE_VALUE)
						.toURL();
			} catch (MalformedURLException ex) {
				System.err.print("Main: " + ex);
				return null;
			}
		}

		Properties props = new Properties();
		InputStream is = null;
		try {
			// Try to load config.properties.
			is = propURL.openConnection().getInputStream();
			props.load(is);
			is.close();
		} catch (Exception ex) {
			// Try to close input stream if we have one.
			try {
				if (is != null)
					is.close();
			} catch (IOException ex2) {
				// Nothing we can do.
			}

			return null;
		}

		for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
			String name = (String) e.nextElement();
			props.setProperty(name,
					Util.substVars(props.getProperty(name), name, null, props));
		}

		return props;
	}

	public static void copySystemProperties(Properties configProps) {
		for (Enumeration e = System.getProperties().propertyNames(); e
				.hasMoreElements();) {
			String key = (String) e.nextElement();
			if (key.startsWith("felix.")
					|| key.startsWith("org.osgi.framework.")) {
				configProps.setProperty(key, System.getProperty(key));
			}
		}
	}
}

-----Original Message-----
From: Richard S. Hall [mailto:heavy@ungoverned.org] 
Sent: 04 April 2011 13:24
To: users@felix.apache.org
Subject: Re: NoClassDefFoundError when embedding felix

You're not really giving enough information. How about showing us your 
manifest file and the contents of your bundle JAR file?

-> richard

On 4/4/11 7:35, adrian.p.smith@bt.com wrote:
> Hopefully someone can help me with this problem that is stopping me from progressing with Felix ?
>
> I have a simple bundle based on the example DictionaryBundle in the examples with the added complexity of an embedded jar file, is this case commons-lang.jar.
>
> I can install and start the bundle into Felix when it is run from the command line (java -jar bin/felix.jar) and I can see the embedded jar being extracted in the felix-cache directory etc. In by Activator.start() method I also invoke the bundle code to prove that it works OK.
>
> If I write some other code, closely following the patterns described at http://felix.apache.org/site/apache-felix-framework-launching-and-embedding.html#ApacheFelixFrameworkLaunchingandEmbedding-embedding, I find that, when the bundle is started, I get an error:
>
> Could not create framework: org.osgi.framework.BundleException: Activator start error in bundle [5].
>       [java] org.osgi.framework.BundleException: Activator start error in bundle [5].
>       [java]               at org.apache.felix.framework.Felix.activateBundle(Felix.java:1899)
>       [java]               at org.apache.felix.framework.Felix.startBundle(Felix.java:1769)
>       [java]               at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:927)
>       [java]               at com.bt.test.Main.main(Main.java:298)
>       [java] Caused by: java.lang.NoClassDefFoundError: org/apache/commons/lang/StringUtils
>       [java]               at com.bt.test.DictionaryImpl.checkWord(DictionaryImpl.java:24)
>       [java]               at com.bt.test.DictionaryActivator.start(DictionaryActivator.java:33)
>       [java]               at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:629)
>       [java]               at org.apache.felix.framework.Felix.activateBundle(Felix.java:1852)
>       [java]               ... 3 more
>       [java]
>
> I have studied the Main class from the Felix jar for differences to my code and cannot find anything obvious. Any clues appreciated.
>
> Thanks
>
> Adrian Smith
> BT Group
>
>

---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@felix.apache.org
For additional commands, e-mail: users-help@felix.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@felix.apache.org
For additional commands, e-mail: users-help@felix.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@felix.apache.org
For additional commands, e-mail: users-help@felix.apache.org


RE: NoClassDefFoundError when embedding felix

Posted by ad...@bt.com.
Absolutely....

The bundle manifest:

Bundle-Name: English dictionary
Bundle-Description: A bundle that registers an English dictionary service
Bundle-Vendor: Apache Felix
Bundle-ClassPath: commons-lang-2.3.jar, .
Bundle-Version: 1.0.0
Bundle-Activator: com.bt.test.DictionaryActivator
Export-Package: com.bt.test
Import-Package: org.osgi.framework

adrian@adrian-small-laptop:/tmp/bundles$ jar tvf dictionaryBundle.jar 
     0 Mon Apr 04 12:57:10 BST 2011 META-INF/
   424 Mon Apr 04 12:57:08 BST 2011 META-INF/MANIFEST.MF
     0 Mon Apr 04 12:57:08 BST 2011 com/
     0 Mon Apr 04 12:57:08 BST 2011 com/bt/
     0 Mon Apr 04 12:57:08 BST 2011 com/bt/test/
  1744 Mon Apr 04 12:57:08 BST 2011 com/bt/test/DictionaryActivator.class
   882 Mon Apr 04 12:57:08 BST 2011 com/bt/test/DictionaryImpl.class
   171 Mon Apr 04 12:57:08 BST 2011 com/bt/test/DictionaryService.class
245274 Tue Feb 13 18:32:02 GMT 2007 commons-lang-2.3.jar



The Main code:

package com.bt.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

import org.apache.felix.framework.util.FelixConstants;
import org.apache.felix.framework.util.Util;
import org.apache.felix.main.AutoProcessor;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.launch.Framework;
import org.osgi.framework.launch.FrameworkFactory;

public class Main {
	public static final String BUNDLE_DIR_SWITCH = "-b";
	public static final String SHUTDOWN_HOOK_PROP = "felix.shutdown.hook";
	public static final String SYSTEM_PROPERTIES_PROP = "felix.system.properties";
	public static final String SYSTEM_PROPERTIES_FILE_VALUE = "system.properties";
	public static final String CONFIG_PROPERTIES_PROP = "felix.config.properties";
	public static final String CONFIG_PROPERTIES_FILE_VALUE = "config.properties";
	public static final String CONFIG_DIRECTORY = "conf";
	private static Framework m_fwk = null;

	public static void main(String[] args) throws Exception {
		String bundleDir = null;
		String cacheDir = null;
		boolean expectBundleDir = false;
		for (int i = 0; i < args.length; i++) {
			if (args[i].equals(BUNDLE_DIR_SWITCH)) {
				expectBundleDir = true;
			} else if (expectBundleDir) {
				bundleDir = args[i];
				expectBundleDir = false;
			} else {
				cacheDir = args[i];
			}
		}

		if ((args.length > 3) || (expectBundleDir && bundleDir == null)) {
			System.out.println("Usage: [-b <bundle-deploy-dir>] [<bundle-cache-dir>]");
			System.exit(0);
		}

		Main.loadSystemProperties();

		// Read configuration properties.
		Properties configProps = Main.loadConfigProperties();
		if (configProps == null) {
			System.err.println("No " + CONFIG_PROPERTIES_FILE_VALUE + " found.");
			configProps = new Properties();
		}

		Main.copySystemProperties(configProps);

		if (bundleDir != null) {
			configProps.setProperty(AutoProcessor.AUTO_DEPLOY_DIR_PROPERY, bundleDir);
		}

		if (cacheDir != null) {
			configProps.setProperty(Constants.FRAMEWORK_STORAGE, cacheDir);
		}

		String enableHook = configProps.getProperty(SHUTDOWN_HOOK_PROP);
		if ((enableHook == null) || !enableHook.equalsIgnoreCase("false")) {
			Runtime.getRuntime().addShutdownHook(
					new Thread("Felix Shutdown Hook") {
						public void run() {
							try {
								if (m_fwk != null) {
									m_fwk.stop();
									m_fwk.waitForStop(0);
								}
							} catch (Exception ex) {
								System.err.println("Error stopping framework: "	+ ex);
							}
						}
					});
		}
		
			
		configProps.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "com.bt.test; version=1.0.0");
		

		try {
			HostActivator m_activator = new HostActivator();
			List list = new ArrayList();
			list.add(m_activator);
			configProps.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list);

			FrameworkFactory factory = getFrameworkFactory();
			m_fwk = factory.newFramework(configProps);
			m_fwk.init();
			AutoProcessor.process(configProps, m_fwk.getBundleContext());
			m_fwk.start();
			
			Bundle installBundle = m_activator.getContext().installBundle(new File("/tmp/bundles/dictionaryBundle.jar").toURL().toString());

			installBundle.start();

			ServiceReference serviceReference = m_activator.getContext().getServiceReference(DictionaryService.class.getName());
			Object object = m_fwk.getBundleContext().getService(serviceReference);
			DictionaryService service = (DictionaryService) object;
			System.out.println("############################# " + service.checkWord("osgi"));
			System.out.println("############################# " + service.checkWord("fred"));

			m_fwk.waitForStop(0);

			//System.exit(0);
		} catch (Exception ex) {
			System.err.println("Could not create framework: " + ex);
			ex.printStackTrace();
			System.exit(0);
		}
	}

	private static FrameworkFactory getFrameworkFactory() throws Exception {
		URL url = Main.class.getClassLoader().getResource("META-INF/services/org.osgi.framework.launch.FrameworkFactory");
		if (url != null) {
			BufferedReader br = new BufferedReader(new InputStreamReader(
					url.openStream()));
			try {
				for (String s = br.readLine(); s != null; s = br.readLine()) {
					s = s.trim();
					if ((s.length() > 0) && (s.charAt(0) != '#')) {
						return (FrameworkFactory) Class.forName(s).newInstance();
					}
				}
			} finally {
				if (br != null)
					br.close();
			}
		}

		throw new Exception("Could not find framework factory.");
	}

	public static void loadSystemProperties() {
		URL propURL = null;
		String custom = System.getProperty(SYSTEM_PROPERTIES_PROP);
		if (custom != null) {
			try {
				propURL = new URL(custom);
			} catch (MalformedURLException ex) {
				System.err.print("Main: " + ex);
				return;
			}
		} else {
			File confDir = null;
			String classpath = System.getProperty("java.class.path");
			int index = classpath.toLowerCase().indexOf("felix.jar");
			int start = classpath.lastIndexOf(File.pathSeparator, index) + 1;
			if (index >= start) {
				String jarLocation = classpath.substring(start, index);
				confDir = new File(new File(new File(jarLocation).getAbsolutePath()).getParent(), CONFIG_DIRECTORY);
			} else {
				confDir = new File(System.getProperty("user.dir"), CONFIG_DIRECTORY);
			}

			try {
				propURL = new File(confDir, SYSTEM_PROPERTIES_FILE_VALUE).toURL();
			} catch (MalformedURLException ex) {
				System.err.print("Main: " + ex);
				return;
			}
		}

		Properties props = new Properties();
		InputStream is = null;
		try {
			is = propURL.openConnection().getInputStream();
			props.load(is);
			is.close();
		} catch (FileNotFoundException ex) {
			// Ignore file not found.
		} catch (Exception ex) {
			System.err.println("Main: Error loading system properties from "	+ propURL);
			System.err.println("Main: " + ex);
			try {
				if (is != null)
					is.close();
			} catch (IOException ex2) {
				// Nothing we can do.
			}
			return;
		}

		// Perform variable substitution on specified properties.
		for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
			String name = (String) e.nextElement();
			System.setProperty(name, Util.substVars(props.getProperty(name), name, null, null));
		}
	}

	public static Properties loadConfigProperties() {
		URL propURL = null;
		String custom = System.getProperty(CONFIG_PROPERTIES_PROP);
		if (custom != null) {
			try {
				propURL = new URL(custom);
			} catch (MalformedURLException ex) {
				System.err.print("Main: " + ex);
				return null;
			}
		} else {
			File confDir = null;
			String classpath = System.getProperty("java.class.path");
			int index = classpath.toLowerCase().indexOf("felix.jar");
			int start = classpath.lastIndexOf(File.pathSeparator, index) + 1;
			if (index >= start) {
				String jarLocation = classpath.substring(start, index);
				confDir = new File(new File(
						new File(jarLocation).getAbsolutePath()).getParent(),
						CONFIG_DIRECTORY);
				System.err.println(confDir.getAbsolutePath());
			} else {
				confDir = new File(System.getProperty("user.dir"),
						CONFIG_DIRECTORY);
			}

			try {
				propURL = new File(confDir, CONFIG_PROPERTIES_FILE_VALUE)
						.toURL();
			} catch (MalformedURLException ex) {
				System.err.print("Main: " + ex);
				return null;
			}
		}

		Properties props = new Properties();
		InputStream is = null;
		try {
			// Try to load config.properties.
			is = propURL.openConnection().getInputStream();
			props.load(is);
			is.close();
		} catch (Exception ex) {
			// Try to close input stream if we have one.
			try {
				if (is != null)
					is.close();
			} catch (IOException ex2) {
				// Nothing we can do.
			}

			return null;
		}

		for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
			String name = (String) e.nextElement();
			props.setProperty(name,
					Util.substVars(props.getProperty(name), name, null, props));
		}

		return props;
	}

	public static void copySystemProperties(Properties configProps) {
		for (Enumeration e = System.getProperties().propertyNames(); e
				.hasMoreElements();) {
			String key = (String) e.nextElement();
			if (key.startsWith("felix.")
					|| key.startsWith("org.osgi.framework.")) {
				configProps.setProperty(key, System.getProperty(key));
			}
		}
	}
}

-----Original Message-----
From: Richard S. Hall [mailto:heavy@ungoverned.org] 
Sent: 04 April 2011 13:24
To: users@felix.apache.org
Subject: Re: NoClassDefFoundError when embedding felix

You're not really giving enough information. How about showing us your 
manifest file and the contents of your bundle JAR file?

-> richard

On 4/4/11 7:35, adrian.p.smith@bt.com wrote:
> Hopefully someone can help me with this problem that is stopping me from progressing with Felix ?
>
> I have a simple bundle based on the example DictionaryBundle in the examples with the added complexity of an embedded jar file, is this case commons-lang.jar.
>
> I can install and start the bundle into Felix when it is run from the command line (java -jar bin/felix.jar) and I can see the embedded jar being extracted in the felix-cache directory etc. In by Activator.start() method I also invoke the bundle code to prove that it works OK.
>
> If I write some other code, closely following the patterns described at http://felix.apache.org/site/apache-felix-framework-launching-and-embedding.html#ApacheFelixFrameworkLaunchingandEmbedding-embedding, I find that, when the bundle is started, I get an error:
>
> Could not create framework: org.osgi.framework.BundleException: Activator start error in bundle [5].
>       [java] org.osgi.framework.BundleException: Activator start error in bundle [5].
>       [java]               at org.apache.felix.framework.Felix.activateBundle(Felix.java:1899)
>       [java]               at org.apache.felix.framework.Felix.startBundle(Felix.java:1769)
>       [java]               at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:927)
>       [java]               at com.bt.test.Main.main(Main.java:298)
>       [java] Caused by: java.lang.NoClassDefFoundError: org/apache/commons/lang/StringUtils
>       [java]               at com.bt.test.DictionaryImpl.checkWord(DictionaryImpl.java:24)
>       [java]               at com.bt.test.DictionaryActivator.start(DictionaryActivator.java:33)
>       [java]               at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:629)
>       [java]               at org.apache.felix.framework.Felix.activateBundle(Felix.java:1852)
>       [java]               ... 3 more
>       [java]
>
> I have studied the Main class from the Felix jar for differences to my code and cannot find anything obvious. Any clues appreciated.
>
> Thanks
>
> Adrian Smith
> BT Group
>
>

---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@felix.apache.org
For additional commands, e-mail: users-help@felix.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@felix.apache.org
For additional commands, e-mail: users-help@felix.apache.org


Re: NoClassDefFoundError when embedding felix

Posted by "Richard S. Hall" <he...@ungoverned.org>.
You're not really giving enough information. How about showing us your 
manifest file and the contents of your bundle JAR file?

-> richard

On 4/4/11 7:35, adrian.p.smith@bt.com wrote:
> Hopefully someone can help me with this problem that is stopping me from progressing with Felix ?
>
> I have a simple bundle based on the example DictionaryBundle in the examples with the added complexity of an embedded jar file, is this case commons-lang.jar.
>
> I can install and start the bundle into Felix when it is run from the command line (java -jar bin/felix.jar) and I can see the embedded jar being extracted in the felix-cache directory etc. In by Activator.start() method I also invoke the bundle code to prove that it works OK.
>
> If I write some other code, closely following the patterns described at http://felix.apache.org/site/apache-felix-framework-launching-and-embedding.html#ApacheFelixFrameworkLaunchingandEmbedding-embedding, I find that, when the bundle is started, I get an error:
>
> Could not create framework: org.osgi.framework.BundleException: Activator start error in bundle [5].
>       [java] org.osgi.framework.BundleException: Activator start error in bundle [5].
>       [java]               at org.apache.felix.framework.Felix.activateBundle(Felix.java:1899)
>       [java]               at org.apache.felix.framework.Felix.startBundle(Felix.java:1769)
>       [java]               at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:927)
>       [java]               at com.bt.test.Main.main(Main.java:298)
>       [java] Caused by: java.lang.NoClassDefFoundError: org/apache/commons/lang/StringUtils
>       [java]               at com.bt.test.DictionaryImpl.checkWord(DictionaryImpl.java:24)
>       [java]               at com.bt.test.DictionaryActivator.start(DictionaryActivator.java:33)
>       [java]               at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:629)
>       [java]               at org.apache.felix.framework.Felix.activateBundle(Felix.java:1852)
>       [java]               ... 3 more
>       [java]
>
> I have studied the Main class from the Felix jar for differences to my code and cannot find anything obvious. Any clues appreciated.
>
> Thanks
>
> Adrian Smith
> BT Group
>
>

---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@felix.apache.org
For additional commands, e-mail: users-help@felix.apache.org