I am implementing A Javabean SQL connection in Xpages. I am trying to create a connection pool for this Bean implementation using HikariCP.
Here is my code.
Datasource Class
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
public class HikariDS
{
private static DataSource datasource;
public static DataSource getDataSource(String jdbcURL, String user, String pass)
{
if(datasource == null)
{
try
{
HikariConfig config = new HikariConfig();
config.setJdbcUrl(jdbcURL);
config.setUsername(user);
config.setPassword(pass);
config.setDataSourceClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
config.setMaximumPoolSize(100);
config.setAutoCommit(false);
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
datasource = new HikariDataSource(config);
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
return datasource;
}
}
SQL Connection bean
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.io.Serializable;
import com.sqlPoolConnect;
import javax.sql.DataSource;
public class sqlConnection implements Serializable
{
private static final long serialVersionUID = 1L;
private String query;
private String retError;
private String conString;
DataSource dataSource;
Connection con = null;
PreparedStatement prep = null;
private String USER;
private String PASS;
public sqlConnection()
{
}
public String getConString()
{
return conString;
}
public void setConString(String cS)
{
this.conString = cS;
}
public String getUSER()
{
return USER;
}
public void setUSER(String U)
{
this.USER = U;
}
public void setPASS(String P)
{
this.PASS = P;
}
public String getPASS()
{
return PASS;
}
public String getQuery()
{
return query;
}
public void setQuery(String query)
{
this.query = query;
}
public void execQuery()
{
con = null;
prep = null;
try
{
dataSource = sqlPoolConnect.getDataSource(getConString(), getUSER(), getPASS());
con = dataSource.getConnection();
prep = con.prepareStatement(getQuery());
prep.executeQuery();
}
catch(Exception sqlex)
{
sqlex.printStackTrace();
}
finally
{
try
{
if(prep != null)
{
prep.close();
}
con.rollback();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}
}
SSJS Call of Bean
function testInsert(inCon)
{
var query = "INSERT INTO table_name
(1,2,3,4,5) ";
sqlConnection.setUSER("USER");
sqlConnection.setPass("PASS");
sqlConnection.setConString(inCon);
sqlConnection.setQuery(query);
sqlConnection.execQuery();
}
When the bean is invoked. IT BREAKS AT HikariConfig config = new HikariConfig(); in the KikaryDS Class.
Please advise if anyone knows why it will break over there.
Edit:
I ran the code in a separate java project and received this error.
Exception in thread "main" java.lang.NoClassDefFoundError: com.zaxxer.hikari.HikariConfig
at HikariCP.getDataSource(HikariCP.java:20)
at HikariCP.main(HikariCP.java:45)
Caused by: java.lang.ClassNotFoundException: com.zaxxer.hikari.HikariConfig
at java.net.URLClassLoader.findClass(URLClassLoader.java:609)
at java.lang.ClassLoader.loadClassHelper(ClassLoader.java:925)
at java.lang.ClassLoader.loadClass(ClassLoader.java:870)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:343)
at java.lang.ClassLoader.loadClass(ClassLoader.java:853)
... 2 more
MANIFEST.MF
Manifest-Version: 1.0
Bnd-LastModified: 1588952278176
Build-Jdk: 11.0.2
Built-By: brettw
Bundle-Description: Ultimate JDBC Connection Pool
Bundle-DocURL: https://github.com/brettwooldridge
Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt
Bundle-ManifestVersion: 2
Bundle-Name: HikariCP
Bundle-SymbolicName: com.zaxxer.HikariCP
Bundle-Vendor: Zaxxer.com
Bundle-Version: 3.4.5
Created-By: Apache Maven Bundle Plugin
DynamicImport-Package: *
Export-Package: com.zaxxer.hikari;version="3.4.5";uses:="com.zaxxer.hi
kari.metrics,javax.naming,javax.naming.spi,javax.sql",com.zaxxer.hika
ri.hibernate;version="3.4.5";uses:="com.zaxxer.hikari,org.hibernate,o
rg.hibernate.engine.jdbc.connections.spi,org.hibernate.service.spi",c
om.zaxxer.hikari.metrics;version="3.4.5",com.zaxxer.hikari.pool;versi
on="3.4.5";uses:="com.zaxxer.hikari,com.zaxxer.hikari.metrics,com.zax
xer.hikari.util,javax.sql",com.zaxxer.hikari.util;version="3.4.5";use
s:="javax.sql"
Import-Package: javax.management,javax.naming,javax.naming.spi,javax.s
ql,com.codahale.metrics;resolution:=optional;version="[3.2,4)",com.co
dahale.metrics.health;resolution:=optional;version="[3.2,4)",io.micro
meter.core.instrument;resolution:=optional,org.slf4j;version="[1.6,2)
",org.hibernate;resolution:=optional;version="[5.2,6)",org.hibernate.
engine.jdbc.connections.spi;resolution:=optional;version="[5.2,6)",or
g.hibernate.service;resolution:=optional;version="[5.2,6)",org.hibern
ate.service.spi;resolution:=optional;version="[5.2,6)",javax.sql.rows
et,javax.sql.rowset.serial,javax.sql.rowset.spi,org.hibernate.cfg;res
olution:=optional;version="[5.2,6)"
Multi-Release: true
Originally-Created-By: Apache Maven Bundle Plugin
Require-Capability: osgi.ee;filter:="(&(osgi.ee=JavaSE)(version=1.8))"
Tool: Bnd-4.2.0.201903051501
I have imported HikariCP-3.4.5.jar and slf4j-simple-1.7.30.jar and have ensured it is in my Java Build Path. What else could be causing this issue?
Related
Below is code that I have. I've been trying different ways to test, including stubbing, mocking and spying. When I tried mocking the DriverManager.getConnection(), I got a message that it's private. I'm trying to practice TDD, so I know that it's not the intention to test the connection itself but rather the behavior surrounding the connection.
public class Main {
public static void main(String[] args) {
Datasource datasource = new Datasource();
if(datasource.open() == false){
return;
}
datasource.close();
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Datasource {
public static final String DB_NAME = "DBNAME";
public static final String DB_USERNAME = "USERNAME";
public static final String DB_PASSWORD = "PASSWORD";
public static final String SUBPROTOCOL = "jdbc:oracle:thin:#";
public static final String SERVER_NAME = "SERVERNAME";
public static final String PORT_NUMBER = "1521";
public static final String CONNECTION_STRING = SUBPROTOCOL + SERVER_NAME + ":" + PORT_NUMBER + "/" + DB_NAME;
private Connection conn;
public boolean open(){
try {
conn = DriverManager.getConnection(CONNECTION_STRING, DB_USERNAME, DB_PASSWORD);
System.out.println("Connected to database successfully.");
return true;
} catch (SQLException e) {
System.out.println("Error connecting to database: " + e.getMessage());
return false;
}
}
/**
* Closes the connection to the HR database.
* #return void
*/
public void close() {
try {
if (conn != null) {
conn.close();
System.out.println("Closed database connection successfully.");
}
} catch (SQLException e) {
System.out.println("Error closing database connection: " + e.getMessage());
}
}
}
import static org.junit.jupiter.api.Assertions.*;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Spy;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class DatasourceTest {
#Test
void exceptionIsThrownIfHRDatabaseConnectionFails() throws SQLException {
//Datasource testDatasource = new Datasource();
//assertThrows(SQLException.class, () -> {testDatasource.open();});
//TODO come back to this to mock connection
Datasource testDatasource = mock(Datasource.class);
DriverManager testDriverManager = mock(DriverManager.class);
when(testDriverManager.getConnection(Datasource.CONNECTION_STRING, Datasource.DB_USERNAME, Datasource.DB_PASSWORD)).thenReturn(null);
assertThrows(SQLException.class, () -> {testDatasource.open();});
}
#Test
void exceptionIsThrownIfConnectionIsNullDuringClose() throws SQLException {
Datasource testDatasource = new Datasource();
DriverManager testDriverManager = mock(DriverManager.class);
when(testDriverManager.getConnection(Datasource.CONNECTION_STRING, Datasource.DB_USERNAME, Datasource.DB_PASSWORD)).thenReturn(null);
}
}
Many developers may argue this test does not make sense, but in some cases you may want to test that a connection was successfully closed after using it (eg: if you find that a bug was happening because your program was exceeding the max number of connections for a giving resource, TDD encourages you to adding a test for this bugfix). In order to do this
Design the method interface by adding a test and make it fail (class DatasetTest.java):
public void whenDatasetClosed_closedReturnsTrue() {
//Arrange
//create a new dataset instance of your Dataset Class
Dataset dataset = new Dataset();
//Act
dataset.close();
//Assert
assertTrue(dataset.isClosed());
}
make conn an attribute of Dataset class
Implement close() method in Dataset class
Add the isClosed() method to the Dataset class exposing the connection status (eg. dataset.isClosed(), class Dataset.java).
public boolean isClosed() {
return this.conn.isClosed();
}
Repeat for the case where the connection is not closed and should return false.
Good afternoon, I am experiencing an issue where my spring application is not autowiring a Datasource to a DAO. The database is a postgresql db being ran on my local machine. I'm getting a null pointer exception in my userDAO where we try to execute datasource.getConnection, which is the error being caused when a certain endpoint of the api is requested. In the DatabaseConfig class method postgresDatasource, there is a commented out try catch block where I see if we still get thrown a null pointer exception if we attempt ds.getConnection. It does not throw an exception in there, event though that code is being ran at server build. Like I said, the error gets thrown when I assume that the autowiring is being execute corrected and we try datasource.getConnection. All relevant code will be pasted below. first is the DatabaseConfig class. It may be worth noting that my DatabaseConfig is in com.example.config, and the DAO is in com.example.dao
#Configuration
#ComponentScan(basePackages="com.example")
public class DatabaseConfig {
#Bean
public DataSource postgresDataSource() {
final DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("org.postgresql.Driver");
ds.setUrl("jdbc:postgresql://localhost:5432/postgres");
ds.setUsername("username");
ds.setPassword("password");
// System.out.println("Returning ds object after setting parameters");
// System.out.println(ds.toString());
// try {
// System.out.println("Attempting connection at server build.");
// ds.getConnection();
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
System.out.println("DataSource postgresDataSource() is being ran");
return ds;
}
}
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import com.fmn.config.DatabaseConfig;
import com.fmn.dto.UserDTO;
#Repository
public class UserDAO {
// #Autowired
private DataSource datasource;
// #Autowired
// public void setDataSource(DataSource datasource) {
// this.datasource = datasource;
// }
//
#Autowired
public UserDAO(DataSource datasource){
System.out.println("Setting datasource in constructor");
this.datasource = datasource;
}
//
public UserDAO() {};
public boolean addUser(UserDTO user) {
//TODO: implement
return false;
}
public boolean updateUser(UserDTO user) {
//TODO: implement
return false;
}
public UserDTO getUserInfo(UserDTO user)/*throws UserNotFoundException*/ {
//TODO: implement
if(user.getUserId() != null) {
return getUserInfoWithUserID(user);
} else if (user.getEmail() != null) {
return getUserInfoWithEmail(user);
} else if (user.getPhoneNum() != null) {
return getUserInfoWithPhone(user);
}
//else throw new UserNotFoundException();
return null;
}
private UserDTO getUserInfoWithEmail(UserDTO user) {
//TODO: implement
return null;
}
private UserDTO getUserInfoWithPhone(UserDTO user) {
//TODO: implement
return null;
}
public UserDTO getUserInfoWithUserID(UserDTO user) {
UserDTO outUser = null;
ResultSet result = null;
Connection conn = null;
try {
// DatabaseConfig dbc = new DatabaseConfig();
// System.out.println("Setting datasource");
// datasource = dbc.postgresDataSource();
System.out.println("Calling datasource.getConnection()");
conn = datasource.getConnection();
CallableStatement caller = conn.prepareCall("{?= call get_user_info_with_userid(?)}");
caller.registerOutParameter(1, Types.REF_CURSOR);
caller.setString(2, user.getUserId());
caller.execute();
result = caller.getResultSet();
result.next();
outUser = setUserDTOFromResultSet(result);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return outUser;
}
private UserDTO setUserDTOFromResultSet(ResultSet result) throws SQLException {
UserDTO outUser = new UserDTO();
outUser.setDOB(result.getDate("DOB"));
outUser.setUserId(result.getString("USER_ID"));
outUser.setfName(result.getString("F_NAME"));
outUser.setlName(result.getString("L_NAME"));
outUser.setEmail(result.getString("EMAIL"));
outUser.setAliveFlg(result.getString("ALIVE_FLG"));
return outUser;
}
}
#SpringBootApplication
#EnableAutoConfiguration
#ComponentScan(basePackageClasses = {DatabaseConfig.class, InteractiveController.class, UserDAO.class})
public class Application {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(DatabaseConfig.class);
ctx.refresh();
SpringApplication.run(Application.class, args);
}
}
Your feedback and input is appreciated. Thank you!
This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 3 years ago.
In my application I have autowired dataSource object which is being returned null.
The object is being used in DAO class.
Application Flow ->
1.OAConsumer.java starts execution
2. calls service.java
3. calls insertOffset in KafkaDAOImpl class
IDE used in eclispe Oxygen.
Code and error details below.
Error shown
java.lang.NullPointerException
at com.oa.dao.KafkaOffsetDAOImpl.insertOffset(KafkaOffsetDAOImpl.java:36)
at com.oa.services.Service.savePayload(Service.java:54)
at com.oa.consumer.OAConsumer.orderConsumer(OAConsumer.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:170)
at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:120)
at org.springframework.kafka.listener.adapter.HandlerAdapter.invoke(HandlerAdapter.java:48)
at org.springframework.kafka.listener.adapter.MessagingMessageListenerAdapter.invokeHandler(MessagingMessageListenerAdapter.java:283)
at org.springframework.kafka.listener.adapter.BatchMessagingMessageListenerAdapter.invoke(BatchMessagingMessageListenerAdapter.java:146)
at org.springframework.kafka.listener.adapter.BatchMessagingMessageListenerAdapter.onMessage(BatchMessagingMessageListenerAdapter.java:138)
at org.springframework.kafka.listener.adapter.BatchMessagingMessageListenerAdapter.onMessage(BatchMessagingMessageListenerAdapter.java:59)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.doInvokeBatchOnMessage(KafkaMessageListenerContainer.java:1052)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeBatchOnMessage(KafkaMessageListenerContainer.java:1036)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.doInvokeBatchListener(KafkaMessageListenerContainer.java:998)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeBatchListener(KafkaMessageListenerContainer.java:938)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeListener(KafkaMessageListenerContainer.java:921)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.pollAndInvoke(KafkaMessageListenerContainer.java:740)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.run(KafkaMessageListenerContainer.java:689)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
KafkaOffsetDAOImpl.java
package com.oa.dao;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import com.oa.model.KafkaOffsetRecord;
public class KafkaOffsetDAOImpl implements KafkaOffsetDAO {
// #Autowired
// JdbcTemplate jdbcTemplate;
#Autowired
DataSource dataSource;
#Override
public boolean insertOffset(KafkaOffsetRecord offsetRecord) {
boolean status=false;
try(Connection connection =dataSource.getConnection()){
if(connection.isValid(10000))
status= true;
}catch (Exception e) {
e.printStackTrace();
}
return false;
}
OracleConfig.java
package com.oa.config;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
#Configuration
public class OracleConfig {
private static final Logger logger = LoggerFactory.getLogger(OracleConfig.class);
#Value("${spring.datasource.url}")
private String url;
#Value("${spring.datasource.username}")
private String username;
#Value("${spring.datasource.password}")
private String password;
#Value("${spring.datasource.driver-class-name}")
private String driverClassName;
#Value("${spring.datasource.maximumPoolSize}")
private int maxPoolSize;
#Value("${spring.datasource.minimumIdle}")
private int minIdle;
#Value("${spring.datasource.connectionTimeout}")
private long connTimeOut;
#Value("${spring.datasource.idleTimeout}")
private long idleTimeout;
//
/**
* See http://www.baeldung.com/hikaricp
*/
#Bean
public HikariDataSource dataSource() {
HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setDriverClassName(driverClassName);
hikariConfig.setUsername(username);
hikariConfig.setPassword(password);
hikariConfig.setJdbcUrl(url);
hikariConfig.setMaximumPoolSize(maxPoolSize);
hikariConfig.setConnectionTimeout(connTimeOut);
hikariConfig.setMinimumIdle(minIdle);
hikariConfig.setIdleTimeout(idleTimeout);
HikariDataSource hikariDataSource = new HikariDataSource(hikariConfig);
if (hikariDataSource.isRunning()) {
logger.info("------> Oracle DB connection created successfully.");
}
return hikariDataSource;
}
Consumer.java
package com.oa.consumer;
import java.util.List;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import com.oa.services.OrderService;
public class OAConsumer {
private static final Logger LOGGER = LoggerFactory.getLogger(OAConsumer.class);
#KafkaListener(topics = "**removed**", groupId = "**removed**")
public void orderConsumer(List<ConsumerRecord<String, String>> records, Acknowledgment acknowledgment) {
LOGGER.debug("START :: orderConsumer");
OrderService orderService = new OrderService();
try {
for (ConsumerRecord<String, String> record : records) {
LOGGER.debug("Processing Offset Order :: offset={} :: partitionId={} :: topicName={}", record.offset(),
record.partition(), record.topic());
orderService.savePayload(record);
}
acknowledgment.acknowledge();
LOGGER.debug("END :: orderConsumer:: Acknowledged");
} catch (Exception exception) {
exception.printStackTrace();
LOGGER.error(exception.getMessage());
}
}
Service.java
package com.oa.services;
import java.io.IOException;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.oa.dao.KafkaOffsetDAO;
import com.oa.dao.KafkaOffsetDAOImpl;
import com.oa.model.KafkaOffsetRecord;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Service {
private static final Logger LOGGER = LoggerFactory.getLogger(Service.class);
public Boolean checkOAEligible(String message, long offset, String topic) throws IOException {
return true;
}
public Boolean savePayload(ConsumerRecord<String, String> record) {
LOGGER.debug("START:: saveOrderPayload ::offset= {} :: topic= {}", record.offset(), record.topic());
Boolean status = false;
KafkaOffsetDAO dao = new KafkaOffsetDAOImpl();
try {
if (checkOAEligible(record.value(), record.offset(), record.topic())) {
KafkaOffsetRecord kafkaOffsetRecord= new KafkaOffsetRecord(record);
status = dao.insertOffset(kafkaOffsetRecord);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
LOGGER.debug("END:: saveOrderPayload :: offset={} :: topic={} , status={}", record.offset(), record.topic(), status);
return status;
}
}
KafkaOffsetRecord
package com.oa.model;
import org.apache.kafka.clients.consumer.ConsumerRecord;
public class KafkaOffsetRecord {
long offsetId;
String jsonMsg;
String kafkaSourceType;
int partitionId;
String kafkaTopicName;
public KafkaOffsetRecord() {
}
public KafkaOffsetRecord(ConsumerRecord<String, String> consumerRecord) {
offsetId = consumerRecord.offset();
jsonMsg = consumerRecord.value();
partitionId=consumerRecord.partition();
kafkaTopicName= consumerRecord.topic();
kafkaSourceType = "TEST";
}
public long getOffsetId() {
return offsetId;
}
public String getJsonMsg() {
return jsonMsg;
}
public String getKafkaSourceType() {
return kafkaSourceType;
}
public int getPartitionId() {
return partitionId;
}
public String getKafkaTopicName() {
return kafkaTopicName;
}
public void setOffsetId(long offsetId) {
this.offsetId = offsetId;
}
public void setJsonMsg(String jsonMsg) {
this.jsonMsg = jsonMsg;
}
public void setKafkaSourceType(String kafkaSourceType) {
this.kafkaSourceType = kafkaSourceType;
}
public void setPartitionId(int partitionId) {
this.partitionId = partitionId;
}
public void setKafkaTopicName(String kafkaTopicName) {
this.kafkaTopicName = kafkaTopicName;
}
}
application.properties
spring.datasource.url=jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS_LIST=(LOAD_BALANCE=ON)(FAILOVER=OFF)(ADDRESS=(PROTOCOL=TCP)(HOST=**removed**)(PORT=**removed**))(ADDRESS=(PROTOCOL=TCP)(HOST=**removed**)(PORT=**removed**)))(CONNECT_DATA=(SERVICE_NAME=**removed**)(SERVER=DEDICATED)))
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.username=**removed**
spring.datasource.password=**removed**
spring.datasource.type=oracle.jdbc.pool.OracleDataSource
spring.datasource.maximumPoolSize=20
spring.datasource.minimumIdle=5
spring.datasource.connectionTimeout=30000
spring.datasource.idleTimeout=1500000
use constructor injection, when you use it
public class KafkaOffsetDAOImpl implements KafkaOffsetDAO {
private final DataSource dataSource;
#Autowired
KafkaOffsetDAOImpl(final Datasource datasrouce) {
this.dataSource = dataSource;
}
this way you can be sure, that spring creates the autowired field and injects it.
I am using below setup for fetching data from oracle DB and connection pooling.
When I do getConnection on this setup, oracle data source always creates new connection and returns, until max limit is reached. Even if I finished executing the statement. how do I release connection?
I know I can use apache dpcp or oracle upc, but I want to fix below code and I can not use any other frameworks.
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import oracle.jdbc.pool.OracleConnectionCacheManager;
import oracle.jdbc.pool.OracleDataSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class DatabaseUtility {
private static final String CACHE_NAME = "DBCACHE";
private static OracleDataSource ods = null;
private static final Logger LOGGER = LogManager.getLogger(DatabaseUtility.class);
public static synchronized void init(Properties properties) throws SQLException {
if (ods == null) {
LOGGER.info("OracleDataSource Initialization");
ods = new OracleDataSource();
ods.setURL(PropertiesLoader.getValue(properties, "jdbc.datasource.url"));
ods.setUser(PropertiesLoader.getValue(properties, "jdbc.datasource.username"));
ods.setPassword(PropertiesLoader.getValue(properties, "jdbc.datasource.password"));
ods.setConnectionCachingEnabled(true);
ods.setConnectionCacheName(CACHE_NAME);
Properties cacheProps = new Properties();
cacheProps.setProperty(
"MinLimit", PropertiesLoader.getValue(properties, "jdbc.datasource.minlimit"));
cacheProps.setProperty(
"MaxLimit", PropertiesLoader.getValue(properties, "jdbc.datasource.maxlimit"));
cacheProps.setProperty(
"InitialLimit", PropertiesLoader.getValue(properties, "jdbc.datasource.minlimit"));
cacheProps.setProperty(
"ConnectionWaitTimeout", PropertiesLoader.getValue(properties, "jdbc.datasource.wait"));
cacheProps.setProperty(
"ValidateConnection",
PropertiesLoader.getValue(properties, "jdbc.datasource.validate"));
ods.setConnectionCacheProperties(cacheProps);
}
}
private DatabaseUtility() {
throw new AssertionError("Can not create object of DatabaseUtility!");
}
public static synchronized Connection getConnection(Properties properties) throws SQLException {
LOGGER.info("Request connection!");
if (ods == null) {
init(properties);
}
return ods.getConnection();
}
public static void closePooledConnections() throws SQLException {
if (ods != null) {
ods.close();
}
}
public static void listCacheInfos() throws SQLException {
OracleConnectionCacheManager occm =
OracleConnectionCacheManager.getConnectionCacheManagerInstance();
LOGGER.info(
occm.getNumberOfAvailableConnections(CACHE_NAME)
+ " connections are available in cache "
+ CACHE_NAME);
LOGGER.info(occm.getNumberOfActiveConnections(CACHE_NAME) + " connections are active");
}
}
So, how can I release a connection for reuse after I finished executing my query?
I'm writing a program (Java Application) for reading ePassport. For access I use the library org.jmrtd. What kind of object should I transfer in CardService.getInstance() ?
import net.sf.scuba.smartcards.CardService;
import net.sf.scuba.smartcards.CardServiceException;
import org.jmrtd.BACKeySpec;
import org.jmrtd.PassportService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestComponent {
private static final Logger log = LoggerFactory.getLogger(MainApp.class);
public static void main(String args[]) {
try {
CardService cs = CardService.getInstance(???????);
PassportService ps = new PassportService(cs);
ps.open();
ps.sendSelectApplet(false);
ps.sendSelectApplet(false);
BACKeySpec bacKey = new BACKeySpec() {
public String getDocumentNumber() {
return "xxxxxxxx";
}
public String getDateOfBirth() {
return "yyMMdd";
}
public String getDateOfExpiry() {
return "yyMMdd";
}
};
ps.doBAC(bacKey);
ps.close();
} catch (CardServiceException e) {
e.printStackTrace();
}
}
}
Answer found:
add in pom
net.sf.scuba
scuba-sc-j2se
0.0.13
import net.sf.scuba.smartcards.TerminalCardService;
CardTerminal terminal =TerminalFactory.getDefault().terminals().list().get(0);
CardService cs = CardService.getInstance(terminal);
PassportService ps = new PassportService(cs);
ps.open();