wildfly-8.1.0.Final Failed instantiate InitialContextFactory - jboss

im getting following Error
**ERROR:**
2014-10-07 16:33:46,692 ERROR [stderr] (default task-1) javax.naming.NamingException:
JBAS011843: **Failed instantiate** **InitialContextFactory
org.jboss.naming.remote.client.InitialContextFactory** from classloader
ModuleClassLoader for Module "deployment.wildfly8.1.ear.wildfly8.1-war.war:main"
from Service Module Loader [Root exception is java.lang.ClassNotFoundException:
org.jboss.naming.remote.client.InitialContextFactory from [Module
"deployment.wildfly8.1.ear.wildfly8.1-war.war:main" from Service Module Loader]]
Code:
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
env.put(Context.PROVIDER_URL, "127.0.0.1");
//OR env.put(Context.PROVIDER_URL, "http-remoting://127.0.0.1");
env.put(Context.SECURITY_PRINCIPAL, "admin");
env.put(Context.SECURITY_CREDENTIALS, "password");
context = new InitialContext(env);

Try adding a jboss-deployment-structure.xml to the META-INF of the top level .ear file. In the jboss-deployment-structure.xml add a dependency for org.jboss.remote-naming and org.jboss.ejb-client.
Here's some documentation on jboss-deployment-strucure.xml: Class Loading in WildFly
Other useful links:
EJB invocations from a remote server instance
ejb-multi-server: EJB Communication Across Servers

You'll need to include in your war/WEB-INF/lib directory all dependencies of a remote client:
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-jms-client-bom</artifactId>
<version>${version.wildfly}</version>
<type>pom</type>
</dependency>

Related

Exposing SOAP service using apache Camel and WSDL

I have a WSDL file located under src\main\resources\wsdl\ folder and it is having multiple operations defined within it. My application is running on Weblogic 12C server. I'm trying to expose the SOAP web-service using Apache Cammel (version: 2.18.3) with Java DSL -
I have written below code under configuration method of my RouteBuilder class -
CxfComponent cxfComponent = new CxfComponent(getContext());
CxfEndpoint serviceEndpoint = new CxfEndpoint("/soap/Manage_Order", cxfComponent);
serviceEndpoint.setAddress("http://<IP>:<PORT>/myproject/soap/ManageOrder_Details");
serviceEndpoint.setServiceClass(
"Fully qualified service interface name generated from WSDL file using maven with #WebService annotation");
serviceEndpoint.setEndpointName(<end point name defined in the service class with #WebEndpoint annotation>);
serviceEndpoint.setDataFormat(DataFormat.MESSAGE);
serviceEndpoint.setDefaultOperationName("manageOrder");
getContext().addEndpoint("myServiceEndPoint1", serviceEndpoint);
from("cxf:myServiceEndPoint1").log("Hi, I am here").end();
While I'm deploying the application, it is throwing below exception -
weblogic.application.ModuleException: java.lang.IllegalArgumentException: serviceClass must be specified
at weblogic.application.internal.ExtensibleModuleWrapper.start(ExtensibleModuleWrapper.java:140)
at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:124)
at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:233)
at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:228)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:45)
Truncated. see log file for complete stacktrace
Caused By: java.lang.IllegalArgumentException: serviceClass must be specified
at org.apache.camel.util.ObjectHelper.notNull(ObjectHelper.java:311)
at org.apache.camel.component.cxf.CxfEndpoint.createServerFactoryBean(CxfEndpoint.java:663)
at org.apache.camel.component.cxf.CxfConsumer.createServer(CxfConsumer.java:70)
at org.apache.camel.component.cxf.CxfConsumer.<init>(CxfConsumer.java:66)
at org.apache.camel.component.cxf.CxfEndpoint.createConsumer(CxfEndpoint.java:252)
Truncated. see log file for complete stacktrace
pom.xml
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-soap</artifactId>
<version>2.18.3</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-cxf</artifactId>
<version>2.18.3</version>
<!-- use the same version as your Camel core version -->
</dependency>
As the error says, you have not mentioned the service class and endpoint names.serviceEndpoint.setServiceClass("Fully qualified service interface name generated from WSDL file using maven with #WebService annotation");
serviceEndpoint.setEndpointName(<end point name defined in the service class with #WebEndpoint annotation>);
Step 1: Generate the service from your wsdl using wsdl2java command or your choice of IDE.
Step 2: Have that in your code classpath
Step 3: Mention the class name and endpoint names in the above piece of code

Spring MVC - Send email, Bean creation

I'm trying to set up my Spring MVC app to send email, but i think i'm doing something wrong in the configuration
In My AppConfig i instantiate the Bean:
#Bean
public JavaMailSender mailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setDefaultEncoding("UTF-8");
return mailSender;
}
Then in my application.properties I have:
mail.port= 465
mail.host= smtp.gmail.com
mail.username= username
mail.password= password
emailTo = info#beingsmart.it
emailSubject = ALERT - ePark Server
mail.smtp.auth = true
mail.smtp.starttls.enable = true
mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail.properties.mail.smtp.socketFactory.fallback = false
When I try to send the email i'm getting
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.mail.javamail.JavaMailSender]: Factory method 'mailSender' threw exception; nested exception is java.lang.NoClassDefFoundError: javax/mail/AuthenticationFailedException
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
... 49 more
Caused by: java.lang.NoClassDefFoundError: javax/mail/AuthenticationFailedException
at it.besmart.config.AppConfig.mailSender(AppConfig.java:128)
at it.besmart.config.AppConfig$$EnhancerBySpringCGLIB$$b2a09c0.CGLIB$mailSender$7(<generated>)
at it.besmart.config.AppConfig$$EnhancerBySpringCGLIB$$b2a09c0$$FastClassBySpringCGLIB$$dd65f050.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:318)
at it.besmart.config.AppConfig$$EnhancerBySpringCGLIB$$b2a09c0.mailSender(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
... 50 more
Caused by: java.lang.ClassNotFoundException: javax.mail.AuthenticationFailedException
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1285)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1119)
... 61 more
EDIT
I added javax mail to my pom
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.5.6</version>
</dependency>
Now I have a different exception when trying to send the email
java.lang.NoClassDefFoundError: com/sun/mail/util/MessageRemovedIOException
It looks like an authentication error, but i'm thinking that JavaMailSender does not takes the setting in my application.properties, could it be?
Thanks
It seems to be missing dependency rather than anything else. If using spring boot have dependency like:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
If you don't I suggest you look inside that POM and figure out what are the missing pieces.
In your particular case it seems you need:
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.5</version>
</dependency>
Generic advice:
ClassNotFoundException means class which you need is not on classpath. It's usually a missing dependency
Google to find which jar contains the missing class
Find the library it on maven central
Add to dependencies

Exception in thread "main" java.io.IOException: Cannot initialize Cluster

I am trying to run a simple Hadoop Map reduce program on eclipse in windows. Iam getting the following exception.
Exception in thread "main" java.io.IOException: Cannot initialize Cluster. Please check your configuration for mapreduce.framework.name and the correspond server addresses.
at org.apache.hadoop.mapreduce.Cluster.initialize(Cluster.java:121)
at org.apache.hadoop.mapreduce.Cluster.<init>(Cluster.java:83)
at org.apache.hadoop.mapreduce.Cluster.<init>(Cluster.java:76)
at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1188)
at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1184)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Unknown Source)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1548)
at org.apache.hadoop.mapreduce.Job.connect(Job.java:1183)
at org.apache.hadoop.mapreduce.Job.submit(Job.java:1212)
at org.apache.hadoop.mapreduce.Job.waitForCompletion(Job.java:1236)
at com.hadoop.mapreduce.WordCountDriverClass.main(WordCountDriverClass.java:41)
These are the jar files I have added in the project.
com.google.guava_1.6.0.jar
commons-configuration-1.7.jar
commons-lang-2.6.jar
commons-logging-1.1.3.jar
commons.collections-3.2.1.jar
guava-13.0.1.jar
hadoop-annotations-2.7.2.jar
hadoop-auth-2.6.0.jar
hadoop-common-2.3.0.jar
hadoop-common.jar
hadoop-mapreduce-client-core-2.0.2-alpha.jar
hadoop-mapreduce-client-core-2.7.2.jar
hadoop-mapreduce-client-jobclient-2.2.0.jar
hadoop-test-1.2.1.jar
log4j-1.2.17.jar
slf4j-api-1.7.7.jar
slf4j-simple-1.6.1.jar
I have added those jar files after checking the exception messages in the console. But I couldn't understand this exception.
Can anyone please help me fixing this.
This is my driver class.
Configuration conf = new Configuration();
// Creating a job
Job job = Job.getInstance(conf,"WordCountDriverClass");
job.setJarByClass(WordCountDriverClass.class);
job.setMapperClass(WordCountMapper.class);
job.setReducerClass(WordCountReducer.class);
job.setNumReduceTasks(2);
job.setInputFormatClass(KeyValueTextInputFormat.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path("inputfiles"));
FileOutputFormat.setOutputPath(job, new Path("outputfiles"));
job.waitForCompletion(true);
Looks like you are running the wordcount example, what it requires are 1.2.1 hadoop-core and 2.2.0 hadoop-common. If you use Maven instead, the config should be as simple as
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-core</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>2.2.0</version>
</dependency>

WFLYNAM0027 : ClassNotFoundException: org.jboss.naming.remote.client.InitialContextFactory

Enviornment- wildfly-9.0.2.Final, EJB 3.0
Following error occurred while trying to connect Test.java class(deployed as module at wildfly-9.0.2.Final#machine-A) to EJB whilch is deployed on jboss at machine-B(291.861.301.732).
17:02:46,666 ERROR [stderr] (default task-1) javax.naming.NamingException: WFLYNAM0027: Failed instantiate InitialContextFactory org.jboss.naming.remote.client.InitialContextFactory from classloader ModuleClassLoader for Module "deployment.test.ear.test.war:main" from Service Module Loader [Root exception is java.lang.ClassNotFoundException: org.jboss.naming.remote.client.InitialContextFactory from [Module "deployment.test.ear.test.war:main" from Service Module Loader]]
17:02:46,667 ERROR [stderr] (default task-1) at org.jboss.as.naming.InitialContext.getDefaultInitCtx(InitialContext.java:118)
17:02:46,667 ERROR [stderr] (default task-1) at org.jboss.as.naming.InitialContext.init(InitialContext.java:99)
17:02:46,670 ERROR [stderr] (default task-1) at javax.naming.ldap.InitialLdapContext.<init>(InitialLdapContext.java:154)
17:02:46,670 ERROR [stderr] (default task-1) at org.jboss.as.naming.InitialContext.<init>(InitialContext.java:89)
17:02:46,670 ERROR [stderr] (default task-1) at org.jboss.as.naming.InitialContextFactory.getInitialContext(InitialContextFactory.java:43)
17:02:46,687 ERROR [stderr] (default task-1) Caused by: java.lang.ClassNotFoundException: org.jboss.naming.remote.client.InitialContextFactory from [Module "deployment.test.ear.test.war:main" from Service Module Loader]
17:02:46,688 ERROR [stderr] (default task-1) at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:205)
17:02:46,688 ERROR [stderr] (default task-1) at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:455)
17:02:46,688 ERROR [stderr] (default task-1) at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:404)
17:02:46,688 ERROR [stderr] (default task-1) at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:385)
17:02:46,688 ERROR [stderr] (default task-1) at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:130)
Test.java class is present in testclient.jar & testclient.jar has been deplyed as a module using command
module add --name=testclient --resources=/Downloads/lib/test/client/testclient.jar --dependencies=javax.api
Test.java class
package com.testmodule.pojo;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
public class Test {
public void getDbConnection(){
try{
Properties jndiProps = new Properties();
jndiProps.put(Context.INITIAL_CONTEXT_FACTORY,"org.jboss.naming.remote.client.InitialContextFactory");
jndiProps.put(Context.PROVIDER_URL,"remote://291.861.301.732:4447");
jndiProps.put(Context.SECURITY_PRINCIPAL, "testuser");
jndiProps.put(Context.SECURITY_CREDENTIALS, "testpassword");
jndiProps.put("jboss.naming.client.ejb.context", true);
Context context = new InitialContext(jndiProps);
}
catch(Exception e){e.printStackTrace();}
}}
why this error has been occurred, For visiblity of 'org.jboss.naming.remote.client.InitialContextFactory' to testclient.jar, should i have to add more dependencies(currently only javax.api) while deploying testclient.jar as a module? or any other issue which is causing error? Class 'org.jboss.naming.remote.client.InitialContextFactory' is also present in $WILDFLY_HOME/bin/client/jboss-client.jar
Note - 291.861.301.732 is the remote system ip, on which ejb is deployed at jboss. ,This ejb is invoking from Test.java(remote client) using JNDI.
There is no jnp in wildfly-9.0.2.Final(which was in JBOSS 5.x), so i replaced property "org.jnp.interfaces.NamingContextFactory" to value org.jboss.naming.remote.client.InitialContextFactory". why still error is occurred?
Following has been added after receving comment 'Try putting jboss-client.jar in the runtime path, as part of WEB-INF/lib maybe' by 'Sampada Wagde'
I am not able to understand, In this scenarion test.jsp (present in test.ear-->test.war-->test.jsp) file is calling function getDbConnection of Test.java file. Test.java file is present in testclient.jar and this testclient.jar has been deployed as a module.
As per your suggestion, when i put 'jboss-client.jar' in test.ear-->test.war-->WEB-INF-->lib, problem was solved, now while accessing
application 'org.jboss.naming.remote.client.InitialContextFactory' ClassNotFound exception was not occurred...But my problem is that there are multiple war's files(Eg..test.war,test1.war,test2.war) and each war file is accessing Test.java file(present in testclient.jar), so i have to put 'jboss-client.jar' file in WEB-INF/lib of each war archive. which will be very complex for me, is there any other approach available? and secondly how this problem is solved by putting 'jboss-client.jar' into WEB-INF/lib direcory as 'org.jboss.naming.remote.client.InitialContextFactory' is present in testclient.jar(Not in test.ear-->test.war).
Following has been added after receving reply 'jboss-client.jar is required by the server at runtime...' by 'Sampada Wagde'
I also tried following steps
1. By putting 'jboss-deployment-structure.xml' in test.ear-->META-INF-->jboss-deployment-structure.xml
<?xml version="1.0"?>
<jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.1">
<deployment>
<dependencies>
<module name="testclient" export="true" />
<module name="jboss-client" export="true" />
</dependencies>
</deployment>
Deploying module name as
module add --name=jboss-client --resources=/Downloads/wildfly-9.0.2.Final/bin/client/jboss-client.jar
but still the following error occurred.
14:14:34,376 WARN [org.jboss.modules] (default task-1) Failed to define class org.jboss.naming.remote.client.InitialContextFactory in Module "jboss-client:main" from local module loader #707f7052 (finder: local module finder #11028347 (roots: /Downloads/wildfly-9.0.2.Final/modules,/Downloads/wildfly-9.0.2.Final/modules/system/layers/base)): java.lang.LinkageError: Failed to link org/jboss/naming/remote/client/InitialContextFactory (Module "jboss-client:main" from local module loader #707f7052 (finder: local module finder #11028347 (roots: /Downloads/wildfly-9.0.2.Final/modules,/Downloads/wildfly-9.0.2.Final/modules/system/layers/base)))
at org.jboss.modules.ModuleClassLoader.defineClass(ModuleClassLoader.java:437)
at org.jboss.modules.ModuleClassLoader.loadClassLocal(ModuleClassLoader.java:269)
at org.jboss.modules.ModuleClassLoader$1.loadClassLocal(ModuleClassLoader.java:77)
at org.jboss.modules.Module.loadModuleClass(Module.java:560)
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:197)
Caused by: java.lang.NoClassDefFoundError: javax/naming/spi/InitialContextFactory
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:760)
at org.jboss.modules.ModuleClassLoader.doDefineOrLoadClass(ModuleClassLoader.java:353)
at org.jboss.modules.ModuleClassLoader.defineClass(ModuleClassLoader.java:432)
Caused by: java.lang.ClassNotFoundException: javax.naming.spi.InitialContextFactory from [Module "jboss-client:main" from local module loader #707f7052 (finder: local module finder #11028347 (roots: /Downloads/wildfly-9.0.2.Final/modules,/Downloads/wildfly-9.0.2.Final/modules/system/layers/base))]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:205)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:455)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:404)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:385)
14:14:34,391 ERROR [io.undertow.request] (default task-1) UT005023: Exception handling request to /test/test.jsp: javax.servlet.ServletException: java.lang.LinkageError: Failed to link org/jboss/naming/remote/client/InitialContextFactory (Module "jboss-client:main" from local module loader #707f7052 (finder: local module finder #11028347 (roots: /Downloads/wildfly-9.0.2.Final/modules,/Downloads/wildfly-9.0.2.Final/modules/system/layers/base)))
at org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:848)
at org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:777)
at org.apache.jsp.test_jsp._jspService(test_jsp.java:85)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:69)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
Caused by: java.lang.LinkageError: Failed to link org/jboss/naming/remote/client/InitialContextFactory (Module "jboss-client:main" from local module loader #707f7052 (finder: local module finder #11028347 (roots: /Downloads/wildfly-9.0.2.Final/modules,/Downloads/wildfly-9.0.2.Final/modules/system/layers/base)))
at org.jboss.modules.ModuleClassLoader.defineClass(ModuleClassLoader.java:437)
at org.jboss.modules.ModuleClassLoader.loadClassLocal(ModuleClassLoader.java:269)
at org.jboss.modules.ModuleClassLoader$1.loadClassLocal(ModuleClassLoader.java:77)
at org.jboss.modules.Module.loadModuleClass(Module.java:560)
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:197)
Caused by: java.lang.NoClassDefFoundError: javax/naming/spi/InitialContextFactory
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:760)
at org.jboss.modules.ModuleClassLoader.doDefineOrLoadClass(ModuleClassLoader.java:353)
at org.jboss.modules.ModuleClassLoader.defineClass(ModuleClassLoader.java:432)
Caused by: java.lang.ClassNotFoundException: javax.naming.spi.InitialContextFactory from [Module "jboss-client:main" from local module loader #707f7052 (finder: local module finder #11028347 (roots: /Downloads/wildfly-9.0.2.Final/modules,/Downloads/wildfly-9.0.2.Final/modules/system/layers/base))]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:205)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:455)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:404)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:385)
jboss-client.jar is required by the server at runtime. There are several ways of providing jars to a JBoss server -
include jars in MANIFEST.MF (this is generally used for your own application jars)
include jars in WEB-INF/lib - if the jar is specific to the given web project or WAR
include jars in a module class loader and provide it to the web project via jboss-deploymet-structure.xml . This is done when there are multiple WARS and some of them (not all) need the jars.
include jars in a module class loader and provide it to the server via global modules in standalone.xml . This is done when the jars are being referenced by all applications deployed on the server.
For details on modules in JBoss, please refer to this link -
https://docs.jboss.org/author/display/AS7/Class+Loading+in+AS7
As to your question on how putting the jboss-client.jar in a WAR instead of testclient.jar is resolving the issue, the answer is the same - this is how class loading works.
You need to make your own module depend on a module that contains not only the jboss-client jar, but also all the dependencies of jboss-client, this might just be other modules or possibly other jars too. The first class it's moaning about being missing is javax/naming/spi/InitialContextFactory so edit the module.xml for the jboss-client module to depend on javax.api

Using #Resource injection for Mongo db, inside Web Bundle inside OSGI, under Liberty Profile

I want to inject Mongo database (com.mongodb.DB) into OSGI Web Bundle Project, using #Resource.
The application is to deployed to WebSphere Liberty Profile V8.5.5.1.
Is this possible to do it?
I got an error message
"....The annotations could not be obtained because of the exception : java.lang.NoClassDefFoundError"
However, I can inject Mongo database into WAR, using #Resource, running on WebSphere Liberty Profile, if not using OSGI.
Below is lookup return null.
public static final DB getMongoDB() throws NamingException {
InitialContext ic = new InitialContext();
DB lookup = (DB) ic.lookup("java:comp/env/mongo/testdb");
return lookup;
}
The web.xml is
<resource-env-ref>
<resource-env-ref-name>mongo/testdb</resource-env-ref-name>
<resource-env-ref-type>com.mongodb.DB</resource-env-ref-type>
</resource-env-ref>
The server.xml is
<!-- Enable features -->
<featureManager>
<feature>jsp-2.2</feature>
<feature>localConnector-1.0</feature>
<feature>jaxrs-1.1</feature>
<feature>wab-1.0</feature>
<feature>ejbLite-3.1</feature>
<feature>jpa-2.0</feature>
<feature>jdbc-4.0</feature>
<feature>cdi-1.0</feature>
<feature>blueprint-1.0</feature>
<feature>jndi-1.0</feature>
<feature>servlet-3.0</feature>
<feature>json-1.0</feature>
<feature>mongodb-2.0</feature>
</featureManager>
<httpEndpoint host="localhost" httpPort="29080" httpsPort="29443" id="defaultHttpEndpoint"/>
<library id="MongoLib">
<file name="${server.config.dir}/lib/mongo-java-driver-2.11.4.jar"/>
</library>
<mongo autoConnectRetry="false" id="mongo" libraryRef="MongoLib">
<ports>27017</ports>
</mongo>
<mongoDB databaseName="test" id="mongo" jndiName="mongo/testdb" mongoRef="mongo">
</mongoDB>
<osgiApplication id="Test.osgi.jndi.app"
location="Test.osgi.jndi.app.eba" name="Test.osgi.jndi.app">
<classloader commonLibraryRef="MongoLib"></classloader>
</osgiApplication>
Alternatively, I tried to replace the JNDI lookup with below injection. The injected resource returns null.
public class MongoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Resource (name="mongo/testdb")
protected DB db;
}
Here is the OSGI Manifest-Version
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Test.osgi.jndi.web
Bundle-SymbolicName: Test.osgi.jndi.web
Bundle-Version: 1.0.0.qualifier
Bundle-ClassPath: WEB-INF/classes
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
Web-ContextPath: /Test.osgi.jndi.web
Import-Package: com.mongodb,
javax.el;version="2.0",
javax.servlet;version="2.5",
javax.servlet.annotation,
javax.servlet.http;version="2.5",
javax.servlet.jsp;version="2.0",
javax.servlet.jsp.el;version="2.0",
javax.servlet.jsp.tagext;version="2.0"
Bundle-Blueprint: OSGI-INF/blueprint/*.xml
The console:
[AUDIT ] CWWKZ0001I: Application apps started in 0.054 seconds.
[AUDIT ] CWWKT0016I: Web application available (default_host): http://localhost:29080/Test.osgi.jndi.web/
[AUDIT ] CWWKZ0001I: Application Test.osgi.jndi.app started in 0.561 seconds.
[AUDIT ] CWWKF0015I: The server has the following interim fixes installed: PI09253.
[AUDIT ] CWWKF0011I: The server defaultServer is ready to run a smarter planet.
[WARNING ] CWNEN0046W: The com.mongodb.DB type specified on the resource-ref, resource-env-ref, or message-destination-ref with the osgi:service/mongo/testdb name in the Test.osgi.jndi.web module could not be loaded. Compatibility type checking will not be performed for this resource reference.
[WARNING ] CWNEN0049W: Resource annotations on the methods of the com.osgi.jndi.web.MongoServlet class will be ignored. The annotations could not be obtained because of the exception : java.lang.NoClassDefFoundError: javax.naming.NamingException
[WARNING ] CWNEN0047W: Resource annotations on the fields of the com.osgi.jndi.web.MongoServlet class will be ignored. The annotations could not be obtained because of the exception : java.lang.NoClassDefFoundError: javax.naming.NamingException
at java.lang.J9VMInternals.verifyImpl(Native Method)
at java.lang.J9VMInternals.verify(J9VMInternals.java:94)
at java.lang.J9VMInternals.prepare(J9VMInternals.java:516)
at java.lang.Class.getDeclaredFields(Class.java:603)
at com.ibm.wsspi.injectionengine.InjectionProcessor.getAllDeclaredFields(InjectionProcessor.java:549)
at [internal classes]
I add Mongodb Java driver jar into Java Build Path Entry, inside Web Deployment Assembly. The java.lang.NoClassDefFoundError disappears.
However, the JNDI lookup returns new exception, "ClassCastException. I create new post for it.
ClassCastException during JNDI lookup for MongoDB, inside WAB, running Liberty
I have got this error. May be you define:
Private MongoServlet mogoServlet;
I don't know why but you try delete this code and replace by some different code. Maybe it will be ok.
It worked for me!