From b2a19e09c15e174eaa93672a8386a4e7552a9fbe Mon Sep 17 00:00:00 2001 From: Marc Baloup Date: Tue, 12 Jul 2016 19:26:49 +0200 Subject: [PATCH] =?UTF-8?q?Mise=20=C3=A0=20jour=20ORM=20+=20Utilisation=20?= =?UTF-8?q?plus=20simple=20des=20logs=20-=20toute=20la=20base=20de=20donn?= =?UTF-8?q?=C3=A9es=20fonctionne=20en=20utf8mb4=20-=20Le=20PlayerFinder=20?= =?UTF-8?q?g=C3=A8re=20l'historique=20des=20pseudos=20-=20Fin=20de=20l'uti?= =?UTF-8?q?lisation=20de=20l'ancien=20ORM?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/fr/pandacube/java/Pandacube.java | 16 ++ src/fr/pandacube/java/PandacubeUtil.java | 45 ---- src/fr/pandacube/java/util/Log.java | 46 ++++ src/fr/pandacube/java/util/PlayerFinder.java | 206 +++++++++++++++++- .../pandacube/java/util/db/DBConnection.java | 54 ----- src/fr/pandacube/java/util/db/ORM.java | 2 + src/fr/pandacube/java/util/db/SQLElement.java | 6 +- src/fr/pandacube/java/util/db/SQLTable.java | 10 +- .../pandacube/java/util/db/package-info.java | 2 + .../pandacube/java/util/db2/SQLContact.java | 15 +- .../java/util/db2/SQLForumForum.java | 23 +- .../pandacube/java/util/db2/SQLForumPost.java | 13 +- .../java/util/db2/SQLForumThread.java | 21 +- .../java/util/db2/SQLLoginHistory.java | 15 +- .../pandacube/java/util/db2/SQLMPGroup.java | 26 +++ .../java/util/db2/SQLMPGroupUser.java | 35 ++- .../pandacube/java/util/db2/SQLMPMessage.java | 108 ++++++++- .../java/util/db2/SQLModoHistory.java | 15 +- .../java/util/db2/SQLOnlineshopHistory.java | 21 +- src/fr/pandacube/java/util/db2/SQLPlayer.java | 22 +- .../java/util/db2/SQLPlayerIgnore.java | 56 ++++- .../java/util/db2/SQLStaffTicket.java | 6 +- .../java/util/db2/SQLUUIDPlayer.java | 36 +++ .../java/util/db2/sql_tools/DBConnection.java | 13 +- .../java/util/db2/sql_tools/ORM.java | 137 ++++++++---- .../java/util/db2/sql_tools/ORMException.java | 18 ++ .../db2/sql_tools/ORMInitTableException.java | 18 ++ .../java/util/db2/sql_tools/SQLElement.java | 206 ++++++++++-------- .../java/util/db2/sql_tools/SQLFKField.java | 63 ++++++ .../java/util/db2/sql_tools/SQLOrderBy.java | 19 +- .../java/util/db2/sql_tools/SQLType.java | 12 + .../util/db2/sql_tools/SQLWhereChain.java | 2 +- .../java/util/db2/sql_tools/SQLWhereComp.java | 2 +- .../java/util/db2/sql_tools/SQLWhereLike.java | 5 +- .../java/util/db2/sql_tools/SQLWhereNull.java | 4 +- .../java/util/network/client/TCPClient.java | 13 +- .../java/util/network/packet/Packet.java | 4 +- .../java/util/network/server/TCPServer.java | 19 +- .../network_api/server/PacketExecutor.java | 4 +- 39 files changed, 977 insertions(+), 361 deletions(-) create mode 100644 src/fr/pandacube/java/Pandacube.java delete mode 100644 src/fr/pandacube/java/PandacubeUtil.java create mode 100644 src/fr/pandacube/java/util/Log.java delete mode 100644 src/fr/pandacube/java/util/db/DBConnection.java create mode 100644 src/fr/pandacube/java/util/db/package-info.java create mode 100644 src/fr/pandacube/java/util/db2/SQLUUIDPlayer.java create mode 100644 src/fr/pandacube/java/util/db2/sql_tools/ORMException.java create mode 100644 src/fr/pandacube/java/util/db2/sql_tools/ORMInitTableException.java create mode 100644 src/fr/pandacube/java/util/db2/sql_tools/SQLFKField.java diff --git a/src/fr/pandacube/java/Pandacube.java b/src/fr/pandacube/java/Pandacube.java new file mode 100644 index 0000000..4c2f3ff --- /dev/null +++ b/src/fr/pandacube/java/Pandacube.java @@ -0,0 +1,16 @@ +package fr.pandacube.java; + +import java.nio.charset.Charset; + +public class Pandacube { + + + + public static final Charset NETWORK_CHARSET = Charset.forName("UTF-8"); + + public static final int NETWORK_TCP_BUFFER_SIZE = 1024*1024; + + public static final int NETWORK_TIMEOUT = 30*1000; // 30 secondes + + +} diff --git a/src/fr/pandacube/java/PandacubeUtil.java b/src/fr/pandacube/java/PandacubeUtil.java deleted file mode 100644 index 8fdaa34..0000000 --- a/src/fr/pandacube/java/PandacubeUtil.java +++ /dev/null @@ -1,45 +0,0 @@ -package fr.pandacube.java; - -import java.nio.charset.Charset; -import java.util.logging.Logger; - -public class PandacubeUtil { - - - - public static final Charset NETWORK_CHARSET = Charset.forName("UTF-8"); - - public static final int NETWORK_TCP_BUFFER_SIZE = 1024*1024; - - public static final int NETWORK_TIMEOUT = 30*1000; // 30 secondes - - - - - /** - * Représente le logger du serveur Spigot ou de Bungee,selon l'environnement - */ - private static Logger masterLogger; - - /** - * Représente le logger de PandacubeUtil, mais défini selon l'environnement Spigot ou Bungee. - */ - private static Logger pluginLogger; - - public static Logger getMasterLogger() { - return masterLogger; - } - - public static void setMasterLogger(Logger masterLogger) { - PandacubeUtil.masterLogger = masterLogger; - } - - public static Logger getPluginLogger() { - return pluginLogger; - } - - public static void setPluginLogger(Logger pluginLogger) { - PandacubeUtil.pluginLogger = pluginLogger; - } - -} diff --git a/src/fr/pandacube/java/util/Log.java b/src/fr/pandacube/java/util/Log.java new file mode 100644 index 0000000..d0101b8 --- /dev/null +++ b/src/fr/pandacube/java/util/Log.java @@ -0,0 +1,46 @@ +package fr.pandacube.java.util; + +import java.util.logging.Level; +import java.util.logging.Logger; + +public class Log { + + private static Logger logger; + + public static Logger getLogger() { + return logger; + } + + public static void setLogger(Logger l) { + logger = l; + } + + public static void info(String message) { + logger.info(message); + } + + public static void warning(String message, Throwable t) { + logger.log(Level.WARNING, message, t); + } + + public static void warning(Throwable t) { + logger.log(Level.WARNING, "", t); + } + + public static void warning(String message) { + logger.warning(message); + } + + public static void severe(String message, Throwable t) { + logger.log(Level.SEVERE, message, t); + } + + public static void severe(Throwable t) { + logger.log(Level.SEVERE, "", t); + } + + public static void severe(String message) { + logger.severe(message); + } + +} diff --git a/src/fr/pandacube/java/util/PlayerFinder.java b/src/fr/pandacube/java/util/PlayerFinder.java index 437edc6..929451b 100644 --- a/src/fr/pandacube/java/util/PlayerFinder.java +++ b/src/fr/pandacube/java/util/PlayerFinder.java @@ -1,9 +1,26 @@ package fr.pandacube.java.util; +import java.util.ArrayList; +import java.util.List; import java.util.UUID; +import fr.pandacube.java.util.db2.SQLLoginHistory; +import fr.pandacube.java.util.db2.SQLPlayer; +import fr.pandacube.java.util.db2.SQLUUIDPlayer; +import fr.pandacube.java.util.db2.sql_tools.ORM; +import fr.pandacube.java.util.db2.sql_tools.SQLOrderBy; +import fr.pandacube.java.util.db2.sql_tools.SQLOrderBy.Direction; +import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp; +import fr.pandacube.java.util.db2.sql_tools.SQLWhereLike; +import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp.SQLComparator; import net.alpenblock.bungeeperms.BungeePerms; +/* + * Etape de recherche de joueur : + * Passer par bungeeperms (si accessible) + * utiliser directement la table pseudo <-> uuid + * chercher dans l'historique de login + */ public class PlayerFinder { private static BungeePerms getPermPlugin() { @@ -15,28 +32,185 @@ public class PlayerFinder { } - - public static String getPlayerName(UUID id) { - BungeePerms pl = getPermPlugin(); - if (pl == null) return null; + public static String getLastKnownName(UUID id) { + if (id == null) + return null; - return pl.getPermissionsManager().getUUIDPlayerDB().getPlayerName(id); + // on passe par le plugin de permission (mise en cache ? ) + BungeePerms pl = getPermPlugin(); + if (pl != null) + return pl.getPermissionsManager().getUUIDPlayerDB().getPlayerName(id); + + // on tente en accédant directement à la table des identifiants + try { + SQLUUIDPlayer el = ORM.getFirst(SQLUUIDPlayer.class, new SQLWhereComp(SQLUUIDPlayer.uuid, SQLComparator.EQ, id.toString()), null); + if (el != null) + return el.get(SQLUUIDPlayer.player); + } catch (Exception e) { + Log.severe("Can't search for player name from uuid in database", e); + } + + // le pseudo est introuvable + return null; + } + + + + + + public static List getLocalNameHistory(UUID id) { + List ret = new ArrayList<>(); + + if (id == null) + return ret; + + String last = getLastKnownName(id); + if (last != null) + ret.add(last); + + try { + List els = ORM.getAll(SQLLoginHistory.class, new SQLWhereComp(SQLLoginHistory.playerId, SQLComparator.EQ, id.toString()), new SQLOrderBy().addField(SQLLoginHistory.time, Direction.DESC), null, null); + + for (SQLLoginHistory el : els) { + String name = el.get(SQLLoginHistory.playerName); + if (ret.contains(name)) + continue; + ret.add(name); + } + + } catch (Exception e) { + Log.severe("Can't search for olds players names from uuid in database", e); + } + + return ret; } - public static UUID getPlayerId(String name) { - if (!isValidPlayerName(name)) return null; // évite une recherche inutile dans la base de donnée - BungeePerms pl = getPermPlugin(); - if (pl == null) return null; + + + + + + /** + * Cherche un identifiant de compte en se basant sur le pseudo passé en paramètre. La méthode + * cherchera d'abord dans les derniers pseudos connus. Puis, cherchera la dernière personne à + * s'être connecté avec ce pseudo sur le serveur. + * @param exactName le pseudo complet, insensible à la casse, et dans un format de pseudo valide + * @param old si on doit chercher dans les anciens pseudos de joueurs + * @return l'UUID du joueur si trouvé, null sinon + */ + public static UUID getPlayerId(String exactName, boolean old) { + if (!isValidPlayerName(exactName)) return null; // évite une recherche inutile dans la base de donnée - return pl.getPermissionsManager().getUUIDPlayerDB().getUUID(name); + // on tente d'abord via le plugin de permission + BungeePerms pl = getPermPlugin(); + if (pl != null) + return pl.getPermissionsManager().getUUIDPlayerDB().getUUID(exactName); + + // on tente en accédant directement à la table des identifiants + try { + SQLUUIDPlayer el = ORM.getFirst(SQLUUIDPlayer.class, new SQLWhereLike(SQLUUIDPlayer.player, exactName.replace("_", "\\_")), null); + if (el != null) + return el.getUUID(); + } catch (Exception e) { + Log.severe("Can't search for uuid from player name in database", e); + } + + if (!old) return null; + + // on recherche dans les anciens pseudos + try { + SQLLoginHistory el = ORM.getFirst(SQLLoginHistory.class, new SQLWhereLike(SQLLoginHistory.playerName, exactName.replace("_", "\\_")), new SQLOrderBy().addField(SQLLoginHistory.time, Direction.DESC)); + if (el != null) + return el.getPlayerId(); + } catch (Exception e) { + Log.severe("Can't search for uuid from old player name in database", e); + } + + // on a pas trouvé + return null; } + + + + /** + * + * @param query le pseudo, partiel ou complet, insensible à la casse, qu'on recherche + * @param old si on cherche aussi dans les anciens pseudos + * @return + */ + public static List searchForPlayers(String query, boolean old) { + List res = new ArrayList<>(); + + if (!isValidPlayerName(query)) return res; + + // rechercher parmis les derniers pseudos connus de chaque joueurs + try { + List els = ORM.getAll(SQLUUIDPlayer.class, new SQLWhereLike(SQLUUIDPlayer.player, "%"+query.replace("_", "\\_")+"%"), null, null, null); + + for (SQLUUIDPlayer el : els) { + res.add(new PlayerSearchResult(el.getUUID(), el.get(SQLUUIDPlayer.player), null)); + } + + } catch (Exception e) { + Log.severe("Can't search for players names in database", e); + } + + + if (!old) return res; + + // rechercher parmi les anciens pseudos de joueurs + try { + List els = ORM.getAll(SQLLoginHistory.class, new SQLWhereLike(SQLLoginHistory.playerName, "%"+query.replace("_", "\\_")+"%"), new SQLOrderBy().addField(SQLLoginHistory.time, Direction.DESC), null, null); + + for (SQLLoginHistory el : els) { + if (res.contains(new PlayerSearchResult(el.getPlayerId(), null, null))) + continue; + res.add(new PlayerSearchResult(el.getPlayerId(), getLastKnownName(el.getPlayerId()), el.get(SQLLoginHistory.playerName))); + } + + } catch (Exception e) { + Log.severe("Can't search for uuid from player name in database", e); + } + + + return res; + } + + + + + + public static class PlayerSearchResult { + public final UUID uuid; + public String lastName; + public final String nameFound; + PlayerSearchResult(UUID id, String last, String found) { + uuid = id; + lastName = last; + nameFound = found; + } + + @Override + public boolean equals(Object o) { + if (o == null || !(o instanceof PlayerSearchResult)) return false; + return uuid.equals(((PlayerSearchResult)o).uuid); + } + + @Override + public int hashCode() { return uuid.hashCode(); } + } + + + + + @@ -49,4 +223,16 @@ public class PlayerFinder { + + + public static SQLPlayer getDBPlayer(UUID id) throws Exception { + if (id == null) return null; + return ORM.getFirst(SQLPlayer.class, new SQLWhereComp(SQLPlayer.playerId, SQLComparator.EQ, id.toString()), null); + } + + + + + + } diff --git a/src/fr/pandacube/java/util/db/DBConnection.java b/src/fr/pandacube/java/util/db/DBConnection.java deleted file mode 100644 index 409c2b6..0000000 --- a/src/fr/pandacube/java/util/db/DBConnection.java +++ /dev/null @@ -1,54 +0,0 @@ -package fr.pandacube.java.util.db; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.sql.Statement; - -public class DBConnection { - Connection conn; - private String url; - private String login; - private String pass; - - public DBConnection(String host, int port, String dbname, String l, String p) throws ClassNotFoundException, SQLException { - Class.forName("com.mysql.jdbc.Driver"); - url = "jdbc:mysql://"+host+":"+port+"/"+dbname; - login = l; - pass = p; - conn = DriverManager.getConnection(url, login, pass); - - - } - - - public void reconnectIfNecessary() throws SQLException - { - try - { - Statement stmt = conn.createStatement(); - stmt.close(); - } - catch(SQLException e) - { - close(); - conn = DriverManager.getConnection(url, login, pass); - } - } - - public Connection getConnection() throws SQLException - { - if (!conn.isValid(1)) - reconnectIfNecessary(); - return conn; - } - - - public void close() { - try { - conn.close(); - } catch (Exception e) { } - - } - -} diff --git a/src/fr/pandacube/java/util/db/ORM.java b/src/fr/pandacube/java/util/db/ORM.java index bbfd6bf..aa6ecde 100644 --- a/src/fr/pandacube/java/util/db/ORM.java +++ b/src/fr/pandacube/java/util/db/ORM.java @@ -4,6 +4,8 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.List; +import fr.pandacube.java.util.db2.sql_tools.DBConnection; + /** * ORM = Object-Relational Mapping
* Liste des tables avec leur classes : diff --git a/src/fr/pandacube/java/util/db/SQLElement.java b/src/fr/pandacube/java/util/db/SQLElement.java index 4ce3543..9dd26a4 100644 --- a/src/fr/pandacube/java/util/db/SQLElement.java +++ b/src/fr/pandacube/java/util/db/SQLElement.java @@ -8,6 +8,8 @@ import java.sql.Statement; import org.apache.commons.lang.StringUtils; +import fr.pandacube.java.util.db2.sql_tools.DBConnection; + public abstract class SQLElement { DBConnection db = ORM.connection; @@ -40,7 +42,7 @@ public abstract class SQLElement { try { Connection conn; - conn = db.getConnection(); + conn = db.getNativeConnection(); String[] fields = getFieldsName(), values = getValues(); @@ -118,7 +120,7 @@ public abstract class SQLElement { try { if (saved) { // supprimer la ligne de la base - PreparedStatement st = db.getConnection().prepareStatement("DELETE FROM "+tableName+" WHERE id="+id); + PreparedStatement st = db.getNativeConnection().prepareStatement("DELETE FROM "+tableName+" WHERE id="+id); try { st.executeUpdate(); saved = false; diff --git a/src/fr/pandacube/java/util/db/SQLTable.java b/src/fr/pandacube/java/util/db/SQLTable.java index 1a91ec0..7d9ca17 100644 --- a/src/fr/pandacube/java/util/db/SQLTable.java +++ b/src/fr/pandacube/java/util/db/SQLTable.java @@ -6,6 +6,8 @@ import java.sql.Statement; import java.util.ArrayList; import java.util.List; +import fr.pandacube.java.util.db2.sql_tools.DBConnection; + public abstract class SQLTable { DBConnection db = ORM.connection; @@ -24,7 +26,7 @@ public abstract class SQLTable { private void createTable() throws SQLException { - Statement stmt = db.getConnection().createStatement(); + Statement stmt = db.getNativeConnection().createStatement(); String sql = "CREATE TABLE IF NOT EXISTS "+tableName+" " + "("+createTableParameters()+")"; try { @@ -39,7 +41,7 @@ public abstract class SQLTable { ResultSet set = null; boolean exist = false; try { - set = db.getConnection().getMetaData().getTables(null, null, tableName, null); + set = db.getNativeConnection().getMetaData().getTables(null, null, tableName, null); exist = set.next(); } finally { if (set != null) @@ -77,7 +79,7 @@ public abstract class SQLTable { public T get(int id) throws SQLException { T elementInstance = null; - Statement stmt = db.getConnection().createStatement(); + Statement stmt = db.getNativeConnection().createStatement(); try { String sql = "SELECT * FROM "+tableName+" WHERE id = "+id+";"; @@ -109,7 +111,7 @@ public abstract class SQLTable { public List getAll(String where, String orderBy, Integer limit, Integer offset) throws SQLException { - Statement stmt = db.getConnection().createStatement(); + Statement stmt = db.getNativeConnection().createStatement(); String sql = "SELECT * FROM "+tableName; if (where != null) diff --git a/src/fr/pandacube/java/util/db/package-info.java b/src/fr/pandacube/java/util/db/package-info.java new file mode 100644 index 0000000..8e88b93 --- /dev/null +++ b/src/fr/pandacube/java/util/db/package-info.java @@ -0,0 +1,2 @@ +@java.lang.Deprecated +package fr.pandacube.java.util.db; diff --git a/src/fr/pandacube/java/util/db2/SQLContact.java b/src/fr/pandacube/java/util/db2/SQLContact.java index 65517dd..fb5bb30 100644 --- a/src/fr/pandacube/java/util/db2/SQLContact.java +++ b/src/fr/pandacube/java/util/db2/SQLContact.java @@ -4,6 +4,7 @@ import java.util.UUID; import fr.pandacube.java.util.db2.sql_tools.SQLElement; import fr.pandacube.java.util.db2.sql_tools.SQLField; +import fr.pandacube.java.util.db2.sql_tools.SQLFKField; import fr.pandacube.java.util.db2.sql_tools.SQLType; public class SQLContact extends SQLElement { @@ -18,13 +19,13 @@ public class SQLContact extends SQLElement { - public static final SQLField time = new SQLField<>("time", SQLType.INT, false); - public static final SQLField playerId = new SQLField<>("playerId", SQLType.CHAR(36), true); - public static final SQLField userName = new SQLField<>("userName", SQLType.VARCHAR(50), true); - public static final SQLField userMail = new SQLField<>("userMail", SQLType.VARCHAR(50), true); - public static final SQLField titre = new SQLField<>("titre", SQLType.VARCHAR(100), false); - public static final SQLField texte = new SQLField<>("texte", SQLType.TEXT, false); - public static final SQLField hidden = new SQLField<>("hidden", SQLType.BOOLEAN, false, (Boolean)false); + public static final SQLField time = new SQLField<>( "time", SQLType.INT, false); + public static final SQLFKField playerId = new SQLFKField<>("playerId", SQLType.CHAR(36), true, SQLPlayer.class, SQLPlayer.playerId); + public static final SQLField userName = new SQLField<>( "userName", SQLType.VARCHAR(50), true); + public static final SQLField userMail = new SQLField<>( "userMail", SQLType.VARCHAR(50), true); + public static final SQLField titre = new SQLField<>( "titre", SQLType.VARCHAR(100), false); + public static final SQLField texte = new SQLField<>( "texte", SQLType.TEXT, false); + public static final SQLField hidden = new SQLField<>( "hidden", SQLType.BOOLEAN, false, (Boolean)false); diff --git a/src/fr/pandacube/java/util/db2/SQLForumForum.java b/src/fr/pandacube/java/util/db2/SQLForumForum.java index d503500..5fad3b3 100644 --- a/src/fr/pandacube/java/util/db2/SQLForumForum.java +++ b/src/fr/pandacube/java/util/db2/SQLForumForum.java @@ -1,6 +1,7 @@ package fr.pandacube.java.util.db2; import fr.pandacube.java.util.db2.sql_tools.SQLElement; +import fr.pandacube.java.util.db2.sql_tools.SQLFKField; import fr.pandacube.java.util.db2.sql_tools.SQLField; import fr.pandacube.java.util.db2.sql_tools.SQLType; @@ -14,17 +15,17 @@ public class SQLForumForum extends SQLElement { protected String tableName() { return "pandacube_forum_forum"; } - public static final SQLField catId = new SQLField<>("catId", SQLType.INT, false); - public static final SQLField nom = new SQLField<>("nom", SQLType.VARCHAR(100), false); - public static final SQLField description = new SQLField<>("description", SQLType.TEXT, false); - public static final SQLField ordre = new SQLField<>("ordre", SQLType.INT, false); - public static final SQLField authView = new SQLField<>("authView", SQLType.INT, false); - public static final SQLField authPost = new SQLField<>("authPost", SQLType.INT, false); - public static final SQLField authThread = new SQLField<>("authThread", SQLType.INT, false); - public static final SQLField authAnchored = new SQLField<>("authAnchored", SQLType.INT, false); - public static final SQLField authModo = new SQLField<>("authModo", SQLType.INT, false); - public static final SQLField nbThreads = new SQLField<>("nbThreads", SQLType.INT, false); - public static final SQLField nbMessages = new SQLField<>("nbMessages", SQLType.INT, false); + public static final SQLFKField catId = SQLFKField.idFK("catId", SQLType.INT, false, SQLForumCategorie.class); + public static final SQLField nom = new SQLField<>("nom", SQLType.VARCHAR(100), false); + public static final SQLField description = new SQLField<>("description", SQLType.TEXT, false); + public static final SQLField ordre = new SQLField<>("ordre", SQLType.INT, false); + public static final SQLField authView = new SQLField<>("authView", SQLType.INT, false); + public static final SQLField authPost = new SQLField<>("authPost", SQLType.INT, false); + public static final SQLField authThread = new SQLField<>("authThread", SQLType.INT, false); + public static final SQLField authAnchored = new SQLField<>("authAnchored", SQLType.INT, false); + public static final SQLField authModo = new SQLField<>("authModo", SQLType.INT, false); + public static final SQLField nbThreads = new SQLField<>("nbThreads", SQLType.INT, false); + public static final SQLField nbMessages = new SQLField<>("nbMessages", SQLType.INT, false); diff --git a/src/fr/pandacube/java/util/db2/SQLForumPost.java b/src/fr/pandacube/java/util/db2/SQLForumPost.java index 3fb1d76..244e90d 100644 --- a/src/fr/pandacube/java/util/db2/SQLForumPost.java +++ b/src/fr/pandacube/java/util/db2/SQLForumPost.java @@ -3,6 +3,7 @@ package fr.pandacube.java.util.db2; import java.util.UUID; import fr.pandacube.java.util.db2.sql_tools.SQLElement; +import fr.pandacube.java.util.db2.sql_tools.SQLFKField; import fr.pandacube.java.util.db2.sql_tools.SQLField; import fr.pandacube.java.util.db2.sql_tools.SQLType; @@ -16,14 +17,14 @@ public class SQLForumPost extends SQLElement { protected String tableName() { return "pandacube_forum_post"; } - public static final SQLField createur = new SQLField<>("createur", SQLType.CHAR(36), false); - public static final SQLField texte = new SQLField<>("texte", SQLType.TEXT, false); - public static final SQLField time = new SQLField<>("time", SQLType.INT, false); - public static final SQLField threadId = new SQLField<>("threadId", SQLType.INT, false); - public static final SQLField moderated = new SQLField<>("moderated", SQLType.BOOLEAN, false); + public static final SQLField createur = new SQLField<>("createur", SQLType.CHAR(36), false); + public static final SQLField texte = new SQLField<>("texte", SQLType.TEXT, false); + public static final SQLField time = new SQLField<>("time", SQLType.INT, false); + public static final SQLFKField threadId = SQLFKField.idFK("threadId", SQLType.INT, false, SQLForumThread.class); + public static final SQLField moderated = new SQLField<>("moderated", SQLType.BOOLEAN, false); + - public UUID getCreateurId() { String id = (String)get(createur); return (id == null) ? null : UUID.fromString(id); diff --git a/src/fr/pandacube/java/util/db2/SQLForumThread.java b/src/fr/pandacube/java/util/db2/SQLForumThread.java index 9cbe19c..78f82d7 100644 --- a/src/fr/pandacube/java/util/db2/SQLForumThread.java +++ b/src/fr/pandacube/java/util/db2/SQLForumThread.java @@ -3,6 +3,7 @@ package fr.pandacube.java.util.db2; import java.util.UUID; import fr.pandacube.java.util.db2.sql_tools.SQLElement; +import fr.pandacube.java.util.db2.sql_tools.SQLFKField; import fr.pandacube.java.util.db2.sql_tools.SQLField; import fr.pandacube.java.util.db2.sql_tools.SQLType; @@ -16,17 +17,17 @@ public class SQLForumThread extends SQLElement { protected String tableName() { return "pandacube_forum_thread"; } - public static final SQLField forumId = new SQLField<>("forumId", SQLType.INT, false); - public static final SQLField titre = new SQLField<>("titre", SQLType.VARCHAR(60), false); - public static final SQLField createur = new SQLField<>("createur", SQLType.CHAR(36), false); - public static final SQLField vu = new SQLField<>("vu", SQLType.INT, false); - public static final SQLField time = new SQLField<>("time", SQLType.BIGINT, false); - public static final SQLField anchored = new SQLField<>("anchored", SQLType.BOOLEAN, false); - public static final SQLField locked = new SQLField<>("locked", SQLType.BOOLEAN, false); - public static final SQLField nbMessages = new SQLField<>("nbMessages", SQLType.INT, false); + public static final SQLFKField forumId = SQLFKField.idFK("forumId", SQLType.INT, false, SQLForumForum.class); + public static final SQLField titre = new SQLField<>("titre", SQLType.VARCHAR(60), false); + public static final SQLFKField createur = new SQLFKField<>("createur", SQLType.CHAR(36), false, SQLPlayer.class, SQLPlayer.playerId); + public static final SQLField vu = new SQLField<>("vu", SQLType.INT, false); + public static final SQLField time = new SQLField<>("time", SQLType.BIGINT, false); + public static final SQLField anchored = new SQLField<>("anchored", SQLType.BOOLEAN, false); + public static final SQLField locked = new SQLField<>("locked", SQLType.BOOLEAN, false); + public static final SQLField nbMessages = new SQLField<>("nbMessages", SQLType.INT, false); + + - - public UUID getCreateurId() { String id = (String)get(createur); return (id == null) ? null : UUID.fromString(id); diff --git a/src/fr/pandacube/java/util/db2/SQLLoginHistory.java b/src/fr/pandacube/java/util/db2/SQLLoginHistory.java index ba28148..57fc0c8 100644 --- a/src/fr/pandacube/java/util/db2/SQLLoginHistory.java +++ b/src/fr/pandacube/java/util/db2/SQLLoginHistory.java @@ -3,6 +3,7 @@ package fr.pandacube.java.util.db2; import java.util.UUID; import fr.pandacube.java.util.db2.sql_tools.SQLElement; +import fr.pandacube.java.util.db2.sql_tools.SQLFKField; import fr.pandacube.java.util.db2.sql_tools.SQLField; import fr.pandacube.java.util.db2.sql_tools.SQLType; @@ -16,13 +17,13 @@ public class SQLLoginHistory extends SQLElement { protected String tableName() { return "pandacube_login_history"; } - public static final SQLField time = new SQLField<>("time", SQLType.BIGINT, false); - public static final SQLField playerId = new SQLField<>("playerId", SQLType.CHAR(36), false); - public static final SQLField ip = new SQLField<>("ip", SQLType.VARCHAR(128), true); - public static final SQLField actionType = new SQLField<>("actionType", SQLType.ENUM(ActionType.class), false); - public static final SQLField nbOnline = new SQLField<>("nbOnline", SQLType.INT, false); - public static final SQLField playerName = new SQLField<>("playerName", SQLType.VARCHAR(16), true); - public static final SQLField minecraftVersion = new SQLField<>("minecraftVersion", SQLType.INT, false, 0); + public static final SQLField time = new SQLField<>("time", SQLType.BIGINT, false); + public static final SQLFKField playerId = new SQLFKField<>("playerId", SQLType.CHAR(36), false, SQLPlayer.class, SQLPlayer.playerId); + public static final SQLField ip = new SQLField<>("ip", SQLType.VARCHAR(128), true); + public static final SQLField actionType = new SQLField<>("actionType", SQLType.ENUM(ActionType.class), false); + public static final SQLField nbOnline = new SQLField<>("nbOnline", SQLType.INT, false); + public static final SQLField playerName = new SQLField<>("playerName", SQLType.VARCHAR(16), true); + public static final SQLField minecraftVersion = new SQLField<>("minecraftVersion", SQLType.INT, false, 0); diff --git a/src/fr/pandacube/java/util/db2/SQLMPGroup.java b/src/fr/pandacube/java/util/db2/SQLMPGroup.java index 7cd47b5..b357558 100644 --- a/src/fr/pandacube/java/util/db2/SQLMPGroup.java +++ b/src/fr/pandacube/java/util/db2/SQLMPGroup.java @@ -1,8 +1,14 @@ package fr.pandacube.java.util.db2; +import fr.pandacube.java.util.db2.sql_tools.ORM; +import fr.pandacube.java.util.db2.sql_tools.ORMException; import fr.pandacube.java.util.db2.sql_tools.SQLElement; +import fr.pandacube.java.util.db2.sql_tools.SQLElementList; import fr.pandacube.java.util.db2.sql_tools.SQLField; +import fr.pandacube.java.util.db2.sql_tools.SQLOrderBy; import fr.pandacube.java.util.db2.sql_tools.SQLType; +import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp; +import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp.SQLComparator; public class SQLMPGroup extends SQLElement { @@ -15,5 +21,25 @@ public class SQLMPGroup extends SQLElement { public static final SQLField groupName = new SQLField<>("groupName", SQLType.VARCHAR(16), false); + + + + public SQLElementList getGroupUsers() throws ORMException { + return ORM.getAll(SQLMPGroupUser.class, + new SQLWhereComp(SQLMPGroupUser.groupId, SQLComparator.EQ, getId()), + new SQLOrderBy().addField(ORM.getSQLIdField(SQLMPGroupUser.class)), null, null); + } + + + + + + public static SQLMPGroup getByName(String name) throws ORMException { + if (name == null) + return null; + + return ORM.getFirst(SQLMPGroup.class, new SQLWhereComp(groupName, SQLComparator.EQ, name), null); + } + } diff --git a/src/fr/pandacube/java/util/db2/SQLMPGroupUser.java b/src/fr/pandacube/java/util/db2/SQLMPGroupUser.java index 7eb12fa..9900ed9 100644 --- a/src/fr/pandacube/java/util/db2/SQLMPGroupUser.java +++ b/src/fr/pandacube/java/util/db2/SQLMPGroupUser.java @@ -1,10 +1,16 @@ package fr.pandacube.java.util.db2; +import java.sql.SQLException; import java.util.UUID; +import fr.pandacube.java.util.db2.sql_tools.ORM; import fr.pandacube.java.util.db2.sql_tools.SQLElement; -import fr.pandacube.java.util.db2.sql_tools.SQLField; +import fr.pandacube.java.util.db2.sql_tools.SQLFKField; import fr.pandacube.java.util.db2.sql_tools.SQLType; +import fr.pandacube.java.util.db2.sql_tools.SQLWhereChain; +import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp; +import fr.pandacube.java.util.db2.sql_tools.SQLWhereChain.SQLBoolOp; +import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp.SQLComparator; public class SQLMPGroupUser extends SQLElement { @@ -16,8 +22,8 @@ public class SQLMPGroupUser extends SQLElement { protected String tableName() { return "pandacube_mp_group_user"; } - public static final SQLField groupId = new SQLField<>("groupId", SQLType.INT, false); - public static final SQLField playerId = new SQLField<>("playerId", SQLType.CHAR(36), false); + public static final SQLFKField groupId = SQLFKField.idFK( "groupId", SQLType.INT, false, SQLMPGroup.class); + public static final SQLFKField playerId = new SQLFKField<>("playerId", SQLType.CHAR(36), false, SQLPlayer.class, SQLPlayer.playerId); // TODO ajouter un champ qui dit si le joueur est admin du groupe @@ -33,5 +39,28 @@ public class SQLMPGroupUser extends SQLElement { set(playerId, (id == null) ? null : id.toString()); } + + + + + + + + + + /** + * Retourne l'instance de SQLMPGroupUser correcpondant à la présence d'un joueur dans un groupe + * @param group le groupe concerné, sous forme d'instance de SQLMPGroup + * @param player l'identifiant du joueur + * @return null si la correspondance n'a pas été trouvée + * @throws SQLException + */ + public static SQLMPGroupUser getPlayerInGroup(SQLMPGroup group, UUID player) throws Exception { + if (player == null || group == null) return null; + return ORM.getFirst(SQLMPGroupUser.class, + new SQLWhereChain(SQLBoolOp.AND) + .add(new SQLWhereComp(groupId, SQLComparator.EQ, group.getId())) + .add(new SQLWhereComp(playerId, SQLComparator.EQ, player.toString())), null); + } } diff --git a/src/fr/pandacube/java/util/db2/SQLMPMessage.java b/src/fr/pandacube/java/util/db2/SQLMPMessage.java index abb4480..fdb8188 100644 --- a/src/fr/pandacube/java/util/db2/SQLMPMessage.java +++ b/src/fr/pandacube/java/util/db2/SQLMPMessage.java @@ -2,9 +2,22 @@ package fr.pandacube.java.util.db2; import java.util.UUID; +import fr.pandacube.java.util.PlayerFinder; +import fr.pandacube.java.util.db2.sql_tools.ORM; +import fr.pandacube.java.util.db2.sql_tools.ORMException; import fr.pandacube.java.util.db2.sql_tools.SQLElement; +import fr.pandacube.java.util.db2.sql_tools.SQLElementList; +import fr.pandacube.java.util.db2.sql_tools.SQLFKField; import fr.pandacube.java.util.db2.sql_tools.SQLField; +import fr.pandacube.java.util.db2.sql_tools.SQLOrderBy; import fr.pandacube.java.util.db2.sql_tools.SQLType; +import fr.pandacube.java.util.db2.sql_tools.SQLWhereChain; +import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp; +import fr.pandacube.java.util.db2.sql_tools.SQLWhereLike; +import fr.pandacube.java.util.db2.sql_tools.SQLOrderBy.Direction; +import fr.pandacube.java.util.db2.sql_tools.SQLWhereChain.SQLBoolOp; +import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp.SQLComparator; +import fr.pandacube.java.util.db2.sql_tools.SQLWhereNull; public class SQLMPMessage extends SQLElement { @@ -16,16 +29,16 @@ public class SQLMPMessage extends SQLElement { protected String tableName() { return "pandacube_mp_message"; } - public static final SQLField time = new SQLField<>("time", SQLType.BIGINT, false); - public static final SQLField securityKey = new SQLField<>("securityKey", SQLType.INT, false); - public static final SQLField viewerId = new SQLField<>("viewerId", SQLType.CHAR(36), false); - public static final SQLField sourceId = new SQLField<>("sourceId", SQLType.CHAR(36), true); - public static final SQLField destId = new SQLField<>("destId", SQLType.CHAR(36), true); - public static final SQLField destGroup = new SQLField<>("destGroup", SQLType.INT, true); - public static final SQLField message = new SQLField<>("message", SQLType.VARCHAR(512), false); - public static final SQLField wasRead = new SQLField<>("wasRead", SQLType.BOOLEAN, false); - public static final SQLField deleted = new SQLField<>("deleted", SQLType.BOOLEAN, false); - public static final SQLField serverSync = new SQLField<>("serverSync", SQLType.BOOLEAN, false); + public static final SQLField time = new SQLField<>("time", SQLType.BIGINT, false); + public static final SQLField securityKey = new SQLField<>("securityKey", SQLType.INT, false); + public static final SQLFKField viewerId = new SQLFKField<>("viewerId", SQLType.CHAR(36), false, SQLPlayer.class, SQLPlayer.playerId); + public static final SQLFKField sourceId = new SQLFKField<>("sourceId", SQLType.CHAR(36), true, SQLPlayer.class, SQLPlayer.playerId); + public static final SQLFKField destId = new SQLFKField<>("destId", SQLType.CHAR(36), true, SQLPlayer.class, SQLPlayer.playerId); + public static final SQLFKField destGroup = SQLFKField.idFK("destGroup", SQLType.INT, true, SQLMPGroup.class); + public static final SQLField message = new SQLField<>("message", SQLType.VARCHAR(512), false); + public static final SQLField wasRead = new SQLField<>("wasRead", SQLType.BOOLEAN, false); + public static final SQLField deleted = new SQLField<>("deleted", SQLType.BOOLEAN, false, (Boolean) false); + public static final SQLField serverSync = new SQLField<>("serverSync", SQLType.BOOLEAN, false); public UUID getViewerId() { @@ -53,4 +66,79 @@ public class SQLMPMessage extends SQLElement { public void setDestId(UUID id) { set(destId, (id == null) ? null : id.toString()); } + + + + + + + + + + + public static SQLElementList getAllUnsyncMessage() throws ORMException { + return ORM.getAll(SQLMPMessage.class, + new SQLWhereComp(SQLMPMessage.serverSync, SQLComparator.EQ, false), + new SQLOrderBy().addField(SQLMPMessage.time), + null, null); + } + + + + public static SQLElementList getAllUnreadForPlayer(UUID player) throws ORMException { + return getForPlayer(player, true, null, false); + } + + + public static SQLElementList getOneDiscussionForPlayer(UUID player, Object discussion, Integer numberLast, boolean revert) throws ORMException { + if (player == null) return null; + if (discussion != null && !(discussion instanceof String) && !(discussion instanceof UUID)) return null; + if (discussion != null && discussion instanceof String && !PlayerFinder.isValidPlayerName(discussion.toString())) return null; + + + SQLWhereChain where = new SQLWhereChain(SQLBoolOp.AND) + .add(new SQLWhereComp(SQLMPMessage.viewerId, SQLComparator.EQ, player.toString())); + if (discussion == null) // message de système + where.add(new SQLWhereNull(SQLMPMessage.sourceId, true)) + .add(new SQLWhereNull(SQLMPMessage.destGroup, true)); + else if (discussion instanceof String) { // message de groupe + SQLMPGroup groupEl = ORM.getFirst(SQLMPGroup.class, + new SQLWhereComp(SQLMPGroup.groupName, SQLComparator.EQ, (String)discussion), null); + if (groupEl == null) + return null; + where.add(new SQLWhereComp(SQLMPMessage.destGroup, SQLComparator.EQ, groupEl.getId())); + } + else if (discussion instanceof UUID && discussion.equals(player)) // message à lui même + where.add(new SQLWhereLike(SQLMPMessage.destId, discussion.toString())) + .add(new SQLWhereLike(SQLMPMessage.sourceId, discussion.toString())) + .add(new SQLWhereNull(SQLMPMessage.destGroup, true)); + else // discussion instanceof UUID + where.add(new SQLWhereChain(SQLBoolOp.OR) + .add(new SQLWhereLike(SQLMPMessage.destId, discussion.toString())) + .add(new SQLWhereLike(SQLMPMessage.sourceId, discussion.toString()))) + .add(new SQLWhereNull(SQLMPMessage.destGroup, true)); + + + SQLOrderBy orderBy = new SQLOrderBy().addField(SQLMPMessage.time, revert ? Direction.DESC : Direction.ASC); + + return ORM.getAll(SQLMPMessage.class, where, orderBy, numberLast, null); + } + + + public static SQLElementList getForPlayer(UUID player, boolean onlyUnread, Integer numberLast, boolean revert) throws ORMException { + if (player == null) return null; + + SQLWhereChain where = new SQLWhereChain(SQLBoolOp.AND); + where.add(new SQLWhereComp(SQLMPMessage.viewerId, SQLComparator.EQ, player.toString())); + if (onlyUnread) + where.add(new SQLWhereComp(SQLMPMessage.wasRead, SQLComparator.EQ, false)); + + SQLOrderBy orderBy = new SQLOrderBy().addField(SQLMPMessage.time, revert ? Direction.DESC : Direction.ASC); + + return ORM.getAll(SQLMPMessage.class, where, orderBy, numberLast, null); + } + + + + } diff --git a/src/fr/pandacube/java/util/db2/SQLModoHistory.java b/src/fr/pandacube/java/util/db2/SQLModoHistory.java index a80fb3a..de9e5e5 100644 --- a/src/fr/pandacube/java/util/db2/SQLModoHistory.java +++ b/src/fr/pandacube/java/util/db2/SQLModoHistory.java @@ -3,6 +3,7 @@ package fr.pandacube.java.util.db2; import java.util.UUID; import fr.pandacube.java.util.db2.sql_tools.SQLElement; +import fr.pandacube.java.util.db2.sql_tools.SQLFKField; import fr.pandacube.java.util.db2.sql_tools.SQLField; import fr.pandacube.java.util.db2.sql_tools.SQLType; @@ -16,16 +17,16 @@ public class SQLModoHistory extends SQLElement { protected String tableName() { return "pandacube_modo_history"; } - public static final SQLField modoId = new SQLField<>("modoId", SQLType.CHAR(36), true); - public static final SQLField actionType = new SQLField<>("actionType", SQLType.ENUM(ActionType.class), false); - public static final SQLField time = new SQLField<>("time", SQLType.BIGINT, false); - public static final SQLField playerId = new SQLField<>("playerId", SQLType.CHAR(36), false); - public static final SQLField value = new SQLField<>("value", SQLType.BIGINT, true); - public static final SQLField message = new SQLField<>("message", SQLType.VARCHAR(512), false); + public static final SQLFKField modoId = new SQLFKField<>("modoId", SQLType.CHAR(36), true, SQLPlayer.class, SQLPlayer.playerId); + public static final SQLField actionType = new SQLField<>("actionType", SQLType.ENUM(ActionType.class), false); + public static final SQLField time = new SQLField<>("time", SQLType.BIGINT, false); + public static final SQLFKField playerId = new SQLFKField<>("playerId", SQLType.CHAR(36), false, SQLPlayer.class, SQLPlayer.playerId); + public static final SQLField value = new SQLField<>("value", SQLType.BIGINT, true); + public static final SQLField message = new SQLField<>("message", SQLType.VARCHAR(512), false); + - public UUID getModoId() { String id = (String)get(modoId); return (id == null) ? null : UUID.fromString(id); diff --git a/src/fr/pandacube/java/util/db2/SQLOnlineshopHistory.java b/src/fr/pandacube/java/util/db2/SQLOnlineshopHistory.java index 6b654df..490cbc7 100644 --- a/src/fr/pandacube/java/util/db2/SQLOnlineshopHistory.java +++ b/src/fr/pandacube/java/util/db2/SQLOnlineshopHistory.java @@ -3,6 +3,7 @@ package fr.pandacube.java.util.db2; import java.util.UUID; import fr.pandacube.java.util.db2.sql_tools.SQLElement; +import fr.pandacube.java.util.db2.sql_tools.SQLFKField; import fr.pandacube.java.util.db2.sql_tools.SQLField; import fr.pandacube.java.util.db2.sql_tools.SQLType; @@ -16,16 +17,16 @@ public class SQLOnlineshopHistory extends SQLElement { protected String tableName() { return "pandacube_onlineshop_history"; } - public static final SQLField time = new SQLField<>("time", SQLType.BIGINT, false); - public static final SQLField transactionId = new SQLField<>("transactionId", SQLType.VARCHAR(255), true); - public static final SQLField sourceType = new SQLField<>("sourceType", SQLType.ENUM(SourceType.class), false); - public static final SQLField sourcePlayerId = new SQLField<>("sourcePlayerId", SQLType.CHAR(36), true); - public static final SQLField sourceQuantity = new SQLField<>("sourceQuantity", SQLType.DOUBLE, false); - public static final SQLField sourceName = new SQLField<>("sourceName", SQLType.VARCHAR(64), false); - public static final SQLField destType = new SQLField<>("destType", SQLType.ENUM(DestType.class), false); - public static final SQLField destPlayerId = new SQLField<>("destPlayerId", SQLType.CHAR(36), false); - public static final SQLField destQuantity = new SQLField<>("destQuantity", SQLType.DOUBLE, false); - public static final SQLField destName = new SQLField<>("destName", SQLType.VARCHAR(64), false); + public static final SQLField time = new SQLField<>("time", SQLType.BIGINT, false); + public static final SQLField transactionId = new SQLField<>("transactionId", SQLType.VARCHAR(255), true); + public static final SQLField sourceType = new SQLField<>("sourceType", SQLType.ENUM(SourceType.class), false); + public static final SQLFKField sourcePlayerId = new SQLFKField<>("sourcePlayerId", SQLType.CHAR(36), true, SQLPlayer.class, SQLPlayer.playerId); + public static final SQLField sourceQuantity = new SQLField<>("sourceQuantity", SQLType.DOUBLE, false); + public static final SQLField sourceName = new SQLField<>("sourceName", SQLType.VARCHAR(64), false); + public static final SQLField destType = new SQLField<>("destType", SQLType.ENUM(DestType.class), false); + public static final SQLFKField destPlayerId = new SQLFKField<>("destPlayerId", SQLType.CHAR(36), false, SQLPlayer.class, SQLPlayer.playerId); + public static final SQLField destQuantity = new SQLField<>("destQuantity", SQLType.DOUBLE, false); + public static final SQLField destName = new SQLField<>("destName", SQLType.VARCHAR(64), false); diff --git a/src/fr/pandacube/java/util/db2/SQLPlayer.java b/src/fr/pandacube/java/util/db2/SQLPlayer.java index a626fc8..c2d8bc9 100644 --- a/src/fr/pandacube/java/util/db2/SQLPlayer.java +++ b/src/fr/pandacube/java/util/db2/SQLPlayer.java @@ -3,9 +3,12 @@ package fr.pandacube.java.util.db2; import java.sql.Date; import java.util.UUID; +import fr.pandacube.java.util.db2.sql_tools.ORM; import fr.pandacube.java.util.db2.sql_tools.SQLElement; import fr.pandacube.java.util.db2.sql_tools.SQLField; import fr.pandacube.java.util.db2.sql_tools.SQLType; +import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp; +import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp.SQLComparator; public class SQLPlayer extends SQLElement { @@ -29,10 +32,10 @@ public class SQLPlayer extends SQLElement { public static final SQLField password = new SQLField<>("password", SQLType.VARCHAR(255), true); public static final SQLField mail = new SQLField<>("mail", SQLType.VARCHAR(255), true); public static final SQLField playerDisplayName = new SQLField<>("playerDisplayName", SQLType.VARCHAR(255), false); - public static final SQLField firstTimeInGame = new SQLField<>("firstTimeInGame", SQLType.BIGINT, false); + public static final SQLField firstTimeInGame = new SQLField<>("firstTimeInGame", SQLType.BIGINT, false, 0L); public static final SQLField timeWebRegister = new SQLField<>("timeWebRegister", SQLType.BIGINT, true); public static final SQLField lastTimeInGame = new SQLField<>("lastTimeInGame", SQLType.BIGINT, true); - public static final SQLField lastWebActivity = new SQLField<>("lastWebActivity", SQLType.BIGINT, false); + public static final SQLField lastWebActivity = new SQLField<>("lastWebActivity", SQLType.BIGINT, false, 0L); public static final SQLField onlineInServer = new SQLField<>("onlineInServer", SQLType.VARCHAR(32), true); public static final SQLField skinURL = new SQLField<>("skinURL", SQLType.VARCHAR(255), true); public static final SQLField isVanish = new SQLField<>("isVanish", SQLType.BOOLEAN, false, (Boolean)false); @@ -78,4 +81,19 @@ public class SQLPlayer extends SQLElement { set(token, (t == null) ? (String)null : t.toString()); } + + + + + + + + + + public static SQLPlayer getPlayerFromUUID(UUID playerId) throws Exception { + return ORM.getFirst(SQLPlayer.class, + new SQLWhereComp(SQLPlayer.playerId, SQLComparator.EQ, playerId.toString()), + null); + } + } diff --git a/src/fr/pandacube/java/util/db2/SQLPlayerIgnore.java b/src/fr/pandacube/java/util/db2/SQLPlayerIgnore.java index e617f2a..b850667 100644 --- a/src/fr/pandacube/java/util/db2/SQLPlayerIgnore.java +++ b/src/fr/pandacube/java/util/db2/SQLPlayerIgnore.java @@ -1,10 +1,18 @@ package fr.pandacube.java.util.db2; +import java.util.ArrayList; +import java.util.List; import java.util.UUID; +import fr.pandacube.java.util.db2.sql_tools.ORM; import fr.pandacube.java.util.db2.sql_tools.SQLElement; -import fr.pandacube.java.util.db2.sql_tools.SQLField; +import fr.pandacube.java.util.db2.sql_tools.SQLFKField; +import fr.pandacube.java.util.db2.sql_tools.SQLOrderBy; import fr.pandacube.java.util.db2.sql_tools.SQLType; +import fr.pandacube.java.util.db2.sql_tools.SQLWhereChain; +import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp; +import fr.pandacube.java.util.db2.sql_tools.SQLWhereChain.SQLBoolOp; +import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp.SQLComparator; public class SQLPlayerIgnore extends SQLElement { @@ -16,8 +24,8 @@ public class SQLPlayerIgnore extends SQLElement { protected String tableName() { return "pandacube_player_ignore"; } - public static final SQLField ignorer = new SQLField<>("ignorer", SQLType.CHAR(36), false); - public static final SQLField ignored = new SQLField<>("ignored", SQLType.CHAR(36), false); + public static final SQLFKField ignorer = new SQLFKField<>("ignorer", SQLType.CHAR(36), false, SQLPlayer.class, SQLPlayer.playerId); + public static final SQLFKField ignored = new SQLFKField<>("ignored", SQLType.CHAR(36), false, SQLPlayer.class, SQLPlayer.playerId); @@ -45,4 +53,46 @@ public class SQLPlayerIgnore extends SQLElement { + + public static SQLPlayerIgnore getPlayerIgnoringPlayer(UUID ignorer, UUID ignored) throws Exception { + return ORM.getFirst(SQLPlayerIgnore.class, + new SQLWhereChain(SQLBoolOp.AND) + .add(new SQLWhereComp(SQLPlayerIgnore.ignorer, SQLComparator.EQ, ignorer.toString())) + .add(new SQLWhereComp(SQLPlayerIgnore.ignored, SQLComparator.EQ, ignored.toString())), + null); + } + public static boolean isPlayerIgnoringPlayer(UUID ignorer, UUID ignored) throws Exception { + return getPlayerIgnoringPlayer(ignorer, ignored) != null; + } + + public static void setPlayerIgnorePlayer(UUID ignorer, UUID ignored, boolean newIgnoreState) throws Exception { + SQLPlayerIgnore el = getPlayerIgnoringPlayer(ignorer, ignored); + if (el == null && newIgnoreState) { + el = new SQLPlayerIgnore(); + el.setIgnorerId(ignorer); + el.setIgnoredId(ignored); + el.save(); + return; + } + if (el != null && !newIgnoreState) { + el.delete(); + return; + } + + } + + + + public static List getListIgnoredPlayer(UUID ignorer) throws Exception { + List els = ORM.getAll(SQLPlayerIgnore.class, + new SQLWhereComp(SQLPlayerIgnore.ignorer, SQLComparator.EQ, ignorer.toString()), + new SQLOrderBy().addField(ORM.getSQLIdField(SQLPlayerIgnore.class)), null, null); + List ret = new ArrayList<>(els.size()); + for (SQLPlayerIgnore el : els) { + ret.add(el.getIgnoredId()); + } + return ret; + } + + } diff --git a/src/fr/pandacube/java/util/db2/SQLStaffTicket.java b/src/fr/pandacube/java/util/db2/SQLStaffTicket.java index 2c70686..40e6a09 100644 --- a/src/fr/pandacube/java/util/db2/SQLStaffTicket.java +++ b/src/fr/pandacube/java/util/db2/SQLStaffTicket.java @@ -3,6 +3,7 @@ package fr.pandacube.java.util.db2; import java.util.UUID; import fr.pandacube.java.util.db2.sql_tools.SQLElement; +import fr.pandacube.java.util.db2.sql_tools.SQLFKField; import fr.pandacube.java.util.db2.sql_tools.SQLField; import fr.pandacube.java.util.db2.sql_tools.SQLType; @@ -16,13 +17,12 @@ public class SQLStaffTicket extends SQLElement { protected String tableName() { return "pandacube_staff_ticket"; } - public static final SQLField playerId = new SQLField<>("playerId", SQLType.CHAR(36), false); + public static final SQLFKField playerId = new SQLFKField<>("playerId", SQLType.CHAR(36), false, SQLPlayer.class, SQLPlayer.playerId); public static final SQLField message = new SQLField<>("message", SQLType.VARCHAR(1024), false); public static final SQLField creationTime = new SQLField<>("creationTime", SQLType.BIGINT, false); - public static final SQLField staffPlayerId = new SQLField<>("staffPlayerId", SQLType.CHAR(36), true); + public static final SQLFKField staffPlayerId = new SQLFKField<>("staffPlayerId", SQLType.CHAR(36), true, SQLPlayer.class, SQLPlayer.playerId); - public UUID getPlayerId() { String id = get(playerId); diff --git a/src/fr/pandacube/java/util/db2/SQLUUIDPlayer.java b/src/fr/pandacube/java/util/db2/SQLUUIDPlayer.java new file mode 100644 index 0000000..40e5526 --- /dev/null +++ b/src/fr/pandacube/java/util/db2/SQLUUIDPlayer.java @@ -0,0 +1,36 @@ +package fr.pandacube.java.util.db2; + +import java.util.UUID; + +import fr.pandacube.java.util.db2.sql_tools.SQLElement; +import fr.pandacube.java.util.db2.sql_tools.SQLFKField; +import fr.pandacube.java.util.db2.sql_tools.SQLField; +import fr.pandacube.java.util.db2.sql_tools.SQLType; + +public class SQLUUIDPlayer extends SQLElement { + + public SQLUUIDPlayer() { super(); } + public SQLUUIDPlayer(int id) { super(id); } + + @Override + protected String tableName() { return "bungeeperms_uuidplayer"; } + + + + public static final SQLFKField uuid = new SQLFKField<>("uuid", SQLType.CHAR(36), false, SQLPlayer.class, SQLPlayer.playerId); + public static final SQLField player = new SQLField<>("player", SQLType.VARCHAR(16), false); + + + + + public UUID getUUID() { + String id = get(uuid); + return (id == null) ? null : UUID.fromString(id); + } + + + public void setUUID(UUID id) { + set(uuid, (id == null) ? null : id.toString()); + } + +} diff --git a/src/fr/pandacube/java/util/db2/sql_tools/DBConnection.java b/src/fr/pandacube/java/util/db2/sql_tools/DBConnection.java index 74dc428..bab12d9 100644 --- a/src/fr/pandacube/java/util/db2/sql_tools/DBConnection.java +++ b/src/fr/pandacube/java/util/db2/sql_tools/DBConnection.java @@ -16,9 +16,7 @@ public class DBConnection { url = "jdbc:mysql://"+host+":"+port+"/"+dbname; login = l; pass = p; - conn = DriverManager.getConnection(url, login, pass); - - + connect(); } @@ -31,8 +29,8 @@ public class DBConnection { } catch(SQLException e) { - close(); - conn = DriverManager.getConnection(url, login, pass); + try { close(); } catch(Exception ex) { } + connect(); } } @@ -44,6 +42,11 @@ public class DBConnection { } + private void connect() throws SQLException { + conn = DriverManager.getConnection(url, login, pass); + } + + public void close() { try { conn.close(); diff --git a/src/fr/pandacube/java/util/db2/sql_tools/ORM.java b/src/fr/pandacube/java/util/db2/sql_tools/ORM.java index a0971fb..7bd48e6 100644 --- a/src/fr/pandacube/java/util/db2/sql_tools/ORM.java +++ b/src/fr/pandacube/java/util/db2/sql_tools/ORM.java @@ -1,6 +1,5 @@ package fr.pandacube.java.util.db2.sql_tools; -import java.lang.reflect.InvocationTargetException; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -9,8 +8,24 @@ import java.util.Collection; import java.util.List; import java.util.logging.Level; -import fr.pandacube.java.PandacubeUtil; +import fr.pandacube.java.util.Log; +import fr.pandacube.java.util.db2.SQLContact; +import fr.pandacube.java.util.db2.SQLForumCategorie; +import fr.pandacube.java.util.db2.SQLForumForum; +import fr.pandacube.java.util.db2.SQLForumPost; +import fr.pandacube.java.util.db2.SQLForumThread; +import fr.pandacube.java.util.db2.SQLLoginHistory; +import fr.pandacube.java.util.db2.SQLMPGroup; +import fr.pandacube.java.util.db2.SQLMPGroupUser; +import fr.pandacube.java.util.db2.SQLMPMessage; +import fr.pandacube.java.util.db2.SQLModoHistory; +import fr.pandacube.java.util.db2.SQLOnlineshopHistory; import fr.pandacube.java.util.db2.SQLPlayer; +import fr.pandacube.java.util.db2.SQLPlayerIgnore; +import fr.pandacube.java.util.db2.SQLShopStock; +import fr.pandacube.java.util.db2.SQLStaffTicket; +import fr.pandacube.java.util.db2.SQLStaticPages; +import fr.pandacube.java.util.db2.SQLUUIDPlayer; import fr.pandacube.java.util.db2.sql_tools.SQLWhereChain.SQLBoolOp; import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp.SQLComparator; import javafx.util.Pair; @@ -41,14 +56,35 @@ public final class ORM { * utile des les initialiser ici, car on peut tout de suite déceler les bugs ou erreurs dans la déclaration des SQLFields */ - initTable(SQLPlayer.class); + try { + initTable(SQLContact.class); + initTable(SQLForumCategorie.class); + initTable(SQLForumForum.class); + initTable(SQLForumPost.class); + initTable(SQLForumThread.class); + initTable(SQLLoginHistory.class); + initTable(SQLModoHistory.class); + initTable(SQLMPGroup.class); + initTable(SQLMPGroupUser.class); + initTable(SQLMPMessage.class); + initTable(SQLOnlineshopHistory.class); + initTable(SQLPlayer.class); + initTable(SQLPlayerIgnore.class); + initTable(SQLShopStock.class); + initTable(SQLStaffTicket.class); + initTable(SQLStaticPages.class); + initTable(SQLUUIDPlayer.class); + } catch (ORMInitTableException e) { + Log.getLogger().log(Level.SEVERE, "Erreur d'initialisation d'une table dans l'ORM", e); + } + } - /* package */ static void initTable(Class elemClass) { + /* package */ static void initTable(Class elemClass) throws ORMInitTableException { if (tables.contains(elemClass)) return; try { @@ -58,7 +94,7 @@ public final class ORM { createTable(instance); tables.add(elemClass); } catch (Exception e) { - PandacubeUtil.getMasterLogger().log(Level.SEVERE, "Can't init table " + elemClass.getName(), e); + throw new ORMInitTableException(elemClass, e); } } @@ -123,16 +159,17 @@ public final class ORM { @SuppressWarnings("unchecked") - public static SQLField getSQLIdField(Class elemClass) { + public static SQLField getSQLIdField(Class elemClass) throws ORMInitTableException { + initTable(elemClass); return (SQLField) SQLElement.fieldsCache.get(elemClass).get("id"); } - public static List getByIds(Class elemClass, Collection ids) throws Exception { + public static List getByIds(Class elemClass, Collection ids) throws ORMException { return getByIds(elemClass, ids.toArray(new Integer[ids.size()])); } - public static List getByIds(Class elemClass, Integer... ids) throws Exception { + public static List getByIds(Class elemClass, Integer... ids) throws ORMException { SQLField idField = getSQLIdField(elemClass); SQLWhereChain where = new SQLWhereChain(SQLBoolOp.OR); for (Integer id : ids) @@ -141,65 +178,72 @@ public final class ORM { return getAll(elemClass, where, new SQLOrderBy().addField(idField), 1, null); } - public static T getById(Class elemClass, int id) throws Exception { + public static T getById(Class elemClass, int id) throws ORMException { return getFirst(elemClass, new SQLWhereComp(getSQLIdField(elemClass), SQLComparator.EQ, id), null); } - public static T getFirst(Class elemClass, SQLWhere where, SQLOrderBy orderBy) throws Exception { + public static T getFirst(Class elemClass, SQLWhere where, SQLOrderBy orderBy) throws ORMException { SQLElementList elts = getAll(elemClass, where, orderBy, 1, null); return (elts.size() == 0)? null : elts.get(0); } - public static SQLElementList getAll(Class elemClass) throws Exception { + public static SQLElementList getAll(Class elemClass) throws ORMException { return getAll(elemClass, null, null, null, null); } - public static SQLElementList getAll(Class elemClass, SQLWhere where, SQLOrderBy orderBy, Integer limit, Integer offset) throws Exception { + public static SQLElementList getAll(Class elemClass, SQLWhere where, SQLOrderBy orderBy, Integer limit, Integer offset) throws ORMException { initTable(elemClass); - String sql = "SELECT * FROM "+elemClass.newInstance().tableName(); - List params = new ArrayList<>(); - - if (where != null) { - Pair> ret = where.toSQL(); - sql += " WHERE "+ret.getKey(); - params.addAll(ret.getValue()); - } - if (orderBy != null) - sql += " ORDER BY "+orderBy.toSQL(); - if (limit != null) - sql += " LIMIT "+limit; - if (offset != null) - sql += " OFFSET "+offset; - sql += ";"; - - SQLElementList elmts = new SQLElementList(); - - PreparedStatement ps = connection.getNativeConnection().prepareStatement(sql); try { + String sql = "SELECT * FROM "+elemClass.newInstance().tableName(); - int i = 1; - for (Object val : params) { - ps.setObject(i++, val); + List params = new ArrayList<>(); + + if (where != null) { + Pair> ret = where.toSQL(); + sql += " WHERE "+ret.getKey(); + params.addAll(ret.getValue()); } + if (orderBy != null) + sql += " ORDER BY "+orderBy.toSQL(); + if (limit != null) + sql += " LIMIT "+limit; + if (offset != null) + sql += " OFFSET "+offset; + sql += ";"; - System.out.println(ps.toString()); + SQLElementList elmts = new SQLElementList(); - ResultSet set = ps.executeQuery(); + PreparedStatement ps = connection.getNativeConnection().prepareStatement(sql); try { - while (set.next()) - elmts.add(getElementInstance(set, elemClass)); + + int i = 1; + for (Object val : params) { + ps.setObject(i++, val); + } + + System.out.println(ps.toString()); + + ResultSet set = ps.executeQuery(); + + try { + while (set.next()) + elmts.add(getElementInstance(set, elemClass)); + } finally { + set.close(); + } } finally { - set.close(); + ps.close(); } - } finally { - ps.close(); + + return elmts; + } catch (ReflectiveOperationException | SQLException e) { + throw new ORMException(e); } - return elmts; } @@ -215,7 +259,7 @@ public final class ORM { - private static T getElementInstance(ResultSet set, Class elemClass) throws Exception { + private static T getElementInstance(ResultSet set, Class elemClass) throws ReflectiveOperationException, SQLException { try { T instance = elemClass.getConstructor(int.class).newInstance(set.getInt("id")); @@ -231,11 +275,8 @@ public final class ORM { } return instance; - } catch (InstantiationException | IllegalAccessException | IllegalArgumentException - | InvocationTargetException | NoSuchMethodException | SecurityException e) { - throw new Exception("Can't instanciate " + elemClass.getName(), e); - } catch (SQLException e) { - throw new Exception("Error reading ResultSet for creating instance of " + elemClass.getName(), e); + } catch (ReflectiveOperationException | IllegalArgumentException | SecurityException e) { + throw new ReflectiveOperationException("Can't instanciate " + elemClass.getName(), e); } } diff --git a/src/fr/pandacube/java/util/db2/sql_tools/ORMException.java b/src/fr/pandacube/java/util/db2/sql_tools/ORMException.java new file mode 100644 index 0000000..2bed4a7 --- /dev/null +++ b/src/fr/pandacube/java/util/db2/sql_tools/ORMException.java @@ -0,0 +1,18 @@ +package fr.pandacube.java.util.db2.sql_tools; + +public class ORMException extends Exception { + private static final long serialVersionUID = 1L; + + public ORMException(Throwable initCause) { + super(initCause); + } + + public ORMException(String message, Throwable initCause) { + super(message, initCause); + } + + public ORMException(String message) { + super(message); + } + +} diff --git a/src/fr/pandacube/java/util/db2/sql_tools/ORMInitTableException.java b/src/fr/pandacube/java/util/db2/sql_tools/ORMInitTableException.java new file mode 100644 index 0000000..caac847 --- /dev/null +++ b/src/fr/pandacube/java/util/db2/sql_tools/ORMInitTableException.java @@ -0,0 +1,18 @@ +package fr.pandacube.java.util.db2.sql_tools; + +public class ORMInitTableException extends ORMException { + private static final long serialVersionUID = 1L; + + + + /* package */ ORMInitTableException(Class tableElem) { + super("Error while initializing table "+tableElem.getName()); + } + + /* package */ ORMInitTableException(Class tableElem, Throwable t) { + super("Error while initializing table "+tableElem.getName(), t); + } + + + +} diff --git a/src/fr/pandacube/java/util/db2/sql_tools/SQLElement.java b/src/fr/pandacube/java/util/db2/sql_tools/SQLElement.java index a3d6870..3f8b8dc 100644 --- a/src/fr/pandacube/java/util/db2/sql_tools/SQLElement.java +++ b/src/fr/pandacube/java/util/db2/sql_tools/SQLElement.java @@ -16,7 +16,10 @@ import java.util.Objects; import java.util.Set; import java.util.logging.Level; -import fr.pandacube.java.PandacubeUtil; +import org.apache.commons.lang.builder.ToStringBuilder; + +import fr.pandacube.java.util.Log; +import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp.SQLComparator; public abstract class SQLElement { /** cache for fields for each subclass of SQLElement */ @@ -109,7 +112,7 @@ public abstract class SQLElement { listToFill.addField((SQLField)val); } catch (IllegalArgumentException | IllegalAccessException e) { - PandacubeUtil.getMasterLogger().log(Level.SEVERE, "Can't get value of static field "+field.toString(), e); + Log.getLogger().log(Level.SEVERE, "Can't get value of static field "+field.toString(), e); } } @@ -193,6 +196,14 @@ public abstract class SQLElement { } + public E getForeign(SQLFKField field) throws ORMException { + T fkValue = get(field); + if (fkValue == null) return null; + return ORM.getFirst(field.getForeignElementClass(), + new SQLWhereComp(field.getForeignField(), SQLComparator.EQ, fkValue), null); + } + + public boolean isValidForSave() { return values.keySet().containsAll(fields.keySet()); @@ -217,105 +228,109 @@ public abstract class SQLElement { - public void save() throws SQLException { + public void save() throws ORMException { if (!isValidForSave()) throw new IllegalStateException("this instance of " + getClass().getName() + " has at least one undefined value and can't be saved."); ORM.initTable(getClass()); - Connection conn = db.getNativeConnection(); - - - if (stored) - { // mettre à jour les valeurs dans la base + try { - // restaurer l'ID au cas il aurait été changé à la main dans values - @SuppressWarnings("unchecked") - SQLField idField = (SQLField) fields.get("id"); - values.put(idField, id); - modifiedSinceLastSave.remove("id"); - Map, Object> modifiedValues = getOnlyModifiedValues(); + Connection conn = db.getNativeConnection(); + - - - String sql = ""; - List psValues = new ArrayList<>(); - - for(Map.Entry, Object> entry : modifiedValues.entrySet()) { - sql += entry.getKey() + " = ? ,"; - psValues.add(entry.getValue()); - } - - if (sql.length() > 0) - sql = sql.substring(0, sql.length()-1); - - PreparedStatement ps = conn.prepareStatement("UPDATE "+tableName+" SET "+sql+" WHERE id="+id); - - try { - - int i = 1; - for (Object val : psValues) { - ps.setObject(i++, val); + if (stored) + { // mettre à jour les valeurs dans la base + + // restaurer l'ID au cas il aurait été changé à la main dans values + @SuppressWarnings("unchecked") + SQLField idField = (SQLField) fields.get("id"); + values.put(idField, id); + modifiedSinceLastSave.remove("id"); + Map, Object> modifiedValues = getOnlyModifiedValues(); + + + + String sql = ""; + List psValues = new ArrayList<>(); + + for(Map.Entry, Object> entry : modifiedValues.entrySet()) { + sql += entry.getKey() + " = ? ,"; + psValues.add(entry.getValue()); } - ps.executeUpdate(); - } finally { - ps.close(); - } - } - else - { // ajouter dans la base - - // restaurer l'ID au cas il aurait été changé à la main dans values - values.put(fields.get("id"), null); - - - String concat_vals = ""; - String concat_fields = ""; - List psValues = new ArrayList<>(); - - boolean first = true; - for(Map.Entry, Object> entry : values.entrySet()) { - if (!first) { - concat_vals += ","; - concat_fields += ","; - } - first = false; - concat_vals += " ? "; - concat_fields += entry.getKey(); - psValues.add(entry.getValue()); - } - - - PreparedStatement ps = conn.prepareStatement("INSERT INTO "+tableName+" ("+concat_fields+") VALUES ("+concat_vals+")", Statement.RETURN_GENERATED_KEYS); - try { - - int i = 1; - for (Object val : psValues) { - ps.setObject(i++, val); - } + if (sql.length() > 0) + sql = sql.substring(0, sql.length()-1); - ps.executeUpdate(); + PreparedStatement ps = conn.prepareStatement("UPDATE "+tableName+" SET "+sql+" WHERE id="+id); - ResultSet rs = ps.getGeneratedKeys(); try { - if(rs.next()) - { - id = rs.getInt(1); - } - - stored = true; + + int i = 1; + for (Object val : psValues) { + ps.setObject(i++, val); + } + + ps.executeUpdate(); } finally { - rs.close(); + ps.close(); } - } finally { - ps.close(); + } + else + { // ajouter dans la base + + // restaurer l'ID au cas il aurait été changé à la main dans values + values.put(fields.get("id"), null); + + + String concat_vals = ""; + String concat_fields = ""; + List psValues = new ArrayList<>(); + + boolean first = true; + for(Map.Entry, Object> entry : values.entrySet()) { + if (!first) { + concat_vals += ","; + concat_fields += ","; + } + first = false; + concat_vals += " ? "; + concat_fields += entry.getKey(); + psValues.add(entry.getValue()); + } + + + PreparedStatement ps = conn.prepareStatement("INSERT INTO "+tableName+" ("+concat_fields+") VALUES ("+concat_vals+")", Statement.RETURN_GENERATED_KEYS); + try { + + int i = 1; + for (Object val : psValues) { + ps.setObject(i++, val); + } + + ps.executeUpdate(); + + ResultSet rs = ps.getGeneratedKeys(); + try { + if(rs.next()) + { + id = rs.getInt(1); + } + + stored = true; + } finally { + rs.close(); + } + } finally { + ps.close(); + } + } + modifiedSinceLastSave.clear(); + } catch(SQLException e) { + throw new ORMException("Error while saving data in table "+tableName(), e); } - - modifiedSinceLastSave.clear(); - } @@ -334,7 +349,7 @@ public abstract class SQLElement { - public void delete() { + public void delete() throws ORMException { try { if (stored) @@ -348,7 +363,7 @@ public abstract class SQLElement { } } } catch (SQLException e) { - e.printStackTrace(); + throw new ORMException(e); } } @@ -388,5 +403,24 @@ public abstract class SQLElement { + @Override + public String toString() { + ToStringBuilder b = new ToStringBuilder(this); + + for (SQLField f : fields.values()) { + try { + b.append(f.name, get(f)); + } catch(IllegalArgumentException e) { + b.append(f.name, "(Must be defined before saving)"); + } + + } + + return b.toString(); + } + + + + } diff --git a/src/fr/pandacube/java/util/db2/sql_tools/SQLFKField.java b/src/fr/pandacube/java/util/db2/sql_tools/SQLFKField.java new file mode 100644 index 0000000..bbc3c2b --- /dev/null +++ b/src/fr/pandacube/java/util/db2/sql_tools/SQLFKField.java @@ -0,0 +1,63 @@ +package fr.pandacube.java.util.db2.sql_tools; + +import fr.pandacube.java.util.Log; + +public class SQLFKField extends SQLField { + + private SQLField sqlForeignKeyField; + private Class sqlForeignKeyElement; + + + + public SQLFKField(String n, SQLType t, boolean nul, Class fkEl, SQLField fkF) { + super(n, t, nul); + construct(fkEl, fkF); + } + + public SQLFKField(String n, SQLType t, boolean nul, T deflt, Class fkEl, SQLField fkF) { + super(n, t, nul, deflt); + construct(fkEl, fkF); + } + + public static SQLFKField idFK(String n, SQLType t, boolean nul, Class fkEl) { + if (fkEl == null) throw new IllegalArgumentException("foreignKeyElement can't be null"); + try { + return new SQLFKField<>(n, t, nul, fkEl, ORM.getSQLIdField(fkEl)); + } catch (ORMInitTableException e) { + Log.severe("Can't create Foreign key Field called '"+n+"'", e); + return null; + } + } + + public static SQLFKField idFKField(String n, SQLType t, boolean nul, Integer deflt, Class fkEl) { + if (fkEl == null) throw new IllegalArgumentException("foreignKeyElement can't be null"); + try { + return new SQLFKField<>(n, t, nul, deflt, fkEl, ORM.getSQLIdField(fkEl)); + } catch (ORMInitTableException e) { + Log.severe("Can't create Foreign key Field called '"+n+"'", e); + return null; + } + } + + private void construct(Class fkEl, SQLField fkF) { + if (fkEl == null) throw new IllegalArgumentException("foreignKeyElement can't be null"); + if (fkF == null) throw new IllegalArgumentException("foreignKeyField can't be null"); + try { + ORM.initTable(fkEl); + } catch (ORMInitTableException e) { + Log.severe(e); + return; + } + if (!fkEl.equals(fkF.getSQLElementType())) + throw new IllegalArgumentException("foreignKeyField must be from supplied foreignKeyElement"); + if (!type.equals(fkF.type)) + throw new IllegalArgumentException("foreignKeyField and current Field must have the same SQLType"); + sqlForeignKeyField = fkF; + sqlForeignKeyElement = fkEl; + } + + + public SQLField getForeignField() { return sqlForeignKeyField; } + public Class getForeignElementClass() { return sqlForeignKeyElement; } + +} diff --git a/src/fr/pandacube/java/util/db2/sql_tools/SQLOrderBy.java b/src/fr/pandacube/java/util/db2/sql_tools/SQLOrderBy.java index 39675ca..0986ab0 100644 --- a/src/fr/pandacube/java/util/db2/sql_tools/SQLOrderBy.java +++ b/src/fr/pandacube/java/util/db2/sql_tools/SQLOrderBy.java @@ -7,13 +7,28 @@ public class SQLOrderBy { private List orderByFields = new ArrayList<>(); + /** + * Construit une nouvelle clause ORDER BY + */ public SQLOrderBy() {} - public SQLOrderBy addField(SQLField field,Direction d) { + /** + * Ajoute un champ dans la clause ORDER BY en construction + * @param field le champ SQL à ordonner + * @param d le sens de tri (croissant ASC ou décroissant DESC) + * @return l'objet courant (permet de chainer les ajouts de champs) + */ + public SQLOrderBy addField(SQLField field, Direction d) { orderByFields.add(new OBField(field, d)); return this; } + /** + * Ajoute un champ dans la clause ORDER BY en construction, + * avec comme ordre de tri croissant ASC par défaut + * @param field le champ SQL à ordonner dans l'ordre croissant ASC + * @return l'objet courant (permet de chainer les ajouts de champs) + */ public SQLOrderBy addField(SQLField field) { return addField(field, Direction.ASC); } @@ -48,7 +63,7 @@ public class SQLOrderBy { } - private enum Direction { + public enum Direction { ASC, DESC; } } diff --git a/src/fr/pandacube/java/util/db2/sql_tools/SQLType.java b/src/fr/pandacube/java/util/db2/sql_tools/SQLType.java index 32eadae..a084b40 100644 --- a/src/fr/pandacube/java/util/db2/sql_tools/SQLType.java +++ b/src/fr/pandacube/java/util/db2/sql_tools/SQLType.java @@ -25,6 +25,18 @@ public class SQLType { return false; } + @Override + public int hashCode() { + return toString().hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof SQLType)) + return false; + return toString().equals(((SQLType)obj).toString()); + } + diff --git a/src/fr/pandacube/java/util/db2/sql_tools/SQLWhereChain.java b/src/fr/pandacube/java/util/db2/sql_tools/SQLWhereChain.java index 314c940..98200d9 100644 --- a/src/fr/pandacube/java/util/db2/sql_tools/SQLWhereChain.java +++ b/src/fr/pandacube/java/util/db2/sql_tools/SQLWhereChain.java @@ -44,7 +44,7 @@ public class SQLWhereChain extends SQLWhere { } - enum SQLBoolOp { + public enum SQLBoolOp { /** Equivalent to SQL "AND" */ AND("AND"), /** Equivalent to SQL "OR" */ diff --git a/src/fr/pandacube/java/util/db2/sql_tools/SQLWhereComp.java b/src/fr/pandacube/java/util/db2/sql_tools/SQLWhereComp.java index 61f2b17..ba06d9b 100644 --- a/src/fr/pandacube/java/util/db2/sql_tools/SQLWhereComp.java +++ b/src/fr/pandacube/java/util/db2/sql_tools/SQLWhereComp.java @@ -36,7 +36,7 @@ public class SQLWhereComp extends SQLWhere { } - enum SQLComparator { + public enum SQLComparator { /** Equivalent to SQL "=" */ EQ("="), /** Equivalent to SQL ">" */ diff --git a/src/fr/pandacube/java/util/db2/sql_tools/SQLWhereLike.java b/src/fr/pandacube/java/util/db2/sql_tools/SQLWhereLike.java index 4968442..edad30b 100644 --- a/src/fr/pandacube/java/util/db2/sql_tools/SQLWhereLike.java +++ b/src/fr/pandacube/java/util/db2/sql_tools/SQLWhereLike.java @@ -13,9 +13,8 @@ public class SQLWhereLike extends SQLWhere { /** * Compare a field with a value - * @param l the field at left of the comparison operator. Can't be null - * @param c the comparison operator, can't be null - * @param r the value at right of the comparison operator. Can't be null + * @param f the field at left of the LIKE keyword. Can't be null + * @param like the like expression. */ public SQLWhereLike(SQLField f, String like) { if (f == null || like == null) diff --git a/src/fr/pandacube/java/util/db2/sql_tools/SQLWhereNull.java b/src/fr/pandacube/java/util/db2/sql_tools/SQLWhereNull.java index 8116120..15781a5 100644 --- a/src/fr/pandacube/java/util/db2/sql_tools/SQLWhereNull.java +++ b/src/fr/pandacube/java/util/db2/sql_tools/SQLWhereNull.java @@ -4,7 +4,7 @@ import java.util.ArrayList; import java.util.List; import java.util.logging.Level; -import fr.pandacube.java.PandacubeUtil; +import fr.pandacube.java.util.Log; import javafx.util.Pair; public class SQLWhereNull extends SQLWhere { @@ -21,7 +21,7 @@ public class SQLWhereNull extends SQLWhere { if (field == null) throw new IllegalArgumentException("field can't be null"); if (!field.canBeNull) - PandacubeUtil.getMasterLogger().log(Level.WARNING, "Useless : Trying to check IS [NOT] NULL on the field "+field.getSQLElementType().getName()+"#"+field.name+" which is declared in the ORM as 'can't be null'"); + Log.getLogger().log(Level.WARNING, "Useless : Trying to check IS [NOT] NULL on the field "+field.getSQLElementType().getName()+"#"+field.name+" which is declared in the ORM as 'can't be null'"); fild = field; nulll = isNull; } diff --git a/src/fr/pandacube/java/util/network/client/TCPClient.java b/src/fr/pandacube/java/util/network/client/TCPClient.java index 3f8d2cf..e3afee2 100644 --- a/src/fr/pandacube/java/util/network/client/TCPClient.java +++ b/src/fr/pandacube/java/util/network/client/TCPClient.java @@ -12,7 +12,8 @@ import java.nio.ByteBuffer; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; -import fr.pandacube.java.PandacubeUtil; +import fr.pandacube.java.Pandacube; +import fr.pandacube.java.util.Log; import fr.pandacube.java.util.network.packet.Packet; import fr.pandacube.java.util.network.packet.PacketClient; import fr.pandacube.java.util.network.packet.PacketException; @@ -37,9 +38,9 @@ public class TCPClient extends Thread implements Closeable { if (a == null || l == null) throw new IllegalArgumentException("les arguments ne peuvent pas être null"); socket = new Socket(); - socket.setReceiveBufferSize(PandacubeUtil.NETWORK_TCP_BUFFER_SIZE); - socket.setSendBufferSize(PandacubeUtil.NETWORK_TCP_BUFFER_SIZE); - socket.setSoTimeout(PandacubeUtil.NETWORK_TIMEOUT); + socket.setReceiveBufferSize(Pandacube.NETWORK_TCP_BUFFER_SIZE); + socket.setSendBufferSize(Pandacube.NETWORK_TCP_BUFFER_SIZE); + socket.setSoTimeout(Pandacube.NETWORK_TIMEOUT); socket.connect(a); addr = a; listener = l; @@ -79,9 +80,9 @@ public class TCPClient extends Thread implements Closeable { listener.onPacketReceive(this, ps); } catch (PacketException|InvalidServerMessage e) { - PandacubeUtil.getMasterLogger().log(Level.SEVERE, "Message du serveur mal formé", e); + Log.getLogger().log(Level.SEVERE, "Message du serveur mal formé", e); } catch (Exception e) { - PandacubeUtil.getMasterLogger().log(Level.SEVERE, "Erreur lors de la prise en charge du message par le serveur", e); + Log.getLogger().log(Level.SEVERE, "Erreur lors de la prise en charge du message par le serveur", e); } } diff --git a/src/fr/pandacube/java/util/network/packet/Packet.java b/src/fr/pandacube/java/util/network/packet/Packet.java index 643c5d4..e45053a 100644 --- a/src/fr/pandacube/java/util/network/packet/Packet.java +++ b/src/fr/pandacube/java/util/network/packet/Packet.java @@ -6,7 +6,7 @@ import java.util.Arrays; import java.util.HashMap; import java.util.Map; -import fr.pandacube.java.PandacubeUtil; +import fr.pandacube.java.Pandacube; import fr.pandacube.java.util.network.packet.bytebuffer.ByteBuffer; import fr.pandacube.java.util.network.packet.bytebuffer.ByteSerializable; @@ -42,7 +42,7 @@ public abstract class Packet implements ByteSerializable { - public static final Charset CHARSET = PandacubeUtil.NETWORK_CHARSET; + public static final Charset CHARSET = Pandacube.NETWORK_CHARSET; private static Map> packetTypes = new HashMap>(); diff --git a/src/fr/pandacube/java/util/network/server/TCPServer.java b/src/fr/pandacube/java/util/network/server/TCPServer.java index 9c060fc..ac5c4ef 100644 --- a/src/fr/pandacube/java/util/network/server/TCPServer.java +++ b/src/fr/pandacube/java/util/network/server/TCPServer.java @@ -17,7 +17,8 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; -import fr.pandacube.java.PandacubeUtil; +import fr.pandacube.java.Pandacube; +import fr.pandacube.java.util.Log; import fr.pandacube.java.util.network.packet.Packet; import fr.pandacube.java.util.network.packet.PacketClient; import fr.pandacube.java.util.network.packet.PacketServer; @@ -52,7 +53,7 @@ public class TCPServer extends Thread implements Closeable { if (port <= 0 || port > 65535) throw new IllegalArgumentException("le numéro de port est invalide"); socket = new ServerSocket(); - socket.setReceiveBufferSize(PandacubeUtil.NETWORK_TCP_BUFFER_SIZE); + socket.setReceiveBufferSize(Pandacube.NETWORK_TCP_BUFFER_SIZE); socket.setPerformancePreferences(0, 2, 1); socket.bind(new InetSocketAddress(port)); listener = l; @@ -67,8 +68,8 @@ public class TCPServer extends Thread implements Closeable { try { while(true) { Socket socketClient = socket.accept(); - socketClient.setSendBufferSize(PandacubeUtil.NETWORK_TCP_BUFFER_SIZE); - socketClient.setSoTimeout(PandacubeUtil.NETWORK_TIMEOUT); + socketClient.setSendBufferSize(Pandacube.NETWORK_TCP_BUFFER_SIZE); + socketClient.setSoTimeout(Pandacube.NETWORK_TIMEOUT); try { TCPServerClientConnection co = new TCPServerClientConnection(socketClient, connectionCounterId.getAndIncrement()); @@ -76,11 +77,11 @@ public class TCPServer extends Thread implements Closeable { listener.onClientConnect(this, co); co.start(); } catch(IOException e) { - PandacubeUtil.getMasterLogger().log(Level.SEVERE, "Connexion impossible avec "+socketClient.getInetAddress()); + Log.getLogger().log(Level.SEVERE, "Connexion impossible avec "+socketClient.getInetAddress()); } } } catch (Exception e) { - PandacubeUtil.getMasterLogger().log(Level.WARNING, "Plus aucune connexion ne peux être acceptée", e); + Log.getLogger().log(Level.WARNING, "Plus aucune connexion ne peux être acceptée", e); } } @@ -135,9 +136,9 @@ public class TCPServer extends Thread implements Closeable { try { interpreteReceivedMessage(this, packetData); } catch (InvalidClientMessage e) { - PandacubeUtil.getMasterLogger().log(Level.SEVERE, "Erreur protocole de : ", e); + Log.getLogger().log(Level.SEVERE, "Erreur protocole de : ", e); } catch (Exception e) { - PandacubeUtil.getMasterLogger().log(Level.SEVERE, "Erreur lors de la prise en charge du message par le serveur", e); + Log.getLogger().log(Level.SEVERE, "Erreur lors de la prise en charge du message par le serveur", e); e.printStackTrace(); } } @@ -146,7 +147,7 @@ public class TCPServer extends Thread implements Closeable { } catch (Exception e) { - PandacubeUtil.getMasterLogger().log(Level.SEVERE, "Fermeture de la connexion de "+address, e); + Log.getLogger().log(Level.SEVERE, "Fermeture de la connexion de "+address, e); } diff --git a/src/fr/pandacube/java/util/network_api/server/PacketExecutor.java b/src/fr/pandacube/java/util/network_api/server/PacketExecutor.java index ed23588..a1ba315 100644 --- a/src/fr/pandacube/java/util/network_api/server/PacketExecutor.java +++ b/src/fr/pandacube/java/util/network_api/server/PacketExecutor.java @@ -4,7 +4,7 @@ import java.io.IOException; import java.io.PrintStream; import java.net.Socket; -import fr.pandacube.java.PandacubeUtil; +import fr.pandacube.java.util.Log; /** @@ -44,7 +44,7 @@ public class PacketExecutor implements Runnable { rep.sendPacket(new PrintStream(socket.getOutputStream())); } catch (IOException e1) { } if (e instanceof IOException) - PandacubeUtil.getPluginLogger().warning("Impossible de lire le packet reçu sur le socket "+socket+" : "+e.toString()); + Log.getLogger().warning("Impossible de lire le packet reçu sur le socket "+socket+" : "+e.toString()); else e.printStackTrace(); }