I'm getting Connection refused when I try to connect to a remote Oracle database.
I can successfully telnet to the same IP address and port and I can even connect via SQL Developer or IntelliJ Idea's Database tab using the same credentials, but when I try it from my code I get the exception.
Note:
I'm Using Ubuntu, IntelliJ IDEA, Tomcat 7, Oracle JDBC Driver v7.0.
The following standalone code throws the same exception:
public static void main(String[] argv) {
System.out.println("-------- Oracle JDBC Connection Testing ------");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return;
}
System.out.println("Oracle JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:oracle:thin:10.1.1.27:1521:xe", "user", "password");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
}
Output:
Oracle JDBC Driver Registered!
java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:673)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:715)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:385)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:30)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:564)
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at com.greenmile.web.DBConnectionTest.main(DBConnectionTest.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: oracle.net.ns.NetException: The Network Adapter could not establish the connection
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:445)
at oracle.net.resolver.AddrResolution.resolveAndExecute(AddrResolution.java:464)
at oracle.net.ns.NSProtocol.establishConnection(NSProtocol.java:594)
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:229)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1360)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:486)
... 12 more
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at oracle.net.nt.TcpNTAdapter.connect(TcpNTAdapter.java:162)
at oracle.net.nt.ConnOption.connect(ConnOption.java:133)
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:411)
... 17 more
Connection Failed! Check output console
Replace you jdbc connect string "jdbc:oracle:thin:10.1.1.27:1521:xe" with "jdbc:oracle:thin:#10.1.1.27:1521/xe"
explanation here
Related
I have a Jenkins pipeline that simply does this:
pipeline {
agent any
stages {
stage('Build') {
steps {
sh "./mvnw -version"
}
}
}
}
The problem is it throws an exception: java.net.ConnectException: Connection refused. Any idea how I can fix or troubleshoot it?
Running shell script
+ ./mvnw -version
Exception in thread "main" java.net.ConnectException: (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:668)
at sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:173)
at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:432)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:527)
at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:264)
at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:367)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:191)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1138)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1032)
I just use docker to install rabbitmq, and I ran it with command:
docker run -d --hostname rabbitTest --name rabbitmq -p 5672:5672 -p 15672:15672 -v /etc/rabbitmq:/etc/rabbitmq daocloud.io/library/rabbitmq:3.6.9
And following is the config file of rabbitmq:
[ { rabbit, [
{ loopback_users, ["ehoo100"] },
{ tcp_listeners, [ {"0.0.0.0", 5672} ] },
{ ssl_listeners, [ ] },
{ hipe_compile, false }
] } ]
I can access the web management with http://ip:15672, but when I use spring-boot to connect to it, it will cause refused connection exception.
Here are my spring-boot config:
public ConnectionFactory connectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory(rabbitMQProperties.getHost(),rabbitMQProperties.getPort());
connectionFactory.setUsername(rabbitMQProperties.getUsername());
connectionFactory.setPassword(rabbitMQProperties.getPassword());
connectionFactory.setVirtualHost(rabbitMQProperties.getVirtualHost());
connectionFactory.setPublisherConfirms(true);
return connectionFactory;
}
The port is 5672, and the exception stack trace:
org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused
at org.springframework.amqp.rabbit.support.RabbitExceptionTranslator.convertRabbitAccessException(RabbitExceptionTranslator.java:62)
at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.createBareConnection(AbstractConnectionFactory.java:368)
at org.springframework.amqp.rabbit.connection.CachingConnectionFactory.createConnection(CachingConnectionFactory.java:565)
at org.springframework.amqp.rabbit.core.RabbitTemplate.doExecute(RabbitTemplate.java:1430)
at org.springframework.amqp.rabbit.core.RabbitTemplate.execute(RabbitTemplate.java:1411)
at org.springframework.amqp.rabbit.core.RabbitTemplate.execute(RabbitTemplate.java:1387)
at org.springframework.amqp.rabbit.core.RabbitAdmin.getQueueProperties(RabbitAdmin.java:336)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.redeclareElementsIfNecessary(SimpleMessageListenerContainer.java:1136)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1387)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at com.rabbitmq.client.impl.SocketFrameHandlerFactory.create(SocketFrameHandlerFactory.java:50)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:907)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:859)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1000)
at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.createBareConnection(AbstractConnectionFactory.java:356)
... 8 common frames omitted
I have a Spring Batch with Spring boot Application in which I am reading data from external Oracle DB and Writing it to SQL Server in production environment. I am validating the connection before reading the data but even then getting Closed Connection issue.Is anyone aware of this issue ? Below is the Datasource config code and error logs.
#Slf4j
#Configuration
public class DataSourceReaderConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(DataSourceReaderConfig.class);
#Autowired
private Environment env;
#SuppressWarnings("deprecation")
#ConfigurationProperties(prefix = "oracle.datasource")
#Bean(name="dataSourceReader")
#Primary
public DataSource dataSourceReader() {
LOGGER.info("Inside dataSourceReader Method");
DataSource datasource = new DataSource();
OracleDataSource ocpds = null;
try {
ocpds = new OracleDataSource();
} catch (SQLException e1) {
LOGGER.error("Error getting Oracle Datasource Connection = " + e1.getMessage());
}
ocpds.setURL(env.getProperty("oracle.datasource.url"));
ocpds.setUser(env.getProperty("oracle.datasource.username"));
ocpds.setPassword(env.getProperty("oracle.datasource.password"));
try {
ocpds.setImplicitCachingEnabled(true);
} catch (SQLException e2) {
LOGGER.error("Error Setting OracleDataSource ImplicitCachingEnabled = " + e2.getMessage());
}
try {
ocpds.setConnectionCachingEnabled(true);
} catch (SQLException e1) {
LOGGER.error("Error Setting OracleDataSource ConnectionCachingEnabled = " + e1.getMessage());
}
Properties cacheProps = new Properties();
cacheProps.setProperty("ValidateConnection","true");
try {
ocpds.setConnectionCacheProperties(cacheProps);
} catch (SQLException e) {
LOGGER.error("Error Setting OracleDataSource Connection Cache Properites = " + e.getMessage());
}
datasource.setDataSource(ocpds);
return datasource;
}
}
[0m[0m09:00:00,000 INFO [com.elm.salamah.scheduler.batch.configuration.CityBatchConfiguration] (pool-3130-thread-1) Job2 importCitiesJob Started at : Thu Dec 07 09:00:00 AST 2017
[0m[31m09:00:00,066 ERROR [org.springframework.scheduling.support.TaskUtils$LoggingErrorHandler] (pool-3130-thread-1) Unexpected error occurred in scheduled task.: org.springframework.transaction.CannotCreateTransactionException: Could not open JDBC Connection for transaction; nested exception is java.sql.SQLRecoverableException: Closed Connection
at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:289)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:447)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:277)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy3242.getLastJobExecution(Unknown Source)
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:98)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy3241.run(Unknown Source)
at com.elm.salamah.scheduler.batch.configuration.CityBatchConfiguration.performSecondJob(CityBatchConfiguration.java:88)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:65)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.sql.SQLRecoverableException: Closed Connection
at oracle.jdbc.driver.PhysicalConnection.needLine(PhysicalConnection.java:5389)
at oracle.jdbc.driver.OracleStatement.closeOrCache(OracleStatement.java:1578)
at oracle.jdbc.driver.OracleStatement.close(OracleStatement.java:1563)
at oracle.jdbc.driver.OracleStatementWrapper.close(OracleStatementWrapper.java:94)
at oracle.jdbc.driver.PhysicalConnection.setTransactionIsolation(PhysicalConnection.java:4620)
at sun.reflect.GeneratedMethodAccessor276.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.tomcat.jdbc.pool.ProxyConnection.invoke(ProxyConnection.java:126)
at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:108)
at org.apache.tomcat.jdbc.pool.interceptor.AbstractCreateStatementInterceptor.invoke(AbstractCreateStatementInterceptor.java:79)
at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:108)
at org.apache.tomcat.jdbc.pool.DisposableConnectionFacade.invoke(DisposableConnectionFacade.java:81)
at com.sun.proxy.$Proxy3237.setTransactionIsolation(Unknown Source)
at org.springframework.jdbc.datasource.DataSourceUtils.prepareConnectionForTransaction(DataSourceUtils.java:193)
at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:256)
... 34 more
I am unable to launch Firefox browser using selenium webdriver 3.4.0
Browser version: Firefox 54.0.1
This is my code:
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.firefox.bin", "C:\\Program Files\\Mozilla Firefox\\firefox.exe");
System.setProperty("webdriver.gecko.driver", "C:\\xx\\geckodriver.exe");
WebDriver driver=new FirefoxDriver();
driver.get("http://www.google.co.in");
driver.quit();
}
}
Getting Error
1508548441651 geckodriver INFO geckodriver 0.18.0
1508548441660 geckodriver INFO Listening on 127.0.0.1:48046 Exception
in thread "main" org.openqa.selenium.WebDriverException:
org.apache.http.conn.HttpHostConnectException: Connect to
localhost:48046 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1]
failed: Connection refused: connect Build info: version: '3.4.0',
revision: 'unknown', time: 'unknown' System info: host:
'ADMINRG-627BJ6K', ip: '192.168.1.3', os.name: 'Windows 10', os.arch:
'amd64', os.version: '10.0', java.version: '1.8.0_131' Driver info:
driver.version: FirefoxDriver at
org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:91)
at
org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:637)
at
org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:250)
at
org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:236)
at
org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:137)
at
org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:191)
at
org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:108)
at
org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:104)
at com.webdriver.Testing.main(Testing.java:15) Caused by:
org.apache.http.conn.HttpHostConnectException: Connect to
localhost:48046 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1]
failed: Connection refused: connect at
org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:159)
at
org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:359)
at
org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:381)
at
org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:237)
at
org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:185)
at
org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
at
org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:111)
at
org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
at
org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:72)
at
org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
at
org.openqa.selenium.remote.internal.ApacheHttpClient.fallBackExecute(ApacheHttpClient.java:139)
at
org.openqa.selenium.remote.internal.ApacheHttpClient.execute(ApacheHttpClient.java:87)
at
org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:343)
at
org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:159)
at
org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:142)
at
org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:82)
... 8 more Caused by: java.net.ConnectException: Connection refused:
connect at java.net.DualStackPlainSocketImpl.waitForConnect(Native
Method) at java.net.DualStackPlainSocketImpl.socketConnect(Unknown
Source) at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source) at
java.net.PlainSocketImpl.connect(Unknown Source) at
java.net.SocksSocketImpl.connect(Unknown Source) at
java.net.Socket.connect(Unknown Source) at
org.apache.http.conn.socket.PlainConnectionSocketFactory.connectSocket(PlainConnectionSocketFactory.java:75)
at
org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:142)
... 23 more
Instead of using driver of specific browser, you can use "Webdrivermanager" plugin in maven, so it will resolve most of problems related to browser and its instance. Even this help me lot to overcome browser related problems. E.g.
1. Add Webdrivermanager plugin with maven
2. Directly call browser of your choice like firefox as mentioned below.
FirefoxDriverManager.getInstance().setup();
driver= new FirefoxDriver();
In case of some firefox browser version, driver is not able to launch browser using property "webdriver.gecko.driver". Instead of this you can try following code:
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
WebDriver driver = new FirefoxDriver(capabilities);
Try this way: I am using C#, but this way worked for me. You can follow same way of doing in Java
Provide 'firefox.exe' & 'GeckoDriver' as your local path
var binary = new FirefoxBinary(#"----Firefox.exe Path------");
var profile = new FirefoxProfile();
FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(#"----GeckoDriver Path------");
service.FirefoxBinaryPath = #"----Firefox.exe Path------";
driverInstance = new FirefoxDriver(service);
Using Spring JdbcTemplate with HikariCP and JTDS to connect to MS SQL Server database in legacy code that I'm maintaining. I'm trying to handle the case where the application has started and later for whatever reason the database becomes unavailable and a connection exception is thrown.
I already have a custom SQL error code translator (below) that captures many other exceptions thrown by jdbcTemplate. But the connection refused exception is not being caught even though it is being encapsulated as a java.sql.SQLException (see the stack trace).
Why is the translator not capturing this exception?
public class CustomSqlErrorCodeTranslator extends
SQLErrorCodeSQLExceptionTranslator {
private final Log log = LogFactory.getLog(getClass());
#Override
protected DataAccessException customTranslate
(String task, String sql, SQLException sqlException) {
/*
* We want to capture all codes.
*/
StringBuilder logMsg = new StringBuilder("*********************SQL Exception:");
logMsg.append(", errorCode: " + sqlException.getErrorCode())
.append(", message: " + sqlException.getMessage())
;
log.error(logMsg.toString());
return null;
}
}
public class Dao {
//HikariDataSource dataSource;
DataSource dataSource;
protected JdbcTemplate jdbcTemplate;
private final Log log = LogFactory.getLog(getClass());
private boolean connected = false;
private CustomSqlErrorCodeTranslator exceptionHandler;
public void setDataSource(DataSource ds) {
//this.jdbcTemplate = new JdbcTemplate(ds);
try {
this.jdbcTemplate = new JdbcTemplate(ds);
exceptionHandler = new CustomSqlErrorCodeTranslator();
this.jdbcTemplate.setExceptionTranslator(exceptionHandler);
connected = true;
} catch (Exception e) {
if (e.getCause() != null && e.getCause() instanceof SQLException) {
log.error("******Cannot connect to database.***************************");
log.debug(e.getMessage());
}
}
}
}
16:59:33,542 [main] WARN PoolBase - springHikariCP - Connection net.sourceforge.jtds.jdbc.JtdsConnection#42206bce failed alive test with exception I/O Error: Connection reset by peer: socket write error
16:59:33,542 [Hikari connection closer (pool springHikariCP)] DEBUG PoolBase - springHikariCP - Closing connection net.sourceforge.jtds.jdbc.JtdsConnection#42206bce: (connection evicted or dead)
16:59:34,530 [main] DEBUG HikariPool - Timeout failure pool springHikariCP stats (total=0, active=0, idle=0, waiting=0)
16:59:34,544 [Hikari connection adder (pool springHikariCP)] DEBUG HikariPool - springHikariCP - Cannot acquire connection from data source
java.sql.SQLException: Network error IOException: Connection refused: connect
at net.sourceforge.jtds.jdbc.JtdsConnection.<init>(JtdsConnection.java:436)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:95)
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:101)
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:314)
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:171)
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:436)
at com.zaxxer.hikari.pool.HikariPool.access$500(HikariPool.java:65)
at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:567)
at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:560)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.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 net.sourceforge.jtds.jdbc.SharedSocket.createSocketForJDBC3(SharedSocket.java:288)
at net.sourceforge.jtds.jdbc.SharedSocket.<init>(SharedSocket.java:251)
at net.sourceforge.jtds.jdbc.JtdsConnection.<init>(JtdsConnection.java:331)
... 13 more
16:59:35,746 [Hikari connection adder (pool springHikariCP)] DEBUG HikariPool - springHikariCP - Cannot acquire connection from data source
java.sql.SQLException: Network error IOException: Connection refused: connect
at net.sourceforge.jtds.jdbc.JtdsConnection.<init>(JtdsConnection.java:436)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:95)
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:101)
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:314)
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:171)
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:436)
at com.zaxxer.hikari.pool.HikariPool.access$500(HikariPool.java:65)
at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:567)
at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:560)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.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 net.sourceforge.jtds.jdbc.SharedSocket.createSocketForJDBC3(SharedSocket.java:288)
at net.sourceforge.jtds.jdbc.SharedSocket.<init>(SharedSocket.java:251)
at net.sourceforge.jtds.jdbc.JtdsConnection.<init>(JtdsConnection.java:331)
... 13 more
16:59:37,010 [Hikari connection adder (pool springHikariCP)] DEBUG HikariPool - springHikariCP - Cannot acquire connection from data source
Sorry that it took me this long to realize I needed to add to the stack trace.
Here is the stack trace when I stop the database. Now it is clear that JDBC Template is involved. And if JdbcTemplate is involved it seems to me the custom exception handler should pick it up. Has anyone else had any experience capturing the database connection exception using the custom error code translator?
5:06:05,076 [ActiveMQ Session Task-1] DEBUG HikariPool - Timeout failure pool HikariPool-0 stats (total=1, active=1, idle=0, waiting=2)
org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLTransientConnectionException: HikariPool-0 - Connection is not available, request timed out after 10000ms.
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:80)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:615)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:866)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:927)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:937)
at com.pevco.persist.resources.AvailabilityDaoImpl.create(AvailabilityDaoImpl.java:51)
at com.pevco.nexgen.health.handlers.SystemModelListener.onMessage(SystemModelListener.java:135)
at org.springframework.jms.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:746)
at org.springframework.jms.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:684)
at org.springframework.jms.listener.AbstractMessageListenerContainer.doExecuteListener(AbstractMessageListenerContainer.java:651)
at org.springframework.jms.listener.AbstractMessageListenerContainer.executeListener(AbstractMessageListenerContainer.java:622)
at org.springframework.jms.listener.SimpleMessageListenerContainer.processMessage(SimpleMessageListenerContainer.java:330)
at org.springframework.jms.listener.SimpleMessageListenerContainer$2.onMessage(SimpleMessageListenerContainer.java:306)
at org.apache.activemq.ActiveMQMessageConsumer.dispatch(ActiveMQMessageConsumer.java:1321)
at org.apache.activemq.ActiveMQSessionExecutor.dispatch(ActiveMQSessionExecutor.java:131)
at org.apache.activemq.ActiveMQSessionExecutor.iterate(ActiveMQSessionExecutor.java:202)
at org.apache.activemq.thread.PooledTaskRunner.runTask(PooledTaskRunner.java:129)
at org.apache.activemq.thread.PooledTaskRunner$1.run(PooledTaskRunner.java:47)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.sql.SQLTransientConnectionException: HikariPool-0 - Connection is not available, request timed out after 10000ms.
at com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:195)
at com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:147)
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:83)
at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:111)
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:77)
... 20 more
Caused by: java.sql.SQLException: Network error IOException: Connection refused: connect
at net.sourceforge.jtds.jdbc.JtdsConnection.<init>(JtdsConnection.java:436)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:95)
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:314)
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:171)
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:436)
at com.zaxxer.hikari.pool.HikariPool.access$500(HikariPool.java:65)
at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:567)
at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:560)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
... 3 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.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 net.sourceforge.jtds.jdbc.SharedSocket.createSocketForJDBC3(SharedSocket.java:288)
at net.sourceforge.jtds.jdbc.SharedSocket.<init>(SharedSocket.java:251)
at net.sourceforge.jtds.jdbc.JtdsConnection.<init>(JtdsConnection.java:331)
... 12 more
15:06:06,217 [ActiveMQ Session Task-1] DEBUG HikariPool - Timeout failure pool HikariPool-0 stats (total=1, active=1, idle=0, waiting=2)
15:06:06,217 [ActiveMQ Session Task-1] WARN SimpleMessageListenerContainer - Execution of JMS message listener failed, and no ErrorHandler has been set.
(I'll award bounty before time expires, but would like to get the accurate answer.)
As "reos" pointed out, there is nothing related to JdbcTemplate in the stack trace. That means you tried to open the connection outside the JdbcTemplate.
Even if you used the JdbcTemplate, the exception would not get translated. Look at the execute method in the source code. They don't use the custom exception translator if the data source fails to obtain the connection.
The problem is because the connection is being asked by Hikari component. Probably Hikari lost the connection and it is trying to reconnect.
In the log there is not any part related to the JdbcTemplate. That is because the problem is cause by a reconnection try and not because a new transaction.
If the transaction is not passing by the template the error translator is never called. The event that throws the exception is no fired by the business logic. It is fired by the reconnect or create connection functionality of Hikari