HornetQ JMS: java.lang.NoSuchMethodError - jar

unfortunately while trying to get a JMS service working with HornetQ, I am running form error message to error message. The prior error was related to a missing core.jar file. Prior Error
After all, I am trying to implement a simple producer/consumer example as a jms service. (Based on "HornetQ Messaging Developer's Guide")
package chapter01;
import javax.jms.JMSException;
import javax.naming.NamingException;
public class ECGMessageConsumerProducerExample {
public static void main(String[] args) throws NamingException, JMSException {
// TODO Auto-generated method stub
javax.naming.Context ic = null;
javax.jms.ConnectionFactory cf = null;
javax.jms.Connection connection = null;
javax.jms.Queue queue = null;
javax.jms.Session session = null;
com.mongodb.Mongo m;
com.mongodb.DB db;
String destinationName = "queue/DLQ";
java.util.Properties p = new java.util.Properties();
p.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY,
"org.jnp.interfaces.NamingContextFactory");
p.put(javax.naming.Context.URL_PKG_PREFIXES,
"org.jboss.naming:org.jnp.interfaces");
p.put(javax.naming.Context.PROVIDER_URL, "jnp://localhost:1099");
ic = new javax.naming.InitialContext(p);
cf = (javax.jms.ConnectionFactory)ic.lookup("/ConnectionFactory");
queue = (javax.jms.Queue)ic.lookup(destinationName);
connection = cf.createConnection();
session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
connection.start();
String theECG = "1;02/20/2012 14:01:59.010;1020,1021,1022";
javax.jms.MessageProducer publisher = session.createProducer(queue);
javax.jms.TextMessage message =
session.createTextMessage(theECG);
publisher.send(message);
System.out.println("Message sent!");
publisher.close();
}
}
While facing erros I probably added unneeded jars:
However, I get the following error message:
Exception in thread "main" java.lang.NoSuchMethodError: org.hornetq.api.core.client.ClientSessionFactory.copy()Lorg/hornetq/api/core/client/ClientSessionFactory;
at org.hornetq.jms.client.HornetQConnectionFactory.createConnectionInternal(HornetQConnectionFactory.java:612)
at org.hornetq.jms.client.HornetQConnectionFactory.createConnection(HornetQConnectionFactory.java:116)
at org.hornetq.jms.client.HornetQConnectionFactory.createConnection(HornetQConnectionFactory.java:111)
at chapter01.ECGMessageConsumerProducerExample.main(ECGMessageConsumerProducerExample.java:33)
I expect the error to be caused by a mismatch between jars used by the server and used by the client. But since I am a programmer noob, I do not really know what exact jars with suitable versions are needed.

Try defining NettyConnectorFactory as connector as in jboss reference.
for example in hornetq-configuration.xml file:
<connectors>
<connector name="netty">
<factory-class>
org.hornetq.core.remoting.impl.netty.NettyConnectorFactory
</factory-class>
<param key="port" value="5446"/>
</connector>
</connectors>

Related

contractVerifierMessaging.receive is null

I'm setting up contract tests for Kafka messaging with Test Containers in a way described in spring-cloud-contract-samples/producer_kafka_middleware/. Works good with Embedded Kafka but not with TestContainers.
When I try to run the generated ContractVerifierTest:
public void validate_shouldProduceKafkaMessage() throws Exception {
// when:
triggerMessageSent();
// then:
ContractVerifierMessage response = contractVerifierMessaging.receive("kafka-messages",
contract(this, "shouldProduceKafkaMessage.yml"));
Cannot invoke "org.springframework.messaging.Message.getPayload()" because "receive" is null
is thrown
Kafka container is running, the topic is created. When debugging receive method I see the message is null in the message(destination);
Contract itself:
label("triggerMessage")
input {
triggeredBy("triggerMessageSent()")
}
outputMessage {
sentTo "kafka-messages"
body(file("kafkaMessage.json"))
Base test configuration:
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE, classes = {TestConfig.class, ServiceApplication.class})
#Testcontainers
#AutoConfigureMessageVerifier
#ActiveProfiles("test")
public abstract class BaseClass {
What am I missing? Maybe a point of communication between the container and ContractVerifierMessage methods?
Resolved the issue by adding a specific topic name to listen() method in KafkaMessageVerifier implementation class.
So instead of #KafkaListener(id = "listener", topicPattern = ".*"), it works with:
#KafkaListener(topics = {"my-messages-topic"})
public void listen(ConsumerRecord payload, #Header(KafkaHeaders.RECEIVED_TOPIC)

After accidentally deleting Data Dictionary (app:dictionary) Alfresco doesn't start

One operator deleted Data Dictionary and restarted Alfresco 3.4.12 Enterprise Edition. The context /alfresco doesn't start with the following exception:
17:43:11,100 INFO [STDOUT] 17:43:11,097 ERROR [web.context.ContextLoader] Context initialization failed
org.alfresco.error.AlfrescoRuntimeException: 08050000 Failed to find 'app:dictionary' node
at org.alfresco.repo.action.scheduled.ScheduledPersistedActionServiceImpl.locatePersistanceFolder(ScheduledPersistedActionServiceImpl.java:132)
Looking at the source code in org.alfresco.repo.action.scheduled.ScheduledPersistedActionServiceImpl.java, the path is hardwired.
Then we followed the tip from https://community.alfresco.com/thread/202859-error-failed-to-find-appdictionary-node, editing bootstrap-context.xml, comment out the class.
After the change the error went over, now the RenditionService couldn't start.
We're looking for a way to recover the deleted node, since we can obtain the nodeid from the database. So we created a small class and invoke it through spring in bootstrap-context.xml, but it's failing due to permissions. Could you take a look at the code and tell us what's wrong. The code is:
package com.impulseit.test;
import javax.transaction.UserTransaction;
import org.alfresco.repo.node.archive.NodeArchiveService;
import org.alfresco.repo.node.archive.RestoreNodeReport;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.NodeRef;
public class RestoreNode {
private NodeArchiveService nodeArchiveService;
private ServiceRegistry serviceRegistry;
private String nodeName ="archive://SpacesStore/adfc0cfe-e20b-467f-ad71-253aea8f9ac9";
public void setNodeArchiveService(NodeArchiveService value)
{
this.nodeArchiveService = value;
}
public void setServiceRegistry(ServiceRegistry value)
{
this.serviceRegistry = value;
}
public void doRestore() {
RunAsWork<Void> runAsWork = new RunAsWork<Void>()
{
public Void doWork() throws Exception
{
NodeRef nodeRef = new NodeRef(nodeName);
//RestoreNodeReport restoreNodeReport =
UserTransaction trx_A = serviceRegistry.getTransactionService().getUserTransaction();
trx_A.begin();
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
RestoreNodeReport restored = nodeArchiveService.restoreArchivedNode(nodeRef);
trx_A.commit();
return null;
}
};
AuthenticationUtil.runAs(runAsWork,AuthenticationUtil.getSystemUserName());
}
public RestoreNode() {
}
}
The exception is:
19:31:21,747 User:admin ERROR [node.archive.NodeArchiveServiceImpl] An unhandled exception stopped the restore
java.lang.NullPointerException
at org.alfresco.repo.security.permissions.impl.model.PermissionModel.getPermissionReference(PermissionModel.java:1315)
at org.alfresco.repo.security.permissions.impl.PermissionServiceImpl.getPermissionReference(PermissionServiceImpl.java:956)
at org.alfresco.repo.security.permissions.impl.PermissionServiceImpl.hasPermission(PermissionServiceImpl.java:976)
Thank you in advance.
Luis

JBoss 7.1.1.Final - EJB Remote Call - java.lang.IllegalStateException: No EJB receiver available for handling

I do have 2 JBoss stanalon instance running. 1 act as Server and another 1 would client.
SERVER:
Remote Interface
package com.xyz.life.service.ejb;
import java.io.Serializable;
import java.rmi.RemoteException;
import javax.ejb.EJB;
import javax.ejb.Remote;
#Remote
public interface QuoteFacade extends Serializable{
public boolean isAlive() throws RemoteException;
}
EJB Impl
package com.xyz.life.common.component.ejb.services;
import java.rmi.RemoteException;
import javax.ejb.Remote;
import javax.ejb.Stateless;
#Stateless(mappedName = "QuoteFacadeEJB")
#Remote(QuoteFacade.class)
public class QuoteFacadeEJB extends CommonSessionBean implements QuoteFacade {
private static final long serialVersionUID = -8788783322280644881L;
#Override
public boolean isAlive() throws RemoteException {
return true;
}
}
server.log
16:40:25,012 INFO [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-4) JNDI bindings for session bean named QuoteFacadeEJB in deployment unit subdeployment "quote.jar" of deployment "quote.ear" are as follows:
java:global/quote/quote.jar/QuoteFacadeEJB!com.xyz.life.service.ejb.QuoteFacade
java:app/quote.jar/QuoteFacadeEJB!com.xyz.life.service.ejb.QuoteFacade
java:module/QuoteFacadeEJB!com.xyz.life.service.ejb.QuoteFacade
java:jboss/exported/quote/quote.jar/QuoteFacadeEJB!com.xyz.life.service.ejb.QuoteFacade
java:global/quote/quote.jar/QuoteFacadeEJB
java:app/quote.jar/QuoteFacadeEJB
java:module/QuoteFacadeEJB
Client
public void testClient() {
try {
Hashtable<String, Object> jndiProps = new Hashtable<String, Object>();
jndiProps.put(Context.URL_PKG_PREFIXES, JNDINames.JBOSS_CLIENT_NAMING_PREFIX);
jndiProps.put("jboss.naming.client.ejb.context", true);
Context ctx = new InitialContext(jndiProps);
String name = "ejb:global/quote/quote.jar/QuoteFacadeEJB!com.ge.life.annuity.service.ejb.QuoteFacade";
/*
"ejb:global/quote/quote.jar/QuoteFacadeEJB!com.ge.life.annuity.service.ejb.QuoteFacade",
"ejb:app/quote.jar/QuoteFacadeEJB!com.ge.life.annuity.service.ejb.QuoteFacade",
"ejb:jboss/exported/quote/quote.jar/QuoteFacadeEJB!com.ge.life.annuity.service.ejb.QuoteFacade"
*/
Object ref = ctx.lookup(name);
QuoteFacade quoteFacade = (QuoteFacade) ref;
LOGGER.debug("isAlive : " + quoteFacade.isAlive());
} catch (Exception e) {
LOGGER.error("Remote Client Exception : ", e);
}
}
No error/log on server side. Client side, it is failing with following error:
java.lang.IllegalStateException: No EJB receiver available for handling [appName:global,modulename:quote,distinctname:quote.jar] combination for invocation context org.jboss.ejb.client.EJBClientInvocationContext#200cae
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)
at $Proxy10.isAlive(Unknown Source)
I tried without using Properties file:
private static QuoteFacade connectToStatelessBean(String name) throws NamingException {
Properties jndiProperties = new Properties();
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
jndiProperties.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
jndiProperties.put(javax.naming.Context.PROVIDER_URL, "remote://localhost:4447");
jndiProperties.put(javax.naming.Context.SECURITY_PRINCIPAL, "admin");
jndiProperties.put(javax.naming.Context.SECURITY_CREDENTIALS, "Pass1234");
final Context context = new InitialContext(jndiProperties);
return (QuoteFacade) context.lookup(name);
}
public static void testLocal() {
String[] JNDINAME1 = {
"ejb:global/quote/quote.jar/QuoteFacadeEJB!com.ge.life.annuity.service.ejb.QuoteFacade",
"ejb:app/quote.jar/QuoteFacadeEJB!com.ge.life.annuity.service.ejb.QuoteFacade",
"ejb:module/QuoteFacadeEJB!com.ge.life.annuity.service.ejb.QuoteFacade",
"ejb:jboss/exported/quote/quote.jar/QuoteFacadeEJB!com.ge.life.annuity.service.ejb.QuoteFacade",
"ejb:global/quote/quote.jar/QuoteFacadeEJB",
"ejb:app/quote.jar/QuoteFacadeEJB",
"ejb:module/QuoteFacadeEJB"
};
for(int i=0;i<JNDINAME1.length;i++){
try {
QuoteFacade test1 = connectToStatelessBean(JNDINAME1[i]);
LOGGER.error("DSLKAJDLAS : " + test1.isAlive());
} catch (Exception e) {
LOGGER.error("DSLKAJDLAS : " , e);
}
}
LOGGER.info("Done - SANSSAN!!!!!!!!");
}
This time, different exception :
14.01.2013 17:40:37.627 [ERROR] - EJBClient - DSLKAJDLAS :
javax.naming.NamingException: JBAS011843: Failed instantiate InitialContextFactory org.jboss.naming.remote.client.InitialContextFactory from classloader ModuleClassLoader for Module "deployment.quote.war:main" from Service Module Loader
at org.jboss.as.naming.InitialContextFactoryBuilder.createInitialContextFactory(InitialContextFactoryBuilder.java:64)
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:681)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:307)
at javax.naming.InitialContext.init(InitialContext.java:242)
at javax.naming.InitialContext.><init>(InitialContext.java:216)
at com.xyz.life.test.EJBClient.connectToStatelessBean(EJBClient.java:208)
at com.xyz.life.test.EJBClient.testLocal(EJBClient.java:225)
at com.xyz.life.test.EJBClient.test(EJBClient.java:172)
at com.xyz.life.common.web.struts.plugin.FrameworkStartupPlugIn.init(FrameworkStartupPlugIn.java:99)
at org.apache.struts.action.ActionServlet.initModulePlugIns(ActionServlet.java:1158)
at org.apache.struts.action.ActionServlet.init(ActionServlet.java:473)
at javax.servlet.GenericServlet.init(GenericServlet.java:242)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1202)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1102)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:3655)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:3873)
at org.jboss.as.web.deployment.WebDeploymentService.start(WebDeploymentService.java:90)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Try removing "global" from name:
String name =
"ejb:quote/quote.jar/QuoteFacadeEJB!com.xyz.life.service.ejb.QuoteFacade"
Also, your package name should be com.xyz.life.service.ejb (as seen on server log) and not com.ge.life.annuity.service.ejb.
Anyway, using remote-naming project for remote EJB invocations is discouraged as explained here.
... . So as you can see, we have managed to optimize certain operations by using the EJB client API for EJB lookup/invocation as against using the remote-naming project. There are other EJB client API implementation details (and probably more might be added) which are superior when it is used for remote EJB invocations in client applications as against remote-naming project which doesn't have the intelligence to carry out such optimizations for EJB invocations. That's why the remote-naming project for remote EJB invocations is considered "deprecated". ...
You can check how to do remote EJB invocations using the EJB client API here.
Found it....
The ones I used for Local machines only. Difference JBoss instances, should change the JNDI lookup name...
like
ejb:quote/quote.jar//QuoteFacadeEJB!com.xyz.life.service.ejb.QuoteFacade

How do I add aliases to a Servlet Context in java?

I have a servlet running under Tomcat.
I need to serve some files, I guess we can call them semi-static (which change occasionally ... they are updated by another part of the app) from an external (to the WEB-APP) directory.
I have managed to do this by adding the following to my context.xml in the META-INF directory
<Context aliases="/working_dir=c:/apache_tomcat_working_dir" ></Context>
This works fine, in my HTML I refer to the file as
<img src="/myWebbApp/working_dir/fixpermin_zoom.png">
and in my web.xml inside WEB-INF
I let the default server handle png files as follows
<!-- use default for static serving of png's, js and css, also ico -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>
So this works fine. But I want to set the external directory from inside java code, not by editing the context.xml file.
Now in the init() method of the servlet I can get the ServletContext.
ServletContext sc = getServletContext();
If I examine this variable sc in the debugger, I can see the alias string several levels deep, see the attached image. How can I get at this alias string programatically?
I have checked the ServletContext docs, but i can't find it very helpful.
Any help much appreciated.
(source: choicecomp.com)
As you can see in your debugger, your context is Tomcat's Context Object org.apache.catalina.core.StandardContext
You can try following steps in Tomcat 6 and below:
StandardEngine engine = (StandardEngine) ServerFactory.getServer().findService("Catalina").getContainer();
StandardContext context = (StandardContext) engine.findChild(engine.getDefaultHost()).findChild(getServletContext().getContextPath());
Mapper mapper = context.getMapper();
Now you can add Host alias using addHostAlias(String HostName, String alias) method of the Mapper class.
mapper.addHostAlias(engine.getDefaultHost(), "myAlias");
Here is the code snippet for Tomcat 7:
MBeanServer mBeanServer = MBeanServerFactory.findMBeanServer(null).get(0);
ObjectName name = new ObjectName("Catalina", "type", "Server");
Server server = (Server) mBeanServer.getAttribute(name, "managedResource");
StandardEngine engine = (StandardEngine) server.findService("Catalina").getContainer();
StandardContext context = (StandardContext) engine.findChild(engine.getDefaultHost()).findChild(getServletContext().getContextPath());
Mapper mapper = context.getMapper();
mapper.addHostAlias(engine.getDefaultHost(), "myAlias");
If there is no host in the mapper, please try below:
MBeanServer mBeanServer = MBeanServerFactory.findMBeanServer(null).get(0);
ObjectName name = new ObjectName("Catalina", "type", "Server");
Server server = (Server) mBeanServer.getAttribute(name, "managedResource");
StandardEngine engine = (StandardEngine) server.findService("Catalina").getContainer();
StandardContext context = (StandardContext) engine.findChild(engine.getDefaultHost()).findChild(getServletContext().getContextPath());
Mapper mapper = context.getMapper();
//just a clean up step(remove the host)
mapper.removeHost(engine.getDefaultHost());
//add the host back with all required aliases
mapper.addHost(engine.getDefaultHost(), new String[]{"myAlias"}, engine.getDefaultHost());
Hope this helps!
I found another method StandardContext.setAliases. Find below the full working code snippet for Tomcat 7.0.30.
MBeanServer mBeanServer = MBeanServerFactory.findMBeanServer(null).get(0);
ObjectName name = new ObjectName("Catalina", "type", "Server");
Server server = (Server) mBeanServer.getAttribute(name, "managedResource");
StandardEngine engine = (StandardEngine) server.findService("Catalina").getContainer();
StandardContext context = (StandardContext) engine.findChild(engine.getDefaultHost()).findChild(getServletContext().getContextPath());
context.setAliases("myAlias");
//infact aliases should be proper e.g. below
//context.setAliases("/aliasPath1=docBase1,/aliasPath2=docBase2");
Mapper mapper = context.getMapper();
mapper.removeHost(engine.getDefaultHost());
mapper.addHost(engine.getDefaultHost(), new String[]{"myAlias"}, engine.getDefaultHost());
mapper.addHostAlias(engine.getDefaultHost(), "myAlias");
//infact aliases should be proper e.g. below
//mapper.addHostAlias(engine.getDefaultHost(), "/aliasPath1=docBase1,/aliasPath2=docBase2");
Please find my debugger screenshots below:
Before the code snippet execution:
After the code snippet execution:
Hope this is more helpful.
Here is my working code to dynamically set Tomcat7 context alias depending on different operating systems. Sure you can improve on it
public class ContextListener implements ServletContextListener {
#Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext context = sce.getServletContext();
// tomcat 7.x
try {
MBeanServer mBeanServer = MBeanServerFactory.findMBeanServer(null).get(0);
ObjectName name = new ObjectName("Catalina", "type", "Server");
Object server = mBeanServer.getAttribute(name, "managedResource");
Object service = server.getClass().getMethod("findService", String.class).invoke(server, "Catalina"); //StandardService[Catalina]
Object connectors = service.getClass().getMethod("findConnectors").invoke(service);
Object engine = service.getClass().getMethod("getContainer").invoke(service); //StandardEngine[Catalina]
Object host = Array.get(engine.getClass().getMethod("findChildren").invoke(engine), 0); //StandardHost[Catalina]
Object stdContext = Array.get(host.getClass().getMethod("findChildren").invoke(host), 0); //StandardContext[Catalina]
Object mapper = stdContext.getClass().getMethod("getMapper").invoke(stdContext);
//just a clean up step(remove the host)
Field f1 = mapper.getClass().getDeclaredField("context");
f1.setAccessible(true);
Object ct = f1.get(mapper);
Field f2 = ct.getClass().getDeclaredField("resources");
f2.setAccessible(true);
Object rs = f2.get(ct);
Field f3 = rs.getClass().getDeclaredField("dirContext");
f3.setAccessible(true);
Object dc = f3.get(rs);
mapper.getClass().getMethod("removeHost",String.class).invoke(mapper, host.getClass().getMethod("getName").invoke(host));
//add the host back with all required aliases
switch (OsCheck.getOperatingSystemType()) {
case Windows:
dc.getClass().getMethod("setAliases",String.class).invoke(dc,"/img/avatars=" + winAvatarAlias);
break;
default:
dc.getClass().getMethod("setAliases",String.class).invoke(dc,"/img/avatars=" + linuxAvatarAlias);
break;
}
String ports = "";
for (Object o :(Object[]) connectors ) {
ports = ports + (Integer)o.getClass().getMethod("getPort").invoke(o) + " ";
}
log.info("Tomcat 7.x detected, service {}, engine {}, host {}, stdContext {}, server port: {}",
service.getClass().getMethod("getName").invoke(service),
engine.getClass().getMethod("getName").invoke(engine),
host.getClass().getMethod("getName").invoke(host),
stdContext.getClass().getMethod("getDisplayName").invoke(stdContext),
ports);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Based on Khanh's approach, here is a context listener that works for an embedded maven tomcat (v.7.0.62).
Please note the differences ("Tomcat" instead of "Catalina" and no findService("Catalina")), so that the approach works for an embedded tomcat. In contrast to Khanh, I used regular methods instead of reflection to get the BaseDirContext object.
Finally, you should note that you need to call setAliases() on the BaseDirContext object instead of the StandardContext object! Internally, StandardContext's setAliases() is just a setter, whereas BaseDirContext's setAliases() does a lot of other stuff, so that the already running tomcat indeed registers your new aliases.
import org.apache.catalina.Container;
import org.apache.catalina.Server;
import org.apache.catalina.Service;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.log4j.Logger;
import org.apache.naming.resources.BaseDirContext;
import org.apache.naming.resources.ProxyDirContext;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class AliasesContextListener implements ServletContextListener {
private static Logger log = Logger.getLogger(AliasesContextListener.class);
#Override
public void contextInitialized(ServletContextEvent sce) {
try {
String aliases = "/foo=C:\\bar";
//get current tomcat server, engine and context objects
MBeanServer mBeanServer = MBeanServerFactory.findMBeanServer(null).get(0);
ObjectName name = new ObjectName("Tomcat", "type", "Server");
Server server = (Server) mBeanServer.getAttribute(name, "managedResource");
Service[] services = server.findServices();
StandardEngine engine = (StandardEngine) services[0].getContainer();
Container defaultHostContainer = engine.findChild(engine.getDefaultHost());
ServletContext servletContext = sce.getServletContext();
StandardContext standardContext = (StandardContext) defaultHostContainer.findChild(servletContext.getContextPath());
ProxyDirContext proxyDirContext = (ProxyDirContext) standardContext.getResources();
BaseDirContext baseDirContext = (BaseDirContext) proxyDirContext.getDirContext();
//modify the aliases entry
baseDirContext.setAliases(aliases);
} catch (Exception e) {
log.error("error while setting aliases in context listener", e);
}
}
#Override
public void contextDestroyed(ServletContextEvent sce) {
//not implemented
}
}

Injecting jms resource in servlet & best practice for MDB

using ejb 3.1, servlet 3.0 (glassfish server v3)
Scenario:
I have MDB that listen to jms messages and give processing to some other session bean (Stateless).
Servelet injecting jms resource.
Question 1: Why servlet can`t inject jms resources when they use static declaration ?
#Resource(mappedName = "jms/Tarturus")
private static ConnectionFactory connectionFactory;
#Resource(mappedName = "jms/StyxMDB")
private static Queue queue;
private Connection connection;
and
#PostConstruct
public void postConstruct() {
try {
connection = connectionFactory.createConnection();
} catch (JMSException e) {
e.printStackTrace();
}
}
#PreDestroy
public void preDestroy() {
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
The error that I get is :
[#|2010-05-03T15:18:17.118+0300|WARNING|glassfish3.0|javax.enterprise.system.container.web.com.sun.enterprise.web|_ThreadID=35;_ThreadName=Thread-1;|StandardWrapperValve[WorkerServlet]:
PWC1382: Allocate exception for
servlet WorkerServlet
com.sun.enterprise.container.common.spi.util.InjectionException:
Error creating managed object for
class
ua.co.rufous.server.services.WorkerServiceImpl
at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.createManagedObject(InjectionManagerImpl.java:312)
at
com.sun.enterprise.web.WebContainer.createServletInstance(WebContainer.java:709)
at
com.sun.enterprise.web.WebModule.createServletInstance(WebModule.java:1937)
at
org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1252)
Caused by:
com.sun.enterprise.container.common.spi.util.InjectionException:
Exception attempting to inject
Unresolved Message-Destination-Ref
ua.co.rufous.server.services.WorkerServiceImpl/queue#java.lang.String#null
into class
ua.co.rufous.server.services.WorkerServiceImpl
at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl._inject(InjectionManagerImpl.java:614) at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.inject(InjectionManagerImpl.java:384)
at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.injectInstance(InjectionManagerImpl.java:141)
at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.injectInstance(InjectionManagerImpl.java:127)
at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.createManagedObject(InjectionManagerImpl.java:306)
... 27 more Caused by:
com.sun.enterprise.container.common.spi.util.InjectionException:
Illegal use of static field private
static javax.jms.Queue
ua.co.rufous.server.services.WorkerServiceImpl.queue
on class that only supports
instance-based injection at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl._inject(InjectionManagerImpl.java:532) ... 31 more |#]
my MDB :
/**
* asadmin commands
* asadmin create-jms-resource --restype javax.jms.ConnectionFactory jms/Tarturus
* asadmin create-jms-resource --restype javax.jms.Queue jms/StyxMDB
* asadmin list-jms-resources
*/
#MessageDriven(mappedName = "jms/StyxMDB", activationConfig =
{
#ActivationConfigProperty(propertyName = "connectionFactoryJndiName", propertyValue = "jms/Tarturus"),
#ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
#ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
})
public class StyxMDB implements MessageListener {
#EJB
private ActivationProcessingLocal aProcessing;
public StyxMDB() {
}
public void onMessage(Message message) {
try {
TextMessage msg = (TextMessage) message;
String hash = msg.getText();
GluttonyLogger.getInstance().writeInfoLog("geted jms message hash = " + hash);
} catch (JMSException e) {
}
}
}
everything work good without static declaration:
#Resource(mappedName = "jms/Tarturus")
private ConnectionFactory connectionFactory;
#Resource(mappedName = "jms/StyxMDB")
private Queue queue;
private Connection connection;
Question 2:
what is the best practice for working with MDB : processing full request in onMessage() or calling another bean(Stateless bean in my case) in onMessage() method that would process it.
Processing including few calls to soap services, so the full processing time could be for a 3 seconds.
Thank you.
Answers:
1. You cannot inject a resource into a static field. Injection into member fields occurs during object construction, static fields are not part of the object (only part of the class). In addition EJBs and servlets are threaded objects so this could possibly be dangerous to do.
2. If splitting the processing up into multiple EJB(s) makes sense do it that way, otherwise processing in onMessage() is perfectly valid.
One additional suggestion that I can give, is that you should take a look at CDI which is a new addition to the EE 6 specification and provides rich dependency injection.
Are you using an MDB to perform asynchronous operations, Servlet 3.0 has some neat asynchronous capabilities. I suggest you watch the entire presentation if you are not familiar with Servlet 3.0.

Resources