From 304d957fa14270a2328011a94b9aa3475689bd6b Mon Sep 17 00:00:00 2001 From: Marc Baloup Date: Sat, 4 Nov 2017 19:20:53 +0100 Subject: [PATCH] Code cleanup in ORM structure --- .../server/NetworkAPIListener.java | 4 +- .../pandacube/java/util/orm/DBConnection.java | 29 +++++++----- .../java/fr/pandacube/java/util/orm/ORM.java | 31 ++++--------- .../pandacube/java/util/orm/SQLElement.java | 44 ++++++------------- .../java/util/orm/SQLElementList.java | 10 ++--- 5 files changed, 43 insertions(+), 75 deletions(-) diff --git a/src/main/java/fr/pandacube/java/util/network_api/server/NetworkAPIListener.java b/src/main/java/fr/pandacube/java/util/network_api/server/NetworkAPIListener.java index 25ce582..2930196 100644 --- a/src/main/java/fr/pandacube/java/util/network_api/server/NetworkAPIListener.java +++ b/src/main/java/fr/pandacube/java/util/network_api/server/NetworkAPIListener.java @@ -2,7 +2,6 @@ package fr.pandacube.java.util.network_api.server; import java.io.IOException; import java.net.ServerSocket; -import java.net.Socket; import java.util.Arrays; import java.util.HashMap; @@ -47,8 +46,7 @@ public class NetworkAPIListener implements Runnable { try { // réception des connexion client while (!serverSocket.isClosed()) { - Socket socketClient = serverSocket.accept(); - nAPIExecutionHandler.handleRun(new PacketExecutor(socketClient, this)); + nAPIExecutionHandler.handleRun(new PacketExecutor(serverSocket.accept(), this)); } } catch (IOException e) {} diff --git a/src/main/java/fr/pandacube/java/util/orm/DBConnection.java b/src/main/java/fr/pandacube/java/util/orm/DBConnection.java index b50c219..6343099 100644 --- a/src/main/java/fr/pandacube/java/util/orm/DBConnection.java +++ b/src/main/java/fr/pandacube/java/util/orm/DBConnection.java @@ -6,10 +6,12 @@ import java.sql.SQLException; import java.sql.Statement; public class DBConnection { - Connection conn; - String url; - String login; - String pass; + private Connection conn; + private String url; + private String login; + private String pass; + + private long timeOfLastCheck = 0; public DBConnection(String host, int port, String dbname, String l, String p) throws ClassNotFoundException, SQLException { @@ -27,31 +29,34 @@ public class DBConnection { } public void reconnectIfNecessary() throws SQLException { - try { - Statement stmt = conn.createStatement(); - stmt.close(); + try(Statement stmt = conn.createStatement()) { } catch (SQLException e) { - try { - close(); - } catch (Exception ex) {} + close(); connect(); } } public Connection getNativeConnection() throws SQLException { - if (!conn.isValid(1)) reconnectIfNecessary(); + if (conn.isClosed()) + connect(); + long now = System.currentTimeMillis(); + if (timeOfLastCheck + 5000 > now) { + timeOfLastCheck = now; + if (!conn.isValid(1)) + reconnectIfNecessary(); + } return conn; } private void connect() throws SQLException { conn = DriverManager.getConnection(url, login, pass); + timeOfLastCheck = System.currentTimeMillis(); } public void close() { try { conn.close(); } catch (Exception e) {} - } } diff --git a/src/main/java/fr/pandacube/java/util/orm/ORM.java b/src/main/java/fr/pandacube/java/util/orm/ORM.java index da34a10..049c178 100644 --- a/src/main/java/fr/pandacube/java/util/orm/ORM.java +++ b/src/main/java/fr/pandacube/java/util/orm/ORM.java @@ -67,26 +67,20 @@ public final class ORM { } sql += ", PRIMARY KEY id(id))"; - PreparedStatement ps = connection.getNativeConnection().prepareStatement(sql); - int i = 1; - for (Object val : params) - ps.setObject(i++, val); - try { + + try (PreparedStatement ps = connection.getNativeConnection().prepareStatement(sql)) { + int i = 1; + for (Object val : params) + ps.setObject(i++, val); Log.info("Creating table " + elem.tableName() + ":\n" + ps.toString()); ps.executeUpdate(); - } finally { - ps.close(); } } private static boolean tableExist(String tableName) throws SQLException { - ResultSet set = null; boolean exist = false; - try { - set = connection.getNativeConnection().getMetaData().getTables(null, null, tableName, null); + try (ResultSet set = connection.getNativeConnection().getMetaData().getTables(null, null, tableName, null)) { exist = set.next(); - } finally { - if (set != null) set.close(); } return exist; } @@ -146,9 +140,7 @@ public final class ORM { SQLElementList elmts = new SQLElementList<>(); - PreparedStatement ps = connection.getNativeConnection().prepareStatement(sql); - - try { + try (PreparedStatement ps = connection.getNativeConnection().prepareStatement(sql)) { int i = 1; for (Object val : params) { @@ -156,16 +148,11 @@ public final class ORM { ps.setObject(i++, val); } Log.debug(ps.toString()); - ResultSet set = ps.executeQuery(); - - try { + + try (ResultSet set = ps.executeQuery()) { while (set.next()) elmts.add(getElementInstance(set, elemClass)); - } finally { - set.close(); } - } finally { - ps.close(); } return elmts; diff --git a/src/main/java/fr/pandacube/java/util/orm/SQLElement.java b/src/main/java/fr/pandacube/java/util/orm/SQLElement.java index a371af3..d5fdd4c 100644 --- a/src/main/java/fr/pandacube/java/util/orm/SQLElement.java +++ b/src/main/java/fr/pandacube/java/util/orm/SQLElement.java @@ -1,6 +1,5 @@ package fr.pandacube.java.util.orm; -import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -211,8 +210,6 @@ public abstract class SQLElement> { String toStringStatement = ""; try { - Connection conn = db.getNativeConnection(); - if (stored) { // mettre à jour les valeurs dans la base // restaurer l'ID au cas il aurait été changé à la main dans @@ -234,9 +231,8 @@ public abstract class SQLElement> { if (sql.length() > 0) sql = sql.substring(0, sql.length() - 1); - PreparedStatement ps = conn.prepareStatement("UPDATE " + tableName + " SET " + sql + " WHERE id=" + id); - - try { + try (PreparedStatement ps = db.getNativeConnection() + .prepareStatement("UPDATE " + tableName + " SET " + sql + " WHERE id=" + id)) { int i = 1; for (Object val : psValues) @@ -244,8 +240,6 @@ public abstract class SQLElement> { toStringStatement = ps.toString(); ps.executeUpdate(); - } finally { - ps.close(); } } else { // ajouter dans la base @@ -270,10 +264,9 @@ public abstract class SQLElement> { addValueToSQLObjectList(psValues, entry.getKey(), entry.getValue()); } - PreparedStatement ps = conn.prepareStatement( + try (PreparedStatement ps = db.getNativeConnection().prepareStatement( "INSERT INTO " + tableName + " (" + concat_fields + ") VALUES (" + concat_vals + ")", - Statement.RETURN_GENERATED_KEYS); - try { + Statement.RETURN_GENERATED_KEYS)) { int i = 1; for (Object val : psValues) @@ -282,16 +275,10 @@ public abstract class SQLElement> { toStringStatement = ps.toString(); ps.executeUpdate(); - ResultSet rs = ps.getGeneratedKeys(); - try { + try (ResultSet rs = ps.getGeneratedKeys()) { if (rs.next()) id = rs.getInt(1); - stored = true; - } finally { - rs.close(); } - } finally { - ps.close(); } } @@ -332,20 +319,15 @@ public abstract class SQLElement> { public void delete() throws ORMException { - try { - if (stored) { // supprimer la ligne de la base - PreparedStatement st = db.getNativeConnection() - .prepareStatement("DELETE FROM " + tableName + " WHERE id=" + id); - try { - Log.debug(st.toString()); - st.executeUpdate(); - markAsNotStored(); - } finally { - st.close(); - } + if (stored) { // supprimer la ligne de la base + try (PreparedStatement st = db.getNativeConnection() + .prepareStatement("DELETE FROM " + tableName + " WHERE id=" + id)) { + Log.debug(st.toString()); + st.executeUpdate(); + markAsNotStored(); + } catch (SQLException e) { + throw new ORMException(e); } - } catch (SQLException e) { - throw new ORMException(e); } } diff --git a/src/main/java/fr/pandacube/java/util/orm/SQLElementList.java b/src/main/java/fr/pandacube/java/util/orm/SQLElementList.java index 5f62fb8..c066b02 100644 --- a/src/main/java/fr/pandacube/java/util/orm/SQLElementList.java +++ b/src/main/java/fr/pandacube/java/util/orm/SQLElementList.java @@ -107,9 +107,8 @@ public class SQLElementList> extends ArrayList { } try(PreparedStatement ps = ORM.getConnection().getNativeConnection() - .prepareStatement("UPDATE " + storedEl.get(0).tableName() + " SET " + sqlSet + " WHERE " + sqlWhere);) { + .prepareStatement("UPDATE " + storedEl.get(0).tableName() + " SET " + sqlSet + " WHERE " + sqlWhere)) { - int i = 1; for (Object val : psValues) ps.setObject(i++, val); @@ -150,17 +149,14 @@ public class SQLElementList> extends ArrayList { sqlWhere += "id = " + el.getId(); } - PreparedStatement st = ORM.getConnection().getNativeConnection() - .prepareStatement("DELETE FROM " + storedEl.get(0).tableName() + " WHERE " + sqlWhere); - try { + try (PreparedStatement st = ORM.getConnection().getNativeConnection() + .prepareStatement("DELETE FROM " + storedEl.get(0).tableName() + " WHERE " + sqlWhere)) { Log.debug(st.toString()); st.executeUpdate(); for (E el : storedEl) el.markAsNotStored(); - } finally { - st.close(); } } catch (SQLException e) {