JBOSS JNDI Stateless bean lookup String - jboss

Deploying an EJB app with Eclipse tools on JBOSS 7.1
what's the format of the look up string to use.
I took a look at the docs,but I'm getting really confused
context.lookup("ejb:" + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!" + viewClassName);
Can you help ?

When the ejb is deployed (e.g. when the ejb is deployed to the server or the server is restarted) you should see something like this in the output:
2015 Jun 07, 18:07:24.352 (MSC service thread 1-4) INFO - (AbstractDeploymentUnitService.java:66) start - JBAS015876: Starting deployment of "_ExampleEjbProject.war"
2015 Jun 07, 18:07:24.463 (MSC service thread 1-4) INFO - (EjbJndiBindingsDeploymentUnitProcessor.java:182) setupJNDIBindings - JNDI bindings for session bean named SayHelloEjb in deployment unit deployment "_ExampleEjbProject.war" are as follows:
java:global/_ExampleEjbProject/SayHelloEjb!org.yaorma.examples.ejb.server.local.SayHelloLocal
java:app/_ExampleEjbProject/SayHelloEjb!org.yaorma.examples.ejb.server.local.SayHelloLocal
java:module/SayHelloEjb!org.yaorma.examples.ejb.server.local.SayHelloLocal
java:global/_ExampleEjbProject/SayHelloEjb!org.yaorma.examples.ejb.server.remote.SayHelloRemote
java:app/_ExampleEjbProject/SayHelloEjb!org.yaorma.examples.ejb.server.remote.SayHelloRemote
java:module/SayHelloEjb!org.yaorma.examples.ejb.server.remote.SayHelloRemote
java:jboss/exported/_ExampleEjbProject/SayHelloEjb!org.yaorma.examples.ejb.server.remote.SayHelloRemote
This is the list of strings that can be used in different contexts for the jndi lookup string. In this case my project name is _ExampleEjbProject, there is no submodule, The bean class (the implementation) is annotated with this "#Stateless(name = "SayHelloEjb")" to give the ejb name, and the local and remote interfaces are "org.yaorma.examples.ejb.server.local.SayHelloLocal" and "org.yaorma.examples.ejb.server.remote.SayHelloLocal" respectively. The lookup strings follow the pattern:
<project_name>/<submodule>/<EJB_name>!<interface_name>.
From a standalone application I am able to connect using this string:
/_ExampleEjbProject/SayHelloEjb!org.yaorma.examples.ejb.server.remote.SayHelloRemote
Like this:
public static void main(String[] args) throws Exception {
Properties jndiProperties = new Properties();
String providerURL = "remote://localhost:7447";
jndiProperties.put(Context.INITIAL_CONTEXT_FACTORY, org.jboss.naming.remote.client.InitialContextFactory.class.getName());
jndiProperties.put(Context.PROVIDER_URL, providerURL);
jndiProperties.put("jboss.naming.client.ejb.context", true);
jndiProperties.put(Context.SECURITY_PRINCIPAL, MY_UID);
jndiProperties.put(Context.SECURITY_CREDENTIALS, MY_PWD);
InitialContext context = new InitialContext(jndiProperties);
testLookup(context, "/_ExampleEjbProject/SayHelloEjb!org.yaorma.examples.ejb.server.remote.SayHelloRemote");
System.out.println("Done!");
}
private static void testLookup(InitialContext context, String lookupString) throws Exception {
Object obj = context.lookup(lookupString);
SayHelloRemote sayHelloRemote = (SayHelloRemote) obj;
String msg = sayHelloRemote.sayHello("John");
System.out.println(msg);
}

Related

Liberty class loading issues or problem with hibernate (migrating tomcat app on liberty)?

i have to deploy a multi-module application in ear on Liberty Server 20 in my Eclipse. This application use hibernate as provider jpa2 and Derby client + driver derby-10.12.1.1.jar(as shared fileset). Persistence.xml is configured with non jta.
This is server.xml:
<enterpriseApplication id="rubrica-ear" location="rubrica-ear.ear" name="rubrica-ear"/>
<dataSource jndiName="jdbc/TestappDS" type="javax.sql.ConnectionPoolDataSource">
<properties.derby.client createDatabase="false" databaseName=".rubrica"></properties.derby.client>
<jdbcDriver>
<library>
<fileset dir="C:\programmiMio\java-eclipse\drivers" id="shared"></fileset>
</library>
</jdbcDriver>
</dataSource>
My .rubrica db location is in /usr/home.
Because I dont want to start a server derby on console but automatically, i do taht in a #WebListener class:
#WebListener
public class ReqListener implements ServletContextListener {
static final Logger log = LoggerFactory.getLogger(ReqListener.class);
PrintWriter pw = new PrintWriter(System.out);
private NetworkServerControl derbyserver;
#Override
public void contextInitialized(ServletContextEvent arg0) {
try {
String userHomeDir = System.getProperty("user.home", ".");
String systemDir = userHomeDir + "/.rubrica";
// Set the db system directory and startup Server Derby for incoming connections.
System.setProperty("derby.system.home", systemDir);//il db viene salvato qui
derbyserver = new NetworkServerControl(InetAddress.getByName("localhost"), 1527);
derbyserver.start(pw);
log.info("Apache derby settings ok");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
log.error(e.getMessage());
}
}
#Override
public void contextDestroyed(ServletContextEvent arg0) {
if (derbyserver!=null){
...
}
}
When i deploy i get this error
[ERROR] An error occurred in the org.hibernate.ejb.HibernatePersistence persistence provider when attempting to create the entity manager factory of the testapp persistence unit container. The following error occurred: java.lang.NullPointerException
at org.hibernate.engine.jdbc.spi.TypeInfo.extractTypeInfo(TypeInfo.java:128)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:163)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1887)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:857)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:425)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:849)
at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:152)
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:67)
at com.ibm.ws.jpa.management.JPAPUnitInfo.createEMFactory(JPAPUnitInfo.java:919)
at [internal classes]
When I debug on Liberty i see that Hibernate classes running before the #WebListener code (this is not the same thing in Tomcat), how can i resolve this issue? Something about class loading settings?
I try derby Embedded instead, but problem still araise again, in server.xml:
<properties.derby.embedded createDatabase="create" databaseName="C:/Users/myuser/.rubrica" shutdownDatabase="false"/>
<jdbcDriver>
<library>
<fileset dir="C:\programmiMio\java-eclipse\drivers" id="shared-libs"/>
</library>
</jdbcDriver>
Thanks
Roberto

Cannot inject EJB with#EJB annotation

Trying to inject an EJB into another one using #EJB annotation :
1) The first EJB "TestEJB" has two interfaces (AdditionRemote and AdditionLocal)
and a class implementation (Addition)
2) The second EJB "TestEJB2" has two interfaces (DivisionRemote and DivisionLocal) and a class implementation (Division)
here is the code of the "TestEJB" where i want to inject a reference of TestEJB2 :
#EJB
private Division d;
public Addition() {
// TODO Auto-generated constructor stub
}
#Override
public int add(int a, int b) {
return a+b;
}
#Override
public void call() {
// TODO Auto-generated method stub
d.div(4, 2);
}
However when i use the #EJB annotation in the code i cannot deploy TestEJB anymore.
i get this error msg :
[org.jboss.as.controller.management-operation] (DeploymentScanner-threads - 1) WFLYCTL0013: Operation ("full-replace-deployment") failed - address: ([]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"TestEJB.jar\".POST_MODULE" => "WFLYSRV0153: Failed to process phase POST_MODULE of deployment \"TestEJB.jar\"
Caused by: java.lang.RuntimeException: WFLYSRV0177: Error getting reflective information for class logic.Addition with ClassLoader ModuleClassLoader for Module \"deployment.TestEJB.jar\" from Service Module Loader
Caused by: java.lang.NoClassDefFoundError: Labsurd/Division;
Caused by: java.lang.ClassNotFoundException: absurd.Division from [Module \"deployment.TestEJB.jar\" from Service Module Loader]"}}
18:45:39,399 INFO [org.jboss.as.server] (DeploymentScanner-threads - 1) WFLYSRV0016: Replaced deployment "TestEJB.jar" with deployment "TestEJB.jar"
18:45:39,400 INFO [org.jboss.as.controller] (DeploymentScanner-threads - 1) WFLYCTL0183: Service status report
WFLYCTL0186: Services which failed to start: service jboss.deployment.unit."TestEJB.jar".POST_MODULE: WFLYSRV0153: Failed to process phase POST_MODULE of deployment "TestEJB.jar"
you must inject one of the interfaces or add #localbean (for no-interface view) to Division
#EJB
private DivisionLocal d;
or
#EJB
private DivisionRemote d;
because the proxy is created for interfaces(when you implement interface the no-interface view will not be created for session bean unless you annotate it with #LocalBean)

How to use replicated Infinispan cache in Wildfly standalone-full-ha

I would like to use a replicated Infinispan cache using two Wildfly standalone instances. I want to insert a value on one node and I should be able to read it on the other node.
Here's what I tried:
I unzipped the full WF10 distribution using two different virtual
maschines running Debian Jessie.
I run both maschines with the standalone-full-ha.xml config.
I changed the binding from localhost to the IP adresses of the VMs -
all ports are reachable from outside.
I added another cache by inserting the following code to the config:
<subsystem xmlns="urn:jboss:domain:infinispan:4.0">
<cache-container name="monitor" default-cache="default">
<transport lock-timeout="60000"/>
<replicated-cache name="default" mode="SYNC">
<transaction mode="BATCH"/>
</replicated-cache>
</cache-container>
...
The rest of the configuration is not modified.
On both nodes I get the following log entries (my interpretation is -
both nodes see each other):
2016-03-13 11:19:43,160 INFO [org.infinispan.remoting.transport.jgroups.JGroupsTransport] (MSC service thread 1-1) ISPN000094: Received new cluster view for channel monitor: [wf1|5] (2) [wf1, wf2]
On one node I created a cache writer. On the other node a cache
reader is deployed:
#Singleton
#Startup
public class CacheWriter {
private final static Logger LOG = LoggerFactory.getLogger(CacheWriter.class);
#Resource(lookup = "java:jboss/infinispan/container/monitor")
private EmbeddedCacheManager cacheManager;
private Cache<String, String> cache;
#PostConstruct
public void init() {
cache = cacheManager.getCache();
LOG.info("Cache name: " + cache.getName());
}
#Schedule(hour = "*", minute = "*", second = "0", persistent = false)
public void createDateString() {
Long date = new Date().getTime();
updateCache("date", date.toString());
}
public void updateCache(String key, String value) {
if (cache.containsKey("date")) {
LOG.info("Update date value: " + value);
cache.put(key, value);
} else {
LOG.info("Create date value: " + value);
cache.put(key, value);
}
}
}
#Singleton
#Startup
public class CacheReader {
private final static Logger LOG = LoggerFactory.getLogger(CacheReader.class);
#Resource(lookup = "java:jboss/infinispan/container/monitor")
private EmbeddedCacheManager cacheManager;
private Cache<String, String> cache;
#PostConstruct
public void init() {
cache = cacheManager.getCache();
LOG.info("Cache name: " + cache.getName());
}
#Schedule(hour = "*", minute = "*", second = "10", persistent = false)
public void readDateString() {
LOG.info("Cache size: " + cache.keySet().size());
if (cache.containsKey("date")) {
LOG.info("The date value is: " + cache.get("date"));
} else {
LOG.warn("No date value found");
}
}
}
The values on the writer are inserted but there are no cache modifications on the reader node and the cache size is always 0. I tried the TCP and the UDP stack. What am I missing? Can you help me.
Thanks in advance.
Try to directly inject a cache reference (not populating it through the CacheManager). As I understand, this is only way to compel infinispan container to start it in the new WildFly 10.
#Resource(lookup = "java:jboss/infinispan/cache/monitor/default")
private Cache<String, String> cache;
By careful with the JNDI name (default one) or specify it explicitly in configuration
Instead of injecting CacheManager you should inject each cache instance. While doing, keep in mind the following points.
Make sure to enter the correct JNDI name. To avoid any confusion you could explicitly mention the JNDI name in the configuration
Add the transport tag to the cache-container. This is needed for replicated or distributed mode.
Sample Configuration in standalone-full-ha.xml
<cache-container name="replicated_cache" default-cache="default" module="org.wildfly.clustering.server" jndi-name="infinispan/replicated_cache">
<transport lock-timeout="60000"/>
<replicated-cache name="customer" mode="SYNC" jndi-name="infinispan/replicated_cache/customer">
<transaction locking="OPTIMISTIC" mode="FULL_XA"/>
<eviction strategy="NONE"/>
</replicated-cache>
</cache-container>
Inject the resource as follows
#Resource(lookup = "java:jboss/infinispan/replicated_cache/customer")
private Cache<String, Customer> customerCache;

UserTransaction used by remote clients in WildFly

Is it possible to lookup and use UserTransaction from a remote-client as
in AS 4?
I followed this document and connected from outside the server: Remote EJB invocations via JNDI - EJB client API or remote-naming project - WildFly 8 - Project Documentation Editor.
Here is the code that I used in AS 4, which failed in WildFly
Eg:
public void beginTransaction() {
try {
ut = (UserTransaction) getCtx().lookup("UserTransaction");
ut.begin();
} catch (Exception ex) {
throw new RuntimeException("Failed to begin UserTransactiion", ex);
}
}
Then I got this error:
Caused by: javax.naming.NameNotFoundException: UserTransaction -- service jboss.naming.context.java.jboss.exported.UserTransaction
Thanks!
It's now deprecated. Better use:
UserTransaction ut = RemoteTransactionContext.getInstance().getUserTransaction();

JNDI JBoss error calling EJB - No EJB receiver available for handling

I have searched the net and old question and have no answer that solves my issue.
Fresh install of JBoss 7 1.1 final, I am trying to call EJB using JNDI. It looks like it connects OK but has an error on actual method call.
Here is the Java JNDI code:
InitialContext context = null;
Hashtable env = new Hashtable();
String ejbUrl = TestEJBClient.calculateJbossEjbJndiName ( "TestEJB" , "" , "" , TestEJB.class.getSimpleName ( ) , TestEJBRemote.class.getName ( ) , false );
env.put("jboss.naming.client.ejb.context", true);
env.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming" );
env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
env.put(Context.PROVIDER_URL, "remote://localhost:4447");
env.put(Context.SECURITY_PRINCIPAL, "jboss");
env.put(Context.SECURITY_CREDENTIALS, "jboss1");
context = new InitialContext(env);
TestEJBRemote ejbRemote = (TestEJBRemote) context.lookup(ejbUrl);
Customer rtn = ejbRemote.getCustomerByAccountNumber(accountNumber);
Here is the method to calculate the name:
public static String calculateJbossEjbJndiName(String appName , String moduleName , String distinctName , String beanName , String viewClassName, boolean stateful)
{
String rtn = "ejb:"+appName+"/"+moduleName+"/"+distinctName+"/"+beanName+"!"+viewClassName;
if (stateful)
{
rtn = rtn + "?stateful";
}
return rtn;
}
Here is the log from run:
[DEBUG][org.jboss.naming.remote.client.InitialContextFactory][getOptionMapFromProperties][12:20:25:PM][jboss.naming.client.connect.options. has the following options {}]
[DEBUG][org.jboss.ejb.client.EJBClientPropertiesLoader][loadEJBClientProperties][12:20:26:PM][Looking for jboss-ejb-client.properties using classloader sun.misc.Launcher$AppClassLoader#35ce36]
[DEBUG][org.jboss.ejb.client.remoting.ConfigBasedEJBClientContextSelector][<init>][12:20:26:PM][EJB client context org.jboss.ejb.client.EJBClientContext#1543c88 will have no EJB receivers associated with it since there was no EJB client configuration available to create the receivers]
[DEBUG][org.jboss.ejb.client.remoting.RemotingConnectionEJBReceiver][handleDone][12:20:26:PM][Channel Channel ID 84a7a320 (outbound) of Remoting connection 00704baa to localhost/127.0.0.1:4447 opened for context EJBReceiverContext{clientContext=org.jboss.ejb.client.EJBClientContext#1592174, receiver=Remoting connection EJB receiver [connection=Remoting connection <1ccce3c>,channel=jboss.ejb,nodename=ny-go-oss2790a]} Waiting for version handshake message from server]
[INFO][org.jboss.ejb.client.remoting.VersionReceiver][handleMessage][12:20:26:PM][Received server version 1 and marshalling strategies [river]]
[INFO][org.jboss.ejb.client.remoting.RemotingConnectionEJBReceiver][associate][12:20:26:PM][Successful version handshake completed for receiver context EJBReceiverContext{clientContext=org.jboss.ejb.client.EJBClientContext#1592174, receiver=Remoting connection EJB receiver [connection=Remoting connection <1ccce3c>,channel=jboss.ejb,nodename=ny-go-oss2790a]} on channel Channel ID 84a7a320 (outbound) of Remoting connection 00704baa to localhost/127.0.0.1:4447]
[DEBUG][org.jboss.ejb.client.remoting.RemotingConnectionEJBReceiver][modulesAvailable][12:20:26:PM][Received module availability report for 2 modules]
[DEBUG][org.jboss.ejb.client.remoting.RemotingConnectionEJBReceiver][modulesAvailable][12:20:26:PM][Registering module EJBModuleIdentifier{appName='TestEJB', moduleName='TestEJB', distinctName=''} availability for receiver context EJBReceiverContext{clientContext=org.jboss.ejb.client.EJBClientContext#1592174, receiver=Remoting connection EJB receiver [connection=Remoting connection <1ccce3c>,channel=jboss.ejb,nodename=ny-go-oss2790a]}]
[DEBUG][org.jboss.ejb.client.remoting.RemotingConnectionEJBReceiver][modulesAvailable][12:20:26:PM][Registering module EJBModuleIdentifier{appName='TestEJB', moduleName='TestWeb', distinctName=''} availability for receiver context EJBReceiverContext{clientContext=org.jboss.ejb.client.EJBClientContext#1592174, receiver=Remoting connection EJB receiver [connection=Remoting connection <1ccce3c>,channel=jboss.ejb,nodename=ny-go-oss2790a]}]
[WARN][org.jboss.ejb.client.remoting.ChannelAssociation][handleMessage][12:20:26:PM][Unsupported message received with header 0xffffffff]
ejbUrl = ejb:TestEJB///TestEJB!org.test.services.om.TestEJBRemote
[INFO][org.jboss.ejb.client][<clinit>][12:20:26:PM][JBoss EJB Client version 1.0.5.Final]
ejbRemote = Proxy for remote EJB StatelessEJBLocator{appName='TestEJB', moduleName='', distinctName='', beanName='TestEJB', view='interface org.test.services.om.TestEJBRemote'}
java.lang.IllegalStateException: No EJB receiver available for handling [appName:TestEJB,modulename:,distinctname:] combination for invocation context org.jboss.ejb.client.EJBClientInvocationContext#105d88a
Exception in thread "main" java.lang.IllegalStateException: No EJB receiver available for handling [appName:TestEJB,modulename:,distinctname:] combination for invocation context org.jboss.ejb.client.EJBClientInvocationContext#105d88a
at org.jboss.ejb.client.EJBClientContext.requireEJBReceiver(EJBClientContext.java:584)
at org.jboss.ejb.client.ReceiverInterceptor.handleInvocation(ReceiverInterceptor.java:119)
at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:181)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:136)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:121)
at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:104)
Might be because of the jar files that were used in the client. Check this out :
https://community.jboss.org/thread/227862
I found the solution, It is to add this line to my client code:
jndiProperties.put("jboss.naming.client.ejb.context", "true");
No EJB receiver available for handling