Implementing MDB Pool Listener in JBoss JMS - jboss

I've an application deployed in JBoss with multiple MDBs deployed using JBoss JMS implementation, each one with a different configuration of MDB Pool Size. I was looking forward to some kind of mechanism where we can have a listener on each MDB Pool size where we can check if at any point all instances from the MDB pool are getting utilized. This will help in analyzing and configuring the appropriate MDB pool size for each MDB.

We use Jamon to monitor instances of MDBs, like this:
#MessageDriven
#TransactionManagement(value = TransactionManagementType.CONTAINER)
#TransactionAttribute(value = TransactionAttributeType.REQUIRED)
#ResourceAdapter("wmq.jmsra.rar")
#AspectDomain("YourDomainName")
public class YourMessageDrivenBean implements MessageListener
{
// jamon package constant
protected static final String WB_ONMESSAGE = "wb.onMessage";
// instance counter
private static AtomicInteger counter = new AtomicInteger(0);
private int instanceIdentifier = 0;
#Resource
MessageDrivenContext ctx;
#Override
public void onMessage(Message message)
{
final Monitor monall = MonitorFactory.start(WB_ONMESSAGE);
final Monitor mon = MonitorFactory.start(WB_ONMESSAGE + "." + toString()
+ "; mdb instance identifier=" + instanceIdentifier);
try {
// process your message here
}
} catch (final Exception x) {
log.error("Error onMessage " + x.getMessage(), x);
ctx.setRollbackOnly();
} finally {
monall.stop();
mon.stop();
}
}
#PostConstruct
public void init()
{
instanceIdentifier = counter.incrementAndGet();
log.debug("constructed instance #" + instanceIdentifier);
}
}
You can then see in the Jamon-Monitor every created instance of your MDB.

Related

I am not getting results from ksql StreamQuery integrated with java. when I am printing log for client is showing not completed

I am using confluent kafka version 6.o
downloaded from https://www.confluent.io/download/
I am referring
https://docs.ksqldb.io/en/latest/developer-guide/ksqldb-clients/java-client/ acritical .
https://www.youtube.com/watch?v=85udigshlNI
with java producer code I am able to send value to ksql. But not able to retrieve this value.
when I am printing log for streamQuery result, I am getting Not Completed message.
used Maven dependency as:
<dependencies>
<dependency>
<groupId>io.confluent.ksql</groupId>
<artifactId>ksqldb-api-client</artifactId>
<version>${ksqldb.version}</version>
</dependency>
</dependencies>
java code :
public class ExampleApp {
public static String KSQLDB_SERVER_HOST = "localhost";
public static int KSQLDB_SERVER_HOST_PORT = 8088;
public static void main(String[] args) {
ClientOptions options = ClientOptions.create()
.setHost(KSQLDB_SERVER_HOST)
.setPort(KSQLDB_SERVER_HOST_PORT);
Client client = Client.create(options);
// Send requests with the client by following the other examples
// Terminate any open connections and close the client
client.close();
}
}public class ExampleApp {
public static String KSQLDB_SERVER_HOST = "localhost";
public static int KSQLDB_SERVER_HOST_PORT = 8088;
public static void main(String[] args) {
ClientOptions options = ClientOptions.create()
.setHost(KSQLDB_SERVER_HOST)
.setPort(KSQLDB_SERVER_HOST_PORT);
Client client = Client.create(options);
StreamedQueryResult streamedQueryResult = client.streamQuery("SELECT * FROM MY_STREAM EMIT CHANGES;").get();
for (int i = 0; i < 10; i++) {
// Block until a new row is available
Row row = streamedQueryResult.poll();
if (row != null) {
System.out.println("Received a row!");
System.out.println("Row: " + row.values());
} else {
System.out.println("Query has ended.");
}
}
client.close();
}
}
output :
get() is waiting for long time even after adding values into topic waiting and finally gives timeout exception.

Why use Kryo serialize framework into apache storm will over write data when blot get values

Maybe mostly develop were use AVRO as serialize framework in Kafka and Apache Storm scheme. But I need handle most complex data then I found the Kryo serialize framework also were successfully integrate it into our project which follow Kafka and Apache Storm environment. But when want to further operation there had a strange status.
I had sent 5 times message to Kafka, the Storm job also can read the 5 messages and deserialize success. But next blot get the data value is wrong. There print out the same value as the last message. Then I had add the print out after when complete the deserialize code. Actually it print out true there had different 5 message. Why the next blot can't the values? See my code below:
KryoScheme.java
public abstract class KryoScheme<T> implements Scheme {
private static final long serialVersionUID = 6923985190833960706L;
private static final Logger logger = LoggerFactory.getLogger(KryoScheme.class);
private Class<T> clazz;
private Serializer<T> serializer;
public KryoScheme(Class<T> clazz, Serializer<T> serializer) {
this.clazz = clazz;
this.serializer = serializer;
}
#Override
public List<Object> deserialize(byte[] buffer) {
Kryo kryo = new Kryo();
kryo.register(clazz, serializer);
T scheme = null;
try {
scheme = kryo.readObject(new Input(new ByteArrayInputStream(buffer)), this.clazz);
logger.info("{}", scheme);
} catch (Exception e) {
String errMsg = String.format("Kryo Scheme failed to deserialize data from Kafka to %s. Raw: %s",
clazz.getName(),
new String(buffer));
logger.error(errMsg, e);
throw new FailedException(errMsg, e);
}
return new Values(scheme);
}}
PrintFunction.java
public class PrintFunction extends BaseFunction {
private static final Logger logger = LoggerFactory.getLogger(PrintFunction.class);
#Override
public void execute(TridentTuple tuple, TridentCollector collector) {
List<Object> data = tuple.getValues();
if (data != null) {
logger.info("Scheme data size: {}", data.size());
for (Object value : data) {
PrintOut out = (PrintOut) value;
logger.info("{}.{}--value: {}",
Thread.currentThread().getName(),
Thread.currentThread().getId(),
out.toString());
collector.emit(new Values(out));
}
}
}}
StormLocalTopology.java
public class StormLocalTopology {
public static void main(String[] args) {
........
BrokerHosts zk = new ZkHosts("xxxxxx");
Config stormConf = new Config();
stormConf.put(Config.TOPOLOGY_DEBUG, false);
stormConf.put(Config.TOPOLOGY_TRIDENT_BATCH_EMIT_INTERVAL_MILLIS, 1000 * 5);
stormConf.put(Config.TOPOLOGY_WORKERS, 1);
stormConf.put(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS, 5);
stormConf.put(Config.TOPOLOGY_TASKS, 1);
TridentKafkaConfig actSpoutConf = new TridentKafkaConfig(zk, topic);
actSpoutConf.fetchSizeBytes = 5 * 1024 * 1024 ;
actSpoutConf.bufferSizeBytes = 5 * 1024 * 1024 ;
actSpoutConf.scheme = new SchemeAsMultiScheme(scheme);
actSpoutConf.startOffsetTime = kafka.api.OffsetRequest.LatestTime();
TridentTopology topology = new TridentTopology();
TransactionalTridentKafkaSpout actSpout = new TransactionalTridentKafkaSpout(actSpoutConf);
topology.newStream(topic, actSpout).parallelismHint(4).shuffle()
.each(new Fields("act"), new PrintFunction(), new Fields());
LocalCluster cluster = new LocalCluster();
cluster.submitTopology(topic+"Topology", stormConf, topology.build());
}}
There also other problem why the kryo scheme only can read one message buffer. Is there other way get multi messages buffer then can batch send data to next blot.
Also if I send 1 message the full flow seems success.
Then send 2 message is wrong. the print out message like below:
56157 [Thread-18-spout0] INFO s.s.a.s.s.c.KryoScheme - 2016-02- 05T17:20:48.122+0800,T6mdfEW#N5pEtNBW
56160 [Thread-20-b-0] INFO s.s.a.s.s.PrintFunction - Scheme data size: 1
56160 [Thread-18-spout0] INFO s.s.a.s.s.c.KryoScheme - 2016-02- 05T17:20:48.282+0800,T(o2KnFxtGB0Tlp8
56161 [Thread-20-b-0] INFO s.s.a.s.s.PrintFunction - Thread-20-b-0.99--value: 2016-02-05T17:20:48.282+0800,T(o2KnFxtGB0Tlp8
56162 [Thread-20-b-0] INFO s.s.a.s.s.PrintFunction - Scheme data size: 1
56162 [Thread-20-b-0] INFO s.s.a.s.s.PrintFunction - Thread-20-b-0.99--value: 2016-02-05T17:20:48.282+0800,T(o2KnFxtGB0Tlp8
I'm sorry this my mistake. Just found a bug in Kryo deserialize class, there exist an local scope parameter, so it can be over write in multi thread environment. Not change the parameter in party scope, the code run well.
reference code see blow:
public class KryoSerializer<T extends BasicEvent> extends Serializer<T> implements Serializable {
private static final long serialVersionUID = -4684340809824908270L;
// It's wrong set
//private T event;
public KryoSerializer(T event) {
this.event = event;
}
#Override
public void write(Kryo kryo, Output output, T event) {
event.write(output);
}
#Override
public T read(Kryo kryo, Input input, Class<T> type) {
T event = new T();
event.read(input);
return event;
}
}

Consuming Rabbit MQ messages using Eclipse on Tomcat

I am using Eclipse, Tomcat and Rabbit MQ.
I want to be able to consume messages of a queue as soon as they hit the queue. I have managed to do this using a Java class in Eclipse (see below), but have not been able to get this working when deploying the WAR file on the Tomcat server.
package org.com.hello;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.QueueingConsumer;
public class HelloRecv {
public static void main(String[] argv)
throws java.io.IOException,
java.lang.InterruptedException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("172.24.3.53");
factory.setPort(6672);
factory.setUsername("user");
factory.setPassword("password");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("q1", true, false, false, null);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume("q1", true, consumer);
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println(" [x] Received '" + message + "'");
}
}
}
Is there something I need to add like a web.xml file and if so, what should I add to this file?
Create a war application using eclipse:
you can see this video:
https://www.youtube.com/watch?v=fk22hQz9L_M
or googling then copy you code inside a servlet. You should use the init method.
an pseudo code:
public class YourServlet extends HttpServlet {
int count;
public void init(ServletConfig config) throws ServletException {
super.init(config);
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("172.24.3.53");
factory.setPort(6672);
factory.setUsername("user");
factory.setPassword("password");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("q1", true, false, false, null);
/// you shoud put the consumer inside a thread.
channel.basicConsume("q1", true, new DefaultConsumer(){
/// here you should use Default consumer and not QueueingConsumer because is blocking
});
}
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
.....
}
}
See also DefaultConsumer
Hope it helps

Call a method after jobss started

Hi i am using struts 2 and want to call a method just after when server is up.
as on server startup we can use FILTER DISPATCHER.
i am using jax ws . and i am deploying my jax client and endpoint project on same jboss server.
How to solve this
Plz help
You can implement a ServletContextListener to respond to the servlet starting up.
Create your implementation like so:
public class SimpleInitializer implements ServletContextListener {
#Override
public void contextInitialized(ServletContextEvent sce) {
//Place your startup logic here.
}
#Override
public void contextDestroyed(ServletContextEvent sce) {
}
}
Then, include it in the web.xml, like so:
<listener>
<display-name>SIMPLE Startup Listener</display-name>
<listener-class>com.you.init.SimpleInitializer</listener-class>
</listener>
MBeanServerConnection server = (MBeanServerConnection)new InitialContext().lookup("jmx/rmi/RMIAdaptor");
ObjectName on = new ObjectName("jboss.system:type=Server");
Object var = server.getAttribute(on, "Started");
System.out.println(**var**);
One more thing you can do is run a thread and check the value of var in Filter Dispatcher. If it is true then call the web service and set the data into your Servlet Context, otherwise sleep the thread for a particular amount of time. Once the value you have retrieved Stop this thread.
// By Gaurav Kumar(SE at Skilrock Technology)
try{
MBeanServerConnection server = (MBeanServerConnection)new InitialContext().lookup("jmx/rmi/RMIAdaptor");
ObjectName on = new ObjectName("jboss.system:type=Server");
Object var = server.getAttribute(on, "Started");
System.out.println(var);
String serverURL = "http://gaurav-compaq-presario-c700-notebook-pc:8080/WServer?wsdl";
String message = "gaurav";
HashMap env = new HashMap();
String[] creds = new String[1];
creds[0] = message;
env.put(JMXConnector.CREDENTIALS, creds);
JMXServiceURL url = new JMXServiceURL(serverURL);
JMXConnector jmxc = JMXConnectorFactory.connect(url, env);
// Remember to call jmxc.close() when you are done with server connection.
MBeanServerConnection server1 = jmxc.getMBeanServerConnection();
System.out.println(server.getAttribute(new ObjectName("MyDomain:key=property"), "AnAttribute"));
server.invoke(new ObjectName("MyDomain:key=property"), "doSomething", new Object[0], new String[0]);
}catch(Exception e){
System.out.println(e);
}

Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file

I'm new to JMS and I'm studying the following example
public class SendRecvClient
{
static CountDown done = new CountDown(1);
QueueConnection conn;
QueueSession session;
Queue que;
public static class ExListener
implements MessageListener
{
public void onMessage(Message msg)
{
done.release();
TextMessage tm = (TextMessage) msg;
try {
System.out.println("onMessage, recv text=" + tm.getText());
} catch(Throwable t) {
t.printStackTrace();
}
}
}
public void setupPTP()
throws JMSException,
NamingException
{
InitialContext iniCtx = new InitialContext();
Object tmp = iniCtx.lookup("ConnectionFactory");
QueueConnectionFactory qcf = (QueueConnectionFactory) tmp;
conn = qcf.createQueueConnection();
que = (Queue) iniCtx.lookup("queue/testQueue");
session = conn.createQueueSession(false,
QueueSession.AUTO_ACKNOWLEDGE);
conn.start();
}
public void sendRecvAsync(String text)
throws JMSException,
NamingException
{
System.out.println("Begin sendRecvAsync");
// Setup the PTP connection, session
setupPTP();
// Set the async listener
QueueReceiver recv = session.createReceiver(que);
recv.setMessageListener(new ExListener());
// Send a text msg
QueueSender send = session.createSender(que);
TextMessage tm = session.createTextMessage(text);
send.send(tm);
System.out.println("sendRecvAsync, sent text=" + tm.getText());
send.close();
System.out.println("End sendRecvAsync");
}
public void stop()
throws JMSException
{
conn.stop();
session.close();
conn.close();
}
public static void main(String args[])
throws Exception
{
SendRecvClient client = new SendRecvClient();
client.sendRecvAsync("A text msg");
client.done.acquire();
client.stop();
System.exit(0);
}
}
I ran this in JBoss and it gave the following exception
Begin sendRecvAsync
Exception in thread "main" javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:645)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:325)
at javax.naming.InitialContext.lookup(InitialContext.java:392)
at se.cambio.jms.SendRecvClient.setupPTP(SendRecvClient.java:53)
at se.cambio.jms.SendRecvClient.sendRecvAsync(SendRecvClient.java:68)
at se.cambio.jms.SendRecvClient.main(SendRecvClient.java:95)
I think this is an error with JNDI name, but I couldn't find which xml file to edit in JBOSS to over come this problem. Please some one help me.