Please help me.
I can't send a normal hello world to the queue. Because it gives an authorization error. The fact is that the connection to the queue manager is carried out through the user, a password is not needed for it. I can't figure out what exactly I'm doing wrong.
import javax.jms.*;
import javax.jms.Message;
import com.ibm.mq.jms.*;
import com.ibm.msg.client.jms.JmsConnectionFactory;
import com.ibm.msg.client.jms.JmsFactoryFactory;
import com.ibm.msg.client.jms.internal.JmsFactoryFactoryImpl;
import com.ibm.msg.client.wmq.WMQConstants;
import org.apache.camel.Producer;
public class SenderMQ {
public static void main(String[] args){
String QMName = "";
String requstQueueName = "";
try {
JmsFactoryFactory jff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
JmsConnectionFactory jcf = jff.createConnectionFactory();
jcf.setStringProperty(WMQConstants.WMQ_HOST_NAME, host);
jcf.setIntProperty(WMQConstants.WMQ_PORT, 1414);
jcf.setStringProperty(WMQConstants.WMQ_CHANNEL,"SYSTEM.ADMIN.SVRCONN");
jcf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE,WMQConstants.WMQ_CM_CLIENT);
jcf.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER,"N_QM");
jcf.setStringProperty(WMQConstants.USER_AUTHENTICATION_MQCSP, String.valueOf(true));
jcf.setStringProperty(WMQConstants.USERID, "admin");
jcf.setStringProperty(WMQConstants.PASSWORD, null);
Connection connection = jcf.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue("queue://EGG_TEST_IN");
MessageProducer producer = session.createProducer(destination);
long uniqueNUmber = System.currentTimeMillis()%1000;
String mess_xml = "<?xml version=\"1.0\" encoding=\"UTF8\"?><RequestMessage xmlns=\"MQMessage\" processID=\"FD12C7B4617F11ecB2E0005056AD53F8\" serviceID=\"SMEV3_ESIA3_IM\" departmentID=\"0\" systemID=\"SBL_FR:ULBSFCNT\"><Request>PFRvU21ldiBIRVhDb2RlPSJTdHJpbmciIHhtbG5zOm5zND0iaHR0cDovL3NjaGVtYXMub3JhY2xlLmNvbS9icGVsL2V4dGVuc2lvbiIgeG1sbnM6bnM2PSJ1cm46Ly9taW5jb21zdnlhei9jb21tb25zL2ludGVncmF0aW9uX21vZHVsZV90eXBlcy8xLjAuMSIgeG1sbnM6bnM1PSJ1cm46Ly94LWFydGVmYWN0cy1zbWV2LWdvdi1ydS9zZXJ2aWNlcy9tZXNzYWdlLWV4Y2hhbmdlL3R5cGVzLzEuMSIgeG1sbnM6bnM3PSJ1cm46Ly9taW5jb21zdnlhei9pbnRlcmdyYXRpb25fbW9kdWxlLzEuMC4xIiB4bWxuczp0bnM9Imh0dHA6Ly93d3cuYnNzeXMuY29tL3Byb2R1Y3RzL2Jzcy1lZ2cvU01FVjNfRVNJQTNfSU0iIHhtbG5zPSJodHRwOi8vd3d3LmJzc3lzLmNvbS9wcm9kdWN0cy9ic3MtZWdnL1NNRVYzX0VTSUEzX0lNIj48dG5zOkNvbnRlbnRUb1NtZXYgU2VhcmNoQWdlPSIzMCIgUmVxdWVzdE1vZGU9InhvciIgVHJhbnNmZXJNZXRob2Q9IjIiPjxuczc6VXNlck9yZGVyUmVxdWVzdD48bnM3OlJvdXRpbmdDb2RlPlBST0Q8L25zNzpSb3V0aW5nQ29kZT48bnM3OnBlcnNvbj48bnM2OnNuaWxzPjEzMi05OTEtOTg3IDk5PC9uczY6c25pbHM+PG5zNjpmaXJzdE5hbWU+0JTQvNC40YLRgNC40Lk8L25zNjpmaXJzdE5hbWU+PG5zNjpsYXN0TmFtZT7QodC60LjQtNCw0L3QvtCyPC9uczY6bGFzdE5hbWU+PG5zNjpzZWNvbmROYW1lPtCU0LzQuNGC0YDQuNC10LLQuNGHPC9uczY6c2Vjb25kTmFtZT48bnM2OmJkYXRlPjE5NzItMDEtMjk8L25zNjpiZGF0ZT48bnM2OnBhc3Nwb3J0PjxuczY6c2VyaWVzPjYwIDE1PC9uczY6c2VyaWVzPjxuczY6bnVtPjkwMzA3MzwvbnM2Om51bT48bnM2Omlzc3VlRGF0ZT4yMDE2LTAyLTA5PC9uczY6aXNzdWVEYXRlPjxuczY6aXNzdWVDb2RlPjYxMC0wMDI8L25zNjppc3N1ZUNvZGU+PC9uczY6cGFzc3BvcnQ+PG5zNjpwaG9uZT4rNyAoOTM4KSAxMDItMjItMDk8L25zNjpwaG9uZT48L25zNzpwZXJzb24+PG5zNzpzZXJ2aWNlRm9ybUNvZGU+MTAwMDAwOTI1NTc8L25zNzpzZXJ2aWNlRm9ybUNvZGU+PG5zNzpzZXJ2aWNlQ29kZT4xMDAwMDU2OTUyNDwvbnM3OnNlcnZpY2VDb2RlPjwvbnM3OlVzZXJPcmRlclJlcXVlc3Q+PC90bnM6Q29udGVudFRvU21ldj48dG5zOkF0dGFjaG1lbnRzPjx0bnM6QXR0YWNobWVudD48dG5zOkZpbGVEYXRhLz48L3RuczpBdHRhY2htZW50PjwvdG5zOkF0dGFjaG1lbnRzPjwvVG9TbWV2Pg==</Request></RequestMessage>";
TextMessage messag = session.createTextMessage(mess_xml);
connection.start();
producer.send(messag);
} catch (JMSException e) {
e.printStackTrace();
}
}
}
What to do with such a output:
com.ibm.msg.client.jms.DetailedJMSSecurityException: JMSWMQ2013: The
security authentication was not valid that was supplied for
QueueManager 'N_MQ' with connection mode 'Client' and host name
'localhost(1414)'. Please check if the supplied username and password
are correct on the QueueManager to which you are connecting.
at com.ibm.msg.client.wmq.common.internal.Reason.reasonToException(Reason.java:531)
at com.ibm.msg.client.wmq.common.internal.Reason.createException(Reason.java:215)
at com.ibm.msg.client.wmq.internal.WMQConnection.<init>(WMQConnection.java:424)
at com.ibm.msg.client.wmq.factories.WMQConnectionFactory.createV7ProviderConnection(WMQConnectionFactory.java:8475)
at com.ibm.msg.client.wmq.factories.WMQConnectionFactory.createProviderConnection(WMQConnectionFactory.java:7815)
at com.ibm.msg.client.jms.admin.JmsConnectionFactoryImpl._createConnection(JmsConnectionFactoryImpl.java:303)
at com.ibm.msg.client.jms.admin.JmsConnectionFactoryImpl.createConnection(JmsConnectionFactoryImpl.java:236)
at com.ibm.mq.jms.MQConnectionFactory.createCommonConnection(MQConnectionFactory.java:6016)
at com.ibm.mq.jms.MQConnectionFactory.createConnection(MQConnectionFactory.java:6041)
at SenderMQ.main(SenderMQ.java:28)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)
Caused by: com.ibm.mq.MQException: JMSCMQ0001: IBM MQ call failed with
compcode '2' ('MQCC_FAILED') reason '2035' ('MQRC_NOT_AUTHORIZED').
at com.ibm.msg.client.wmq.common.internal.Reason.createException(Reason.java:203)
... 13 more
Related
I have a ActiveMQ consumer script running in Java where I am calling consumer.receive() in a while(true) loop.
I need to implement timeout for each message processed (eg: if a message process goes beyond 15 seconds I have to receive the next one).
I have given the client acknowledge mode for ACK.
Please look at the consumeMessage method where I have implemented the consume.
Desired outcome:
After 15 seconds the first message needs to be discarded (i.e. it should not invoke acknowledge()). The next message needs to be processed instead.
//package consumer;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
public class ActivmqConsumer implements ExceptionListener {
ActiveMQConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
public ActivmqConsumer() throws Exception{
String USERNAME = "admin";
String PASSWORD = "admin";
this.connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, "tcp://192.168.56.101:61616?jms.prefetchPolicy.all=1");
// Create a Connection
this.connection = connectionFactory.createConnection();
connection.start();
connection.setExceptionListener(this);
// Create a Session
this.session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
}
public void consumeMessage(String destinationName, EventProcesser eventprocess){
Destination destination = null;
MessageConsumer consumer = null;
try{
// Create the destination (Topic or Queue)
destination = session.createQueue(destinationName);
// Create a MessageConsumer from the Session to the Topic or Queue
consumer = session.createConsumer(destination);
// Wait for a message
while(true){
Message message = consumer.receive(2);
if(message==null){
continue;
}
else if(message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
String text = textMessage.getText();
System.out.println("Received: " + text);
eventprocess.processEvent(text);
message.acknowledge();
} else{
System.out.println("Received: " + message);
}
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
try{
consumer.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
}
There is no "max message processing time" or equivalent feature in ActiveMQ. You'll need to monitor the processing yourself. Maybe take a look at this question/answer for ideas on how to do that. An alternative would be to use a JTA transaction manager and consume the message in a transaction with a timeout of 15 seconds. Using an MDB in a Java EE container would be a simple way to get the transaction timeout functionality.
New to JMS
Requirement - connect to Message queue . try to send some file/message to test the connection.
Getting Error- ERROR yarn.ApplicationMaster: User class threw exception: java.io.IOException: Failed to bind to server socket: tcp://dbusmq-sd00007.svc.db.com:1427 due to: java.net.BindException: Cannot assign requested address (Bind failed)
java.io.IOException: Failed to bind to server socket: tcp://dbusmq-sd00007.svc.db.com:1427 due to: java.net.BindException: Cannot assign requested address (Bind failed)
its firewall/SSL issue or something wrong with code ?
package practice;
import java.net.URI;
import java.net.URISyntaxException;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerFactory;
import org.apache.activemq.broker.BrokerService;
public class jmsQueue {
public static void main(String[] args) throws URISyntaxException, Exception {
BrokerService broker = BrokerFactory.createBroker(new URI(
"broker:(tcp://dbusmq-sd00007.svc.db.com:1427)"));
broker.start();
Connection connection = null;
try {
// Producer
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
"tcp://dbusmq-sd00007.svc.db.com:1427");
connection = connectionFactory.createConnection();
Session session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue("QM.SU00007");
String payload = "Testing helloworld";
Message msg = session.createTextMessage(payload);
MessageProducer producer = session.createProducer(queue);
System.out.println("Sending text '" + payload + "'");
producer.send(msg);
// Consumer
/* MessageConsumer consumer = session.createConsumer(queue);
connection.start();
TextMessage textMsg = (TextMessage) consumer.receive();
System.out.println(textMsg);
System.out.println("Received: " + textMsg.getText());*/
session.close();
} finally {
if (connection != null) {
connection.close();
}
broker.stop();
}
}
}
I'm currently working on a JMS project and I have created 2 keys and 2 certificates as well as a TrustStorage, mytruststore which I created through Qpid's UI.
In my jndi.properties file I have the following code:
//Set the InitialContextFactory class to use
java.naming.factory.initial = org.apache.qpid.jms.jndi.JmsInitialContextFactory
//Define the required ConnectionFactory instances
//connectionfactory.<JNDI-lookup-name> = <URI>
connectionfactory.myFactoryLookup = amqp://localhost:5672
connectionfactory.producerConnectionFactory = amqp://admin:admin#?brokerlist='tcp://localhost:5672?encryption_remote_trust_store='$certificates%255c/mytruststore''
connectionfactory.consumer1ConnectionFactory = amqp://admin:admin#?brokerlist='tcp://localhost:5672?encryption_key_store='C:\OpenSSL-Win64\bin\mytruststorage.jks'&encryption_key_store_password='thanos''
connectionfactory.consumer2ConnectionFactory = amqp://admin:admin#?brokerlist='tcp://localhost:5672?encryption_key_store='C:\OpenSSL-Win64\bin\mytruststorage.jks'&encryption_key_store_password='thanos''
//Configure the necessary Queue and Topic objects
//queue.<JNDI-lookup-name> = <queue-name>
//topic.<JNDI-lookup-name> = <topic-name>
queue.myQueueLookup = queue
topic.myTopicLookup = topic
queue.myTestQueue = queue
In my EncryptionExample.java class I have the following code:
package org.apache.qpid.jms.example;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.jms.BytesMessage;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class EncryptionExample {
public EncryptionExample() {
}
public static void main(String[] args) throws Exception {
EncryptionExample encryptionExampleApp = new EncryptionExample();
encryptionExampleApp.runProducerExample();
encryptionExampleApp.runReceiverExample();
}
private void runProducerExample() throws Exception
{
Connection connection = createConnection("producerConnectionFactory");
try {
Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
Destination destination = createDesination("myTestQueue");
MessageProducer messageProducer = session.createProducer(destination);
TextMessage message = session.createTextMessage("Hello world!");
// ============== Enable encryption for this message ==============
message.setBooleanProperty("x-qpid-encrypt", true);
// ============== Configure recipients for encryption ==============
message.setStringProperty("x-qpid-encrypt-recipients", "CN=client1, OU=Qpid, O=Apache, C=US");
messageProducer.send(message);
session.commit();
}
finally {
connection.close();
}
}
private void runReceiverExample() throws Exception
{
Connection connection = createConnection("consumer1ConnectionFactory");
try {
connection.start();
Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
Destination destination = createDesination("myTestQueue");
MessageConsumer messageConsumer = session.createConsumer(destination);
Message message = messageConsumer.receive();
if (message instanceof TextMessage) {
// application logic
System.out.println(((TextMessage) message).getText());
} else if (message instanceof BytesMessage) {
// handle potential decryption failure
System.out.println("Potential decryption problem. Application not in list of intended recipients?");
}
session.commit();
}
finally {
connection.close();
}
}
///////////////////////////////////////
// The following is boilerplate code //
///////////////////////////////////////
private Connection createConnection(final String connectionFactoryName) throws JMSException, IOException, NamingException
{
try (InputStream resourceAsStream = getResourceAsStream("jndi.properties")) {
Properties properties = new Properties();
properties.load(resourceAsStream);
Context context = new InitialContext(properties);
ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup(connectionFactoryName);
final Connection connection = connectionFactory.createConnection();
context.close();
return connection;
}
}
private InputStream getResourceAsStream(String string) {
// TODO Auto-generated method stub
return null;
}
private Destination createDesination(String desinationJndiName) throws IOException, NamingException
{
try (InputStream resourceAsStream = this.getClass().getResourceAsStream("example.properties")) {
Properties properties = new Properties();
properties.load(resourceAsStream);
Context context = new InitialContext(properties);
Destination destination = (Destination) context.lookup(desinationJndiName);
context.close();
return destination;
}
}
}
When I'm trying to build it I get the following exceptions.
Exception in thread "main" java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Unknown Source)
at java.util.Properties.load0(Unknown Source)
at java.util.Properties.load(Unknown Source)
at
org.apache.qpid.jms.example.EncryptionExample.createConnection(EncryptionExample.java:106)
at
org.apache.qpid.jms.example.EncryptionExample.runProducerExample(EncryptionExample.java:54)
at org.apache.qpid.jms.example.EncryptionExample.main(EncryptionExample.java:48)
I assume that something's wrong with the following code in jndi.properties file:
connectionfactory.myFactoryLookup = amqp://localhost:5672
connectionfactory.producerConnectionFactory = amqp://admin:admin#?brokerlist='tcp://localhost:5672?encryption_remote_trust_store='$certificates%255c/mytruststore''
connectionfactory.consumer1ConnectionFactory = amqp://admin:admin#?brokerlist='tcp://localhost:5672?encryption_key_store='C:\OpenSSL-Win64\bin\mytruststorage.jks'&encryption_key_store_password='thanos''
connectionfactory.consumer2ConnectionFactory = amqp://admin:admin#?brokerlist='tcp://localhost:5672?encryption_key_store='C:\OpenSSL-Win64\bin\mytruststorage.jks'&encryption_key_store_password='thanos''
This is my solution Explorer:
This first and biggest problem you have is that you are trying to use connection URIs and client features from a client other than the one you have configured you project to use. You seem to be using Qpid JMS which is the new AMQP 1.0 client developed at the Qpid project. This client uses a different URI syntax that the previous AMQP 0.x clients and you will get exception from the connection factory when passing in these invalid URIs.
The other problem you will have (which was called out in the comments on your post) is that there is not message encryption feature in the AMQP 1.0 JMS client so that would be your next problem once you got the URIs correctly defined.
The documentation for the newer AMQP 1.0 JMS client is here.
You cannot use // for comments in Properties files. Use # or ! instead.
See: https://docs.oracle.com/javase/8/docs/api/java/util/Properties.html#load-java.io.Reader-
I have a web application developed with "pure" JSP, Servlet and Hibernate. It is also working with Java Mail. The Java mail function is working almost every machine we tested here, until today. It didn't work on the deployment server (it is actually a windows 7 PC I think bcs it has a GUI). It gave me the below error
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: mail.xxx.com, 25; timeout -1;
nested exception is:
java.net.ConnectException: Connection timed out: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2053)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:69
7)
at javax.mail.Service.connect(Service.java:386)
at javax.mail.Service.connect(Service.java:245)
at javax.mail.Service.connect(Service.java:194)
at javax.mail.Transport.send0(Transport.java:253)
at javax.mail.Transport.send(Transport.java:124)
at RemindeWorker.Listener.MailClient.sendEmail(MailClient.java:65)
at Filter.AuthenticationFilter_Level1.doFilter(AuthenticationFilter_Leve
l1.java:99)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Appl
icationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationF
ilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperV
alve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextV
alve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(Authentica
torBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.j
ava:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.j
ava:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:
950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineVal
ve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.jav
a:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp
11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(
AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoin
t.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.
java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor
.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskTh
read.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketI
mpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.ja
va:345)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocket
Impl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java
:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:312)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:236)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2019)
... 25 more
Level1 executed
NUM is: 1
Below is my Code.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package RemindeWorker.Listener;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
*
* #author Yohan
*/
public class MailClient
{
public void sendEmail(final String userName, final String password, final String host, final String html, final List<String>emails, String subject) throws MessagingException
{
System.out.println("User Name: "+userName);
System.out.println("Password: "+password);
System.out.println("Host: "+host);
// String host="mail.xxx.com";
// final String user="abc#xxx.com";//change accordingly
// final String password="knight55";//change accordingly
//Get the session object
Properties props = new Properties();
props.put("mail.smtp.host",host);
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName,password);
}
});
if(!emails.isEmpty())
{
//Compose the message
InternetAddress[] address = new InternetAddress[emails.size()];
for (int i = 0; i < emails.size(); i++) {
address[i] = new InternetAddress(emails.get(i));
}
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(userName));
message.setRecipients(Message.RecipientType.TO, address);
message.setSubject(subject);
message.setContent(html,"text/html");
//send the message
Transport.send(message);
System.out.println("message sent successfully...");
}
else
{
System.out.println("No Recieptions");
}
}
}
What kind of thing is stopping my application from sending emails? The sever is having JRE 8 and XAMPP. Server admin says the firewall is turned off!
The issue was that port 25 was blocked in the server by somehow. The default port for SMTP is port 25. I changed the port for the Java mail using Properties and it worked.
I have been trying to learn ActiveMQ and JMS. When I compile the following code I get the above exception. Although, I have attached the right jar files for JMS and ActiveMQ. Eclipse asks me to add a cast to the ConnectionFactory object when I try to create a connection (i.e. connectionFactory.createConnection()) using the ConnectionFactory object. The codes that I see everywhere on the internet are the same as I have written.
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
public class JMSProducer {
public static void main(String[] args) {
try {
// Create a ConnectionFactory
ConnectionFactory connectionFactory=new ActiveMQConnectionFactory("admin", "admin",
ActiveMQConnection.DEFAULT_BROKER_URL);
// Create a Connection
Connection connection = connectionFactory.createConnection();
//Error seen in above line
connection.start();
// Create a Session
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// Create the destination
Destination destination = session.createQueue("testQ");
// Create a MessageProducer from the Session to the Queue
MessageProducer producer = session.createProducer(destination);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
// Create a messages
TextMessage message = session.createTextMessage("Helloworld");
producer.send(message);
session.close();
connection.close();
System.out.println("Message sent");
}
catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
}
}
Sholud have done ActiveMQConnection connection = connectionFactory.createConnection(); instead of Connection connection = connectionFactory.createConnection();. Now the code is running fine.