i try to send mail using aspose but the build for program is runing for along time then give me errorthis is my code
public static void main(String[] args) {
SmtpClient client = new SmtpClient("smtp.gmail.com", 587, "kerolos", "MyPassword");
MailMessage message = new MailMessage();
message.setFrom(new MailAddress("sender#gmail.com"));
message.getTo().addMailAddress(new MailAddress("reciver#gmail.com"));
message.setBody("nothinge");
message.setSubject("me");
client.send(message);
}
for sure i downloaded and import all libarar that i need
this is my error
Exception in thread "main" class com.aspose.email.SmtpException: Failure sending mail. ---> class com.aspose.email.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
5.5.1 https://support.google.com/mail/?p=WantAuthError g73sm13415755wme.16 - gsmtp
com.aspose.email.abk.f(SourceFile:49)
com.aspose.email.asu.n(SourceFile:130)
com.aspose.email.cg.a(SourceFile:311)
com.aspose.email.internal.ah.h.a(Unknown Source)
com.aspose.email.internal.ah.j.run(Unknown Source)
java.lang.Thread.run(Thread.java:745)
--- End of inner exception stack trace ---
com.aspose.email.SmtpClient.a(SourceFile:1982)
com.aspose.email.SmtpClient.send(SourceFile:1785)
test.mina.main(mina.java:23)
at com.aspose.email.SmtpClient.a(SourceFile:1982)
at com.aspose.email.SmtpClient.send(SourceFile:1785)
at test.mina.main(mina.java:23)
Caused by: class com.aspose.email.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
5.5.1 https://support.google.com/mail/?p=WantAuthError g73sm13415755wme.16 - gsmtp
com.aspose.email.abk.f(SourceFile:49)
com.aspose.email.asu.n(SourceFile:130)
com.aspose.email.cg.a(SourceFile:311)
com.aspose.email.internal.ah.h.a(Unknown Source)
com.aspose.email.internal.ah.j.run(Unknown Source)
java.lang.Thread.run(Thread.java:745)
at com.aspose.email.abk.f(SourceFile:49)
at com.aspose.email.asu.n(SourceFile:130)
at com.aspose.email.cg.a(SourceFile:311)
at com.aspose.email.internal.ah.h.a(Unknown Source)
at com.aspose.email.internal.ah.j.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
Java returned: 1
BUILD FAILED (total time: 35 seconds)
GMail has strict rules for accessing emails by less secure applications. In order to allow GMail account to be accessed by less secure applications, you should enable the access by configuring your email account.
https://support.google.com/a/answer/6260879?hl=en
Please try it at your end and if the issue still persists, you can write to us on Aspose.Email forum for further assistance.
I work with Aspose as Developer Evangelist.
Related
Currently I am running Redis 6 with ACL and mTLS with a C# client just fine. I am trying to update our Java side to also use ACL and mTLS but have been running into issues. I am primarily focused on mTLS at the moment and have not been getting anywhere with it. This could be user fault in these that I have not used Java for 5-6 years before attempting to do this, so please advise. Not sure what or how to really progress from this error and I have done google searches with not success really. Any help greatly appreciated, again I have not done Java in a long time so that most likely might be the issue.
Trace:
Caused by: io.lettuce.core.RedisConnectionException: Unable to connect to localhost:6379
at io.lettuce.core.RedisConnectionException.create(RedisConnectionException.java:78)
at io.lettuce.core.RedisConnectionException.create(RedisConnectionException.java:56)
at io.lettuce.core.AbstractRedisClient.getConnection(AbstractRedisClient.java:295)
at io.lettuce.core.RedisClient.connect(RedisClient.java:214)
at io.lettuce.core.RedisClient.connect(RedisClient.java:199)
at blah blah blah my code....
... 48 more
Caused by: javax.net.ssl.SSLException: SSLEngine closed already
at io.netty.handler.ssl.SslHandler.wrap(SslHandler.java:834)
at io.netty.handler.ssl.SslHandler.wrapAndFlush(SslHandler.java:797)
at io.netty.handler.ssl.SslHandler.handleUnwrapThrowable(SslHandler.java:1254)
at io.netty.handler.ssl.SslHandler.decodeJdkCompatible(SslHandler.java:1230)
at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1271)
at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:505)
at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:444)
at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:283)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:374)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:360)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:352)
at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1422)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:374)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:360)
at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:931)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:163)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:700)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:635)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:552)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:514)
at io.netty.util.concurrent.SingleThreadEventExecutor$6.run(SingleThreadEventExecutor.java:1044)
at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
... 2 more
Redis Server Debug logs:
1:M 30 Jul 2020 15:23:10.837 - Accepted 10.0.2.2:62023
1:M 30 Jul 2020 15:23:11.024 # Error accepting a client connection: (null)
Java code:
final RedisClient client = RedisClient.create(RedisURI.Builder.redis(hostConfig,portConfig)
.withSsl(true).withVerifyPeer(false).build().toURI().toString());
if (redisTruststorePath != null && !redisTruststorePath.isEmpty()) {
SslOptions sslOptions;
if (redisKeystorePath != null && !redisKeystorePath.isEmpty()) {
sslOptions = SslOptions.builder()
.jdkSslProvider()
.keystore(new File(redisKeystorePath), redisKeystorePass)
.truststore(new File(redisTruststorePath), redisTruststorePass)
.build();
}
else {
sslOptions = SslOptions.builder()
.jdkSslProvider()
.truststore(new File(redisTruststorePath), redisTruststorePass)
.build();
}
client.setOptions(ClientOptions.builder().sslOptions(sslOptions).build());
}
client.connect();
Versions:
Lettuce version(s): 6.0.0.M1 (Running on windows locally)
Redis version: 6.0.5 (Running on linux VM locally)
Notes:
C# client is working fine so doubt its a Redis Server issue.
Redis URI (printed in my real code before set): rediss://localhost:6379
Please check your client-side logs.
16797:M 03 Aug 2020 09:11:11.246 # Error accepting a client connection: (null)
This message above happens when Redis wasn't able to continue with the connection phase. Such a message occurs in SSL arrangements when the SSL handshake wasn't completed successfully, e.g. caused by a failed certificate validation.
Looking at the code above, the client gets created with:
RedisClient.create(RedisURI.Builder.redis(hostConfig,portConfig) .withSsl(true).withVerifyPeer(false).build().toURI().toString());
The RedisURI object gets converted into a string which causes a loss of the verifyPeer flag.
Please change your code to:
RedisClient.create(RedisURI.Builder.redis(hostConfig,portConfig) .withSsl(true).withVerifyPeer(false).build());
by removing .toURI().toString().
As #mp911de mentioned I removed .toURI().toString(); as well as, updated to lettuce-core 6.0.0.RC and started using RESP2 (as suggested here). This resolved my problem. I think the main solution here was switching to RESP2, which again was a suggestion from #mp911de. Thank you for the assistance #mp911de!!
I've already researched the topic for a few days but none of the answers I found online did the trick for me.
Context: I've got a Spring Boot web application which sends automatic emails notifications using Java Mail API and Spring Boot Starter Mail.
It is using GMail SMTP server with a GSuite account. I recently upgraded to use Spring 5.0.6 and Spring Boot 2.0.2 and the email sending stopped working.
A few clues:
the Java code sending the email is the same as before
Gmail SMTP still works correctly (from another VM using older version of the application with the same settings and authentication, the emails are sent properly).
unless I am missing something, the application configuration remains the same as before
The things that have changed:
upgrade to Spring 5.0.6
upgrade to Spring Boot 2.0.2
changes in many places in the Java code to match this upgrades and add features in other parts of the app
The IP address of the VM is different than before (AWS EC2 instance)
Here are the relevant dependencies in pom.xml :
<!-- https://mvnrepository.com/artifact/javax.mail/javax.mail-api -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
Here is the application.yml relevant to Spring mail:
spring:
mail:
host: ${FT_MAIL_SMTP_HOST}
port: ${FT_MAIL_SMTP_PORT}
username: ${FT_MAIL_SMTP_USERNAME}
password: ${FT_MAIL_SMTP_PASSWORD}
debug: false
properties:
mail:
smtp:
starttls:
enable: ${FT_MAIL_SMTP_STARTTLS}
required: ${FT_MAIL_SMTP_TLSREQUIRED}
auth: ${FT_MAIL_SMTP_AUTH}
connectiontimeout: ${FT_MAIL_SMTP_CONN_TIMEOUT}
timeout: ${FT_MAIL_SMTP_TIMEOUT}
writetimeout: ${FT_MAIL_SMTP_WRITE_TIMEOUT}
These variables are defined in the environment:
FT_MAIL_SMTP_HOST=smtp.gmail.com
FT_MAIL_SMTP_PORT=587
FT_MAIL_SMTP_USERNAME=myaccount#myapp.com
FT_MAIL_SMTP_PASSWORD=mypassword
FT_MAIL_SMTP_STARTTLS=true
FT_MAIL_SMTP_TLSREQUIRED=true
FT_MAIL_SMTP_AUTH=true
FT_MAIL_SMTP_CONN_TIMEOUT=5000
FT_MAIL_SMTP_TIMEOUT=5000
FT_MAIL_SMTP_WRITE_TIMEOUT=5000
Here is the Spring #Service used to send the email (unchanged):
#Service
public class EmailServiceImpl {
#Autowired
public JavaMailSender emailSender;
#Autowired
private SpringTemplateEngine templateEngine;
#Value("${myapp.mail.from}")
private String fromAddress;
#Value("${myapp.mail.replyto}")
private String replyToAddress;
public void sendTemplatedMessage(String template, String to, String subject, Map<String, Object> model) throws MailException, MessagingException {
sendTemplatedMessage(template, to, fromAddress, replyToAddress, subject, model);
}
public void sendTemplatedMessage(String template, String to, String from, String subject, Map<String, Object> model) throws MailException, MessagingException {
sendTemplatedMessage(template, to, from, replyToAddress, subject, model);
}
private void sendTemplatedMessage(String template, String to, String from, String replyTo, String subject, Map<String, Object> model) throws MailException, MessagingException {
MimeMessage message = emailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message,
MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
StandardCharsets.UTF_8.name());
//helper.addAttachment("logo.png", new ClassPathResource("memorynotfound-logo.png"));
Context context = new Context();
context.setVariables(model);
String html = templateEngine.process(template, context);
helper.setTo(to);
helper.setFrom(from);
helper.setReplyTo(from);
helper.setSubject(subject);
helper.setText(html, true);
emailSender.send(message);
}
public void sendSimpleMessage(String to, String from, String subject, String text) {
try {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setFrom(from);
message.setSubject(subject);
message.setText(text);
emailSender.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now here is the error I get when trying to send an email:
04:42:19.900 [https-jsse-nio-443-exec-3] ERROR c.f.controller.StayController - Could not send Guest confirmation email to gfgorostidi#protonmail.com
org.springframework.mail.MailSendException: Failed to close server connection after message sending; nested exception is javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:482)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:359)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:354)
at com.myapp.util.EmailServiceImpl.sendTemplatedMessage(EmailServiceImpl.java:61)
at com.myapp.util.EmailServiceImpl.sendTemplatedMessage(EmailServiceImpl.java:35)
at com.myapp.controller.StayController.sendConfirmEmailToGuest(StayController.java:437)
at com.myapp.controller.StayController.saveStay(StayController.java:383)
at com.myapp.controller.StayController.createStay(StayController.java:163)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
......
......
......
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:844)
Caused by: javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2202)
at com.sun.mail.smtp.SMTPTransport.close(SMTPTransport.java:1212)
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:473)
... 104 more
Caused by: java.net.SocketTimeoutException: Read timed out
at java.base/java.net.SocketInputStream.socketRead0(Native Method)
at java.base/java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:171)
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.base/sun.security.ssl.SSLSocketInputRecord.read(SSLSocketInputRecord.java:425)
at java.base/sun.security.ssl.SSLSocketInputRecord.bytesInCompletePacket(SSLSocketInputRecord.java:65)
at java.base/sun.security.ssl.SSLSocketImpl.bytesInCompletePacket(SSLSocketImpl.java:918)
at java.base/sun.security.ssl.AppInputStream.read(AppInputStream.java:144)
at com.sun.mail.util.TraceInputStream.read(TraceInputStream.java:124)
at java.base/java.io.BufferedInputStream.fill(BufferedInputStream.java:252)
at java.base/java.io.BufferedInputStream.read(BufferedInputStream.java:271)
at com.sun.mail.util.LineInputStream.readLine(LineInputStream.java:89)
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2182)
... 106 more
org.springframework.mail.MailSendException: Failed to close server connection after message sending; nested exception is javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:482)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:359)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:354)
at com.myapp.util.EmailServiceImpl.sendTemplatedMessage(EmailServiceImpl.java:61)
at com.myapp.util.EmailServiceImpl.sendTemplatedMessage(EmailServiceImpl.java:35)
at com.myapp.controller.StayController.sendConfirmEmailToGuest(StayController.java:437)
at com.myapp.controller.StayController.saveStay(StayController.java:383)
at com.myapp.controller.StayController.createStay(StayController.java:163)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
......
......
......
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1468)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:844)
Caused by: javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2202)
at com.sun.mail.smtp.SMTPTransport.close(SMTPTransport.java:1212)
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:473)
... 104 more
Caused by: java.net.SocketTimeoutException: Read timed out
at java.base/java.net.SocketInputStream.socketRead0(Native Method)
at java.base/java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:171)
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.base/sun.security.ssl.SSLSocketInputRecord.read(SSLSocketInputRecord.java:425)
at java.base/sun.security.ssl.SSLSocketInputRecord.bytesInCompletePacket(SSLSocketInputRecord.java:65)
at java.base/sun.security.ssl.SSLSocketImpl.bytesInCompletePacket(SSLSocketImpl.java:918)
at java.base/sun.security.ssl.AppInputStream.read(AppInputStream.java:144)
at com.sun.mail.util.TraceInputStream.read(TraceInputStream.java:124)
at java.base/java.io.BufferedInputStream.fill(BufferedInputStream.java:252)
at java.base/java.io.BufferedInputStream.read(BufferedInputStream.java:271)
at com.sun.mail.util.LineInputStream.readLine(LineInputStream.java:89)
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2182)
... 106 more
I have tried setting an incorrect SMTP server or bad credentials and this made the connection fail, so I assumed the server and credentials are correct as they are, and the error happens after a successful connection.
The account used hasn't reached its limit, as another VM uses the same credentials and sends emails without problem.
I've tried changing "Start TLS" settings to false and use port 465 instead, but this isn't working either.
Any help is appreciated !! Thanks in advance!
After much more trial and error with the configuration, I found out that it required an application property "spring.mail.protocol" in the configuration.
I've added the line protocol: smtp in application.yml:
spring:
mail:
protocol: smtp
And that fixed the read timeout issue, email are now sent properly. Hope that may help someone in the future.
I did face the same issue, but my scenario was a bit different
I was trying to send in a schedule manner using quartz
When I did not use Quartz, it was all working fine, but with quartz it started failing
The above solution did not help me, but pointed me in direction of looking at the properties that I had set.
Increasing the connection timeout did the job for me
Thus changed the application properties
from:
spring.mail.properties.mail.smtp.timeout=3000
to:
spring.mail.properties.mail.smtp.timeout=25000
Hope it works for others as well
I have issue to accept all certs while using the VCloud SDK.
The problem is that there is a self signed cert on the machine and even with the FakeSSL object it is not working, it cannot accept all certs, how do I make a workaround to make it work?
VcloudClient.setLogLevel(Level.OFF);
vcloudClient = new VcloudClient(arg[0], Version.V5_5);
vcloudClient.registerScheme("<https>", 443, FakeSSLSocketFactory.getInstance());
vcloudClient.login(arg[1], arg[2]);
extension = vcloudClient.getVcloudAdminExtension();
Exception in thread "main" com.vmware.vcloud.sdk.VCloudRuntimeException: com.vmware.vcloud.sdk.VCloudRuntimeException: javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
at com.vmware.vcloud.sdk.VcloudClient.getSupportedVersions(VcloudClient.java:231)
at com.vmware.vcloud.sdk.VcloudClient.login(VcloudClient.java:329)
at sdt.ericsson.capacity.main.Main.main(Main.java:155)
Caused by: com.vmware.vcloud.sdk.VCloudRuntimeException: javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
at com.vmware.vcloud.sdk.RestUtil.getSupportedVersions(RestUtil.java:431)
at com.vmware.vcloud.sdk.VcloudClient.getSupportedVersions(VcloudClient.java:227)
... 2 more
Caused by: javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
at sun.security.ssl.SSLSessionImpl.getPeerCertificates(Unknown Source)
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:128)
at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:572)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:180)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:151)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:125)
at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:641)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:480)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)
at com.vmware.vcloud.sdk.RestUtil.getSupportedVersions(RestUtil.java:408)
... 3 more
There is my FakeSSLSocketFactory object (from the VMWere samples).
http://wklej.to/2nIV7/text
Any advice?
I switched to use the PERL SDK since it is working perfectly without http/s and API handling is even working for IP address instead, perfectly documented as well, and it pretty fast.
I tried to connect to my remote MySQL database, but I failed and got this error.
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The confusion is that It was effective when I used MySQL-Front tool to connect the remote database, and I can ping to the IP address successfully. but when I used my code, it wound show the error after about ten seconds.
Also when I used the wrong username or password in my code, it wound show the wrong verification immediately. Did that prove it is no problem to set up conection?
Here is my code(It can work on my localhost database):
public static void main(String[] args) {
String url = "jdbc:mysql://(IP address):3306/";
String dbName = "talk";
String driver = "com.mysql.jdbc.Driver";
String userName = "talkroot";
String password = "123456";
try {
Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(url + dbName,
userName, password);
System.out.println("connect");
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("end");
}
Here is the error:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
Last packet sent to the server was 0 ms ago.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1074)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2120)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:723)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:282)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.test.TestMySQL.main(TestMySQL.java:16)
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
Last packet sent to the server was 21298 ms ago.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1074)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3009)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2895)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3438)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1951)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2101)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2548)
at com.mysql.jdbc.ConnectionImpl.configureClientCharacterSet(ConnectionImpl.java:1802)
at com.mysql.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:3444)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2062)
... 12 more
Caused by: java.net.SocketException: Software caused connection abort: recv failed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at com.mysql.jdbc.util.ReadAheadInputStream.fill(ReadAheadInputStream.java:113)
at com.mysql.jdbc.util.ReadAheadInputStream.readFromUnderlyingStreamIfNecessary(ReadAheadInputStream.java:160)
at com.mysql.jdbc.util.ReadAheadInputStream.read(ReadAheadInputStream.java:188)
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:2452)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2906)
... 20 more
Anyone can help me please?
This com.mysql.jdbc.exceptions.jdbc4.CommunicationsException exception occurs if your database connection is idle for long time. This idle connection returns true on connection.isClosed(); but if we try to execute statement then it will fire this exception so I will suggest to go with database pooling.
Usually this error occurs when you don't use right port number. May be the machine which working on this database (client'db) has different port number. (Ex: 3307) . Go task manager==> Services ==> services and check is there other version of mysql. if they use 3306 change your port to 3307.
you can try to replace the mysql-connector-java-version.jar jar file. Some people update the jar file from 5.1.10 to 5.1.14, then it works. Wish you are luck..
update your drive version to:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.18</version>
Double Check the following things:
Verify whether the IP address/Port Number is correct or not
Ping to the server using ping "IP address" it may tells is the server in startup mode/shutdown mode
If you are getting connection objects from connection pool, verify
once connections availability.
Hope this information helps...
I solved it by removing the port number from the connection URL.
So instead of using connection string as:
jdbc:mysql://12x.xxx.xxx.xxx:1527/yourdbname
use
jdbc:mysql://12x.xxx.xxx.xxx/yourdbname
Also when I used the wrong username or password in my code, it wound show the wrong verification immediately. Did that prove it is no problem to set up conection?
this is probably done locally. so it doesn't relate to why your code isn't working.
There seems to be many ways to go about this, so you can try multiple things; people have solved this link failure in different ways as per their own situations:
Here are some the solutions:
changing "bind-address" attribute
Uncomment "bind-address" attribute or change it to one of the following IPs:
bind-address="127.0.0.1"
or
bind-address="0.0.0.0"
commenting out "skip-networking"
If there is a "skip-networking" line in your MySQL config file, make it comment by adding "#" sign at the beginning of that line.
change "wait_timeout" and "interactive_timeout"
Add these lines to the MySQL config file:
[wait_timeout][1] = number
interactive_timeout = number
connect_timeout = number
check Operating System proxy settings
Make sure the Fire wall, or Anti virus soft wares don't block MySQL service.
change connection string
Check your query string. your connection string should be some thing like this:
dbName = "my_database";
dbUserName = "root";
dbPassword = "";
String connectionString = "jdbc:mysql://localhost/" + dbName + "?user=" + dbUserName + "&password=" + dbPassword + "&useUnicode=true&characterEncoding=UTF-8";
Make sure you don't have spaces in your string. All the connection string should be continues without any space characters.
Try to replace "localhost" with your port, like 127.0.0.1.
Also try to add port number to your connection string, like:
String connectionString = "jdbc:mysql://localhost:3306/my_database?user=root&password=Pass&useUnicode=true&characterEncoding=UTF-8";
Usually default port for MySQL is 3306.
Don't forget to change username and password to the username and password of your MySQL server.
update your JDK driver library file
test different JDK and JREs (like JDK 6 and 7)
don't change max_allowed_packet
"[max_allowed_packet][4]" is a variable in MySQL config file that indicates the maximum packet size, not the maximum number of packets. So it will not help to solve this error.
change tomcat security
change TOMCAT6_SECURITY=yes to TOMCAT6_SECURITY=no
use validationQuery property
use validationQuery="select now()" to make sure each query has responses
AutoReconnect
Add this code to your connection string:
&autoReconnect=true&failOverReadOnly=false&maxReconnects=10
Your MySQL server isn't running. Check the same in the services page of the task manager if you are running Windows.
If you are working with Amazon Ubuntu instance then you have to follow this steps:
Check the amazon instance
Check the security group of instance
Assign the mysql/aura service and add your machine ip here or
service provider ip.
Please update your mysql configuration file in /etc/mysql/my.cnf file
By default, MySQL only allows connections from the localhost address. The configuration file is usually found in /etc/mysql/my.cnf
You will want to comment out the bind-address line by making it look like this:
#bind-address = 127.0.0.1
Next, you will need to restart the database server:
sudo /etc/init.d/mysql restart
I had faced this issue and struggled a lot like a lot. I did everything single thing said in all the portals and not worked for me. The only thing which worked to me was updating my jar file to the current new version . Earlier I was using 5.1.38 and now updated to 8.0.15 and just that my program worked super fine.
I'm running the following tutorial:
http://download.oracle.com/javase/6/docs/technotes/guides/security/jgss/tutorials/BasicClientServer.html
I'm getting the following prompts:
Connected to server localhost/127.0.0.1
Kerberos username [login]: {I enter my username here}
Kerberos password for login: {I enter my password here}
I get the following error:
Can you ascertain the root cause of this?
Exception in thread "main" GSSException: No valid credentials provided (Mechanism level: Attempt to obtain new INITIATE credentials failed! (null))
at sun.security.jgss.krb5.Krb5InitCredential.getTgt(Krb5InitCredential.java:333)
at sun.security.jgss.krb5.Krb5InitCredential.getInstance(Krb5InitCredential.java:128)
at sun.security.jgss.krb5.Krb5MechFactory.getCredentialElement(Krb5MechFactory.java:106)
at sun.security.jgss.krb5.Krb5MechFactory.getMechanismContext(Krb5MechFactory.java:172)
at sun.security.jgss.GSSManagerImpl.getMechanismContext(GSSManagerImpl.java:209)
at sun.security.jgss.GSSContextImpl.initSecContext(GSSContextImpl.java:195)
at sun.security.jgss.GSSContextImpl.initSecContext(GSSContextImpl.java:162)
at demo.SampleClient.main(SampleClient.java:145)
Caused by: javax.security.auth.login.LoginException: Message stream modified (41)
at com.sun.security.auth.module.Krb5LoginModule.attemptAuthentication(Krb5LoginModule.java:696)
at com.sun.security.auth.module.Krb5LoginModule.login(Krb5LoginModule.java:542)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at javax.security.auth.login.LoginContext.invoke(LoginContext.java:769)
at javax.security.auth.login.LoginContext.access$000(LoginContext.java:186)
at javax.security.auth.login.LoginContext$5.run(LoginContext.java:706)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.login.LoginContext.invokeCreatorPriv(LoginContext.java:703)
at javax.security.auth.login.LoginContext.login(LoginContext.java:575)
at sun.security.jgss.GSSUtil.login(GSSUtil.java:246)
at sun.security.jgss.krb5.Krb5Util.getTicket(Krb5Util.java:136)
at sun.security.jgss.krb5.Krb5InitCredential$1.run(Krb5InitCredential.java:328)
at java.security.AccessController.doPrivileged(Native Method)
at sun.security.jgss.krb5.Krb5InitCredential.getTgt(Krb5InitCredential.java:325)
... 7 more
Caused by: KrbException: Message stream modified (41)
at sun.security.krb5.KrbKdcRep.check(KrbKdcRep.java:53)
at sun.security.krb5.KrbAsRep.<init>(KrbAsRep.java:96)
at sun.security.krb5.KrbAsReq.getReply(KrbAsReq.java:449)
at sun.security.krb5.Credentials.sendASRequest(Credentials.java:410)
at sun.security.krb5.Credentials.acquireTGT(Credentials.java:378)
at com.sun.security.auth.module.Krb5LoginModule.attemptAuthentication(Krb5LoginModule.java:662)
... 23 more
I got exceptions “Message stream modified (41)”, when the Kerberos realm didn’t match. The realm (in system property java.security.krb5.realm) has to match exactly, including upper/lower case.
I'm wondering if this is a possibility (ie even if registry key is set, locked out for local administrators):
http://cr.openjdk.java.net/~weijun/special/krb5winguide-2/raw_files/new/kwin
Known Issues
If an AD account is also added into local administrator group on the
client PC, Microsoft restricts such client from getting the session key
for tickets (even if you set the allowtgtsessionkey registry key to 1).
The workaround is: Just forget you're a logged in user, call kinit.exe.
Do not depends on LSA credential cache.
I cannot confirm that issue. I do have admin rights on my machine and still are able to obtain the session key from the LSA. You should enable full debug ouput on JGSS and the Krb5LoginModule. Share your krb5.ini and login.conf too. I hope your are aware that the above example cannot work because your client cannot obtain a ticket for a local host. It has to be a FQDN with an appropriate SPN set in the Active Directory.