Java Code Examples for org.apache.activemq.artemis.api.jms.ActiveMQJMSClient#createConnectionFactory()

The following examples show how to use org.apache.activemq.artemis.api.jms.ActiveMQJMSClient#createConnectionFactory() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EmbeddedTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public static void publish(String destination, Serializable object, String contentType) throws Exception {
   ConnectionFactory factory = ActiveMQJMSClient.createConnectionFactory("vm://0","cf");
   Connection conn = factory.createConnection();
   Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
   Destination dest = session.createQueue(destination);

   try {
      Assert.assertNotNull("Destination was null", dest);
      MessageProducer producer = session.createProducer(dest);
      ObjectMessage message = session.createObjectMessage();

      if (contentType != null) {
         message.setStringProperty(HttpHeaderProperty.CONTENT_TYPE, contentType);
      }
      message.setObject(object);

      producer.send(message);
   } finally {
      conn.close();
   }
}
 
Example 2
Source File: AcknowledgementTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Ensure no blocking calls in acknowledge flow when block on acknowledge = false.
 * This is done by checking the performance compared to blocking is much improved.
 */
@Test
public void testNonBlockingAckPerf() throws Exception {
   ConnectionFactory cf1 = ActiveMQJMSClient.createConnectionFactory("tcp://127.0.0.1:61616?blockOnNonDurableSend=true&blockOnAcknowledge=false", "testsuitecf1");
   ConnectionFactory cf2 = ActiveMQJMSClient.createConnectionFactory("tcp://127.0.0.1:61616?blockOnNonDurableSend=true&blockOnAcknowledge=true", "testsuitecf2");

   int messageCount = 100;

   long sendT1 = send(cf1, queue1, messageCount);
   long sendT2 = send(cf2, queue2, messageCount);

   long time1 = consume(cf1, queue1, messageCount);
   long time2 = consume(cf2, queue2, messageCount);

   log.debug("BlockOnAcknowledge=false MessageCount=" + messageCount + " TimeToConsume=" + time1);
   log.debug("BlockOnAcknowledge=true MessageCount=" + messageCount + " TimeToConsume=" + time2);

   Assert.assertTrue(time1 < (time2 / 2));

}
 
Example 3
Source File: MultipleProducersPagingTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Override
@Before
public void setUp() throws Exception {
   super.setUp();
   executor = Executors.newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory());

   server = createServer(createBasicConfig()
                            .setPersistenceEnabled(false)
                            .setAddressesSettings(Collections.singletonMap("#", new AddressSettings()
                               .setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE)
                               .setPageSizeBytes(50000)
                               .setMaxSizeBytes(404850)))
                            .setAcceptorConfigurations(Collections.singleton(new TransportConfiguration(NettyAcceptorFactory.class.getName()))));

   server.start();

   cf = ActiveMQJMSClient.createConnectionFactory("tcp://127.0.0.1:61616", "cf");
   queue = ActiveMQJMSClient.createQueue("simple");

   barrierLatch = new CyclicBarrier(PRODUCERS + 1);
   runnersLatch = new CountDownLatch(PRODUCERS + 1);
   msgReceived = new AtomicLong(0);
   msgSent = new AtomicLong(0);
}
 
Example 4
Source File: ServerUtil.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public static boolean waitForServerToStart(String uri, long timeout) throws InterruptedException {
   long realTimeout = System.currentTimeMillis() + timeout;
   while (System.currentTimeMillis() < realTimeout) {
      try (ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactory(uri, null)) {
         cf.createConnection().close();
         System.out.println("server " + uri + " started");
      } catch (Exception e) {
         System.out.println("awaiting server " + uri + " start at ");
         Thread.sleep(500);
         continue;
      }
      return true;
   }

   return false;
}
 
Example 5
Source File: ConnectionFactoryProvider.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private ActiveMQConnectionFactory createConnectionFactory() throws Exception {
   Map<String, Object> params = new HashMap<>();
   params.put(org.apache.activemq.artemis.core.remoting.impl.invm.TransportConstants.SERVER_ID_PROP_NAME, "1");
   final ActiveMQConnectionFactory activeMQConnectionFactory;
   if (configuration.getUrl() != null) {
      activeMQConnectionFactory = ActiveMQJMSClient.createConnectionFactory(configuration.getUrl(), null);
   } else {
      if (configuration.getHost() != null) {
         params.put(TransportConstants.HOST_PROP_NAME, configuration.getHost());
         params.put(TransportConstants.PORT_PROP_NAME, configuration.getPort());
      }
      if (configuration.isHa()) {
         activeMQConnectionFactory = ActiveMQJMSClient.createConnectionFactoryWithHA(JMSFactoryType.CF, new TransportConfiguration(configuration.getConnectorFactory(), params));
      } else {
         activeMQConnectionFactory = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(configuration.getConnectorFactory(), params));
      }
   }
   if (configuration.hasAuthentication()) {
      activeMQConnectionFactory.setUser(configuration.getUsername());
      activeMQConnectionFactory.setPassword(configuration.getPassword());
   }
   // The CF will probably be GCed since it was injected, so we disable the finalize check
   return activeMQConnectionFactory.disableFinalizeChecks();
}
 
Example 6
Source File: EmbeddedRestActiveMQJMSTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void startEmbedded() throws Exception {
   server = new EmbeddedRestActiveMQ(null);
   assertNotNull(server.getEmbeddedActiveMQ());
   server.getManager().setConfigResourcePath("activemq-rest.xml");

   SecurityConfiguration securityConfiguration = createDefaultSecurityConfiguration();
   ActiveMQJAASSecurityManager securityManager = new ActiveMQJAASSecurityManager(InVMLoginModule.class.getName(), securityConfiguration);
   server.getEmbeddedActiveMQ().setSecurityManager(securityManager);

   server.start();
   factory = ActiveMQJMSClient.createConnectionFactory("vm://0", "cf");

   ClientRequest request = new ClientRequest(TestPortProvider.generateURL("/queues/exampleQueue"));

   ClientResponse<?> response = request.head();
   response.releaseConnection();
   assertEquals(200, response.getStatus());
   Link sender = response.getLinkHeader().getLinkByTitle("create");
   log.debug("create: " + sender);
   Link consumers = response.getLinkHeader().getLinkByTitle("pull-consumers");
   log.debug("pull: " + consumers);
   response = Util.setAutoAck(consumers, true);
   consumeNext = response.getLinkHeader().getLinkByTitle("consume-next");
   log.debug("consume-next: " + consumeNext);
}
 
Example 7
Source File: RejectValidatedUserTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testAcceptJMSException() throws Exception {
   ActiveMQConnectionFactory connectionFactory = ActiveMQJMSClient.createConnectionFactory("vm://0", "0");
   Connection connection = connectionFactory.createConnection();
   Session session = connection.createSession();
   Queue queue = session.createQueue(ADDRESS.toString());
   MessageProducer producer = session.createProducer(queue);
   Message message = session.createMessage();
   message.setStringProperty("JMSXUserID", "testuser");
   producer.send(message);
}
 
Example 8
Source File: FloodServerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void _testFlood() throws Exception {
   ConnectionFactory cf = ActiveMQJMSClient.createConnectionFactory("tcp://127.0.0.1:61616?retryInterval=1000&retryIntervalMultiplier=1.0&reconnectAttempts=-1&callTimeout=30000&clientFailureCheckPeriod=1000&maxRetryInterval=1000&blockOnDurableSend=false&blockOnAcknowledge=false", "cf");

   final int numProducers = 20;

   final int numConsumers = 20;

   final int numMessages = 10000;

   ProducerThread[] producers = new ProducerThread[numProducers];

   for (int i = 0; i < numProducers; i++) {
      producers[i] = new ProducerThread(cf, numMessages);
   }

   ConsumerThread[] consumers = new ConsumerThread[numConsumers];

   for (int i = 0; i < numConsumers; i++) {
      consumers[i] = new ConsumerThread(cf, numMessages);
   }

   for (int i = 0; i < numConsumers; i++) {
      consumers[i].start();
   }

   for (int i = 0; i < numProducers; i++) {
      producers[i].start();
   }

   for (int i = 0; i < numConsumers; i++) {
      consumers[i].join();
   }

   for (int i = 0; i < numProducers; i++) {
      producers[i].join();
   }

}
 
Example 9
Source File: URITest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testParseURIs() throws Throwable {
   ActiveMQConnectionFactory factory = ActiveMQJMSClient.createConnectionFactory("(tcp://localhost:61616,tcp://localhost:61617)?blockOnDurableSend=false", "some name");
   Assert.assertEquals(2, ((ServerLocatorImpl) factory.getServerLocator()).getInitialConnectors().length);

   ActiveMQConnectionFactory factory2 = new ActiveMQConnectionFactory("(tcp://localhost:61614,tcp://localhost:61616)?blockOnDurableSend=false");
   Assert.assertEquals(2, ((ServerLocatorImpl) factory2.getServerLocator()).getInitialConnectors().length);

   ServerLocator locator = ServerLocatorImpl.newLocator("(tcp://localhost:61616,tcp://localhost:61617)?blockOnDurableSend=false");
   Assert.assertEquals(2, ((ServerLocatorImpl) locator).getInitialConnectors().length);

   ServerLocator locator2 = ActiveMQClient.createServerLocator("(tcp://localhost:61616,tcp://localhost:61617)?blockOnDurableSend=false");
   Assert.assertEquals(2, ((ServerLocatorImpl) locator2).getInitialConnectors().length);

}
 
Example 10
Source File: HornetQProtocolManagerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/** This test will use an ArtemisConnectionFactory with clientProtocolManager=*/
@Test
public void testLegacy2() throws Exception {
   // WORKAROUND: the 2.0.0 broker introduced addressing change and the 2.2.0 broker added compatibility for old
   // client libraries relying on the legacy prefixes. The new client being used in this test needs prefix explicitly.
   Queue queue = new ActiveMQQueue("jms.queue.testQueue");
   ActiveMQConnectionFactory connectionFactory = ActiveMQJMSClient.createConnectionFactory("tcp://localhost:61616?protocolManagerFactoryStr=" + HornetQClientProtocolManagerFactory.class.getName(), "legacy");
   Connection connection = connectionFactory.createConnection();
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageProducer producer = session.createProducer(queue);

   TextMessage message = session.createTextMessage("Test");
   for (int i = 0; i < 5; i++) {
      message.setStringProperty(Message.HDR_DUPLICATE_DETECTION_ID.toString(), "duplicate");
      producer.send(message);
   }

   connection.start();
   MessageConsumer consumer = session.createConsumer(queue);
   TextMessage messageRec = (TextMessage) consumer.receive(5000);
   Assert.assertNotNull(messageRec);

   Assert.assertEquals("Test", messageRec.getText());
   Assert.assertNull(consumer.receiveNoWait());
   connection.close();
   connectionFactory.close();

}
 
Example 11
Source File: JMSXDeliveryCountTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
@Before
public void setUp() throws Exception {
   super.setUp();

   xacf = ActiveMQJMSClient.createConnectionFactory("tcp://localhost:61616", "test");

   queue1 = createQueue("queue1");
   topic1 = createTopic("topic1");

   TxControl.enable();
}
 
Example 12
Source File: CTSMiscellaneousTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
@Before
public void setUp() throws Exception {
   try {
      super.setUp();
      CTSMiscellaneousTest.cf = ActiveMQJMSClient.createConnectionFactory("tcp://127.0.0.1:61616?blockOnAcknowledge=true&blockOnDurableSend=true&blockOnNonDurableSend=true", "StrictTCKConnectionFactory");
   } catch (Exception e) {
      e.printStackTrace();
   }

}
 
Example 13
Source File: ArtemisJmsTest.java    From a with Apache License 2.0 5 votes vote down vote up
@Override
protected ConnectionFactory getConnectionFactory() {
   try {
      return ActiveMQJMSClient.createConnectionFactory(AMQ_ARTEMIS_URL, "");
   }catch(Exception e){
      e.printStackTrace();
      return null;
   }
}
 
Example 14
Source File: XmlImportExportTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testLargeJmsTextMessage() throws Exception {
   basicSetUp();
   ConnectionFactory cf = ActiveMQJMSClient.createConnectionFactory("vm://0", "test");
   Connection c = cf.createConnection();
   Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
   server.createQueue(new QueueConfiguration("A").setRoutingType(RoutingType.ANYCAST));
   MessageProducer p = s.createProducer(ActiveMQJMSClient.createQueue("A"));
   p.setDeliveryMode(DeliveryMode.PERSISTENT);
   StringBuilder stringBuilder = new StringBuilder();
   for (int i = 0; i < 1024 * 200; i++) {
      stringBuilder.append(RandomUtil.randomChar());
   }
   TextMessage textMessage = s.createTextMessage(stringBuilder.toString());
   textMessage.setStringProperty("_AMQ_DUPL_ID", String.valueOf(UUID.randomUUID()));
   p.send(textMessage);
   c.close();

   locator.close();
   server.stop();

   ByteArrayOutputStream xmlOutputStream = new ByteArrayOutputStream();
   XmlDataExporter xmlDataExporter = new XmlDataExporter();
   xmlDataExporter.process(xmlOutputStream, server.getConfiguration().getBindingsDirectory(), server.getConfiguration().getJournalDirectory(), server.getConfiguration().getPagingDirectory(), server.getConfiguration().getLargeMessagesDirectory());
   System.out.print(new String(xmlOutputStream.toByteArray()));

   clearDataRecreateServerDirs();
   server.start();
   checkForLongs();
   locator = createInVMNonHALocator();
   factory = createSessionFactory(locator);
   ClientSession session = factory.createSession(false, true, true);

   ByteArrayInputStream xmlInputStream = new ByteArrayInputStream(xmlOutputStream.toByteArray());
   XmlDataImporter xmlDataImporter = new XmlDataImporter();
   xmlDataImporter.validate(xmlInputStream);
   xmlInputStream.reset();
   xmlDataImporter.process(xmlInputStream, session);
   session.close();

   c = cf.createConnection();
   s = c.createSession();
   MessageConsumer mc = s.createConsumer(ActiveMQJMSClient.createQueue("A"));
   c.start();
   javax.jms.Message msg = mc.receive(CONSUMER_TIMEOUT);

   assertNotNull(msg);

   c.close();
}
 
Example 15
Source File: OpenWireTestBase.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Override
@Before
public void setUp() throws Exception {
   super.setUp();
   server = this.createServer(realStore, true);

   Configuration serverConfig = server.getConfiguration();

   Map<String, AddressSettings> addressSettingsMap = serverConfig.getAddressesSettings();

   configureAddressSettings(addressSettingsMap);

   serverConfig.setSecurityEnabled(enableSecurity);

   extraServerConfig(serverConfig);

   if (enableSecurity) {
      ActiveMQJAASSecurityManager securityManager = (ActiveMQJAASSecurityManager) server.getSecurityManager();
      securityManager.getConfiguration().addRole("openwireSender", "sender");
      securityManager.getConfiguration().addUser("openwireSender", "SeNdEr");
      //sender cannot receive
      Role senderRole = new Role("sender", true, false, false, false, true, true, false, false, true, true);

      securityManager.getConfiguration().addRole("openwireReceiver", "receiver");
      securityManager.getConfiguration().addUser("openwireReceiver", "ReCeIvEr");
      //receiver cannot send
      Role receiverRole = new Role("receiver", false, true, false, false, true, true, false, true, false, false);

      securityManager.getConfiguration().addRole("openwireGuest", "guest");
      securityManager.getConfiguration().addUser("openwireGuest", "GuEsT");

      //guest cannot do anything
      Role guestRole = new Role("guest", false, false, false, false, false, false, false, false, false, false);

      securityManager.getConfiguration().addRole("openwireDestinationManager", "manager");
      securityManager.getConfiguration().addUser("openwireDestinationManager", "DeStInAtIoN");

      Role destRole = new Role("manager", false, false, false, false, true, true, false, false, true, false);

      Set<Role> roles = new HashSet<>();
      roles.add(senderRole);
      roles.add(receiverRole);
      roles.add(guestRole);
      roles.add(destRole);

      server.getConfiguration().putSecurityRoles("#", roles);
   }

   mbeanServer = MBeanServerFactory.createMBeanServer();
   server.setMBeanServer(mbeanServer);
   addServer(server);
   server.start();

   coreCf = ActiveMQJMSClient.createConnectionFactory("vm://0?reconnectAttempts=-1","cf");
}
 
Example 16
Source File: XATest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Override
@Before
public void setUp() throws Exception {
   super.setUp();

   xacf = ActiveMQJMSClient.createConnectionFactory("tcp://localhost:61616", "test");

   queue1 = createQueue("queue1");
   TxControl.enable();

   tm = new TransactionManagerImple();

   Assert.assertTrue(tm instanceof TransactionManagerImple);

   suspendedTx = tm.suspend();
}
 
Example 17
Source File: JmxServerControlTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testListConsumers() throws Exception {
   // Without this, the RMI server would bind to the default interface IP (the user's local IP mostly)
   System.setProperty("java.rmi.server.hostname", JMX_SERVER_HOSTNAME);

   // I don't specify both ports here manually on purpose. See actual RMI registry connection port extraction below.
   String urlString = "service:jmx:rmi:///jndi/rmi://" + JMX_SERVER_HOSTNAME + ":" + JMX_SERVER_PORT + "/jmxrmi";

   JMXServiceURL url = new JMXServiceURL(urlString);
   JMXConnector jmxConnector = null;

   try {
      jmxConnector = JMXConnectorFactory.connect(url);
      System.out.println("Successfully connected to: " + urlString);
   } catch (Exception e) {
      jmxConnector = null;
      e.printStackTrace();
      Assert.fail(e.getMessage());
   }

   try {
      MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection();
      String brokerName = "0.0.0.0";  // configured e.g. in broker.xml <broker-name> element
      ObjectNameBuilder objectNameBuilder = ObjectNameBuilder.create(ActiveMQDefaultConfiguration.getDefaultJmxDomain(), brokerName, true);
      ActiveMQServerControl activeMQServerControl = MBeanServerInvocationHandler.newProxyInstance(mBeanServerConnection, objectNameBuilder.getActiveMQServerObjectName(), ActiveMQServerControl.class, false);

      String addressName = "test_list_consumers_address";
      String queueName = "test_list_consumers_queue";
      activeMQServerControl.createAddress(addressName, RoutingType.ANYCAST.name());
      activeMQServerControl.createQueue(new QueueConfiguration(queueName).setAddress(addressName).setRoutingType(RoutingType.ANYCAST).toJSON());
      String uri = "tcp://localhost:61616";
      try (ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactory(uri, null)) {
         MessageConsumer consumer = cf.createConnection().createSession(true, Session.SESSION_TRANSACTED).createConsumer(new ActiveMQQueue(queueName));

         try {
            String options = JsonUtil.toJsonObject(ImmutableMap.of("field","queue", "operation", "EQUALS", "value", queueName)).toString();
            String consumersAsJsonString = activeMQServerControl.listConsumers(options, 1, 10);

            JsonObject consumersAsJsonObject = JsonUtil.readJsonObject(consumersAsJsonString);
            JsonArray array = (JsonArray) consumersAsJsonObject.get("data");

            Assert.assertEquals("number of consumers returned from query", 1, array.size());
            JsonObject jsonConsumer = array.getJsonObject(0);
            Assert.assertEquals("queue name in consumer", queueName, jsonConsumer.getString("queue"));
            Assert.assertEquals("address name in consumer", addressName, jsonConsumer.getString("address"));
         } finally {
            consumer.close();
         }
      }
   } finally {
      jmxConnector.close();
   }
}
 
Example 18
Source File: ConnectionFactoryURITest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testWeirdEncodingsOnIP() throws Exception {
   // This is to make things worse. Having & and = on the property shouldn't break it
   final String BROKEN_PROPERTY = "e80::56ee:75ff:fe53:e6a7%25enp0s25&host=[fe80::56ee:75ff:fe53:e6a7]#";

   Map<String, Object> params = new HashMap<>();
   params.put(TransportConstants.LOCAL_ADDRESS_PROP_NAME, BROKEN_PROPERTY);

   TransportConfiguration configuration = new TransportConfiguration(NettyConnector.class.getName(), params);

   ActiveMQConnectionFactory factory = ActiveMQJMSClient.createConnectionFactoryWithHA(JMSFactoryType.CF, configuration);

   URI uri = factory.toURI();

   ActiveMQConnectionFactory newFactory = ActiveMQJMSClient.createConnectionFactory(uri.toString(), "somefactory");

   TransportConfiguration[] initialConnectors = ((ServerLocatorImpl) newFactory.getServerLocator()).getInitialConnectors();

   Assert.assertEquals(1, initialConnectors.length);

   Assert.assertEquals(BROKEN_PROPERTY, initialConnectors[0].getParams().get(TransportConstants.LOCAL_ADDRESS_PROP_NAME).toString());
}