HornetQ connecting to a JMS server - jms

I am currently trying to create a JMS client for a JMS Server both using HornetQ. I did not code the server and I don't know much about hoy it works, I only know how to connect to it: no username, no password and the address is jnp://x.y.z.t:1099 .
I am trying to connect to the server without using JNDI and I am having some trouble. In fact I have found this example: http://anonsvn.jboss.org/repos/hornetq/trunk/examples/jms/instantiate-connection-factory/
and I don't know what do I need to change in the XML files and in the code to make it work.
I had this code, with JNDI:
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A simple polymorphic JMS producer which can work with Queues or Topics which
* uses JNDI to lookup the JMS connection factory and destination
*
*
*/
public final class SimpleProducer {
private static final Logger LOG = LoggerFactory.getLogger(SimpleProducer.class);
private SimpleProducer() {
}
/**
* #param args the destination name to send to and optionally, the number of
* messages to send
*/
public static void main(String[] args) {
Context jndiContext = null;
ConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
Destination destination = null;
MessageProducer producer = null;
String destinationName = null;
final int numMsgs;
if ((args.length < 1) || (args.length > 2)) {
LOG.info("Usage: java SimpleProducer <destination-name> [<number-of-messages>]");
System.exit(1);
}
destinationName = args[0];
LOG.info("Destination name is " + destinationName);
if (args.length == 2) {
numMsgs = (new Integer(args[1])).intValue();
} else {
numMsgs = 1;
}
/*
* Create a JNDI API InitialContext object
*/
try {
jndiContext = new InitialContext();
} catch (NamingException e) {
LOG.info("Could not create JNDI API context: " + e.toString());
System.exit(1);
}
/*
* Look up connection factory and destination.
*/
try {
connectionFactory = (ConnectionFactory)jndiContext.lookup("ConnectionFactory");
destination = (Destination)jndiContext.lookup(destinationName);
} catch (NamingException e) {
LOG.info("JNDI API lookup failed: " + e);
System.exit(1);
}
/*
* Create connection. Create session from connection; false means
* session is not transacted. Create sender and text message. Send
* messages, varying text slightly. Send end-of-messages message.
* Finally, close connection.
*/
try {
connection = connectionFactory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
producer = session.createProducer(destination);
TextMessage message = session.createTextMessage();
for (int i = 0; i < numMsgs; i++) {
message.setText("This is message " + (i + 1));
LOG.info("Sending message: " + message.getText());
producer.send(message);
}
/*
* Send a non-text control message indicating end of messages.
*/
producer.send(session.createMessage());
} catch (JMSException e) {
LOG.info("Exception occurred: " + e);
} finally {
if (connection != null) {
try {
connection.close();
} catch (JMSException e) {
}
}
}
}
}
with this jndi.properties file:
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url = jnp://x.y.z.t:1099
and everything worked fine. But now I need to do the same thing without JNDI.
The example I gave above (http://anonsvn.jboss.org/repos/hornetq/trunk/examples/jms/instantiate-connection-factory/) shoutd work, but I don't know what to change in the config to make it work, I have never used a JMS client this way, so I'm completelly lost!
These are the config files I'm talking about:
http://anonsvn.jboss.org/repos/hornetq/trunk/examples/jms/instantiate-connection-factory/server0/ . I coulnd't find on the net to what the files correpsond, I'm confused.
Also, the Java code is here:
http://anonsvn.jboss.org/repos/hornetq/trunk/examples/jms/instantiate-connection-factory/src/org/hornetq/jms/example/InstantiateConnectionFactoryExample.java
Thank you in advance
----- EDIT
This is the last vesion of my code:
import java.util.HashMap;
import java.util.Map;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.hornetq.api.core.TransportConfiguration;
import org.hornetq.api.jms.HornetQJMSClient;
import org.hornetq.api.jms.JMSFactoryType;
import org.hornetq.common.example.HornetQExample;
import org.hornetq.core.remoting.impl.netty.NettyConnectorFactory;
import org.hornetq.core.remoting.impl.netty.TransportConstants;
import org.hornetq.jms.client.HornetQConnectionFactory;
public class Snippet extends HornetQExample
{
public static void main(final String[] args)
{
new Snippet().run(args);
}
#Override
public boolean runExample() throws Exception
{
Connection connection = null;
try
{
// Step 1. Directly instantiate the JMS Queue object.
Queue queue = HornetQJMSClient.createQueue("exampleQueue");
// Step 2. Instantiate the TransportConfiguration object which contains the knowledge of what transport to use,
// The server port etc.
Map<String, Object> connectionParams = new HashMap<String, Object>();
connectionParams.put(TransportConstants.PORT_PROP_NAME, 5446);
//My server's port:
//connectionParams.put(TransportConstants.PORT_PROP_NAME, 1099);
TransportConfiguration transportConfiguration = new TransportConfiguration(NettyConnectorFactory.class.getName(),
connectionParams);
// Step 3 Directly instantiate the JMS ConnectionFactory object using that TransportConfiguration
HornetQConnectionFactory cf = HornetQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, transportConfiguration);
// Step 4.Create a JMS Connection
connection = cf.createConnection();
// Step 5. Create a JMS Session
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// Step 6. Create a JMS Message Producer
MessageProducer producer = session.createProducer(queue);
// Step 7. Create a Text Message
TextMessage message = session.createTextMessage("This is a text message");
System.out.println("Sent message: " + message.getText());
// Step 8. Send the Message
producer.send(message);
// Step 9. Create a JMS Message Consumer
MessageConsumer messageConsumer = session.createConsumer(queue);
// Step 10. Start the Connection
connection.start();
// Step 11. Receive the message
TextMessage messageReceived = (TextMessage)messageConsumer.receive(5000);
System.out.println("Received message: " + messageReceived.getText());
return true;
}
finally
{
if (connection != null)
{
connection.close();
}
}
}
}
This is my hornetq-beans.xml (I disable JNDI)
<?xml version="1.0" encoding="UTF-8"?>
<deployment xmlns="urn:jboss:bean-deployer:2.0">
<bean name="Naming" class="org.jnp.server.NamingBeanImpl"/>
<!-- JNDI server. Disable this if you don't want JNDI -->
<!-- <bean name="JNDIServer" class="org.jnp.server.Main">
<property name="namingInfo">
<inject bean="Naming"/>
</property>
<property name="port">1099</property>
<!-- <property name="bindAddress">localhost</property>
<property name="bindAddress">jnp://X.Y.Z.T</property>
<property name="rmiPort">1098</property>
<!-- <property name="rmiBindAddress">localhost</property>
<property name="bindAddress">jnp://X.Y.Z.T</property>
</bean>-->
<!-- MBean server -->
<bean name="MBeanServer" class="javax.management.MBeanServer">
<constructor factoryClass="java.lang.management.ManagementFactory"
factoryMethod="getPlatformMBeanServer"/>
</bean>
<!-- The core configuration -->
<bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration"/>
<!-- The security manager -->
<bean name="HornetQSecurityManager" class="org.hornetq.spi.core.security.HornetQSecurityManagerImpl">
<start ignored="true"/>
<stop ignored="true"/>
</bean>
<!-- The core server -->
<bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
<constructor>
<parameter>
<inject bean="Configuration"/>
</parameter>
<parameter>
<inject bean="MBeanServer"/>
</parameter>
<parameter>
<inject bean="HornetQSecurityManager"/>
</parameter>
</constructor>
<start ignored="true"/>
<stop ignored="true"/>
</bean>
<!-- The JMS server -->
<bean name="JMSServerManager" class="org.hornetq.jms.server.impl.JMSServerManagerImpl">
<constructor>
<parameter>
<inject bean="HornetQServer"/>
</parameter>
</constructor>
</bean>
</deployment>
and my hornetq-jms.xml (same as in the example)
<configuration xmlns="urn:hornetq"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:hornetq /schema/hornetq-jms.xsd">
<!--the queue used by the example-->
<queue name="exampleQueue">
<entry name="/queue/exampleQueue"/>
</queue>
</configuration>
hornetq-users.xml (There is no need to have users to connect to the JMS server, so I commented it):
<configuration xmlns="urn:hornetq" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:hornetq /schema/hornetq-users.xsd">
<!-- the default user. this is used where username is null
<defaultuser name="guest" password="guest">
<role name="guest"/>
</defaultuser>-->
</configuration>
My hornetq-configuratio.xml: I am not sur whether I have to put jnp:// in the connectors and acceptors or not. Actually I don't really get much of this....
<configuration xmlns="urn:hornetq"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd">
<!-- Connectors -->
<connectors>
<connector name="netty-connector">
<factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
<param key="host" value="jnp://X.Y.Z.T"/>
<param key="port" value="5445"/>
</connector>
</connectors>
<!-- Acceptors -->
<acceptors>
<acceptor name="netty-acceptor">
<factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
<param key="host" value="jnp://X.Y.Z.T"/>
<param key="port" value="5445"/>
</acceptor>
</acceptors>
<!-- Other config -->
<security-settings>
<!--security for example queue-->
<security-setting match="jms.queue.exampleQueue">
<permission type="createDurableQueue" roles="guest"/>
<permission type="deleteDurableQueue" roles="guest"/>
<permission type="createNonDurableQueue" roles="guest"/>
<permission type="deleteNonDurableQueue" roles="guest"/>
<permission type="consume" roles="guest"/>
<permission type="send" roles="guest"/>
</security-setting>
</security-settings>
</configuration>
What I get with this code is:
HornetQException[errorCode=2 message=Cannot connect to server(s). Tried with all available servers.]
at org.hornetq.core.client.impl.ServerLocatorImpl.createSessionFactory(ServerLocatorImpl.java:619)
at org.hornetq.jms.client.HornetQConnectionFactory.createConnectionInternal(HornetQConnectionFactory.java:601)
I am using version 2.2.2, by the way ;)

If you want to use HornetQ's native client, look at these documents
http://docs.jboss.org/hornetq/2.2.2.Final/user-manual/en/html_single/#d0e1611
This will likely also help, with direct connections
http://docs.jboss.org/hornetq/2.2.2.Final/user-manual/en/html_single/#d0e2387
You'll want to use their local core client examples.

Related

Is it possible to create a new RabbitMQ queue from a proxy in WSO2 ESB that previously didn’t exist?

We are using WSO2 with RabbitMQ in our project. One requirement is that the consumer of RabbitMQ should generate the queue in case it did not previously exist.
We make the following proxy (without creating the "queue" queue previously in the Rabbit broker):
<?xml version="1.0" encoding="UTF-8"?>
<proxy name="AMQPProxy3" startOnLoad="true" trace="enable" transports="rabbitmq" xmlns="http://ws.apache.org/ns/synapse">
<target>
<inSequence>
<log level="full"/>
<property name="OUT_ONLY" scope="default" type="STRING" value="true"/>
<property name="FORCE_SC_ACCEPTED" scope="axis2" type="STRING" value="true"/>
<send>
<endpoint>
<address uri="http://localhost:8080/greeting"/>
</endpoint>
</send>
</inSequence>
<outSequence/>
<faultSequence/>
</target>
<parameter name="rabbitmq.queue.name">queue</parameter>
<parameter name="rabbitmq.connection.factory">AMQPConnectionFactory</parameter>
</proxy>
The ESB throws the following exception:
TID: [-1] [] [2017-08-25 13:23:06,139] ERROR {org.apache.axis2.transport.rabbitmq.ServiceTaskManager} - Error, Connection already closed AMQPProxy3, Listner id - 302 {org.apache.axis2.transport.rabbitmq.ServiceTaskManager}
com.rabbitmq.client.AlreadyClosedException: channel is already closed due to channel error; protocol method: #method(reply-code=404, reply-text=NOT_FOUND - no queue 'queue' in vhost '/', class-id=50, method-id=10)
In this case, the RabbitMQ consumer using the ESB does not create the queue in case it does not exist.
However, if we use a Java project that uses amqp-client-4.0.2.jar (Java library that gives us the official page of Rabbit) that consumer is able to create the queue.
package com.ing.rabbitmq;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class Send2 {
private final static String QUEUE_NAME = "queue";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "{\"id\":100,\"content\":\"Manolito\"}";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
channel.close();
connection.close();
}
}
Could we get the ESB to create the queue just like if we used the java client (amqp-client-4.0.2.jar)?
I think it should be possible with WSO2 ESB.
Try setting out the following property in your proxy configuration.
<parameter name="rabbitmq.queue.autodeclare">true</parameter>
If that not works, please let me know the WSO2 ESB version you are using.

Dynamically provide directory and file name to ftp outbound gateway

We have a requirement for the FTP client to download a file whose name and directory is provided at run-time. So, the FTP client may be asked to download file1.txt from foo1/foo2 directory path on the remote server.
We do have a solution using Spring Integration FTP outbound gateway. With this solution to make it dynamic:
the ApplicationContext for the gateway is created
the gateway properties get set using file name and remote directory path
the file is downloaded
the ApplicationContext is closed.
What we're not happy about is that the ApplicationContext is created and closed every time which obviously affects performance. Is there a way to dynamically pass the file name and the directory path to the gateway without reloading the Appplication Context every time?
Your help will be greatly appreciated.
Here's the main code and configuration:
package com.cvc.ipcdservice.ftp;
import java.util.List;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.StandardEnvironment;
public class DynamicFtpClient {
private static final Logger LOGGER = LoggerFactory
.getLogger(DynamicFtpClient.class);
public void download(final FtpMetaData ftpMetaData) {
final ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext(
new String[] { "/META-INF/spring/integration/FtpOutboundGateway-context.xml" },
false);
setEnvironment(ctx, ftpMetaData);
ctx.refresh();
final ToFtpFlowGateway toFtpFlow = ctx.getBean(ToFtpFlowGateway.class);
// execute the flow (mget to download from FTP server)
final List<Boolean> downloadResults = toFtpFlow.mGetFiles("/");
LOGGER.info(
"Completed downloading from remote FTP server. ftpMetaData:{}, downloadResults.size:{} ",
ftpMetaData, downloadResults.size());
ctx.close();
}
/**
* Populate {#code ConfigurableApplicationContext} with Provider-specific
* FTP properties.
*
* #param ctx
* #param customer
*/
private void setEnvironment(final ConfigurableApplicationContext ctx,
final FtpMetaData ftpMetaData) {
final StandardEnvironment env = new StandardEnvironment();
final Properties props = new Properties();
// populate properties for customer
props.setProperty("ftp.host", ftpMetaData.getHost());
props.setProperty("ftp.port", ftpMetaData.getPort());
props.setProperty("ftp.userid", ftpMetaData.getUserName());
props.setProperty("ftp.password", ftpMetaData.getPassword());
// props.setProperty("remote.directory", "/");
// WARNING: the file name pattern has to be surrounded by single-quotes
props.setProperty("ftp.remote.filename.pattern",
"'" + ftpMetaData.getFileNamePattern() + "'");
props.setProperty("ftp.local.dir", ftpMetaData.getLocalDirectory());
final PropertiesPropertySource pps = new PropertiesPropertySource(
"ftpprops", props);
env.getPropertySources().addLast(pps);
ctx.setEnvironment(env);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-ftp="http://www.springframework.org/schema/integration/ftp"
xsi:schemaLocation="http://www.springframework.org/schema/integration/ftp http://www.springframework.org/schema/integration/ftp/spring-integration-ftp.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder/>
<int:gateway id="gw" service-interface="com.cvc.ipcdservice.ftp.ToFtpFlowGateway"
default-request-channel="inbound"/>
<bean id="ftpSessionFactory"
class="org.springframework.integration.ftp.session.DefaultFtpSessionFactory">
<property name="host" value="${ftp.host}"/>
<property name="port" value="${ftp.port}"/>
<property name="username" value="${ftp.userid}"/>
<property name="password" value="${ftp.password}"/>
</bean>
<int-ftp:outbound-gateway id="gatewayGET"
local-directory="${ftp.local.dir}"
session-factory="ftpSessionFactory"
request-channel="inbound"
command="mget"
command-options="-P"
expression="${ftp.remote.filename.pattern}"/>
</beans>
There is no need to create the context for each request.
Instead of using a literal for the expression:
props.setProperty("ftp.remote.filename.pattern",
"'" + ftpMetaData.getFileNamePattern() + "'");
Use an expression based on the request; e.g.
props.setProperty("ftp.remote.filename.pattern",
"payload");
Then simply send the required path in your gateway call...
final List<Boolean> downloadResults = toFtpFlow.mGetFiles("/some/path/*.txt");

Receiving JMS messages via Spring integration inbound adapter randomly fails

I am new to this Spring Integration and JMS and i started playing with it. In here i want to create plain jms message via activemq and receive it through spring inbound adapter(message driven).
following is my spring config file
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:stream="http://www.springframework.org/schema/integration/stream"
xmlns:jms="http://www.springframework.org/schema/integration/jms"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/stream
http://www.springframework.org/schema/integration/stream/spring-integration-stream.xsd>
http://www.springframework.org/schema/integration/jms
http://www.springframework.org/schema/integration/jms/spring-integration-jms.xsd">
<!-- jms beans -->
<beans:bean id="jms.msgQueue" class="org.apache.activemq.command.ActiveMQQueue">
<beans:constructor-arg value="MSG_QUEUE" />
</beans:bean>
<beans:bean name="jms.connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<beans:property name="brokerURL" value="tcp://localhost:61616" />
</beans:bean>
<!-- spring integration beans -->
<channel id="channels.jms.allMessages">
<queue capacity="1000" />
</channel>
<jms:message-driven-channel-adapter id="adapters.jms.msgAdapter"
connection-factory="jms.connectionFactory"
destination="jms.msgQueue"
channel="channels.jms.allMessages" />
and this is my testing class
package com.bst.jms;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.Message;
import org.springframework.integration.core.PollableChannel;
public class TestActiveMQ {
public static void main(String[] args){
try{
AbstractApplicationContext context = new ClassPathXmlApplicationContext("app-context.xml");
ConnectionFactory connectionFactory = (ConnectionFactory)context.getBean("jms.connectionFactory");
Destination destination = (Destination)context.getBean("jms.msgQueue");
PollableChannel msgChannel = (PollableChannel) context.getBean("channels.jms.allMessages", PollableChannel.class );
Connection connection = connectionFactory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(destination);
TextMessage textMessage = session.createTextMessage();
textMessage.setText("Message from JMS");
producer.send(textMessage);
System.out.println("--------------- Message Sending ------------------------");
Message<?> received = msgChannel.receive();
String payload = (String) received.getPayload();
System.out.println("Receving message = " + payload);
}catch(JMSException ex){
System.out.println("----------- JMS Exception --------------");
}
}
}
But the thing is i can not guarantee the delivery. some times the program can not receive the message and some tomes it succeeds with some warnings like
Setup of JMS message listener invoker failed for destination 'queue://MSG_QUEUE' - trying to recover. Cause: Connection reset
Could not refresh JMS Connection for destination 'queue://MSG_QUEUE' - retrying in 5000 ms. Cause: Could not connect to broker URL: tcp://localhost:61616. Reason: java.net.ConnectException: Connection refused: connect
Could not refresh JMS Connection for destination 'queue://MSG_QUEUE' - retrying in 5000 ms. Cause: Could not connect to broker URL: tcp://localhost:61616. Reason: java.net.ConnectException: Connection refused: connect
This occurs few times before it succeeds.
Do you guys have any idea about this.
appreciate your help.
thanks,
keth
This just means the broker isn't running when the listener container starts. When using a tcp:// URL you should run the broker in it's own context (or another JVM) before creating this context.
I have tested these code in my STS its working fine .
The only problem in your side is , first start message Broker (say ActiveMQ) then run your project, you can get your required output.
Thanks.

Use of Spring Framework for RabbitMQ is reducing the performance

I have created a producer, which was using com.rabbitmq.client.connectionFactory and was sending 1,000,000 messages (40 Bytes) in 100 seconds.
But now I want an spring abstraction. I was unable to use com.rabbitmq.client.connectionFactory rather I had to use org.springframework.amqp.rabbit.connection.SingleConnectionFactory. Using this connection factory only 100,000 messages (40 Bytes) are send to the broker in 100 seconds.
Does anybody have experience why the performance is reduced so much (around 90%).
The code using "import com.rabbitmq.client.ConnectionFactory;" is ->
package Multiple_queues_multiple_consumers;
import java.io.IOException;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class Producer {
private static Connection myConnection;
private static Channel myChannel;
public static String myQueueName;
public static void main(String[] args) throws IOException {
long startTime=0;
int count=0;
ConnectionFactory myFactory=new ConnectionFactory();
myFactory.setHost("localhost");
try {
myConnection = myFactory.newConnection();
myChannel = myConnection.createChannel();
String myExchange = "wxyzabc";
String myBody = "This is a message : message numberxxxxxx";
String myRoutingKey = "RoutingKey";
myQueueName = "new_Queue";
myChannel.exchangeDeclare(myExchange, "direct", true, false, null);
myChannel.queueDeclare(myQueueName, true, false, false, null);
myChannel.queueBind(myQueueName, myExchange, myRoutingKey);
startTime=System.currentTimeMillis();
AMQP.BasicProperties properties = new AMQP.BasicProperties();
properties.setDeliveryMode(2);
startTime=System.currentTimeMillis();
while(count++<=10000){
myChannel.basicPublish(myExchange, myRoutingKey, true, true, properties, myBody.getBytes() );
}
System.out.println(System.currentTimeMillis()-startTime);
} catch (Exception e){
System.exit(0);
}
}
}
The code using SpringFramework is :->
Producer1.java
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Producer1 {
public static void main(String[] args) {
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("Producer1.xml");
AmqpAdmin amqpAdmin = context.getBean(RabbitAdmin.class);
Queue queue = new Queue("sampleQueue");
DirectExchange exchange = new DirectExchange("myExchange");
Binding binding = new Binding(queue, exchange, "");
amqpAdmin.declareQueue(queue);
amqpAdmin.declareExchange(exchange);
amqpAdmin.declareBinding(binding);
RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class);
String routingKey = "";
String myBody = "This is a message : message numberxxxxxx";
Message Msg = new Message(myBody.getBytes(), null);
int count=0;
long CurrTime = System.currentTimeMillis();
while(count++<=10000){
rabbitTemplate.send(routingKey, Msg);
//System.out.println("Message Sent");
}
System.out.println(System.currentTimeMillis()-CurrTime);
}
}
Producer1.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- Define a connectionFactory -->
<bean id="rabbitConnectionFactory" class="com.rabbitmq.client.ConnectionFactory">
<property name="host" value="localhost" />
</bean>
<bean id="connectionFactory" class="org.springframework.amqp.rabbit.connection.SingleConnectionFactory">
<constructor-arg ref="rabbitConnectionFactory"/>
</bean>
<!-- Tell the Admin bean about that connectionFactory and initialize it, create a queue and an exchange on Rabbit Broker using the RabbitTemplate provided by Spring framework-Rabbit APIs -->
<bean id="Admin" class="org.springframework.amqp.rabbit.core.RabbitAdmin">
<constructor-arg ref="connectionFactory" />
</bean>
<bean id="rabbitTemplate" class="org.springframework.amqp.rabbit.core.RabbitTemplate"
p:connectionFactory-ref="connectionFactory"
p:routingKey="myRoutingKey"
p:exchange="myExchange" />
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Define a connectionFactory -->
<bean id="connectionFactory" class="com.rabbitmq.client.connectionFactory">
<constructor-arg value="localhost" />
<property name="username" value="guest" />
<property name="password" value="guest" />
</bean>
<bean id="Admin" class="org.springframework.amqp.rabbit.core.RabbitAdmin">
<constructor-arg ref="connectionFactory" />
</bean>
</beans>
Using this xml file, the error appears saying org.springframework.amqp.rabbit.core.RabbitAdmin could not cast com.rabbitmq.client.connectionFactory for connectionfactory bean.
The exact error is: "nested exception is java.lang.IllegalStateException: Cannot convert value of type [com.rabbitmq.client.ConnectionFactory] to required type [org.springframework.amqp.rabbit.core.RabbitTemplate]: no matching editors or conversion strategy found" .
Hence i have to use bean:
<bean id="connectionFactory"
class="org.springframework.amqp.rabbit.connection.SingleConnectionFactory">
</bean>
Are you sure that you used the same Rabbit MQ broker? Could you be using a broker on a different server, or an upgraded/downgraded version of RabbitMQ?
The other thing to look at is your jvm. Is it possible that you don't have enough memory configured and now the garbage collector is thrashing? Run top and see if the jvm's memory usage is close to the configured memory size.
Are you using an old version of RabbitMQ. Lots of Linux distros include RabbitMQ 1.7.2 which is an old version that has problems with large numbers of messages. Large is hard to define because it depends on your RAM, but RabbitMQ does not like to use more than 40% of RAM because it needs to copy a persistence transaction log in order to process it and clean it for log rollover. This can cause RabbitMQ to crash, and, of course, processing the huge logs will slow it down. RabbitMQ 2.4.1 handles the persister logs much better, in smaller chunks, and it also has much, much faster message routing code.
This still sounds to me like a Java problem, either Spring is just a pig and is terribly inefficient, or you have not given your jvm enough RAM to avoid frequent gc runs. What setting are you using for -Xmx?

HornetQ Unable to validate user

I am using jboss AS 6 Final on ubuntu with hornetQ
I have created a new Queue on the server named Message Buffer Queue using the admin panel.
I get the following error:
Unable to validate user: guest for check type CONSUME for address jms.queue.MessageBufferQueue
Here are my files:
package org.jboss.ejb3timers.example;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.UUID;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueBrowser;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
public class TestClass {
ConnectionFactory Hconnection=null;
Queue q=null;
Connection Hconn=null;
Context lContext=null;
MessageConsumer messageConsumer=null;
MessageProducer messageProducer=null;
javax.jms.Session session=null;
/**
* #param args
*/
public void sendMessagetoJMS(String sender,String receiver,String Message,String smsc,String Credit,String userid,long ctime,String savenumber)
{
int count=0;
Hashtable<String, String> ht = new Hashtable<String, String>();
ht.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
ht.put(Context.PROVIDER_URL, "127.0.0.1");
ht.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
try{
lContext = new InitialContext(ht);
Hconnection = (ConnectionFactory) lContext.lookup("ConnectionFactory");
q = (Queue) lContext.lookup("queue/MessageBufferQueue");
Hconn = (Connection) Hconnection.createConnection("guest","guest");
session = Hconn.createSession(false, Session.AUTO_ACKNOWLEDGE);
messageProducer = session.createProducer(q);
/*
* Insert into Database
*/
UUID id=UUID.randomUUID();
Hconn.start();
textmsg msg = new textmsg();
msg.setReciever(receiver);
msg.setSender(sender);
msg.setText(Message);
msg.setSmsc(smsc);
msg.setCredit(Credit);
msg.setUserid(userid);
msg.setCtime(ctime);
msg.setId(id.toString());
ObjectMessage message = session.createObjectMessage();
message.setObject(msg);
messageProducer.send(message);
System.out.println("Message sent ");
Hconn.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
public int getQueueSize()
{
Hashtable<String, String> ht = new Hashtable<String, String>();
ht.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
ht.put(Context.PROVIDER_URL, "127.0.0.1");
ht.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
InitialContext ctx;
int numMsgs = 0;
try {
ctx = new InitialContext(ht);
QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.lookup("ConnectionFactory");
Queue queue = (Queue) ctx.lookup("queue/MessageBufferQueue");
QueueConnection queueConn = connFactory.createQueueConnection("guest","guest");
QueueSession queueSession = queueConn.createQueueSession(false,Session.AUTO_ACKNOWLEDGE);
QueueBrowser queueBrowser = queueSession.createBrowser(queue);
queueConn.start();
Enumeration e = queueBrowser.getEnumeration();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");;
String s=null;
while (e.hasMoreElements()) {
Message message = (Message) e.nextElement();
s = df.format(message.getJMSTimestamp());
System.out.println("=================1===================Timestamp it got to the queue"+s);
numMsgs++;
}
queueConn.close();
} catch (Exception e1) {
// TODO Auto-generated catch block
System.out.println(e1.getMessage());
}
return numMsgs;
}
public static void main(String[] args) {
int i = 0;
TestClass tc = new TestClass();
System.out.println(tc.getQueueSize());
tc.sendMessagetoJMS("jk", "gv", "Hey there", "somesmsc", "34", "thedon", 234233634, "2423487");
System.out.println(tc.getQueueSize());
}
}
My HornetQ config file is
<configuration xmlns="urn:hornetq"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd">
<!-- Make Queue Persistent -->
<persistence-enabled>true</persistence-enabled>
<log-delegate-factory-class-name>org.hornetq.integration.logging.Log4jLogDelegateFactory</log-delegate-factory-class-name>
<bindings-directory>${jboss.server.data.dir}/hornetq/bindings</bindings-directory>
<journal-directory>${jboss.server.data.dir}/hornetq/journal</journal-directory>
<!-- Default journal file size is set to 1Mb for faster first boot -->
<journal-file-size>${hornetq.journal.file.size:1048576}</journal-file-size>
<!-- Default journal min file is 2, increase for higher average msg rates -->
<journal-min-files>${hornetq.journal.min.files:2}</journal-min-files>
<!-- create new user named guest as the default user -->
<defaultuser name="guest" password="guest">
<role name="guest"/>
</defaultuser>
<!-- create new user named admin with admin stuff -->
<user name="admin" password="admin">
<role name="admin"/>
</user>
<large-messages-directory>${jboss.server.data.dir}/hornetq/largemessages</large-messages-directory>
<paging-directory>${jboss.server.data.dir}/hornetq/paging</paging-directory>
<connectors>
<connector name="netty">
<factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
<param key="host" value="${jboss.bind.address:localhost}"/>
<param key="port" value="${hornetq.remoting.netty.port:5445}"/>
</connector>
<connector name="netty-throughput">
<factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
<param key="host" value="${jboss.bind.address:localhost}"/>
<param key="port" value="${hornetq.remoting.netty.batch.port:5455}"/>
<param key="batch-delay" value="50"/>
</connector>
<connector name="in-vm">
<factory-class>org.hornetq.core.remoting.impl.invm.InVMConnectorFactory</factory-class>
<param key="server-id" value="${hornetq.server-id:0}"/>
</connector>
</connectors>
<acceptors>
<acceptor name="netty">
<factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
<param key="host" value="${jboss.bind.address:localhost}"/>
<param key="port" value="${hornetq.remoting.netty.port:5445}"/>
</acceptor>
<acceptor name="netty-throughput">
<factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
<param key="host" value="${jboss.bind.address:localhost}"/>
<param key="port" value="${hornetq.remoting.netty.batch.port:5455}"/>
<param key="batch-delay" value="50"/>
<param key="direct-deliver" value="false"/>
</acceptor>
<acceptor name="in-vm">
<factory-class>org.hornetq.core.remoting.impl.invm.InVMAcceptorFactory</factory-class>
<param key="server-id" value="0"/>
</acceptor>
</acceptors>
<security-settings>
<security-setting match="#">
<permission type="createNonDurableQueue" roles="guest"/>
<permission type="deleteNonDurableQueue" roles="guest"/>
<!-- Admin can create durable and non durable queues -->
<!-- Add permisions to make a durabe queue for guest -->
<permission type="createDurableQueue" roles="admin"/>
<!-- Add permisions to make a durabe queue for guest -->
<permission type="deleteDurableQueue" roles="admin"/>
<permission type="consume" roles="guest"/>
<permission type="send" roles="guest"/>
</security-setting>
</security-settings>
<address-settings>
<!--default for catch all-->
<address-setting match="#">
<dead-letter-address>jms.queue.DLQ</dead-letter-address>
<expiry-address>jms.queue.ExpiryQueue</expiry-address>
<redelivery-delay>0</redelivery-delay>
<max-size-bytes>10485760</max-size-bytes>
<message-counter-history-day-limit>10</message-counter-history-day-limit>
<address-full-policy>BLOCK</address-full-policy>
</address-setting>
</address-settings>
</configuration>
my stack trace is :
log4j:WARN No appenders could be found for logger (org.jnp.interfaces.TimedSocketFactory).
log4j:WARN Please initialize the log4j system properly.
Unable to validate user: guest for check type CONSUME for address jms.queue.MessageBufferQueue
0
javax.jms.JMSSecurityException: Unable to validate user: guest for check type SEND for address jms.queue.MessageBufferQueue
at org.hornetq.core.protocol.core.impl.ChannelImpl.sendBlocking(ChannelImpl.java:287)
at org.hornetq.core.client.impl.ClientProducerImpl.doSend(ClientProducerImpl.java:285)
at org.hornetq.core.client.impl.ClientProducerImpl.send(ClientProducerImpl.java:139)
at org.hornetq.jms.client.HornetQMessageProducer.doSend(HornetQMessageProducer.java:451)
at org.hornetq.jms.client.HornetQMessageProducer.send(HornetQMessageProducer.java:199)
at org.jboss.ejb3.timerservice.example.TestClass.sendMessagetoJMS(TestClass.java:70)
at org.jboss.ejb3.timerservice.example.TestClass.main(TestClass.java:117)
Caused by: HornetQException[errorCode=105 message=Unable to validate user: guest for check type SEND for address jms.queue.MessageBufferQueue]
... 7 more
Unable to validate user: guest for check type CONSUME for address jms.queue.MessageBufferQueue
0
11 Apr, 2011 7:35:54 PM org.hornetq.core.logging.impl.JULLogDelegate warn
WARNING: I'm closing a JMS connection you left open. Please make sure you close all JMS connections explicitly before letting them go out of scope!
What seems to be the problem the problem ?
it took me a long time to solve this issue, and the answer is the HornetQ reference documentation:
JBoss can be configured to allow client login, basically this is when a Java EE component such as a Servlet or EJB sets security credentials on the current security context and these are used throughout the call.
If you would like these credentials to be used by HornetQ when sending or consuming messages then set allowClientLogin to true. This will bypass HornetQ authentication and propgate the provided Security Context. If you would like HornetQ to authenticate using the propogated security then set the authoriseOnClientLogin to true also.
The important part is: if you would like these credentials to be used by HornetQ when sending or consuming messages then set allowClientLogin to true
In my case, for test purpose I disactivated authentication in my application, and thus the credentials were not propagated anymore in the security context.
While trying to create queues with
queueConnection = connectionFactory.createQueueConnection("guest", "guest");
I got the exception: HornetQException[errorCode=105 message=Unable to validate user: guest
And when trying to create queues with
queueConnection = connectionFactory.createQueueConnection();
I got the exception: HornetQException[errorCode=105 message=Unable to validate user: null
After setting allowClientLogin to true in $JBOSS_HOME/server//deploy/hornetq/hornetq-jboss-beans.xml, I finally succed in creating the queues.
<bean name="HornetQSecurityManager" class="org.hornetq.integration.jboss.security.JBossASSecurityManager">
<start ignored="true"/>
<stop ignored="true"/>
<depends>JBossSecurityJNDIContextEstablishment</depends>
<property name="allowClientLogin">true</property>
<property name="authoriseOnClientLogin">true</property>
</bean>
i'm having a similar problem with Jboss6 Final.
Are you using a security domain (for instance in your jboss.xml <security-domain>unirepo</security-domain>)?
Is the user "guest" "guest" authenticated in your security domain? (i know it shouldn't be necessary, but seem a weird behavior of Jboss 6).
You can also have a look here: https://issues.jboss.org/browse/JBAS-8895
and here: http://community.jboss.org/message/587605
It might be fixed in jboss 6.1 :(

Resources