From 724e9ecd6cf337f8acc4fd9dd4b71f7a38859c89 Mon Sep 17 00:00:00 2001 From: Marc Baloup Date: Thu, 14 Jul 2016 14:22:23 +0200 Subject: [PATCH] Cleanup/format code + suppression ancien ORM --- .../earth2me/essentials/utils/DateUtil.java | 160 +-- src/fr/pandacube/java/Pandacube.java | 13 +- .../java/external_tools/OfflineUUID.java | 39 +- src/fr/pandacube/java/util/Callback.java | 1 - src/fr/pandacube/java/util/EnumUtil.java | 70 +- .../java/util/JArithmeticInterpreter.java | 1188 ++++++++--------- src/fr/pandacube/java/util/Log.java | 27 +- .../pandacube/java/util/MinecraftVersion.java | 17 +- src/fr/pandacube/java/util/PlayerFinder.java | 204 ++- .../java/util/PlayerNameHistoryLookup.java | 234 ++-- src/fr/pandacube/java/util/RandomUtil.java | 12 +- .../java/util/ServerPropertyFile.java | 131 +- src/fr/pandacube/java/util/StringUtil.java | 18 +- .../java/util/chat_display/Display.java | 110 +- .../java/util/chat_display/DisplayUtil.java | 210 ++- .../util/chat_display/TextProgressBar.java | 61 +- .../java/util/db/LoginHistoryElement.java | 145 -- .../java/util/db/LoginHistoryTable.java | 40 - .../java/util/db/MPGroupElement.java | 63 - .../pandacube/java/util/db/MPGroupTable.java | 26 - .../java/util/db/MPGroupUserElement.java | 71 - .../java/util/db/MPGroupUserTable.java | 42 - .../java/util/db/MPMessageElement.java | 177 --- .../java/util/db/MPMessageTable.java | 99 -- .../java/util/db/ModoHistoryElement.java | 141 -- .../java/util/db/ModoHistoryTable.java | 40 - src/fr/pandacube/java/util/db/ORM.java | 97 -- .../util/db/OnlineShopHistoryElement.java | 129 -- .../java/util/db/OnlineShopHistoryTable.java | 47 - .../pandacube/java/util/db/PlayerElement.java | 179 --- .../java/util/db/PlayerIgnoreElement.java | 66 - .../java/util/db/PlayerIgnoreTable.java | 79 -- .../pandacube/java/util/db/PlayerTable.java | 74 - src/fr/pandacube/java/util/db/SQLElement.java | 162 --- src/fr/pandacube/java/util/db/SQLTable.java | 142 -- .../java/util/db/ShopStockElement.java | 74 - .../java/util/db/ShopStockTable.java | 30 - .../java/util/db/StaffTicketElement.java | 77 -- .../java/util/db/StaffTicketTable.java | 37 - .../pandacube/java/util/db/package-info.java | 2 - .../pandacube/java/util/db2/SQLContact.java | 55 +- .../java/util/db2/SQLForumCategorie.java | 23 +- .../java/util/db2/SQLForumForum.java | 42 +- .../pandacube/java/util/db2/SQLForumPost.java | 40 +- .../java/util/db2/SQLForumThread.java | 51 +- .../java/util/db2/SQLLoginHistory.java | 52 +- .../pandacube/java/util/db2/SQLMPGroup.java | 36 +- .../java/util/db2/SQLMPGroupUser.java | 55 +- .../pandacube/java/util/db2/SQLMPMessage.java | 123 +- .../java/util/db2/SQLModoHistory.java | 59 +- .../java/util/db2/SQLOnlineshopHistory.java | 77 +- src/fr/pandacube/java/util/db2/SQLPlayer.java | 107 +- .../java/util/db2/SQLPlayerIgnore.java | 69 +- .../pandacube/java/util/db2/SQLShopStock.java | 22 +- .../java/util/db2/SQLStaffTicket.java | 35 +- .../java/util/db2/SQLStaticPages.java | 18 +- .../java/util/db2/SQLUUIDPlayer.java | 32 +- .../java/util/db2/sql_tools/DBConnection.java | 44 +- .../java/util/db2/sql_tools/ORM.java | 271 ++-- .../java/util/db2/sql_tools/ORMException.java | 4 +- .../db2/sql_tools/ORMInitTableException.java | 8 +- .../java/util/db2/sql_tools/SQLElement.java | 355 ++--- .../util/db2/sql_tools/SQLElementList.java | 133 +- .../java/util/db2/sql_tools/SQLFKField.java | 32 +- .../java/util/db2/sql_tools/SQLField.java | 44 +- .../java/util/db2/sql_tools/SQLOrderBy.java | 25 +- .../java/util/db2/sql_tools/SQLType.java | 67 +- .../java/util/db2/sql_tools/SQLWhere.java | 11 +- .../util/db2/sql_tools/SQLWhereChain.java | 28 +- .../java/util/db2/sql_tools/SQLWhereComp.java | 41 +- .../java/util/db2/sql_tools/SQLWhereLike.java | 7 +- .../java/util/db2/sql_tools/SQLWhereNull.java | 25 +- .../java/util/measurement/DistanceUtil.java | 50 +- .../java/util/measurement/MemoryUtil.java | 29 +- .../java/util/measurement/TimeUtil.java | 45 +- .../java/util/network/client/TCPClient.java | 97 +- .../network/client/TCPClientListener.java | 8 +- .../java/util/network/packet/Packet.java | 49 +- .../util/network/packet/PacketClient.java | 5 +- .../util/network/packet/PacketException.java | 4 +- .../util/network/packet/PacketServer.java | 2 +- .../network/packet/bytebuffer/ByteBuffer.java | 44 +- .../packet/bytebuffer/ByteSerializable.java | 10 +- .../network/server/BandwidthCalculation.java | 34 +- .../java/util/network/server/TCPServer.java | 189 +-- .../network/server/TCPServerListener.java | 15 +- .../network_api/client/AbstractRequest.java | 17 +- .../network_api/client/NetworkAPISender.java | 15 +- .../network_api/client/ResponseAnalyser.java | 52 +- .../server/AbstractRequestExecutor.java | 33 +- .../server/NAPIExecutionHandler.java | 3 +- .../server/NetworkAPIListener.java | 90 +- .../network_api/server/PacketExecutor.java | 35 +- .../network_api/server/RequestAnalyser.java | 62 +- .../util/network_api/server/Response.java | 19 +- src/net/md_5/bungee/api/ChatColor.java | 131 +- src/net/md_5/bungee/api/ChatMessageType.java | 9 +- .../md_5/bungee/api/chat/BaseComponent.java | 355 +++-- src/net/md_5/bungee/api/chat/ClickEvent.java | 48 +- .../bungee/api/chat/ComponentBuilder.java | 194 ++- src/net/md_5/bungee/api/chat/HoverEvent.java | 48 +- .../md_5/bungee/api/chat/TextComponent.java | 272 ++-- .../api/chat/TranslatableComponent.java | 309 ++--- 103 files changed, 3047 insertions(+), 5751 deletions(-) delete mode 100644 src/fr/pandacube/java/util/db/LoginHistoryElement.java delete mode 100644 src/fr/pandacube/java/util/db/LoginHistoryTable.java delete mode 100644 src/fr/pandacube/java/util/db/MPGroupElement.java delete mode 100644 src/fr/pandacube/java/util/db/MPGroupTable.java delete mode 100644 src/fr/pandacube/java/util/db/MPGroupUserElement.java delete mode 100644 src/fr/pandacube/java/util/db/MPGroupUserTable.java delete mode 100644 src/fr/pandacube/java/util/db/MPMessageElement.java delete mode 100644 src/fr/pandacube/java/util/db/MPMessageTable.java delete mode 100644 src/fr/pandacube/java/util/db/ModoHistoryElement.java delete mode 100644 src/fr/pandacube/java/util/db/ModoHistoryTable.java delete mode 100644 src/fr/pandacube/java/util/db/ORM.java delete mode 100644 src/fr/pandacube/java/util/db/OnlineShopHistoryElement.java delete mode 100644 src/fr/pandacube/java/util/db/OnlineShopHistoryTable.java delete mode 100644 src/fr/pandacube/java/util/db/PlayerElement.java delete mode 100644 src/fr/pandacube/java/util/db/PlayerIgnoreElement.java delete mode 100644 src/fr/pandacube/java/util/db/PlayerIgnoreTable.java delete mode 100644 src/fr/pandacube/java/util/db/PlayerTable.java delete mode 100644 src/fr/pandacube/java/util/db/SQLElement.java delete mode 100644 src/fr/pandacube/java/util/db/SQLTable.java delete mode 100644 src/fr/pandacube/java/util/db/ShopStockElement.java delete mode 100644 src/fr/pandacube/java/util/db/ShopStockTable.java delete mode 100644 src/fr/pandacube/java/util/db/StaffTicketElement.java delete mode 100644 src/fr/pandacube/java/util/db/StaffTicketTable.java delete mode 100644 src/fr/pandacube/java/util/db/package-info.java diff --git a/src/com/earth2me/essentials/utils/DateUtil.java b/src/com/earth2me/essentials/utils/DateUtil.java index b725ac1..c1d8feb 100644 --- a/src/com/earth2me/essentials/utils/DateUtil.java +++ b/src/com/earth2me/essentials/utils/DateUtil.java @@ -5,12 +5,12 @@ import java.util.GregorianCalendar; import java.util.regex.Matcher; import java.util.regex.Pattern; - -public class DateUtil -{ - public static long parseDateDiff(String time, boolean future) throws Exception - { - Pattern timePattern = Pattern.compile("(?:([0-9]+)\\s*y[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*mo[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*w[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*d[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*h[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*m[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*(?:s[a-z]*)?)?", Pattern.CASE_INSENSITIVE); +public class DateUtil { + public static long parseDateDiff(String time, boolean future) throws Exception { + Pattern timePattern = Pattern.compile("(?:([0-9]+)\\s*y[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*mo[a-z]*[,\\s]*)?" + + "(?:([0-9]+)\\s*w[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*d[a-z]*[,\\s]*)?" + + "(?:([0-9]+)\\s*h[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*m[a-z]*[,\\s]*)?" + + "(?:([0-9]+)\\s*(?:s[a-z]*)?)?", Pattern.CASE_INSENSITIVE); Matcher m = timePattern.matcher(time); int years = 0; int months = 0; @@ -20,101 +20,43 @@ public class DateUtil int minutes = 0; int seconds = 0; boolean found = false; - while (m.find()) - { - if (m.group() == null || m.group().isEmpty()) - { - continue; - } + while (m.find()) { + if (m.group() == null || m.group().isEmpty()) continue; for (int i = 0; i < m.groupCount(); i++) - { - if (m.group(i) != null && !m.group(i).isEmpty()) - { + if (m.group(i) != null && !m.group(i).isEmpty()) { found = true; break; } - } - if (found) - { - if (m.group(1) != null && !m.group(1).isEmpty()) - { - years = Integer.parseInt(m.group(1)); - } - if (m.group(2) != null && !m.group(2).isEmpty()) - { - months = Integer.parseInt(m.group(2)); - } - if (m.group(3) != null && !m.group(3).isEmpty()) - { - weeks = Integer.parseInt(m.group(3)); - } - if (m.group(4) != null && !m.group(4).isEmpty()) - { - days = Integer.parseInt(m.group(4)); - } - if (m.group(5) != null && !m.group(5).isEmpty()) - { - hours = Integer.parseInt(m.group(5)); - } - if (m.group(6) != null && !m.group(6).isEmpty()) - { - minutes = Integer.parseInt(m.group(6)); - } - if (m.group(7) != null && !m.group(7).isEmpty()) - { - seconds = Integer.parseInt(m.group(7)); - } + if (found) { + if (m.group(1) != null && !m.group(1).isEmpty()) years = Integer.parseInt(m.group(1)); + if (m.group(2) != null && !m.group(2).isEmpty()) months = Integer.parseInt(m.group(2)); + if (m.group(3) != null && !m.group(3).isEmpty()) weeks = Integer.parseInt(m.group(3)); + if (m.group(4) != null && !m.group(4).isEmpty()) days = Integer.parseInt(m.group(4)); + if (m.group(5) != null && !m.group(5).isEmpty()) hours = Integer.parseInt(m.group(5)); + if (m.group(6) != null && !m.group(6).isEmpty()) minutes = Integer.parseInt(m.group(6)); + if (m.group(7) != null && !m.group(7).isEmpty()) seconds = Integer.parseInt(m.group(7)); break; } } - if (!found) - { - throw new Exception("Format de durée invalide"); - } + if (!found) throw new Exception("Format de durée invalide"); Calendar c = new GregorianCalendar(); - if (years > 0) - { - c.add(Calendar.YEAR, years * (future ? 1 : -1)); - } - if (months > 0) - { - c.add(Calendar.MONTH, months * (future ? 1 : -1)); - } - if (weeks > 0) - { - c.add(Calendar.WEEK_OF_YEAR, weeks * (future ? 1 : -1)); - } - if (days > 0) - { - c.add(Calendar.DAY_OF_MONTH, days * (future ? 1 : -1)); - } - if (hours > 0) - { - c.add(Calendar.HOUR_OF_DAY, hours * (future ? 1 : -1)); - } - if (minutes > 0) - { - c.add(Calendar.MINUTE, minutes * (future ? 1 : -1)); - } - if (seconds > 0) - { - c.add(Calendar.SECOND, seconds * (future ? 1 : -1)); - } + if (years > 0) c.add(Calendar.YEAR, years * (future ? 1 : -1)); + if (months > 0) c.add(Calendar.MONTH, months * (future ? 1 : -1)); + if (weeks > 0) c.add(Calendar.WEEK_OF_YEAR, weeks * (future ? 1 : -1)); + if (days > 0) c.add(Calendar.DAY_OF_MONTH, days * (future ? 1 : -1)); + if (hours > 0) c.add(Calendar.HOUR_OF_DAY, hours * (future ? 1 : -1)); + if (minutes > 0) c.add(Calendar.MINUTE, minutes * (future ? 1 : -1)); + if (seconds > 0) c.add(Calendar.SECOND, seconds * (future ? 1 : -1)); Calendar max = new GregorianCalendar(); max.add(Calendar.YEAR, 10); - if (c.after(max)) - { - return max.getTimeInMillis(); - } + if (c.after(max)) return max.getTimeInMillis(); return c.getTimeInMillis(); } - static int dateDiff(int type, Calendar fromDate, Calendar toDate, boolean future) - { + static int dateDiff(int type, Calendar fromDate, Calendar toDate, boolean future) { int diff = 0; long savedDate = fromDate.getTimeInMillis(); - while ((future && !fromDate.after(toDate)) || (!future && !fromDate.before(toDate))) - { + while ((future && !fromDate.after(toDate)) || (!future && !fromDate.before(toDate))) { savedDate = fromDate.getTimeInMillis(); fromDate.add(type, future ? 1 : -1); diff++; @@ -124,52 +66,32 @@ public class DateUtil return diff; } - public static String formatDateDiff(long date) - { + public static String formatDateDiff(long date) { Calendar c = new GregorianCalendar(); c.setTimeInMillis(date); Calendar now = new GregorianCalendar(); return DateUtil.formatDateDiff(now, c); } - public static String formatDateDiff(Calendar fromDate, Calendar toDate) - { + public static String formatDateDiff(Calendar fromDate, Calendar toDate) { boolean future = false; - if (toDate.equals(fromDate)) - { - return "now"; - } - if (toDate.after(fromDate)) - { - future = true; - } + if (toDate.equals(fromDate)) return "now"; + if (toDate.after(fromDate)) future = true; StringBuilder sb = new StringBuilder(); - int[] types = new int[] - { - Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND - }; - String[] names = new String[] - { - "year", "years", "month", "months", "day", "days", "hour", "hours", "minute", "minutes", "second", "seconds" - }; + int[] types = new int[] { Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, Calendar.HOUR_OF_DAY, + Calendar.MINUTE, Calendar.SECOND }; + String[] names = new String[] { "year", "years", "month", "months", "day", "days", "hour", "hours", "minute", + "minutes", "second", "seconds" }; int accuracy = 0; - for (int i = 0; i < types.length; i++) - { - if (accuracy > 2) - { - break; - } + for (int i = 0; i < types.length; i++) { + if (accuracy > 2) break; int diff = dateDiff(types[i], fromDate, toDate, future); - if (diff > 0) - { + if (diff > 0) { accuracy++; sb.append(" ").append(diff).append(" ").append(names[i * 2 + (diff > 1 ? 1 : 0)]); } } - if (sb.length() == 0) - { - return "now"; - } + if (sb.length() == 0) return "now"; return sb.toString().trim(); } -} \ No newline at end of file +} diff --git a/src/fr/pandacube/java/Pandacube.java b/src/fr/pandacube/java/Pandacube.java index 4c2f3ff..d503eb2 100644 --- a/src/fr/pandacube/java/Pandacube.java +++ b/src/fr/pandacube/java/Pandacube.java @@ -3,14 +3,11 @@ 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 - - + + 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/external_tools/OfflineUUID.java b/src/fr/pandacube/java/external_tools/OfflineUUID.java index e4fab12..09bc77d 100644 --- a/src/fr/pandacube/java/external_tools/OfflineUUID.java +++ b/src/fr/pandacube/java/external_tools/OfflineUUID.java @@ -1,35 +1,28 @@ package fr.pandacube.java.external_tools; import java.nio.charset.Charset; -import java.util.*; +import java.util.UUID; public class OfflineUUID { public static void main(String[] args) { - for (String arg : args) - { - System.out.println(""+arg+":"+getFromNickName(arg)); - } - if (args.length == 0) - throw new IllegalArgumentException("no argument given. Please give at least one argument."); - } - - public static UUID getFromNickName(String nickname) - { - String str = "OfflinePlayer:"+nickname; - byte[] from_str = str.getBytes(Charset.forName("UTF-8")); - return UUID.nameUUIDFromBytes(from_str); + for (String arg : args) + System.out.println("" + arg + ":" + getFromNickName(arg)); + if (args.length == 0) + throw new IllegalArgumentException("no argument given. Please give at least one argument."); } - - - public static UUID[] getFromNickName(String[] nicknames) - { - if (nicknames == null) - throw new NullPointerException(); - + public static UUID getFromNickName(String nickname) { + String str = "OfflinePlayer:" + nickname; + byte[] from_str = str.getBytes(Charset.forName("UTF-8")); + return UUID.nameUUIDFromBytes(from_str); + } + + public static UUID[] getFromNickName(String[] nicknames) { + if (nicknames == null) throw new NullPointerException(); + UUID[] uuids = new UUID[nicknames.length]; - for (int i=0; i { public void done(T arg); } - diff --git a/src/fr/pandacube/java/util/EnumUtil.java b/src/fr/pandacube/java/util/EnumUtil.java index 8aff869..565fb73 100644 --- a/src/fr/pandacube/java/util/EnumUtil.java +++ b/src/fr/pandacube/java/util/EnumUtil.java @@ -4,82 +4,86 @@ public class EnumUtil { /** * List all enum constants which are in the specified enum class. + * * @param enumType the enum class. * @param separator a string which will be used as a separator * @return a string representation of the enum class. */ public static > String enumList(Class enumType, String separator) { T[] elements = enumType.getEnumConstants(); - + String out = ""; boolean first = true; for (T el : elements) { - if (!first) { - out += separator; - } + if (!first) out += separator; first = false; out += el.name(); - + } return out; } - /** - * List all enum constants which are in the specified enum class. It is equivalent to call - * {@link #enumList(Class, String)} with the second parameter ", " + * List all enum constants which are in the specified enum class. It is + * equivalent to call + * {@link #enumList(Class, String)} with the second parameter + * ", " + * * @param enumType the enum class. * @return a string representation of the enum class. */ public static > String enumList(Class enumType) { return enumList(enumType, ", "); } - + /** - * Permet de rechercher l'existance d'un élément dans un enum, de façon insensible à la casse + * Permet de rechercher l'existance d'un élément dans un enum, de façon + * insensible à la casse + * * @param enumType la classe correpondant à l'enum à lister * @param search l'élément à rechercher, insensible à la casse * @return l'élément de l'énumarétion, si elle a été trouvée, null sinon */ public static > T searchEnum(Class enumType, String search) { T[] elements = enumType.getEnumConstants(); - - for (T el : elements) - if (el.name().equalsIgnoreCase(search)) - return el; - return null; + + for (T el : elements) + if (el.name().equalsIgnoreCase(search)) return el; + return null; } - + /** - * Permet de rechercher l'existance d'un élément dans un enum, de façon insensible à la casse - * La validité de la classe passé en premier paramètre est vérifiée dynamiquement et non - * statiquement. Préférez l'utilisation de {@link #searchEnum(Class, String)} quand c'est possible. + * Permet de rechercher l'existance d'un élément dans un enum, de façon + * insensible à la casse + * La validité de la classe passé en premier paramètre est vérifiée + * dynamiquement et non + * statiquement. Préférez l'utilisation de + * {@link #searchEnum(Class, String)} quand c'est possible. + * * @param enumType la classe correpondant à l'enum à lister * @param search l'élément à rechercher, insensible à la casse - * @return l'élément de l'énumération, si elle a été trouvée et si la classe passée en paramètre est un enum, null dans les autres cas + * @return l'élément de l'énumération, si elle a été trouvée et si la classe + * passée en paramètre est un enum, null dans les autres cas */ public static Enum searchUncheckedEnum(Class enumType, String search) { - if (!enumType.isEnum()) - return null; + if (!enumType.isEnum()) return null; Enum[] elements = (Enum[]) enumType.getEnumConstants(); - - for (Enum el : elements) - if (el.name().equalsIgnoreCase(search)) - return el; - return null; + + for (Enum el : elements) + if (el.name().equalsIgnoreCase(search)) return el; + return null; } - - - - + /** - * Retourne une valeur aléatoire parmis les élément de l'Enum spécifié en paramètre. + * Retourne une valeur aléatoire parmis les élément de l'Enum spécifié en + * paramètre. + * * @param enumType l'enum dans lequel piocher la valeur * @return une des valeurs de l'enum */ public static > T randomValue(Class enumType) { T[] elements = enumType.getEnumConstants(); - + return elements[RandomUtil.rand.nextInt(elements.length)]; } diff --git a/src/fr/pandacube/java/util/JArithmeticInterpreter.java b/src/fr/pandacube/java/util/JArithmeticInterpreter.java index 9e17d88..c63b43b 100644 --- a/src/fr/pandacube/java/util/JArithmeticInterpreter.java +++ b/src/fr/pandacube/java/util/JArithmeticInterpreter.java @@ -15,16 +15,16 @@ Historique: - Version Java disponible: # les operateurs mathematiques disponibles sont ceux de Java donc certains manquent. -2.0: +2.0: - Portage en C++ et debut en Java Version C++: - + - Meilleure gestion memoire lors de la construction de l'expression. - Acceleration de certaines operations. Version Java: - + - Premiere version. Normalement ca doit marcher 1.3b: ajoute les fonctions suivantes: (NON DISTRIBUEE) @@ -37,7 +37,7 @@ Version Java: ajoute: - la verification de la chaine entree (voir code d'erreur) - la verification de l'existence de l'evaluation (voir code d'erreur) - + 1.1: corrige un bug au niveau de l'interpretation des fonctions du type: @@ -50,7 +50,7 @@ Le code source peut etre librement modifie et distribue. Puisqu'il s'agit d'un essai en Java, le code ne doit pas etre super genial et merite sans doute quelques modifications.En particulier, il serait interessant de rajouter le support des Exceptions pour les calculs (division par zero, etc...). - + */ // Classe servant � palier l'absence de passage par variables ou reference @@ -64,709 +64,699 @@ class VariableInt { public class JArithmeticInterpreter { // Variables - - int mOperator; - double mValue; - JArithmeticInterpreter fg, fd; - + + int mOperator; + double mValue; + JArithmeticInterpreter fg, fd; + // Methods - - //.................................................................................... Node - + + // .................................................................................... + // Node + private JArithmeticInterpreter() { this(0, 0, null, null); } - - //.................................................................................... Node - - private JArithmeticInterpreter(int Operator,double Value,JArithmeticInterpreter Fg,JArithmeticInterpreter Fd) { - mOperator=Operator; - mValue=Value; - fg=Fg; - fd=Fd; + + // .................................................................................... + // Node + + private JArithmeticInterpreter(int Operator, double Value, JArithmeticInterpreter Fg, JArithmeticInterpreter Fd) { + mOperator = Operator; + mValue = Value; + fg = Fg; + fd = Fd; } - - private JArithmeticInterpreter(int Operator,double Value) { + + private JArithmeticInterpreter(int Operator, double Value) { this(Operator, Value, null, null); } - - //.................................................................................... Construct_Tree - - private static JArithmeticInterpreter constructTree(StringBuffer string,int length,int error) { - int imbric,Bimbric; - int priorite,ope; - int position,positionv,i,j; - int opetemp=0; - int espa=0,espat=0; - int caspp=0; - - JArithmeticInterpreter node; - + + // .................................................................................... + // Construct_Tree + + private static JArithmeticInterpreter constructTree(StringBuffer string, int length, int error) { + int imbric, Bimbric; + int priorite, ope; + int position, positionv, i, j; + int opetemp = 0; + int espa = 0, espat = 0; + int caspp = 0; + + JArithmeticInterpreter node; + // Initialisation des variables - - if (length<=0) { - error=3; + + if (length <= 0) { + error = 3; return null; } - - ope=0; - imbric=0;Bimbric=128; - priorite=6; - i=0; - positionv=position=0; - + + ope = 0; + imbric = 0; + Bimbric = 128; + priorite = 6; + i = 0; + positionv = position = 0; + // Mise en place des donnees sur le morceau de chaine - - while (i47) && (string.charAt(i)<58)) || (string.charAt(i)=='�')) { - if (priorite>5) { - priorite=5; - positionv=i; + + while (i < length) + if (((string.charAt(i) > 47) && (string.charAt(i) < 58)) || (string.charAt(i) == '�')) { + if (priorite > 5) { + priorite = 5; + positionv = i; } i++; } - else { - if ((string.charAt(i)>96) && (string.charAt(i)<117)) { - VariableInt Vopetemp,Vespat; - - Vopetemp= new VariableInt(); - Vespat= new VariableInt(); - - Vopetemp.mValue=opetemp; - Vespat.mValue=espat; - - FindOperator(Vopetemp,Vespat,string,i); - - opetemp=Vopetemp.mValue; - espat=Vespat.mValue; - - if (opetemp>=0) { - if (imbric=4)) { - ope=opetemp; - position=i; - priorite=4; - espa=espat; + else if ((string.charAt(i) > 96) && (string.charAt(i) < 117)) { + VariableInt Vopetemp, Vespat; + + Vopetemp = new VariableInt(); + Vespat = new VariableInt(); + + Vopetemp.mValue = opetemp; + Vespat.mValue = espat; + + FindOperator(Vopetemp, Vespat, string, i); + + opetemp = Vopetemp.mValue; + espat = Vespat.mValue; + + if (opetemp >= 0) { + if (imbric < Bimbric) { + Bimbric = imbric; + ope = opetemp; + position = i; + priorite = 4; + espa = espat; } - j=i+1; - i+=espat; - while(j= 4)) { + ope = opetemp; + position = i; + priorite = 4; + espa = espat; + } + j = i + 1; + i += espat; + while (j < i) j++; - + } - else if (string.charAt(i)=='t') { - if (priorite==6) ope=-1; + else if (string.charAt(i) == 't') { + if (priorite == 6) ope = -1; i++; } - else if (string.charAt(i)=='p') { - if (priorite==6) ope=-2; + else if (string.charAt(i) == 'p') { + if (priorite == 6) ope = -2; i++; } - else if (string.charAt(i)=='r') { - if (priorite==6) ope=-2; + else if (string.charAt(i) == 'r') { + if (priorite == 6) ope = -2; i++; } - else if (string.charAt(i)=='n') { - if (priorite==6) ope=-1; + else if (string.charAt(i) == 'n') { + if (priorite == 6) ope = -1; i++; } else { - error=2; // symbole non reconnu - return null; - } - } - else { - switch(string.charAt(i)) { - case '(': - imbric++; - i++; - break; - case ')': - imbric--; - i++; - break; - case '+': - if (imbric=1)) { - priorite=1; - ope=1; - position=i; - caspp=0; - } - i++; - break; - case '-': - if (imbric5) { - priorite=1; - position=i; - ope=2; - Bimbric=imbric; - caspp=1; - } - } - else if (string.charAt(i-1)=='(') { - if (priorite>1){ - priorite=1; - position=i; - Bimbric=imbric; - caspp=1; - ope=2; - } - } - else { - Bimbric=imbric; - priorite=1; - ope=2; - position=i; - caspp=0; - } - } - else if ((imbric==Bimbric) && (priorite>=1)) { - if ((i-1)<0) { - if (priorite>5) { - priorite=1; - position=i; - ope=2; - caspp=1; - } - } - else if (string.charAt(i-1)=='(') { - if (priorite>1){ - priorite=1; - position=i; - caspp=1; - ope=2; - } - } - else { - priorite=1; - ope=2; - position=i; - caspp=0; - } - } - i++; - break; - case '*': - if (imbric=2)) { - priorite=2; - ope=3; - position=i; - } - i++; - break; - case '/': - if (imbric=2)) { - priorite=2; - ope=4; - position=i; - } - i++; - break; - case '^': - if (imbric=3)) { - priorite=3; - ope=5; - position=i; - } - i++; - break; - case '.': - i++; - break; - default: - error=2; // symbole non reconnu - return null; - } + error = 2; // symbole non reconnu + return null; } } - } - - if (imbric!=0) { - error=1; // erreur de "parenthesage" + else + switch (string.charAt(i)) { + case '(': + imbric++; + i++; + break; + case ')': + imbric--; + i++; + break; + case '+': + if (imbric < Bimbric) { + Bimbric = imbric; + priorite = 1; + ope = 1; + position = i; + caspp = 0; + } + else if ((imbric == Bimbric) && (priorite >= 1)) { + priorite = 1; + ope = 1; + position = i; + caspp = 0; + } + i++; + break; + case '-': + if (imbric < Bimbric) { + if ((i - 1) < 0) { + if (priorite > 5) { + priorite = 1; + position = i; + ope = 2; + Bimbric = imbric; + caspp = 1; + } + } + else if (string.charAt(i - 1) == '(') { + if (priorite > 1) { + priorite = 1; + position = i; + Bimbric = imbric; + caspp = 1; + ope = 2; + } + } + else { + Bimbric = imbric; + priorite = 1; + ope = 2; + position = i; + caspp = 0; + } + } + else if ((imbric == Bimbric) && (priorite >= 1)) if ((i - 1) < 0) { + if (priorite > 5) { + priorite = 1; + position = i; + ope = 2; + caspp = 1; + } + } + else if (string.charAt(i - 1) == '(') { + if (priorite > 1) { + priorite = 1; + position = i; + caspp = 1; + ope = 2; + } + } + else { + priorite = 1; + ope = 2; + position = i; + caspp = 0; + } + i++; + break; + case '*': + if (imbric < Bimbric) { + Bimbric = imbric; + priorite = 2; + ope = 3; + position = i; + } + else if ((imbric == Bimbric) && (priorite >= 2)) { + priorite = 2; + ope = 3; + position = i; + } + i++; + break; + case '/': + if (imbric < Bimbric) { + Bimbric = imbric; + priorite = 2; + ope = 4; + position = i; + } + else if ((imbric == Bimbric) && (priorite >= 2)) { + priorite = 2; + ope = 4; + position = i; + } + i++; + break; + case '^': + if (imbric < Bimbric) { + Bimbric = imbric; + priorite = 3; + ope = 5; + position = i; + } + else if ((imbric == Bimbric) && (priorite >= 3)) { + priorite = 3; + ope = 5; + position = i; + } + i++; + break; + case '.': + i++; + break; + default: + error = 2; // symbole non reconnu + return null; + } + + if (imbric != 0) { + error = 1; // erreur de "parenthesage" return null; } - - // Traitement des donnees - - if (priorite==6) { - node =new JArithmeticInterpreter(ope,0.0); + + // Traitement des donnees + + if (priorite == 6) { + node = new JArithmeticInterpreter(ope, 0.0); return node; } - else if (caspp==1) { - node = new JArithmeticInterpreter(2,0); - - node.fg= new JArithmeticInterpreter(0,0); - node.fd= new JArithmeticInterpreter(); - - if ((length-position-1-Bimbric)==0) { // argument absent - error=3; + else if (caspp == 1) { + node = new JArithmeticInterpreter(2, 0); + + node.fg = new JArithmeticInterpreter(0, 0); + node.fd = new JArithmeticInterpreter(); + + if ((length - position - 1 - Bimbric) == 0) { // argument absent + error = 3; return null; - } - StringBuffer temp=CopyPartialString(string,(position+1),(length-1-Bimbric)); - node.fd=constructTree(temp,(length-position-1-Bimbric),error); - - return node; } - - else if (priorite==5) { - node = new JArithmeticInterpreter(0,calc_const(string,positionv),null,null); - + StringBuffer temp = CopyPartialString(string, (position + 1), (length - 1 - Bimbric)); + node.fd = constructTree(temp, (length - position - 1 - Bimbric), error); + return node; } - else if (ope>5) { - node = new JArithmeticInterpreter(ope,0,null,null); - - if ((length-position-espa-Bimbric)==0) { // argument absent - error=3; - return null; - } - StringBuffer temp=CopyPartialString(string,(position+espa),(length-1)); - node.fg=constructTree(temp,(length-position-espa-Bimbric),error); + + else if (priorite == 5) { + node = new JArithmeticInterpreter(0, calc_const(string, positionv), null, null); + return node; - } - else{ - node = new JArithmeticInterpreter(ope,0,null,null); - - if ((position-Bimbric)==0) { // argument absent - error=3; + } + else if (ope > 5) { + node = new JArithmeticInterpreter(ope, 0, null, null); + + if ((length - position - espa - Bimbric) == 0) { // argument absent + error = 3; return null; } - StringBuffer temp=CopyPartialString(string,Bimbric,(position-1)); - node.fg=constructTree(temp,(position-Bimbric),error); - if ((length-position-1-Bimbric)==0) { // argument absent - error=3; + StringBuffer temp = CopyPartialString(string, (position + espa), (length - 1)); + node.fg = constructTree(temp, (length - position - espa - Bimbric), error); + return node; + } + else { + node = new JArithmeticInterpreter(ope, 0, null, null); + + if ((position - Bimbric) == 0) { // argument absent + error = 3; return null; } - temp=CopyPartialString(string,(position+1),(length-1-Bimbric)); - node.fd=constructTree(temp,(length-position-1-Bimbric),error); + StringBuffer temp = CopyPartialString(string, Bimbric, (position - 1)); + node.fg = constructTree(temp, (position - Bimbric), error); + if ((length - position - 1 - Bimbric) == 0) { // argument absent + error = 3; + return null; + } + temp = CopyPartialString(string, (position + 1), (length - 1 - Bimbric)); + node.fd = constructTree(temp, (length - position - 1 - Bimbric), error); return node; } } - - //.................................................................................... - + + // .................................................................................... + private double computeTree() { - if (mOperator==0) return mValue; + if (mOperator == 0) return mValue; int error = 0; - - double valueL=fg.computeTree(); - - if (error!=0) return 0; - double valueR=0; - - if (fd!=null) valueR=fd.computeTree(); - if (error!=0) return 0; - - switch(mOperator) { - case 1: // + - return (valueL+valueR); - case 2: // - - return (valueL-valueR); - case 3: // * - return (valueL*valueR); - case 4: // - - if (valueR==0) { - error=1; - return 0; - } - return (valueL/valueR); - case 5: // ^ - return Math.pow(valueL,valueR); - case 6: // exp - return Math.exp(valueL); - case 7: // ln - if (valueL<=0) { - if (valueL<0) error=2; - else error=1; - return 0; - } - return (Math.log(valueL)/Math.log(2)); - case 8: // log - if (valueL<=0) { - if (valueL<0) error=2; - else error=1; - return 0; - } - return Math.log(valueL); - case 9: // sqrt - if (valueL<0) { - error=2; - return 0; - } - return Math.sqrt(valueL); - case 10: // abs - return Math.abs(valueL); - case 11: - return Math.sin(valueL); // sin - case 12: - return Math.cos(valueL); // cos - case 13: - return Math.tan(valueL); // tan - case 14: - return Math.asin(valueL); // asin - case 15: - return Math.acos(valueL); // acos - case 16: - return Math.atan(valueL); // atan - default: + + double valueL = fg.computeTree(); + + if (error != 0) return 0; + double valueR = 0; + + if (fd != null) valueR = fd.computeTree(); + if (error != 0) return 0; + + switch (mOperator) { + case 1: // + + return (valueL + valueR); + case 2: // - + return (valueL - valueR); + case 3: // * + return (valueL * valueR); + case 4: // - + if (valueR == 0) { + error = 1; return 0; + } + return (valueL / valueR); + case 5: // ^ + return Math.pow(valueL, valueR); + case 6: // exp + return Math.exp(valueL); + case 7: // ln + if (valueL <= 0) { + if (valueL < 0) error = 2; + else + error = 1; + return 0; + } + return (Math.log(valueL) / Math.log(2)); + case 8: // log + if (valueL <= 0) { + if (valueL < 0) error = 2; + else + error = 1; + return 0; + } + return Math.log(valueL); + case 9: // sqrt + if (valueL < 0) { + error = 2; + return 0; + } + return Math.sqrt(valueL); + case 10: // abs + return Math.abs(valueL); + case 11: + return Math.sin(valueL); // sin + case 12: + return Math.cos(valueL); // cos + case 13: + return Math.tan(valueL); // tan + case 14: + return Math.asin(valueL); // asin + case 15: + return Math.acos(valueL); // acos + case 16: + return Math.atan(valueL); // atan + default: + return 0; } } - - //.................................................................................... Write_Tree - + + // .................................................................................... + // Write_Tree + private void writeTree(StringBuffer string) { - boolean parenthese=false; - - switch(mOperator) { - case 0: - string.append(StringUtil.formatDouble(mValue)); - break; - case 1: + boolean parenthese = false; + + switch (mOperator) { + case 0: + string.append(StringUtil.formatDouble(mValue)); + break; + case 1: + fg.writeTree(string); + string.append('+'); + fd.writeTree(string); + break; + case 2: + if ((fg.mOperator == 0) && (fg.mValue == 0)) ; + else fg.writeTree(string); - string.append('+'); - fd.writeTree(string); - break; - case 2: - if ((fg.mOperator==0) && (fg.mValue==0)); - else fg.writeTree(string); - string.append('-'); - if ((fd.mOperator==1) || (fd.mOperator==2)) { - parenthese=true; - string.append('('); - } - fd.writeTree(string); - if (parenthese==true) { - string.append(')'); - } - break; - case 3: - if ((fg.mOperator==1) || (fg.mOperator==2)) { - parenthese=true; - string.append('('); - } - fg.writeTree(string); - if (parenthese==true) - string.append(')'); - parenthese=false; - string.append('*'); - if ((fd.mOperator==1) || (fd.mOperator==2)) { - parenthese=true; - string.append('('); - } - fd.writeTree(string); - if (parenthese==true) - string.append(')'); - break; - case 4: - if ((fg.mOperator==1) || (fg.mOperator==2)) { - parenthese=true; - string.append('('); - } - fg.writeTree(string); - if (parenthese==true) - string.append(')'); - parenthese=false; - string.append('/'); - if ((fd.mOperator>0) && (fd.mOperator<5)) { - parenthese=true; - string.append('('); - } - fd.writeTree(string); - if (parenthese==true) - string.append(')'); - break; - case 5: - if ((fg.mOperator>0) && (fg.mOperator<5)) { - parenthese=true; - string.append('('); - } - fg.writeTree(string); - if (parenthese==true) - string.append(')'); - parenthese=false; - string.append('^'); - if ((fd.mOperator>0) && (fd.mOperator<5)) { - parenthese=true; - string.append('('); - } - fd.writeTree(string); - if (parenthese==true) - string.append(')'); - break; - case 6: - string.append("exp("); - fg.writeTree(string); - string.append(')'); - break; - case 7: - string.append("log("); - fg.writeTree(string); - string.append(')'); - break; - case 8: - string.append("ln("); - fg.writeTree(string); - string.append(')'); - break; - case 9: - string.append("sqrt("); - fg.writeTree(string); - string.append(')'); - break; - case 10: - string.append("|"); - fg.writeTree(string); - string.append('|'); - break; - case 11: - string.append("sin("); - fg.writeTree(string); - string.append(')'); - break; - case 12: - string.append("cos("); - fg.writeTree(string); - string.append(')'); - break; - case 13: - string.append("tan("); - fg.writeTree(string); - string.append(')'); - break; - case 14: - string.append("asin("); - fg.writeTree(string); - string.append(')'); - break; - case 15: - string.append("acos("); - fg.writeTree(string); - string.append(')'); - break; - case 16: - string.append("atan("); - fg.writeTree(string); - string.append(')'); - break; + string.append('-'); + if ((fd.mOperator == 1) || (fd.mOperator == 2)) { + parenthese = true; + string.append('('); + } + fd.writeTree(string); + if (parenthese == true) string.append(')'); + break; + case 3: + if ((fg.mOperator == 1) || (fg.mOperator == 2)) { + parenthese = true; + string.append('('); + } + fg.writeTree(string); + if (parenthese == true) string.append(')'); + parenthese = false; + string.append('*'); + if ((fd.mOperator == 1) || (fd.mOperator == 2)) { + parenthese = true; + string.append('('); + } + fd.writeTree(string); + if (parenthese == true) string.append(')'); + break; + case 4: + if ((fg.mOperator == 1) || (fg.mOperator == 2)) { + parenthese = true; + string.append('('); + } + fg.writeTree(string); + if (parenthese == true) string.append(')'); + parenthese = false; + string.append('/'); + if ((fd.mOperator > 0) && (fd.mOperator < 5)) { + parenthese = true; + string.append('('); + } + fd.writeTree(string); + if (parenthese == true) string.append(')'); + break; + case 5: + if ((fg.mOperator > 0) && (fg.mOperator < 5)) { + parenthese = true; + string.append('('); + } + fg.writeTree(string); + if (parenthese == true) string.append(')'); + parenthese = false; + string.append('^'); + if ((fd.mOperator > 0) && (fd.mOperator < 5)) { + parenthese = true; + string.append('('); + } + fd.writeTree(string); + if (parenthese == true) string.append(')'); + break; + case 6: + string.append("exp("); + fg.writeTree(string); + string.append(')'); + break; + case 7: + string.append("log("); + fg.writeTree(string); + string.append(')'); + break; + case 8: + string.append("ln("); + fg.writeTree(string); + string.append(')'); + break; + case 9: + string.append("sqrt("); + fg.writeTree(string); + string.append(')'); + break; + case 10: + string.append("|"); + fg.writeTree(string); + string.append('|'); + break; + case 11: + string.append("sin("); + fg.writeTree(string); + string.append(')'); + break; + case 12: + string.append("cos("); + fg.writeTree(string); + string.append(')'); + break; + case 13: + string.append("tan("); + fg.writeTree(string); + string.append(')'); + break; + case 14: + string.append("asin("); + fg.writeTree(string); + string.append(')'); + break; + case 15: + string.append("acos("); + fg.writeTree(string); + string.append(')'); + break; + case 16: + string.append("atan("); + fg.writeTree(string); + string.append(')'); + break; } } - - //.................................................................................... calc_const - - private static double calc_const(StringBuffer chaine,int pos) { - int i=pos,j; - double temp=0; - int signe=1; - int longueur=chaine.length(); - - - if (chaine.charAt(i)=='-') { - signe=-1; + + // .................................................................................... + // calc_const + + private static double calc_const(StringBuffer chaine, int pos) { + int i = pos, j; + double temp = 0; + int signe = 1; + int longueur = chaine.length(); + + if (chaine.charAt(i) == '-') { + signe = -1; i++; } - if (chaine.charAt(i)=='π') return signe*Math.PI; - - while (i47 && chaine.charAt(i)<58) { - temp=temp*10+(chaine.charAt(i)-48); + if (chaine.charAt(i) == 'π') return signe * Math.PI; + + while (i < longueur && chaine.charAt(i) > 47 && chaine.charAt(i) < 58) { + temp = temp * 10 + (chaine.charAt(i) - 48); i++; } - if (i47 && chaine.charAt(i)<58) { - temp=temp+(chaine.charAt(i)-48)*Math.exp(-j*2.30258509); + j = 1; + while (i < longueur && chaine.charAt(i) > 47 && chaine.charAt(i) < 58) { + temp = temp + (chaine.charAt(i) - 48) * Math.exp(-j * 2.30258509); i++; j++; } } - return (signe*temp); + return (signe * temp); } - - //.................................................................................... FindOperator - - private static void FindOperator(VariableInt oper,VariableInt esp,StringBuffer chaine,int pos) { - switch(chaine.charAt(pos)) { + + // .................................................................................... + // FindOperator + + private static void FindOperator(VariableInt oper, VariableInt esp, StringBuffer chaine, int pos) { + switch (chaine.charAt(pos)) { case 'a': - switch(chaine.charAt(pos+1)) { - case 'b': - esp.mValue=3; - oper.mValue=10; - break; - case 'c': - esp.mValue=4; - oper.mValue=15; - break; - case 's': - esp.mValue=4; - oper.mValue=14; - break; - case 't': - esp.mValue=4; - oper.mValue=16; - break; + switch (chaine.charAt(pos + 1)) { + case 'b': + esp.mValue = 3; + oper.mValue = 10; + break; + case 'c': + esp.mValue = 4; + oper.mValue = 15; + break; + case 's': + esp.mValue = 4; + oper.mValue = 14; + break; + case 't': + esp.mValue = 4; + oper.mValue = 16; + break; } break; case 'c': - if (chaine.charAt(pos+1)=='h') { - esp.mValue=2; - oper.mValue=18; + if (chaine.charAt(pos + 1) == 'h') { + esp.mValue = 2; + oper.mValue = 18; } - else if ((chaine.charAt(pos+1)=='o') && (chaine.charAt(pos+2)=='s')) { - if (chaine.charAt(pos+3)=='h') { - esp.mValue=4; - oper.mValue=18; - } - else { - esp.mValue=3; - oper.mValue=12; - } + else if ((chaine.charAt(pos + 1) == 'o') && (chaine.charAt(pos + 2) == 's')) + if (chaine.charAt(pos + 3) == 'h') { + esp.mValue = 4; + oper.mValue = 18; + } + else { + esp.mValue = 3; + oper.mValue = 12; } break; case 'e': - if ((chaine.charAt(pos+1)=='x') && (chaine.charAt(pos+2)=='p')) { - esp.mValue=3; - oper.mValue=6; + if ((chaine.charAt(pos + 1) == 'x') && (chaine.charAt(pos + 2) == 'p')) { + esp.mValue = 3; + oper.mValue = 6; } - else oper.mValue=-10; + else + oper.mValue = -10; break; case 'l': - if (chaine.charAt(pos+1)=='n') { - esp.mValue=2; - oper.mValue=7; + if (chaine.charAt(pos + 1) == 'n') { + esp.mValue = 2; + oper.mValue = 7; } - else if ((chaine.charAt(pos+1)=='o') && (chaine.charAt(pos+2)=='g')){ - esp.mValue=3; - oper.mValue=8; - } - else oper.mValue=-10; - break; + else if ((chaine.charAt(pos + 1) == 'o') && (chaine.charAt(pos + 2) == 'g')) { + esp.mValue = 3; + oper.mValue = 8; + } + else + oper.mValue = -10; + break; case 's': - if (chaine.charAt(pos+1)=='h') { - esp.mValue=2; - oper.mValue=17; + if (chaine.charAt(pos + 1) == 'h') { + esp.mValue = 2; + oper.mValue = 17; } - else if (chaine.charAt(pos+1)=='q') { - esp.mValue=4; - oper.mValue=9; + else if (chaine.charAt(pos + 1) == 'q') { + esp.mValue = 4; + oper.mValue = 9; + } + else if (chaine.charAt(pos + 3) == 'h') { + esp.mValue = 4; + oper.mValue = 17; } else { - if (chaine.charAt(pos+3)=='h') { - esp.mValue=4; - oper.mValue=17; - } - else { - esp.mValue=3; - oper.mValue=11; - } + esp.mValue = 3; + oper.mValue = 11; } break; case 't': - if (chaine.charAt(pos+1)=='h') { - esp.mValue=2; - oper.mValue=19; + if (chaine.charAt(pos + 1) == 'h') { + esp.mValue = 2; + oper.mValue = 19; } - else if ((chaine.charAt(pos+1)=='a') && (chaine.charAt(pos+2)=='n')) { - if (chaine.charAt(pos+3)=='h') { - esp.mValue=4; - oper.mValue=19; + else if ((chaine.charAt(pos + 1) == 'a') && (chaine.charAt(pos + 2) == 'n')) { + if (chaine.charAt(pos + 3) == 'h') { + esp.mValue = 4; + oper.mValue = 19; } else { - esp.mValue=3; - oper.mValue=13; + esp.mValue = 3; + oper.mValue = 13; } } - else oper.mValue=-10; + else + oper.mValue = -10; break; default: - oper.mValue=-10; + oper.mValue = -10; break; } } - - //.................................................................................... CopyPartialString - - private static StringBuffer CopyPartialString(StringBuffer chaine,int debut,int fin) { - StringBuffer chartemp; - int a=fin-debut+1; - chartemp=new StringBuffer(a+1); - - for(int i=0;i getLocalNameHistory(UUID id) { List ret = new ArrayList<>(); - - if (id == null) - return ret; - + + if (id == null) return ret; + String last = getLastKnownName(id); - if (last != null) - ret.add(last); - + 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); - + 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; + 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; - + } - - - - - - - + /** - * 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 à + * 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 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 - + if (!isValidPlayerName(exactName)) return null; // évite une recherche + // inutile dans la base + // de donnée + // on tente d'abord via le plugin de permission BungeePerms pl = getPermPlugin(); - if (pl != null) - return pl.getPermissionsManager().getUUIDPlayerDB().getUUID(exactName); - + 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(); + 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(); + 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 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) { + 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); - + 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))); + 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); + return uuid.equals(((PlayerSearchResult) o).uuid); } - - @Override - public int hashCode() { return uuid.hashCode(); } - } - - - - - - - + @Override + public int hashCode() { + return uuid.hashCode(); + } + } public static boolean isValidPlayerName(String name) { if (name == null) return false; return name.matches("[0-9a-zA-Z_]{2,16}"); } - - - - - - + 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); + return ORM.getFirst(SQLPlayer.class, new SQLWhereComp(SQLPlayer.playerId, SQLComparator.EQ, id.toString()), + null); } - - - - - - + } diff --git a/src/fr/pandacube/java/util/PlayerNameHistoryLookup.java b/src/fr/pandacube/java/util/PlayerNameHistoryLookup.java index c6bdcce..b101fcb 100644 --- a/src/fr/pandacube/java/util/PlayerNameHistoryLookup.java +++ b/src/fr/pandacube/java/util/PlayerNameHistoryLookup.java @@ -8,114 +8,138 @@ import java.net.URL; import java.util.Arrays; import java.util.Date; import java.util.UUID; - + import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; - + /** -* This class performs a name lookup for a player and gets back all the name changes of the player (if any). -*
https://bukkit.org/threads/player-name-history-lookup.412679/ -* @since 25-3-2016 -* @author mine-care (AKA fillpant) -* -*/ + * This class performs a name lookup for a player and gets back all the name + * changes of the player (if any). + *
+ * https + * ://bukkit.org/threads/player-name-history-lookup.412679/ + * + * @since 25-3-2016 + * @author mine-care (AKA fillpant) + * + */ public class PlayerNameHistoryLookup { - - /** - * The URL from Mojang API that provides the JSON String in response. - */ - private static final String LOOKUP_URL = "https://api.mojang.com/user/profiles/%s/names"; - - private static final Gson JSON_PARSER = new Gson(); - - /** - *

NOTE: Avoid running this method Synchronously with the main thread!It blocks while attempting to get a response from Mojang servers!

- * @param player The UUID of the player to be looked up. - * @return Returns an array of {@link PreviousPlayerNameEntry} objects, or null if the response couldn't be interpreted. - * @throws IOException {@link #getPlayerPreviousNames(String)} - */ - public static PreviousPlayerNameEntry[] getPlayerPreviousNames(UUID player) throws IOException { - return getPlayerPreviousNames(player.toString()); - } - - /** - *

NOTE: Avoid running this method Synchronously with the main thread! It blocks while attempting to get a response from Mojang servers!

- * Alternative method accepting an {@link OfflinePlayer} (and therefore {@link Player}) objects as parameter. - * @param uuid The UUID String to lookup - * @return Returns an array of {@link PreviousPlayerNameEntry} objects, or null if the response couldn't be interpreted. - * @throws IOException {@link #getRawJsonResponse(String)} - */ - public static PreviousPlayerNameEntry[] getPlayerPreviousNames(String uuid) throws IOException { - if (uuid == null || uuid.isEmpty()) - return null; - uuid = uuid.replace("-", ""); - String response = getRawJsonResponse(new URL(String.format(LOOKUP_URL, uuid))); - PreviousPlayerNameEntry[] names = JSON_PARSER.fromJson(response, PreviousPlayerNameEntry[].class); - return names; - } - - /** - * This is a helper method used to read the response of Mojang's API webservers. - * @param u the URL to connect to - * @return a String with the data read. - * @throws IOException Inherited by {@link BufferedReader#readLine()}, {@link BufferedReader#close()}, {@link URL}, {@link HttpURLConnection#getInputStream()} - */ - private static String getRawJsonResponse(URL u) throws IOException { - HttpURLConnection con = (HttpURLConnection) u.openConnection(); - con.setDoInput(true); - con.setConnectTimeout(2000); - con.setReadTimeout(2000); - con.connect(); - BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); - String response = in.readLine(); - in.close(); - return response; - } - - /** - * This class represents the typical response expected by Mojang servers when requesting the name history of a player. - */ - public class PreviousPlayerNameEntry { - private String name; - @SerializedName("changedToAt") - private long changeTime; - - /** - * Gets the player name of this entry. - * @return The name of the player. - */ - public String getPlayerName() { - return name; - } - - /** - * Get the time of change of the name. - *
Note: This will return 0 if the name is the original (initial) name of the player! Make sure you check if it is 0 before handling! - *
Parsing 0 to a Date will result in the date "01/01/1970".
- * @return a timestamp in miliseconds that you can turn into a date or handle however you want :) - */ - public long getChangeTime() { - return changeTime; - } - - /** - * Check if this name is the name used to register the account (the initial/original name) - * @return a boolean, true if it is the the very first name of the player, otherwise false. - */ - public boolean isPlayersInitialName() { - return getChangeTime() == 0; - } - - @Override - public String toString() { - return "Name: " + name + " Date of change: " + new Date(changeTime).toString(); - } - } - - - - public static void main(String[] args) throws IOException { + + /** + * The URL from Mojang API that provides the JSON String in response. + */ + private static final String LOOKUP_URL = "https://api.mojang.com/user/profiles/%s/names"; + + private static final Gson JSON_PARSER = new Gson(); + + /** + *

NOTE: Avoid running this method Synchronously with the main + * thread!It blocks while attempting to get a response from Mojang servers! + *

+ * + * @param player The UUID of the player to be looked up. + * @return Returns an array of {@link PreviousPlayerNameEntry} objects, or + * null if the response couldn't be interpreted. + * @throws IOException {@link #getPlayerPreviousNames(String)} + */ + public static PreviousPlayerNameEntry[] getPlayerPreviousNames(UUID player) throws IOException { + return getPlayerPreviousNames(player.toString()); + } + + /** + *

NOTE: Avoid running this method Synchronously with the main + * thread! It blocks while attempting to get a response from Mojang servers! + *

+ * Alternative method accepting an {@link OfflinePlayer} (and therefore + * {@link Player}) objects as parameter. + * + * @param uuid The UUID String to lookup + * @return Returns an array of {@link PreviousPlayerNameEntry} objects, or + * null if the response couldn't be interpreted. + * @throws IOException {@link #getRawJsonResponse(String)} + */ + public static PreviousPlayerNameEntry[] getPlayerPreviousNames(String uuid) throws IOException { + if (uuid == null || uuid.isEmpty()) return null; + uuid = uuid.replace("-", ""); + String response = getRawJsonResponse(new URL(String.format(LOOKUP_URL, uuid))); + PreviousPlayerNameEntry[] names = JSON_PARSER.fromJson(response, PreviousPlayerNameEntry[].class); + return names; + } + + /** + * This is a helper method used to read the response of Mojang's API + * webservers. + * + * @param u the URL to connect to + * @return a String with the data read. + * @throws IOException Inherited by {@link BufferedReader#readLine()}, + * {@link BufferedReader#close()}, {@link URL}, + * {@link HttpURLConnection#getInputStream()} + */ + private static String getRawJsonResponse(URL u) throws IOException { + HttpURLConnection con = (HttpURLConnection) u.openConnection(); + con.setDoInput(true); + con.setConnectTimeout(2000); + con.setReadTimeout(2000); + con.connect(); + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String response = in.readLine(); + in.close(); + return response; + } + + /** + * This class represents the typical response expected by Mojang servers + * when requesting the name history of a player. + */ + public class PreviousPlayerNameEntry { + private String name; + @SerializedName("changedToAt") + private long changeTime; + + /** + * Gets the player name of this entry. + * + * @return The name of the player. + */ + public String getPlayerName() { + return name; + } + + /** + * Get the time of change of the name. + *
+ * Note: This will return 0 if the name is the original (initial) + * name of the player! Make sure you check if it is 0 before handling! + *
+ * Parsing 0 to a Date will result in the date "01/01/1970".
+ * + * @return a timestamp in miliseconds that you can turn into a date or + * handle however you want :) + */ + public long getChangeTime() { + return changeTime; + } + + /** + * Check if this name is the name used to register the account (the + * initial/original name) + * + * @return a boolean, true if it is the the very first name of the + * player, otherwise false. + */ + public boolean isPlayersInitialName() { + return getChangeTime() == 0; + } + + @Override + public String toString() { + return "Name: " + name + " Date of change: " + new Date(changeTime).toString(); + } + } + + public static void main(String[] args) throws IOException { System.out.println(Arrays.toString(getPlayerPreviousNames("a18d9b2c-e18f-4933-9e15-36452bc36857"))); } - -} \ No newline at end of file + +} diff --git a/src/fr/pandacube/java/util/RandomUtil.java b/src/fr/pandacube/java/util/RandomUtil.java index 04ed2c2..cc0bd1d 100644 --- a/src/fr/pandacube/java/util/RandomUtil.java +++ b/src/fr/pandacube/java/util/RandomUtil.java @@ -3,17 +3,15 @@ package fr.pandacube.java.util; import java.util.Random; public class RandomUtil { - + public static Random rand = new Random(); - - + public static int nextIntBetween(int minInclu, int maxExclu) { - return rand.nextInt(maxExclu-minInclu)+minInclu; + return rand.nextInt(maxExclu - minInclu) + minInclu; } - - + public static double nextDoubleBetween(double minInclu, double maxExclu) { - return rand.nextDouble()*(maxExclu-minInclu)+minInclu; + return rand.nextDouble() * (maxExclu - minInclu) + minInclu; } } diff --git a/src/fr/pandacube/java/util/ServerPropertyFile.java b/src/fr/pandacube/java/util/ServerPropertyFile.java index 42adf90..613875e 100644 --- a/src/fr/pandacube/java/util/ServerPropertyFile.java +++ b/src/fr/pandacube/java/util/ServerPropertyFile.java @@ -12,16 +12,15 @@ import java.util.Map; import com.google.gson.Gson; public class ServerPropertyFile { - + private File file; - + private Map data; - - + public ServerPropertyFile(File f) { if (f == null) throw new IllegalArgumentException("f ne doit pas être null"); file = f; - + data = new HashMap(); data.put("name", "default_name"); data.put("memory", "512M"); @@ -30,138 +29,120 @@ public class ServerPropertyFile { data.put("jarFile", ""); data.put("isLobby", false); } - - + /** * Charge le fichier de configuration dans cette instance de la classe + * * @return true si le chargement a réussi, false sinon */ public boolean loadFromFile() { BufferedReader in = null; try { in = new BufferedReader(new FileReader(file)); - - + @SuppressWarnings("unchecked") Map dataFile = new Gson().fromJson(in, Map.class); - if (!dataFile.containsKey("name") || !(dataFile.get("name") instanceof String)) - return false; + if (!dataFile.containsKey("name") || !(dataFile.get("name") instanceof String)) return false; - if (!dataFile.containsKey("memory") || !(dataFile.get("memory") instanceof String)) - return false; + if (!dataFile.containsKey("memory") || !(dataFile.get("memory") instanceof String)) return false; - if (!dataFile.containsKey("javaArgs") || !(dataFile.get("javaArgs") instanceof String)) - return false; + if (!dataFile.containsKey("javaArgs") || !(dataFile.get("javaArgs") instanceof String)) return false; if (!dataFile.containsKey("MinecraftArgs") || !(dataFile.get("MinecraftArgs") instanceof String)) return false; - if (!dataFile.containsKey("jarFile") || !(dataFile.get("jarFile") instanceof String)) - return false; + if (!dataFile.containsKey("jarFile") || !(dataFile.get("jarFile") instanceof String)) return false; + + if (!dataFile.containsKey("isLobby") || !(dataFile.get("isLobby") instanceof Boolean)) return false; - if (!dataFile.containsKey("isLobby") || !(dataFile.get("isLobby") instanceof Boolean)) - return false; - data = dataFile; - - return true; - } - catch (IOException e) { - e.printStackTrace(); - } - finally { - try { - in.close(); - } catch (Exception e) { } - } - return false; - } - - - - public boolean save() { - BufferedWriter out = null; - try { - out = new BufferedWriter(new FileWriter(file,false)); - - String jsonStr = new Gson().toJson(data); - - out.append(jsonStr); - - out.flush(); - + return true; } catch (IOException e) { e.printStackTrace(); - } - finally { + } finally { try { - out.close(); - } catch (Exception e) { } + in.close(); + } catch (Exception e) {} } - return false; } - - - - + + public boolean save() { + BufferedWriter out = null; + try { + out = new BufferedWriter(new FileWriter(file, false)); + + String jsonStr = new Gson().toJson(data); + + out.append(jsonStr); + + out.flush(); + + return true; + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + out.close(); + } catch (Exception e) {} + } + + return false; + } public String getName() { return (String) data.get("name"); } + public String getMemory() { return (String) data.get("memory"); } + public String getJavaArgs() { return (String) data.get("javaArgs"); } + public String getMinecraftArgs() { return (String) data.get("MinecraftArgs"); } + public String getJarFile() { return (String) data.get("jarFile"); } + public boolean getIsLobby() { return (boolean) data.get("isLobby"); } - - - - - public void setName(String n) { - if (n == null || !n.matches("^[a-zA-Z]$")) - throw new IllegalArgumentException(); + if (n == null || !n.matches("^[a-zA-Z]$")) throw new IllegalArgumentException(); data.put("name", n); } + public void setMemory(String m) { - if (m == null || !m.matches("^[0-9]+[mgMG]$")) - throw new IllegalArgumentException(); + if (m == null || !m.matches("^[0-9]+[mgMG]$")) throw new IllegalArgumentException(); data.put("memory", m); } + public void setJavaArgs(String ja) { - if (ja == null) - throw new IllegalArgumentException(); + if (ja == null) throw new IllegalArgumentException(); data.put("javaArgs", ja); } + public void setMinecraftArgs(String ma) { - if (ma == null) - throw new IllegalArgumentException(); + if (ma == null) throw new IllegalArgumentException(); data.put("MinecraftArgs", ma); } - + public void setJarFile(String j) { - if (j == null) - throw new IllegalArgumentException(); + if (j == null) throw new IllegalArgumentException(); data.put("jarFile", j); } - + public void setIsLobby(boolean l) { data.put("isLobby", l); } - - + } diff --git a/src/fr/pandacube/java/util/StringUtil.java b/src/fr/pandacube/java/util/StringUtil.java index 5aa891c..fff9e1d 100644 --- a/src/fr/pandacube/java/util/StringUtil.java +++ b/src/fr/pandacube/java/util/StringUtil.java @@ -1,26 +1,22 @@ package fr.pandacube.java.util; public class StringUtil { - public static String formatDouble(double d) - { - if(d == (long) d) - return String.format("%d",(long)d); - else - return String.valueOf(d); + public static String formatDouble(double d) { + if (d == (long) d) return String.format("%d", (long) d); + else + return String.valueOf(d); } - + /** * @param s Chaine de caractère à parcourir * @param c_match le caractère dont on doit retourner le nombre d'occurence * @return nombre d'occurence de c_match dans s */ - public static int char_count(CharSequence s, char c_match) - { + public static int char_count(CharSequence s, char c_match) { char[] chars = s.toString().toCharArray(); int count = 0; for (char c : chars) - if (c == c_match) - count++; + if (c == c_match) count++; return count; } } diff --git a/src/fr/pandacube/java/util/chat_display/Display.java b/src/fr/pandacube/java/util/chat_display/Display.java index a382372..762d4c5 100644 --- a/src/fr/pandacube/java/util/chat_display/Display.java +++ b/src/fr/pandacube/java/util/chat_display/Display.java @@ -9,86 +9,78 @@ import net.md_5.bungee.api.chat.HoverEvent; import net.md_5.bungee.api.chat.TextComponent; public class Display { - + private BaseComponent first = new TextComponent(""); - + private BaseComponent current = null; - - - public Display() { - } - + + public Display() {} /** - * Après l'appel de ce contructeur, vous devez appeler nextComponent() pour initialiser la composante suivante + * Après l'appel de ce contructeur, vous devez appeler nextComponent() pour + * initialiser la composante suivante */ public Display(String legacyText) { convertAndAddLegacy(legacyText); } /** - * Construit un message en mettant à la ligne après chaque chaine passé en paramètre.
- * Après l'appel de ce contructeur, vous devez appeler nextComponent() pour initialiser la composante suivante + * Construit un message en mettant à la ligne après chaque chaine passé en + * paramètre.
+ * Après l'appel de ce contructeur, vous devez appeler nextComponent() pour + * initialiser la composante suivante */ public Display(String[] legacyText) { boolean f = true; for (String s : legacyText) { if (s == null) s = ""; - if (!f) - first.addExtra("\n"); + if (!f) first.addExtra("\n"); f = false; convertAndAddLegacy(s); } } + /** - * Construit un message en mettant à la ligne après chaque chaine passé en paramètre.
- * Après l'appel de ce contructeur, vous devez appeler nextComponent() pour initialiser la composante suivante + * Construit un message en mettant à la ligne après chaque chaine passé en + * paramètre.
+ * Après l'appel de ce contructeur, vous devez appeler nextComponent() pour + * initialiser la composante suivante */ public Display(List legacyText) { this(legacyText.toArray(new String[legacyText.size()])); } - + /** - * Après l'appel de ce contructeur, vous devez appeler nextComponent() pour initialiser la composante suivante + * Après l'appel de ce contructeur, vous devez appeler nextComponent() pour + * initialiser la composante suivante */ public Display(BaseComponent firstComponent) { if (firstComponent == null) throw new IllegalArgumentException("le paramètre ne doit pas être null"); first.addExtra(firstComponent); } - - - /** - * Après l'appel de cette méthode, vous devez appeler nextComponent() pour initialiser la composante suivante + * Après l'appel de cette méthode, vous devez appeler nextComponent() pour + * initialiser la composante suivante */ public Display convertAndAddLegacy(String legacyText) { finalizeCurrentComponent(); - - if (legacyText == null) - return this; + + if (legacyText == null) return this; BaseComponent[] compo = TextComponent.fromLegacyText(legacyText); - - for (BaseComponent c : compo) { + + for (BaseComponent c : compo) first.addExtra(c); - } return this; } - - - - - + public Display nextComponent(String str) { finalizeCurrentComponent(); if (str == null) str = ""; current = new TextComponent(str); return this; } - - - - + public Display addComponent(BaseComponent cmp) { if (cmp == null) throw new IllegalArgumentException("le paramètre ne doit pas être null"); finalizeCurrentComponent(); @@ -97,86 +89,70 @@ public class Display { } /** - * Équivalent à nextComponent("\n"), sauf qu'un nouvel appel à nextComponent() est nécessaire après. + * Équivalent à nextComponent("\n"), sauf qu'un nouvel appel à + * nextComponent() est nécessaire après. */ public Display nextLine() { finalizeCurrentComponent(); first.addExtra(new TextComponent("\n")); return this; } - + public Display setColor(ChatColor color) { current.setColor(color); return this; } - + public Display setBold(boolean b) { current.setBold(b); return this; } - + public Display setItalic(boolean i) { current.setItalic(i); return this; } - + public Display setUnderlined(boolean u) { current.setUnderlined(u); return this; } - + public Display setObfuscated(boolean o) { current.setObfuscated(o); return this; } - + public Display setStrikethrough(boolean s) { current.setStrikethrough(s); return this; } - + public Display setHoverText(Display content) { - current.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new BaseComponent[] {content.get()})); + current.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new BaseComponent[] { content.get() })); return this; } - + public Display setClickURL(String url) { current.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, url)); return this; } - + public Display setClickCommand(String cmd) { current.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, cmd)); return this; } - + public Display setClickSuggest(String cmd) { current.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, cmd)); return this; } - - - - - - - - - - - - - - - + private void finalizeCurrentComponent() { - if (current != null) - first.addExtra(current); + if (current != null) first.addExtra(current); current = null; } - - - + public BaseComponent get() { finalizeCurrentComponent(); return first; diff --git a/src/fr/pandacube/java/util/chat_display/DisplayUtil.java b/src/fr/pandacube/java/util/chat_display/DisplayUtil.java index babd4aa..e65e18d 100644 --- a/src/fr/pandacube/java/util/chat_display/DisplayUtil.java +++ b/src/fr/pandacube/java/util/chat_display/DisplayUtil.java @@ -7,217 +7,195 @@ import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.chat.BaseComponent; public class DisplayUtil { - - @SuppressWarnings("serial") - private static Map charList = new HashMap(){{ - put(-6, "§"); - put(2, "!.,:;i|¡"); - put(3, "'`lìí"); - put(4, " I[]tï×"); - put(5, "\"()*<>fk{}"); - put(7, "@~®"); - }}; - + + private static Map charList = new HashMap() { + private static final long serialVersionUID = 1L; + + { + put(-6, "§"); + put(2, "!.,:;i|¡"); + put(3, "'`lìí"); + put(4, " I[]tï×"); + put(5, "\"()*<>fk{}"); + put(7, "@~®"); + } + }; private static final int defaultChatMaxWidth = 320; private static int chatMaxWidth = defaultChatMaxWidth; - + private static final int defaultNbCharPerLineForConsole = 50; private static int nbCharPerLineForConsole = defaultNbCharPerLineForConsole; - + public static final ChatColor COLOR_TITLE = ChatColor.GOLD; public static final ChatColor COLOR_LINK = ChatColor.GREEN; public static final ChatColor COLOR_COMMAND = ChatColor.GRAY; - - - public static BaseComponent createURLLink(String textLink, String url, String hoverText) { - String dispURL = (url.length() > 50) ? (url.substring(0, 48)+"...") : url; - - return new Display() - .nextComponent(textLink) - .setClickURL(url) - .setHoverText(new Display(ChatColor.GRAY+((hoverText == null)?"Cliquez pour accéder au site :":hoverText)+"\n"+ChatColor.GRAY+dispURL)) - .setColor(COLOR_LINK) - .get(); + String dispURL = (url.length() > 50) ? (url.substring(0, 48) + "...") : url; + + return new Display().nextComponent(textLink).setClickURL(url) + .setHoverText(new Display( + ChatColor.GRAY + ((hoverText == null) ? "Cliquez pour accéder au site :" : hoverText) + "\n" + + ChatColor.GRAY + dispURL)) + .setColor(COLOR_LINK).get(); } - - + public static BaseComponent createCommandLink(String textLink, String commandWithSlash, String hoverText) { - Display d = new Display() - .nextComponent(textLink) - .setClickCommand(commandWithSlash) - .setColor(COLOR_COMMAND); - if (hoverText != null) - d.setHoverText(new Display(hoverText)); + Display d = new Display().nextComponent(textLink).setClickCommand(commandWithSlash).setColor(COLOR_COMMAND); + if (hoverText != null) d.setHoverText(new Display(hoverText)); return d.get(); } - - + public static BaseComponent createCommandSuggest(String textLink, String commandWithSlash, String hoverText) { - Display d = new Display() - .nextComponent(textLink) - .setClickSuggest(commandWithSlash) - .setColor(COLOR_COMMAND); - if (hoverText != null) - d.setHoverText(new Display(hoverText)); + Display d = new Display().nextComponent(textLink).setClickSuggest(commandWithSlash).setColor(COLOR_COMMAND); + if (hoverText != null) d.setHoverText(new Display(hoverText)); return d.get(); } - - - public static BaseComponent centerText(BaseComponent text, char repeatedChar, ChatColor decorationColor, boolean console) { - + + public static BaseComponent centerText(BaseComponent text, char repeatedChar, ChatColor decorationColor, + boolean console) { + int textWidth = strWidth(text.toPlainText(), console); - if (textWidth > ((console)?nbCharPerLineForConsole:chatMaxWidth)) return text; - - + if (textWidth > ((console) ? nbCharPerLineForConsole : chatMaxWidth)) return text; + String current = text.toPlainText(); int count = 0; do { count++; current = repeatedChar + current + repeatedChar; - } while (strWidth(current, console) <= ((console)?nbCharPerLineForConsole:chatMaxWidth)); + } while (strWidth(current, console) <= ((console) ? nbCharPerLineForConsole : chatMaxWidth)); count--; - - String finalLeftOrRight = ""; - - for (int i=0; i ((console)?nbCharPerLineForConsole:chatMaxWidth) || textWidth + nbLeft*charW(repeatedChar, console) > ((console)?nbCharPerLineForConsole:chatMaxWidth)) return text; - + if (textWidth > ((console) ? nbCharPerLineForConsole : chatMaxWidth) || textWidth + + nbLeft * charW(repeatedChar, console) > ((console) ? nbCharPerLineForConsole : chatMaxWidth)) + return text; + Display d = new Display(); - + String finalLeft = ""; if (nbLeft > 0) { - for (int i=0; i ((console)?nbCharPerLineForConsole:chatMaxWidth) || textWidth + nbRight*charW(repeatedChar, console) > ((console)?nbCharPerLineForConsole:chatMaxWidth)) return text; - - + if (textWidth > ((console) ? nbCharPerLineForConsole : chatMaxWidth) || textWidth + + nbRight * charW(repeatedChar, console) > ((console) ? nbCharPerLineForConsole : chatMaxWidth)) + return text; + String tempText = text.toPlainText(); if (nbRight > 0) { tempText += decorationColor; - for (int i=0; i= 0) - return px; + for (int px : charList.keySet()) + if (charList.get(px).indexOf(c) >= 0) return px; return 6; } - - - public static void setNbCharPerLineForConsole(int nb) { if (nb < 0) nb = 0; nbCharPerLineForConsole = nb; } + public static void resetNbCharPerLineForConsole() { nbCharPerLineForConsole = defaultNbCharPerLineForConsole; } + public static void setChatMaxWidth(int px) { if (px < 0) px = 0; chatMaxWidth = px; } + public static void resetChatMaxWidth() { chatMaxWidth = defaultChatMaxWidth; } - - + } diff --git a/src/fr/pandacube/java/util/chat_display/TextProgressBar.java b/src/fr/pandacube/java/util/chat_display/TextProgressBar.java index 2344d32..5eb46dd 100644 --- a/src/fr/pandacube/java/util/chat_display/TextProgressBar.java +++ b/src/fr/pandacube/java/util/chat_display/TextProgressBar.java @@ -10,61 +10,54 @@ public class TextProgressBar { private static ChatColor color_default = ChatColor.RESET; private static String pattern_empty = "."; private static String pattern_full = "|"; - - public static String progressBar(double[] values, ChatColor[] colors, double total, int nbCar) - { + + public static String progressBar(double[] values, ChatColor[] colors, double total, int nbCar) { long[] sizes = new long[values.length]; - + int max_size = nbCar - pattern_start.length() - pattern_end.length(); - - for (int i=0; i=0; j--) + for (int j = i; j >= 0; j--) sum_values_before += values[j]; - + long car_position = Math.round(max_size * sum_values_before / total); - - // évite les barre de progressions plus grandes que la taille demandée + + // évite les barre de progressions plus grandes que la taille + // demandée if (car_position > max_size) car_position = max_size; - + long sum_sizes_before = 0; - for (int j = i-1 ; j>=0; j--) + for (int j = i - 1; j >= 0; j--) sum_sizes_before += sizes[j]; - + sizes[i] = car_position - sum_sizes_before; } int sum_sizes = 0; - - - String bar = color_decoration+pattern_start; - for (int i=0; i { - - public LoginHistoryTable() throws SQLException { - super("pandacube_login_history"); - } - - @Override - protected String createTableParameters() { - return "id INT AUTO_INCREMENT PRIMARY KEY," - + "time BIGINT NOT NULL," - + "playerId CHAR(36) NOT NULL," - + "ip VARCHAR(128) NULL," - + "actionType ENUM('LOGIN', 'LOGOUT') NOT NULL," - + "nbOnline INT NOT NULL," - + "playerName VARCHAR(16) NULL," - + "minecraftVersion INT NOT NULL DEFAULT 0"; - } - - @Override - protected LoginHistoryElement getElementInstance(ResultSet sqlResult) throws SQLException { - LoginHistoryElement el = new LoginHistoryElement( - sqlResult.getInt("id"), - sqlResult.getLong("time"), - sqlResult.getString("playerId"), - sqlResult.getString("ip"), - ActionType.valueOf(sqlResult.getString("actionType")), - sqlResult.getInt("nbOnline")); - el.setPlayerName(sqlResult.getString("playerName")); - el.setMinecraftVersion(sqlResult.getInt("minecraftVersion")); - return el; - } - -} diff --git a/src/fr/pandacube/java/util/db/MPGroupElement.java b/src/fr/pandacube/java/util/db/MPGroupElement.java deleted file mode 100644 index 18c09a6..0000000 --- a/src/fr/pandacube/java/util/db/MPGroupElement.java +++ /dev/null @@ -1,63 +0,0 @@ -package fr.pandacube.java.util.db; - -import java.sql.SQLException; -import java.util.List; - -import fr.pandacube.java.util.PlayerFinder; - -public class MPGroupElement extends SQLElement { - - private String groupName; - - - - public MPGroupElement(String name) { - super("pandacube_mp_group"); - setGroupName(name); - } - - protected MPGroupElement(int id, String name) { - super("pandacube_mp_group", id); - setGroupName(name); - } - - - - - - - - @Override - protected String[] getValues() { - return new String[] { - groupName - }; - } - - @Override - protected String[] getFieldsName() { - return new String[] { - "groupName" - }; - } - - - - public String getGroupName() { return groupName; } - - public void setGroupName(String name) { - if (name == null) - throw new NullPointerException(); - if (!PlayerFinder.isValidPlayerName(name)) - throw new IllegalArgumentException("Le nom d'un groupe doit respecter le pattern d'un pseudo valide"); - groupName = name; - } - - - - public List getUsers() throws SQLException { - return ORM.getTable(MPGroupUserTable.class) - .getAll("groupId = "+getId(), "id ASC", null, null); - } - -} diff --git a/src/fr/pandacube/java/util/db/MPGroupTable.java b/src/fr/pandacube/java/util/db/MPGroupTable.java deleted file mode 100644 index 41d1da9..0000000 --- a/src/fr/pandacube/java/util/db/MPGroupTable.java +++ /dev/null @@ -1,26 +0,0 @@ -package fr.pandacube.java.util.db; - -import java.sql.ResultSet; -import java.sql.SQLException; - -public class MPGroupTable extends SQLTable { - - public MPGroupTable() throws SQLException { - super("pandacube_mp_group"); - } - - @Override - protected String createTableParameters() { - return "id INT AUTO_INCREMENT PRIMARY KEY," - + "groupName VARCHAR(16) NOT NULL"; - } - - @Override - protected MPGroupElement getElementInstance(ResultSet sqlResult) - throws SQLException { - return new MPGroupElement( - sqlResult.getInt("id"), - sqlResult.getString("groupName")); - } - -} diff --git a/src/fr/pandacube/java/util/db/MPGroupUserElement.java b/src/fr/pandacube/java/util/db/MPGroupUserElement.java deleted file mode 100644 index d2f4491..0000000 --- a/src/fr/pandacube/java/util/db/MPGroupUserElement.java +++ /dev/null @@ -1,71 +0,0 @@ -package fr.pandacube.java.util.db; - -import java.sql.SQLException; -import java.util.UUID; - -public class MPGroupUserElement extends SQLElement { - - private int groupId; - private String playerId; - - - public MPGroupUserElement(int gId, UUID pId) { - super("pandacube_mp_group_user"); - setGroupId(gId); - setPlayerId(pId); - } - - protected MPGroupUserElement(int id, int gId, String pId) { - super("pandacube_mp_group_user", id); - setGroupId(gId); - setPlayerId(UUID.fromString(pId)); - } - - - - @Override - protected String[] getValues() { - return new String[] { - Integer.toString(groupId), - playerId - }; - } - - @Override - protected String[] getFieldsName() { - return new String[] { - "groupId", - "playerId" - }; - } - - - - - - - - public int getGroupId() { return groupId; } - public UUID getPlayerId() { return UUID.fromString(playerId); } - - public void setGroupId(int gId) { groupId = gId; } - public void setPlayerId(UUID pId) { - if (pId == null) - throw new NullPointerException(); - this.playerId = pId.toString(); - } - - - - - - - public PlayerElement getPlayerElement() throws SQLException { - return ORM.getTable(PlayerTable.class) - .getFirst("playerId LIKE '"+getPlayerId()+"'", "id ASC"); - } - - - - -} diff --git a/src/fr/pandacube/java/util/db/MPGroupUserTable.java b/src/fr/pandacube/java/util/db/MPGroupUserTable.java deleted file mode 100644 index 07a04bf..0000000 --- a/src/fr/pandacube/java/util/db/MPGroupUserTable.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.pandacube.java.util.db; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.UUID; - -public class MPGroupUserTable extends SQLTable { - - public MPGroupUserTable() throws SQLException { - super("pandacube_mp_group_user"); - } - - @Override - protected String createTableParameters() { - return "id INT AUTO_INCREMENT PRIMARY KEY," - + "groupId INT NOT NULL," - + "playerId VARCHAR(36) NOT NULL"; - } - - @Override - protected MPGroupUserElement getElementInstance(ResultSet sqlResult) - throws SQLException { - return new MPGroupUserElement( - sqlResult.getInt("id"), - sqlResult.getInt("groupId"), - sqlResult.getString("playerId")); - } - - - /** - * Retourne l'instance de MPGroupUserElement correcpondant à la présence d'un joueur dans un groupe - * @param group le groupe concerné, sous forme d'instance de MPGroupElement - * @param player l'identifiant du joueur - * @return null si la correspondance n'a pas été trouvée - * @throws SQLException - */ - public MPGroupUserElement getPlayerInGroup(MPGroupElement group, UUID player) throws SQLException { - if (player == null || group == null) return null; - return getFirst("groupId = "+group.getId()+" AND playerId = '"+player+"'", "id"); - } - -} diff --git a/src/fr/pandacube/java/util/db/MPMessageElement.java b/src/fr/pandacube/java/util/db/MPMessageElement.java deleted file mode 100644 index 5283c34..0000000 --- a/src/fr/pandacube/java/util/db/MPMessageElement.java +++ /dev/null @@ -1,177 +0,0 @@ -package fr.pandacube.java.util.db; - -import java.sql.SQLException; -import java.util.UUID; - -/** - * Représente un message dans la base de donnée
- *
- * Les propriétés suivantes doivent être complétés hors constructeur (par défaut null) : - *
    - *
  • destNick
  • - *
  • ou destGroup
  • - *
- * La propriété deleted est défini par défaut à Faux. - * @author Marc Baloup - * - */ -public class MPMessageElement extends SQLElement { - - private long time; - private int securityKey; // permet de différencier deux message, dans le cas où 2 messages ont exactement la même valeur time - private String viewerId; - private String sourceId; - private String destId = null; - private Integer destGroup = null; - private String message; - private boolean wasRead; - private boolean deleted = false; - private boolean serverSync; - - - - public MPMessageElement(long t, int secKey, UUID viewId, UUID srcId, String msg, boolean r, boolean sync) { - super("pandacube_mp_message"); - setTime(t); - setSecurityKey(secKey); - setViewerId(viewId); - setSourceId(srcId); - setMessage(msg); - setRead(r); - setServerSync(sync); - } - - - protected MPMessageElement(int id, long t, int secKey, String viewNick, String srcNick, String msg, boolean r, boolean sync) { - super("pandacube_mp_message", id); - setTime(t); - setSecurityKey(secKey); - setViewerId(UUID.fromString(viewNick)); - setSourceId((srcNick == null) ? null : UUID.fromString(srcNick)); - setMessage(msg); - setRead(r); - setServerSync(sync); - } - - - - - - - - - - - - - - - - - - - @Override - protected String[] getValues() { - return new String[] { - Long.toString(time), - Integer.toString(securityKey), - viewerId, - sourceId, - destId, - (destGroup==null)?null:destGroup.toString(), - message, - (wasRead)?"1":"0", - (deleted)?"1":"0", - (serverSync)?"1":"0" - }; - } - - - - - @Override - protected String[] getFieldsName() { - return new String[] { - "time", - "securityKey", - "viewerId", - "sourceId", - "destId", - "destGroup", - "message", - "wasRead", - "deleted", - "serverSync" - }; - } - - - public long getTime() { return time; } - public int getSecurityKey() { return securityKey; } - public UUID getViewerId() { return UUID.fromString(viewerId); } - public UUID getSourceId() { - if (sourceId == null) return null; - return UUID.fromString(sourceId); - } - public UUID getDestId() { - if (destId == null) return null; - return UUID.fromString(destId); - } - public Integer getDestGroup() { return destGroup; } - public String getMessage() { return message; } - public boolean isRead() { return wasRead; } - public boolean isDeleted() { return deleted; } - public boolean isServerSync() { return serverSync; } - - - - - public void setTime(long t) { time = t; } - public void setSecurityKey(int secKey) { securityKey = secKey; } - - public void setViewerId(UUID viewId) { - if (viewId == null) - throw new NullPointerException(); - viewerId = viewId.toString(); - } - - public void setSourceId(UUID srcId) { - if (srcId == null) sourceId = null; - else sourceId = srcId.toString(); - } - - public void setDestId(UUID destId) { - if (destId == null) this.destId = null; - else { - this.destId = destId.toString(); - destGroup = null; - } - } - - public void setDestGroup(Integer destGroup) { - this.destGroup = destGroup; - if (destGroup != null) - destId = null; - } - - public void setMessage(String msg) { - if (msg == null) - throw new NullPointerException(); - message = msg; - } - - public void setRead(boolean r) { wasRead = r; } - public void setDeleted(boolean del) { deleted = del; } - public void setServerSync(boolean sync) { serverSync = sync; } - - - - - - public MPGroupElement getDestGroupElement() throws SQLException { - if (getDestGroup() == null) return null; - - return ORM.getTable(MPGroupTable.class).get(getDestGroup()); - } - -} diff --git a/src/fr/pandacube/java/util/db/MPMessageTable.java b/src/fr/pandacube/java/util/db/MPMessageTable.java deleted file mode 100644 index 8239d5d..0000000 --- a/src/fr/pandacube/java/util/db/MPMessageTable.java +++ /dev/null @@ -1,99 +0,0 @@ -package fr.pandacube.java.util.db; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.List; -import java.util.UUID; - -import fr.pandacube.java.util.PlayerFinder; - -public class MPMessageTable extends SQLTable { - - public MPMessageTable() throws SQLException { - super("pandacube_mp_message"); - } - - @Override - protected String createTableParameters() { - return "id INT AUTO_INCREMENT PRIMARY KEY," - + "time BIGINT NOT NULL," - + "securityKey INT NOT NULL," - + "viewerId VARCHAR(36) NOT NULL," - + "sourceId VARCHAR(36) NULL," // Null si la source est la console ou une autre entité qu'un joueur - + "destId VARCHAR(36) NULL," - + "destGroup INT NULL," - + "message VARCHAR(512) NOT NULL," - + "wasRead TINYINT NOT NULL," - + "deleted TINYINT NOT NULL," - + "serverSync TINYINT NOT NULL"; - } - - @Override - protected MPMessageElement getElementInstance(ResultSet sqlResult) - throws SQLException { - MPMessageElement el = new MPMessageElement( - sqlResult.getInt("id"), - sqlResult.getLong("time"), - sqlResult.getInt("securityKey"), - sqlResult.getString("viewerId"), - sqlResult.getString("sourceId"), - sqlResult.getString("message"), - sqlResult.getBoolean("wasRead"), - sqlResult.getBoolean("serverSync")); - String destId = sqlResult.getString("destId"); - el.setDestId(destId==null ? null : UUID.fromString(destId)); - - int group = sqlResult.getInt("destGroup"); - el.setDestGroup(sqlResult.wasNull()?null:group); - - el.setDeleted(sqlResult.getBoolean("deleted")); - - return el; - } - - - - - - public List getAllUnsyncMessage() throws SQLException { - return getAll("serverSync = 0", "time ASC", null, null); - } - - - - public List getAllUnreadForPlayer(UUID player) throws SQLException { - return getForPlayer(player, true, null, false); - } - - - public List getOneDiscussionForPlayer(UUID player, Object discussion, Integer numberLast, boolean revert) throws SQLException { - 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; - - String where = "viewerId = '"+player+"'"; - if (discussion == null) - where += " AND sourceId IS NULL AND destGroup IS NULL"; - else if (discussion instanceof String) - where += " AND destGroup IN (SELECT id FROM "+ORM.getTable(MPGroupTable.class).getTableName()+" WHERE groupName LIKE '"+discussion+"')"; - else if (discussion instanceof UUID && discussion.equals(player)) - where += " AND destId LIKE '"+discussion+"' AND sourceId LIKE '"+discussion+"' AND destGroup IS NULL"; - else // discussion instanceof UUID - where += " AND (destId LIKE '"+discussion+"' OR sourceId LIKE '"+discussion+"') AND destGroup IS NULL"; - - return getAll(where, (revert)?"time DESC":"time ASC", numberLast, null); - } - - - public List getForPlayer(UUID player, boolean onlyUnread, Integer numberLast, boolean revert) throws SQLException { - if (player == null) return null; - - String where = "viewerId = '"+player+"'"; - if (onlyUnread) - where += " AND wasRead = 0"; - - return getAll(where, (revert)?"time DESC":"time ASC", numberLast, null); - } - - -} diff --git a/src/fr/pandacube/java/util/db/ModoHistoryElement.java b/src/fr/pandacube/java/util/db/ModoHistoryElement.java deleted file mode 100644 index 2f20bf3..0000000 --- a/src/fr/pandacube/java/util/db/ModoHistoryElement.java +++ /dev/null @@ -1,141 +0,0 @@ -package fr.pandacube.java.util.db; - -import java.util.UUID; - -public class ModoHistoryElement extends SQLElement { - - private String modoId = null; - private ActionType actionType; - private long time; - private String playerId; - private Long value = null; - private String message; - - - public ModoHistoryElement(UUID modo, ActionType type, UUID player, String message) { - super("pandacube_modo_history"); - setModoId(modo); - setActionType(type); - setPlayerId(player); - setMessage(message); - time = System.currentTimeMillis(); - } - - ModoHistoryElement(int id, String modo, ActionType type, String player, String message) { - super("pandacube_modo_history", id); - setModoId((modo == null)?null:UUID.fromString(modo)); - setActionType(type); - setPlayerId(UUID.fromString(player)); - setMessage(message); - time = System.currentTimeMillis(); - } - - @Override - protected String[] getValues() { - return new String[] { - modoId, - actionType.name(), - String.valueOf(time), - playerId, - (value == null)?null:value.toString(), - message - }; - } - - @Override - protected String[] getFieldsName() { - return new String[] { - "modoId", - "actionType", - "time", - "playerId", - "value", - "message" - }; - } - - - - public UUID getModoId() { - return modoId == null ? null : UUID.fromString(modoId); - } - - public void setModoId(UUID modo) { - this.modoId = modo == null ? null : modo.toString(); - } - - - - public ActionType getActionType() { - return actionType; - } - - public void setActionType(ActionType actionType) { - if (actionType == null) throw new IllegalArgumentException("le paramètre ne peut être null"); - this.actionType = actionType; - } - - - /** - * Retourne la durée de la sanction appliquée (en secondes), ou la somme d'argent retirée du compte - * @return - */ - public long getValue() { - return value; - } - - /** - * Value correspond soit à la durée de la sanction appliquée (en secondes), soit à la valeur de l'amende appliquée - * @param value - */ - public void setValue(Long value) { - if (value != null && value.longValue() < 0) value = null; - this.value = value; - } - - - - public UUID getPlayerId() { - return UUID.fromString(playerId); - } - - public void setPlayerId(UUID player) { - if (player == null) throw new IllegalArgumentException("le paramètre ne peut être null"); - this.playerId = player.toString(); - } - - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - if (message == null) throw new IllegalArgumentException("le paramètre ne peut être null"); - this.message = message; - } - - - - - - - - public long getTime() { - return time; - } - - public void setTime(long time) { - this.time = time; - } - - - - - - - - public enum ActionType{ - BAN, UNBAN, MUTE, UNMUTE, REPORT, KICK - } - -} diff --git a/src/fr/pandacube/java/util/db/ModoHistoryTable.java b/src/fr/pandacube/java/util/db/ModoHistoryTable.java deleted file mode 100644 index 1ca4e36..0000000 --- a/src/fr/pandacube/java/util/db/ModoHistoryTable.java +++ /dev/null @@ -1,40 +0,0 @@ -package fr.pandacube.java.util.db; - -import java.sql.ResultSet; -import java.sql.SQLException; - -import fr.pandacube.java.util.db.ModoHistoryElement.ActionType; - -public class ModoHistoryTable extends SQLTable { - - - - public ModoHistoryTable() throws SQLException { - super("pandacube_modo_history"); - } - - @Override - protected String createTableParameters() { - return "id INT AUTO_INCREMENT PRIMARY KEY," - + "modoId CHAR(36) NULL," // null si c'est la console - + "actionType ENUM('BAN', 'UNBAN', 'MUTE', 'UNMUTE', 'REPORT', 'KICK') NOT NULL," - + "time BIGINT NOT NULL," - + "playerId CHAR(36) NOT NULL," - + "value BIGINT NULL," - + "message VARCHAR(512) NOT NULL"; - } - - @Override - protected ModoHistoryElement getElementInstance(ResultSet sqlResult) throws SQLException { - ModoHistoryElement el = new ModoHistoryElement( - sqlResult.getInt("id"), - sqlResult.getString("modoId"), - ActionType.valueOf(sqlResult.getString("actionType")), - sqlResult.getString("playerId"), - sqlResult.getString("message")); - el.setValue(sqlResult.getLong("value")); - el.setTime(sqlResult.getLong("time")); - return el; - } - -} diff --git a/src/fr/pandacube/java/util/db/ORM.java b/src/fr/pandacube/java/util/db/ORM.java deleted file mode 100644 index aa6ecde..0000000 --- a/src/fr/pandacube/java/util/db/ORM.java +++ /dev/null @@ -1,97 +0,0 @@ -package fr.pandacube.java.util.db; - -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 : - *
    - *
  • LoginHistoryTable
  • - *
  • ModoHistoryTable
  • - *
  • StaffTicketTable
  • - *
  • MPMessageTable
  • - *
  • MPGroupTable
  • - *
  • MPGroupUserTable
  • - *
  • MPWebSessionTable
  • - *
  • PlayerIgnoreTable
  • - *
- * @author Marc Baloup - * - */ -public final class ORM { - - private static List> tables = new ArrayList>(); - - /* package */ static DBConnection connection; - - - public synchronized static void init(DBConnection conn) { - try { - - connection = conn; - /* - * Les tables SQL sont à instancier ici ! - */ - - tables.add(new LoginHistoryTable()); - - tables.add(new ModoHistoryTable()); - - tables.add(new MPGroupTable()); - tables.add(new MPGroupUserTable()); - tables.add(new MPMessageTable()); - - tables.add(new OnlineShopHistoryTable()); - - tables.add(new PlayerTable()); - - tables.add(new PlayerIgnoreTable()); - - tables.add(new ShopStockTable()); - - tables.add(new StaffTicketTable()); - - - } catch (SQLException e) { - e.printStackTrace(); - } - } - - - - - - public synchronized static > T getTable(Class c) { - if (c == null) return null; - for (SQLTable table : tables) { - - if (c.isAssignableFrom(table.getClass())) { - return c.cast(table); - } - } - return null; - } - - - - - - - - - private ORM() { } // rend la classe non instanciable - - - - - - - - - - -} diff --git a/src/fr/pandacube/java/util/db/OnlineShopHistoryElement.java b/src/fr/pandacube/java/util/db/OnlineShopHistoryElement.java deleted file mode 100644 index ac148af..0000000 --- a/src/fr/pandacube/java/util/db/OnlineShopHistoryElement.java +++ /dev/null @@ -1,129 +0,0 @@ -package fr.pandacube.java.util.db; - -import java.util.UUID; - -public class OnlineShopHistoryElement extends SQLElement { - - - private long time;// timestamp en millisecondes - private String transactionId; - private SourceType sourceType;// enum(REAL_MONEY, BAMBOU) - private String sourcePlayerId;// l'id du joueur duquel vient l'élément source - private double sourceQuantity;// la quantité d'entrée (en euro, ou bambou) - private String sourceName;// le nom désignant la source ("euro", "bambou", ...) - private DestType destType;// enum(BAMBOU, GRADE) - private String destPlayerId;// l'id du joueur qui reçoit l'élément obtenu après cette transaction - private double destQuantity;// la quantité de sortie (bambou, ou 1 pour l'achat d'un grade) - private String destName;// le nom désignant la destination ("bambou", le nom du grade) - - public OnlineShopHistoryElement(long t, SourceType st, double sQtt, String sN, DestType dt, UUID dPID, double dQtt, String dN) { - super("pandacube_onlineshop_history"); - setTime(t); - setSourceType(st); - setSourceQuantity(sQtt); - setSourceName(sN); - setDestType(dt); - setDestPlayerId(dPID); - setDestQuantity(dQtt); - setDestName(dN); - } - - OnlineShopHistoryElement(int id, long t, String st, double sQtt, String sN, String dt, String dPID, double dQtt, String dN) { - super("pandacube_onlineshop_history", id); - setTime(t); - setSourceType(SourceType.valueOf(st)); - setSourceQuantity(sQtt); - setSourceName(sN); - setDestType(DestType.valueOf(dt)); - destPlayerId = dPID; - setDestQuantity(dQtt); - setDestName(dN); - } - - @Override - protected String[] getValues() { - return new String[] { - Long.toString(time), - transactionId, - sourceType.name(), - sourcePlayerId, - Double.toString(sourceQuantity), - sourceName, - destType.name(), - destPlayerId, - Double.toString(destQuantity), - destName - - }; - } - - @Override - protected String[] getFieldsName() { - return new String[] { - "time", - "transactionId", - "sourceType", - "sourcePlayerId", - "sourceQuantity", - "sourceName", - "destType", - "destPlayerId", - "destQuantity", - "destName" - }; - } - - - public long getTime() { return time; } - public String getTransactionId() { return transactionId; } - public SourceType getSourceType() { return sourceType; } - public UUID getSourcePlayerId() { return UUID.fromString(sourcePlayerId); } - public double getSourceQuantity() { return sourceQuantity; } - public String getSourceName() { return sourceName; } - public DestType getDestType() { return destType; } - public UUID getDestPlayerId() { return UUID.fromString(destPlayerId); } - public double getDestQuantity() { return destQuantity; } - public String getDestName() { return destName; } - - - - - - - - public void setTime(long t) { time = t; } - public void setTransactionId(String t) { transactionId = t; } - public void setSourceType(SourceType st) { - if (st == null) throw new IllegalArgumentException("sourceType can't be null"); - sourceType = st; - } - public void setSourcePlayerId(UUID pId) { sourcePlayerId = pId.toString(); } - public void setSourceQuantity(double qtt) { sourceQuantity = qtt; } - public void setSourceName(String name) { - if (name == null) throw new IllegalArgumentException("sourceName can't be null"); - sourceName = name; - } - public void setDestType(DestType st) { - if (st == null) throw new IllegalArgumentException("destType can't be null"); - destType = st; - } - public void setDestPlayerId(UUID pId) { - if (pId == null) throw new IllegalArgumentException("destPlayerId can't be null"); - destPlayerId = pId.toString(); - } - public void setDestQuantity(double qtt) { destQuantity = qtt; } - public void setDestName(String name) { - if (name == null) throw new IllegalArgumentException("destName can't be null"); - destName = name; - } - - - public static enum SourceType { - REAL_MONEY, BAMBOU - } - - public static enum DestType { - BAMBOU, GRADE - } - -} diff --git a/src/fr/pandacube/java/util/db/OnlineShopHistoryTable.java b/src/fr/pandacube/java/util/db/OnlineShopHistoryTable.java deleted file mode 100644 index d95dfeb..0000000 --- a/src/fr/pandacube/java/util/db/OnlineShopHistoryTable.java +++ /dev/null @@ -1,47 +0,0 @@ -package fr.pandacube.java.util.db; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.UUID; - -public class OnlineShopHistoryTable extends SQLTable { - - public OnlineShopHistoryTable() throws SQLException { - super("pandacube_onlineshop_history"); - } - - @Override - protected String createTableParameters() { - return "id INT AUTO_INCREMENT PRIMARY KEY," - + "time BIGINT NOT NULL," - + "transactionId VARCHAR(255) NULL," - + "sourceType ENUM('REAL_MONEY', 'BAMBOU') NOT NULL," - + "sourcePlayerId CHAR(36) NULL," - + "sourceQuantity DOUBLE NOT NULL," - + "sourceName VARCHAR(64) NOT NULL," - + "destType ENUM('BAMBOU', 'GRADE') NOT NULL," - + "destPlayerId CHAR(36) NOT NULL," - + "destQuantity DOUBLE NOT NULL," - + "destName VARCHAR(64) NOT NULL"; - } - - @Override - protected OnlineShopHistoryElement getElementInstance(ResultSet sqlResult) throws SQLException { - OnlineShopHistoryElement el = new OnlineShopHistoryElement( - sqlResult.getInt("id"), - sqlResult.getLong("time"), - sqlResult.getString("sourceType"), - sqlResult.getDouble("sourceQuantity"), - sqlResult.getString("sourceName"), - sqlResult.getString("destType"), - sqlResult.getString("destPlayerId"), - sqlResult.getDouble("destQuantity"), - sqlResult.getString("destName")); - el.setTransactionId(sqlResult.getString("transactionId")); - String sourcePlayerId = sqlResult.getString("sourcePlayerId"); - if (sourcePlayerId != null) - el.setSourcePlayerId(UUID.fromString(sourcePlayerId)); - return el; - } - -} diff --git a/src/fr/pandacube/java/util/db/PlayerElement.java b/src/fr/pandacube/java/util/db/PlayerElement.java deleted file mode 100644 index 8dd21f0..0000000 --- a/src/fr/pandacube/java/util/db/PlayerElement.java +++ /dev/null @@ -1,179 +0,0 @@ -package fr.pandacube.java.util.db; - -import java.sql.Date; -import java.util.UUID; - -public class PlayerElement extends SQLElement { - - private String playerId; - private String token = null; - private String mailCheck = null; - private String password = null; - private String mail = null; - private String playerDisplayName; - private long firstTimeInGame; - private long timeWebRegister = 0; - private long lastTimeInGame = 0; - private long lastWebActivity = 0; - private String onlineInServer = null; - private String skinURL = null; - private boolean isVanish = false; - private Date birthday = null; - private int lastYearCelebratedBirthday = 0; - private Long banTimeout = null; - private Long muteTimeout = null; - private boolean isWhitelisted = false; - private long bambou = 0; - private String grade = "default"; - - public PlayerElement(UUID pId, String dispName, long firstTimeIG, long lastWebAct, String onlineInServer) { - super("pandacube_player"); - setPlayerId(pId); - setOnlineInServer(onlineInServer); - setLastWebActivity(lastWebAct); - setPlayerDisplayName(dispName); - setFirstTimeInGame(firstTimeIG); - } - - PlayerElement(int id, String pId, String dispName, long firstTimeIG, long lastWebAct, String onlineInServer) { - super("pandacube_player", id); - setPlayerId(UUID.fromString(pId)); - setOnlineInServer(onlineInServer); - setLastWebActivity(lastWebAct); - setPlayerDisplayName(dispName); - setFirstTimeInGame(firstTimeIG); - } - - @Override - protected String[] getValues() { - return new String[] { - playerId, - token, - mailCheck, - password, - mail, - playerDisplayName, - Long.toString(firstTimeInGame), - Long.toString(timeWebRegister), - Long.toString(lastTimeInGame), - Long.toString(lastWebActivity), - onlineInServer, - skinURL, - isVanish?"1":"0", - (birthday!=null)?birthday.toString():null, - Integer.toString(lastYearCelebratedBirthday), - (banTimeout!=null)?banTimeout.toString():null, - (muteTimeout!=null)?muteTimeout.toString():null, - isWhitelisted?"1":"0", - Long.toString(bambou), - grade - }; - } - - @Override - protected String[] getFieldsName() { - return new String[] { - "playerId", - "token", - "mailCheck", - "password", - "mail", - "playerDisplayName", - "firstTimeInGame", - "timeWebRegister", - "lastTimeInGame", - "lastWebActivity", - "onlineInServer", - "skinURL", - "isVanish", - "birthday", - "lastYearCelebratedBirthday", - "banTimeout", - "muteTimeout", - "isWhitelisted", - "bambou", - "grade" - }; - } - - public UUID getPlayerId() { return UUID.fromString(playerId); } - public UUID getToken() { return (token == null) ? null : UUID.fromString(token); } - public String getMailCheck() { return mailCheck; } - public String getPasswordHash() { return password; } - public String getMail() { return mail; } - public long getFirstTimeInGame() { return firstTimeInGame; } - public long getTimeWebRegister() { return timeWebRegister; } - public long getLastTimeInGame() { return lastTimeInGame; } - public long getLastWebActivity() { return lastWebActivity; } - public String getOnlineInServer() { return onlineInServer; } - public String getPlayerDisplayName() { return playerDisplayName; } - public String getSkinURL() { return skinURL; } - public boolean isVanish() { return isVanish; } - public Date getBirthday() { return birthday; } - public int getLastYearCelebratedBirthday() { return lastYearCelebratedBirthday; } - public Long getBanTimeout() { return banTimeout; } - public Long getMuteTimeout() { return muteTimeout; } - public boolean isWhitelisted() { return isWhitelisted; } - public long getBambou() { return bambou; } - public String getGrade() { return grade; } - - - - public void setPlayerId(UUID pName) { - if (pName == null) - throw new NullPointerException(); - playerId = pName.toString(); - } - - public void setToken(UUID t) { - if (t == null) - token = null; - else - token = t.toString(); - } - - public void setMailCheck(String mCheck) { mailCheck = mCheck; } - - public void setPasswordHash(String pass) { password = pass; } - - public void setMail(String m) { mail = m; } - - public void setFirstTimeInGame(long time) { firstTimeInGame = time; } - - public void setTimeWebRegister(long time) { timeWebRegister = time; } - - public void setLastTimeInGame(long time) { lastTimeInGame = time; } - - public void setLastWebActivity(long time) { lastWebActivity = time; } - - public void setOnlineInServer(String onlineInServer) { this.onlineInServer = onlineInServer; } - - public void setSkinURL(String skinURL) { this.skinURL = skinURL; } - - public void setPlayerDisplayName(String dispName) { - if (dispName == null) - throw new NullPointerException(); - playerDisplayName = dispName; - } - - public void setVanish(boolean v) { isVanish = v; } - - public void setBirthday(Date b) { birthday = b; } - - public void setLastYearCelebratedBirthday(int y) { lastYearCelebratedBirthday = y; } - - public void setBanTimeout(Long banT) { banTimeout = banT; } - - public void setMuteTimeout(Long muteT) { muteTimeout = muteT; } - - public void setWhitelisted(boolean w) { isWhitelisted = w; } - - public void setBambou(long b) { bambou = b; } - - public void setGrade(String g) { - if (g == null || g.equals("")) - g = "default"; - grade = g; - } - -} diff --git a/src/fr/pandacube/java/util/db/PlayerIgnoreElement.java b/src/fr/pandacube/java/util/db/PlayerIgnoreElement.java deleted file mode 100644 index 1b560bc..0000000 --- a/src/fr/pandacube/java/util/db/PlayerIgnoreElement.java +++ /dev/null @@ -1,66 +0,0 @@ -package fr.pandacube.java.util.db; - -import java.util.UUID; - -public class PlayerIgnoreElement extends SQLElement { - - private String ignore; - private String ignored; - - - public PlayerIgnoreElement(UUID ignore, UUID ignored) { - super("pandacube_player_ignore"); - setIgnore(ignore); - setIgnored(ignored); - } - - - protected PlayerIgnoreElement(int id, String ignore, String ignored) { - super("pandacube_player_ignore", id); - this.ignore = ignore; - this.ignored = ignored; - } - - - @Override - protected String[] getValues() { - return new String[] { - ignore, - ignored - }; - } - - - @Override - protected String[] getFieldsName() { - return new String[] { - "ignorer", - "ignored" - }; - } - - - public UUID getIgnore() { - return UUID.fromString(ignore); - } - - - public void setIgnore(UUID i) { - if (i == null) - throw new IllegalArgumentException("i can't be null"); - ignore = i.toString(); - } - - - public UUID getIgnored() { - return UUID.fromString(ignored); - } - - - public void setIgnored(UUID i) { - if (i == null) - throw new IllegalArgumentException("i can't be null"); - ignored = i.toString(); - } - -} diff --git a/src/fr/pandacube/java/util/db/PlayerIgnoreTable.java b/src/fr/pandacube/java/util/db/PlayerIgnoreTable.java deleted file mode 100644 index 0636058..0000000 --- a/src/fr/pandacube/java/util/db/PlayerIgnoreTable.java +++ /dev/null @@ -1,79 +0,0 @@ -package fr.pandacube.java.util.db; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -public class PlayerIgnoreTable extends SQLTable { - - public PlayerIgnoreTable() throws SQLException { - super("pandacube_player_ignore"); - } - - @Override - protected String createTableParameters() { - return "id INT AUTO_INCREMENT PRIMARY KEY," - + "ignorer CHAR(36) NOT NULL," - + "ignored CHAR(36) NOT NULL"; - } - - @Override - protected PlayerIgnoreElement getElementInstance(ResultSet sqlResult) throws SQLException { - return new PlayerIgnoreElement(sqlResult.getInt("id"), - sqlResult.getString("ignorer"), - sqlResult.getString("ignored")); - } - - - - public List getListIgnoredPlayer(UUID ignore) throws SQLException { - if (ignore == null) - throw new IllegalArgumentException("ignore can't be null"); - - List dbIgnored = getAll("ignorer = '"+ignore+"'", "id", null, null); - - List ret = new ArrayList(); - - for (PlayerIgnoreElement el : dbIgnored) { - ret.add(el.getIgnored()); - } - - return ret; - - } - - - public boolean isPlayerIgnoringPlayer(UUID ignore, UUID ignored) throws SQLException { - if (ignore == null) - throw new IllegalArgumentException("ignore can't be null"); - if (ignored == null) - throw new IllegalArgumentException("ignored can't be null"); - - return getFirst("ignorer = '"+ignore+"' AND ignored = '"+ignored+"'", "id") != null; - - } - - - public void setPlayerIgnorePlayer(UUID ignore, UUID ignored, boolean set) throws SQLException { - if (ignore == null) - throw new IllegalArgumentException("ignore can't be null"); - if (ignored == null) - throw new IllegalArgumentException("ignored can't be null"); - if (ignore.equals(ignored)) // on ne peut pas s'auto ignorer - return; - - PlayerIgnoreElement el = getFirst("ignorer = '"+ignore+"' AND ignored = '"+ignored+"'", "id"); - - if (set && el == null) { - el = new PlayerIgnoreElement(ignore, ignored); - el.save(); - } - else if (!set && el != null) { - el.delete(); - } - - } - -} diff --git a/src/fr/pandacube/java/util/db/PlayerTable.java b/src/fr/pandacube/java/util/db/PlayerTable.java deleted file mode 100644 index 00712fc..0000000 --- a/src/fr/pandacube/java/util/db/PlayerTable.java +++ /dev/null @@ -1,74 +0,0 @@ -package fr.pandacube.java.util.db; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.UUID; - -public class PlayerTable extends SQLTable { - - public PlayerTable() throws SQLException { - super("pandacube_player"); - } - - @Override - protected String createTableParameters() { - return "id INT AUTO_INCREMENT PRIMARY KEY," - + "playerId CHAR(36) NOT NULL," - + "token CHAR(36) NULL," - + "mailCheck VARCHAR(255) NULL," - + "password VARCHAR(255) NULL," - + "mail VARCHAR(255) NULL," - + "playerDisplayName VARCHAR(255) NOT NULL," - + "firstTimeInGame BIGINT NOT NULL," - + "timeWebRegister BIGINT NULL," - + "lastTimeInGame BIGINT NULL," - + "lastWebActivity BIGINT NOT NULL," - + "onlineInServer VARCHAR(32) NULL," - + "skinURL VARCHAR(255) NULL," - + "isVanish TINYINT NULL," - + "birthday DATE NULL," - + "lastYearCelebratedBirthday INT NOT NULL DEFAULT 0," - + "banTimeout BIGINT NULL," - + "muteTimeout BIGINT NULL," - + "isWhitelisted TINYINT NOT NULL DEFAULT 0," - + "bambou BIGINT NOT NULL DEFAULT 0," - + "grade VARCHAR(36) NOT NULL DEFAULT 'default'"; - } - - @Override - protected PlayerElement getElementInstance(ResultSet sqlResult) - throws SQLException { - PlayerElement el = new PlayerElement( - sqlResult.getInt("id"), - sqlResult.getString("playerId"), - sqlResult.getString("playerDisplayName"), - sqlResult.getLong("firstTimeInGame"), - sqlResult.getLong("lastWebActivity"), - sqlResult.getString("onlineInServer")); - String token = sqlResult.getString("token"); - el.setToken((token == null) ? null : UUID.fromString(token)); - el.setMailCheck(sqlResult.getString("mailCheck")); - el.setPasswordHash(sqlResult.getString("password")); - el.setMail(sqlResult.getString("mail")); - el.setFirstTimeInGame(sqlResult.getLong("firstTimeInGame")); - el.setTimeWebRegister(sqlResult.getLong("timeWebRegister")); - el.setLastTimeInGame(sqlResult.getLong("lastTimeInGame")); - el.setSkinURL(sqlResult.getString("skinURL")); - el.setVanish(sqlResult.getBoolean("isVanish")); - el.setBirthday(sqlResult.getDate("birthday")); - el.setLastYearCelebratedBirthday(sqlResult.getInt("lastYearCelebratedBirthday")); - el.setBambou(sqlResult.getLong("bambou")); - el.setGrade(sqlResult.getString("grade")); - - long longVal; - - longVal = sqlResult.getLong("banTimeout"); - el.setBanTimeout(sqlResult.wasNull()?null:longVal); - longVal = sqlResult.getLong("muteTimeout"); - el.setMuteTimeout(sqlResult.wasNull()?null:longVal); - - el.setWhitelisted(sqlResult.getBoolean("isWhitelisted")); - return el; - } - -} diff --git a/src/fr/pandacube/java/util/db/SQLElement.java b/src/fr/pandacube/java/util/db/SQLElement.java deleted file mode 100644 index 9dd26a4..0000000 --- a/src/fr/pandacube/java/util/db/SQLElement.java +++ /dev/null @@ -1,162 +0,0 @@ -package fr.pandacube.java.util.db; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -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; - - - private boolean saved = false; - - protected final String tableName; - - // champ relatif aux données - private int id = 0; - - - - public SQLElement(String name) { - tableName = name; - saved = false; - } - protected SQLElement(String name, int id) { - tableName = name; - this.id = id; - saved = true; - } - - - - - - public void save() { - - try { - Connection conn; - conn = db.getNativeConnection(); - - String[] fields = getFieldsName(), values = getValues(); - - - - if (saved) - { // mettre à jour les valeurs dans la base - String sql = ""; - for (int i=0; i 0) - sql = sql.substring(0, sql.length()-1); - - PreparedStatement st = conn.prepareStatement("UPDATE "+tableName+" SET "+sql+" WHERE id="+id); - try { - for (int i=0; iid - * @return les valeurs des champs sous la forme de chaine de caractères - */ - protected abstract String[] getValues(); - - - - /** - * Récupère la liste des noms des champs de la table correspondante, excepté - * le champ id - * @return les noms des champs sous la forme de chaine de caractères - */ - protected abstract String[] getFieldsName(); -} diff --git a/src/fr/pandacube/java/util/db/SQLTable.java b/src/fr/pandacube/java/util/db/SQLTable.java deleted file mode 100644 index 7d9ca17..0000000 --- a/src/fr/pandacube/java/util/db/SQLTable.java +++ /dev/null @@ -1,142 +0,0 @@ -package fr.pandacube.java.util.db; - -import java.sql.ResultSet; -import java.sql.SQLException; -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; - - private final String tableName; - - - public SQLTable(String name) throws SQLException { - tableName = name; - - if (!tableExist()) - createTable(); - - - } - - - private void createTable() throws SQLException { - Statement stmt = db.getNativeConnection().createStatement(); - String sql = "CREATE TABLE IF NOT EXISTS "+tableName+" " + - "("+createTableParameters()+")"; - try { - stmt.executeUpdate(sql); - } finally { - stmt.close(); - } - } - - - private boolean tableExist() throws SQLException { - ResultSet set = null; - boolean exist = false; - try { - set = db.getNativeConnection().getMetaData().getTables(null, null, tableName, null); - exist = set.next(); - } finally { - if (set != null) - set.close(); - } - return exist; - } - - - /** - * Retourne une chaine de caractère qui sera inclu dans la requête SQL de création de la table. - * La requête est de la forme : CRATE TABLE tableName (); - * La chaine retournée sera ajoutée entre les parenthèses. - */ - protected abstract String createTableParameters(); - - - - /** - * Crée une instance de l'élément courant se trouvant dans le resultSet passé en paramètre - * @param sqlResult le set de résultat, déjà positionné sur un élément. Ne surtout pas appeler la méthode next() ! - * @return - * @throws SQLException - */ - protected abstract T getElementInstance(ResultSet sqlResult) throws SQLException; - - - - - public String getTableName() { - return tableName; - } - - - - public T get(int id) throws SQLException { - T elementInstance = null; - Statement stmt = db.getNativeConnection().createStatement(); - try { - String sql = "SELECT * FROM "+tableName+" WHERE id = "+id+";"; - - ResultSet set = stmt.executeQuery(sql); - try { - if (set.next()) - elementInstance = getElementInstance(set); - } finally { - set.close(); - } - } finally { - stmt.close(); - } - return elementInstance; - } - - - - public List getAll() throws SQLException { - return getAll(null, null, null, null); - } - - - - public T getFirst(String where, String orderBy) throws SQLException { - List elts = getAll(where, orderBy, 1, null); - return (elts.size() == 0)? null : elts.get(0); - } - - - public List getAll(String where, String orderBy, Integer limit, Integer offset) throws SQLException { - Statement stmt = db.getNativeConnection().createStatement(); - String sql = "SELECT * FROM "+tableName; - - if (where != null) - sql += " WHERE "+where; - if (orderBy != null) - sql += " ORDER BY "+orderBy; - if (limit != null) - sql += " LIMIT "+limit; - if (offset != null) - sql += " OFFSET "+offset; - sql += ";"; - - List elmts = new ArrayList(); - try { - ResultSet set = stmt.executeQuery(sql); - try { - while (set.next()) - elmts.add(getElementInstance(set)); - } finally { - set.close(); - } - } finally { - stmt.close(); - } - return elmts; - } - -} diff --git a/src/fr/pandacube/java/util/db/ShopStockElement.java b/src/fr/pandacube/java/util/db/ShopStockElement.java deleted file mode 100644 index 29f421a..0000000 --- a/src/fr/pandacube/java/util/db/ShopStockElement.java +++ /dev/null @@ -1,74 +0,0 @@ -package fr.pandacube.java.util.db; - -public class ShopStockElement extends SQLElement { - - private String material; - private short damage = 0; - private double quantity; - private String server; - - - public ShopStockElement(String m, short d, double q, String s) { - super("pandacube_shop_stock"); - setMaterial(m); - setDamage(d); - setQuantity(q); - setServer(s); - } - - protected ShopStockElement(int id, String m, short d, double q, String s) { - super("pandacube_shop_stock", id); - setMaterial(m); - setDamage(d); - setQuantity(q); - setServer(s); - } - - @Override - protected String[] getValues() { - return new String[] { - material, - Short.toString(damage), - Double.toString(quantity), - server - }; - } - - @Override - protected String[] getFieldsName() { - return new String[] { - "material", - "damage", - "quantity", - "server" - }; - } - - public String getMaterial() { return material; } - - public void setMaterial(String m) { - if (m == null) throw new IllegalArgumentException("Material can't be null"); - material = m; - } - - public short getDamage() { return damage; } - - public void setDamage(short d) { - damage = d; - } - - public double getQuantity() { return quantity; } - - public void setQuantity(double q) { - if (q < 0) q = 0; - quantity = q; - } - - public String getServer() { return server; } - - public void setServer(String s) { - if (s == null) throw new IllegalArgumentException("Server can't be null"); - server = s; - } - -} diff --git a/src/fr/pandacube/java/util/db/ShopStockTable.java b/src/fr/pandacube/java/util/db/ShopStockTable.java deleted file mode 100644 index 7f769e1..0000000 --- a/src/fr/pandacube/java/util/db/ShopStockTable.java +++ /dev/null @@ -1,30 +0,0 @@ -package fr.pandacube.java.util.db; - -import java.sql.ResultSet; -import java.sql.SQLException; - -public class ShopStockTable extends SQLTable { - - public ShopStockTable() throws SQLException { - super("pandacube_shop_stock"); - } - - @Override - protected String createTableParameters() { - return "id INT AUTO_INCREMENT PRIMARY KEY," - + "material varchar(50) NOT NULL," - + "damage int(11) NOT NULL DEFAULT '0'," - + "quantity double NOT NULL," - + "server varchar(50) NOT NULL"; - } - - @Override - protected ShopStockElement getElementInstance(ResultSet sqlResult) throws SQLException { - return new ShopStockElement(sqlResult.getInt("id"), - sqlResult.getString("material"), - sqlResult.getShort("damage"), - sqlResult.getDouble("quantity"), - sqlResult.getString("server")); - } - -} diff --git a/src/fr/pandacube/java/util/db/StaffTicketElement.java b/src/fr/pandacube/java/util/db/StaffTicketElement.java deleted file mode 100644 index cd6b28d..0000000 --- a/src/fr/pandacube/java/util/db/StaffTicketElement.java +++ /dev/null @@ -1,77 +0,0 @@ -package fr.pandacube.java.util.db; - -import java.util.UUID; - -public class StaffTicketElement extends SQLElement { - - - private String playerId; - private String message; - private long creationTime; - private String staffPlayerId = null; - - - public StaffTicketElement(UUID pId, String m, long creaTime) { - super("pandacube_staff_ticket"); - setPlayerId(pId); - setMessage(m); - setCreationTime(creaTime); - - } - protected StaffTicketElement(int id, String pId, String m, long creaTime) { - super("pandacube_staff_ticket", id); - setPlayerId(UUID.fromString(pId)); - setMessage(m); - setCreationTime(creaTime); - } - - - @Override - protected String[] getValues() { - return new String[] { - playerId, - message, - Long.toString(creationTime), - staffPlayerId, - }; - } - - @Override - protected String[] getFieldsName() { - return new String[] { - "playerId", - "message", - "creationTime", - "staffPlayerId" - }; - } - public UUID getPlayerId() { - return UUID.fromString(playerId); - } - public void setPlayerId(UUID pId) { - if (pId == null) throw new IllegalArgumentException("playerName can't be null"); - this.playerId = pId.toString(); - } - public String getMessage() { - return message; - } - public void setMessage(String message) { - if (message == null) throw new IllegalArgumentException("message can't be null"); - this.message = message; - } - public long getCreationTime() { - return creationTime; - } - public void setCreationTime(long creationTime) { - this.creationTime = creationTime; - } - public UUID getStaffPlayer() { - if (staffPlayerId == null) return null; - return UUID.fromString(staffPlayerId); - } - public void setStaffPlayer(UUID staffId) { - if (staffId == null) staffPlayerId = null; - else staffPlayerId = staffId.toString(); - } - -} diff --git a/src/fr/pandacube/java/util/db/StaffTicketTable.java b/src/fr/pandacube/java/util/db/StaffTicketTable.java deleted file mode 100644 index a3896c9..0000000 --- a/src/fr/pandacube/java/util/db/StaffTicketTable.java +++ /dev/null @@ -1,37 +0,0 @@ -package fr.pandacube.java.util.db; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.UUID; - -public class StaffTicketTable extends SQLTable { - - - public StaffTicketTable() throws SQLException { - super("pandacube_staff_ticket"); - } - - @Override - protected String createTableParameters() { - return "id INT AUTO_INCREMENT PRIMARY KEY," - + "playerId CHAR(36) NOT NULL," - + "message VARCHAR(1024) NOT NULL," - + "creationTime BIGINT NOT NULL," - + "staffPlayerId CHAR(36) NULL"; - } - - @Override - protected StaffTicketElement getElementInstance(ResultSet sqlResult) - throws SQLException { - StaffTicketElement el = new StaffTicketElement( - sqlResult.getInt("id"), - sqlResult.getString("playerId"), - sqlResult.getString("message"), - sqlResult.getLong("creationTime")); - String staffId = sqlResult.getString("staffPlayerId"); - el.setStaffPlayer((staffId == null) ? null : UUID.fromString(staffId)); - - return el; - } - -} diff --git a/src/fr/pandacube/java/util/db/package-info.java b/src/fr/pandacube/java/util/db/package-info.java deleted file mode 100644 index 8e88b93..0000000 --- a/src/fr/pandacube/java/util/db/package-info.java +++ /dev/null @@ -1,2 +0,0 @@ -@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 fb5bb30..176cffd 100644 --- a/src/fr/pandacube/java/util/db2/SQLContact.java +++ b/src/fr/pandacube/java/util/db2/SQLContact.java @@ -3,42 +3,41 @@ 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.SQLField; 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 SQLContact extends SQLElement { - - public SQLContact() { super(); } - public SQLContact(int id) { super(id); } - + + public SQLContact() { + super(); + } + + public SQLContact(int id) { + super(id); + } + @Override - protected String tableName() { return "pandacube_contact"; } - - - - - - 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); - - - + protected String tableName() { + return "pandacube_contact"; + } + + 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); + public UUID getPlayerId() { - String id = (String)get(playerId); + String id = get(playerId); return (id == null) ? null : UUID.fromString(id); } - - + public void setPlayerId(UUID pName) { - set(playerId, (pName == null) ? (String)null : pName.toString()); + set(playerId, (pName == null) ? (String) null : pName.toString()); } - - - + } diff --git a/src/fr/pandacube/java/util/db2/SQLForumCategorie.java b/src/fr/pandacube/java/util/db2/SQLForumCategorie.java index 7174bcc..cb01872 100644 --- a/src/fr/pandacube/java/util/db2/SQLForumCategorie.java +++ b/src/fr/pandacube/java/util/db2/SQLForumCategorie.java @@ -5,16 +5,21 @@ import fr.pandacube.java.util.db2.sql_tools.SQLField; import fr.pandacube.java.util.db2.sql_tools.SQLType; public class SQLForumCategorie extends SQLElement { - - public SQLForumCategorie() { super(); } - public SQLForumCategorie(int id) { super(id); } + + public SQLForumCategorie() { + super(); + } + + public SQLForumCategorie(int id) { + super(id); + } @Override - protected String tableName() { return "pandacube_forum_categorie"; } - - - public static final SQLField nom = new SQLField<>("nom", SQLType.VARCHAR(100), false); - public static final SQLField ordre = new SQLField<>("ordre", SQLType.INT, false); - + protected String tableName() { + return "pandacube_forum_categorie"; + } + + public static final SQLField nom = new SQLField<>("nom", SQLType.VARCHAR(100), false); + public static final SQLField ordre = new SQLField<>("ordre", SQLType.INT, false); } diff --git a/src/fr/pandacube/java/util/db2/SQLForumForum.java b/src/fr/pandacube/java/util/db2/SQLForumForum.java index 5fad3b3..f32388e 100644 --- a/src/fr/pandacube/java/util/db2/SQLForumForum.java +++ b/src/fr/pandacube/java/util/db2/SQLForumForum.java @@ -7,26 +7,30 @@ import fr.pandacube.java.util.db2.sql_tools.SQLType; public class SQLForumForum extends SQLElement { - - public SQLForumForum() { super(); } - public SQLForumForum(int id) { super(id); } + public SQLForumForum() { + super(); + } + + public SQLForumForum(int id) { + super(id); + } @Override - protected String tableName() { return "pandacube_forum_forum"; } - - - 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); - - + protected String tableName() { + return "pandacube_forum_forum"; + } + + 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 244e90d..e4bb779 100644 --- a/src/fr/pandacube/java/util/db2/SQLForumPost.java +++ b/src/fr/pandacube/java/util/db2/SQLForumPost.java @@ -9,31 +9,33 @@ import fr.pandacube.java.util.db2.sql_tools.SQLType; public class SQLForumPost extends SQLElement { - - public SQLForumPost() { super(); } - public SQLForumPost(int id) { super(id); } + public SQLForumPost() { + super(); + } + + public SQLForumPost(int id) { + super(id); + } @Override - 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 SQLFKField threadId = SQLFKField.idFK("threadId", SQLType.INT, false, SQLForumThread.class); - public static final SQLField moderated = new SQLField<>("moderated", SQLType.BOOLEAN, false); - - - + 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 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); + String id = get(createur); return (id == null) ? null : UUID.fromString(id); } - - + public void setCreateurId(UUID pName) { - set(createur, (pName == null) ? (String)null : pName.toString()); + set(createur, (pName == null) ? (String) null : pName.toString()); } - } diff --git a/src/fr/pandacube/java/util/db2/SQLForumThread.java b/src/fr/pandacube/java/util/db2/SQLForumThread.java index 78f82d7..c50c4e2 100644 --- a/src/fr/pandacube/java/util/db2/SQLForumThread.java +++ b/src/fr/pandacube/java/util/db2/SQLForumThread.java @@ -9,36 +9,37 @@ import fr.pandacube.java.util.db2.sql_tools.SQLType; public class SQLForumThread extends SQLElement { - - public SQLForumThread() { super(); } - public SQLForumThread(int id) { super(id); } + public SQLForumThread() { + super(); + } + + public SQLForumThread(int id) { + super(id); + } @Override - protected String tableName() { return "pandacube_forum_thread"; } - - - 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); - - - + protected String tableName() { + return "pandacube_forum_thread"; + } + + 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); + String id = get(createur); return (id == null) ? null : UUID.fromString(id); } - - + public void setCreateurId(UUID pName) { - set(createur, (pName == null) ? (String)null : pName.toString()); + set(createur, (pName == null) ? (String) null : pName.toString()); } - - - - + } diff --git a/src/fr/pandacube/java/util/db2/SQLLoginHistory.java b/src/fr/pandacube/java/util/db2/SQLLoginHistory.java index 57fc0c8..5156b7a 100644 --- a/src/fr/pandacube/java/util/db2/SQLLoginHistory.java +++ b/src/fr/pandacube/java/util/db2/SQLLoginHistory.java @@ -9,40 +9,38 @@ import fr.pandacube.java.util.db2.sql_tools.SQLType; public class SQLLoginHistory extends SQLElement { - - public SQLLoginHistory() { super(); } - public SQLLoginHistory(int id) { super(id); } + public SQLLoginHistory() { + super(); + } + + public SQLLoginHistory(int id) { + super(id); + } @Override - protected String tableName() { return "pandacube_login_history"; } - - - 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); - - - - - + protected String tableName() { + return "pandacube_login_history"; + } + + 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); + public UUID getPlayerId() { - String id = (String)get(playerId); + String id = get(playerId); return (id == null) ? null : UUID.fromString(id); } - - + public void setPlayerId(UUID pName) { - set(playerId, (pName == null) ? (String)null : pName.toString()); + set(playerId, (pName == null) ? (String) null : pName.toString()); } - - - - - + public enum ActionType { LOGIN, LOGOUT } diff --git a/src/fr/pandacube/java/util/db2/SQLMPGroup.java b/src/fr/pandacube/java/util/db2/SQLMPGroup.java index b357558..6b25376 100644 --- a/src/fr/pandacube/java/util/db2/SQLMPGroup.java +++ b/src/fr/pandacube/java/util/db2/SQLMPGroup.java @@ -12,34 +12,30 @@ import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp.SQLComparator; public class SQLMPGroup extends SQLElement { - - public SQLMPGroup() { super(); } - public SQLMPGroup(int id) { super(id); } + public SQLMPGroup() { + super(); + } + + public SQLMPGroup(int id) { + super(id); + } @Override - protected String tableName() { return "pandacube_mp_group"; } - - + protected String tableName() { + return "pandacube_mp_group"; + } + 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()), + 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; - + 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 9900ed9..dfe4825 100644 --- a/src/fr/pandacube/java/util/db2/SQLMPGroupUser.java +++ b/src/fr/pandacube/java/util/db2/SQLMPGroupUser.java @@ -8,48 +8,45 @@ 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.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; import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp.SQLComparator; public class SQLMPGroupUser extends SQLElement { - - - public SQLMPGroupUser() { super(); } - public SQLMPGroupUser(int id) { super(id); } + + public SQLMPGroupUser() { + super(); + } + + public SQLMPGroupUser(int id) { + super(id); + } @Override - protected String tableName() { return "pandacube_mp_group_user"; } - - - 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); - + protected String tableName() { + return "pandacube_mp_group_user"; + } + + 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 - - - + public UUID getPlayerId() { String id = get(playerId); return (id == null) ? null : UUID.fromString(id); } - - + public void setPlayerId(UUID id) { set(playerId, (id == null) ? null : id.toString()); } - - - - - - - - - /** - * Retourne l'instance de SQLMPGroupUser correcpondant à la présence d'un joueur dans un groupe + * 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 @@ -58,9 +55,9 @@ public class SQLMPGroupUser extends SQLElement { 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); + 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 fdb8188..77d6f48 100644 --- a/src/fr/pandacube/java/util/db2/SQLMPMessage.java +++ b/src/fr/pandacube/java/util/db2/SQLMPMessage.java @@ -10,92 +10,89 @@ 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.SQLOrderBy.Direction; 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; import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp.SQLComparator; +import fr.pandacube.java.util.db2.sql_tools.SQLWhereLike; import fr.pandacube.java.util.db2.sql_tools.SQLWhereNull; public class SQLMPMessage extends SQLElement { - - - public SQLMPMessage() { super(); } - public SQLMPMessage(int id) { super(id); } + + public SQLMPMessage() { + super(); + } + + public SQLMPMessage(int id) { + super(id); + } @Override - 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 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); + 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 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() { String id = get(viewerId); return (id == null) ? null : UUID.fromString(id); } + public void setViewerId(UUID id) { set(viewerId, (id == null) ? null : id.toString()); } - public UUID getSourceId() { String id = get(sourceId); return (id == null) ? null : UUID.fromString(id); } + public void setSourceId(UUID id) { set(sourceId, (id == null) ? null : id.toString()); } - public UUID getDestId() { String id = get(destId); return (id == null) ? null : UUID.fromString(id); } + 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); + 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 { + + 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; - - + 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 @@ -103,42 +100,38 @@ public class SQLMPMessage extends SQLElement { .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; + 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 + 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()))) + 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 { + + 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)); - + 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 de9e5e5..e428916 100644 --- a/src/fr/pandacube/java/util/db2/SQLModoHistory.java +++ b/src/fr/pandacube/java/util/db2/SQLModoHistory.java @@ -9,51 +9,48 @@ import fr.pandacube.java.util.db2.sql_tools.SQLType; public class SQLModoHistory extends SQLElement { - - public SQLModoHistory() { super(); } - public SQLModoHistory(int id) { super(id); } + public SQLModoHistory() { + super(); + } + + public SQLModoHistory(int id) { + super(id); + } @Override - protected String tableName() { return "pandacube_modo_history"; } - - - 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); - - - - + protected String tableName() { + return "pandacube_modo_history"; + } + + 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); + String id = get(modoId); return (id == null) ? null : UUID.fromString(id); } - - + public void setModoId(UUID pName) { - set(modoId, (pName == null) ? (String)null : pName.toString()); + set(modoId, (pName == null) ? (String) null : pName.toString()); } - - public UUID getPlayerId() { - String id = (String)get(playerId); + String id = get(playerId); return (id == null) ? null : UUID.fromString(id); } - - + public void setPlayerId(UUID pName) { - set(playerId, (pName == null) ? (String)null : pName.toString()); + set(playerId, (pName == null) ? (String) null : pName.toString()); } - - - - - public enum ActionType{ + public enum ActionType { BAN, UNBAN, MUTE, UNMUTE, REPORT, KICK } diff --git a/src/fr/pandacube/java/util/db2/SQLOnlineshopHistory.java b/src/fr/pandacube/java/util/db2/SQLOnlineshopHistory.java index 490cbc7..3f78f57 100644 --- a/src/fr/pandacube/java/util/db2/SQLOnlineshopHistory.java +++ b/src/fr/pandacube/java/util/db2/SQLOnlineshopHistory.java @@ -9,64 +9,57 @@ import fr.pandacube.java.util.db2.sql_tools.SQLType; public class SQLOnlineshopHistory extends SQLElement { - - public SQLOnlineshopHistory() { super(); } - public SQLOnlineshopHistory(int id) { super(id); } + public SQLOnlineshopHistory() { + super(); + } + + public SQLOnlineshopHistory(int id) { + super(id); + } @Override - 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 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); - - - + 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 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); - public UUID getSourcePlayerId() { - String id = (String)get(sourcePlayerId); + String id = get(sourcePlayerId); return (id == null) ? null : UUID.fromString(id); } - - - public void setSourcePlayerId(UUID pName) { - set(sourcePlayerId, (pName == null) ? (String)null : pName.toString()); - } - - + public void setSourcePlayerId(UUID pName) { + set(sourcePlayerId, (pName == null) ? (String) null : pName.toString()); + } + public UUID getDestPlayerId() { - String id = (String)get(destPlayerId); + String id = get(destPlayerId); return (id == null) ? null : UUID.fromString(id); } - - + public void setDestPlayerId(UUID pName) { - set(destPlayerId, (pName == null) ? (String)null : pName.toString()); + set(destPlayerId, (pName == null) ? (String) null : pName.toString()); } - - - - - - - + public static enum SourceType { REAL_MONEY, BAMBOU } - + public static enum DestType { BAMBOU, GRADE } - - + } diff --git a/src/fr/pandacube/java/util/db2/SQLPlayer.java b/src/fr/pandacube/java/util/db2/SQLPlayer.java index fdad506..8274fbc 100644 --- a/src/fr/pandacube/java/util/db2/SQLPlayer.java +++ b/src/fr/pandacube/java/util/db2/SQLPlayer.java @@ -11,90 +11,81 @@ 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 { - - public SQLPlayer() { super(); } - public SQLPlayer(int id) { super(id); } - - + + public SQLPlayer() { + super(); + } + + public SQLPlayer(int id) { + super(id); + } + /* * Nom de la table */ @Override - protected String tableName() { return "pandacube_player"; } - + protected String tableName() { + return "pandacube_player"; + } + /* * Champs de la table */ - public static final SQLField playerId = new SQLField<>("playerId", SQLType.CHAR(36), false); - public static final SQLField token = new SQLField<>("token", SQLType.CHAR(36), true); - public static final SQLField mailCheck = new SQLField<>("mailCheck", SQLType.VARCHAR(255), true); - 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, 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, 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); - public static final SQLField birthday = new SQLField<>("birthday", SQLType.DATE, true); - public static final SQLField lastYearCelebBday = new SQLField<>("lastYearCelebratedBirthday", SQLType.INT, false, 0); - public static final SQLField banTimeout = new SQLField<>("banTimeout", SQLType.BIGINT, true); - public static final SQLField muteTimeout = new SQLField<>("muteTimeout", SQLType.BIGINT, true); - public static final SQLField isWhitelisted = new SQLField<>("isWhitelisted", SQLType.BOOLEAN, false, (Boolean)false); - public static final SQLField bambou = new SQLField<>("bambou", SQLType.BIGINT, false, 0L); - public static final SQLField grade = new SQLField<>("grade", SQLType.VARCHAR(36), false, "default"); + public static final SQLField playerId = new SQLField<>("playerId", SQLType.CHAR(36), false); + public static final SQLField token = new SQLField<>("token", SQLType.CHAR(36), true); + public static final SQLField mailCheck = new SQLField<>("mailCheck", SQLType.VARCHAR(255), true); + 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, 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, 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); + public static final SQLField birthday = new SQLField<>("birthday", SQLType.DATE, true); + public static final SQLField lastYearCelebBday = new SQLField<>("lastYearCelebratedBirthday", SQLType.INT, + false, 0); + public static final SQLField banTimeout = new SQLField<>("banTimeout", SQLType.BIGINT, true); + public static final SQLField muteTimeout = new SQLField<>("muteTimeout", SQLType.BIGINT, true); + public static final SQLField isWhitelisted = new SQLField<>("isWhitelisted", SQLType.BOOLEAN, false, + (Boolean) false); + public static final SQLField bambou = new SQLField<>("bambou", SQLType.BIGINT, false, 0L); + public static final SQLField grade = new SQLField<>("grade", SQLType.VARCHAR(36), false, "default"); - - - /* * Getteurs spécifique (encapsulation) */ - + public UUID getPlayerId() { - String id = (String)get(playerId); + String id = get(playerId); return (id == null) ? null : UUID.fromString(id); } + public UUID getToken() { - String id = (String)get(token); + String id = get(token); return (id == null) ? null : UUID.fromString(id); } - - - - - - + /* * Setteurs spécifique (encapsulation) */ - - - + public void setPlayerId(UUID pName) { - set(playerId, (pName == null) ? (String)null : pName.toString()); + set(playerId, (pName == null) ? (String) null : pName.toString()); } + public void setToken(UUID t) { - set(token, (t == null) ? (String)null : t.toString()); + set(token, (t == null) ? (String) null : t.toString()); } - - - - - - - - - - + public static SQLPlayer getPlayerFromUUID(UUID playerId) throws ORMException { return ORM.getFirst(SQLPlayer.class, - new SQLWhereComp(SQLPlayer.playerId, SQLComparator.EQ, playerId.toString()), - null); + 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 b850667..1e9dde5 100644 --- a/src/fr/pandacube/java/util/db2/SQLPlayerIgnore.java +++ b/src/fr/pandacube/java/util/db2/SQLPlayerIgnore.java @@ -10,61 +10,60 @@ 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; import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp.SQLComparator; public class SQLPlayerIgnore extends SQLElement { - - - public SQLPlayerIgnore() { super(); } - public SQLPlayerIgnore(int id) { super(id); } + + public SQLPlayerIgnore() { + super(); + } + + public SQLPlayerIgnore(int id) { + super(id); + } @Override - protected String tableName() { return "pandacube_player_ignore"; } - - - 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); - + protected String tableName() { + return "pandacube_player_ignore"; + } + + 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); - public UUID getIgnorerId() { - String id = (String)get(ignorer); + String id = get(ignorer); return (id == null) ? null : UUID.fromString(id); } - - - public void setIgnorerId(UUID pName) { - set(ignorer, (pName == null) ? (String)null : pName.toString()); - } - - + public void setIgnorerId(UUID pName) { + set(ignorer, (pName == null) ? (String) null : pName.toString()); + } + public UUID getIgnoredId() { - String id = (String)get(ignored); + String id = get(ignored); return (id == null) ? null : UUID.fromString(id); } - - + public void setIgnoredId(UUID pName) { - set(ignored, (pName == null) ? (String)null : pName.toString()); + set(ignored, (pName == null) ? (String) null : pName.toString()); } - - - 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())), + .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) { @@ -78,21 +77,17 @@ public class SQLPlayerIgnore extends SQLElement { 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) { + for (SQLPlayerIgnore el : els) ret.add(el.getIgnoredId()); - } return ret; } - - + } diff --git a/src/fr/pandacube/java/util/db2/SQLShopStock.java b/src/fr/pandacube/java/util/db2/SQLShopStock.java index 2e97363..c9b61a7 100644 --- a/src/fr/pandacube/java/util/db2/SQLShopStock.java +++ b/src/fr/pandacube/java/util/db2/SQLShopStock.java @@ -5,19 +5,23 @@ import fr.pandacube.java.util.db2.sql_tools.SQLField; import fr.pandacube.java.util.db2.sql_tools.SQLType; public class SQLShopStock extends SQLElement { - - - public SQLShopStock() { super(); } - public SQLShopStock(int id) { super(id); } + + public SQLShopStock() { + super(); + } + + public SQLShopStock(int id) { + super(id); + } @Override - protected String tableName() { return "pandacube_shop_stock"; } - - + protected String tableName() { + return "pandacube_shop_stock"; + } + public static final SQLField material = new SQLField<>("material", SQLType.VARCHAR(50), false); public static final SQLField damage = new SQLField<>("damage", SQLType.INT, false, 0); public static final SQLField quantity = new SQLField<>("quantity", SQLType.DOUBLE, false); public static final SQLField server = new SQLField<>("server", SQLType.VARCHAR(50), false); - - + } diff --git a/src/fr/pandacube/java/util/db2/SQLStaffTicket.java b/src/fr/pandacube/java/util/db2/SQLStaffTicket.java index 40e6a09..b1bf76f 100644 --- a/src/fr/pandacube/java/util/db2/SQLStaffTicket.java +++ b/src/fr/pandacube/java/util/db2/SQLStaffTicket.java @@ -9,39 +9,40 @@ import fr.pandacube.java.util.db2.sql_tools.SQLType; public class SQLStaffTicket extends SQLElement { - - public SQLStaffTicket() { super(); } - public SQLStaffTicket(int id) { super(id); } + public SQLStaffTicket() { + super(); + } + + public SQLStaffTicket(int id) { + super(id); + } @Override - protected String tableName() { return "pandacube_staff_ticket"; } - - - public static final SQLFKField playerId = new SQLFKField<>("playerId", SQLType.CHAR(36), false, SQLPlayer.class, SQLPlayer.playerId); + protected String tableName() { + return "pandacube_staff_ticket"; + } + + 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 SQLFKField staffPlayerId = new SQLFKField<>("staffPlayerId", SQLType.CHAR(36), true, SQLPlayer.class, SQLPlayer.playerId); - - - + public static final SQLFKField staffPlayerId = new SQLFKField<>("staffPlayerId", + SQLType.CHAR(36), true, SQLPlayer.class, SQLPlayer.playerId); + public UUID getPlayerId() { String id = get(playerId); return (id == null) ? null : UUID.fromString(id); } - - + public void setPlayerId(UUID id) { set(playerId, (id == null) ? null : id.toString()); } - - public UUID getstaffPlayerId() { String id = get(staffPlayerId); return (id == null) ? null : UUID.fromString(id); } - - + public void setstaffPlayerId(UUID id) { set(staffPlayerId, (id == null) ? null : id.toString()); } diff --git a/src/fr/pandacube/java/util/db2/SQLStaticPages.java b/src/fr/pandacube/java/util/db2/SQLStaticPages.java index 31a6ee3..8dbedc8 100644 --- a/src/fr/pandacube/java/util/db2/SQLStaticPages.java +++ b/src/fr/pandacube/java/util/db2/SQLStaticPages.java @@ -6,19 +6,23 @@ import fr.pandacube.java.util.db2.sql_tools.SQLType; public class SQLStaticPages extends SQLElement { - - public SQLStaticPages() { super(); } - public SQLStaticPages(int id) { super(id); } + public SQLStaticPages() { + super(); + } + + public SQLStaticPages(int id) { + super(id); + } @Override - protected String tableName() { return "pandacube_static_pages"; } - - + protected String tableName() { + return "pandacube_static_pages"; + } + public static final SQLField permalink = new SQLField<>("permalink", SQLType.VARCHAR(128), false); public static final SQLField titreHead = new SQLField<>("titreHead", SQLType.VARCHAR(128), false); public static final SQLField titreH2 = new SQLField<>("titreH2", SQLType.VARCHAR(255), false); public static final SQLField texte = new SQLField<>("texte", SQLType.TEXT, false); public static final SQLField permissions = new SQLField<>("permissions", SQLType.VARCHAR(255), true); - } diff --git a/src/fr/pandacube/java/util/db2/SQLUUIDPlayer.java b/src/fr/pandacube/java/util/db2/SQLUUIDPlayer.java index 40e5526..c5ac026 100644 --- a/src/fr/pandacube/java/util/db2/SQLUUIDPlayer.java +++ b/src/fr/pandacube/java/util/db2/SQLUUIDPlayer.java @@ -8,29 +8,31 @@ 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); } + + 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); - - + 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 bab12d9..42d7cd1 100644 --- a/src/fr/pandacube/java/util/db2/sql_tools/DBConnection.java +++ b/src/fr/pandacube/java/util/db2/sql_tools/DBConnection.java @@ -10,48 +10,42 @@ public class DBConnection { String url; String login; String pass; - - public DBConnection(String host, int port, String dbname, String l, String p) throws ClassNotFoundException, SQLException { + + 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; + url = "jdbc:mysql://" + host + ":" + port + "/" + dbname; login = l; pass = p; connect(); } - - - public void reconnectIfNecessary() throws SQLException - { - try - { + + public void reconnectIfNecessary() throws SQLException { + try { Statement stmt = conn.createStatement(); stmt.close(); - } - catch(SQLException e) - { - try { close(); } catch(Exception ex) { } + } catch (SQLException e) { + try { + close(); + } catch (Exception ex) {} connect(); } } - - public Connection getNativeConnection() throws SQLException - { - if (!conn.isValid(1)) - reconnectIfNecessary(); + + public Connection getNativeConnection() throws SQLException { + if (!conn.isValid(1)) reconnectIfNecessary(); return conn; } - - + private void connect() throws SQLException { conn = DriverManager.getConnection(url, login, pass); } - - + public void close() { try { conn.close(); - } catch (Exception e) { } - + } catch (Exception e) {} + } - + } 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 735b295..f7cdcc3 100644 --- a/src/fr/pandacube/java/util/db2/sql_tools/ORM.java +++ b/src/fr/pandacube/java/util/db2/sql_tools/ORM.java @@ -33,30 +33,30 @@ import javafx.util.Pair; /** * ORM = Object-Relational Mapping + * * @author Marc Baloup * */ public final class ORM { - + private static List> tables = new ArrayList<>(); - + private static DBConnection connection; - + public static DBConnection getConnection() { return connection; } - - + public synchronized static void init(DBConnection conn) { - + connection = conn; - + /* * Les tables à initialiser - * - * utile des les initialiser ici, car on peut tout de suite déceler les bugs ou erreurs dans la déclaration des SQLFields + * utile des les initialiser ici, car on peut tout de suite déceler les + * bugs ou erreurs dans la déclaration des SQLFields */ - + try { initTable(SQLContact.class); initTable(SQLForumCategorie.class); @@ -78,68 +78,49 @@ public final class ORM { } catch (ORMInitTableException e) { Log.getLogger().log(Level.SEVERE, "Erreur d'initialisation d'une table dans l'ORM", e); } - - - - + } - - + /* package */ static void initTable(Class elemClass) throws ORMInitTableException { - if (tables.contains(elemClass)) - return; + if (tables.contains(elemClass)) return; try { T instance = elemClass.newInstance(); String tableName = instance.tableName(); - if (!tableExist(tableName)) - createTable(instance); + if (!tableExist(tableName)) createTable(instance); tables.add(elemClass); } catch (Exception e) { throw new ORMInitTableException(elemClass, e); } } - - - private static void createTable(T elem) throws SQLException { - - String sql = "CREATE TABLE IF NOT EXISTS "+elem.tableName()+" ("; + + String sql = "CREATE TABLE IF NOT EXISTS " + elem.tableName() + " ("; List params = new ArrayList<>(); - + Collection> tableFields = elem.getFields().values(); boolean first = true; for (SQLField f : tableFields) { Pair> statementPart = f.forSQLPreparedStatement(); params.addAll(statementPart.getValue()); - + if (!first) sql += ", "; first = false; sql += statementPart.getKey(); } - - - - + sql += ", PRIMARY KEY id(id))"; PreparedStatement ps = connection.getNativeConnection().prepareStatement(sql); int i = 1; - for (Object val : params) { + for (Object val : params) ps.setObject(i++, val); - } try { - Log.info("Creating table "+elem.tableName()+":\n"+ps.toString()); + 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; @@ -148,88 +129,78 @@ public final class ORM { set = connection.getNativeConnection().getMetaData().getTables(null, null, tableName, null); exist = set.next(); } finally { - if (set != null) - set.close(); + if (set != null) set.close(); } return exist; } - - - - - - + @SuppressWarnings("unchecked") - public static SQLField getSQLIdField(Class elemClass) throws ORMInitTableException { + 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 ORMException { + 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 ORMException { SQLField idField = getSQLIdField(elemClass); SQLWhereChain where = new SQLWhereChain(SQLBoolOp.OR); for (Integer id : ids) - if (id != null) - where.add(new SQLWhereComp(idField, SQLComparator.EQ, id)); + if (id != null) where.add(new SQLWhereComp(idField, SQLComparator.EQ, id)); return getAll(elemClass, where, new SQLOrderBy().addField(idField), 1, null); } - + 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 ORMException { + + 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); + return (elts.size() == 0) ? null : elts.get(0); } - - - + 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 ORMException { + + public static SQLElementList getAll(Class elemClass, SQLWhere where, + SQLOrderBy orderBy, Integer limit, Integer offset) throws ORMException { initTable(elemClass); - + try { - String sql = "SELECT * FROM "+elemClass.newInstance().tableName(); - + String sql = "SELECT * FROM " + elemClass.newInstance().tableName(); + List params = new ArrayList<>(); if (where != null) { Pair> ret = where.toSQL(); - sql += " WHERE "+ret.getKey(); + 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; + 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 { - + int i = 1; for (Object val : params) { - if (val instanceof Enum) - val = ((Enum)val).name(); + if (val instanceof Enum) val = ((Enum) val).name(); ps.setObject(i++, val); } Log.debug(ps.toString()); ResultSet set = ps.executeQuery(); - + try { while (set.next()) elmts.add(getElementInstance(set, elemClass)); @@ -239,123 +210,91 @@ public final class ORM { } finally { ps.close(); } - + return elmts; } catch (ReflectiveOperationException | SQLException e) { throw new ORMException(e); } - - } - - - - - - - - - - - - - + } + private static T getElementInstance(ResultSet set, Class elemClass) throws ORMException { try { T instance = elemClass.getConstructor(int.class).newInstance(set.getInt("id")); - + int fieldCount = set.getMetaData().getColumnCount(); - - for (int c = 1; c<= fieldCount; c++) { + + for (int c = 1; c <= fieldCount; c++) { String fieldName = set.getMetaData().getColumnLabel(c); - if (!instance.getFields().containsKey(fieldName)) - continue; // ignore when field is present in database but not handled by SQLElement instance + if (!instance.getFields().containsKey(fieldName)) continue; // ignore + // when + // field + // is + // present + // in + // database + // but + // not + // handled + // by + // SQLElement + // instance @SuppressWarnings("unchecked") SQLField sqlField = (SQLField) instance.getFields().get(fieldName); if (sqlField.type.getJavaType().isEnum()) { // JDBC ne supporte pas les enums String enumStrValue = set.getString(c); - if (enumStrValue == null || set.wasNull()) - instance.set(sqlField, null, false); + if (enumStrValue == null || set.wasNull()) instance.set(sqlField, null, false); else { Enum enumValue = EnumUtil.searchUncheckedEnum(sqlField.type.getJavaType(), enumStrValue); - if (enumValue == null) - throw new ORMException("The enum constant '"+enumStrValue+"' is not found in enum class "+sqlField.type.getJavaType().getName()); + if (enumValue == null) throw new ORMException("The enum constant '" + enumStrValue + + "' is not found in enum class " + sqlField.type.getJavaType().getName()); instance.set(sqlField, enumValue, false); } } else { Object val = set.getObject(c, sqlField.type.getJavaType()); - if (val == null || set.wasNull()) - instance.set(sqlField, null, false); + if (val == null || set.wasNull()) instance.set(sqlField, null, false); else instance.set(sqlField, val, false); } - - // la valeur venant de la BDD est marqué comme "non modifié" dans l'instance - // car le constructeur de l'instance met tout les champs comme modifiés + + // la valeur venant de la BDD est marqué comme "non modifié" + // dans l'instance + // car le constructeur de l'instance met tout les champs comme + // modifiés instance.modifiedSinceLastSave.remove(sqlField.name); } - - if (!instance.isValidForSave()) - throw new ORMException("This SQLElement representing a database entry is not valid for save : "+instance.toString()); - + + if (!instance.isValidForSave()) throw new ORMException( + "This SQLElement representing a database entry is not valid for save : " + instance.toString()); + return instance; } catch (ReflectiveOperationException | IllegalArgumentException | SecurityException | SQLException e) { throw new ORMException("Can't instanciate " + elemClass.getName(), e); } } - - - - - - - - - - - - - - - private ORM() { } // rend la classe non instanciable - + + private ORM() {} // rend la classe non instanciable + /* - public static void main(String[] args) throws Throwable { - ORM.init(new DBConnection("localhost", 3306, "pandacube", "pandacube", "pandacube")); - - List players = ORM.getAll(SQLPlayer.class, - new SQLWhereChain(SQLBoolOp.AND) - .add(new SQLWhereNull(SQLPlayer.banTimeout, true)) - .add(new SQLWhereChain(SQLBoolOp.OR) - .add(new SQLWhereComp(SQLPlayer.bambou, SQLComparator.EQ, 0L)) - .add(new SQLWhereComp(SQLPlayer.grade, SQLComparator.EQ, "default")) - ), - new SQLOrderBy().addField(SQLPlayer.playerDisplayName), null, null); - - for(SQLPlayer p : players) { - System.out.println(p.get(SQLPlayer.playerDisplayName)); - } - - - // TODO LIST - - * - Gérer mise à jour relative d'un champ (incrément / décrément) - - - - - } - */ - - - - - - - - - - + * public static void main(String[] args) throws Throwable { + * ORM.init(new DBConnection("localhost", 3306, "pandacube", "pandacube", + * "pandacube")); + * List players = ORM.getAll(SQLPlayer.class, + * new SQLWhereChain(SQLBoolOp.AND) + * .add(new SQLWhereNull(SQLPlayer.banTimeout, true)) + * .add(new SQLWhereChain(SQLBoolOp.OR) + * .add(new SQLWhereComp(SQLPlayer.bambou, SQLComparator.EQ, 0L)) + * .add(new SQLWhereComp(SQLPlayer.grade, SQLComparator.EQ, "default")) + * ), + * new SQLOrderBy().addField(SQLPlayer.playerDisplayName), null, null); + * for(SQLPlayer p : players) { + * System.out.println(p.get(SQLPlayer.playerDisplayName)); + * } + * // TODO LIST + * - Gérer mise à jour relative d'un champ (incrément / décrément) + * } + */ + } diff --git a/src/fr/pandacube/java/util/db2/sql_tools/ORMException.java b/src/fr/pandacube/java/util/db2/sql_tools/ORMException.java index 2bed4a7..896c4ac 100644 --- a/src/fr/pandacube/java/util/db2/sql_tools/ORMException.java +++ b/src/fr/pandacube/java/util/db2/sql_tools/ORMException.java @@ -6,11 +6,11 @@ public class ORMException extends Exception { 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 index caac847..6184a8a 100644 --- a/src/fr/pandacube/java/util/db2/sql_tools/ORMInitTableException.java +++ b/src/fr/pandacube/java/util/db2/sql_tools/ORMInitTableException.java @@ -3,16 +3,12 @@ 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()); + super("Error while initializing table " + tableElem.getName()); } /* package */ ORMInitTableException(Class tableElem, Throwable t) { - super("Error while initializing table "+tableElem.getName(), 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 2b537cb..eaba34f 100644 --- a/src/fr/pandacube/java/util/db2/sql_tools/SQLElement.java +++ b/src/fr/pandacube/java/util/db2/sql_tools/SQLElement.java @@ -24,258 +24,208 @@ import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp.SQLComparator; public abstract class SQLElement { /** cache for fields for each subclass of SQLElement */ /* package */ static final Map, SQLFieldMap> fieldsCache = new HashMap<>(); - - - - + DBConnection db = ORM.getConnection(); - + private boolean stored = false; private int id; - + private final String tableName; private final SQLFieldMap fields; private final Map, Object> values; /* package */ final Set modifiedSinceLastSave; - public SQLElement() { tableName = tableName(); - - + if (fieldsCache.get(getClass()) == null) { fields = new SQLFieldMap(getClass()); - + // le champ id commun à toutes les tables fields.addField(new SQLField<>("id", SQLType.INT, false, true, 0)); - + generateFields(fields); fieldsCache.put(getClass(), fields); } - else { + else fields = fieldsCache.get(getClass()); - } - + values = new LinkedHashMap<>(fields.size()); modifiedSinceLastSave = new HashSet<>(fields.size()); - + initDefaultValues(); - - + } - - - protected SQLElement(int id) { + + protected SQLElement(int id) { this(); @SuppressWarnings("unchecked") - SQLField idField = (SQLField)fields.get("id"); + SQLField idField = (SQLField) fields.get("id"); set(idField, id, false); this.id = id; stored = true; } - + /** * @return The name of the table in the database. */ protected abstract String tableName(); - - - - - - @SuppressWarnings("unchecked") private void initDefaultValues() { - // remplissage des données par défaut (si peut être null ou si valeur par défaut existe) - for (@SuppressWarnings("rawtypes") SQLField f : fields.values()) { - if (f.defaultValue != null) { - set(f, f.defaultValue); - } else if (f.canBeNull || (f.autoIncrement && !stored)) { - set(f, null); - } - } + // remplissage des données par défaut (si peut être null ou si valeur + // par défaut existe) + for (@SuppressWarnings("rawtypes") + SQLField f : fields.values()) + if (f.defaultValue != null) set(f, f.defaultValue); + else if (f.canBeNull || (f.autoIncrement && !stored)) set(f, null); } - + protected void generateFields(SQLFieldMap listToFill) { - + java.lang.reflect.Field[] declaredFields = getClass().getDeclaredFields(); for (java.lang.reflect.Field field : declaredFields) { - if (!java.lang.reflect.Modifier.isStatic(field.getModifiers())) - continue; - + if (!java.lang.reflect.Modifier.isStatic(field.getModifiers())) continue; + try { Object val = field.get(null); - if (val == null || !(val instanceof SQLField)) - continue; - - listToFill.addField((SQLField)val); + if (val == null || !(val instanceof SQLField)) continue; + + listToFill.addField((SQLField) val); } catch (IllegalArgumentException | IllegalAccessException e) { - Log.getLogger().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); } } - - - - + } - + /* package */ Map> getFields() { return Collections.unmodifiableMap(fields); } - - - - + public Map, Object> getValues() { return Collections.unmodifiableMap(values); } - - - - - - - - + public void set(SQLField field, T value) { set(field, value, true); } - - + /* package */ void set(SQLField sqlField, T value, boolean setModified) { - if (sqlField == null) - throw new IllegalArgumentException("sqlField can't be null"); + if (sqlField == null) throw new IllegalArgumentException("sqlField can't be null"); if (!fields.containsValue(sqlField)) throw new IllegalArgumentException(sqlField.name + " is not a SQLField of " + getClass().getName()); - + boolean modify = false; if (value == null) { - if (sqlField.canBeNull || (sqlField.autoIncrement && !stored)) - modify = true; + if (sqlField.canBeNull || (sqlField.autoIncrement && !stored)) modify = true; else - throw new IllegalArgumentException("SQLField '" + sqlField.name + "' of " + getClass().getName() + " is a NOT NULL field"); - } else { - if (sqlField.type.isAssignableFrom(value)) - modify = true; - else - throw new IllegalArgumentException("SQLField '" + sqlField.name + "' of " + getClass().getName() + " type is '" + sqlField.type.toString() + "' and can't accept values of type " + value.getClass().getName()); + throw new IllegalArgumentException( + "SQLField '" + sqlField.name + "' of " + getClass().getName() + " is a NOT NULL field"); } - - if (modify) { - if (!values.containsKey(sqlField)) { + else if (sqlField.type.isAssignableFrom(value)) modify = true; + else + throw new IllegalArgumentException("SQLField '" + sqlField.name + "' of " + getClass().getName() + + " type is '" + sqlField.type.toString() + "' and can't accept values of type " + + value.getClass().getName()); + + if (modify) if (!values.containsKey(sqlField)) { + values.put(sqlField, value); + if (setModified) modifiedSinceLastSave.add(sqlField.name); + } + else { + Object oldVal = values.get(sqlField); + if (!Objects.equals(oldVal, value)) { values.put(sqlField, value); - if (setModified) - modifiedSinceLastSave.add(sqlField.name); + if (setModified) modifiedSinceLastSave.add(sqlField.name); } - else { - Object oldVal = values.get(sqlField); - if (!Objects.equals(oldVal, value)) { - values.put(sqlField, value); - if (setModified) - modifiedSinceLastSave.add(sqlField.name); - } - // sinon, rien n'est modifié - } - + // sinon, rien n'est modifié } - + } - - + public T get(SQLField field) { - if (field == null) - throw new IllegalArgumentException("field can't be null"); + if (field == null) throw new IllegalArgumentException("field can't be null"); if (values.containsKey(field)) { @SuppressWarnings("unchecked") T val = (T) values.get(field); return val; } - throw new IllegalArgumentException("The field '" + field.name + "' in this instance of " + getClass().getName() + " does not exist or is not set"); + throw new IllegalArgumentException("The field '" + field.name + "' in this instance of " + getClass().getName() + + " does not exist or is not set"); } - - + 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.values()); } - - - + private Map, Object> getOnlyModifiedValues() { Map, Object> modifiedValues = new LinkedHashMap<>(); values.forEach((k, v) -> { - if (modifiedSinceLastSave.contains(k.name)) - modifiedValues.put(k, v); + if (modifiedSinceLastSave.contains(k.name)) modifiedValues.put(k, v); }); return modifiedValues; } - - - + public boolean isModified(SQLField field) { return modifiedSinceLastSave.contains(field.name); } - - - + public void save() throws ORMException { if (!isValidForSave()) throw new IllegalStateException(toString() + " has at least one undefined value and can't be saved."); - + ORM.initTable(getClass()); 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 values + + 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(); - - if (modifiedValues.isEmpty()) - return; - + + if (modifiedValues.isEmpty()) return; + String sql = ""; List psValues = new ArrayList<>(); - - for(Map.Entry, Object> entry : modifiedValues.entrySet()) { + + for (Map.Entry, Object> entry : modifiedValues.entrySet()) { sql += entry.getKey().name + " = ? ,"; - if (entry.getKey().type.getJavaType().isEnum()) { - // prise en charge enum (non prise en charge par JDBC) - psValues.add(((Enum)entry.getValue()).name()); - } + if (entry.getKey().type.getJavaType().isEnum()) // prise en + // charge + // enum (non + // prise en + // charge + // par JDBC) + psValues.add(((Enum) entry.getValue()).name()); else 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); - + + 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) { + for (Object val : psValues) ps.setObject(i++, val); - } toStringStatement = ps.toString(); ps.executeUpdate(); @@ -283,19 +233,18 @@ public abstract class SQLElement { ps.close(); } } - else - { // ajouter dans la base - - // restaurer l'ID au cas il aurait été changé à la main dans values + 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()) { + for (Map.Entry, Object> entry : values.entrySet()) { if (!first) { concat_vals += ","; concat_fields += ","; @@ -303,33 +252,33 @@ public abstract class SQLElement { first = false; concat_vals += " ? "; concat_fields += entry.getKey().name; - if (entry.getKey().type.getJavaType().isEnum()) { - // prise en charge enum (non prise en charge par JDBC) - psValues.add(((Enum)entry.getValue()).name()); - } + if (entry.getKey().type.getJavaType().isEnum()) // prise en + // charge + // enum (non + // prise en + // charge + // par JDBC) + psValues.add(((Enum) entry.getValue()).name()); else psValues.add(entry.getValue()); } - - - PreparedStatement ps = conn.prepareStatement("INSERT INTO "+tableName+" ("+concat_fields+") VALUES ("+concat_vals+")", Statement.RETURN_GENERATED_KEYS); + + PreparedStatement ps = conn.prepareStatement( + "INSERT INTO " + tableName + " (" + concat_fields + ") VALUES (" + concat_vals + ")", + Statement.RETURN_GENERATED_KEYS); try { - + int i = 1; - for (Object val : psValues) { + for (Object val : psValues) ps.setObject(i++, val); - } toStringStatement = ps.toString(); ps.executeUpdate(); - + ResultSet rs = ps.getGeneratedKeys(); try { - if(rs.next()) - { - id = rs.getInt(1); - } - + if (rs.next()) id = rs.getInt(1); + stored = true; } finally { rs.close(); @@ -337,38 +286,35 @@ public abstract class SQLElement { } finally { ps.close(); } - + } - + modifiedSinceLastSave.clear(); - } catch(SQLException e) { - throw new ORMException("Error while executing SQL statement "+toStringStatement, e); + } catch (SQLException e) { + throw new ORMException("Error while executing SQL statement " + toStringStatement, e); } Log.debug(toStringStatement); } - - - public boolean isStored() { return stored; } - + + public boolean isStored() { + return stored; + } + public Integer getId() { return (stored) ? id : null; } - + @SuppressWarnings("unchecked") public SQLField getFieldId() { return (SQLField) getFields().get("id"); } - - - - - + 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); + 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(); @@ -380,11 +326,12 @@ public abstract class SQLElement { } catch (SQLException e) { throw new ORMException(e); } - + } - + /** - * Méthode appelée quand l'élément courant est retirée de la base de données via une requête externe + * Méthode appelée quand l'élément courant est retirée de la base de données + * via une requête externe */ /* package */ void markAsNotStored() { stored = false; @@ -392,50 +339,38 @@ public abstract class SQLElement { modifiedSinceLastSave.clear(); values.forEach((k, v) -> modifiedSinceLastSave.add(k.name)); } - - - - + protected static class SQLFieldMap extends LinkedHashMap> { private static final long serialVersionUID = 1L; - + private final Class sqlElemClass; - + private SQLFieldMap(Class elemClass) { sqlElemClass = elemClass; } - + private void addField(SQLField f) { if (f == null) return; - if (containsKey(f.name)) - throw new IllegalArgumentException("SQLField "+f.name+" already exist in "+sqlElemClass.getName()); + if (containsKey(f.name)) throw new IllegalArgumentException( + "SQLField " + f.name + " already exist in " + sqlElemClass.getName()); f.setSQLElementType(sqlElemClass); put(f.name, f); } - + } - - - - + @Override public String toString() { ToStringBuilder b = new ToStringBuilder(this); - - for (SQLField f : fields.values()) { + + for (SQLField f : fields.values()) try { b.append(f.name, get(f)); - } catch(IllegalArgumentException e) { + } catch (IllegalArgumentException e) { b.append(f.name, "(Undefined)"); } - - } - + return b.toString(); } - - - - - + } diff --git a/src/fr/pandacube/java/util/db2/sql_tools/SQLElementList.java b/src/fr/pandacube/java/util/db2/sql_tools/SQLElementList.java index 2030aaa..988f2e3 100644 --- a/src/fr/pandacube/java/util/db2/sql_tools/SQLElementList.java +++ b/src/fr/pandacube/java/util/db2/sql_tools/SQLElementList.java @@ -10,25 +10,29 @@ import java.util.Map; import fr.pandacube.java.util.Log; /** - * + * * @param */ public class SQLElementList extends ArrayList { private static final long serialVersionUID = 1L; private final Map, Object> modifiedValues = new LinkedHashMap<>(); - + @Override public synchronized boolean add(E e) { if (e == null || !e.isStored()) return false; return super.add(e); } - + /** - * Défini une valeur à un champ qui sera appliquée dans la base de données à tous les - * entrées présente dans cette liste lors de l'appel à {@link #saveCommon()}. - * Les valeurs stockés dans chaque élément de cette liste ne seront affectés que lors de + * Défini une valeur à un champ qui sera appliquée dans la base de données à + * tous les + * entrées présente dans cette liste lors de l'appel à {@link #saveCommon()} + * . + * Les valeurs stockés dans chaque élément de cette liste ne seront affectés + * que lors de * l'appel à {@link #saveCommon()} + * * @param * @param field le champs à modifier * @param value la valeur à lui appliquer @@ -37,72 +41,73 @@ public class SQLElementList extends ArrayList { if (field != null && field.name == "id") throw new IllegalArgumentException("Can't modify id field in a SQLElementList"); @SuppressWarnings("unchecked") - + Class elemClass = (Class) field.getSQLElementType(); try { E emptyElement = elemClass.newInstance(); emptyElement.set(field, value, false); } catch (Exception e) { - throw new IllegalArgumentException("Illegal field or value or can't instanciante an empty instance of " + elemClass.getName() + ". (the instance is only created to test validity of field and value)", e); + throw new IllegalArgumentException("Illegal field or value or can't instanciante an empty instance of " + + elemClass.getName() + ". (the instance is only created to test validity of field and value)", e); } - + // ici, la valeur est bonne modifiedValues.put(field, value); - + } - - - - - - - + /** - * Applique toutes les valeurs défini avec {@link #setCommon(SQLField, Object)} à toutes - * les entrées dans la base de données correspondants aux entrées de cette liste. Les nouvelles - * valeurs sont aussi mises à jour dans les objets contenus dans cette liste, si la valeur n'a pas été modifiée individuellement avec {@link SQLElement#set(SQLField, Object)}.
- * Les objets de cette liste qui n'ont pas leur données en base de données sont ignorées. - * @throws SQLException + * Applique toutes les valeurs défini avec + * {@link #setCommon(SQLField, Object)} à toutes + * les entrées dans la base de données correspondants aux entrées de cette + * liste. Les nouvelles + * valeurs sont aussi mises à jour dans les objets contenus dans cette + * liste, si la valeur n'a pas été modifiée individuellement avec + * {@link SQLElement#set(SQLField, Object)}.
+ * Les objets de cette liste qui n'ont pas leur données en base de données + * sont ignorées. + * + * @throws SQLException */ public synchronized void saveCommon() throws SQLException { List storedEl = getStoredEl(); if (storedEl.isEmpty()) return; - + String sqlSet = ""; List psValues = new ArrayList<>(); - - for(Map.Entry, Object> entry : modifiedValues.entrySet()) { + + for (Map.Entry, Object> entry : modifiedValues.entrySet()) { sqlSet += entry.getKey().name + " = ? ,"; - if (entry.getKey().type.getJavaType().isEnum()) { - // prise en charge enum (non prise en charge par JDBC) - psValues.add(((Enum)entry.getValue()).name()); - } + if (entry.getKey().type.getJavaType().isEnum()) // prise en charge + // enum (non prise + // en charge par + // JDBC) + psValues.add(((Enum) entry.getValue()).name()); else psValues.add(entry.getValue()); } - - if (sqlSet.length() > 0) - sqlSet = sqlSet.substring(0, sqlSet.length()-1); - + + if (sqlSet.length() > 0) sqlSet = sqlSet.substring(0, sqlSet.length() - 1); + String sqlWhere = ""; boolean first = true; for (E el : storedEl) { if (!first) sqlWhere += " OR "; first = false; - sqlWhere += "id = "+el.getId(); + sqlWhere += "id = " + el.getId(); } - - PreparedStatement ps = ORM.getConnection().getNativeConnection().prepareStatement("UPDATE "+storedEl.get(0).tableName()+" SET "+sqlSet+" WHERE "+sqlWhere); + + PreparedStatement ps = ORM.getConnection().getNativeConnection() + .prepareStatement("UPDATE " + storedEl.get(0).tableName() + " SET " + sqlSet + " WHERE " + sqlWhere); try { int i = 1; - for (Object val : psValues) { + for (Object val : psValues) ps.setObject(i++, val); - } - + Log.debug(ps.toString()); ps.executeUpdate(); - + applyNewValuesToElements(storedEl); } finally { ps.close(); @@ -112,16 +117,12 @@ public class SQLElementList extends ArrayList { @SuppressWarnings("unchecked") private void applyNewValuesToElements(List storedEl) { // applique les valeurs dans chaques objets de la liste - for (E el : storedEl) { - for (@SuppressWarnings("rawtypes") SQLField entry : modifiedValues.keySet()) { - if (!el.isModified(entry)) - el.set(entry, modifiedValues.get(entry), false); - } - } + for (E el : storedEl) + for (@SuppressWarnings("rawtypes") + SQLField entry : modifiedValues.keySet()) + if (!el.isModified(entry)) el.set(entry, modifiedValues.get(entry), false); } - - - + private List getStoredEl() { List listStored = new ArrayList<>(); forEach(el -> { @@ -129,46 +130,38 @@ public class SQLElementList extends ArrayList { }); return listStored; } - - - + public synchronized void removeFromDB() { List storedEl = getStoredEl(); if (storedEl.isEmpty()) return; - + try { - + String sqlWhere = ""; boolean first = true; for (E el : storedEl) { if (!first) sqlWhere += " OR "; first = false; - sqlWhere += "id = "+el.getId(); + sqlWhere += "id = " + el.getId(); } - - PreparedStatement st = ORM.getConnection().getNativeConnection().prepareStatement("DELETE FROM "+storedEl.get(0).tableName()+" WHERE "+sqlWhere); + + PreparedStatement st = ORM.getConnection().getNativeConnection() + .prepareStatement("DELETE FROM " + storedEl.get(0).tableName() + " WHERE " + sqlWhere); try { Log.debug(st.toString()); st.executeUpdate(); - - for (E el : storedEl) { + + for (E el : storedEl) el.markAsNotStored(); - } - + } finally { st.close(); } - + } catch (SQLException e) { e.printStackTrace(); } - + } - - - - - - - + } diff --git a/src/fr/pandacube/java/util/db2/sql_tools/SQLFKField.java b/src/fr/pandacube/java/util/db2/sql_tools/SQLFKField.java index bbc3c2b..f90cf74 100644 --- a/src/fr/pandacube/java/util/db2/sql_tools/SQLFKField.java +++ b/src/fr/pandacube/java/util/db2/sql_tools/SQLFKField.java @@ -6,39 +6,39 @@ 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) { + + 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); + 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) { + + 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); + 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"); @@ -55,9 +55,13 @@ public class SQLFKField extends SQLField { sqlForeignKeyField = fkF; sqlForeignKeyElement = fkEl; } - - - public SQLField getForeignField() { return sqlForeignKeyField; } - public Class getForeignElementClass() { return sqlForeignKeyElement; } + + public SQLField getForeignField() { + return sqlForeignKeyField; + } + + public Class getForeignElementClass() { + return sqlForeignKeyElement; + } } diff --git a/src/fr/pandacube/java/util/db2/sql_tools/SQLField.java b/src/fr/pandacube/java/util/db2/sql_tools/SQLField.java index aad7872..8093221 100644 --- a/src/fr/pandacube/java/util/db2/sql_tools/SQLField.java +++ b/src/fr/pandacube/java/util/db2/sql_tools/SQLField.java @@ -6,14 +6,14 @@ import java.util.List; import javafx.util.Pair; public class SQLField { - + private Class sqlElemClass; public final String name; public final SQLType type; public final boolean canBeNull; public final boolean autoIncrement; /* package */ final T defaultValue; - + public SQLField(String n, SQLType t, boolean nul, boolean autoIncr, T deflt) { name = n; type = t; @@ -21,52 +21,47 @@ public class SQLField { autoIncrement = autoIncr; defaultValue = deflt; } - + public SQLField(String n, SQLType t, boolean nul) { this(n, t, nul, false, null); } - + public SQLField(String n, SQLType t, boolean nul, boolean autoIncr) { this(n, t, nul, autoIncr, null); } - + public SQLField(String n, SQLType t, boolean nul, T deflt) { this(n, t, nul, false, deflt); } - + /* package */ Pair> forSQLPreparedStatement() { List params = new ArrayList<>(1); - if (defaultValue != null && !autoIncrement) - params.add(defaultValue); - return new Pair<>(name - + " "+ type.toString() - + (canBeNull ? " NULL" : " NOT NULL") - + (autoIncrement ? " AUTO_INCREMENT" : "") - + ((defaultValue == null || autoIncrement) ? "" : " DEFAULT ?"), - params); + if (defaultValue != null && !autoIncrement) params.add(defaultValue); + return new Pair<>(name + " " + type.toString() + (canBeNull ? " NULL" : " NOT NULL") + + (autoIncrement ? " AUTO_INCREMENT" : "") + + ((defaultValue == null || autoIncrement) ? "" : " DEFAULT ?"), params); } - + /* package */ void setSQLElementType(Class elemClass) { sqlElemClass = elemClass; } - + public Class getSQLElementType() { return sqlElemClass; } - - + /** * Don't use this {@link #toString()} method in a SQL query, because * the default value is not escaped correctly + * * @see java.lang.Object#toString() */ @Override public String toString() { - return forSQLPreparedStatement().getKey().replaceFirst("\\?", (defaultValue != null && !autoIncrement) ? defaultValue.toString() : ""); + return forSQLPreparedStatement().getKey().replaceFirst("\\?", + (defaultValue != null && !autoIncrement) ? defaultValue.toString() : ""); } - - - + @Override public boolean equals(Object obj) { if (obj == null) return false; @@ -76,11 +71,10 @@ public class SQLField { if (!f.sqlElemClass.equals(sqlElemClass)) return false; return true; } - + @Override public int hashCode() { return name.hashCode() + sqlElemClass.hashCode(); } - - + } 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 0986ab0..68d0f04 100644 --- a/src/fr/pandacube/java/util/db2/sql_tools/SQLOrderBy.java +++ b/src/fr/pandacube/java/util/db2/sql_tools/SQLOrderBy.java @@ -4,16 +4,17 @@ import java.util.ArrayList; import java.util.List; public class SQLOrderBy { - + private List orderByFields = new ArrayList<>(); - + /** * Construit une nouvelle clause ORDER BY */ public SQLOrderBy() {} - + /** * 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) @@ -22,18 +23,18 @@ public class SQLOrderBy { 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); } - - + /* package */ String toSQL() { String ret = ""; boolean first = true; @@ -44,25 +45,23 @@ public class SQLOrderBy { } return ret; } - + @Override public String toString() { return toSQL(); } - - + private class OBField { public final SQLField field; public final Direction direction; - + public OBField(SQLField f, Direction d) { field = f; direction = d; } - - + } - + 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 904c774..cba255e 100644 --- a/src/fr/pandacube/java/util/db2/sql_tools/SQLType.java +++ b/src/fr/pandacube/java/util/db2/sql_tools/SQLType.java @@ -3,97 +3,88 @@ package fr.pandacube.java.util.db2.sql_tools; import java.sql.Date; public class SQLType { - + private final String sqlType; private final String sqlTypeParam; private final Class javaTypes; - + public SQLType(String sqlT, String sqlP, Class javaT) { sqlType = sqlT; sqlTypeParam = sqlP; javaTypes = javaT; } - + @Override public String toString() { return sqlType + sqlTypeParam; } - + public boolean isAssignableFrom(Object val) { - if (javaTypes.isInstance(val)) - return true; + if (javaTypes.isInstance(val)) return true; 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()); + if (obj == null || !(obj instanceof SQLType)) return false; + return toString().equals(((SQLType) obj).toString()); } - + public Class getJavaType() { return javaTypes; } - - - - - - + public static final SQLType BOOLEAN = new SQLType<>("BOOLEAN", "", Boolean.class); - + public static final SQLType TINYINT = new SQLType<>("TINYINT", "", Byte.class); public static final SQLType BYTE = TINYINT; - + public static final SQLType SMALLINT = new SQLType<>("SMALLINT", "", Short.class); public static final SQLType SHORT = SMALLINT; - + public static final SQLType INT = new SQLType<>("INT", "", Integer.class); public static final SQLType INTEGER = INT; - + public static final SQLType BIGINT = new SQLType<>("BIGINT", "", Long.class); public static final SQLType LONG = BIGINT; - + public static final SQLType DATE = new SQLType<>("DATE", "", Date.class); - + public static final SQLType FLOAT = new SQLType<>("FLOAT", "", Float.class); - + public static final SQLType DOUBLE = new SQLType<>("DOUBLE", "", Double.class); - + public static final SQLType CHAR(int charCount) { if (charCount <= 0) throw new IllegalArgumentException("charCount must be positive."); - return new SQLType<>("CHAR", "("+charCount+")", String.class); + return new SQLType<>("CHAR", "(" + charCount + ")", String.class); } - + public static final SQLType VARCHAR(int charCount) { if (charCount <= 0) throw new IllegalArgumentException("charCount must be positive."); - return new SQLType<>("VARCHAR", "("+charCount+")", String.class); + return new SQLType<>("VARCHAR", "(" + charCount + ")", String.class); } - + public static final SQLType TEXT = new SQLType<>("TEXT", "", String.class); public static final SQLType STRING = TEXT; - + public static final > SQLType ENUM(Class enumType) { if (enumType == null) throw new IllegalArgumentException("enumType can't be null."); String enumStr = "'"; boolean first = true; for (T el : enumType.getEnumConstants()) { - if (!first) - enumStr += "', '"; + if (!first) enumStr += "', '"; first = false; enumStr += el.name(); - + } enumStr += "'"; - - return new SQLType<>("VARCHAR", "("+enumStr+")", enumType); + + return new SQLType<>("VARCHAR", "(" + enumStr + ")", enumType); } - - + } diff --git a/src/fr/pandacube/java/util/db2/sql_tools/SQLWhere.java b/src/fr/pandacube/java/util/db2/sql_tools/SQLWhere.java index 8e6e93f..2233b67 100644 --- a/src/fr/pandacube/java/util/db2/sql_tools/SQLWhere.java +++ b/src/fr/pandacube/java/util/db2/sql_tools/SQLWhere.java @@ -5,17 +5,12 @@ import java.util.List; import javafx.util.Pair; public abstract class SQLWhere { - - - - - + public abstract Pair> toSQL(); - - + @Override public String toString() { return toSQL().getKey(); } - + } 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 98200d9..d55ff7b 100644 --- a/src/fr/pandacube/java/util/db2/sql_tools/SQLWhereChain.java +++ b/src/fr/pandacube/java/util/db2/sql_tools/SQLWhereChain.java @@ -6,55 +6,49 @@ import java.util.List; import javafx.util.Pair; public class SQLWhereChain extends SQLWhere { - + private SQLBoolOp operator; private List conditions = new ArrayList<>(); - + public SQLWhereChain(SQLBoolOp op) { - if (op == null) - throw new IllegalArgumentException("op can't be null"); + if (op == null) throw new IllegalArgumentException("op can't be null"); operator = op; } - - + public SQLWhereChain add(SQLWhere sqlWhere) { - if (sqlWhere == null) - throw new IllegalArgumentException("sqlWhere can't be null"); + if (sqlWhere == null) throw new IllegalArgumentException("sqlWhere can't be null"); conditions.add(sqlWhere); return this; } - @Override public Pair> toSQL() { String sql = ""; List params = new ArrayList<>(); boolean first = true; - + for (SQLWhere w : conditions) { if (!first) sql += " " + operator.sql + " "; first = false; - + Pair> ret = w.toSQL(); sql += "(" + ret.getKey() + ")"; params.addAll(ret.getValue()); } - + return new Pair<>(sql, params); } - public enum SQLBoolOp { /** Equivalent to SQL "AND" */ - AND("AND"), - /** Equivalent to SQL "OR" */ + AND("AND"), /** Equivalent to SQL "OR" */ OR("OR"); public final String sql; - + private SQLBoolOp(String s) { sql = s; } - + } } 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 ba06d9b..497772e 100644 --- a/src/fr/pandacube/java/util/db2/sql_tools/SQLWhereComp.java +++ b/src/fr/pandacube/java/util/db2/sql_tools/SQLWhereComp.java @@ -6,13 +6,14 @@ import java.util.List; import javafx.util.Pair; public class SQLWhereComp extends SQLWhere { - + private SQLField left; private SQLComparator comp; private Object right; - + /** * 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 @@ -22,41 +23,31 @@ public class SQLWhereComp extends SQLWhere { throw new IllegalArgumentException("All arguments for SQLWhereComp constructor can't be null"); left = l; comp = c; - right = r; + right = r; } - - - - + @Override - public Pair> toSQL() { + public Pair> toSQL() { List params = new ArrayList<>(); params.add(right); return new Pair<>(left.name + " " + comp.sql + " ? ", params); } - - + public enum SQLComparator { /** Equivalent to SQL "=" */ - EQ("="), - /** Equivalent to SQL ">" */ - GT(">"), - /** Equivalent to SQL ">=" */ - GEQ(">="), - /** Equivalent to SQL "<" */ - LT("<"), - /** Equivalent to SQL "<=" */ - LEQ("<="), - /** Equivalent to SQL "!=" */ + EQ("="), /** Equivalent to SQL ">" */ + GT(">"), /** Equivalent to SQL ">=" */ + GEQ(">="), /** Equivalent to SQL "<" */ + LT("<"), /** Equivalent to SQL "<=" */ + LEQ("<="), /** Equivalent to SQL "!=" */ NEQ("!="); - + public final String sql; - + private SQLComparator(String s) { sql = s; } - + } - - + } 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 edad30b..eabf7b9 100644 --- a/src/fr/pandacube/java/util/db2/sql_tools/SQLWhereLike.java +++ b/src/fr/pandacube/java/util/db2/sql_tools/SQLWhereLike.java @@ -6,13 +6,13 @@ import java.util.List; import javafx.util.Pair; public class SQLWhereLike extends SQLWhere { - private SQLField field; private String likeExpr; - + /** * Compare a field with a value + * * @param f the field at left of the LIKE keyword. Can't be null * @param like the like expression. */ @@ -22,8 +22,7 @@ public class SQLWhereLike extends SQLWhere { field = f; likeExpr = like; } - - + @Override public Pair> toSQL() { ArrayList params = new ArrayList<>(); 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 15781a5..37c424b 100644 --- a/src/fr/pandacube/java/util/db2/sql_tools/SQLWhereNull.java +++ b/src/fr/pandacube/java/util/db2/sql_tools/SQLWhereNull.java @@ -8,30 +8,29 @@ import fr.pandacube.java.util.Log; import javafx.util.Pair; public class SQLWhereNull extends SQLWhere { - + private SQLField fild; private boolean nulll; - + /** * Init a IS NULL / IS NOT NULL expression for a SQL WHERE condition. + * * @param field the field to check null / not null state - * @param isNull true if we want to ckeck if "IS NULL", or false to check if "IS NOT NULL" + * @param isNull true if we want to ckeck if "IS NULL", or false to check if + * "IS NOT NULL" */ public SQLWhereNull(SQLField field, boolean isNull) { - if (field == null) - throw new IllegalArgumentException("field can't be null"); - if (!field.canBeNull) - 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'"); + if (field == null) throw new IllegalArgumentException("field can't be null"); + if (!field.canBeNull) 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; } - - + @Override public Pair> toSQL() { - return new Pair<>(fild.name + " IS" + ((nulll)?" NULL":" NOT NULL"), new ArrayList<>()); + return new Pair<>(fild.name + " IS" + ((nulll) ? " NULL" : " NOT NULL"), new ArrayList<>()); } - - - + } diff --git a/src/fr/pandacube/java/util/measurement/DistanceUtil.java b/src/fr/pandacube/java/util/measurement/DistanceUtil.java index 11bba47..3f1ba6a 100644 --- a/src/fr/pandacube/java/util/measurement/DistanceUtil.java +++ b/src/fr/pandacube/java/util/measurement/DistanceUtil.java @@ -6,58 +6,42 @@ import java.util.Arrays; public class DistanceUtil { public static String distanceToString(double meterDist, int precision, DistanceUnit... desiredUnits) { - - + Arrays.sort(desiredUnits); - + DistanceUnit choosenUnit = desiredUnits[0]; // la plus petite unitée for (DistanceUnit unit : desiredUnits) { - if (meterDist / unit.multiplicator < 1) - continue; + if (meterDist / unit.multiplicator < 1) continue; choosenUnit = unit; } - - if (choosenUnit != desiredUnits[0] && precision <= 2) - precision = 2; - - + + if (choosenUnit != desiredUnits[0] && precision <= 2) precision = 2; + String precisionFormat = "##0"; - if (precision > 0) - precisionFormat += "."; - for (int i=0;i 0) precisionFormat += "."; + for (int i = 0; i < precision; i++) precisionFormat += "0"; DecimalFormat df = new DecimalFormat(precisionFormat); - + double dist = meterDist / choosenUnit.multiplicator; - - return df.format(dist)+choosenUnit.unitStr; + + return df.format(dist) + choosenUnit.unitStr; } - + public static String distanceToString(double meterDist, int precision) { return distanceToString(meterDist, precision, DistanceUnit.M, DistanceUnit.KM); } - - - - - - + public enum DistanceUnit implements Comparable { - NM(0.000000001, "nm"), - µM(0.000001, "µm"), - MM(0.001, "mm"), - CM(0.01, "cm"), - M(1, "m"), - KM(1000, "km"); - - + NM(0.000000001, "nm"), µM(0.000001, "µm"), MM(0.001, "mm"), CM(0.01, "cm"), M(1, "m"), KM(1000, "km"); + private final double multiplicator; private final String unitStr; - + private DistanceUnit(double mult, String s) { multiplicator = mult; unitStr = s; } } - + } diff --git a/src/fr/pandacube/java/util/measurement/MemoryUtil.java b/src/fr/pandacube/java/util/measurement/MemoryUtil.java index f371938..bac4099 100644 --- a/src/fr/pandacube/java/util/measurement/MemoryUtil.java +++ b/src/fr/pandacube/java/util/measurement/MemoryUtil.java @@ -3,33 +3,26 @@ package fr.pandacube.java.util.measurement; import java.text.DecimalFormat; public class MemoryUtil { - + private static final DecimalFormat format = new DecimalFormat("#####0.00"); - - public static String humanReadableSize(long octet, boolean si) - { - + + public static String humanReadableSize(long octet, boolean si) { + double size = octet; - + int diveBy = si ? 1000 : 1024; - - - if (size < diveBy) - return size+"o"; + + if (size < diveBy) return size + "o"; size /= diveBy; - if (size < diveBy) - return format.format(size) + (si ? "ko" : "kio"); + if (size < diveBy) return format.format(size) + (si ? "ko" : "kio"); size /= diveBy; - if (size < diveBy) - return format.format(size) + (si ? "Mo" : "Mio"); + if (size < diveBy) return format.format(size) + (si ? "Mo" : "Mio"); size /= diveBy; - if (size < diveBy) - return format.format(size) + (si ? "Go" : "Gio"); + if (size < diveBy) return format.format(size) + (si ? "Go" : "Gio"); size /= diveBy; - + return format.format(size) + (si ? "To" : "Tio"); } - public static String humanReadableSize(long octet) { return humanReadableSize(octet, false); diff --git a/src/fr/pandacube/java/util/measurement/TimeUtil.java b/src/fr/pandacube/java/util/measurement/TimeUtil.java index 5860ad6..9483c15 100644 --- a/src/fr/pandacube/java/util/measurement/TimeUtil.java +++ b/src/fr/pandacube/java/util/measurement/TimeUtil.java @@ -1,41 +1,36 @@ package fr.pandacube.java.util.measurement; public class TimeUtil { - public static String durationToString (long msec_time, boolean dec_seconde) - { + public static String durationToString(long msec_time, boolean dec_seconde) { int j = 0, h = 0, m = 0, s = 0; long msec = msec_time; - + j = (int) (msec / (1000 * 60 * 60 * 24)); - msec -= (long)(1000 * 60 * 60 * 24) * j; + msec -= (long) (1000 * 60 * 60 * 24) * j; h = (int) (msec / (1000 * 60 * 60)); - msec -= (long)(1000 * 60 * 60) * h; + msec -= (long) (1000 * 60 * 60) * h; m = (int) (msec / (1000 * 60)); - msec -= (long)(1000 * 60) * m; + msec -= (long) (1000 * 60) * m; s = (int) (msec / 1000); - msec -= (long)1000 * s; - + msec -= (long) 1000 * s; + String result = ""; - if (j>0) result = result.concat(j+"j "); - if (h>0) result = result.concat(h+"h "); - if (m>0) result = result.concat(m+"m "); - if (s>0 && !dec_seconde) result = result.concat(s+"s"); - else if (dec_seconde && (s>0 || msec > 0)) - { - msec += s*1000; - result = result.concat((msec/1000D)+"s"); + if (j > 0) result = result.concat(j + "j "); + if (h > 0) result = result.concat(h + "h "); + if (m > 0) result = result.concat(m + "m "); + if (s > 0 && !dec_seconde) result = result.concat(s + "s"); + else if (dec_seconde && (s > 0 || msec > 0)) { + msec += s * 1000; + result = result.concat((msec / 1000D) + "s"); } - - if (result.equals("")) - result = "0"; - + + if (result.equals("")) result = "0"; + return result.trim(); } - - public static String durationToString (long msec_time) - { + + public static String durationToString(long msec_time) { return durationToString(msec_time, false); } - - + } diff --git a/src/fr/pandacube/java/util/network/client/TCPClient.java b/src/fr/pandacube/java/util/network/client/TCPClient.java index e3afee2..4f82ef1 100644 --- a/src/fr/pandacube/java/util/network/client/TCPClient.java +++ b/src/fr/pandacube/java/util/network/client/TCPClient.java @@ -20,23 +20,19 @@ import fr.pandacube.java.util.network.packet.PacketException; import fr.pandacube.java.util.network.packet.PacketServer; public class TCPClient extends Thread implements Closeable { - + private Socket socket; private SocketAddress addr; private TCPClientListener listener; private InputStream in; private OutputStream out; private Object outSynchronizer = new Object(); - + private AtomicBoolean isClosed = new AtomicBoolean(false); - - - - + public TCPClient(InetSocketAddress a, String connName, TCPClientListener l) throws IOException { - super("TCPCl "+connName); - if (a == null || l == null) - throw new IllegalArgumentException("les arguments ne peuvent pas être null"); + super("TCPCl " + connName); + if (a == null || l == null) throw new IllegalArgumentException("les arguments ne peuvent pas être null"); socket = new Socket(); socket.setReceiveBufferSize(Pandacube.NETWORK_TCP_BUFFER_SIZE); socket.setSendBufferSize(Pandacube.NETWORK_TCP_BUFFER_SIZE); @@ -46,47 +42,43 @@ public class TCPClient extends Thread implements Closeable { listener = l; listener.onConnect(this); } - - + @Override public void run() { - + try { byte[] code = new byte[1]; - while(!socket.isClosed() && in.read(code) != -1) { + while (!socket.isClosed() && in.read(code) != -1) { byte[] sizeB = new byte[4]; - if (in.read(sizeB) != 4) - throw new IOException("Socket "+addr+" fermé"); - + if (in.read(sizeB) != 4) throw new IOException("Socket " + addr + " fermé"); + int size = ByteBuffer.wrap(sizeB).getInt(); - + byte[] content = new byte[size]; - + forceReadBytes(content); - - byte[] packetData = ByteBuffer.allocate(1+4+size).put(code).put(sizeB).put(content).array(); - - + + byte[] packetData = ByteBuffer.allocate(1 + 4 + size).put(code).put(sizeB).put(content).array(); + try { - if (listener == null) - throw new InvalidServerMessage("Le serveur ne peut actuellement pas prendre en charge de nouvelles requêtes. Les listeners n'ont pas encore été définis"); - + if (listener == null) throw new InvalidServerMessage( + "Le serveur ne peut actuellement pas prendre en charge de nouvelles requêtes. Les listeners n'ont pas encore été définis"); + Packet p = Packet.constructPacket(packetData); - - if (!(p instanceof PacketServer)) - throw new InvalidServerMessage("Le type de packet reçu n'est pas un packet attendu : "+p.getClass().getCanonicalName()); - + + if (!(p instanceof PacketServer)) throw new InvalidServerMessage( + "Le type de packet reçu n'est pas un packet attendu : " + p.getClass().getCanonicalName()); + PacketServer ps = (PacketServer) p; - + listener.onPacketReceive(this, ps); - } catch (PacketException|InvalidServerMessage e) { + } catch (PacketException | InvalidServerMessage e) { Log.getLogger().log(Level.SEVERE, "Message du serveur mal formé", e); } catch (Exception e) { Log.getLogger().log(Level.SEVERE, "Erreur lors de la prise en charge du message par le serveur", e); } } - - + } catch (SocketTimeoutException e) { System.err.println("Le serveur a prit trop de temps à répondre"); } catch (Exception e) { @@ -94,35 +86,28 @@ public class TCPClient extends Thread implements Closeable { } close(); } - - private void forceReadBytes(byte[] buff) throws IOException { int pos = 0; do { - int nbR = in.read(buff, pos, buff.length-pos); - if (nbR == -1) - throw new IOException("Can't read required amount of byte"); + int nbR = in.read(buff, pos, buff.length - pos); + if (nbR == -1) throw new IOException("Can't read required amount of byte"); pos += nbR; } while (pos < buff.length); } - - - public void send(PacketClient packet) throws IOException { synchronized (outSynchronizer) { out.write(packet.getFullSerializedPacket()); out.flush(); } } - + @Override public void close() { try { synchronized (outSynchronizer) { - if (isClosed.get()) - return; + if (isClosed.get()) return; socket.close(); isClosed.set(true); listener.onDisconnect(this); @@ -131,37 +116,27 @@ public class TCPClient extends Thread implements Closeable { e.printStackTrace(); } } - - + public void sendSilently(PacketClient packet) { try { send(packet); - } catch (IOException e) { } + } catch (IOException e) {} } - - - - - + public SocketAddress getServerAddress() { return addr; } - - - + public boolean isClosed() { return isClosed.get() || socket.isClosed(); } - - - - - + public static class InvalidServerMessage extends RuntimeException { private static final long serialVersionUID = 1L; + public InvalidServerMessage(String message) { super(message); } } - + } diff --git a/src/fr/pandacube/java/util/network/client/TCPClientListener.java b/src/fr/pandacube/java/util/network/client/TCPClientListener.java index d1c8f69..13ef999 100644 --- a/src/fr/pandacube/java/util/network/client/TCPClientListener.java +++ b/src/fr/pandacube/java/util/network/client/TCPClientListener.java @@ -3,11 +3,11 @@ package fr.pandacube.java.util.network.client; import fr.pandacube.java.util.network.packet.PacketServer; public interface TCPClientListener { - + public void onConnect(TCPClient connection); - + public void onPacketReceive(TCPClient connection, PacketServer packet); - + public void onDisconnect(TCPClient connection); - + } diff --git a/src/fr/pandacube/java/util/network/packet/Packet.java b/src/fr/pandacube/java/util/network/packet/Packet.java index e45053a..fda089e 100644 --- a/src/fr/pandacube/java/util/network/packet/Packet.java +++ b/src/fr/pandacube/java/util/network/packet/Packet.java @@ -1,6 +1,5 @@ package fr.pandacube.java.util.network.packet; - import java.nio.charset.Charset; import java.util.Arrays; import java.util.HashMap; @@ -11,45 +10,32 @@ import fr.pandacube.java.util.network.packet.bytebuffer.ByteBuffer; import fr.pandacube.java.util.network.packet.bytebuffer.ByteSerializable; public abstract class Packet implements ByteSerializable { - + private final byte code; - + public Packet(byte c) { code = c; } - public byte getCode() { return code; } + public byte getCode() { + return code; + } public byte[] getFullSerializedPacket() { ByteBuffer internal = new ByteBuffer(CHARSET).putObject(this); byte[] data = Arrays.copyOfRange(internal.array(), 0, internal.getPosition()); - - return new ByteBuffer(5+data.length, CHARSET).putByte(code).putInt(data.length).putBytes(data).array(); + + return new ByteBuffer(5 + data.length, CHARSET).putByte(code).putInt(data.length).putBytes(data).array(); } - - - - - - - - - - - - - - - - + public static final Charset CHARSET = Pandacube.NETWORK_CHARSET; - + private static Map> packetTypes = new HashMap>(); - + public static Packet constructPacket(byte[] data) { if (!packetTypes.containsKey(data[0])) - throw new PacketException("l'identifiant du packet ne correspond à aucun type de packet : "+data[0]); - + throw new PacketException("l'identifiant du packet ne correspond à aucun type de packet : " + data[0]); + try { Packet p = packetTypes.get(data[0]).newInstance(); ByteBuffer dataBuffer = new ByteBuffer(Arrays.copyOfRange(data, 5, data.length), CHARSET); @@ -60,26 +46,23 @@ public abstract class Packet implements ByteSerializable { throw new PacketException("erreur lors de la construction du packet"); } } - + @SuppressWarnings("unused") private static void addPacket(Class packetClass) { try { - Packet p = (Packet)packetClass.newInstance(); + Packet p = packetClass.newInstance(); packetTypes.put(p.code, packetClass); } catch (Exception e) { e.printStackTrace(); } } - - - + static { - + /* * Ajout des types de packets (client + serveur) */ // addPacket(PacketToto.class); } - } diff --git a/src/fr/pandacube/java/util/network/packet/PacketClient.java b/src/fr/pandacube/java/util/network/packet/PacketClient.java index 8d83463..37eb157 100644 --- a/src/fr/pandacube/java/util/network/packet/PacketClient.java +++ b/src/fr/pandacube/java/util/network/packet/PacketClient.java @@ -5,10 +5,9 @@ package fr.pandacube.java.util.network.packet; * une connexion Client vers une connexion Serveur (d'un point de vue TCP) */ public abstract class PacketClient extends Packet { - + public PacketClient(byte c) { super(c); } - - + } diff --git a/src/fr/pandacube/java/util/network/packet/PacketException.java b/src/fr/pandacube/java/util/network/packet/PacketException.java index 6ffc86f..463c0de 100644 --- a/src/fr/pandacube/java/util/network/packet/PacketException.java +++ b/src/fr/pandacube/java/util/network/packet/PacketException.java @@ -6,11 +6,11 @@ public class PacketException extends RuntimeException { public PacketException(String m) { super(m); } - + public PacketException(String m, Throwable t) { super(m, t); } - + public PacketException(Throwable t) { super(t); } diff --git a/src/fr/pandacube/java/util/network/packet/PacketServer.java b/src/fr/pandacube/java/util/network/packet/PacketServer.java index 2b3d24e..d729719 100644 --- a/src/fr/pandacube/java/util/network/packet/PacketServer.java +++ b/src/fr/pandacube/java/util/network/packet/PacketServer.java @@ -9,5 +9,5 @@ public abstract class PacketServer extends Packet { public PacketServer(byte c) { super(c); } - + } diff --git a/src/fr/pandacube/java/util/network/packet/bytebuffer/ByteBuffer.java b/src/fr/pandacube/java/util/network/packet/bytebuffer/ByteBuffer.java index 5e584be..c9440b9 100644 --- a/src/fr/pandacube/java/util/network/packet/bytebuffer/ByteBuffer.java +++ b/src/fr/pandacube/java/util/network/packet/bytebuffer/ByteBuffer.java @@ -6,24 +6,24 @@ import java.util.Arrays; import java.util.List; public class ByteBuffer implements Cloneable { - + private java.nio.ByteBuffer buff; private Charset charset; - + public ByteBuffer(Charset c) { this(16, c); } - + public ByteBuffer(int initSize, Charset c) { buff = java.nio.ByteBuffer.allocate(initSize); charset = c; } - + public ByteBuffer(byte[] data, Charset c) { buff = java.nio.ByteBuffer.wrap(Arrays.copyOf(data, data.length)); charset = c; } - + private void askForBufferExtension(int needed) { if (buff.remaining() >= needed) return; java.nio.ByteBuffer newBuff = java.nio.ByteBuffer.wrap(Arrays.copyOf(buff.array(), buff.array().length * 2)); @@ -106,7 +106,7 @@ public class ByteBuffer implements Cloneable { * @see java.nio.ByteBuffer#put(byte[]) */ public ByteBuffer putBytes(byte[] b) { - askForBufferExtension(b.length*Byte.BYTES); + askForBufferExtension(b.length * Byte.BYTES); buff.put(b); return this; } @@ -185,21 +185,21 @@ public class ByteBuffer implements Cloneable { public int capacity() { return buff.capacity(); } - - + public ByteBuffer putString(String s) { byte[] charBytes = s.getBytes(charset); putInt(charBytes.length); putBytes(charBytes); return this; } - + public String getString() { return new String(getBytes(new byte[getInt()]), charset); } - + /** * The objet will be serialized and the data put in the current buffer + * * @param obj the object to serialize * @return the current buffer */ @@ -207,11 +207,14 @@ public class ByteBuffer implements Cloneable { obj.serializeToByteBuffer(this); return this; } - + /** - * Ask to object passed as argument to deserialize data in buffer and fill the object content + * Ask to object passed as argument to deserialize data in buffer and fill + * the object content + * * @param - * @param obj the objet to fill with his method {@link ByteSerializable#deserializeFromByteBuffer(ByteBuffer)} + * @param obj the objet to fill with his method + * {@link ByteSerializable#deserializeFromByteBuffer(ByteBuffer)} * @return obj a reference to the same object */ public T getObject(Class clazz) { @@ -223,32 +226,27 @@ public class ByteBuffer implements Cloneable { throw new RuntimeException(e); } } - + public ByteBuffer putListObject(List list) { putInt(list.size()); for (ByteSerializable obj : list) putObject(obj); return this; } - + public List getListObject(Class clazz) { List list = new ArrayList(); int size = getInt(); - for (int i=0; i *
- * Les classes concrètes implémentant cette interface doivent avoir un constructeur vide, utilisé + * Les classes concrètes implémentant cette interface doivent avoir un + * constructeur vide, utilisé * lors de la désérialisation * */ public interface ByteSerializable { - + public void serializeToByteBuffer(ByteBuffer buffer); - + public void deserializeFromByteBuffer(ByteBuffer buffer); } diff --git a/src/fr/pandacube/java/util/network/server/BandwidthCalculation.java b/src/fr/pandacube/java/util/network/server/BandwidthCalculation.java index 70b34a7..c39d295 100644 --- a/src/fr/pandacube/java/util/network/server/BandwidthCalculation.java +++ b/src/fr/pandacube/java/util/network/server/BandwidthCalculation.java @@ -7,54 +7,44 @@ import java.util.List; import fr.pandacube.java.util.network.server.TCPServer.TCPServerClientConnection; public class BandwidthCalculation { - + private List packetHistory = new LinkedList(); - - + public synchronized void addPacket(TCPServerClientConnection co, boolean in, long size) { packetHistory.add(new PacketStat(co, in, size)); } - + /** * Get the instant bandwith in byte/s - * @param input true if getting input bw, false if getting output, null if getting input + output - * @param co + * + * @param input true if getting input bw, false if getting output, null if + * getting input + output + * @param co * @return */ public synchronized long getBandWidth(Boolean input, TCPServerClientConnection co) { long currentTime = System.currentTimeMillis(); Iterator it = packetHistory.iterator(); long sum = 0; - while(it.hasNext()) { + while (it.hasNext()) { PacketStat el = it.next(); if (el.time < currentTime - 1000) { it.remove(); continue; } - if (input != null && el.input != input.booleanValue()) - continue; - if (co != null && !co.equals(el.connection)) - continue; + if (input != null && el.input != input.booleanValue()) continue; + if (co != null && !co.equals(el.connection)) continue; sum += el.packetSize; } return sum; } - - - - - - - - - - - + private class PacketStat { public final long time; public final long packetSize; public final boolean input; public final TCPServerClientConnection connection; + public PacketStat(TCPServerClientConnection co, boolean input, long size) { time = System.currentTimeMillis(); packetSize = size; diff --git a/src/fr/pandacube/java/util/network/server/TCPServer.java b/src/fr/pandacube/java/util/network/server/TCPServer.java index ac5c4ef..2a28ab0 100644 --- a/src/fr/pandacube/java/util/network/server/TCPServer.java +++ b/src/fr/pandacube/java/util/network/server/TCPServer.java @@ -24,34 +24,27 @@ import fr.pandacube.java.util.network.packet.PacketClient; import fr.pandacube.java.util.network.packet.PacketServer; import fr.pandacube.java.util.network.packet.bytebuffer.ByteBuffer; - /** - * + * * @author Marc Baloup * */ public class TCPServer extends Thread implements Closeable { private static AtomicInteger connectionCounterId = new AtomicInteger(0); - - + private ServerSocket socket; private TCPServerListener listener; private String socketName; - + private List clients = new ArrayList<>(); - + private AtomicBoolean isClosed = new AtomicBoolean(false); - - + public final BandwidthCalculation bandwidthCalculation = new BandwidthCalculation(); - - - - + public TCPServer(int port, String sckName, TCPServerListener l) throws IOException { - super("TCPSv "+sckName); - if (port <= 0 || port > 65535) - throw new IllegalArgumentException("le numéro de port est invalide"); + super("TCPSv " + sckName); + if (port <= 0 || port > 65535) throw new IllegalArgumentException("le numéro de port est invalide"); socket = new ServerSocket(); socket.setReceiveBufferSize(Pandacube.NETWORK_TCP_BUFFER_SIZE); socket.setPerformancePreferences(0, 2, 1); @@ -60,51 +53,40 @@ public class TCPServer extends Thread implements Closeable { listener.onSocketOpen(this); socketName = sckName; } - @Override public void run() { try { - while(true) { + while (true) { Socket socketClient = socket.accept(); socketClient.setSendBufferSize(Pandacube.NETWORK_TCP_BUFFER_SIZE); socketClient.setSoTimeout(Pandacube.NETWORK_TIMEOUT); - + try { - TCPServerClientConnection co = new TCPServerClientConnection(socketClient, connectionCounterId.getAndIncrement()); + TCPServerClientConnection co = new TCPServerClientConnection(socketClient, + connectionCounterId.getAndIncrement()); clients.add(co); listener.onClientConnect(this, co); co.start(); - } catch(IOException e) { - Log.getLogger().log(Level.SEVERE, "Connexion impossible avec "+socketClient.getInetAddress()); + } catch (IOException e) { + Log.getLogger().log(Level.SEVERE, "Connexion impossible avec " + socketClient.getInetAddress()); } } } catch (Exception e) { Log.getLogger().log(Level.WARNING, "Plus aucune connexion ne peux être acceptée", e); } } - - - - - - - - - - - + public class TCPServerClientConnection extends Thread { private Socket socket; private InputStream in; private OutputStream out; private SocketAddress address; private TCPServerConnectionOutputThread outThread; - - + public TCPServerClientConnection(Socket s, int coId) throws IOException { - super("TCPSv "+socketName+" Conn#"+coId+" In"); + super("TCPSv " + socketName + " Conn#" + coId + " In"); socket = s; in = socket.getInputStream(); out = socket.getOutputStream(); @@ -113,171 +95,148 @@ public class TCPServer extends Thread implements Closeable { outThread = new TCPServerConnectionOutputThread(coId); outThread.start(); } - + @Override public void run() { try { byte[] code = new byte[1]; - while(!socket.isClosed() && in.read(code) != -1) { + while (!socket.isClosed() && in.read(code) != -1) { byte[] sizeB = new byte[4]; - if (in.read(sizeB) != 4) - throw new IOException("Socket "+address+" fermé"); - + if (in.read(sizeB) != 4) throw new IOException("Socket " + address + " fermé"); + int size = new ByteBuffer(sizeB, Packet.CHARSET).getInt(); - + byte[] content = new byte[size]; - + forceReadBytes(content); - - byte[] packetData = new ByteBuffer(1+4+size, Packet.CHARSET).putBytes(code).putBytes(sizeB).putBytes(content).array(); - + + byte[] packetData = new ByteBuffer(1 + 4 + size, Packet.CHARSET).putBytes(code).putBytes(sizeB) + .putBytes(content).array(); + bandwidthCalculation.addPacket(this, true, packetData.length); - + try { interpreteReceivedMessage(this, packetData); } catch (InvalidClientMessage e) { Log.getLogger().log(Level.SEVERE, "Erreur protocole de : ", e); } catch (Exception e) { - Log.getLogger().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(); } } - - - - + } catch (Exception e) { - Log.getLogger().log(Level.SEVERE, "Fermeture de la connexion de "+address, e); + Log.getLogger().log(Level.SEVERE, "Fermeture de la connexion de " + address, e); } - - + close(); } - + public void send(PacketServer p) { outThread.addPacket(p); } - + private void forceReadBytes(byte[] buff) throws IOException { int pos = 0; do { - int nbR = in.read(buff, pos, buff.length-pos); - if (nbR == -1) - throw new IOException("Can't read required amount of byte"); + int nbR = in.read(buff, pos, buff.length - pos); + if (nbR == -1) throw new IOException("Can't read required amount of byte"); pos += nbR; } while (pos < buff.length); } - + public void close() { if (socket.isClosed()) return; - + listener.onClientDisconnect(TCPServer.this, this); clients.remove(this); - + try { socket.close(); - if (!Thread.currentThread().equals(outThread)) - send(new PacketServer((byte)0){ - @Override - public void serializeToByteBuffer( ByteBuffer buffer) {} - @Override - public void deserializeFromByteBuffer( ByteBuffer buffer) {} - }); - // provoque une exception dans le thread de sortie, et la termine + if (!Thread.currentThread().equals(outThread)) send(new PacketServer((byte) 0) { + @Override + public void serializeToByteBuffer(ByteBuffer buffer) {} + + @Override + public void deserializeFromByteBuffer(ByteBuffer buffer) {} + }); + // provoque une exception dans le thread de sortie, et la + // termine } catch (IOException e) { e.printStackTrace(); } } - - + private class TCPServerConnectionOutputThread extends Thread { private BlockingQueue packetQueue = new LinkedBlockingDeque(); - + public TCPServerConnectionOutputThread(int coId) { - super("TCPSv "+socketName+" Conn#"+coId+" Out"); + super("TCPSv " + socketName + " Conn#" + coId + " Out"); } - private void addPacket(PacketServer packet) { packetQueue.add(packet); } - - + @Override public void run() { try { while (!socket.isClosed()) { PacketServer packet = packetQueue.poll(1, TimeUnit.SECONDS); - byte[] data; + byte[] data; if (packet != null) { data = packet.getFullSerializedPacket(); bandwidthCalculation.addPacket(TCPServerClientConnection.this, false, data.length); out.write(data); out.flush(); } - - - + } - } catch (InterruptedException e) { - } catch (IOException e) { } - + } catch (InterruptedException e) {} catch (IOException e) {} + close(); } - - + } - - + } - - - - - + private void interpreteReceivedMessage(TCPServerClientConnection co, byte[] data) { - + Packet p = Packet.constructPacket(data); - - if (!(p instanceof PacketClient)) - throw new InvalidClientMessage("Le type de packet reçu n'est pas un packet attendu : "+p.getClass().getCanonicalName()); - + + if (!(p instanceof PacketClient)) throw new InvalidClientMessage( + "Le type de packet reçu n'est pas un packet attendu : " + p.getClass().getCanonicalName()); + PacketClient pc = (PacketClient) p; - + listener.onPacketReceive(this, co, pc); } - - - + @Override public void close() { try { if (isClosed.get()) return; - + clients.forEach(el -> el.close()); - + socket.close(); isClosed.set(true); listener.onSocketClose(this); - } catch (IOException e) { } + } catch (IOException e) {} } - + public boolean isClosed() { return isClosed.get() || socket.isClosed(); } - - - - - - - - + public static class InvalidClientMessage extends RuntimeException { private static final long serialVersionUID = 1L; + public InvalidClientMessage(String message) { super(message); } } - + } diff --git a/src/fr/pandacube/java/util/network/server/TCPServerListener.java b/src/fr/pandacube/java/util/network/server/TCPServerListener.java index 31e2221..bfe8352 100644 --- a/src/fr/pandacube/java/util/network/server/TCPServerListener.java +++ b/src/fr/pandacube/java/util/network/server/TCPServerListener.java @@ -4,15 +4,16 @@ import fr.pandacube.java.util.network.packet.PacketClient; import fr.pandacube.java.util.network.server.TCPServer.TCPServerClientConnection; public interface TCPServerListener { - + public void onSocketOpen(TCPServer svConnection); - + public void onClientConnect(TCPServer svConnection, TCPServerClientConnection clientConnection); - - public void onPacketReceive(TCPServer svConnection, TCPServerClientConnection clientConnection, PacketClient packet); - + + public void onPacketReceive(TCPServer svConnection, TCPServerClientConnection clientConnection, + PacketClient packet); + public void onClientDisconnect(TCPServer svConnection, TCPServerClientConnection clientConnection); - + public void onSocketClose(TCPServer svConnection); - + } diff --git a/src/fr/pandacube/java/util/network_api/client/AbstractRequest.java b/src/fr/pandacube/java/util/network_api/client/AbstractRequest.java index 43322c9..40cf448 100644 --- a/src/fr/pandacube/java/util/network_api/client/AbstractRequest.java +++ b/src/fr/pandacube/java/util/network_api/client/AbstractRequest.java @@ -3,29 +3,26 @@ package fr.pandacube.java.util.network_api.client; import java.io.PrintStream; public abstract class AbstractRequest { - + private final String pass; private String command; private String data; - - + protected AbstractRequest(String cmd, String p) { if (cmd == null || cmd.isEmpty()) throw new IllegalArgumentException("Un message doit-être défini"); command = cmd; pass = p; } - - + protected void setData(String d) { if (d == null) d = ""; data = d; } - - + public void sendPacket(PrintStream out) { - out.print(pass+"\n"); - out.print(command+"\n"); - out.print(data.getBytes().length+"\n"); + out.print(pass + "\n"); + out.print(command + "\n"); + out.print(data.getBytes().length + "\n"); out.print(data); out.flush(); } diff --git a/src/fr/pandacube/java/util/network_api/client/NetworkAPISender.java b/src/fr/pandacube/java/util/network_api/client/NetworkAPISender.java index 77b74e1..421b4b9 100644 --- a/src/fr/pandacube/java/util/network_api/client/NetworkAPISender.java +++ b/src/fr/pandacube/java/util/network_api/client/NetworkAPISender.java @@ -9,20 +9,17 @@ public class NetworkAPISender { public static ResponseAnalyser sendRequest(InetSocketAddress cible, AbstractRequest request) throws IOException { Socket s = new Socket(cible.getAddress(), cible.getPort()); - + PrintStream out = new PrintStream(s.getOutputStream()); - + request.sendPacket(out); s.shutdownOutput(); - + ResponseAnalyser response = new ResponseAnalyser(s); - + s.close(); - + return response; } - - + } - - diff --git a/src/fr/pandacube/java/util/network_api/client/ResponseAnalyser.java b/src/fr/pandacube/java/util/network_api/client/ResponseAnalyser.java index a8381bb..3dc6847 100644 --- a/src/fr/pandacube/java/util/network_api/client/ResponseAnalyser.java +++ b/src/fr/pandacube/java/util/network_api/client/ResponseAnalyser.java @@ -7,57 +7,47 @@ import java.net.Socket; public class ResponseAnalyser { /** - * Indique si la requête s'est bien exécutée (l'entête de la réponse est 'ok') + * Indique si la requête s'est bien exécutée (l'entête de la réponse est + * 'ok') */ public final boolean good; - - + public final String data; - - + public ResponseAnalyser(Socket socket) throws IOException { - if (socket == null || socket.isClosed() || socket.isInputShutdown()) throw new IllegalArgumentException("le socket doit être non null et doit être ouvert sur le flux d'entrée"); - + if (socket == null || socket.isClosed() || socket.isInputShutdown()) + throw new IllegalArgumentException("le socket doit être non null et doit être ouvert sur le flux d'entrée"); + // on lis la réponse BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); - + String line; - - + // lecture de la première ligne line = in.readLine(); good = line.equalsIgnoreCase("OK"); - - - - + // lecture de la deuxième ligne line = in.readLine(); - + int data_size = 0; try { data_size = Integer.parseInt(line); - } catch (NumberFormatException e) { throw new RuntimeException("Réponse mal formée : la deuxième ligne doit-être un nombre entier"); } - - - - - - + } catch (NumberFormatException e) { + throw new RuntimeException("Réponse mal formée : la deuxième ligne doit-être un nombre entier"); + } + // lecture du reste StringBuilder sB_data = new StringBuilder(); char[] c = new char[100]; int nbC = 0; - while((nbC = in.read(c)) != -1) + while ((nbC = in.read(c)) != -1) sB_data.append(c, 0, nbC); data = sB_data.toString(); - - if (data.getBytes().length != data_size) - throw new RuntimeException("Réponse mal formée : "+data_size+" caractères annoncée dans la requête, mais "+data.getBytes().length+" s'y trouvent."); - - + + if (data.getBytes().length != data_size) throw new RuntimeException("Réponse mal formée : " + data_size + + " caractères annoncée dans la requête, mais " + data.getBytes().length + " s'y trouvent."); + } - - - + } diff --git a/src/fr/pandacube/java/util/network_api/server/AbstractRequestExecutor.java b/src/fr/pandacube/java/util/network_api/server/AbstractRequestExecutor.java index 89b038d..4226d95 100644 --- a/src/fr/pandacube/java/util/network_api/server/AbstractRequestExecutor.java +++ b/src/fr/pandacube/java/util/network_api/server/AbstractRequestExecutor.java @@ -7,40 +7,35 @@ import java.net.Socket; public abstract class AbstractRequestExecutor { - - public final String command; - - + public AbstractRequestExecutor(String cmd, NetworkAPIListener napiListener) { command = cmd.toLowerCase(); napiListener.registerRequestExecutor(command, this); } - - - + public void execute(String data, Socket socket) throws IOException { - if (socket == null || socket.isClosed() || socket.isOutputShutdown()) throw new IllegalArgumentException("le socket doit être non null et doit être ouvert sur le flux d'entrée"); - + if (socket == null || socket.isClosed() || socket.isOutputShutdown()) + throw new IllegalArgumentException("le socket doit être non null et doit être ouvert sur le flux d'entrée"); + try { - + Response rep = run(socket.getInetAddress(), data); rep.sendPacket(new PrintStream(socket.getOutputStream())); - - } catch(Exception e) { + + } catch (Exception e) { new Response(false, e.toString()).sendPacket(new PrintStream(socket.getOutputStream())); e.printStackTrace(); } - + } - - + /** - * - * @param data La représentation sous forme de String des données envoyés dans la requête + * + * @param data La représentation sous forme de String des données envoyés + * dans la requête * @return La réponse à retourner au client */ protected abstract Response run(InetAddress source, String data); - - + } diff --git a/src/fr/pandacube/java/util/network_api/server/NAPIExecutionHandler.java b/src/fr/pandacube/java/util/network_api/server/NAPIExecutionHandler.java index 075357f..65c88bf 100644 --- a/src/fr/pandacube/java/util/network_api/server/NAPIExecutionHandler.java +++ b/src/fr/pandacube/java/util/network_api/server/NAPIExecutionHandler.java @@ -2,12 +2,13 @@ package fr.pandacube.java.util.network_api.server; /** * Interface permettant de gérer l'exécution asynchrone d'un PacketExecutor. + * * @author Marc Baloup * */ @FunctionalInterface public interface NAPIExecutionHandler { - + public void handleRun(Runnable executor); } diff --git a/src/fr/pandacube/java/util/network_api/server/NetworkAPIListener.java b/src/fr/pandacube/java/util/network_api/server/NetworkAPIListener.java index 08d312e..7f9cc7c 100644 --- a/src/fr/pandacube/java/util/network_api/server/NetworkAPIListener.java +++ b/src/fr/pandacube/java/util/network_api/server/NetworkAPIListener.java @@ -7,32 +7,22 @@ import java.util.Arrays; import java.util.HashMap; public class NetworkAPIListener implements Runnable { - - - - - - - - - - - - - + private int port = 0; String pass; private ServerSocket serverSocket; private HashMap requestExecutors = new HashMap(); private String name; private NAPIExecutionHandler nAPIExecutionHandler; - + /** * Instencie le côté serveur du NetworkAPI + * * @param n nom du networkAPI (permet l'identification dans les logs) * @param p le port d'écoute * @param pa le mot de passe réseau - * @param peh PacketExecutionHandler permettant de prendre en charge l'exécution asynchrone d'une requête reçu pas un client + * @param peh PacketExecutionHandler permettant de prendre en charge + * l'exécution asynchrone d'une requête reçu pas un client */ public NetworkAPIListener(String n, int p, String pa, NAPIExecutionHandler peh) { port = p; @@ -40,8 +30,7 @@ public class NetworkAPIListener implements Runnable { name = n; nAPIExecutionHandler = peh; } - - + @Override public void run() { synchronized (this) { @@ -52,74 +41,51 @@ public class NetworkAPIListener implements Runnable { return; } } - - - - System.out.println("NetworkAPI '"+name+"' à l'écoute sur le port "+port); - - + + System.out.println("NetworkAPI '" + name + "' à l'écoute sur le port " + port); + try { // réception des connexion client while (!serverSocket.isClosed()) { Socket socketClient = serverSocket.accept(); nAPIExecutionHandler.handleRun(new PacketExecutor(socketClient, this)); } - } catch(IOException e) { } - + } catch (IOException e) {} + synchronized (this) { try { - if (!serverSocket.isClosed()) - serverSocket.close(); - } catch (IOException e) { } + if (!serverSocket.isClosed()) serverSocket.close(); + } catch (IOException e) {} } - - System.out.println("NetworkAPI '"+name+"' ferme le port "+port); - - + + System.out.println("NetworkAPI '" + name + "' ferme le port " + port); + } - /** - * Ferme le ServerSocket. Ceci provoque l'arrêt du thread associé à l'instance de la classe + * Ferme le ServerSocket. Ceci provoque l'arrêt du thread associé à + * l'instance de la classe */ public synchronized void closeServerSocket() { - if (serverSocket != null) - { - try { - serverSocket.close(); - } catch (IOException e) { } - } + if (serverSocket != null) try { + serverSocket.close(); + } catch (IOException e) {} + } + + public int getPort() { + return port; } - - - - - public int getPort() { return port; } - - - - public void registerRequestExecutor(String command, AbstractRequestExecutor executor) { requestExecutors.put(command, executor); } - + public AbstractRequestExecutor getRequestExecutor(String command) { return requestExecutors.get(command); } - - + public String getCommandList() { return Arrays.toString(requestExecutors.keySet().toArray()); } - - + } - - - - - - - - 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 a1ba315..bff8ab0 100644 --- a/src/fr/pandacube/java/util/network_api/server/PacketExecutor.java +++ b/src/fr/pandacube/java/util/network_api/server/PacketExecutor.java @@ -6,51 +6,50 @@ import java.net.Socket; import fr.pandacube.java.util.Log; - /** - * Prends en charge un socket client et le transmet au gestionnaire de paquet correspondant.
- * La connexion est fermée après chaque requête du client (règle pouvant évoluer) + * Prends en charge un socket client et le transmet au gestionnaire de paquet + * correspondant.
+ * La connexion est fermée après chaque requête du client (règle pouvant + * évoluer) + * * @author Marc Baloup * */ public class PacketExecutor implements Runnable { private Socket socket; private NetworkAPIListener networkAPIListener; - + public PacketExecutor(Socket s, NetworkAPIListener napiListener) { socket = s; networkAPIListener = napiListener; } - + @Override public void run() { try { - + // analyse de la requête RequestAnalyser analyse = new RequestAnalyser(socket, networkAPIListener); - - + AbstractRequestExecutor executor = networkAPIListener.getRequestExecutor(analyse.command); - + executor.execute(analyse.data, socket); - - - - } catch(Throwable e) { + + } catch (Throwable e) { Response rep = new Response(); rep.good = false; rep.data = e.toString(); try { rep.sendPacket(new PrintStream(socket.getOutputStream())); - } catch (IOException e1) { } - if (e instanceof IOException) - Log.getLogger().warning("Impossible de lire le packet reçu sur le socket "+socket+" : "+e.toString()); + } catch (IOException e1) {} + if (e instanceof IOException) Log.getLogger() + .warning("Impossible de lire le packet reçu sur le socket " + socket + " : " + e.toString()); else e.printStackTrace(); } - + try { socket.close(); - } catch (Exception e) { } + } catch (Exception e) {} } } diff --git a/src/fr/pandacube/java/util/network_api/server/RequestAnalyser.java b/src/fr/pandacube/java/util/network_api/server/RequestAnalyser.java index 2fdcf6e..609eb09 100644 --- a/src/fr/pandacube/java/util/network_api/server/RequestAnalyser.java +++ b/src/fr/pandacube/java/util/network_api/server/RequestAnalyser.java @@ -10,75 +10,61 @@ public class RequestAnalyser { private NetworkAPIListener networkAPIListener; public final String command; public final String data; - + public RequestAnalyser(Socket socket, NetworkAPIListener napiListener) throws IOException, BadRequestException { - if (socket == null || socket.isClosed() || socket.isInputShutdown() || napiListener == null) throw new IllegalArgumentException("le socket doit être non null et doit être ouvert sur le flux d'entrée et napiListener ne doit pas être null"); - + if (socket == null || socket.isClosed() || socket.isInputShutdown() || napiListener == null) + throw new IllegalArgumentException( + "le socket doit être non null et doit être ouvert sur le flux d'entrée et napiListener ne doit pas être null"); + networkAPIListener = napiListener; - + // on lis la réponse BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); - + String line; - - - + // lecture de la première ligne line = in.readLine(); - if (line == null || !line.equals(networkAPIListener.pass)) - throw new BadRequestException("wrong_password"); - - - + if (line == null || !line.equals(networkAPIListener.pass)) throw new BadRequestException("wrong_password"); - // lecture de la deuxième ligne line = in.readLine(); if (line == null || networkAPIListener.getRequestExecutor(line) == null) throw new BadRequestException("command_not_exists"); command = line; - - - + // lecture de la troisième ligne line = in.readLine(); - + int data_size = 0; try { data_size = Integer.parseInt(line); - } catch (NumberFormatException e) { throw new BadRequestException("wrong_data_size_format"); } - - + } catch (NumberFormatException e) { + throw new BadRequestException("wrong_data_size_format"); + } + // lecture du reste StringBuilder sB_data = new StringBuilder(); char[] c = new char[100]; int nbC = 0; - while((nbC = in.read(c)) != -1) + while ((nbC = in.read(c)) != -1) sB_data.append(c, 0, nbC); - + data = sB_data.toString(); - - if (data.getBytes().length != data_size) - throw new BadRequestException("wrong_data_size"); - - + + if (data.getBytes().length != data_size) throw new BadRequestException("wrong_data_size"); + socket.shutdownInput(); } - - - - - - + public class BadRequestException extends Exception { private static final long serialVersionUID = 1L; - + public BadRequestException(String message) { super(message); } - + } - - + } diff --git a/src/fr/pandacube/java/util/network_api/server/Response.java b/src/fr/pandacube/java/util/network_api/server/Response.java index 5235ef4..242ae2d 100644 --- a/src/fr/pandacube/java/util/network_api/server/Response.java +++ b/src/fr/pandacube/java/util/network_api/server/Response.java @@ -5,27 +5,24 @@ import java.io.PrintStream; public class Response { public boolean good = true; public String data = ""; - - + public Response(boolean good, String data) { this.good = good; this.data = data; } - + /** * Construit une réponse positive avec aucune donnée. Équivaut à * new Response(true, "") */ - public Response() { - } - - + public Response() {} + public void sendPacket(PrintStream out) { - + if (data == null) data = ""; - - out.print((good?"OK":"ERROR")+"\n"); - out.print(data.getBytes().length+"\n"); + + out.print((good ? "OK" : "ERROR") + "\n"); + out.print(data.getBytes().length + "\n"); out.print(data); out.flush(); } diff --git a/src/net/md_5/bungee/api/ChatColor.java b/src/net/md_5/bungee/api/ChatColor.java index 2e83fb8..b800067 100644 --- a/src/net/md_5/bungee/api/ChatColor.java +++ b/src/net/md_5/bungee/api/ChatColor.java @@ -8,78 +8,75 @@ import java.util.Map; import java.util.regex.Pattern; public enum ChatColor { - BLACK('0', "black"), - DARK_BLUE('1', "dark_blue"), - DARK_GREEN('2', "dark_green"), - DARK_AQUA('3', "dark_aqua"), - DARK_RED('4', "dark_red"), - DARK_PURPLE('5', "dark_purple"), - GOLD('6', "gold"), - GRAY('7', "gray"), - DARK_GRAY('8', "dark_gray"), - BLUE('9', "blue"), - GREEN('a', "green"), - AQUA('b', "aqua"), - RED('c', "red"), - LIGHT_PURPLE('d', "light_purple"), - YELLOW('e', "yellow"), - WHITE('f', "white"), - MAGIC('k', "obfuscated"), - BOLD('l', "bold"), - STRIKETHROUGH('m', "strikethrough"), - UNDERLINE('n', "underline"), - ITALIC('o', "italic"), - RESET('r', "reset"); - - public static final char COLOR_CHAR = '\u00a7'; - public static final String ALL_CODES = "0123456789AaBbCcDdEeFfKkLlMmNnOoRr"; - public static final Pattern STRIP_COLOR_PATTERN; - private static final Map BY_CHAR; - private final char code; - private final String toString; - private final String name; + BLACK('0', "black"), + DARK_BLUE('1', "dark_blue"), + DARK_GREEN('2', "dark_green"), + DARK_AQUA('3', "dark_aqua"), + DARK_RED('4', "dark_red"), + DARK_PURPLE('5', "dark_purple"), + GOLD('6', "gold"), + GRAY('7', "gray"), + DARK_GRAY('8', "dark_gray"), + BLUE('9', "blue"), + GREEN('a', "green"), + AQUA('b', "aqua"), + RED('c', "red"), + LIGHT_PURPLE('d', "light_purple"), + YELLOW('e', "yellow"), + WHITE('f', "white"), + MAGIC('k', "obfuscated"), + BOLD('l', "bold"), + STRIKETHROUGH('m', "strikethrough"), + UNDERLINE('n', "underline"), + ITALIC('o', "italic"), + RESET('r', "reset"); - private ChatColor(char code, String name) { - this.code = code; - this.name = name; - this.toString = new String(new char[]{'\u00a7', code}); - } + public static final char COLOR_CHAR = '\u00a7'; + public static final String ALL_CODES = "0123456789AaBbCcDdEeFfKkLlMmNnOoRr"; + public static final Pattern STRIP_COLOR_PATTERN; + private static final Map BY_CHAR; + private final char code; + private final String toString; + private final String name; - public String toString() { - return this.toString; - } + private ChatColor(char code, String name) { + this.code = code; + this.name = name; + toString = new String(new char[] { '\u00a7', code }); + } - public static String stripColor(String input) { - if (input == null) { - return null; - } - return STRIP_COLOR_PATTERN.matcher(input).replaceAll(""); - } + @Override + public String toString() { + return toString; + } - public static String translateAlternateColorCodes(char altColorChar, String textToTranslate) { - char[] b2 = textToTranslate.toCharArray(); - for (int i = 0; i < b2.length - 1; ++i) { - if (b2[i] != altColorChar || "0123456789AaBbCcDdEeFfKkLlMmNnOoRr".indexOf(b2[i + 1]) <= -1) continue; - b2[i] = 167; - b2[i + 1] = Character.toLowerCase(b2[i + 1]); - } - return new String(b2); - } + public static String stripColor(String input) { + if (input == null) return null; + return STRIP_COLOR_PATTERN.matcher(input).replaceAll(""); + } - public static ChatColor getByChar(char code) { - return BY_CHAR.get(Character.valueOf(code)); - } + public static String translateAlternateColorCodes(char altColorChar, String textToTranslate) { + char[] b2 = textToTranslate.toCharArray(); + for (int i = 0; i < b2.length - 1; ++i) { + if (b2[i] != altColorChar || "0123456789AaBbCcDdEeFfKkLlMmNnOoRr".indexOf(b2[i + 1]) <= -1) continue; + b2[i] = 167; + b2[i + 1] = Character.toLowerCase(b2[i + 1]); + } + return new String(b2); + } - public String getName() { - return this.name; - } + public static ChatColor getByChar(char code) { + return BY_CHAR.get(Character.valueOf(code)); + } - static { - STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + String.valueOf('\u00a7') + "[0-9A-FK-OR]"); - BY_CHAR = new HashMap(); - for (ChatColor colour : ChatColor.values()) { - BY_CHAR.put(Character.valueOf(colour.code), colour); - } - } + public String getName() { + return name; + } + + static { + STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + String.valueOf('\u00a7') + "[0-9A-FK-OR]"); + BY_CHAR = new HashMap(); + for (ChatColor colour : ChatColor.values()) + BY_CHAR.put(Character.valueOf(colour.code), colour); + } } - diff --git a/src/net/md_5/bungee/api/ChatMessageType.java b/src/net/md_5/bungee/api/ChatMessageType.java index 2c2d8bc..88e2899 100644 --- a/src/net/md_5/bungee/api/ChatMessageType.java +++ b/src/net/md_5/bungee/api/ChatMessageType.java @@ -4,12 +4,7 @@ package net.md_5.bungee.api; public enum ChatMessageType { - CHAT, - SYSTEM, - ACTION_BAR; - + CHAT, SYSTEM, ACTION_BAR; - private ChatMessageType() { - } + private ChatMessageType() {} } - diff --git a/src/net/md_5/bungee/api/chat/BaseComponent.java b/src/net/md_5/bungee/api/chat/BaseComponent.java index 51a95d6..92027f9 100644 --- a/src/net/md_5/bungee/api/chat/BaseComponent.java +++ b/src/net/md_5/bungee/api/chat/BaseComponent.java @@ -5,236 +5,211 @@ package net.md_5.bungee.api.chat; import java.util.ArrayList; import java.util.List; + import net.md_5.bungee.api.ChatColor; -import net.md_5.bungee.api.chat.ClickEvent; -import net.md_5.bungee.api.chat.HoverEvent; -import net.md_5.bungee.api.chat.TextComponent; public abstract class BaseComponent { - BaseComponent parent; - private ChatColor color; - private Boolean bold; - private Boolean italic; - private Boolean underlined; - private Boolean strikethrough; - private Boolean obfuscated; - private String insertion; - private List extra; - private ClickEvent clickEvent; - private HoverEvent hoverEvent; + BaseComponent parent; + private ChatColor color; + private Boolean bold; + private Boolean italic; + private Boolean underlined; + private Boolean strikethrough; + private Boolean obfuscated; + private String insertion; + private List extra; + private ClickEvent clickEvent; + private HoverEvent hoverEvent; - BaseComponent(BaseComponent old) { - this.setColor(old.getColorRaw()); - this.setBold(old.isBoldRaw()); - this.setItalic(old.isItalicRaw()); - this.setUnderlined(old.isUnderlinedRaw()); - this.setStrikethrough(old.isStrikethroughRaw()); - this.setObfuscated(old.isObfuscatedRaw()); - this.setInsertion(old.getInsertion()); - this.setClickEvent(old.getClickEvent()); - this.setHoverEvent(old.getHoverEvent()); - if (old.getExtra() != null) { - for (BaseComponent component : old.getExtra()) { - this.addExtra(component.duplicate()); - } - } - } + BaseComponent(BaseComponent old) { + setColor(old.getColorRaw()); + setBold(old.isBoldRaw()); + setItalic(old.isItalicRaw()); + setUnderlined(old.isUnderlinedRaw()); + setStrikethrough(old.isStrikethroughRaw()); + setObfuscated(old.isObfuscatedRaw()); + setInsertion(old.getInsertion()); + setClickEvent(old.getClickEvent()); + setHoverEvent(old.getHoverEvent()); + if (old.getExtra() != null) for (BaseComponent component : old.getExtra()) + this.addExtra(component.duplicate()); + } - public abstract BaseComponent duplicate(); + public abstract BaseComponent duplicate(); - public static /* varargs */ String toLegacyText(BaseComponent ... components) { - StringBuilder builder = new StringBuilder(); - for (BaseComponent msg : components) { - builder.append(msg.toLegacyText()); - } - return builder.toString(); - } + public static /* varargs */ String toLegacyText(BaseComponent... components) { + StringBuilder builder = new StringBuilder(); + for (BaseComponent msg : components) + builder.append(msg.toLegacyText()); + return builder.toString(); + } - public static /* varargs */ String toPlainText(BaseComponent ... components) { - StringBuilder builder = new StringBuilder(); - for (BaseComponent msg : components) { - builder.append(msg.toPlainText()); - } - return builder.toString(); - } + public static /* varargs */ String toPlainText(BaseComponent... components) { + StringBuilder builder = new StringBuilder(); + for (BaseComponent msg : components) + builder.append(msg.toPlainText()); + return builder.toString(); + } - public ChatColor getColor() { - if (this.color == null) { - if (this.parent == null) { - return ChatColor.WHITE; - } - return this.parent.getColor(); - } - return this.color; - } + public ChatColor getColor() { + if (color == null) { + if (parent == null) return ChatColor.WHITE; + return parent.getColor(); + } + return color; + } - public ChatColor getColorRaw() { - return this.color; - } + public ChatColor getColorRaw() { + return color; + } - public boolean isBold() { - if (this.bold == null) { - return this.parent != null && this.parent.isBold(); - } - return this.bold; - } + public boolean isBold() { + if (bold == null) return parent != null && parent.isBold(); + return bold; + } - public Boolean isBoldRaw() { - return this.bold; - } + public Boolean isBoldRaw() { + return bold; + } - public boolean isItalic() { - if (this.italic == null) { - return this.parent != null && this.parent.isItalic(); - } - return this.italic; - } + public boolean isItalic() { + if (italic == null) return parent != null && parent.isItalic(); + return italic; + } - public Boolean isItalicRaw() { - return this.italic; - } + public Boolean isItalicRaw() { + return italic; + } - public boolean isUnderlined() { - if (this.underlined == null) { - return this.parent != null && this.parent.isUnderlined(); - } - return this.underlined; - } + public boolean isUnderlined() { + if (underlined == null) return parent != null && parent.isUnderlined(); + return underlined; + } - public Boolean isUnderlinedRaw() { - return this.underlined; - } + public Boolean isUnderlinedRaw() { + return underlined; + } - public boolean isStrikethrough() { - if (this.strikethrough == null) { - return this.parent != null && this.parent.isStrikethrough(); - } - return this.strikethrough; - } + public boolean isStrikethrough() { + if (strikethrough == null) return parent != null && parent.isStrikethrough(); + return strikethrough; + } - public Boolean isStrikethroughRaw() { - return this.strikethrough; - } + public Boolean isStrikethroughRaw() { + return strikethrough; + } - public boolean isObfuscated() { - if (this.obfuscated == null) { - return this.parent != null && this.parent.isObfuscated(); - } - return this.obfuscated; - } + public boolean isObfuscated() { + if (obfuscated == null) return parent != null && parent.isObfuscated(); + return obfuscated; + } - public Boolean isObfuscatedRaw() { - return this.obfuscated; - } + public Boolean isObfuscatedRaw() { + return obfuscated; + } - public void setExtra(List components) { - for (BaseComponent component : components) { - component.parent = this; - } - this.extra = components; - } + public void setExtra(List components) { + for (BaseComponent component : components) + component.parent = this; + extra = components; + } - public void addExtra(String text) { - this.addExtra(new TextComponent(text)); - } + public void addExtra(String text) { + this.addExtra(new TextComponent(text)); + } - public void addExtra(BaseComponent component) { - if (this.extra == null) { - this.extra = new ArrayList(); - } - component.parent = this; - this.extra.add(component); - } + public void addExtra(BaseComponent component) { + if (extra == null) extra = new ArrayList(); + component.parent = this; + extra.add(component); + } - public boolean hasFormatting() { - return this.color != null || this.bold != null || this.italic != null || this.underlined != null || this.strikethrough != null || this.obfuscated != null || this.hoverEvent != null || this.clickEvent != null; - } + public boolean hasFormatting() { + return color != null || bold != null || italic != null || underlined != null || strikethrough != null + || obfuscated != null || hoverEvent != null || clickEvent != null; + } - public String toPlainText() { - StringBuilder builder = new StringBuilder(); - this.toPlainText(builder); - return builder.toString(); - } + public String toPlainText() { + StringBuilder builder = new StringBuilder(); + this.toPlainText(builder); + return builder.toString(); + } - void toPlainText(StringBuilder builder) { - if (this.extra != null) { - for (BaseComponent e2 : this.extra) { - e2.toPlainText(builder); - } - } - } + void toPlainText(StringBuilder builder) { + if (extra != null) for (BaseComponent e2 : extra) + e2.toPlainText(builder); + } - public String toLegacyText() { - StringBuilder builder = new StringBuilder(); - this.toLegacyText(builder); - return builder.toString(); - } + public String toLegacyText() { + StringBuilder builder = new StringBuilder(); + this.toLegacyText(builder); + return builder.toString(); + } - void toLegacyText(StringBuilder builder) { - if (this.extra != null) { - for (BaseComponent e2 : this.extra) { - e2.toLegacyText(builder); - } - } - } + void toLegacyText(StringBuilder builder) { + if (extra != null) for (BaseComponent e2 : extra) + e2.toLegacyText(builder); + } - public void setColor(ChatColor color) { - this.color = color; - } + public void setColor(ChatColor color) { + this.color = color; + } - public void setBold(Boolean bold) { - this.bold = bold; - } + public void setBold(Boolean bold) { + this.bold = bold; + } - public void setItalic(Boolean italic) { - this.italic = italic; - } + public void setItalic(Boolean italic) { + this.italic = italic; + } - public void setUnderlined(Boolean underlined) { - this.underlined = underlined; - } + public void setUnderlined(Boolean underlined) { + this.underlined = underlined; + } - public void setStrikethrough(Boolean strikethrough) { - this.strikethrough = strikethrough; - } + public void setStrikethrough(Boolean strikethrough) { + this.strikethrough = strikethrough; + } - public void setObfuscated(Boolean obfuscated) { - this.obfuscated = obfuscated; - } + public void setObfuscated(Boolean obfuscated) { + this.obfuscated = obfuscated; + } - public void setInsertion(String insertion) { - this.insertion = insertion; - } + public void setInsertion(String insertion) { + this.insertion = insertion; + } - public void setClickEvent(ClickEvent clickEvent) { - this.clickEvent = clickEvent; - } + public void setClickEvent(ClickEvent clickEvent) { + this.clickEvent = clickEvent; + } - public void setHoverEvent(HoverEvent hoverEvent) { - this.hoverEvent = hoverEvent; - } + public void setHoverEvent(HoverEvent hoverEvent) { + this.hoverEvent = hoverEvent; + } - public String toString() { - return "BaseComponent(color=" + (Object)((Object)this.getColor()) + ", bold=" + this.bold + ", italic=" + this.italic + ", underlined=" + this.underlined + ", strikethrough=" + this.strikethrough + ", obfuscated=" + this.obfuscated + ", insertion=" + this.getInsertion() + ", extra=" + this.getExtra() + ", clickEvent=" + this.getClickEvent() + ", hoverEvent=" + this.getHoverEvent() + ")"; - } + @Override + public String toString() { + return "BaseComponent(color=" + (getColor()) + ", bold=" + bold + ", italic=" + italic + ", underlined=" + + underlined + ", strikethrough=" + strikethrough + ", obfuscated=" + obfuscated + ", insertion=" + + getInsertion() + ", extra=" + getExtra() + ", clickEvent=" + getClickEvent() + ", hoverEvent=" + + getHoverEvent() + ")"; + } - public BaseComponent() { - } + public BaseComponent() {} - public String getInsertion() { - return this.insertion; - } + public String getInsertion() { + return insertion; + } - public List getExtra() { - return this.extra; - } + public List getExtra() { + return extra; + } - public ClickEvent getClickEvent() { - return this.clickEvent; - } + public ClickEvent getClickEvent() { + return clickEvent; + } - public HoverEvent getHoverEvent() { - return this.hoverEvent; - } + public HoverEvent getHoverEvent() { + return hoverEvent; + } } - diff --git a/src/net/md_5/bungee/api/chat/ClickEvent.java b/src/net/md_5/bungee/api/chat/ClickEvent.java index cc8436c..4c473cf 100644 --- a/src/net/md_5/bungee/api/chat/ClickEvent.java +++ b/src/net/md_5/bungee/api/chat/ClickEvent.java @@ -6,38 +6,32 @@ package net.md_5.bungee.api.chat; import java.beans.ConstructorProperties; public final class ClickEvent { - private final Action action; - private final String value; + private final Action action; + private final String value; - public Action getAction() { - return this.action; - } + public Action getAction() { + return action; + } - public String getValue() { - return this.value; - } + public String getValue() { + return value; + } - public String toString() { - return "ClickEvent(action=" + (Object)((Object)this.getAction()) + ", value=" + this.getValue() + ")"; - } + @Override + public String toString() { + return "ClickEvent(action=" + (getAction()) + ", value=" + getValue() + ")"; + } - @ConstructorProperties(value={"action", "value"}) - public ClickEvent(Action action, String value) { - this.action = action; - this.value = value; - } + @ConstructorProperties(value = { "action", "value" }) + public ClickEvent(Action action, String value) { + this.action = action; + this.value = value; + } - public static enum Action { - OPEN_URL, - OPEN_FILE, - RUN_COMMAND, - SUGGEST_COMMAND, - CHANGE_PAGE; - + public static enum Action { + OPEN_URL, OPEN_FILE, RUN_COMMAND, SUGGEST_COMMAND, CHANGE_PAGE; - private Action() { - } - } + private Action() {} + } } - diff --git a/src/net/md_5/bungee/api/chat/ComponentBuilder.java b/src/net/md_5/bungee/api/chat/ComponentBuilder.java index 20586f4..3ca8835 100644 --- a/src/net/md_5/bungee/api/chat/ComponentBuilder.java +++ b/src/net/md_5/bungee/api/chat/ComponentBuilder.java @@ -5,128 +5,118 @@ package net.md_5.bungee.api.chat; import java.util.ArrayList; import java.util.List; + import net.md_5.bungee.api.ChatColor; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.ClickEvent; -import net.md_5.bungee.api.chat.HoverEvent; -import net.md_5.bungee.api.chat.TextComponent; public class ComponentBuilder { - private TextComponent current; - private final List parts = new ArrayList(); + private TextComponent current; + private final List parts = new ArrayList(); - public ComponentBuilder(ComponentBuilder original) { - this.current = new TextComponent(original.current); - for (BaseComponent baseComponent : original.parts) { - this.parts.add(baseComponent.duplicate()); - } - } + public ComponentBuilder(ComponentBuilder original) { + current = new TextComponent(original.current); + for (BaseComponent baseComponent : original.parts) + parts.add(baseComponent.duplicate()); + } - public ComponentBuilder(String text) { - this.current = new TextComponent(text); - } + public ComponentBuilder(String text) { + current = new TextComponent(text); + } - public ComponentBuilder append(String text) { - return this.append(text, FormatRetention.ALL); - } + public ComponentBuilder append(String text) { + return this.append(text, FormatRetention.ALL); + } - public ComponentBuilder append(String text, FormatRetention retention) { - this.parts.add(this.current); - this.current = new TextComponent(this.current); - this.current.setText(text); - this.retain(retention); - return this; - } + public ComponentBuilder append(String text, FormatRetention retention) { + parts.add(current); + current = new TextComponent(current); + current.setText(text); + retain(retention); + return this; + } - public ComponentBuilder color(ChatColor color) { - this.current.setColor(color); - return this; - } + public ComponentBuilder color(ChatColor color) { + current.setColor(color); + return this; + } - public ComponentBuilder bold(boolean bold) { - this.current.setBold(bold); - return this; - } + public ComponentBuilder bold(boolean bold) { + current.setBold(bold); + return this; + } - public ComponentBuilder italic(boolean italic) { - this.current.setItalic(italic); - return this; - } + public ComponentBuilder italic(boolean italic) { + current.setItalic(italic); + return this; + } - public ComponentBuilder underlined(boolean underlined) { - this.current.setUnderlined(underlined); - return this; - } + public ComponentBuilder underlined(boolean underlined) { + current.setUnderlined(underlined); + return this; + } - public ComponentBuilder strikethrough(boolean strikethrough) { - this.current.setStrikethrough(strikethrough); - return this; - } + public ComponentBuilder strikethrough(boolean strikethrough) { + current.setStrikethrough(strikethrough); + return this; + } - public ComponentBuilder obfuscated(boolean obfuscated) { - this.current.setObfuscated(obfuscated); - return this; - } + public ComponentBuilder obfuscated(boolean obfuscated) { + current.setObfuscated(obfuscated); + return this; + } - public ComponentBuilder insertion(String insertion) { - this.current.setInsertion(insertion); - return this; - } + public ComponentBuilder insertion(String insertion) { + current.setInsertion(insertion); + return this; + } - public ComponentBuilder event(ClickEvent clickEvent) { - this.current.setClickEvent(clickEvent); - return this; - } + public ComponentBuilder event(ClickEvent clickEvent) { + current.setClickEvent(clickEvent); + return this; + } - public ComponentBuilder event(HoverEvent hoverEvent) { - this.current.setHoverEvent(hoverEvent); - return this; - } + public ComponentBuilder event(HoverEvent hoverEvent) { + current.setHoverEvent(hoverEvent); + return this; + } - public ComponentBuilder reset() { - return this.retain(FormatRetention.NONE); - } + public ComponentBuilder reset() { + return retain(FormatRetention.NONE); + } - public ComponentBuilder retain(FormatRetention retention) { - TextComponent previous = this.current; - switch (retention) { - case NONE: { - this.current = new TextComponent(this.current.getText()); - break; - } - case ALL: { - break; - } - case EVENTS: { - this.current = new TextComponent(this.current.getText()); - this.current.setInsertion(previous.getInsertion()); - this.current.setClickEvent(previous.getClickEvent()); - this.current.setHoverEvent(previous.getHoverEvent()); - break; - } - case FORMATTING: { - this.current.setClickEvent(null); - this.current.setHoverEvent(null); - } - } - return this; - } + public ComponentBuilder retain(FormatRetention retention) { + TextComponent previous = current; + switch (retention) { + case NONE: { + current = new TextComponent(current.getText()); + break; + } + case ALL: { + break; + } + case EVENTS: { + current = new TextComponent(current.getText()); + current.setInsertion(previous.getInsertion()); + current.setClickEvent(previous.getClickEvent()); + current.setHoverEvent(previous.getHoverEvent()); + break; + } + case FORMATTING: { + current.setClickEvent(null); + current.setHoverEvent(null); + } + } + return this; + } - public BaseComponent[] create() { - this.parts.add(this.current); - return this.parts.toArray(new BaseComponent[this.parts.size()]); - } + public BaseComponent[] create() { + parts.add(current); + return parts.toArray(new BaseComponent[parts.size()]); + } - public static enum FormatRetention { - NONE, - FORMATTING, - EVENTS, - ALL; - + public static enum FormatRetention { + NONE, FORMATTING, EVENTS, ALL; - private FormatRetention() { - } - } + private FormatRetention() {} + } } - diff --git a/src/net/md_5/bungee/api/chat/HoverEvent.java b/src/net/md_5/bungee/api/chat/HoverEvent.java index 5ff3b46..7bba5e9 100644 --- a/src/net/md_5/bungee/api/chat/HoverEvent.java +++ b/src/net/md_5/bungee/api/chat/HoverEvent.java @@ -5,40 +5,34 @@ package net.md_5.bungee.api.chat; import java.beans.ConstructorProperties; import java.util.Arrays; -import net.md_5.bungee.api.chat.BaseComponent; public final class HoverEvent { - private final Action action; - private final BaseComponent[] value; + private final Action action; + private final BaseComponent[] value; - public Action getAction() { - return this.action; - } + public Action getAction() { + return action; + } - public BaseComponent[] getValue() { - return this.value; - } + public BaseComponent[] getValue() { + return value; + } - public String toString() { - return "HoverEvent(action=" + (Object)((Object)this.getAction()) + ", value=" + Arrays.deepToString(this.getValue()) + ")"; - } + @Override + public String toString() { + return "HoverEvent(action=" + (getAction()) + ", value=" + Arrays.deepToString(getValue()) + ")"; + } - @ConstructorProperties(value={"action", "value"}) - public HoverEvent(Action action, BaseComponent[] value) { - this.action = action; - this.value = value; - } + @ConstructorProperties(value = { "action", "value" }) + public HoverEvent(Action action, BaseComponent[] value) { + this.action = action; + this.value = value; + } - public static enum Action { - SHOW_TEXT, - SHOW_ACHIEVEMENT, - SHOW_ITEM, - SHOW_ENTITY; - + public static enum Action { + SHOW_TEXT, SHOW_ACHIEVEMENT, SHOW_ITEM, SHOW_ENTITY; - private Action() { - } - } + private Action() {} + } } - diff --git a/src/net/md_5/bungee/api/chat/TextComponent.java b/src/net/md_5/bungee/api/chat/TextComponent.java index 67f4bdd..62086e0 100644 --- a/src/net/md_5/bungee/api/chat/TextComponent.java +++ b/src/net/md_5/bungee/api/chat/TextComponent.java @@ -8,163 +8,145 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; + import net.md_5.bungee.api.ChatColor; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.ClickEvent; -public class TextComponent -extends BaseComponent { - private static final Pattern url = Pattern.compile("^(?:(https?)://)?([-\\w_\\.]{2,}\\.[a-z]{2,4})(/\\S*)?$"); - private String text; +public class TextComponent extends BaseComponent { + private static final Pattern url = Pattern.compile("^(?:(https?)://)?([-\\w_\\.]{2,}\\.[a-z]{2,4})(/\\S*)?$"); + private String text; - public static BaseComponent[] fromLegacyText(String message) { - ArrayList components = new ArrayList(); - StringBuilder builder = new StringBuilder(); - TextComponent component = new TextComponent(); - Matcher matcher = url.matcher(message); - block8 : for (int i = 0; i < message.length(); ++i) { - TextComponent old; - char c2 = message.charAt(i); - if (c2 == '\u00a7') { - ChatColor format; - if ((c2 = message.charAt(++i)) >= 'A' && c2 <= 'Z') { - c2 = (char)(c2 + 32); - } - if ((format = ChatColor.getByChar(c2)) == null) continue; - if (builder.length() > 0) { - old = component; - component = new TextComponent(old); - old.setText(builder.toString()); - builder = new StringBuilder(); - components.add(old); - } - switch (format) { - case BOLD: { - component.setBold(true); - continue block8; - } - case ITALIC: { - component.setItalic(true); - continue block8; - } - case UNDERLINE: { - component.setUnderlined(true); - continue block8; - } - case STRIKETHROUGH: { - component.setStrikethrough(true); - continue block8; - } - case MAGIC: { - component.setObfuscated(true); - continue block8; - } - case RESET: { - format = ChatColor.WHITE; - } - default: - } - component = new TextComponent(); - component.setColor(format); - continue; - } - int pos = message.indexOf(32, i); - if (pos == -1) { - pos = message.length(); - } - if (matcher.region(i, pos).find()) { - if (builder.length() > 0) { - old = component; - component = new TextComponent(old); - old.setText(builder.toString()); - builder = new StringBuilder(); - components.add(old); - } - old = component; - component = new TextComponent(old); - String urlString = message.substring(i, pos); - component.setText(urlString); - component.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, urlString.startsWith("http") ? urlString : "http://" + urlString)); - components.add(component); - i += pos - i - 1; - component = old; - continue; - } - builder.append(c2); - } - if (builder.length() > 0) { - component.setText(builder.toString()); - components.add(component); - } - if (components.isEmpty()) { - components.add(new TextComponent("")); - } - return components.toArray(new BaseComponent[components.size()]); - } + public static BaseComponent[] fromLegacyText(String message) { + ArrayList components = new ArrayList(); + StringBuilder builder = new StringBuilder(); + TextComponent component = new TextComponent(); + Matcher matcher = url.matcher(message); + block8: + for (int i = 0; i < message.length(); ++i) { + TextComponent old; + char c2 = message.charAt(i); + if (c2 == '\u00a7') { + ChatColor format; + if ((c2 = message.charAt(++i)) >= 'A' && c2 <= 'Z') c2 = (char) (c2 + 32); + if ((format = ChatColor.getByChar(c2)) == null) continue; + if (builder.length() > 0) { + old = component; + component = new TextComponent(old); + old.setText(builder.toString()); + builder = new StringBuilder(); + components.add(old); + } + switch (format) { + case BOLD: { + component.setBold(true); + continue block8; + } + case ITALIC: { + component.setItalic(true); + continue block8; + } + case UNDERLINE: { + component.setUnderlined(true); + continue block8; + } + case STRIKETHROUGH: { + component.setStrikethrough(true); + continue block8; + } + case MAGIC: { + component.setObfuscated(true); + continue block8; + } + case RESET: { + format = ChatColor.WHITE; + } + default: + } + component = new TextComponent(); + component.setColor(format); + continue; + } + int pos = message.indexOf(32, i); + if (pos == -1) pos = message.length(); + if (matcher.region(i, pos).find()) { + if (builder.length() > 0) { + old = component; + component = new TextComponent(old); + old.setText(builder.toString()); + builder = new StringBuilder(); + components.add(old); + } + old = component; + component = new TextComponent(old); + String urlString = message.substring(i, pos); + component.setText(urlString); + component.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, + urlString.startsWith("http") ? urlString : "http://" + urlString)); + components.add(component); + i += pos - i - 1; + component = old; + continue; + } + builder.append(c2); + } + if (builder.length() > 0) { + component.setText(builder.toString()); + components.add(component); + } + if (components.isEmpty()) components.add(new TextComponent("")); + return components.toArray(new BaseComponent[components.size()]); + } - public TextComponent(TextComponent textComponent) { - super(textComponent); - this.setText(textComponent.getText()); - } + public TextComponent(TextComponent textComponent) { + super(textComponent); + setText(textComponent.getText()); + } - public /* varargs */ TextComponent(BaseComponent ... extras) { - this.setText(""); - this.setExtra(new ArrayList(Arrays.asList(extras))); - } + public /* varargs */ TextComponent(BaseComponent... extras) { + setText(""); + setExtra(new ArrayList(Arrays.asList(extras))); + } - @Override - public BaseComponent duplicate() { - return new TextComponent(this); - } + @Override + public BaseComponent duplicate() { + return new TextComponent(this); + } - @Override - protected void toPlainText(StringBuilder builder) { - builder.append(this.text); - super.toPlainText(builder); - } + @Override + protected void toPlainText(StringBuilder builder) { + builder.append(text); + super.toPlainText(builder); + } - @Override - protected void toLegacyText(StringBuilder builder) { - builder.append((Object)this.getColor()); - if (this.isBold()) { - builder.append((Object)ChatColor.BOLD); - } - if (this.isItalic()) { - builder.append((Object)ChatColor.ITALIC); - } - if (this.isUnderlined()) { - builder.append((Object)ChatColor.UNDERLINE); - } - if (this.isStrikethrough()) { - builder.append((Object)ChatColor.STRIKETHROUGH); - } - if (this.isObfuscated()) { - builder.append((Object)ChatColor.MAGIC); - } - builder.append(this.text); - super.toLegacyText(builder); - } + @Override + protected void toLegacyText(StringBuilder builder) { + builder.append(getColor()); + if (isBold()) builder.append(ChatColor.BOLD); + if (isItalic()) builder.append(ChatColor.ITALIC); + if (isUnderlined()) builder.append(ChatColor.UNDERLINE); + if (isStrikethrough()) builder.append(ChatColor.STRIKETHROUGH); + if (isObfuscated()) builder.append(ChatColor.MAGIC); + builder.append(text); + super.toLegacyText(builder); + } - @Override - public String toString() { - return String.format("TextComponent{text=%s, %s}", this.text, super.toString()); - } + @Override + public String toString() { + return String.format("TextComponent{text=%s, %s}", text, super.toString()); + } - public String getText() { - return this.text; - } + public String getText() { + return text; + } - public void setText(String text) { - this.text = text; - } + public void setText(String text) { + this.text = text; + } - @ConstructorProperties(value={"text"}) - public TextComponent(String text) { - this.text = text; - } + @ConstructorProperties(value = { "text" }) + public TextComponent(String text) { + this.text = text; + } - public TextComponent() { - } + public TextComponent() {} } - diff --git a/src/net/md_5/bungee/api/chat/TranslatableComponent.java b/src/net/md_5/bungee/api/chat/TranslatableComponent.java index 8e69917..f2e1dbc 100644 --- a/src/net/md_5/bungee/api/chat/TranslatableComponent.java +++ b/src/net/md_5/bungee/api/chat/TranslatableComponent.java @@ -9,188 +9,165 @@ import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.regex.Matcher; import java.util.regex.Pattern; + import net.md_5.bungee.api.ChatColor; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.TextComponent; -public class TranslatableComponent -extends BaseComponent { - private final ResourceBundle locales = ResourceBundle.getBundle("mojang-translations/en_US"); - private final Pattern format = Pattern.compile("%(?:(\\d+)\\$)?([A-Za-z%]|$)"); - private String translate; - private List with; +public class TranslatableComponent extends BaseComponent { + private final ResourceBundle locales = ResourceBundle.getBundle("mojang-translations/en_US"); + private final Pattern format = Pattern.compile("%(?:(\\d+)\\$)?([A-Za-z%]|$)"); + private String translate; + private List with; - public TranslatableComponent(TranslatableComponent original) { - super(original); - this.setTranslate(original.getTranslate()); - if (original.getWith() != null) { - ArrayList temp = new ArrayList(); - for (BaseComponent baseComponent : original.getWith()) { - temp.add(baseComponent.duplicate()); - } - this.setWith(temp); - } - } + public TranslatableComponent(TranslatableComponent original) { + super(original); + setTranslate(original.getTranslate()); + if (original.getWith() != null) { + ArrayList temp = new ArrayList(); + for (BaseComponent baseComponent : original.getWith()) + temp.add(baseComponent.duplicate()); + setWith(temp); + } + } - public /* varargs */ TranslatableComponent(String translate, Object ... with) { - this.setTranslate(translate); - ArrayList temp = new ArrayList(); - for (Object w : with) { - if (w instanceof String) { - temp.add(new TextComponent((String)w)); - continue; - } - temp.add((BaseComponent)w); - } - this.setWith(temp); - } + public /* varargs */ TranslatableComponent(String translate, Object... with) { + setTranslate(translate); + ArrayList temp = new ArrayList(); + for (Object w : with) { + if (w instanceof String) { + temp.add(new TextComponent((String) w)); + continue; + } + temp.add((BaseComponent) w); + } + setWith(temp); + } - @Override - public BaseComponent duplicate() { - return new TranslatableComponent(this); - } + @Override + public BaseComponent duplicate() { + return new TranslatableComponent(this); + } - public void setWith(List components) { - for (BaseComponent component : components) { - component.parent = this; - } - this.with = components; - } + public void setWith(List components) { + for (BaseComponent component : components) + component.parent = this; + with = components; + } - public void addWith(String text) { - this.addWith(new TextComponent(text)); - } + public void addWith(String text) { + this.addWith(new TextComponent(text)); + } - public void addWith(BaseComponent component) { - if (this.with == null) { - this.with = new ArrayList(); - } - component.parent = this; - this.with.add(component); - } + public void addWith(BaseComponent component) { + if (with == null) with = new ArrayList(); + component.parent = this; + with.add(component); + } - @Override - protected void toPlainText(StringBuilder builder) { - String trans; - try { - trans = this.locales.getString(this.translate); - } - catch (MissingResourceException ex) { - trans = this.translate; - } - Matcher matcher = this.format.matcher(trans); - int position = 0; - int i = 0; - while (matcher.find(position)) { - int pos = matcher.start(); - if (pos != position) { - builder.append(trans.substring(position, pos)); - } - position = matcher.end(); - String formatCode = matcher.group(2); - switch (formatCode.charAt(0)) { - case 'd': - case 's': { - String withIndex = matcher.group(1); - this.with.get(withIndex != null ? Integer.parseInt(withIndex) - 1 : i++).toPlainText(builder); - break; - } - case '%': { - builder.append('%'); - } - } - } - if (trans.length() != position) { - builder.append(trans.substring(position, trans.length())); - } - super.toPlainText(builder); - } + @Override + protected void toPlainText(StringBuilder builder) { + String trans; + try { + trans = locales.getString(translate); + } catch (MissingResourceException ex) { + trans = translate; + } + Matcher matcher = format.matcher(trans); + int position = 0; + int i = 0; + while (matcher.find(position)) { + int pos = matcher.start(); + if (pos != position) builder.append(trans.substring(position, pos)); + position = matcher.end(); + String formatCode = matcher.group(2); + switch (formatCode.charAt(0)) { + case 'd': + case 's': { + String withIndex = matcher.group(1); + with.get(withIndex != null ? Integer.parseInt(withIndex) - 1 : i++).toPlainText(builder); + break; + } + case '%': { + builder.append('%'); + } + } + } + if (trans.length() != position) builder.append(trans.substring(position, trans.length())); + super.toPlainText(builder); + } - @Override - protected void toLegacyText(StringBuilder builder) { - String trans; - try { - trans = this.locales.getString(this.translate); - } - catch (MissingResourceException e) { - trans = this.translate; - } - Matcher matcher = this.format.matcher(trans); - int position = 0; - int i = 0; - while (matcher.find(position)) { - int pos = matcher.start(); - if (pos != position) { - this.addFormat(builder); - builder.append(trans.substring(position, pos)); - } - position = matcher.end(); - String formatCode = matcher.group(2); - switch (formatCode.charAt(0)) { - case 'd': - case 's': { - String withIndex = matcher.group(1); - this.with.get(withIndex != null ? Integer.parseInt(withIndex) - 1 : i++).toLegacyText(builder); - break; - } - case '%': { - this.addFormat(builder); - builder.append('%'); - } - } - } - if (trans.length() != position) { - this.addFormat(builder); - builder.append(trans.substring(position, trans.length())); - } - super.toLegacyText(builder); - } + @Override + protected void toLegacyText(StringBuilder builder) { + String trans; + try { + trans = locales.getString(translate); + } catch (MissingResourceException e) { + trans = translate; + } + Matcher matcher = format.matcher(trans); + int position = 0; + int i = 0; + while (matcher.find(position)) { + int pos = matcher.start(); + if (pos != position) { + addFormat(builder); + builder.append(trans.substring(position, pos)); + } + position = matcher.end(); + String formatCode = matcher.group(2); + switch (formatCode.charAt(0)) { + case 'd': + case 's': { + String withIndex = matcher.group(1); + with.get(withIndex != null ? Integer.parseInt(withIndex) - 1 : i++).toLegacyText(builder); + break; + } + case '%': { + addFormat(builder); + builder.append('%'); + } + } + } + if (trans.length() != position) { + addFormat(builder); + builder.append(trans.substring(position, trans.length())); + } + super.toLegacyText(builder); + } - private void addFormat(StringBuilder builder) { - builder.append((Object)this.getColor()); - if (this.isBold()) { - builder.append((Object)ChatColor.BOLD); - } - if (this.isItalic()) { - builder.append((Object)ChatColor.ITALIC); - } - if (this.isUnderlined()) { - builder.append((Object)ChatColor.UNDERLINE); - } - if (this.isStrikethrough()) { - builder.append((Object)ChatColor.STRIKETHROUGH); - } - if (this.isObfuscated()) { - builder.append((Object)ChatColor.MAGIC); - } - } + private void addFormat(StringBuilder builder) { + builder.append(getColor()); + if (isBold()) builder.append(ChatColor.BOLD); + if (isItalic()) builder.append(ChatColor.ITALIC); + if (isUnderlined()) builder.append(ChatColor.UNDERLINE); + if (isStrikethrough()) builder.append(ChatColor.STRIKETHROUGH); + if (isObfuscated()) builder.append(ChatColor.MAGIC); + } - public ResourceBundle getLocales() { - return this.locales; - } + public ResourceBundle getLocales() { + return locales; + } - public Pattern getFormat() { - return this.format; - } + public Pattern getFormat() { + return format; + } - public String getTranslate() { - return this.translate; - } + public String getTranslate() { + return translate; + } - public List getWith() { - return this.with; - } + public List getWith() { + return with; + } - public void setTranslate(String translate) { - this.translate = translate; - } + public void setTranslate(String translate) { + this.translate = translate; + } - @Override - public String toString() { - return "TranslatableComponent(locales=" + this.getLocales() + ", format=" + this.getFormat() + ", translate=" + this.getTranslate() + ", with=" + this.getWith() + ")"; - } + @Override + public String toString() { + return "TranslatableComponent(locales=" + getLocales() + ", format=" + getFormat() + ", translate=" + + getTranslate() + ", with=" + getWith() + ")"; + } - public TranslatableComponent() { - } + public TranslatableComponent() {} } -