Spring Boot + OSGI : NoClassDefFoundError on jackson databind - noclassdeffounderror

I fail to configure a project based on Spring Boot, extended with OSGI, and using Jackson in a bundle
by using import/export package system (I would like to avoid to embed the lib).
I started from this project.
Maven modules:
a Spring Boot module, the main app, initialized with Felix, like the referenced project above
a bundle module, where I want to use ObjectMapper on activation like this
#Activate
public void activate() {
ObjectMapper objectMapper = new ObjectMapper();
}
But on activation I got the following error:
NoClassDefFoundError: com/fasterxml/jackson/databind/ObjectMapper
Yet, I had exported this package from the main app bundle (Spring Boot) and imported it in the bundle module.
This bundle module use maven-bundle-plugin (while the main app use nothing specific):
<instructions>
<_dsannotations>*</_dsannotations>
<_metatypeannotations>*</_metatypeannotations>
<Bundle-Vendor>Foo</Bundle-Vendor>
<Bundle-Version>${project.version}</Bundle-Version>
<Export-Service>
com.foo.bar.plugin.RestTaskPlugin
</Export-Service>
<Export-Package>
com.foo.bar.plugin.rest,
com.foo.bar.plugin.rest.web,
com.foo.bar.plugin.rest.config
</Export-Package>
<Import-Package>*;resolution:=optional</Import-Package>
<Embed-Dependency>*;scope=compile|runtime; type=!pom; inline=true</Embed-Dependency>
<Embed-Transitive>false</Embed-Transitive>
</instructions>
I only embed logback-classic and logback-core in this bundle (this could be another story...). In other words, I only have these 2 dependencies declared in the module. I also tried to add databind in provided scope but it changes nothing.
I don't get it since I have exported all "com.fasterxml.jackson" packages and sub-packages. To do so, the Spring boot initialize the Felix framework with a custom configuration, with the config key org.osgi.framework.system.packages.extra containing all packages to export automatically according to
the documention.
When I log them we can see around 100 exported packages including these ones :
....
com.fasterxml.jackson.databind.deser.impl,
com.fasterxml.jackson.databind,
com.fasterxml.jackson.core.sym,
....
The module bundle using databind MANIFEST.MF :
Export-Package: com.foooooooo.baaaar.plugin.rest;uses:="com.foooooooo.d
atagen.api.plugins,com.foooooooo.baaaaar.api.plugins.properties,com.baa
aaaaar.datagen.api.plugins.web,com.foooooooo.baaaaar.plugin.rest.config
,com.foooooooo.baaaaar.plugin.rest.web,com.foooooooo.baaaaar.task,com.d
atanumia.baaaaar.task.config,com.foooooooo.baaaaar.task.environment,com
.foooooooo.baaaaar.task.template,org.springframework.http,org.springfra
mework.web.client";version="0.1.0.SNAPSHOT",com.foooooooo.baaaaar.plugi
n.rest.web;uses:="com.foooooooo.baaaaar.api.plugins,com.foooooooo.baaaa
ar.api.plugins.web";version="0.1.0.SNAPSHOT",com.foooooooo.baaaaar.plug
in.rest.config;uses:="com.foooooooo.baaaaar.task.config,com.fasterxml.j
ackson.annotation,com.fasterxml.jackson.databind.annotation,org.springf
ramework.http";version="0.1.0.SNAPSHOT"
Export-Service: com.foooooooo.baaaaar.plugin.RestTaskPlugin
Import-Package: com.foooooooo.baaaar.api.plugins;resolution:=optional,c
om.foooooooo.baaaaar.api.plugins.properties;resolution:=optional,com.da
tanumia.baaaaar.api.plugins.web;resolution:=optional,com.foooooooo.baaa
aar.task;resolution:=optional,com.foooooooo.baaaaar.task.config;resolut
ion:=optional,com.foooooooo.baaaaar.task.environment;resolution:=option
al,com.foooooooo.baaaaar.task.template;resolution:=optional,com.foooooo
al,com.foooooooo.baaaaar.task.template;resolution:=optional,com.foooooo
oo.baaaaar.tools.file;resolution:=optional,com.fasterxml.jackson.annota
tion;resolution:=optional;version="[2.13,3)",com.fasterxml.jackson.data
bind;resolution:=optional;version="[2.13,3)",com.fasterxml.jackson.data
bind.annotation;resolution:=optional;version="[2.13,3)",com.jayway.json
path;resolution:=optional;version="[2.7,3)",java.io;resolution:=optiona
l,java.lang;resolution:=optional,java.lang.annotation;resolution:=optio
nal,java.lang.invoke;resolution:=optional,java.lang.management;resoluti
on:=optional,java.lang.reflect;resolution:=optional,java.net;resolution
:=optional,java.nio.channels;resolution:=optional,java.nio.charset;reso
lution:=optional,java.nio.file;resolution:=optional,java.security;resol
ution:=optional,java.security.cert;resolution:=optional,java.text;resol
ution:=optional,java.util;resolution:=optional,java.util.concurrent;res
olution:=optional,java.util.concurrent.atomic;resolution:=optional,java
.util.concurrent.locks;resolution:=optional,java.util.function;resoluti
on:=optional,java.util.logging;resolution:=optional,java.util.regex;res
olution:=optional,java.util.stream;resolution:=optional,java.util.zip;r
esolution:=optional,javax.mail;resolution:=optional,javax.mail.internet
;resolution:=optional,javax.management;resolution:=optional,javax.namin
g;resolution:=optional,javax.net;resolution:=optional,javax.net.ssl;res
olution:=optional,javax.servlet;resolution:=optional,javax.servlet.http
;resolution:=optional,javax.xml.namespace;resolution:=optional,javax.xm
l.parsers;resolution:=optional,javax.xml.stream;resolution:=optional,ja
vax.xml.stream.events;resolution:=optional,lombok;resolution:=optional,
org.apache.commons.lang3;resolution:=optional;version="[3.12,4)",org.co
dehaus.commons.compiler;resolution:=optional,org.codehaus.janino;resolu
tion:=optional,org.springframework.http;resolution:=optional,org.spring
framework.http.converter.json;resolution:=optional,org.springframework.
util;resolution:=optional,org.springframework.web.client;resolution:=op
tional,org.springframework.web.util;resolution:=optional,org.xml.sax;re
solution:=optional,org.xml.sax.helpers;resolution:=optional,sun.reflect
;resolution:=optional
It is difficult to see but we have the expected import-package:
com.fasterxml.jackson.databind;resolution:=optional;version="[2.13,3)"
I do not have any other loaded bundle excepted the framework bundles:
org.apache.felix.fileinstall-3.7.4.jar
org.apache.felix.scr-2.2.0.jar
org.osgi.service.cm-1.6.1.jar
org.osgi.util.function-1.2.0.jar
org.osgi.util.promise-1.2.0.jar
I spend days to understand what is happening but each new tests bring me new unresolved challenges.
I can have a working project if I change strategy and embed everything, but then in some particular situations I have a linkage problem since I use the same lib in different class loaders.
How to use import/export package system correctly ?
Any idea about the problem here ?
UPDATE: the export-import seems to work with other packages. For example I can use spring-web in provided scope, it is not in the final bundle module, and I can use some methods of spring-web, exported from main app. The problem seems to be the Jackson Databind or something in related to it.
UPDATE
If I use bnd-maven-plugin I do not have the problem, I will post it unless someone give a better answer.

Related

Getting error log while previewing report from Jasper [duplicate]

I am getting a NoClassDefFoundError when I run my Java application. What is typically the cause of this?
While it's possible that this is due to a classpath mismatch between compile-time and run-time, it's not necessarily true.
It is important to keep two or three different exceptions straight in our head in this case:
java.lang.ClassNotFoundException This exception indicates that the class was not found on the classpath. This indicates that we were trying to load the class definition, and the class did not exist on the classpath.
java.lang.NoClassDefFoundError This exception indicates that the JVM looked in its internal class definition data structure for the definition of a class and did not find it. This is different than saying that it could not be loaded from the classpath. Usually this indicates that we previously attempted to load a class from the classpath, but it failed for some reason - now we're trying to use the class again (and thus need to load it, since it failed last time), but we're not even going to try to load it, because we failed loading it earlier (and reasonably suspect that we would fail again). The earlier failure could be a ClassNotFoundException or an ExceptionInInitializerError (indicating a failure in the static initialization block) or any number of other problems. The point is, a NoClassDefFoundError is not necessarily a classpath problem.
This is caused when there is a class file that your code depends on and it is present at compile time but not found at runtime. Look for differences in your build time and runtime classpaths.
Here is the code to illustrate java.lang.NoClassDefFoundError. Please see Jared's answer for detailed explanation.
NoClassDefFoundErrorDemo.java
public class NoClassDefFoundErrorDemo {
public static void main(String[] args) {
try {
// The following line would throw ExceptionInInitializerError
SimpleCalculator calculator1 = new SimpleCalculator();
} catch (Throwable t) {
System.out.println(t);
}
// The following line would cause NoClassDefFoundError
SimpleCalculator calculator2 = new SimpleCalculator();
}
}
SimpleCalculator.java
public class SimpleCalculator {
static int undefined = 1 / 0;
}
NoClassDefFoundError In Java
Definition:
Java Virtual Machine is not able to find a particular class at runtime which was available at compile time.
If a class was present during compile time but not available in java classpath during runtime.
Examples:
The class is not in Classpath, there is no sure shot way of knowing it but many times you can just have a look to print System.getproperty("java.classpath") and it will print the classpath from there you can at least get an idea of your actual runtime classpath.
A simple example of NoClassDefFoundError is class belongs to a missing JAR file or JAR was not added into classpath or sometimes jar's name has been changed by someone like in my case one of my colleagues has changed tibco.jar into tibco_v3.jar and the program is failing with java.lang.NoClassDefFoundError and I were wondering what's wrong.
Just try to run with explicitly -classpath option with the classpath you think will work and if it's working then it's a sure short sign that someone is overriding java classpath.
Permission issue on JAR file can also cause NoClassDefFoundError in Java.
Typo on XML Configuration can also cause NoClassDefFoundError in Java.
when your compiled class which is defined in a package, doesn’t present in the same package while loading like in the case of JApplet it will throw NoClassDefFoundError in Java.
Possible Solutions:
The class is not available in Java Classpath.
If you are working in J2EE environment than the visibility of Class among multiple Classloader can also cause java.lang.NoClassDefFoundError, see examples and scenario section for detailed discussion.
Check for java.lang.ExceptionInInitializerError in your log file. NoClassDefFoundError due to the failure of static initialization is quite common.
Because NoClassDefFoundError is a subclass of java.lang.LinkageError it can also come if one of it dependency like native library may not available.
Any start-up script is overriding Classpath environment variable.
You might be running your program using jar command and class was not defined in manifest file's ClassPath attribute.
Resources:
3 ways to solve NoClassDefFoundError
java.lang.NoClassDefFoundError Problem patterns
I have found that sometimes I get a NoClassDefFound error when code is compiled with an incompatible version of the class found at runtime. The specific instance I recall is with the apache axis library. There were actually 2 versions on my runtime classpath and it was picking up the out of date and incompatible version and not the correct one, causing a NoClassDefFound error. This was in a command line app where I was using a command similar to this.
set classpath=%classpath%;axis.jar
I was able to get it to pick up the proper version by using:
set classpath=axis.jar;%classpath%;
One interesting case in which you might see a lot of NoClassDefFoundErrors is when you:
throw a RuntimeException in the static block of your class Example
Intercept it (or if it just doesn't matter like it is thrown in a test case)
Try to create an instance of this class Example
static class Example {
static {
thisThrowsRuntimeException();
}
}
static class OuterClazz {
OuterClazz() {
try {
new Example();
} catch (Throwable ignored) { //simulating catching RuntimeException from static block
// DO NOT DO THIS IN PRODUCTION CODE, THIS IS JUST AN EXAMPLE in StackOverflow
}
new Example(); //this throws NoClassDefFoundError
}
}
NoClassDefError will be thrown accompanied with ExceptionInInitializerError from the static block RuntimeException.
This is especially important case when you see NoClassDefFoundErrors in your UNIT TESTS.
In a way you're "sharing" the static block execution between tests, but the initial ExceptionInInitializerError will be just in one test case. The first one that uses the problematic Example class. Other test cases that use the Example class will just throw NoClassDefFoundErrors.
This is the best solution I found so far.
Suppose we have a package called org.mypackage containing the classes:
HelloWorld (main class)
SupportClass
UtilClass
and the files defining this package are stored physically under the directory D:\myprogram (on Windows) or /home/user/myprogram (on Linux).
The file structure will look like this:
When we invoke Java, we specify the name of the application to run: org.mypackage.HelloWorld. However we must also tell Java where to look for the files and directories defining our package. So to launch the program, we have to use the following command:
I was using Spring Framework with Maven and solved this error in my project.
There was a runtime error in the class. I was reading a property as integer, but when it read the value from the property file, its value was double.
Spring did not give me a full stack trace of on which line the runtime failed.
It simply said NoClassDefFoundError. But when I executed it as a native Java application (taking it out of MVC), it gave ExceptionInInitializerError which was the true cause and which is how I traced the error.
#xli's answer gave me insight into what may be wrong in my code.
I get NoClassFoundError when classes loaded by the runtime class loader cannot access classes already loaded by the java rootloader. Because the different class loaders are in different security domains (according to java) the jvm won't allow classes already loaded by the rootloader to be resolved in the runtime loader address space.
Run your program with 'java -javaagent:tracer.jar [YOUR java ARGS]'
It produces output showing the loaded class, and the loader env that loaded the class. It's very helpful tracing why a class cannot be resolved.
// ClassLoaderTracer.java
// From: https://blogs.oracle.com/sundararajan/entry/tracing_class_loading_1_5
import java.lang.instrument.*;
import java.security.*;
// manifest.mf
// Premain-Class: ClassLoadTracer
// jar -cvfm tracer.jar manifest.mf ClassLoaderTracer.class
// java -javaagent:tracer.jar [...]
public class ClassLoadTracer
{
public static void premain(String agentArgs, Instrumentation inst)
{
final java.io.PrintStream out = System.out;
inst.addTransformer(new ClassFileTransformer() {
public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
String pd = (null == protectionDomain) ? "null" : protectionDomain.getCodeSource().toString();
out.println(className + " loaded by " + loader + " at " + new java.util.Date() + " in " + pd);
// dump stack trace of the thread loading class
Thread.dumpStack();
// we just want the original .class bytes to be loaded!
// we are not instrumenting it...
return null;
}
});
}
}
The technique below helped me many times:
System.out.println(TheNoDefFoundClass.class.getProtectionDomain().getCodeSource().getLocation());
where the TheNoDefFoundClass is the class that might be "lost" due to a preference for an older version of the same library used by your program. This most frequently happens with the cases, when the client software is being deployed into a dominant container, armed with its own classloaders and tons of ancient versions of most popular libs.
Java ClassNotFoundException vs NoClassDefFoundError
[ClassLoader]
Static vs Dynamic class loading
Static(Implicit) class loading - result of reference, instantiation, or inheritance.
MyClass myClass = new MyClass();
Dynamic(Explicit) class loading is result of Class.forName(), loadClass(), findSystemClass()
MyClass myClass = (MyClass) Class.forName("MyClass").newInstance();
Every class has a ClassLoader which uses loadClass(String name); that is why
explicit class loader uses implicit class loader
NoClassDefFoundError is a part of explicit class loader. It is Error to guarantee that during compilation this class was presented but now (in run time) it is absent.
ClassNotFoundException is a part of implicit class loader. It is Exception to be elastic with scenarios where additionally it can be used - for example reflection.
In case you have generated-code (EMF, etc.) there can be too many static initialisers which consume all stack space.
See Stack Overflow question How to increase the Java stack size?.
Two different checkout copies of the same project
In my case, the problem was Eclipse's inability to differentiate between two different copies of the same project. I have one locked on trunk (SVN version control) and the other one working in one branch at a time. I tried out one change in the working copy as a JUnit test case, which included extracting a private inner class to be a public class on its own and while it was working, I open the other copy of the project to look around at some other part of the code that needed changes. At some point, the NoClassDefFoundError popped up complaining that the private inner class was not there; double-clicking in the stack trace brought me to the source file in the wrong project copy.
Closing the trunk copy of the project and running the test case again got rid of the problem.
I fixed my problem by disabling the preDexLibraries for all modules:
dexOptions {
preDexLibraries false
...
I got this error when I add Maven dependency of another module to my project, the issue was finally solved by add -Xss2m to my program's JVM option(It's one megabyte by default since JDK5.0). It's believed the program does not have enough stack to load class.
In my case I was getting this error due to a mismatch in the JDK versions. When I tried to run the application from Intelij it wasn't working but then running it from the command line worked. This is because Intelij was attempting to run it with the Java 11 JDK that was setup but on the command line it was running with the Java 8 JDK. After switching that setting under File > Project Structure > Project Settings > Project SDK, it worked for me.
Update [https://www.infoq.com/articles/single-file-execution-java11/]:
In Java SE 11, you get the option to launch a single source code file
directly, without intermediate compilation. Just for your convenience,
so that newbies like you don't have to run javac + java (of course,
leaving them confused why that is).
NoClassDefFoundError can also occur when a static initializer tries to load a resource bundle that is not available in runtime, for example a properties file that the affected class tries to load from the META-INF directory, but isn’t there. If you don’t catch NoClassDefFoundError, sometimes you won’t be able to see the full stack trace; to overcome this you can temporarily use a catch clause for Throwable:
try {
// Statement(s) that cause(s) the affected class to be loaded
} catch (Throwable t) {
Logger.getLogger("<logger-name>").info("Loading my class went wrong", t);
}
I was getting NoClassDefFoundError while trying to deploy application on Tomcat/JBOSS servers. I played with different dependencies to resolve the issue, but kept getting the same error. Marked all javax.* dependencies as provided in pom.xml, And war literally had no Dependency in it. Still the issue kept popping up.
Finally realized that src/main/webapps/WEB-INF/classes had classes folder which was getting copied into my war, so instead of compiled classes, this classes were getting copied, hence no dependency change was resolving the issue.
Hence be careful if any previously compiled data is getting copied, After deleting classes folder and fresh compilation, It worked!..
If someone comes here because of java.lang.NoClassDefFoundError: org/apache/log4j/Logger error, in my case it was produced because I used log4j 2 (but I didn't add all the files that come with it), and some dependency library used log4j 1. The solution was to add the Log4j 1.x bridge: the jar log4j-1.2-api-<version>.jar which comes with log4j 2. More info in the log4j 2 migration.
This error can be caused by unchecked Java version requirements.
In my case I was able to resolve this error, while building a high-profile open-source project, by switching from Java 9 to Java 8 using SDKMAN!.
sdk list java
sdk install java 8u152-zulu
sdk use java 8u152-zulu
Then doing a clean install as described below.
When using Maven as your build tool, it is sometimes helpful -- and usually gratifying, to do a clean 'install' build with testing disabled.
mvn clean install -DskipTests
Now that everything has been built and installed, you can go ahead and run the tests.
mvn test
I got NoClassDefFound errors when I didn't export a class on the "Order and Export" tab in the Java Build Path of my project. Make sure to put a checkmark in the "Order and Export" tab of any dependencies you add to the project's build path. See Eclipse warning: XXXXXXXXXXX.jar will not be exported or published. Runtime ClassNotFoundExceptions may result.
It could also be because you copy the code file from an IDE with a certain package name and you want to try to run it using terminal. You will have to remove the package name from the code first.
This happens to me.
Everyone talks here about some Java configuration stuff, JVM problems etc., in my case the error was not related to these topics at all and had a very trivial and easy to solve reason: I had a wrong annotation at my endpoint in my Controller (Spring Boot application).
I have had an interesting issue wiht NoClassDefFoundError in JavaEE working with Liberty server. I was using IMS resource adapters and my server.xml had already resource adapter for imsudbJXA.rar.
When I added new adapter for imsudbXA.rar, I would start getting this error for instance objects for DLIException, IMSConnectionSpec or SQLInteractionSpec.
I could not figure why but I resolved it by creating new server.xml for my work using only imsudbXA.rar. I am sure using multiple resource adapters in server.xml is fine, I just had no time to look into that.
I had this error but could not figure out the solution based on this thread but solved it myself.
For my problem I was compiling this code:
package valentines;
import java.math.BigInteger;
import java.util.ArrayList;
public class StudentSolver {
public static ArrayList<Boolean> solve(ArrayList<ArrayList<BigInteger>> problems) {
//DOING WORK HERE
}
public static void main(String[] args){
//TESTING SOLVE FUNCTION
}
}
I was then compiling this code in a folder structure that was like /ProjectName/valentines
Compiling it worked fine but trying to execute: java StudentSolver
I was getting the NoClassDefError.
To fix this I simply removed: package valentines;
I'm not very well versed in java packages and such but this how I fixed my error so sorry if this was already answered by someone else but I couldn't interpret it to my problem.
My solution to this was to "avail" the classpath contents for the specific classes that were missing. In my case, I had 2 dependencies, and though I was able to compile successfully using javac ..., I was not able to run the resulting class file using java ..., because a Dynamic class in the BouncyCastle jar could not be loaded at runtime.
javac --classpath "ext/commons-io-2.11.0;ext/bc-fips-1.0.2.3" hello.java
So at compile time and by runtime, the JVM is aware of where to fetch Apache Commons and BouncyCastle dependencies, however, when running this, I got
Error: Unable to initialize main class hello
Caused by: java.lang.NoClassDefFoundError:
org/bouncycastle/jcajce/provider/BouncyCastleFipsProvider
And I therefore manually created a new folder named ext at the same location, as per the classpath, where I then placed the BouncyCastle jar to ensure it would be found at runtime. You can place the jar relative to the class file or the jar file as long as the resulting manifest has the location of the jar specified. Note I only need to avail the one jar containing the missing class file.
Java was unable to find the class A in runtime.
Class A was in maven project ArtClient from a different workspace.
So I imported ArtClient to my Eclipse project.
Two of my projects was using ArtClient as dependency.
I changed library reference to project reference for these ones (Build Path -> Configure Build Path).
And the problem gone away.
I had the same problem, and I was stock for many hours.
I found the solution. In my case, there was the static method defined due to that. The JVM can not create the another object of that class.
For example,
private static HttpHost proxy = new HttpHost(proxyHost, Integer.valueOf(proxyPort), "http");
I got this message after removing two files from the SRC library, and when I brought them back I kept seeing this error message.
My solution was: Restart Eclipse. Since then I haven't seen this message again :-)

GWT module xml source element to specify single class

I have a GWT application (FooGwtApp) and a library module (FooLib) used as a dependency in FooGwtApp. The package structure of FooLib looks like this:
packageFoo.ImportantClass
packageFoo.UnimportantClass
packageBar.OtherClass
I want ImportantClass (and only ImportantClass) to be compiled to JS by the GWT compiler. Moving ImportantClass to another package is not an option.
I created ImportantClass.gwt.xml within packageFoo with the following content:
<module>
<inherits name="com.google.gwt.user.User"/>
<source path="" includes="**/ImportantClass*"/>
</module>
Next I put an inherited reference to the ImportantClass module definition in FooGwtApp.gwt.xml (this seems to work: the IDE recognizes it, and is able to parse the reference to ImportantClass.gwt.xml).
Now If I put references to ImportantClass into FooGwtApp's client code, the GWT compiler fails, because it does not find ImportantClass on the source path:
No source code is available for type packageFoo.ImportantClass; did you forget to inherit a required module?
I likely messed up sommething in the source path / includes attribute in ImportantClass.gwt.xml - either defining the current package as root package with path="" is not a valid notation or something's wrong with the includes attribute. Or both. Or neither.
Can you give me a clue about where it all went wrong?
It turns out the problem was not in ImportantClass.gwt.xml, but in other Maven related stuff:
ImportantClass.gwt.xml should be placed under src/main/resources/packageFoo, not src/main/java/packageFoo, otherwise it won't be packaged into the binary jar.
GWT compiler compiles from Java source to Javascript source. This means we don't just need ImportantClass.class in FooLib.jar, but also its source. Best solution for this is to use maven-source-plugin in FooLib's pom.xml and also to import the FooLib dependency into FooGwtApp with sources classifier.
On the latter topic, see the following SO answers:
Maven: Distribute source code with with jar-with-dependencies
How to properly include Java sources in Maven?
After fixing the above problems, the source path declaration present in the question works.

OSGI: How to update a 'consumer' bundle

I have been trying to understand a strange OSGI behavior. Hoping someone can shed some light on it. Here is my setup
1) Using eclipse\plugins\org.eclipse.osgi_3.7.0.v20110613.jar
2) I have a Bundle that exports a service (HelloworldService)
It registers the service in the activator as such
public void start(BundleContext context) throws Exception {
IHelloService helloService = new HelloServiceImpl();
helloServiceRegistration =context.registerService(
IHelloService.class.getName(), helloService, null
);
}
3) I have a 'consumer' bundle that uses the service via a ServiceTracker
ServiceReference externalServiceReference = Activator.getContext().getServiceReference(IHelloService.class.getName());
IHelloService externalService = (IHelloService) Activator.getContext().getService(externalServiceReference);
Now when I deploy both these jars to OSGI (helloworld.jar and helloworldservice.jar); it works fine. I am able to get a 'IHelloService' impl object and make calls on it. I can start/stop the bundles and when they come back; it works just fine
The problem happens when I 'uninstall' and then 'install' the HelloWorldservice bundle.
In that case; the 'Helloworld' consumer externalServiceReference is NULL.
If I view the bundle info; I see this
osgi> bundle 1
mypackage.helloworld_1.0.0.qualifier [1]
Id=1, Status=RESOLVED Data Root=C:\Users\\dev\eclipse\plugins\configuration\org.eclipse.obundles\1\data
No registered services.
No services in use.
No exported packages
Imported packages
mypackage.helloworldservice; version="0.0.0" **stale**
org.osgi.framework; version="1.6.0"
org.osgi.util.tracker; version="1.5.0"
No fragment bundles
Named class space
mypackage.helloworld; bundle-version="1.0.0.qualifier"[provided]
No required bundles
Notice that its 'imported packages' has GONE STALE. Here is the line in question
Imported packages
mypackage.helloworldservice; version="0.0.0"<stale>
Now I can fix this by issuing an 'update' command from the console.
Here is my question
1) How do I programatically do this from within my 'consumer' bundle..
2) If I am on a production system and I deploy a new 'copy' of the helloworlservice.jar (replacing the existing version); Do I have to update all its users.. I thought the ServiceTracker would give me the service on the fly
Thanks
The consumer bundle imports the mypackage.helloworldservice package from the service jar. When you uninstall the service jar, the consumer jar is still wired to the now stale package from the uninstalled service jar. When you install a new service jar, it exports a new "copy" of the mypackage.helloworldservice package (I suspect the service jar does not also import the mypackage.helloworldservice package). So you need to refresh the consumer jar to get it to wire to the new mypackage.helloworldservice package.

How to include predefined set of netbeans platform modules in maven project?

I am working on maven netbeans platform project consisting of several modules. I need to depend on some modules (say java.source module), but when I try to run the application, it reports, that required modules are not installed. And event despite I have dependency on java.source declared in my pom.xml
I think, that I have to tell maven somehow, to install (and turn on) these modules in the final assembled application before my module is loaded.
How could I do something like this?
UPDATE:
When I try to create complete netbeans application project from maven artifact and add Java Source API as a dependency into pom.xml... when I run the application, window with following message appears:
Warning - could not install some modules: Editor Library 2 - None of the modules providing the capability org.netbeans.modules.editor.actions could be installed. Editor Indentation for Projects - The module named org.netbeans.modules.editor.settings.storage/1 was needed and not found. Editor Indentation for Projects - The module named org.netbeans.modules.options.editor/1 was needed and not found. Project UI API - No module providing the capability org.netbeans.modules.project.uiapi.ActionsFactory could be found. Project UI API - No module providing the capability org.netbeans.modules.project.uiapi.OpenProjectsTrampoline could be found. Project UI API - No module providing the capability org.netbeans.modules.project.uiapi.ProjectChooserFactory could be found. Editor Error Stripe Impl - The module named org.netbeans.modules.editor.errorstripe.api/1 was needed and not found. Java Source - The module named org.netbeans.libs.javacimpl/1 was needed and not found. Java Source - The module named org.netbeans.modules.editor.indent.project/0-1 was needed and not found. Java Source - The module named org.netbeans.modules.java.preprocessorbridge was needed and not found. Java Source - The module named org.netbeans.modules.options.editor/1 was needed and not found. Java Source - The module named org.netbeans.modules.parsing.api/1 was needed and not found. Editor Settings - No module providing the capability org.netbeans.api.editor.settings.implementation could be found. Diff - The module named org.netbeans.modules.options.editor/1 was needed and not found. 11 further modules could not be installed due to the above problems.
The error-message "Module dependency has friend dependency [...] but is not listed as friend" means that you need to specify an implementation version of org.netbeans.modules.options.editor.
You can achieve this by editing src/main/nbm/module.xml to contain the following entry (I didn't use the actually needed values here. Make sure to find out which values to enter for id and explicitValue to satisfy the dependencies (You can find explanations / instructions in the article linked below):
<dependencies>
<dependency>
<id>org.netbeans.modules:org-netbeans-modules-editor</id>
<type>impl</type>
<explicitValue>org.netbeans.modules.editor/1 = 201107282000</explicitValue>
</dependency>
</dependencies>
I'm pretty sure that the following article will explain some issues and help you find out the needed values for id and explicitValue (language is english, author is me):
http://blog.macrominds.de/2011/08/open-favorites-per-default-in-netbeans-rich-client-platform-maven-standalone-application/
I'm currently having related problems with my application, so I might come back with a more concrete solution in a while.
the easiest way is to grab a class that its complaining about, say "org.netbeans.modules.editor.actions" and go to the Add Dependencies and plug it into the Query field.
From there you should be able to tell which module you will need to include

ATG taglibs on OSGI problems

We're currently creating an app that needs ATG taglibs on SLING/OSGI, we have created a bundle with these taglibs and uploaded it, of course these taglibs call ATG classes, so we are including them in the bootdelegation, using sling.properties file.
sling.bootdelegation.simple=atg.nucleus
sling.bootdelegation.class.atg.nucleus.Nucleus=atg.appassembly, \
atg.appassembly.ant, \
atg.appassembly.progress, \
atg.appassembly.util, \
...ETC...
First we got this error:
org.apache.sling.api.scripting.ScriptEvaluationException: atg/taglib/dspjsp/ImportBeanTag
at org.apache.sling.scripting.core.impl.DefaultSlingScript.call(DefaultSlingScript.java:163)
at org.apache.sling.scripting.core.impl.DefaultSlingScript.eval(DefaultSlingScript.java:107)
at org.apache.sling.scripting.core.impl.DefaultSlingScript.service(DefaultSlingScript.java:226)
at org.apache.sling.engine.impl.request.RequestData.service(RequestData.java:465)
....
....
Caused by: java.lang.NoClassDefFoundError: atg/taglib/dspjsp/ImportBeanTag
at org.apache.jsp.apps.mygeometrixx.components.contenpage.center_jsp._jspx_meth_dsp_005fimportbean_005f0(center_jsp.java:177)
at org.apache.jsp.apps.mygeometrixx.components.contenpage.center_jsp._jspService(center_jsp.java:154)
at org.apache.sling.scripting.jsp.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
at
So we added atg.taglib.dspjsp to the packages to be added in bootdelegation sling.properties file.
Then we got this error:
org.apache.sling.api.scripting.ScriptEvaluationException: atg.taglib.dspjsp.ImportBeanTag
at org.apache.sling.scripting.core.impl.DefaultSlingScript.call(DefaultSlingScript.java:163)
at org.apache.sling.scripting.core.impl.DefaultSlingScript.eval(DefaultSlingScript.java:107)
at org.apache.sling.scripting.core.impl.DefaultSlingScript.service(DefaultSlingScript.java:226)
at org.apache.sling.engine.impl.request.RequestData.service(RequestData.java:465)
...
Caused by: java.lang.ClassCastException: atg.taglib.dspjsp.ImportBeanTag
at org.apache.sling.scripting.jsp.jasper.runtime.TagHandlerPool.get(TagHandlerPool.java:125)
at org.apache.jsp.apps.mygeometrixx.components.contenpage.center_jsp._jspx_meth_dsp_005fimportbean_005f0(center_jsp.java:177)
at org.apache.jsp.apps.mygeometrixx.components.contenpage.center_jsp._jspService(center_jsp.java:154)
at org.apache.sling.scripting.jsp.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
All this is running on JBOSS.
Is there a way to avoid this class conflict that is causing the cast exception?
The class cast exception is usually a sign that that class is being made available in two different places (in your case probably via bootdelegation and maybe via a bundle that exports this class). That's what I would investigate first.
Also, to make things more explicit, I would in general advise you to not use boot delegation but instead export these packages explicitly through the system bundle. That way at least you can better debug where classes come from and how things are "wired" by the OSGi resolver.
When loading the ATG tag libraries from outside of the OSGi framework you also have to make sure to provide the JSP API from outside of the framework. By default Sling embeds the JSP API (in the JSP Scripting Bundle).
There are various ways to expose the JSP API into the framework. One is to add them to the system packages in the sling.properties file:
sling.system.packages.atg_jsp = javax.servlet.jsp;javax.servlet.jsp.el; \
javax.servlet.jsp.resources;javax.servlet.jsp.tagext;version=2.1.0