Here are the examples of the java api org.apache.activemq.ActiveMQConnectionFactory.createConnection() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
136 Examples
19
View Complete Implementation : Listener.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
public static void main(String[] args) throws JMSException {
String user = env("APOLLO_USER", "admin");
String preplacedword = env("APOLLO_PreplacedWORD", "preplacedword");
String host = env("APOLLO_HOST", "localhost");
int port = Integer.parseInt(env("APOLLO_PORT", "61613"));
String destination = arg(args, 0, "event");
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://" + host + ":" + port);
Connection connection = factory.createConnection(user, preplacedword);
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination dest = new ActiveMQTopic(destination);
MessageConsumer consumer = session.createConsumer(dest);
long start = System.currentTimeMillis();
long count = 1;
System.out.println("Waiting for messages...");
while (true) {
Message msg = consumer.receive();
if (msg instanceof TextMessage) {
String body = ((TextMessage) msg).getText();
if ("SHUTDOWN".equals(body)) {
long diff = System.currentTimeMillis() - start;
System.out.println(String.format("Received %d in %.2f seconds", count, (1.0 * diff / 1000.0)));
break;
} else {
if (count != msg.getIntProperty("id")) {
System.out.println("mismatch: " + count + "!=" + msg.getIntProperty("id"));
}
count = msg.getIntProperty("id");
if (count == 0) {
start = System.currentTimeMillis();
}
if (count % 1000 == 0) {
System.out.println(String.format("Received %d messages.", count));
}
count++;
}
} else {
System.out.println("Unexpected message type: " + msg.getClreplaced());
}
}
connection.close();
}
19
View Complete Implementation : Producer.java
Copyright Apache License 2.0
Author : javahongxi
Copyright Apache License 2.0
Author : javahongxi
public static void main(String[] args) throws Exception {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");
Connection connection = factory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue("TEST.QUEUE");
MessageProducer producer = session.createProducer(queue);
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
for (int i = 0; i < 100; i++) {
TextMessage message = session.createTextMessage("hello world! " + i);
producer.send(message);
System.out.println(message);
}
producer.close();
}
19
View Complete Implementation : Consumer.java
Copyright Apache License 2.0
Author : javahongxi
Copyright Apache License 2.0
Author : javahongxi
public static void main(String[] args) throws Exception {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");
Connection connection = factory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue("TEST.QUEUE");
MessageConsumer consumer = session.createConsumer(queue);
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
System.out.println(message);
}
});
connection.start();
}
19
View Complete Implementation : AbstractJMSPublisherTest.java
Copyright Apache License 2.0
Author : fcrepo4
Copyright Apache License 2.0
Author : fcrepo4
@Test
public void testAcquireConnections() throws JMSException {
when(mockConnections.createConnection()).thenReturn(mockConn);
when(mockConn.createSession(false, AUTO_ACKNOWLEDGE)).thenReturn(mockJmsSession);
testJMSPublisher.acquireConnections();
verify(mockBus).register(any());
}
19
View Complete Implementation : TopicProducer.java
Copyright Apache License 2.0
Author : shuangyueliao
Copyright Apache License 2.0
Author : shuangyueliao
public static void main(String[] args) throws JMSException {
// 连接到ActiveMQ服务器
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("username", "preplacedword", "tcp://127.0.0.1:61616");
Connection connection = factory.createConnection();
connection.start();
Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
// 创建主题
Topic topic = session.createTopic("slimsmart.topic.test");
MessageProducer producer = session.createProducer(topic);
// NON_PERSISTENT 非持久化 PERSISTENT 持久化,发送消息时用使用持久模式
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
TextMessage message = session.createTextMessage();
message.setText("topic 消息。");
message.setStringProperty("property", "消息Property");
// 发布主题消息
producer.send(message);
System.out.println("Sent message: " + message.getText());
session.commit();
session.close();
connection.close();
}
19
View Complete Implementation : Publisher.java
Copyright MIT License
Author : chipster
Copyright MIT License
Author : chipster
public static void main(String[] args) throws JMSException {
String user = env("ACTIVEMQ_USER", "admin");
String preplacedword = env("ACTIVEMQ_PreplacedWORD", "preplacedword");
String host = env("ACTIVEMQ_HOST", "localhost");
int port = Integer.parseInt(env("ACTIVEMQ_PORT", "61616"));
String destination = arg(args, 0, "event");
int messages = 10000;
int size = 256;
String DATA = "abcdefghijklmnopqrstuvwxyz";
String body = "";
for (int i = 0; i < size; i++) {
body += DATA.charAt(i % DATA.length());
}
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://" + host + ":" + port);
Connection connection = factory.createConnection(user, preplacedword);
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination dest = new ActiveMQTopic(destination);
MessageProducer producer = session.createProducer(dest);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
for (int i = 1; i <= messages; i++) {
TextMessage msg = session.createTextMessage(body);
msg.setIntProperty("id", i);
producer.send(msg);
if ((i % 1000) == 0) {
System.out.println(String.format("Sent %d messages", i));
}
}
producer.send(session.createTextMessage("SHUTDOWN"));
connection.close();
}
19
View Complete Implementation : BasicOpenWireTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
protected Connection createConnection() throws JMSException {
return factory.createConnection();
}
19
View Complete Implementation : Listener.java
Copyright MIT License
Author : chipster
Copyright MIT License
Author : chipster
public static void main(String[] args) throws JMSException {
String user = env("ACTIVEMQ_USER", "admin");
String preplacedword = env("ACTIVEMQ_PreplacedWORD", "preplacedword");
String host = env("ACTIVEMQ_HOST", "localhost");
int port = Integer.parseInt(env("ACTIVEMQ_PORT", "61616"));
String destination = arg(args, 0, "event");
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://" + host + ":" + port);
Connection connection = factory.createConnection(user, preplacedword);
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination dest = new ActiveMQTopic(destination);
MessageConsumer consumer = session.createConsumer(dest);
long start = System.currentTimeMillis();
long count = 1;
System.out.println("Waiting for messages...");
while (true) {
Message msg = consumer.receive();
if (msg instanceof TextMessage) {
String body = ((TextMessage) msg).getText();
if ("SHUTDOWN".equals(body)) {
long diff = System.currentTimeMillis() - start;
System.out.println(String.format("Received %d in %.2f seconds", count, (1.0 * diff / 1000.0)));
break;
} else {
if (count != msg.getIntProperty("id")) {
System.out.println("mismatch: " + count + "!=" + msg.getIntProperty("id"));
}
count = msg.getIntProperty("id");
if (count == 0) {
start = System.currentTimeMillis();
}
if (count % 1000 == 0) {
System.out.println(String.format("Received %d messages.", count));
}
count++;
}
} else {
System.out.println("Unexpected message type: " + msg.getClreplaced());
}
}
connection.close();
}
19
View Complete Implementation : JMSHelperActiveMQ.java
Copyright Creative Commons Zero v1.0 Universal
Author : kgary
Copyright Creative Commons Zero v1.0 Universal
Author : kgary
public static Connection getJMSConnection() throws Exception {
// Create a ConnectionFactory
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");
return connectionFactory.createConnection();
}
19
View Complete Implementation : AMQSinkTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@BeforeEach
public void before() throws Exception {
connectionFactory = mock(ActiveMQConnectionFactory.clreplaced);
producer = mock(MessageProducer.clreplaced);
session = mock(Session.clreplaced);
connection = mock(Connection.clreplaced);
destination = mock(Destination.clreplaced);
message = mock(BytesMessage.clreplaced);
when(connectionFactory.createConnection()).thenReturn(connection);
when(connection.createSession(anyBoolean(), anyInt())).thenReturn(session);
when(session.createProducer(null)).thenReturn(producer);
when(session.createBytesMessage()).thenReturn(message);
serializationSchema = new SimpleStringSchema();
AMQSinkConfig<String> config = new AMQSinkConfig.AMQSinkConfigBuilder<String>().setConnectionFactory(connectionFactory).setDestinationName(DESTINATION_NAME).setSerializationSchema(serializationSchema).build();
amqSink = new AMQSink<>(config);
amqSink.open(new Configuration());
}
19
View Complete Implementation : TwoBrokerTopicSendReceiveTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@Override
protected Connection createSendConnection() throws JMSException {
return sendFactory.createConnection();
}
19
View Complete Implementation : Publisher.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
public static void main(String[] args) throws JMSException {
String user = env("APOLLO_USER", "admin");
String preplacedword = env("APOLLO_PreplacedWORD", "preplacedword");
String host = env("APOLLO_HOST", "localhost");
int port = Integer.parseInt(env("APOLLO_PORT", "61613"));
String destination = arg(args, 0, "event");
int messages = 10000;
int size = 256;
String DATA = "abcdefghijklmnopqrstuvwxyz";
String body = "";
for (int i = 0; i < size; i++) {
body += DATA.charAt(i % DATA.length());
}
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://" + host + ":" + port);
Connection connection = factory.createConnection(user, preplacedword);
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination dest = new ActiveMQTopic(destination);
MessageProducer producer = session.createProducer(dest);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
for (int i = 1; i <= messages; i++) {
TextMessage msg = session.createTextMessage(body);
msg.setIntProperty("id", i);
producer.send(msg);
if ((i % 1000) == 0) {
System.out.println(String.format("Sent %d messages", i));
}
}
producer.send(session.createTextMessage("SHUTDOWN"));
connection.close();
}
19
View Complete Implementation : TwoBrokerTopicSendReceiveTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@Override
protected Connection createReceiveConnection() throws JMSException {
return receiveFactory.createConnection();
}
18
View Complete Implementation : LoggingActiveMQServerPluginOpenWireTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@Override
protected Connection createActiveMQConnection() throws JMSException {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616?jms.watchTopicAdvisories=false");
return factory.createConnection();
}
18
View Complete Implementation : JMSWebSocketConnectionTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
protected void sendLargeMessageViaOpenWire() throws Exception {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(getBrokerOpenWireConnectionURI());
doSendLargeMessageViaOpenWire(factory.createConnection());
}
18
View Complete Implementation : AMQSourceTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@SuppressWarnings("unchecked")
@BeforeEach
public void before() throws Exception {
connectionFactory = mock(ActiveMQConnectionFactory.clreplaced);
session = mock(Session.clreplaced);
connection = mock(Connection.clreplaced);
destination = mock(Destination.clreplaced);
consumer = mock(MessageConsumer.clreplaced);
context = mock(SourceFunction.SourceContext.clreplaced);
message = mock(BytesMessage.clreplaced);
when(connectionFactory.createConnection()).thenReturn(connection);
when(connection.createSession(anyBoolean(), anyInt())).thenReturn(session);
when(consumer.receive(anyInt())).thenReturn(message);
when(session.createConsumer(any(Destination.clreplaced))).thenReturn(consumer);
when(context.getCheckpointLock()).thenReturn(new Object());
when(message.getJMSMessageID()).thenReturn(MSG_ID);
deserializationSchema = new SimpleStringSchema();
AMQSourceConfig<String> config = new AMQSourceConfig.AMQSourceConfigBuilder<String>().setConnectionFactory(connectionFactory).setDestinationName(DESTINATION_NAME).setDeserializationSchema(deserializationSchema).setRunningChecker(new SingleLoopRunChecker()).build();
amqSource = new AMQSource<>(config);
amqSource.setRuntimeContext(createRuntimeContext());
amqSource.open(new Configuration());
amqSource.initializeState(new FunctionInitializationContext() {
@Override
public boolean isRestored() {
return false;
}
@Override
public OperatorStateStore getOperatorStateStore() {
return mock(OperatorStateStore.clreplaced);
}
@Override
public KeyedStateStore getKeyedStateStore() {
return mock(KeyedStateStore.clreplaced);
}
});
}
18
View Complete Implementation : JmsWSConnectionTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
protected void sendLargeMessageViaOpenWire() throws Exception {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?create=false");
doSendLargeMessageViaOpenWire(factory.createConnection());
}
18
View Complete Implementation : JmsTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
public void testProxy() throws Exception {
// Create a Session
final Connection connection = connectionFactory.createConnection();
try {
connection.start();
final Destination requestQueue = createListener(connection);
createSender(connection, requestQueue);
} finally {
MdbUtil.close(connection);
}
}
18
View Complete Implementation : JMSMessager.java
Copyright GNU General Public License v2.0
Author : geonetwork
Copyright GNU General Public License v2.0
Author : geonetwork
public void sendMessage(String queue, ApplicationEvent event) {
try {
// Create a ConnectionFactory
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(this.jmsUrl);
// Create a Connection
Connection connection = connectionFactory.createConnection();
connection.start();
try {
// Create a Session
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
try {
// Create the destination (Topic or Queue)
Destination destination = session.createQueue(queue);
// Create a MessageProducer from the Session to the Topic or Queue
MessageProducer producer = session.createProducer(destination);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
// Create a messages
ObjectMessage message = session.createObjectMessage(event);
// Tell the producer to send the message
producer.send(message);
} finally {
session.close();
}
} finally {
connection.close();
}
} catch (Exception e) {
// TODO : dedicated logger needed
System.out.println("Caught: " + e);
e.printStackTrace();
}
}
18
View Complete Implementation : QueueUtils.java
Copyright MIT License
Author : intuit
Copyright MIT License
Author : intuit
public static Connection getConnection() {
try {
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");
Connection connection = connectionFactory.createConnection();
connection.start();
return connection;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
18
View Complete Implementation : ConsumerPersistent.java
Copyright Apache License 2.0
Author : shuangyueliao
Copyright Apache License 2.0
Author : shuangyueliao
public static void main(String[] args) throws JMSException {
String clientId = "client_id2";
// 连接到ActiveMQ服务器
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("username", "preplacedword", "tcp://127.0.0.1:61616");
Connection connection = factory.createConnection();
// 客户端ID,持久订阅需要设置
connection.setClientID(clientId);
connection.start();
Session session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
// 创建主题
Topic topic = session.createTopic("slimsmart.topic.test");
// 创建持久订阅,指定客户端ID。
MessageConsumer consumer = session.createDurableSubscriber(topic, clientId);
consumer.setMessageListener(new MessageListener() {
// 订阅接收方法
public void onMessage(Message message) {
TextMessage tm = (TextMessage) message;
try {
System.out.println("Received message: " + tm.getText() + ":" + tm.getStringProperty("property"));
} catch (JMSException e) {
e.printStackTrace();
}
}
});
}
18
View Complete Implementation : DoSTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
public void testInvalidAuthentication() throws Throwable {
// with failover reconnect, we don't expect this thread to complete
// but periodically the failure changes from ExceededMaximumConnectionsException on the broker
// side to a SecurityException.
// A failed to authenticated but idle connection (dos style) is aborted by the inactivity monitor
// since useKeepAlive=false
final AtomicBoolean done = new AtomicBoolean(false);
Thread thread = new Thread() {
Connection connection = null;
@Override
public void run() {
for (int i = 0; i < 1000 && !done.get(); i++) {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();
try {
// Bad preplacedword
connection = factory.createConnection("bad", "krap");
connection.start();
fail("Expected exception.");
} catch (JMSException e) {
// ignore exception and don't close
e.printStackTrace();
}
}
}
};
thread.start();
// run dos for a while
TimeUnit.SECONDS.sleep(10);
LOG.info("trying genuine connection ...");
// verify a valid connection can work with one of the 2 allowed connections provided it is eager!
// it could take a while as it is competing with the three other reconnect threads.
// wonder if it makes sense to serialise these reconnect attempts on an executor
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("failover:(tcp://127.0.0.1:61616)?useExponentialBackOff=false&reconnectDelay=10");
Connection goodConnection = factory.createConnection("user", "preplacedword");
goodConnection.start();
goodConnection.close();
LOG.info("giving up on DOS");
done.set(true);
}
18
View Complete Implementation : StartAndStopBrokerTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
public void testStartupShutdown() throws Exception {
// This systemproperty is used if we dont want to
// have persistence messages as a default
System.setProperty("activemq.persistenceAdapter", "org.apache.activemq.store.vm.VMPersistenceAdapter");
// configuration of container and all protocols
BrokerService broker = createBroker();
// start a client
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:9100");
factory.createConnection();
// stop activemq broker
broker.stop();
// start activemq broker again
broker = createBroker();
// start a client again
factory = new ActiveMQConnectionFactory("tcp://localhost:9100");
factory.createConnection();
// stop activemq broker
broker.stop();
}
17
View Complete Implementation : OpsEventPublisherTest.java
Copyright Apache License 2.0
Author : oneops
Copyright Apache License 2.0
Author : oneops
@Test(expectedExceptions = JMSException.clreplaced)
public /**
* negative test that JMSException happens if bad factory
*/
void initFailTest() throws Exception {
OpsEventPublisher oep = new OpsEventPublisher();
ActiveMQConnectionFactory factoryMock = mock(ActiveMQConnectionFactory.clreplaced);
try {
when(factoryMock.createConnection()).thenThrow(new JMSException("from mock"));
oep.setConnectionFactory(factoryMock);
oep.setPersistent(false);
oep.setQueue("mock-queue");
oep.setTimeToLive(123L);
oep.init();
} catch (JMSException e) {
// as expected, we are here
throw e;
}
}
17
View Complete Implementation : Jms1ITest.java
Copyright Apache License 2.0
Author : opentracing-contrib
Copyright Apache License 2.0
Author : opentracing-contrib
public static void main(final String[] args) throws Exception {
final ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");
final Connection connection = connectionFactory.createConnection();
connection.start();
for (int i = 0; i < threadCount; ++i) new Thread(new HelloWorldProducer(connection)).start();
latch.await();
TestUtil.checkSpan("java-jms", 4);
connection.close();
}
17
View Complete Implementation : MessageServiceConnectionInfo.java
Copyright Apache License 2.0
Author : sleuthkit
Copyright Apache License 2.0
Author : sleuthkit
/**
* Verifies connection to messaging service. Throws if we cannot communicate
* with messaging service.
*
* When issues occur, it attempts to diagnose them by looking at the
* exception messages, returning the appropriate user-facing text for the
* exception received. This method expects the Exceptions messages to be in
* English and compares against English text.
*
* @throws org.sleuthkit.autopsy.events.MessageServiceException
*/
public void tryConnect() throws MessageServiceException {
if (host == null || host.isEmpty()) {
// NON-NLS
throw new MessageServiceException(NbBundle.getMessage(MessageServiceConnectionInfo.clreplaced, "MessageServiceConnectionInfo.MissingHostname"));
} else if (userName == null) {
// NON-NLS
throw new MessageServiceException(NbBundle.getMessage(MessageServiceConnectionInfo.clreplaced, "MessageServiceConnectionInfo.MissingUsername"));
} else if (preplacedword == null) {
// NON-NLS
throw new MessageServiceException(NbBundle.getMessage(MessageServiceConnectionInfo.clreplaced, "MessageServiceConnectionInfo.MissingPreplacedword"));
}
try {
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(getUserName(), getPreplacedword(), getURI());
Connection connection = connectionFactory.createConnection(getUserName(), getPreplacedword());
connection.start();
connection.close();
} catch (URISyntaxException ex) {
// The hostname or port seems bad
// NON-NLS
throw new MessageServiceException(NbBundle.getMessage(MessageServiceConnectionInfo.clreplaced, "MessageServiceConnectionInfo.ConnectionCheck.HostnameOrPort"));
} catch (JMSException ex) {
String result;
Throwable cause = ex.getCause();
if (null != cause && null != cause.getMessage()) {
// there is more information from another exception
String msg = cause.getMessage();
if (msg.startsWith(CONNECTION_TIMED_OUT)) {
// The hostname or IP address seems bad
// NON-NLS
result = NbBundle.getMessage(MessageServiceConnectionInfo.clreplaced, "MessageServiceConnectionInfo.ConnectionCheck.Hostname");
} else if (msg.toLowerCase().startsWith(CONNECTION_REFUSED)) {
// The port seems bad
// NON-NLS
result = NbBundle.getMessage(MessageServiceConnectionInfo.clreplaced, "MessageServiceConnectionInfo.ConnectionCheck.Port");
} else if (msg.toLowerCase().startsWith(PreplacedWORD_OR_USERNAME_BAD)) {
// The username or preplacedword seems bad
// NON-NLS
result = NbBundle.getMessage(MessageServiceConnectionInfo.clreplaced, "MessageServiceConnectionInfo.ConnectionCheck.UsernameAndPreplacedword");
} else {
// Could be either hostname or port number
// NON-NLS
result = NbBundle.getMessage(MessageServiceConnectionInfo.clreplaced, "MessageServiceConnectionInfo.ConnectionCheck.HostnameOrPort");
}
} else {
// there is no more information from another exception
try {
if (InetAddress.getByName(getHost()).isReachable(IS_REACHABLE_TIMEOUT_MS)) {
// if we can reach the host, then it's probably a port problem
// NON-NLS
result = NbBundle.getMessage(MessageServiceConnectionInfo.clreplaced, "MessageServiceConnectionInfo.ConnectionCheck.Port");
} else {
// NON-NLS
result = NbBundle.getMessage(MessageServiceConnectionInfo.clreplaced, "MessageServiceConnectionInfo.ConnectionCheck.Hostname");
}
} catch (IOException | MissingResourceException any) {
// it may be anything
// NON-NLS
result = NbBundle.getMessage(MessageServiceConnectionInfo.clreplaced, "MessageServiceConnectionInfo.ConnectionCheck.Everything");
}
}
throw new MessageServiceException(result);
}
}
17
View Complete Implementation : DiscoveryUriTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
public void testFailedConnect() throws Exception {
try {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("discovery:(multicast://default?group=test1)?reconnectDelay=1000&startupMaxReconnectAttempts=3&useExponentialBackOff=false");
Connection conn = factory.createConnection();
conn.start();
} catch (Exception e) {
return;
}
fail("Expected connection failure");
}
17
View Complete Implementation : SlowConnectionTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@Test
public void testSlowConnection() throws Exception {
MockBroker broker = new MockBroker();
broker.start();
socketReadyLatch.await();
int timeout = 1000;
URI tcpUri = new URI("tcp://localhost:" + broker.ss.getLocalPort() + "?soTimeout=" + timeout + "&trace=true&connectionTimeout=" + timeout + "&wireFormat.maxInactivityDurationInitalDelay=" + timeout);
ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + tcpUri + ")");
final Connection connection = cf.createConnection();
new Thread(new Runnable() {
@Override
public void run() {
try {
connection.start();
} catch (Throwable ignored) {
}
}
}).start();
int count = 0;
replacedert.replacedertTrue("Transport count: " + count + ", expected <= 1", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception {
int count = 0;
for (Thread thread : Thread.getAllStackTraces().keySet()) {
if (thread.getName().contains("ActiveMQ Transport")) {
count++;
}
}
return count == 1;
}
}));
broker.interrupt();
broker.join();
}
17
View Complete Implementation : PeerTransportTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
protected Connection createConnection(int i) throws JMSException {
LOG.info("creating connection ....");
ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory("peer://" + getClreplaced().getName() + "/node" + i);
return fac.createConnection();
}
17
View Complete Implementation : JMSClientTestSupport.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
private Connection createOpenWireConnection(String connectionString, String username, String preplacedword, String clientId, boolean start) throws JMSException {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionString);
Connection connection = trackJMSConnection(factory.createConnection(username, preplacedword));
connection.setExceptionListener(new ExceptionListener() {
@Override
public void onException(JMSException exception) {
exception.printStackTrace();
}
});
if (clientId != null && !clientId.isEmpty()) {
connection.setClientID(clientId);
}
if (start) {
connection.start();
}
return connection;
}
17
View Complete Implementation : MessageListenerRedeliveryTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
protected Connection createRetryConnection() throws Exception {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(urlString);
factory.setRedeliveryPolicy(getRedeliveryPolicy());
return factory.createConnection();
}
17
View Complete Implementation : ActiveMQConnectionProvider.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
protected Connection startJmsConnection(String url) {
try {
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
connectionFactory.setAlwaysSyncSend(false);
Connection connect = connectionFactory.createConnection();
connect.start();
return connect;
} catch (JMSException e) {
throw new replacedertionError("Failed to establish the JMS-Connection!", e);
}
}
17
View Complete Implementation : JmsServiceTest.java
Copyright Apache License 2.0
Author : cschneider
Copyright Apache License 2.0
Author : cschneider
private Connection createAndStartConnection() throws JMSException {
ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://test?broker.persistent=false");
Connection con = cf.createConnection();
con.start();
return con;
}
17
View Complete Implementation : ConnectionFactory.java
Copyright Apache License 2.0
Author : hazelcast
Copyright Apache License 2.0
Author : hazelcast
public Connection newConnection(String brokerURL, ExceptionListener exceptionListener) throws JMSException {
String finalBrokerURL = toUrl(brokerURL);
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(finalBrokerURL);
// to speed things up; don't wait till it is on the socket buffer.
// http://activemq.apache.org/async-sends.html
connectionFactory.setUseAsyncSend(true);
// authentication stuff.
connectionFactory.setUserName(username);
connectionFactory.setPreplacedword(preplacedword);
// we want to consume the least amount of resources possible. And there will be very low volume traffic.
connectionFactory.setMaxThreadPoolSize(MAX_THREAD_POOL_SIZE);
//
// connectionFactory.setRejectedTaskHandler(new RejectedExecutionHandler() {
// public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
// try {
// executor.getQueue().put(r);
// } catch (InterruptedException var4) {
// throw new RejectedExecutionException(var4);
// }
// }
// });
Connection connection = connectionFactory.createConnection();
connection.setExceptionListener(exceptionListener);
connection.start();
return connection;
}
16
View Complete Implementation : BrokerPropertiesTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
public void testVmBrokerPropertiesFile() throws Exception {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?brokerConfig=properties:org/apache/activemq/config/broker.properties");
Connection connection = factory.createConnection();
BrokerService broker = BrokerRegistry.getInstance().lookup("Cheese");
LOG.info("Found broker : " + broker);
replacedertNotNull(broker);
replacedertEquals("isUseJmx()", false, broker.isUseJmx());
replacedertEquals("isPersistent()", false, broker.isPersistent());
replacedertEquals("getBrokerName()", "Cheese", broker.getBrokerName());
connection.close();
broker.stop();
}
16
View Complete Implementation : ConfigUsingDestinationOptionsTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@Test(timeout = 60000)
public void testInvalidSelectorConfig() throws JMSException {
ActiveMQQueue queue = new ActiveMQQueue("TEST.FOO?consumer.selector=test||1");
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost");
Connection conn = factory.createConnection();
Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
ActiveMQMessageConsumer cons;
// JMS selector should be priority
try {
cons = (ActiveMQMessageConsumer) sess.createConsumer(queue, "test||1");
fail("Selector should be invalid" + cons);
} catch (InvalidSelectorException e) {
}
// Test setting using JMS destinations
try {
cons = (ActiveMQMessageConsumer) sess.createConsumer(queue);
fail("Selector should be invalid" + cons);
} catch (InvalidSelectorException e) {
}
}
16
View Complete Implementation : DiscoveryTransportNoBrokerTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
public void testInitialConnectDelayWithNoBroker() throws Exception {
// the initialReconnectDelay only kicks in once a set of connect URL have
// been returned from the discovery agent.
// Up to that point the reconnectDelay is used which has a default value of 10
//
long initialReconnectDelay = 4000;
long startT = System.currentTimeMillis();
String groupId = "WillNotMatch" + startT;
try {
String urlStr = "discovery:(multicast://default?group=" + groupId + ")?useExponentialBackOff=false&maxReconnectAttempts=2&reconnectDelay=" + initialReconnectDelay;
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(urlStr);
LOG.info("Connecting.");
Connection connection = factory.createConnection();
connection.setClientID("test");
fail("Did not fail to connect as expected.");
} catch (JMSException expected) {
replacedertTrue("reason is java.io.IOException, was: " + expected.getCause(), expected.getCause() instanceof java.io.IOException);
long duration = System.currentTimeMillis() - startT;
replacedertTrue("took at least initialReconnectDelay time: " + duration + " e:" + expected, duration >= initialReconnectDelay);
}
}
16
View Complete Implementation : DiscoveryTransportNoBrokerTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
public void testMaxReconnectAttempts() throws JMSException {
try {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("discovery:(multicast://doesNOTexist)");
LOG.info("Connecting.");
Connection connection = factory.createConnection();
connection.setClientID("test");
fail("Did not fail to connect as expected.");
} catch (JMSException expected) {
replacedertTrue("reason is java.io.IOException, was: " + expected.getCause(), expected.getCause() instanceof java.io.IOException);
}
}
16
View Complete Implementation : AMQ1925Test.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
private int tryToFetchMissingMessages() throws JMSException {
Connection connection = cf.createConnection();
connection.start();
Session session = connection.createSession(true, 0);
MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME));
int count = 0;
while (true) {
Message message = consumer.receive(500);
if (message == null)
break;
log.info("Found \"missing\" message: " + message);
count++;
}
consumer.close();
session.close();
connection.close();
return count;
}
16
View Complete Implementation : ActiveMQEc2LiveTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
private Connection getActiveMQConnection(ActiveMQBroker activeMQ) throws Exception {
int port = activeMQ.getAttribute(ActiveMQBroker.OPEN_WIRE_PORT);
String address = activeMQ.getAttribute(ActiveMQBroker.ADDRESS);
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(String.format("tcp://%s:%s", address, port));
Connection connection = factory.createConnection("admin", "activemq");
connection.start();
return connection;
}
16
View Complete Implementation : ActiveMQIntegrationTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
private Connection getActiveMQConnection(ActiveMQBroker activeMQ) throws Exception {
int port = activeMQ.getAttribute(ActiveMQBroker.OPEN_WIRE_PORT);
String address = activeMQ.getAttribute(ActiveMQBroker.ADDRESS);
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://" + address + ":" + port);
Connection connection = factory.createConnection("admin", "activemq");
connection.start();
return connection;
}
16
View Complete Implementation : MessageListenerTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
private static Connection createConnection(String name) throws JMSException {
ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://" + name + "?broker.persistent=false");
cf.setRedeliveryPolicy(redeliveryPolicy());
Connection connection = cf.createConnection();
connection.start();
return connection;
}
15
View Complete Implementation : ConfigUsingDestinationOptionsTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@Test(timeout = 60000)
public void testValidSelectorConfig() throws JMSException {
ActiveMQQueue queue = new ActiveMQQueue("TEST.FOO?consumer.selector=test=1");
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost");
Connection conn = factory.createConnection();
Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
ActiveMQMessageConsumer cons;
// JMS selector should be priority
cons = (ActiveMQMessageConsumer) sess.createConsumer(queue, "test=2");
replacedertEquals("test=2", cons.getMessageSelector());
// Test setting using JMS destinations
cons = (ActiveMQMessageConsumer) sess.createConsumer(queue);
replacedertEquals("test=1", cons.getMessageSelector());
}
15
View Complete Implementation : FailoverTimeoutTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@Test
public void testTimoutDoesNotFailConnectionAttempts() throws Exception {
server.stop();
long timeout = 1000;
long startTime = System.currentTimeMillis();
ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + tcpUri + ")" + "?timeout=" + timeout + "&useExponentialBackOff=false" + "&maxReconnectAttempts=5" + "&initialReconnectDelay=1000");
Connection connection = cf.createConnection();
try {
connection.start();
fail("Should have failed to connect");
} catch (JMSException ex) {
LOG.info("Caught exception on call to start: {}", ex.getMessage());
}
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
LOG.info("Time spent waiting to connect: {} ms", duration);
replacedertTrue(duration > 3000);
}
15
View Complete Implementation : FailoverTransactionTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@Test
public void testFailoverProducerCloseBeforeTransactionFailWhenDisabled() throws Exception {
LOG.info(this + " running test testFailoverProducerCloseBeforeTransactionFailWhenDisabled");
startCleanBroker();
ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")?trackTransactionProducers=false");
configureConnectionFactory(cf);
Connection connection = cf.createConnection();
connection.start();
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
Queue destination = session.createQueue(QUEUE_NAME);
MessageConsumer consumer = session.createConsumer(destination);
produceMessage(session, destination);
// restart to force failover and connection state recovery before the commit
broker.stop();
startBroker();
session.commit();
// without tracking producers, message will not be replayed on recovery
replacedert.replacedertNull("we got the message", consumer.receive(5000));
session.commit();
connection.close();
}
15
View Complete Implementation : FailoverTransactionTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@Test
public void testFailoverProducerCloseBeforeTransaction() throws Exception {
LOG.info(this + " running test testFailoverProducerCloseBeforeTransaction");
startCleanBroker();
ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")");
configureConnectionFactory(cf);
Connection connection = cf.createConnection();
connection.start();
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
Queue destination = session.createQueue(QUEUE_NAME);
MessageConsumer consumer = session.createConsumer(destination);
produceMessage(session, destination);
// restart to force failover and connection state recovery before the commit
broker.stop();
startBroker();
session.commit();
replacedert.replacedertNotNull("we got the message", consumer.receive(20000));
session.commit();
connection.close();
}
15
View Complete Implementation : NonBlockingConsumerRedeliveryTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@Test
public void testMessageDeleiveryDoesntStop() throws Exception {
final LinkedHashSet<Message> received = new LinkedHashSet<>();
final LinkedHashSet<Message> beforeRollback = new LinkedHashSet<>();
final LinkedHashSet<Message> afterRollback = new LinkedHashSet<>();
Connection connection = connectionFactory.createConnection();
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue(destinationName);
MessageConsumer consumer = session.createConsumer(destination);
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
received.add(message);
}
});
sendMessages();
connection.start();
replacedertTrue("Pre-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception {
LOG.info("Consumer has received " + received.size() + " messages.");
return received.size() == MSG_COUNT;
}
}));
beforeRollback.addAll(received);
received.clear();
session.rollback();
sendMessages();
replacedertTrue("Post-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception {
LOG.info("Consumer has received " + received.size() + " messages since rollback.");
return received.size() == MSG_COUNT * 2;
}
}));
afterRollback.addAll(received);
received.clear();
replacedertEquals(beforeRollback.size() * 2, afterRollback.size());
session.commit();
}
15
View Complete Implementation : NonBlockingConsumerRedeliveryTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@Test
public void testMessageDeleiveredWhenNonBlockingEnabled() throws Exception {
final LinkedHashSet<Message> received = new LinkedHashSet<>();
final LinkedHashSet<Message> beforeRollback = new LinkedHashSet<>();
final LinkedHashSet<Message> afterRollback = new LinkedHashSet<>();
Connection connection = connectionFactory.createConnection();
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue(destinationName);
MessageConsumer consumer = session.createConsumer(destination);
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
received.add(message);
}
});
sendMessages();
session.commit();
connection.start();
replacedertTrue("Pre-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception {
LOG.info("Consumer has received " + received.size() + " messages.");
return received.size() == MSG_COUNT;
}
}));
beforeRollback.addAll(received);
received.clear();
session.rollback();
replacedertTrue("Post-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception {
LOG.info("Consumer has received " + received.size() + " messages since rollback.");
return received.size() == MSG_COUNT;
}
}));
afterRollback.addAll(received);
received.clear();
replacedertEquals(beforeRollback.size(), afterRollback.size());
replacedertEquals(beforeRollback, afterRollback);
session.commit();
}
15
View Complete Implementation : NonBlockingConsumerRedeliveryTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@Test
public void testMessageDeleiveredInCorrectOrder() throws Exception {
final LinkedHashSet<Message> received = new LinkedHashSet<>();
final LinkedHashSet<Message> beforeRollback = new LinkedHashSet<>();
final LinkedHashSet<Message> afterRollback = new LinkedHashSet<>();
Connection connection = connectionFactory.createConnection();
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue(destinationName);
MessageConsumer consumer = session.createConsumer(destination);
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
received.add(message);
}
});
sendMessages();
session.commit();
connection.start();
replacedertTrue("Pre-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception {
LOG.info("Consumer has received " + received.size() + " messages.");
return received.size() == MSG_COUNT;
}
}));
beforeRollback.addAll(received);
received.clear();
session.rollback();
replacedertTrue("Post-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception {
LOG.info("Consumer has received " + received.size() + " messages since rollback.");
return received.size() == MSG_COUNT;
}
}));
afterRollback.addAll(received);
received.clear();
replacedertEquals(beforeRollback.size(), afterRollback.size());
replacedertEquals(beforeRollback, afterRollback);
Iterator<Message> after = afterRollback.iterator();
Iterator<Message> before = beforeRollback.iterator();
while (before.hasNext() && after.hasNext()) {
TextMessage original = (TextMessage) before.next();
TextMessage rolledBack = (TextMessage) after.next();
int originalInt = Integer.parseInt(original.getText());
int rolledbackInt = Integer.parseInt(rolledBack.getText());
replacedertEquals(originalInt, rolledbackInt);
}
session.commit();
}
15
View Complete Implementation : RequestReplyTempDestRemovalAdvisoryRaceTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
private void noConsumerAdvisory() throws JMSException {
for (BrokerItem item : brokers.values()) {
ActiveMQConnectionFactory brokerAFactory = new ActiveMQConnectionFactory(item.broker.getTransportConnectorByScheme("tcp").getName() + "?jms.watchTopicAdvisories=false");
Connection connection = brokerAFactory.createConnection();
connection.start();
connection.createSession(false, Session.AUTO_ACKNOWLEDGE).createConsumer(AdvisorySupport.getNoTopicConsumersAdvisoryTopic(new ActiveMQTempTopic(">"))).setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
sendsWithNoConsumers.incrementAndGet();
}
});
}
}