List of usage examples for javax.jms Session AUTO_ACKNOWLEDGE
int AUTO_ACKNOWLEDGE
To view the source code for javax.jms Session AUTO_ACKNOWLEDGE.
Click Source Link
From source file:org.wso2.extension.siddhi.io.jms.source.client.JMSClient.java
public void sendJMSEvents(List<String> messageList, String topicName, String queueName, String format, String broker, String providerURL) { if (format == null || "map".equals(format)) { format = "csv"; }// w ww . j a va 2 s . c o m if ("".equalsIgnoreCase(broker)) { broker = "activemq"; } Session session = null; Properties properties = new Properties(); if (!"activemq".equalsIgnoreCase(broker) && !"mb".equalsIgnoreCase(broker) && !"qpid".equalsIgnoreCase(broker)) { log.error("Please enter a valid JMS message broker. (ex: activemq, mb, qpid"); return; } try { if (topicName != null && !"".equalsIgnoreCase(topicName)) { TopicConnection topicConnection; TopicConnectionFactory connFactory = null; if ("activemq".equalsIgnoreCase(broker)) { properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties")); // to provide custom provider urls if (providerURL != null) { properties.put(Context.PROVIDER_URL, providerURL); } Context context = new InitialContext(properties); connFactory = (TopicConnectionFactory) context.lookup("ConnectionFactory"); } else if ("mb".equalsIgnoreCase(broker)) { properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("mb.properties")); Context context = new InitialContext(properties); connFactory = (TopicConnectionFactory) context.lookup("qpidConnectionFactory"); } else if ("qpid".equalsIgnoreCase(broker)) { properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("qpid.properties")); Context context = new InitialContext(properties); connFactory = (TopicConnectionFactory) context.lookup("qpidConnectionFactory"); } if (connFactory != null) { topicConnection = connFactory.createTopicConnection(); topicConnection.start(); session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); if (session != null) { Topic topic = session.createTopic(topicName); MessageProducer producer = session.createProducer(topic); //List<String> messagesList = JMSClientUtil.readFile(filePath); try { if ("csv".equalsIgnoreCase(format)) { log.info("Sending Map messages on '" + topicName + "' topic"); JMSClientUtil.publishMapMessage(producer, session, messageList); } else { log.info("Sending " + format + " messages on '" + topicName + "' topic"); JMSClientUtil.publishTextMessage(producer, session, messageList); } log.info("All Order Messages sent"); } catch (JMSException e) { log.error("Cannot subscribe." + e.getMessage(), e); } catch (IOException e) { log.error("Error when reading the data file." + e.getMessage(), e); } finally { producer.close(); session.close(); topicConnection.stop(); } } } else { log.error("Error when creating connection factory. Please check necessary jar files"); } } else if (queueName != null && !queueName.equalsIgnoreCase("")) { QueueConnection queueConnection; QueueConnectionFactory connFactory = null; if ("activemq".equalsIgnoreCase(broker)) { properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties")); // to provide custom provider urls if (providerURL != null) { properties.put(Context.PROVIDER_URL, providerURL); } Context context = new InitialContext(properties); connFactory = (QueueConnectionFactory) context.lookup("ConnectionFactory"); } else if ("mb".equalsIgnoreCase(broker)) { properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("mb.properties")); Context context = new InitialContext(properties); connFactory = (QueueConnectionFactory) context.lookup("qpidConnectionFactory"); } else if ("qpid".equalsIgnoreCase(broker)) { properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("qpid.properties")); Context context = new InitialContext(properties); connFactory = (QueueConnectionFactory) context.lookup("qpidConnectionFactory"); } if (connFactory != null) { queueConnection = connFactory.createQueueConnection(); queueConnection.start(); session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); if (session != null) { Queue queue = session.createQueue(queueName); MessageProducer producer = session.createProducer(queue); //List<String> messagesList = JMSClientUtil.readFile(filePath); try { if ("csv".equalsIgnoreCase(format)) { log.info("Sending Map messages on '" + queueName + "' queue"); JMSClientUtil.publishMapMessage(producer, session, messageList); } else { log.info("Sending " + format + " messages on '" + queueName + "' queue"); JMSClientUtil.publishTextMessage(producer, session, messageList); } } catch (JMSException e) { log.error("Cannot subscribe." + e.getMessage(), e); } catch (IOException e) { log.error("Error when reading the data file." + e.getMessage(), e); } finally { producer.close(); session.close(); queueConnection.stop(); } } } else { log.error("Error when creating connection factory. Please check necessary jar files"); } } else { log.error("Enter queue name or topic name to be published!"); } } catch (Exception e) { log.error("Error when publishing" + e.getMessage(), e); } }
From source file:org.apache.activemq.store.kahadb.SubscriptionRecoveryTest.java
private void createInactiveDurableSub(Topic topic) throws Exception { Connection connection = cf.createConnection(); connection.setClientID("Inactive"); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createDurableSubscriber(topic, "Inactive"); consumer.close();/* w ww . j ava 2 s .co m*/ connection.close(); }
From source file:org.apache.axis2.transport.jms.JMSConnectionFactory.java
/** * Create a new Session/*from w w w . j a v a 2 s. com*/ * @param connection Connection to use * @return A new Session */ private Session createSession(Connection connection) { try { if (log.isDebugEnabled()) { log.debug("Creating a new JMS Session from JMS CF : " + name); } return JMSUtils.createSession(connection, isSessionTransacted(), Session.AUTO_ACKNOWLEDGE, isJmsSpec11(), isQueue()); } catch (JMSException e) { handleException("Error creating JMS session from JMS CF : " + name, e); } return null; }
From source file:org.aludratest.service.jms.impl.JmsActionImpl.java
private Session getSession() throws JMSException { if (session == null) { session = getConnection().createSession(false, Session.AUTO_ACKNOWLEDGE); }/* www . j ava2 s . c o m*/ return session; }
From source file:org.apache.activemq.store.kahadb.SubscriptionRecoveryTest.java
private void consumeDurableMessages(Topic topic, int count) throws Exception { Connection connection = cf.createConnection(); connection.setClientID("Inactive"); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createDurableSubscriber(topic, "Inactive"); connection.start();//from w w w .jav a 2s . c om for (int i = 0; i < count; ++i) { if (consumer.receive(TimeUnit.SECONDS.toMillis(10)) == null) { fail("should have received a message"); } } consumer.close(); connection.close(); }
From source file:org.openanzo.combus.bayeux.BridgeConnectionManager.java
/** * Creates a single JMS connection and session for use by the BayeuxJMSBridge. It connects to the combus using a configured sysadmin account. * // www . j a va2 s .c om * @param factory * this will be used to create the JMS connection and session. * @param properties * must contain the username and password * @throws JMSException */ protected void initialize(ConnectionFactory factory, Properties properties) throws AnzoException { try { conn = factory.createConnection(credentials.getUserName(), credentials.getPassword()); conn.setExceptionListener(new ExceptionListener() { public void onException(JMSException exception) { if (!closed) { // if user has not requested disconnect if (exception.getCause() instanceof BrokerStoppedException || exception.getCause() instanceof TransportDisposedIOException) { closed = true; if (conn != null) { try { conn.close(); } catch (JMSException e) { log.debug(LogUtils.COMBUS_MARKER, "Error closing JMS connection", e); } } } else { log.error(LogUtils.COMBUS_MARKER, "Exception over Bayeux JMS connection", exception); } } } }); conn.start(); session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); mp = session.createProducer(null); mp.setDeliveryMode(DeliveryMode.NON_PERSISTENT); // setup all the destination queues destinations.put(COMBUS.NOTIFICATION_SERVICE_QUEUE, session.createQueue(COMBUS.NOTIFICATION_SERVICE_QUEUE)); destinations.put(COMBUS.MODEL_SERVICE_QUEUE, session.createQueue(COMBUS.MODEL_SERVICE_QUEUE)); destinations.put(COMBUS.UPDATE_SERVICE_QUEUE, session.createQueue(COMBUS.UPDATE_SERVICE_QUEUE)); destinations.put(COMBUS.AUTHENTICATION_SERVICE_QUEUE, session.createQueue(COMBUS.AUTHENTICATION_SERVICE_QUEUE)); destinations.put(COMBUS.REPLICATION_SERVICE_QUEUE, session.createQueue(COMBUS.REPLICATION_SERVICE_QUEUE)); destinations.put(COMBUS.QUERY_SERVICE_QUEUE, session.createQueue(COMBUS.QUERY_SERVICE_QUEUE)); destinations.put(COMBUS.RESET_SERVICE_QUEUE, session.createQueue(COMBUS.RESET_SERVICE_QUEUE)); destinations.put(COMBUS.EXECUTION_SERVICE_QUEUE, session.createQueue(COMBUS.EXECUTION_SERVICE_QUEUE)); destinations.put(COMBUS.AUTHORIZATION_SERVICE_QUEUE, session.createQueue(COMBUS.AUTHORIZATION_SERVICE_QUEUE)); } catch (JMSException jmsex) { throw new AnzoException(ExceptionConstants.COMBUS.JMS_CONNECT_FAILED, jmsex); } }
From source file:org.openanzo.combus.CombusConnection.java
private void performConnect() throws JMSException, AnzoException { if (connected || closing) { return;/*ww w . j a v a2 s .c om*/ } if (jmsProvider == null) { throw new AnzoException(ExceptionConstants.COMBUS.NOTIFICATION_SERVICE_ERROR); } Properties propertiesNew = new Properties(); CombusProperties.setHost(propertiesNew, host); CombusProperties.setPort(propertiesNew, port); CombusProperties.setUseSsl(propertiesNew, useSsl); ConnectionFactory connectionFactory = jmsProvider.createConnectionFactory(propertiesNew); if (connectionFactory != null) { if (userName != null && password != null) { connection = connectionFactory.createConnection(userName, password); } else { connection = connectionFactory.createConnection(); } connection.setExceptionListener(new ExceptionListener() { public void onException(JMSException exception) { if (!closed) { // if user has not requested disconnect if (exception.getCause() instanceof BrokerStoppedException || exception.getCause() instanceof TransportDisposedIOException) { closed = true; } else { try { fireConnectionStateChange(INotificationConnectionListener.CONNECTIONFAILED); performDisconnect(false); } catch (AnzoException e) { log.error(LogUtils.COMBUS_MARKER, Messages.formatString(ExceptionConstants.COMBUS.JMS_DISCONNECT_FAILED), e); } finally { connected = false; } } } } }); connection.start(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); destinations.clear(); destinations.put(INotificationRegistrationService.SERVICE_NAME, session.createQueue(COMBUS.NOTIFICATION_SERVICE_QUEUE)); destinations.put(IModelService.SERVICE_NAME, session.createQueue(COMBUS.MODEL_SERVICE_QUEUE)); destinations.put(IAuthorizationService.SERVICE_NAME, session.createQueue(COMBUS.AUTHORIZATION_SERVICE_QUEUE)); destinations.put(IAuthenticationService.SERVICE_NAME, session.createQueue(COMBUS.AUTHENTICATION_SERVICE_QUEUE)); destinations.put(IReplicationService.SERVICE_NAME, session.createQueue(COMBUS.REPLICATION_SERVICE_QUEUE)); destinations.put(IResetService.SERVICE_NAME, session.createQueue(COMBUS.RESET_SERVICE_QUEUE)); destinations.put(IUpdateService.SERVICE_NAME, session.createQueue(COMBUS.UPDATE_SERVICE_QUEUE)); destinations.put(IQueryService.SERVICE_NAME, session.createQueue(COMBUS.QUERY_SERVICE_QUEUE)); destinations.put(IIndexService.SERVICE_NAME, session.createQueue(COMBUS.INDEX_SERVICE_QUEUE)); destinations.put(IExecutionService.SERVICE_NAME, session.createQueue(COMBUS.EXECUTION_SERVICE_QUEUE)); tempQueue = session.createTemporaryQueue(); messageProducer = session.createProducer(null); messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); messageConsumer = session.createConsumer(tempQueue); listener = new JMSMessageListener(); messageConsumer.setMessageListener(listener); connected = true; fireConnectionStateChange(INotificationConnectionListener.CONNECTED); } return; }
From source file:tools.ProducerTool.java
public void parseCommandLine(String[] args) { CommandLineParser parser = new PosixParser(); Options options = new Options(); Option ackModeOpt = OptionBuilder.withLongOpt("acknowledgement-mode").withArgName("ackMode").hasArg() .withDescription(//from w ww . j av a 2 s . c om "session acknowledgement mode: AUTO_ACKNOWLEDGE, CLIENT_ACKNOWLEDGE, DUPS_OK_ACKNOWLEDGE") .create("a"); options.addOption(ackModeOpt); Option clientIdOpt = OptionBuilder.withLongOpt("client-id").withArgName("id").hasArg() .withDescription("client id string that can optionally be set on a connection").create("c"); options.addOption(clientIdOpt); Option durableOpt = OptionBuilder.withLongOpt("durable").withDescription("create a durable subscriber") .create("d"); options.addOption(durableOpt); Option perMessageSleepOpt = OptionBuilder.withLongOpt("per-message-sleep").withArgName("millis").hasArg() .withDescription("amount of time (in ms) to sleep after receiving each message").create("e"); options.addOption(perMessageSleepOpt); Option connFactOpt = OptionBuilder.withLongOpt("connection-factory-name").withArgName("name").hasArg() .withDescription("name of the connection factory to lookup").create("f"); options.addOption(connFactOpt); Option numThreadsOpt = OptionBuilder.withLongOpt("num-threads").withArgName("num").hasArg() .withDescription("number of threads to run in parallel each with a connection").create("g"); options.addOption(numThreadsOpt); Option helpOpt = OptionBuilder.withLongOpt("help").withDescription("show help").create("h"); options.addOption(helpOpt); Option jndiDestOpt = OptionBuilder.withLongOpt("jndi-lookup-destination") .withDescription("lookup destinations with jndi").create("j"); options.addOption(jndiDestOpt); Option bytesLengthOpt = OptionBuilder.withLongOpt("bytes-message-length").withArgName("length").hasArg() .withDescription("use a bytes message of a specific length").create("l"); options.addOption(bytesLengthOpt); Option numMessagesOpt = OptionBuilder.withLongOpt("num-messages").withArgName("num").hasArg() .withDescription("number of messages to receive before stopping").create("m"); options.addOption(numMessagesOpt); Option destNameOpt = OptionBuilder.withLongOpt("destination-name").withArgName("name").hasArg() .withDescription("name of the destination to receive from").create("n"); options.addOption(destNameOpt); Option controlOpt = OptionBuilder.withLongOpt("final-control-message") .withDescription("use a control message as the final message").create("o"); options.addOption(controlOpt); Option tempOpt = OptionBuilder.withLongOpt("temporary-destination") .withDescription("use a temporary destination").create("p"); options.addOption(tempOpt); Option useQueueOpt = OptionBuilder.withLongOpt("queue-destination") .withDescription("use a queue destination").create("q"); options.addOption(useQueueOpt); Option transOpt = OptionBuilder.withLongOpt("transacted").withDescription("use a transacted session") .create("t"); options.addOption(transOpt); Option groupIdOpt = OptionBuilder.withLongOpt("message-group-id").withArgName("groupId").hasArg() .withDescription("JMSXGroupID").create("x"); options.addOption(groupIdOpt); Option batchSizeOpt = OptionBuilder.withLongOpt("batch-size").withArgName("size").hasArg() .withDescription( "size of the batch to ack or commit when using client ack mode or transacted sessions") .create("z"); options.addOption(batchSizeOpt); try { // parse the command line arguments CommandLine line = parser.parse(options, args); if (line.hasOption("h")) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("ProducerTool", options, true); System.exit(0); } if (line.hasOption("a")) { String ackModeStr = line.getOptionValue("a"); if (ackModeStr.equalsIgnoreCase("AUTO_ACKNOWLEDGE")) { acknowledgeMode = Session.AUTO_ACKNOWLEDGE; } else if (ackModeStr.equalsIgnoreCase("CLIENT_ACKNOWLEDGE")) { acknowledgeMode = Session.CLIENT_ACKNOWLEDGE; } else if (ackModeStr.equalsIgnoreCase("DUPS_OK_ACKNOWLEDGE")) { acknowledgeMode = Session.DUPS_OK_ACKNOWLEDGE; } else if (ackModeStr.equalsIgnoreCase("SESSION_TRANSACTED")) { acknowledgeMode = Session.SESSION_TRANSACTED; } else { throw new ParseException("Invalid value for acknowledge mode: " + ackModeStr); } } if (line.hasOption("c")) { clientId = line.getOptionValue("c"); } if (line.hasOption("d")) { durable = true; } if (line.hasOption("e")) { perMessageSleepMS = Integer.parseInt(line.getOptionValue("e")); } if (line.hasOption("f")) { connectionFactoryName = line.getOptionValue("f"); } if (line.hasOption("g")) { numThreads = Integer.parseInt(line.getOptionValue("g")); } if (line.hasOption("j")) { jndiLookupDestinations = true; } if (line.hasOption("l")) { bytesLength = Integer.parseInt(line.getOptionValue("l")); } if (line.hasOption("m")) { numMessages = Integer.parseInt(line.getOptionValue("m")); } if (line.hasOption("n")) { destinationName = line.getOptionValue("n"); } if (line.hasOption("o")) { useFinalControlMessage = true; } if (line.hasOption("p")) { useTemporaryDestinations = true; } if (line.hasOption("q")) { useQueueDestinations = true; } if (line.hasOption("t")) { transacted = true; } if (line.hasOption("x")) { messageGroupId = line.getOptionValue("x"); } if (line.hasOption("z")) { batchSize = Integer.parseInt(line.getOptionValue("z")); } } catch (ParseException exp) { LOGGER.error("Commandline parsing exception: " + exp.getMessage(), exp); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("ProducerTool", options, true); System.exit(-1); } }
From source file:com.headstrong.fusion.messaging.model.endpoint.binding.JmsBindingEndPointModeler.java
/** * Creates a {@link JmsComponent} using the parameters set. * // ww w . j a v a2s . c o m * @param routeBuilder * @return {@link JmsComponent} * @throws ProcessModellingException */ @SuppressWarnings("unchecked") private Component getJmsComponent(RouteBuilder routeBuilder) throws ProcessModellingException { JmsComponent jmsComponent = null; if (this.getProvider().equals(Provider.activemq.toString())) { jmsComponent = ActiveMQComponent.activeMQComponent(); jmsComponent.setConnectionFactory(new PooledConnectionFactory(this.getBrokerUrl())); jmsComponent.setCamelContext(routeBuilder.getContext()); jmsComponent.setAcknowledgementMode(Session.AUTO_ACKNOWLEDGE); } else if (this.getProvider().equals(Provider.ibmmq.toString())) { JmsConnectionFactory factory = null; try { JmsFactoryFactory jmsFactoryFactory; jmsFactoryFactory = JmsFactoryFactory.getInstance(JmsConstants.WMQ_PROVIDER); factory = jmsFactoryFactory.createConnectionFactory(); factory.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT); factory.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, this.getQueueManager()); factory.setStringProperty(WMQConstants.WMQ_HOST_NAME, this.getBrokerUrl()); factory.setIntProperty(WMQConstants.WMQ_PORT, this.getPort()); if (this.getChannel() != null && !this.getChannel().isEmpty()) factory.setStringProperty(WMQConstants.WMQ_CHANNEL, this.getChannel()); factory.setIntProperty(WMQConstants.DELIVERY_MODE, this.getDeliveryMode()); } catch (JMSException e) { logger.error("Error connecting to JMS provider.", e); throw new ProcessModellingException("Error connecting to JMS provider.", e); } UserCredentialsConnectionFactoryAdapter adapter = new UserCredentialsConnectionFactoryAdapter(); adapter.setTargetConnectionFactory(factory); if (this.getUserName() != null) { adapter.setUsername(this.getUserName()); } if (this.getPassword() != null) { adapter.setPassword(this.getPassword()); } jmsComponent = JmsComponent.jmsComponent(); jmsComponent.setConnectionFactory(adapter); jmsComponent.setCamelContext(routeBuilder.getContext()); jmsComponent.setAcknowledgementMode(Session.AUTO_ACKNOWLEDGE); } else { Hashtable<String, String> prop = new Hashtable<String, String>(); // Mandatory property. prop.put(Context.PROVIDER_URL, this.getLdapConfiguration().getProviderUrl()); prop.put(Context.INITIAL_CONTEXT_FACTORY, this.getLdapConfiguration().getInitialContextFactory()); // Only these optional properties supported now. if (this.getLdapConfiguration().getSecurityAuthentication() != null) { prop.put(Context.SECURITY_AUTHENTICATION, this.getLdapConfiguration().getSecurityAuthentication()); } if (this.getLdapConfiguration().getSecutiryPrincipal() != null) { prop.put(Context.SECURITY_PRINCIPAL, this.getLdapConfiguration().getSecutiryPrincipal()); } if (this.getLdapConfiguration().getSecutiryCredentials() != null) { prop.put(Context.SECURITY_CREDENTIALS, this.getLdapConfiguration().getSecutiryCredentials()); } Context context; ConnectionFactory connectionFactory; try { // HACK required to avoid ClassNotFoundException while // retrieving the // InitialContext. ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); context = new InitialContext(prop); connectionFactory = (ConnectionFactory) context .lookup(this.getLdapConfiguration().getConnectionFactoryJndiName()); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } // HACK -- Finished } catch (NamingException e) { logger.error("Error connecting to JMS provider.", e); throw new ProcessModellingException("Error connecting to JMS provider.", e); } UserCredentialsConnectionFactoryAdapter adapter = new UserCredentialsConnectionFactoryAdapter(); adapter.setTargetConnectionFactory(connectionFactory); if (this.getUserName() != null) { adapter.setUsername(this.getUserName()); } if (this.getPassword() != null) { adapter.setPassword(this.getPassword()); } jmsComponent = JmsComponent.jmsComponent(); jmsComponent.setConnectionFactory(adapter); jmsComponent.setCamelContext(routeBuilder.getContext()); jmsComponent.setAcknowledgementMode(Session.AUTO_ACKNOWLEDGE); } if (jmsComponent != null) { jmsComponent.setConcurrentConsumers(getThreadCount()); } return jmsComponent; }
From source file:com.facetime.communication.activemq.AmqConsumer.java
protected Session createSession() throws JMSException { return getConnection().createSession(false, Session.AUTO_ACKNOWLEDGE); }