Skip to content

Commit

Permalink
- Use of try(resource) with Connection
Browse files Browse the repository at this point in the history
  • Loading branch information
belaban committed May 7, 2024
1 parent 1a0e117 commit 65030ac
Showing 1 changed file with 64 additions and 141 deletions.
205 changes: 64 additions & 141 deletions src/org/jgroups/protocols/JDBC_PING2.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import org.jgroups.stack.IpAddress;
import org.jgroups.util.NameCache;
import org.jgroups.util.Responses;
import org.jgroups.util.UUID;
import org.jgroups.util.Util;

import javax.naming.InitialContext;
Expand All @@ -16,6 +15,9 @@
import java.util.List;
import java.util.function.Function;

import static java.sql.ResultSet.CONCUR_UPDATABLE;
import static java.sql.ResultSet.TYPE_FORWARD_ONLY;

/**
* New version of {@link JDBC_PING}. Has a new, better legible schema. plus some refactoring
*
Expand Down Expand Up @@ -142,8 +144,14 @@ public void init() throws Exception {


protected void write(List<PingData> list, String clustername) {
for(PingData data: list)
writeToDB(data, clustername);
for(PingData data: list) {
try {
writeToDB(data, clustername);
}
catch(SQLException e) {
log.error(Util.getMessage("ErrorUpdatingJDBCPINGTable"), e);
}
}
}


Expand All @@ -154,23 +162,11 @@ protected void write(List<PingData> list, String clustername) {
// This synchronization should not be a performance problem as this is just a Discovery protocol.
// Many SQL dialects have some "insert or update" expression, but that would need
// additional configuration and testing on each database. See JGRP-1440
protected synchronized void writeToDB(PingData data, String clustername) {
final Connection connection=getConnection();
if(connection != null) {
try {
// todo: make a stored procedure
delete(connection, clustername, data.getAddress());
insert(connection, data, clustername, data.getAddress());
}
catch(SQLException e) {
log.error(Util.getMessage("ErrorUpdatingJDBCPINGTable"), e);
}
finally {
closeConnection(connection);
}
}
else {
log.error(Util.getMessage("FailedToStorePingDataInDatabase"));
protected synchronized void writeToDB(PingData data, String clustername) throws SQLException {
try(Connection connection=getConnection()) {
// todo: make a stored procedure
delete(connection, clustername, data.getAddress());
insert(connection, data, clustername, data.getAddress());
}
}

Expand All @@ -180,34 +176,31 @@ protected void remove(String clustername, Address addr) {
delete(clustername, addr);
}
catch(SQLException e) {
log.error("Error", e);
log.error(String.format("failed deleting %s from the table", addr), e);
}
}

protected void removeAll(String clustername) {
clearTable(clustername);
try {
clearTable(clustername);
}
catch(Exception ex) {
log.error(String.format("failed clearing the table for cluster %s", clustername), ex);
}
}

protected void readAll(List<Address> members, String clustername, Responses responses) {
final Connection connection=getConnection();
if(connection != null) {
try {
readAll(connection, members, clustername, responses);
}
catch(Exception e) {
log.error(Util.getMessage("ErrorReadingJDBCPINGTable"), e);
}
finally {
closeConnection(connection);
}
try {
_readAll(members, clustername, responses);
}
catch(Exception e) {
log.error(Util.getMessage("ErrorReadingJDBCPINGTable"), e);
}
}



protected void readAll(Connection connection, List<Address> members, String clustername, Responses rsps) throws Exception {
try(PreparedStatement ps=prepareStatement(connection, select_all_pingdata_sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) {
ps.setString(1, clustername);
protected void _readAll(List<Address> members, String cluster, Responses rsps) throws Exception {
try(Connection conn=getConnection(); PreparedStatement ps=prepare(conn, select_all_pingdata_sql, TYPE_FORWARD_ONLY, CONCUR_UPDATABLE)) {
ps.setString(1, cluster);
if(log.isTraceEnabled())
log.trace("%s: SQL for reading: %s", local_addr, ps);
try(ResultSet resultSet=ps.executeQuery()) {
Expand All @@ -230,8 +223,8 @@ protected void readAll(Connection connection, List<Address> members, String clus
}
}

protected static PreparedStatement prepareStatement(final Connection conn, final String sql, final int resultSetType,
final int resultSetConcurrency) throws SQLException {
protected static PreparedStatement prepare(final Connection conn, final String sql, final int resultSetType,
final int resultSetConcurrency) throws SQLException {
try {
return conn.prepareStatement(sql, resultSetType, resultSetConcurrency);
}
Expand All @@ -251,28 +244,21 @@ protected void attemptSchemaInitialization() {
log.debug("Table creation step skipped: initialize_sql attribute is missing");
return;
}
Connection connection=getConnection();
if(connection == null)
return;

try(PreparedStatement ps=connection.prepareStatement(initialize_sql)) {
try(Connection conn=getConnection(); PreparedStatement ps=conn.prepareStatement(initialize_sql)) {
if(log.isTraceEnabled())
log.trace("SQL for initializing schema: %s", ps);
ps.execute();
log.debug("Table created for JDBC_PING Discovery Protocol");
log.debug("table " + table_name + " created for JDBC_PING discovery protocol");
}
catch(SQLException e) {
log.debug("Could not execute initialize_sql statement; not necessarily an error, we always attempt to create the schema. " +
"To suppress this message, set initialize_sql to an empty value. Cause: %s", e.getMessage());
}
finally {
closeConnection(connection);
}
}

protected void loadDriver() {
assertNonNull("connection_driver", connection_driver);
log.debug("Registering JDBC driver %s", connection_driver);
log.debug("registering JDBC driver %s", connection_driver);
try {
Util.loadClass(connection_driver, this.getClass().getClassLoader());
}
Expand All @@ -288,33 +274,11 @@ protected DataSource injectDataSource(String ds_class) throws Exception {
return fun.apply(this);
}

protected Connection getConnection() {
if(dataSource == null) {
Connection connection;
try {
connection=DriverManager.getConnection(connection_url, connection_username, connection_password);
}
catch(SQLException e) {
log.error(Util.getMessage("CouldNotOpenConnectionToDatabase"), e);
return null;
}
if(connection == null) {
log.error(Util.getMessage("ReceivedNullConnectionFromTheDriverManager"));
}
return connection;
}
else {
try {
return dataSource.getConnection();
}
catch(SQLException e) {
log.error(Util.getMessage("CouldNotOpenConnectionToDatabase"), e);
return null;
}
}
protected Connection getConnection() throws SQLException {
return dataSource != null? dataSource.getConnection() :
DriverManager.getConnection(connection_url, connection_username, connection_password);
}


protected synchronized void insert(Connection connection, PingData data, String clustername, Address address) throws SQLException {
try(PreparedStatement ps=connection.prepareStatement(insert_single_sql)) {
String addr=Util.addressToString(address);
Expand All @@ -333,9 +297,9 @@ protected synchronized void insert(Connection connection, PingData data, String
}
}

protected synchronized void delete(Connection connection, String clustername, Address addressToDelete) throws SQLException {
try(PreparedStatement ps=connection.prepareStatement(delete_single_sql)) {
String addr=Util.addressToString((UUID)addressToDelete);
protected synchronized void delete(Connection conn, String clustername, Address addressToDelete) throws SQLException {
try(PreparedStatement ps=conn.prepareStatement(delete_single_sql)) {
String addr=Util.addressToString(addressToDelete);
ps.setString(1, addr);
ps.setString(2, clustername);
if(log.isTraceEnabled())
Expand All @@ -346,56 +310,20 @@ protected synchronized void delete(Connection connection, String clustername, Ad
}

protected void delete(String clustername, Address addressToDelete) throws SQLException {
final Connection connection=getConnection();
if(connection != null) {
try {
delete(connection, clustername, addressToDelete);
}
catch(SQLException e) {
log.error(Util.getMessage("ErrorUpdatingJDBCPINGTable"), e);
}
finally {
closeConnection(connection);
}
}
else {
log.error(Util.getMessage("FailedToDeletePingDataInDatabase"));
try(Connection connection=getConnection()) {
delete(connection, clustername, addressToDelete);
}
}


protected void clearTable(String clustername) {
try(Connection conn=getConnection()) {
if(conn != null) {
try(PreparedStatement ps=conn.prepareStatement(clear_sql)) {
// check presence of cluster parameter for backwards compatibility
if(clear_sql.indexOf('?') >= 0)
ps.setString(1, clustername);
else
log.debug("Please update your clear_sql to include cluster parameter.");
ps.execute();
log.trace("%s: cleared table for cluster %s", local_addr, clustername);
}
catch(SQLException e1) {
log.error(Util.getMessage("ErrorClearingTable"), e1);
}
finally {
closeConnection(conn);
}
}
}
catch(SQLException e2) {
log.error(Util.getMessage("ErrorClearingTable"), e2);
}
}


protected void closeConnection(final Connection connection) {
try {
connection.close();
}
catch(SQLException e) {
log.error(Util.getMessage("ErrorClosingConnectionToJDBCPINGDatabase"), e);
protected void clearTable(String clustername) throws SQLException {
try(Connection conn=getConnection(); PreparedStatement ps=conn.prepareStatement(clear_sql)) {
// check presence of cluster parameter for backwards compatibility
if(clear_sql.indexOf('?') >= 0)
ps.setString(1, clustername);
else
log.debug("Please update your clear_sql to include cluster parameter.");
ps.execute();
log.trace("%s: cleared table for cluster %s", local_addr, clustername);
}
}

Expand Down Expand Up @@ -445,13 +373,13 @@ protected static void assertNonNull(String... strings) {
}


public static void main(String[] args) throws ClassNotFoundException {
public static void main(String[] args) throws Exception {
String driver="org.hsqldb.jdbcDriver";
String user="SA";
String pwd="";
String conn="jdbc:hsqldb:hsql://localhost/";
String cluster="draw";
String select="SELECT ping_data, own_addr, cluster_name FROM JGROUPSPING WHERE cluster_name=?";
String select="SELECT address, name, cluster, ip, coord FROM JGROUPS WHERE cluster=?";

for(int i=0; i < args.length; i++) {
if(args[i].equals("-driver")) {
Expand All @@ -478,37 +406,32 @@ public static void main(String[] args) throws ClassNotFoundException {
select=args[++i];
continue;
}
System.out.println("JDBC_PING [-driver driver] [-conn conn-url] [-user user] [-pwd password] " +
System.out.println("JDBC_PING2 [-driver driver] [-conn conn-url] [-user user] [-pwd password] " +
"[-cluster cluster-name] [-select select-stmt]");
return;
}

Class.forName(driver);

try(Connection c=DriverManager.getConnection(conn, user, pwd);
PreparedStatement ps=prepareStatement(c, select, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) {
PreparedStatement ps=prepare(c, select, TYPE_FORWARD_ONLY, CONCUR_UPDATABLE)) {
ps.setString(1, cluster);
try(ResultSet resultSet=ps.executeQuery()) {
int index=1;
while(resultSet.next()) {
byte[] bytes=resultSet.getBytes(1);
try {
List<PingData> list=deserialize(bytes, 0, bytes.length);
if(list != null) {
for(PingData data: list) {
System.out.printf("%d %s\n", index++, data);
}
}
}
catch(Exception e) {
}
String uuid=resultSet.getString(1);
String name=resultSet.getString(2);
String cluster_name=resultSet.getString(3);
String ip=resultSet.getString(4);
boolean coord=resultSet.getBoolean(5);
System.out.printf("%d: %s, name=%s, ip=%s, %b (cluster=%s)\n",
index++, uuid, name, ip, coord? "coord" : "server", cluster_name);
}
}
}
catch(SQLException e) {
e.printStackTrace();
}

}

}

0 comments on commit 65030ac

Please sign in to comment.