Cleanup/format code + suppression ancien ORM

This commit is contained in:
Marc Baloup 2016-07-14 14:22:23 +02:00
parent c5af1bd213
commit 724e9ecd6c
103 changed files with 3047 additions and 5751 deletions

View File

@ -5,12 +5,12 @@ import java.util.GregorianCalendar;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class DateUtil {
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]*)?"
public static long parseDateDiff(String time, boolean future) throws Exception + "(?:([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]*)?"
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); + "(?:([0-9]+)\\s*(?:s[a-z]*)?)?", Pattern.CASE_INSENSITIVE);
Matcher m = timePattern.matcher(time); Matcher m = timePattern.matcher(time);
int years = 0; int years = 0;
int months = 0; int months = 0;
@ -20,101 +20,43 @@ public class DateUtil
int minutes = 0; int minutes = 0;
int seconds = 0; int seconds = 0;
boolean found = false; boolean found = false;
while (m.find()) while (m.find()) {
{ if (m.group() == null || m.group().isEmpty()) continue;
if (m.group() == null || m.group().isEmpty())
{
continue;
}
for (int i = 0; i < m.groupCount(); i++) 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; found = true;
break; break;
} }
} if (found) {
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(1) != null && !m.group(1).isEmpty()) 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));
years = Integer.parseInt(m.group(1)); 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(2) != null && !m.group(2).isEmpty()) if (m.group(7) != null && !m.group(7).isEmpty()) seconds = Integer.parseInt(m.group(7));
{
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; break;
} }
} }
if (!found) if (!found) throw new Exception("Format de durée invalide");
{
throw new Exception("Format de durée invalide");
}
Calendar c = new GregorianCalendar(); Calendar c = new GregorianCalendar();
if (years > 0) if (years > 0) c.add(Calendar.YEAR, years * (future ? 1 : -1));
{ if (months > 0) c.add(Calendar.MONTH, months * (future ? 1 : -1));
c.add(Calendar.YEAR, years * (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 (months > 0) if (hours > 0) c.add(Calendar.HOUR_OF_DAY, hours * (future ? 1 : -1));
{ if (minutes > 0) c.add(Calendar.MINUTE, minutes * (future ? 1 : -1));
c.add(Calendar.MONTH, months * (future ? 1 : -1)); if (seconds > 0) c.add(Calendar.SECOND, seconds * (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(); Calendar max = new GregorianCalendar();
max.add(Calendar.YEAR, 10); max.add(Calendar.YEAR, 10);
if (c.after(max)) if (c.after(max)) return max.getTimeInMillis();
{
return max.getTimeInMillis();
}
return c.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; int diff = 0;
long savedDate = fromDate.getTimeInMillis(); 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(); savedDate = fromDate.getTimeInMillis();
fromDate.add(type, future ? 1 : -1); fromDate.add(type, future ? 1 : -1);
diff++; diff++;
@ -124,52 +66,32 @@ public class DateUtil
return diff; return diff;
} }
public static String formatDateDiff(long date) public static String formatDateDiff(long date) {
{
Calendar c = new GregorianCalendar(); Calendar c = new GregorianCalendar();
c.setTimeInMillis(date); c.setTimeInMillis(date);
Calendar now = new GregorianCalendar(); Calendar now = new GregorianCalendar();
return DateUtil.formatDateDiff(now, c); return DateUtil.formatDateDiff(now, c);
} }
public static String formatDateDiff(Calendar fromDate, Calendar toDate) public static String formatDateDiff(Calendar fromDate, Calendar toDate) {
{
boolean future = false; boolean future = false;
if (toDate.equals(fromDate)) if (toDate.equals(fromDate)) return "now";
{ if (toDate.after(fromDate)) future = true;
return "now";
}
if (toDate.after(fromDate))
{
future = true;
}
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
int[] types = new int[] int[] types = new int[] { Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, Calendar.HOUR_OF_DAY,
{ Calendar.MINUTE, Calendar.SECOND };
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" };
String[] names = new String[]
{
"year", "years", "month", "months", "day", "days", "hour", "hours", "minute", "minutes", "second", "seconds"
};
int accuracy = 0; int accuracy = 0;
for (int i = 0; i < types.length; i++) for (int i = 0; i < types.length; i++) {
{ if (accuracy > 2) break;
if (accuracy > 2)
{
break;
}
int diff = dateDiff(types[i], fromDate, toDate, future); int diff = dateDiff(types[i], fromDate, toDate, future);
if (diff > 0) if (diff > 0) {
{
accuracy++; accuracy++;
sb.append(" ").append(diff).append(" ").append(names[i * 2 + (diff > 1 ? 1 : 0)]); sb.append(" ").append(diff).append(" ").append(names[i * 2 + (diff > 1 ? 1 : 0)]);
} }
} }
if (sb.length() == 0) if (sb.length() == 0) return "now";
{
return "now";
}
return sb.toString().trim(); return sb.toString().trim();
} }
} }

View File

@ -3,14 +3,11 @@ package fr.pandacube.java;
import java.nio.charset.Charset; import java.nio.charset.Charset;
public class Pandacube { public class Pandacube {
public static final Charset NETWORK_CHARSET = Charset.forName("UTF-8"); 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_TCP_BUFFER_SIZE = 1024 * 1024;
public static final int NETWORK_TIMEOUT = 30*1000; // 30 secondes public static final int NETWORK_TIMEOUT = 30 * 1000; // 30 secondes
} }

View File

@ -1,35 +1,28 @@
package fr.pandacube.java.external_tools; package fr.pandacube.java.external_tools;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.util.*; import java.util.UUID;
public class OfflineUUID { public class OfflineUUID {
public static void main(String[] args) { public static void main(String[] args) {
for (String arg : args) for (String arg : args)
{ System.out.println("" + arg + ":" + getFromNickName(arg));
System.out.println(""+arg+":"+getFromNickName(arg)); if (args.length == 0)
} throw new IllegalArgumentException("no argument given. Please give at least one argument.");
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);
} }
public static UUID getFromNickName(String nickname) {
public static UUID[] getFromNickName(String[] nicknames) String str = "OfflinePlayer:" + nickname;
{ byte[] from_str = str.getBytes(Charset.forName("UTF-8"));
if (nicknames == null) return UUID.nameUUIDFromBytes(from_str);
throw new NullPointerException(); }
public static UUID[] getFromNickName(String[] nicknames) {
if (nicknames == null) throw new NullPointerException();
UUID[] uuids = new UUID[nicknames.length]; UUID[] uuids = new UUID[nicknames.length];
for (int i=0; i<nicknames.length; i++) for (int i = 0; i < nicknames.length; i++)
uuids[i] = getFromNickName(nicknames[i]); uuids[i] = getFromNickName(nicknames[i]);
return uuids; return uuids;
} }
} }

View File

@ -4,4 +4,3 @@ package fr.pandacube.java.util;
public interface Callback<T> { public interface Callback<T> {
public void done(T arg); public void done(T arg);
} }

View File

@ -4,82 +4,86 @@ public class EnumUtil {
/** /**
* List all enum constants which are in the specified enum class. * List all enum constants which are in the specified enum class.
*
* @param enumType the enum class. * @param enumType the enum class.
* @param separator a string which will be used as a separator * @param separator a string which will be used as a separator
* @return a string representation of the enum class. * @return a string representation of the enum class.
*/ */
public static <T extends Enum<T>> String enumList(Class<T> enumType, String separator) { public static <T extends Enum<T>> String enumList(Class<T> enumType, String separator) {
T[] elements = enumType.getEnumConstants(); T[] elements = enumType.getEnumConstants();
String out = ""; String out = "";
boolean first = true; boolean first = true;
for (T el : elements) { for (T el : elements) {
if (!first) { if (!first) out += separator;
out += separator;
}
first = false; first = false;
out += el.name(); out += el.name();
} }
return out; return out;
} }
/** /**
* List all enum constants which are in the specified enum class. It is equivalent to call * List all enum constants which are in the specified enum class. It is
* {@link #enumList(Class, String)} with the second parameter <code>", "</code> * equivalent to call
* {@link #enumList(Class, String)} with the second parameter
* <code>", "</code>
*
* @param enumType the enum class. * @param enumType the enum class.
* @return a string representation of the enum class. * @return a string representation of the enum class.
*/ */
public static <T extends Enum<T>> String enumList(Class<T> enumType) { public static <T extends Enum<T>> String enumList(Class<T> enumType) {
return enumList(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 enumType la classe correpondant à l'enum à lister
* @param search l'élément à rechercher, insensible à la casse * @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 * @return l'élément de l'énumarétion, si elle a été trouvée, null sinon
*/ */
public static <T extends Enum<T>> T searchEnum(Class<T> enumType, String search) { public static <T extends Enum<T>> T searchEnum(Class<T> enumType, String search) {
T[] elements = enumType.getEnumConstants(); T[] elements = enumType.getEnumConstants();
for (T el : elements) for (T el : elements)
if (el.name().equalsIgnoreCase(search)) if (el.name().equalsIgnoreCase(search)) return el;
return el; return null;
return null;
} }
/** /**
* 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
* La validité de la classe passé en premier paramètre est vérifiée dynamiquement et non * insensible à la casse
* statiquement. Préférez l'utilisation de {@link #searchEnum(Class, String)} quand c'est possible. * 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 enumType la classe correpondant à l'enum à lister
* @param search l'élément à rechercher, insensible à la casse * @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) { public static Enum<?> searchUncheckedEnum(Class<?> enumType, String search) {
if (!enumType.isEnum()) if (!enumType.isEnum()) return null;
return null;
Enum<?>[] elements = (Enum<?>[]) enumType.getEnumConstants(); Enum<?>[] elements = (Enum<?>[]) enumType.getEnumConstants();
for (Enum<?> el : elements) for (Enum<?> el : elements)
if (el.name().equalsIgnoreCase(search)) if (el.name().equalsIgnoreCase(search)) return el;
return el; return null;
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 * @param enumType l'enum dans lequel piocher la valeur
* @return une des valeurs de l'enum * @return une des valeurs de l'enum
*/ */
public static <T extends Enum<T>> T randomValue(Class<T> enumType) { public static <T extends Enum<T>> T randomValue(Class<T> enumType) {
T[] elements = enumType.getEnumConstants(); T[] elements = enumType.getEnumConstants();
return elements[RandomUtil.rand.nextInt(elements.length)]; return elements[RandomUtil.rand.nextInt(elements.length)];
} }

File diff suppressed because it is too large Load Diff

View File

@ -5,18 +5,17 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
public class Log { public class Log {
private static Logger logger; private static Logger logger;
private static AtomicBoolean logDebug = new AtomicBoolean(false); private static AtomicBoolean logDebug = new AtomicBoolean(false);
public static void setDebugState(boolean newVal) { public static void setDebugState(boolean newVal) {
logDebug.set(newVal); logDebug.set(newVal);
} }
public static boolean getDebugState() { public static boolean getDebugState() {
return logDebug.get(); return logDebug.get();
} }
public static Logger getLogger() { public static Logger getLogger() {
return logger; return logger;
@ -25,45 +24,45 @@ public class Log {
public static void setLogger(Logger l) { public static void setLogger(Logger l) {
logger = l; logger = l;
} }
public static void info(String message) { public static void info(String message) {
logger.info(message); logger.info(message);
} }
public static void warning(String message, Throwable t) { public static void warning(String message, Throwable t) {
logger.log(Level.WARNING, message, t); logger.log(Level.WARNING, message, t);
} }
public static void warning(Throwable t) { public static void warning(Throwable t) {
logger.log(Level.WARNING, "", t); logger.log(Level.WARNING, "", t);
} }
public static void warning(String message) { public static void warning(String message) {
logger.warning(message); logger.warning(message);
} }
public static void severe(String message, Throwable t) { public static void severe(String message, Throwable t) {
logger.log(Level.SEVERE, message, t); logger.log(Level.SEVERE, message, t);
} }
public static void severe(Throwable t) { public static void severe(Throwable t) {
logger.log(Level.SEVERE, "", t); logger.log(Level.SEVERE, "", t);
} }
public static void severe(String message) { public static void severe(String message) {
logger.severe(message); logger.severe(message);
} }
public static void debug(String message, Throwable t) { public static void debug(String message, Throwable t) {
if (!logDebug.get()) return; if (!logDebug.get()) return;
logger.log(Level.INFO, message, t); logger.log(Level.INFO, message, t);
} }
public static void debug(Throwable t) { public static void debug(Throwable t) {
if (!logDebug.get()) return; if (!logDebug.get()) return;
logger.log(Level.INFO, "", t); logger.log(Level.INFO, "", t);
} }
public static void debug(String message) { public static void debug(String message) {
if (!logDebug.get()) return; if (!logDebug.get()) return;
logger.info(message); logger.info(message);

View File

@ -9,26 +9,25 @@ public enum MinecraftVersion {
v1_9_2(109, "1.9.2"), v1_9_2(109, "1.9.2"),
v1_9_3_to_1_9_4(110, "1.9.3-1.9.4"), v1_9_3_to_1_9_4(110, "1.9.3-1.9.4"),
v1_10(210, "1.10"); v1_10(210, "1.10");
public final int versionNumber; public final int versionNumber;
public final String versionDisplay; public final String versionDisplay;
private MinecraftVersion(int v, String d) { private MinecraftVersion(int v, String d) {
versionNumber = v; versionNumber = v;
versionDisplay = d; versionDisplay = d;
} }
@Override
public String toString() { public String toString() {
return versionDisplay; return versionDisplay;
} }
public static MinecraftVersion getVersion(int v) { public static MinecraftVersion getVersion(int v) {
for (MinecraftVersion mcV : MinecraftVersion.values()) for (MinecraftVersion mcV : MinecraftVersion.values())
if (mcV.versionNumber == v) if (mcV.versionNumber == v) return mcV;
return mcV;
return null; return null;
} }
} }

View File

@ -11,8 +11,8 @@ import fr.pandacube.java.util.db2.sql_tools.ORM;
import fr.pandacube.java.util.db2.sql_tools.SQLOrderBy; import fr.pandacube.java.util.db2.sql_tools.SQLOrderBy;
import fr.pandacube.java.util.db2.sql_tools.SQLOrderBy.Direction; import fr.pandacube.java.util.db2.sql_tools.SQLOrderBy.Direction;
import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp; import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp;
import fr.pandacube.java.util.db2.sql_tools.SQLWhereLike;
import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp.SQLComparator; import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp.SQLComparator;
import fr.pandacube.java.util.db2.sql_tools.SQLWhereLike;
import net.alpenblock.bungeeperms.BungeePerms; import net.alpenblock.bungeeperms.BungeePerms;
/* /*
@ -22,217 +22,187 @@ import net.alpenblock.bungeeperms.BungeePerms;
* chercher dans l'historique de login * chercher dans l'historique de login
*/ */
public class PlayerFinder { public class PlayerFinder {
private static BungeePerms getPermPlugin() { private static BungeePerms getPermPlugin() {
try { try {
return BungeePerms.getInstance(); return BungeePerms.getInstance();
} catch(NoClassDefFoundError|Exception e) { } catch (NoClassDefFoundError | Exception e) {
return null; return null;
} }
} }
public static String getLastKnownName(UUID id) { public static String getLastKnownName(UUID id) {
if (id == null) if (id == null) return null;
return null;
// on passe par le plugin de permission (mise en cache ? ) // on passe par le plugin de permission (mise en cache ? )
BungeePerms pl = getPermPlugin(); BungeePerms pl = getPermPlugin();
if (pl != null) if (pl != null) return pl.getPermissionsManager().getUUIDPlayerDB().getPlayerName(id);
return pl.getPermissionsManager().getUUIDPlayerDB().getPlayerName(id);
// on tente en accédant directement à la table des identifiants // on tente en accédant directement à la table des identifiants
try { try {
SQLUUIDPlayer el = ORM.getFirst(SQLUUIDPlayer.class, new SQLWhereComp(SQLUUIDPlayer.uuid, SQLComparator.EQ, id.toString()), null); SQLUUIDPlayer el = ORM.getFirst(SQLUUIDPlayer.class,
if (el != null) new SQLWhereComp(SQLUUIDPlayer.uuid, SQLComparator.EQ, id.toString()), null);
return el.get(SQLUUIDPlayer.player); if (el != null) return el.get(SQLUUIDPlayer.player);
} catch (Exception e) { } catch (Exception e) {
Log.severe("Can't search for player name from uuid in database", e); Log.severe("Can't search for player name from uuid in database", e);
} }
// le pseudo est introuvable // le pseudo est introuvable
return null; return null;
} }
public static List<String> getLocalNameHistory(UUID id) { public static List<String> getLocalNameHistory(UUID id) {
List<String> ret = new ArrayList<>(); List<String> ret = new ArrayList<>();
if (id == null) if (id == null) return ret;
return ret;
String last = getLastKnownName(id); String last = getLastKnownName(id);
if (last != null) if (last != null) ret.add(last);
ret.add(last);
try { try {
List<SQLLoginHistory> els = ORM.getAll(SQLLoginHistory.class, new SQLWhereComp(SQLLoginHistory.playerId, SQLComparator.EQ, id.toString()), new SQLOrderBy().addField(SQLLoginHistory.time, Direction.DESC), null, null); List<SQLLoginHistory> 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) { for (SQLLoginHistory el : els) {
String name = el.get(SQLLoginHistory.playerName); String name = el.get(SQLLoginHistory.playerName);
if (ret.contains(name)) if (ret.contains(name)) continue;
continue;
ret.add(name); ret.add(name);
} }
} catch (Exception e) { } catch (Exception e) {
Log.severe("Can't search for olds players names from uuid in database", e); Log.severe("Can't search for olds players names from uuid in database", e);
} }
return ret; return ret;
} }
/** /**
* Cherche un identifiant de compte en se basant sur le pseudo passé en paramètre. La méthode * Cherche un identifiant de compte en se basant sur le pseudo passé en
* cherchera d'abord dans les derniers pseudos connus. Puis, cherchera la dernière personne à * 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. * 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 * @param old si on doit chercher dans les anciens pseudos de joueurs
* @return l'UUID du joueur si trouvé, null sinon * @return l'UUID du joueur si trouvé, null sinon
*/ */
public static UUID getPlayerId(String exactName, boolean old) { 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 // on tente d'abord via le plugin de permission
BungeePerms pl = getPermPlugin(); BungeePerms pl = getPermPlugin();
if (pl != null) if (pl != null) return pl.getPermissionsManager().getUUIDPlayerDB().getUUID(exactName);
return pl.getPermissionsManager().getUUIDPlayerDB().getUUID(exactName);
// on tente en accédant directement à la table des identifiants // on tente en accédant directement à la table des identifiants
try { try {
SQLUUIDPlayer el = ORM.getFirst(SQLUUIDPlayer.class, new SQLWhereLike(SQLUUIDPlayer.player, exactName.replace("_", "\\_")), null); SQLUUIDPlayer el = ORM.getFirst(SQLUUIDPlayer.class,
if (el != null) new SQLWhereLike(SQLUUIDPlayer.player, exactName.replace("_", "\\_")), null);
return el.getUUID(); if (el != null) return el.getUUID();
} catch (Exception e) { } catch (Exception e) {
Log.severe("Can't search for uuid from player name in database", e); Log.severe("Can't search for uuid from player name in database", e);
} }
if (!old) return null; if (!old) return null;
// on recherche dans les anciens pseudos // on recherche dans les anciens pseudos
try { try {
SQLLoginHistory el = ORM.getFirst(SQLLoginHistory.class, new SQLWhereLike(SQLLoginHistory.playerName, exactName.replace("_", "\\_")), new SQLOrderBy().addField(SQLLoginHistory.time, Direction.DESC)); SQLLoginHistory el = ORM.getFirst(SQLLoginHistory.class,
if (el != null) new SQLWhereLike(SQLLoginHistory.playerName, exactName.replace("_", "\\_")),
return el.getPlayerId(); new SQLOrderBy().addField(SQLLoginHistory.time, Direction.DESC));
if (el != null) return el.getPlayerId();
} catch (Exception e) { } catch (Exception e) {
Log.severe("Can't search for uuid from old player name in database", e); Log.severe("Can't search for uuid from old player name in database", e);
} }
// on a pas trouvé // on a pas trouvé
return null; 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 * @param old si on cherche aussi dans les anciens pseudos
* @return * @return
*/ */
public static List<PlayerSearchResult> searchForPlayers(String query, boolean old) { public static List<PlayerSearchResult> searchForPlayers(String query, boolean old) {
List<PlayerSearchResult> res = new ArrayList<>(); List<PlayerSearchResult> res = new ArrayList<>();
if (!isValidPlayerName(query)) return res; if (!isValidPlayerName(query)) return res;
// rechercher parmis les derniers pseudos connus de chaque joueurs // rechercher parmis les derniers pseudos connus de chaque joueurs
try { try {
List<SQLUUIDPlayer> els = ORM.getAll(SQLUUIDPlayer.class, new SQLWhereLike(SQLUUIDPlayer.player, "%"+query.replace("_", "\\_")+"%"), null, null, null); List<SQLUUIDPlayer> els = ORM.getAll(SQLUUIDPlayer.class,
new SQLWhereLike(SQLUUIDPlayer.player, "%" + query.replace("_", "\\_") + "%"), null, null, null);
for (SQLUUIDPlayer el : els) {
for (SQLUUIDPlayer el : els)
res.add(new PlayerSearchResult(el.getUUID(), el.get(SQLUUIDPlayer.player), null)); res.add(new PlayerSearchResult(el.getUUID(), el.get(SQLUUIDPlayer.player), null));
}
} catch (Exception e) { } catch (Exception e) {
Log.severe("Can't search for players names in database", e); Log.severe("Can't search for players names in database", e);
} }
if (!old) return res; if (!old) return res;
// rechercher parmi les anciens pseudos de joueurs // rechercher parmi les anciens pseudos de joueurs
try { try {
List<SQLLoginHistory> els = ORM.getAll(SQLLoginHistory.class, new SQLWhereLike(SQLLoginHistory.playerName, "%"+query.replace("_", "\\_")+"%"), new SQLOrderBy().addField(SQLLoginHistory.time, Direction.DESC), null, null); List<SQLLoginHistory> els = ORM.getAll(SQLLoginHistory.class,
new SQLWhereLike(SQLLoginHistory.playerName, "%" + query.replace("_", "\\_") + "%"),
new SQLOrderBy().addField(SQLLoginHistory.time, Direction.DESC), null, null);
for (SQLLoginHistory el : els) { for (SQLLoginHistory el : els) {
if (res.contains(new PlayerSearchResult(el.getPlayerId(), null, null))) if (res.contains(new PlayerSearchResult(el.getPlayerId(), null, null))) continue;
continue; res.add(new PlayerSearchResult(el.getPlayerId(), getLastKnownName(el.getPlayerId()),
res.add(new PlayerSearchResult(el.getPlayerId(), getLastKnownName(el.getPlayerId()), el.get(SQLLoginHistory.playerName))); el.get(SQLLoginHistory.playerName)));
} }
} catch (Exception e) { } catch (Exception e) {
Log.severe("Can't search for uuid from player name in database", e); Log.severe("Can't search for uuid from player name in database", e);
} }
return res; return res;
} }
public static class PlayerSearchResult { public static class PlayerSearchResult {
public final UUID uuid; public final UUID uuid;
public String lastName; public String lastName;
public final String nameFound; public final String nameFound;
PlayerSearchResult(UUID id, String last, String found) { PlayerSearchResult(UUID id, String last, String found) {
uuid = id; uuid = id;
lastName = last; lastName = last;
nameFound = found; nameFound = found;
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (o == null || !(o instanceof PlayerSearchResult)) return false; 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) { public static boolean isValidPlayerName(String name) {
if (name == null) return false; if (name == null) return false;
return name.matches("[0-9a-zA-Z_]{2,16}"); return name.matches("[0-9a-zA-Z_]{2,16}");
} }
public static SQLPlayer getDBPlayer(UUID id) throws Exception { public static SQLPlayer getDBPlayer(UUID id) throws Exception {
if (id == null) return null; 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);
} }
} }

View File

@ -8,114 +8,138 @@ import java.net.URL;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.UUID; import java.util.UUID;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName; 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). * This class performs a name lookup for a player and gets back all the name
* <br/><a href="https://bukkit.org/threads/player-name-history-lookup.412679/">https://bukkit.org/threads/player-name-history-lookup.412679/</a> * changes of the player (if any).
* @since 25-3-2016 * <br/>
* @author mine-care (AKA fillpant) * <a href="https://bukkit.org/threads/player-name-history-lookup.412679/">https
* * ://bukkit.org/threads/player-name-history-lookup.412679/</a>
*/ *
* @since 25-3-2016
* @author mine-care (AKA fillpant)
*
*/
public class PlayerNameHistoryLookup { public class PlayerNameHistoryLookup {
/** /**
* The URL from Mojang API that provides the JSON String in response. * 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 String LOOKUP_URL = "https://api.mojang.com/user/profiles/%s/names";
private static final Gson JSON_PARSER = new Gson(); private static final Gson JSON_PARSER = new Gson();
/** /**
* <h1>NOTE: Avoid running this method <i>Synchronously</i> with the main thread!It blocks while attempting to get a response from Mojang servers!</h1> * <h1>NOTE: Avoid running this method <i>Synchronously</i> with the main
* @param player The UUID of the player to be looked up. * thread!It blocks while attempting to get a response from Mojang servers!
* @return Returns an array of {@link PreviousPlayerNameEntry} objects, or null if the response couldn't be interpreted. * </h1>
* @throws IOException {@link #getPlayerPreviousNames(String)} *
*/ * @param player The UUID of the player to be looked up.
public static PreviousPlayerNameEntry[] getPlayerPreviousNames(UUID player) throws IOException { * @return Returns an array of {@link PreviousPlayerNameEntry} objects, or
return getPlayerPreviousNames(player.toString()); * null if the response couldn't be interpreted.
} * @throws IOException {@link #getPlayerPreviousNames(String)}
*/
/** public static PreviousPlayerNameEntry[] getPlayerPreviousNames(UUID player) throws IOException {
* <h1>NOTE: Avoid running this method <i>Synchronously</i> with the main thread! It blocks while attempting to get a response from Mojang servers!</h1> return getPlayerPreviousNames(player.toString());
* 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)} * <h1>NOTE: Avoid running this method <i>Synchronously</i> with the main
*/ * thread! It blocks while attempting to get a response from Mojang servers!
public static PreviousPlayerNameEntry[] getPlayerPreviousNames(String uuid) throws IOException { * </h1>
if (uuid == null || uuid.isEmpty()) * Alternative method accepting an {@link OfflinePlayer} (and therefore
return null; * {@link Player}) objects as parameter.
uuid = uuid.replace("-", ""); *
String response = getRawJsonResponse(new URL(String.format(LOOKUP_URL, uuid))); * @param uuid The UUID String to lookup
PreviousPlayerNameEntry[] names = JSON_PARSER.fromJson(response, PreviousPlayerNameEntry[].class); * @return Returns an array of {@link PreviousPlayerNameEntry} objects, or
return names; * null if the response couldn't be interpreted.
} * @throws IOException {@link #getRawJsonResponse(String)}
*/
/** public static PreviousPlayerNameEntry[] getPlayerPreviousNames(String uuid) throws IOException {
* This is a helper method used to read the response of Mojang's API webservers. if (uuid == null || uuid.isEmpty()) return null;
* @param u the URL to connect to uuid = uuid.replace("-", "");
* @return a String with the data read. String response = getRawJsonResponse(new URL(String.format(LOOKUP_URL, uuid)));
* @throws IOException Inherited by {@link BufferedReader#readLine()}, {@link BufferedReader#close()}, {@link URL}, {@link HttpURLConnection#getInputStream()} PreviousPlayerNameEntry[] names = JSON_PARSER.fromJson(response, PreviousPlayerNameEntry[].class);
*/ return names;
private static String getRawJsonResponse(URL u) throws IOException { }
HttpURLConnection con = (HttpURLConnection) u.openConnection();
con.setDoInput(true); /**
con.setConnectTimeout(2000); * This is a helper method used to read the response of Mojang's API
con.setReadTimeout(2000); * webservers.
con.connect(); *
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); * @param u the URL to connect to
String response = in.readLine(); * @return a String with the data read.
in.close(); * @throws IOException Inherited by {@link BufferedReader#readLine()},
return response; * {@link BufferedReader#close()}, {@link URL},
} * {@link HttpURLConnection#getInputStream()}
*/
/** private static String getRawJsonResponse(URL u) throws IOException {
* This class represents the typical response expected by Mojang servers when requesting the name history of a player. HttpURLConnection con = (HttpURLConnection) u.openConnection();
*/ con.setDoInput(true);
public class PreviousPlayerNameEntry { con.setConnectTimeout(2000);
private String name; con.setReadTimeout(2000);
@SerializedName("changedToAt") con.connect();
private long changeTime; BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String response = in.readLine();
/** in.close();
* Gets the player name of this entry. return response;
* @return The name of the player. }
*/
public String getPlayerName() { /**
return name; * This class represents the typical response expected by Mojang servers
} * when requesting the name history of a player.
*/
/** public class PreviousPlayerNameEntry {
* Get the time of change of the name. private String name;
* <br><b>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! @SerializedName("changedToAt")
* <br>Parsing 0 to a Date will result in the date "01/01/1970".</b> private long changeTime;
* @return a timestamp in miliseconds that you can turn into a date or handle however you want :)
*/ /**
public long getChangeTime() { * Gets the player name of this entry.
return changeTime; *
} * @return The name of the player.
*/
/** public String getPlayerName() {
* Check if this name is the name used to register the account (the initial/original name) return name;
* @return a boolean, true if it is the the very first name of the player, otherwise false. }
*/
public boolean isPlayersInitialName() { /**
return getChangeTime() == 0; * Get the time of change of the name.
} * <br>
* <b>Note: This will return 0 if the name is the original (initial)
@Override * name of the player! Make sure you check if it is 0 before handling!
public String toString() { * <br>
return "Name: " + name + " Date of change: " + new Date(changeTime).toString(); * Parsing 0 to a Date will result in the date "01/01/1970".</b>
} *
} * @return a timestamp in miliseconds that you can turn into a date or
* handle however you want :)
*/
public long getChangeTime() {
public static void main(String[] args) throws IOException { 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"))); System.out.println(Arrays.toString(getPlayerPreviousNames("a18d9b2c-e18f-4933-9e15-36452bc36857")));
} }
} }

View File

@ -3,17 +3,15 @@ package fr.pandacube.java.util;
import java.util.Random; import java.util.Random;
public class RandomUtil { public class RandomUtil {
public static Random rand = new Random(); public static Random rand = new Random();
public static int nextIntBetween(int minInclu, int maxExclu) { 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) { public static double nextDoubleBetween(double minInclu, double maxExclu) {
return rand.nextDouble()*(maxExclu-minInclu)+minInclu; return rand.nextDouble() * (maxExclu - minInclu) + minInclu;
} }
} }

View File

@ -12,16 +12,15 @@ import java.util.Map;
import com.google.gson.Gson; import com.google.gson.Gson;
public class ServerPropertyFile { public class ServerPropertyFile {
private File file; private File file;
private Map<String, Object> data; private Map<String, Object> data;
public ServerPropertyFile(File f) { public ServerPropertyFile(File f) {
if (f == null) throw new IllegalArgumentException("f ne doit pas être null"); if (f == null) throw new IllegalArgumentException("f ne doit pas être null");
file = f; file = f;
data = new HashMap<String, Object>(); data = new HashMap<String, Object>();
data.put("name", "default_name"); data.put("name", "default_name");
data.put("memory", "512M"); data.put("memory", "512M");
@ -30,138 +29,120 @@ public class ServerPropertyFile {
data.put("jarFile", ""); data.put("jarFile", "");
data.put("isLobby", false); data.put("isLobby", false);
} }
/** /**
* Charge le fichier de configuration dans cette instance de la classe * Charge le fichier de configuration dans cette instance de la classe
*
* @return true si le chargement a réussi, false sinon * @return true si le chargement a réussi, false sinon
*/ */
public boolean loadFromFile() { public boolean loadFromFile() {
BufferedReader in = null; BufferedReader in = null;
try { try {
in = new BufferedReader(new FileReader(file)); in = new BufferedReader(new FileReader(file));
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Map<String, Object> dataFile = new Gson().fromJson(in, Map.class); Map<String, Object> dataFile = new Gson().fromJson(in, Map.class);
if (!dataFile.containsKey("name") || !(dataFile.get("name") instanceof String)) if (!dataFile.containsKey("name") || !(dataFile.get("name") instanceof String)) return false;
return false;
if (!dataFile.containsKey("memory") || !(dataFile.get("memory") instanceof String)) if (!dataFile.containsKey("memory") || !(dataFile.get("memory") instanceof String)) return false;
return false;
if (!dataFile.containsKey("javaArgs") || !(dataFile.get("javaArgs") instanceof String)) if (!dataFile.containsKey("javaArgs") || !(dataFile.get("javaArgs") instanceof String)) return false;
return false;
if (!dataFile.containsKey("MinecraftArgs") || !(dataFile.get("MinecraftArgs") instanceof String)) if (!dataFile.containsKey("MinecraftArgs") || !(dataFile.get("MinecraftArgs") instanceof String))
return false; return false;
if (!dataFile.containsKey("jarFile") || !(dataFile.get("jarFile") instanceof String)) if (!dataFile.containsKey("jarFile") || !(dataFile.get("jarFile") instanceof String)) return false;
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; 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; return true;
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} } finally {
finally {
try { try {
out.close(); in.close();
} catch (Exception e) { } } catch (Exception e) {}
} }
return false; 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() { public String getName() {
return (String) data.get("name"); return (String) data.get("name");
} }
public String getMemory() { public String getMemory() {
return (String) data.get("memory"); return (String) data.get("memory");
} }
public String getJavaArgs() { public String getJavaArgs() {
return (String) data.get("javaArgs"); return (String) data.get("javaArgs");
} }
public String getMinecraftArgs() { public String getMinecraftArgs() {
return (String) data.get("MinecraftArgs"); return (String) data.get("MinecraftArgs");
} }
public String getJarFile() { public String getJarFile() {
return (String) data.get("jarFile"); return (String) data.get("jarFile");
} }
public boolean getIsLobby() { public boolean getIsLobby() {
return (boolean) data.get("isLobby"); return (boolean) data.get("isLobby");
} }
public void setName(String n) { public void setName(String n) {
if (n == null || !n.matches("^[a-zA-Z]$")) if (n == null || !n.matches("^[a-zA-Z]$")) throw new IllegalArgumentException();
throw new IllegalArgumentException();
data.put("name", n); data.put("name", n);
} }
public void setMemory(String m) { public void setMemory(String m) {
if (m == null || !m.matches("^[0-9]+[mgMG]$")) if (m == null || !m.matches("^[0-9]+[mgMG]$")) throw new IllegalArgumentException();
throw new IllegalArgumentException();
data.put("memory", m); data.put("memory", m);
} }
public void setJavaArgs(String ja) { public void setJavaArgs(String ja) {
if (ja == null) if (ja == null) throw new IllegalArgumentException();
throw new IllegalArgumentException();
data.put("javaArgs", ja); data.put("javaArgs", ja);
} }
public void setMinecraftArgs(String ma) { public void setMinecraftArgs(String ma) {
if (ma == null) if (ma == null) throw new IllegalArgumentException();
throw new IllegalArgumentException();
data.put("MinecraftArgs", ma); data.put("MinecraftArgs", ma);
} }
public void setJarFile(String j) { public void setJarFile(String j) {
if (j == null) if (j == null) throw new IllegalArgumentException();
throw new IllegalArgumentException();
data.put("jarFile", j); data.put("jarFile", j);
} }
public void setIsLobby(boolean l) { public void setIsLobby(boolean l) {
data.put("isLobby", l); data.put("isLobby", l);
} }
} }

View File

@ -1,26 +1,22 @@
package fr.pandacube.java.util; package fr.pandacube.java.util;
public class StringUtil { public class StringUtil {
public static String formatDouble(double d) public static String formatDouble(double d) {
{ if (d == (long) d) return String.format("%d", (long) d);
if(d == (long) d) else
return String.format("%d",(long)d); return String.valueOf(d);
else
return String.valueOf(d);
} }
/** /**
* @param s Chaine de caractère à parcourir * @param s Chaine de caractère à parcourir
* @param c_match le caractère dont on doit retourner le nombre d'occurence * @param c_match le caractère dont on doit retourner le nombre d'occurence
* @return nombre d'occurence de <b>c_match</b> dans <b>s</b> * @return nombre d'occurence de <b>c_match</b> dans <b>s</b>
*/ */
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(); char[] chars = s.toString().toCharArray();
int count = 0; int count = 0;
for (char c : chars) for (char c : chars)
if (c == c_match) if (c == c_match) count++;
count++;
return count; return count;
} }
} }

View File

@ -9,86 +9,78 @@ import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.chat.TextComponent;
public class Display { public class Display {
private BaseComponent first = new TextComponent(""); private BaseComponent first = new TextComponent("");
private BaseComponent current = null; 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) { public Display(String legacyText) {
convertAndAddLegacy(legacyText); convertAndAddLegacy(legacyText);
} }
/** /**
* Construit un message en mettant à la ligne après chaque chaine passé en paramètre.<br/> * Construit un message en mettant à la ligne après chaque chaine passé en
* Après l'appel de ce contructeur, vous devez appeler nextComponent() pour initialiser la composante suivante * paramètre.<br/>
* Après l'appel de ce contructeur, vous devez appeler nextComponent() pour
* initialiser la composante suivante
*/ */
public Display(String[] legacyText) { public Display(String[] legacyText) {
boolean f = true; boolean f = true;
for (String s : legacyText) { for (String s : legacyText) {
if (s == null) s = ""; if (s == null) s = "";
if (!f) if (!f) first.addExtra("\n");
first.addExtra("\n");
f = false; f = false;
convertAndAddLegacy(s); convertAndAddLegacy(s);
} }
} }
/** /**
* Construit un message en mettant à la ligne après chaque chaine passé en paramètre.<br/> * Construit un message en mettant à la ligne après chaque chaine passé en
* Après l'appel de ce contructeur, vous devez appeler nextComponent() pour initialiser la composante suivante * paramètre.<br/>
* Après l'appel de ce contructeur, vous devez appeler nextComponent() pour
* initialiser la composante suivante
*/ */
public Display(List<String> legacyText) { public Display(List<String> legacyText) {
this(legacyText.toArray(new String[legacyText.size()])); 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) { public Display(BaseComponent firstComponent) {
if (firstComponent == null) throw new IllegalArgumentException("le paramètre ne doit pas être null"); if (firstComponent == null) throw new IllegalArgumentException("le paramètre ne doit pas être null");
first.addExtra(firstComponent); 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) { public Display convertAndAddLegacy(String legacyText) {
finalizeCurrentComponent(); finalizeCurrentComponent();
if (legacyText == null) if (legacyText == null) return this;
return this;
BaseComponent[] compo = TextComponent.fromLegacyText(legacyText); BaseComponent[] compo = TextComponent.fromLegacyText(legacyText);
for (BaseComponent c : compo) { for (BaseComponent c : compo)
first.addExtra(c); first.addExtra(c);
}
return this; return this;
} }
public Display nextComponent(String str) { public Display nextComponent(String str) {
finalizeCurrentComponent(); finalizeCurrentComponent();
if (str == null) str = ""; if (str == null) str = "";
current = new TextComponent(str); current = new TextComponent(str);
return this; return this;
} }
public Display addComponent(BaseComponent cmp) { public Display addComponent(BaseComponent cmp) {
if (cmp == null) throw new IllegalArgumentException("le paramètre ne doit pas être null"); if (cmp == null) throw new IllegalArgumentException("le paramètre ne doit pas être null");
finalizeCurrentComponent(); finalizeCurrentComponent();
@ -97,86 +89,70 @@ public class Display {
} }
/** /**
* Équivalent à <code>nextComponent("\n")</code>, sauf qu'un nouvel appel à nextComponent() est nécessaire après. * Équivalent à <code>nextComponent("\n")</code>, sauf qu'un nouvel appel à
* nextComponent() est nécessaire après.
*/ */
public Display nextLine() { public Display nextLine() {
finalizeCurrentComponent(); finalizeCurrentComponent();
first.addExtra(new TextComponent("\n")); first.addExtra(new TextComponent("\n"));
return this; return this;
} }
public Display setColor(ChatColor color) { public Display setColor(ChatColor color) {
current.setColor(color); current.setColor(color);
return this; return this;
} }
public Display setBold(boolean b) { public Display setBold(boolean b) {
current.setBold(b); current.setBold(b);
return this; return this;
} }
public Display setItalic(boolean i) { public Display setItalic(boolean i) {
current.setItalic(i); current.setItalic(i);
return this; return this;
} }
public Display setUnderlined(boolean u) { public Display setUnderlined(boolean u) {
current.setUnderlined(u); current.setUnderlined(u);
return this; return this;
} }
public Display setObfuscated(boolean o) { public Display setObfuscated(boolean o) {
current.setObfuscated(o); current.setObfuscated(o);
return this; return this;
} }
public Display setStrikethrough(boolean s) { public Display setStrikethrough(boolean s) {
current.setStrikethrough(s); current.setStrikethrough(s);
return this; return this;
} }
public Display setHoverText(Display content) { 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; return this;
} }
public Display setClickURL(String url) { public Display setClickURL(String url) {
current.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, url)); current.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, url));
return this; return this;
} }
public Display setClickCommand(String cmd) { public Display setClickCommand(String cmd) {
current.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, cmd)); current.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, cmd));
return this; return this;
} }
public Display setClickSuggest(String cmd) { public Display setClickSuggest(String cmd) {
current.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, cmd)); current.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, cmd));
return this; return this;
} }
private void finalizeCurrentComponent() { private void finalizeCurrentComponent() {
if (current != null) if (current != null) first.addExtra(current);
first.addExtra(current);
current = null; current = null;
} }
public BaseComponent get() { public BaseComponent get() {
finalizeCurrentComponent(); finalizeCurrentComponent();
return first; return first;

View File

@ -7,217 +7,195 @@ import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.BaseComponent;
public class DisplayUtil { public class DisplayUtil {
@SuppressWarnings("serial") private static Map<Integer, String> charList = new HashMap<Integer, String>() {
private static Map<Integer, String> charList = new HashMap<Integer, String>(){{ private static final long serialVersionUID = 1L;
put(-6, "§");
put(2, "!.,:;i|¡"); {
put(3, "'`lìí"); put(-6, "§");
put(4, " I[]tï×"); put(2, "!.,:;i|¡");
put(5, "\"()*<>fk{}"); put(3, "'`lìí");
put(7, "@~®"); put(4, " I[]tï×");
}}; put(5, "\"()*<>fk{}");
put(7, "@~®");
}
};
private static final int defaultChatMaxWidth = 320; private static final int defaultChatMaxWidth = 320;
private static int chatMaxWidth = defaultChatMaxWidth; private static int chatMaxWidth = defaultChatMaxWidth;
private static final int defaultNbCharPerLineForConsole = 50; private static final int defaultNbCharPerLineForConsole = 50;
private static int nbCharPerLineForConsole = defaultNbCharPerLineForConsole; private static int nbCharPerLineForConsole = defaultNbCharPerLineForConsole;
public static final ChatColor COLOR_TITLE = ChatColor.GOLD; public static final ChatColor COLOR_TITLE = ChatColor.GOLD;
public static final ChatColor COLOR_LINK = ChatColor.GREEN; public static final ChatColor COLOR_LINK = ChatColor.GREEN;
public static final ChatColor COLOR_COMMAND = ChatColor.GRAY; public static final ChatColor COLOR_COMMAND = ChatColor.GRAY;
public static BaseComponent createURLLink(String textLink, String url, String hoverText) { public static BaseComponent createURLLink(String textLink, String url, String hoverText) {
String dispURL = (url.length() > 50) ? (url.substring(0, 48)+"...") : url; String dispURL = (url.length() > 50) ? (url.substring(0, 48) + "...") : url;
return new Display() return new Display().nextComponent(textLink).setClickURL(url)
.nextComponent(textLink) .setHoverText(new Display(
.setClickURL(url) ChatColor.GRAY + ((hoverText == null) ? "Cliquez pour accéder au site :" : hoverText) + "\n"
.setHoverText(new Display(ChatColor.GRAY+((hoverText == null)?"Cliquez pour accéder au site :":hoverText)+"\n"+ChatColor.GRAY+dispURL)) + ChatColor.GRAY + dispURL))
.setColor(COLOR_LINK) .setColor(COLOR_LINK).get();
.get();
} }
public static BaseComponent createCommandLink(String textLink, String commandWithSlash, String hoverText) { public static BaseComponent createCommandLink(String textLink, String commandWithSlash, String hoverText) {
Display d = new Display() Display d = new Display().nextComponent(textLink).setClickCommand(commandWithSlash).setColor(COLOR_COMMAND);
.nextComponent(textLink) if (hoverText != null) d.setHoverText(new Display(hoverText));
.setClickCommand(commandWithSlash)
.setColor(COLOR_COMMAND);
if (hoverText != null)
d.setHoverText(new Display(hoverText));
return d.get(); return d.get();
} }
public static BaseComponent createCommandSuggest(String textLink, String commandWithSlash, String hoverText) { public static BaseComponent createCommandSuggest(String textLink, String commandWithSlash, String hoverText) {
Display d = new Display() Display d = new Display().nextComponent(textLink).setClickSuggest(commandWithSlash).setColor(COLOR_COMMAND);
.nextComponent(textLink) if (hoverText != null) d.setHoverText(new Display(hoverText));
.setClickSuggest(commandWithSlash)
.setColor(COLOR_COMMAND);
if (hoverText != null)
d.setHoverText(new Display(hoverText));
return d.get(); return d.get();
} }
public static BaseComponent centerText(BaseComponent text, char repeatedChar, ChatColor decorationColor,
public static BaseComponent centerText(BaseComponent text, char repeatedChar, ChatColor decorationColor, boolean console) { boolean console) {
int textWidth = strWidth(text.toPlainText(), 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(); String current = text.toPlainText();
int count = 0; int count = 0;
do { do {
count++; count++;
current = repeatedChar + current + repeatedChar; current = repeatedChar + current + repeatedChar;
} while (strWidth(current, console) <= ((console)?nbCharPerLineForConsole:chatMaxWidth)); } while (strWidth(current, console) <= ((console) ? nbCharPerLineForConsole : chatMaxWidth));
count--; count--;
String finalLeftOrRight = "";
for (int i=0; i<count; i++)
finalLeftOrRight += repeatedChar;
Display d = new Display().nextComponent(finalLeftOrRight).setColor(decorationColor)
.addComponent(text);
if (repeatedChar != ' ') {
d.nextComponent(finalLeftOrRight).setColor(decorationColor);
}
return d.get();
}
public static BaseComponent leftText(BaseComponent text, char repeatedChar, ChatColor decorationColor, int nbLeft, boolean console) { String finalLeftOrRight = "";
for (int i = 0; i < count; i++)
finalLeftOrRight += repeatedChar;
Display d = new Display().nextComponent(finalLeftOrRight).setColor(decorationColor).addComponent(text);
if (repeatedChar != ' ') d.nextComponent(finalLeftOrRight).setColor(decorationColor);
return d.get();
}
public static BaseComponent leftText(BaseComponent text, char repeatedChar, ChatColor decorationColor, int nbLeft,
boolean console) {
int textWidth = strWidth(text.toPlainText(), console); int textWidth = strWidth(text.toPlainText(), console);
if (textWidth > ((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(); Display d = new Display();
String finalLeft = ""; String finalLeft = "";
if (nbLeft > 0) { if (nbLeft > 0) {
for (int i=0; i<nbLeft; i++) for (int i = 0; i < nbLeft; i++)
finalLeft += repeatedChar; finalLeft += repeatedChar;
d.nextComponent(finalLeft).setColor(decorationColor); d.nextComponent(finalLeft).setColor(decorationColor);
} }
d.addComponent(text); d.addComponent(text);
int count = 0; int count = 0;
String current = finalLeft+text.toPlainText(); String current = finalLeft + text.toPlainText();
do { do {
count++; count++;
current += repeatedChar; current += repeatedChar;
} while (strWidth(current, console) <= ((console)?nbCharPerLineForConsole:chatMaxWidth)); } while (strWidth(current, console) <= ((console) ? nbCharPerLineForConsole : chatMaxWidth));
count--; count--;
if (repeatedChar != ' ') { if (repeatedChar != ' ') {
String finalRight = ""; String finalRight = "";
for (int i=0; i<count; i++) for (int i = 0; i < count; i++)
finalRight += repeatedChar; finalRight += repeatedChar;
d.nextComponent(finalRight).setColor(decorationColor); d.nextComponent(finalRight).setColor(decorationColor);
} }
return d.get(); return d.get();
} }
public static BaseComponent rightText(BaseComponent text, char repeatedChar, ChatColor decorationColor, int nbRight, boolean console) {
public static BaseComponent rightText(BaseComponent text, char repeatedChar, ChatColor decorationColor, int nbRight,
boolean console) {
int textWidth = strWidth(text.toPlainText(), console); int textWidth = strWidth(text.toPlainText(), console);
if (textWidth > ((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(); String tempText = text.toPlainText();
if (nbRight > 0) { if (nbRight > 0) {
tempText += decorationColor; tempText += decorationColor;
for (int i=0; i<nbRight; i++) for (int i = 0; i < nbRight; i++)
tempText += repeatedChar; tempText += repeatedChar;
} }
int count = 0; int count = 0;
String current = tempText; String current = tempText;
do { do {
count++; count++;
current = repeatedChar + current; current = repeatedChar + current;
} while (strWidth(current, console) <= ((console)?nbCharPerLineForConsole:chatMaxWidth)); } while (strWidth(current, console) <= ((console) ? nbCharPerLineForConsole : chatMaxWidth));
count--; count--;
String finalLeft = ""; String finalLeft = "";
for (int i=0; i<count; i++) for (int i = 0; i < count; i++)
finalLeft += repeatedChar; finalLeft += repeatedChar;
Display d = new Display().nextComponent(finalLeft).setColor(decorationColor) Display d = new Display().nextComponent(finalLeft).setColor(decorationColor).addComponent(text);
.addComponent(text);
if (repeatedChar != ' ') { if (repeatedChar != ' ') {
String finalRight = ""; String finalRight = "";
for (int i=0; i<nbRight; i++) for (int i = 0; i < nbRight; i++)
finalRight += repeatedChar; finalRight += repeatedChar;
d.nextComponent(finalRight).setColor(decorationColor); d.nextComponent(finalRight).setColor(decorationColor);
} }
return d.get(); return d.get();
} }
public static BaseComponent emptyLine(char repeatedChar, ChatColor decorationColor, boolean console) { public static BaseComponent emptyLine(char repeatedChar, ChatColor decorationColor, boolean console) {
int count = ((console)?nbCharPerLineForConsole:chatMaxWidth)/charW(repeatedChar, console); int count = ((console) ? nbCharPerLineForConsole : chatMaxWidth) / charW(repeatedChar, console);
String finalLine = ""; String finalLine = "";
for (int i=0;i<count;i++) for (int i = 0; i < count; i++)
finalLine += repeatedChar; finalLine += repeatedChar;
return new Display().nextComponent(finalLine).setColor(decorationColor).get(); return new Display().nextComponent(finalLine).setColor(decorationColor).get();
} }
public static int strWidth(String str, boolean console) { public static int strWidth(String str, boolean console) {
int count = 0; int count = 0;
for (char c : str.toCharArray()) for (char c : str.toCharArray())
count += charW(c, console); count += charW(c, console);
return (count < 0) ? 0 : count; return (count < 0) ? 0 : count;
} }
private static int charW(char c, boolean console) { private static int charW(char c, boolean console) {
if (console) return (c == '§') ? -1 : 1; if (console) return (c == '§') ? -1 : 1;
for (int px: charList.keySet()) for (int px : charList.keySet())
if (charList.get(px).indexOf(c) >= 0) if (charList.get(px).indexOf(c) >= 0) return px;
return px;
return 6; return 6;
} }
public static void setNbCharPerLineForConsole(int nb) { public static void setNbCharPerLineForConsole(int nb) {
if (nb < 0) nb = 0; if (nb < 0) nb = 0;
nbCharPerLineForConsole = nb; nbCharPerLineForConsole = nb;
} }
public static void resetNbCharPerLineForConsole() { public static void resetNbCharPerLineForConsole() {
nbCharPerLineForConsole = defaultNbCharPerLineForConsole; nbCharPerLineForConsole = defaultNbCharPerLineForConsole;
} }
public static void setChatMaxWidth(int px) { public static void setChatMaxWidth(int px) {
if (px < 0) px = 0; if (px < 0) px = 0;
chatMaxWidth = px; chatMaxWidth = px;
} }
public static void resetChatMaxWidth() { public static void resetChatMaxWidth() {
chatMaxWidth = defaultChatMaxWidth; chatMaxWidth = defaultChatMaxWidth;
} }
} }

View File

@ -10,61 +10,54 @@ public class TextProgressBar {
private static ChatColor color_default = ChatColor.RESET; private static ChatColor color_default = ChatColor.RESET;
private static String pattern_empty = "."; private static String pattern_empty = ".";
private static String pattern_full = "|"; 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]; long[] sizes = new long[values.length];
int max_size = nbCar - pattern_start.length() - pattern_end.length(); int max_size = nbCar - pattern_start.length() - pattern_end.length();
for (int i=0; i<values.length; i++) for (int i = 0; i < values.length; i++) {
{
double sum_values_before = 0; double sum_values_before = 0;
for (int j = i ; j>=0; j--) for (int j = i; j >= 0; j--)
sum_values_before += values[j]; sum_values_before += values[j];
long car_position = Math.round(max_size * sum_values_before / total); 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; if (car_position > max_size) car_position = max_size;
long sum_sizes_before = 0; 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]; sum_sizes_before += sizes[j];
sizes[i] = car_position - sum_sizes_before; sizes[i] = car_position - sum_sizes_before;
} }
int sum_sizes = 0; int sum_sizes = 0;
String bar = color_decoration + pattern_start;
String bar = color_decoration+pattern_start; for (int i = 0; i < sizes.length; i++) {
for (int i=0; i<sizes.length; i++)
{
sum_sizes += sizes[i]; sum_sizes += sizes[i];
ChatColor color = color_default; ChatColor color = color_default;
if (colors != null && i < colors.length && colors[i] != null) if (colors != null && i < colors.length && colors[i] != null) color = colors[i];
color = colors[i];
bar = bar + color; bar = bar + color;
for (int j=0; j<sizes[i]; j++) for (int j = 0; j < sizes[i]; j++)
bar = bar + pattern_full; bar = bar + pattern_full;
} }
bar = bar + color_empty; bar = bar + color_empty;
for (int j=0; j<(max_size-sum_sizes); j++) for (int j = 0; j < (max_size - sum_sizes); j++)
bar = bar + pattern_empty; bar = bar + pattern_empty;
bar = bar + color_decoration + pattern_end; bar = bar + color_decoration + pattern_end;
return bar; return bar;
} }
public static String progressBar(double value, ChatColor color, double max, int nbCar) {
public static String progressBar(double value, ChatColor color, double max, int nbCar) return progressBar(new double[] { value }, new ChatColor[] { color }, max, nbCar);
{
return progressBar(new double[] {value}, new ChatColor[] {color}, max, nbCar);
} }
} }

View File

@ -1,145 +0,0 @@
package fr.pandacube.java.util.db;
import java.net.InetAddress;
import java.util.UUID;
public class LoginHistoryElement extends SQLElement {
private long time;
private String playerId;
private String ip = null;
private ActionType actionType;
private int nbOnline;
private String playerName;
private int minecraftVersion = 0;
public LoginHistoryElement(long t, UUID pId, ActionType action, int nbO) {
super("pandacube_login_history");
setTime(t);
setPlayerId(pId);
setActionType(action);
setNbOnline(nbO);
}
LoginHistoryElement(int id, long t, String pId, String ip, ActionType action, int nbO) {
super("pandacube_login_history", id);
if (pId == null)
throw new IllegalArgumentException("pId ne peuvent être null");
setTime(t);
playerId = pId;
this.ip = ip;
setActionType(action);
setNbOnline(nbO);
}
@Override
protected String[] getValues() {
return new String[] {
Long.toString(time),
playerId,
ip,
actionType.toString(),
Integer.toString(nbOnline),
playerName,
Integer.toString(minecraftVersion)
};
}
@Override
protected String[] getFieldsName() {
return new String[] {
"time",
"playerId",
"ip",
"actionType",
"nbOnline",
"playerName",
"minecraftVersion"
};
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public UUID getPlayerId() {
return UUID.fromString(playerId);
}
public void setPlayerId(UUID pId) {
if (pId == null)
throw new IllegalArgumentException("pId ne peut être null");
playerId = pId.toString();
}
public String getIp() {
return ip;
}
public void setIp(InetAddress addr) {
if (addr == null)
ip = null;
else
ip = addr.getHostAddress();
}
public ActionType getActionType() {
return actionType;
}
public void setActionType(ActionType actionT) {
if (actionT == null)
throw new IllegalArgumentException("actionT ne peut être null");
actionType = actionT;
}
public int getNbOnline() {
return nbOnline;
}
public void setNbOnline(int nbOnline) {
this.nbOnline = nbOnline;
}
public String getPlayerName() {
return playerName;
}
public void setPlayerName(String pn) {
playerName = pn;
}
public int getMinecraftVersion() {
return minecraftVersion;
}
public void setMinecraftVersion(int m) {
minecraftVersion = m;
}
public enum ActionType {
LOGIN, LOGOUT
}
}

View File

@ -1,40 +0,0 @@
package fr.pandacube.java.util.db;
import java.sql.ResultSet;
import java.sql.SQLException;
import fr.pandacube.java.util.db.LoginHistoryElement.ActionType;
public class LoginHistoryTable extends SQLTable<LoginHistoryElement> {
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;
}
}

View File

@ -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<MPGroupUserElement> getUsers() throws SQLException {
return ORM.getTable(MPGroupUserTable.class)
.getAll("groupId = "+getId(), "id ASC", null, null);
}
}

View File

@ -1,26 +0,0 @@
package fr.pandacube.java.util.db;
import java.sql.ResultSet;
import java.sql.SQLException;
public class MPGroupTable extends SQLTable<MPGroupElement> {
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"));
}
}

View File

@ -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");
}
}

View File

@ -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<MPGroupUserElement> {
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");
}
}

View File

@ -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<br/>
* <br/>
* Les propriétés suivantes doivent être complétés hors constructeur (par défaut <code>null</code>) :
* <ul>
* <li><code>destNick</code></li>
* <li>ou <code>destGroup</code></li>
* </ul>
* La propriété <code>deleted</code> 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 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());
}
}

View File

@ -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<MPMessageElement> {
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<MPMessageElement> getAllUnsyncMessage() throws SQLException {
return getAll("serverSync = 0", "time ASC", null, null);
}
public List<MPMessageElement> getAllUnreadForPlayer(UUID player) throws SQLException {
return getForPlayer(player, true, null, false);
}
public List<MPMessageElement> 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<MPMessageElement> 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);
}
}

View File

@ -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
}
}

View File

@ -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<ModoHistoryElement> {
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;
}
}

View File

@ -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;
/**
* <b>ORM = Object-Relational Mapping</b><br/>
* Liste des tables avec leur classes :
* <ul>
* <li><code>LoginHistoryTable</code></li>
* <li><code>ModoHistoryTable</code></li>
* <li><code>StaffTicketTable</code></li>
* <li><code>MPMessageTable</code></li>
* <li><code>MPGroupTable</code></li>
* <li><code>MPGroupUserTable</code></li>
* <li><code>MPWebSessionTable</code></li>
* <li><code>PlayerIgnoreTable</code></li>
* </ul>
* @author Marc Baloup
*
*/
public final class ORM {
private static List<SQLTable<?>> tables = new ArrayList<SQLTable<?>>();
/* 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 extends SQLTable<?>> T getTable(Class<T> 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
}

View File

@ -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
}
}

View File

@ -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<OnlineShopHistoryElement> {
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;
}
}

View File

@ -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;
}
}

View File

@ -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();
}
}

View File

@ -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<PlayerIgnoreElement> {
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<UUID> getListIgnoredPlayer(UUID ignore) throws SQLException {
if (ignore == null)
throw new IllegalArgumentException("ignore can't be null");
List<PlayerIgnoreElement> dbIgnored = getAll("ignorer = '"+ignore+"'", "id", null, null);
List<UUID> ret = new ArrayList<UUID>();
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();
}
}
}

View File

@ -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<PlayerElement> {
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;
}
}

View File

@ -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<fields.length && i<values.length; i++)
{
sql += fields[i]+" = ? ,";
}
if (sql.length() > 0)
sql = sql.substring(0, sql.length()-1);
PreparedStatement st = conn.prepareStatement("UPDATE "+tableName+" SET "+sql+" WHERE id="+id);
try {
for (int i=0; i<fields.length && i<values.length; i++)
{
st.setString(i+1, values[i]);
}
st.executeUpdate();
} finally {
st.close();
}
}
else
{ // ajouter dans la base
String concat_vals = "";
String concat_fields = StringUtils.join(fields, ',');
for (int i=0; i<fields.length && i<values.length; i++)
{
if (i!=0) concat_vals += ",";
concat_vals += " ? ";
}
PreparedStatement st = conn.prepareStatement("INSERT INTO "+tableName+" ("+concat_fields+") VALUES ("+concat_vals+")", Statement.RETURN_GENERATED_KEYS);
try {
for (int i=0; i<fields.length && i<values.length; i++)
{
st.setString(i+1, values[i]);
}
st.executeUpdate();
ResultSet rs = st.getGeneratedKeys();
try {
if(rs.next())
{
id = rs.getInt(1);
}
saved = true;
} finally {
rs.close();
}
} finally {
st.close();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void delete() {
try {
if (saved)
{ // supprimer la ligne de la base
PreparedStatement st = db.getNativeConnection().prepareStatement("DELETE FROM "+tableName+" WHERE id="+id);
try {
st.executeUpdate();
saved = false;
} finally {
st.close();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public int getId() {
if (!saved)
throw new IllegalStateException("Ne peut pas fournir l'ID d'un élément non sauvegardé");
return id;
}
/**
* Récupère la liste des valeurs des champs de la table correspondante, excepté
* le champ <code>id</code>
* @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 <code>id</code>
* @return les noms des champs sous la forme de chaine de caractères
*/
protected abstract String[] getFieldsName();
}

View File

@ -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<T extends SQLElement> {
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 : <code>CRATE TABLE tableName ();</code>
* 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<T> getAll() throws SQLException {
return getAll(null, null, null, null);
}
public T getFirst(String where, String orderBy) throws SQLException {
List<T> elts = getAll(where, orderBy, 1, null);
return (elts.size() == 0)? null : elts.get(0);
}
public List<T> 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<T> elmts = new ArrayList<T>();
try {
ResultSet set = stmt.executeQuery(sql);
try {
while (set.next())
elmts.add(getElementInstance(set));
} finally {
set.close();
}
} finally {
stmt.close();
}
return elmts;
}
}

View File

@ -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;
}
}

View File

@ -1,30 +0,0 @@
package fr.pandacube.java.util.db;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ShopStockTable extends SQLTable<ShopStockElement> {
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"));
}
}

View File

@ -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();
}
}

View File

@ -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<StaffTicketElement> {
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;
}
}

View File

@ -1,2 +0,0 @@
@java.lang.Deprecated
package fr.pandacube.java.util.db;

View File

@ -3,42 +3,41 @@ package fr.pandacube.java.util.db2;
import java.util.UUID; import java.util.UUID;
import fr.pandacube.java.util.db2.sql_tools.SQLElement; 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.SQLFKField;
import fr.pandacube.java.util.db2.sql_tools.SQLField;
import fr.pandacube.java.util.db2.sql_tools.SQLType; import fr.pandacube.java.util.db2.sql_tools.SQLType;
public class SQLContact extends SQLElement { public class SQLContact extends SQLElement {
public SQLContact() { super(); } public SQLContact() {
public SQLContact(int id) { super(id); } super();
}
public SQLContact(int id) {
super(id);
}
@Override @Override
protected String tableName() { return "pandacube_contact"; } protected String tableName() {
return "pandacube_contact";
}
public static final SQLField<Integer> time = new SQLField<>("time", SQLType.INT, false);
public static final SQLFKField<String, SQLPlayer> playerId = new SQLFKField<>("playerId", SQLType.CHAR(36), true,
public static final SQLField<Integer> time = new SQLField<>( "time", SQLType.INT, false); SQLPlayer.class, SQLPlayer.playerId);
public static final SQLFKField<String, SQLPlayer> playerId = new SQLFKField<>("playerId", SQLType.CHAR(36), true, SQLPlayer.class, SQLPlayer.playerId); public static final SQLField<String> userName = new SQLField<>("userName", SQLType.VARCHAR(50), true);
public static final SQLField<String> userName = new SQLField<>( "userName", SQLType.VARCHAR(50), true); public static final SQLField<String> userMail = new SQLField<>("userMail", SQLType.VARCHAR(50), true);
public static final SQLField<String> userMail = new SQLField<>( "userMail", SQLType.VARCHAR(50), true); public static final SQLField<String> titre = new SQLField<>("titre", SQLType.VARCHAR(100), false);
public static final SQLField<String> titre = new SQLField<>( "titre", SQLType.VARCHAR(100), false); public static final SQLField<String> texte = new SQLField<>("texte", SQLType.TEXT, false);
public static final SQLField<String> texte = new SQLField<>( "texte", SQLType.TEXT, false); public static final SQLField<Boolean> hidden = new SQLField<>("hidden", SQLType.BOOLEAN, false, (Boolean) false);
public static final SQLField<Boolean> hidden = new SQLField<>( "hidden", SQLType.BOOLEAN, false, (Boolean)false);
public UUID getPlayerId() { public UUID getPlayerId() {
String id = (String)get(playerId); String id = get(playerId);
return (id == null) ? null : UUID.fromString(id); return (id == null) ? null : UUID.fromString(id);
} }
public void setPlayerId(UUID pName) { public void setPlayerId(UUID pName) {
set(playerId, (pName == null) ? (String)null : pName.toString()); set(playerId, (pName == null) ? (String) null : pName.toString());
} }
} }

View File

@ -5,16 +5,21 @@ import fr.pandacube.java.util.db2.sql_tools.SQLField;
import fr.pandacube.java.util.db2.sql_tools.SQLType; import fr.pandacube.java.util.db2.sql_tools.SQLType;
public class SQLForumCategorie extends SQLElement { public class SQLForumCategorie extends SQLElement {
public SQLForumCategorie() { super(); } public SQLForumCategorie() {
public SQLForumCategorie(int id) { super(id); } super();
}
public SQLForumCategorie(int id) {
super(id);
}
@Override @Override
protected String tableName() { return "pandacube_forum_categorie"; } protected String tableName() {
return "pandacube_forum_categorie";
}
public static final SQLField<String> nom = new SQLField<>("nom", SQLType.VARCHAR(100), false);
public static final SQLField<Integer> ordre = new SQLField<>("ordre", SQLType.INT, false); public static final SQLField<String> nom = new SQLField<>("nom", SQLType.VARCHAR(100), false);
public static final SQLField<Integer> ordre = new SQLField<>("ordre", SQLType.INT, false);
} }

View File

@ -7,26 +7,30 @@ import fr.pandacube.java.util.db2.sql_tools.SQLType;
public class SQLForumForum extends SQLElement { public class SQLForumForum extends SQLElement {
public SQLForumForum() {
public SQLForumForum() { super(); } super();
public SQLForumForum(int id) { super(id); } }
public SQLForumForum(int id) {
super(id);
}
@Override @Override
protected String tableName() { return "pandacube_forum_forum"; } protected String tableName() {
return "pandacube_forum_forum";
}
public static final SQLFKField<Integer, SQLForumCategorie> catId = SQLFKField.idFK("catId", SQLType.INT, false, SQLForumCategorie.class);
public static final SQLField<String> nom = new SQLField<>("nom", SQLType.VARCHAR(100), false); public static final SQLFKField<Integer, SQLForumCategorie> catId = SQLFKField.idFK("catId", SQLType.INT, false,
public static final SQLField<String> description = new SQLField<>("description", SQLType.TEXT, false); SQLForumCategorie.class);
public static final SQLField<Integer> ordre = new SQLField<>("ordre", SQLType.INT, false); public static final SQLField<String> nom = new SQLField<>("nom", SQLType.VARCHAR(100), false);
public static final SQLField<Integer> authView = new SQLField<>("authView", SQLType.INT, false); public static final SQLField<String> description = new SQLField<>("description", SQLType.TEXT, false);
public static final SQLField<Integer> authPost = new SQLField<>("authPost", SQLType.INT, false); public static final SQLField<Integer> ordre = new SQLField<>("ordre", SQLType.INT, false);
public static final SQLField<Integer> authThread = new SQLField<>("authThread", SQLType.INT, false); public static final SQLField<Integer> authView = new SQLField<>("authView", SQLType.INT, false);
public static final SQLField<Integer> authAnchored = new SQLField<>("authAnchored", SQLType.INT, false); public static final SQLField<Integer> authPost = new SQLField<>("authPost", SQLType.INT, false);
public static final SQLField<Integer> authModo = new SQLField<>("authModo", SQLType.INT, false); public static final SQLField<Integer> authThread = new SQLField<>("authThread", SQLType.INT, false);
public static final SQLField<Integer> nbThreads = new SQLField<>("nbThreads", SQLType.INT, false); public static final SQLField<Integer> authAnchored = new SQLField<>("authAnchored", SQLType.INT, false);
public static final SQLField<Integer> nbMessages = new SQLField<>("nbMessages", SQLType.INT, false); public static final SQLField<Integer> authModo = new SQLField<>("authModo", SQLType.INT, false);
public static final SQLField<Integer> nbThreads = new SQLField<>("nbThreads", SQLType.INT, false);
public static final SQLField<Integer> nbMessages = new SQLField<>("nbMessages", SQLType.INT, false);
} }

View File

@ -9,31 +9,33 @@ import fr.pandacube.java.util.db2.sql_tools.SQLType;
public class SQLForumPost extends SQLElement { public class SQLForumPost extends SQLElement {
public SQLForumPost() {
public SQLForumPost() { super(); } super();
public SQLForumPost(int id) { super(id); } }
public SQLForumPost(int id) {
super(id);
}
@Override @Override
protected String tableName() { return "pandacube_forum_post"; } protected String tableName() {
return "pandacube_forum_post";
}
public static final SQLField<String> createur = new SQLField<>("createur", SQLType.CHAR(36), false);
public static final SQLField<String> texte = new SQLField<>("texte", SQLType.TEXT, false); public static final SQLField<String> createur = new SQLField<>("createur", SQLType.CHAR(36), false);
public static final SQLField<Integer> time = new SQLField<>("time", SQLType.INT, false); public static final SQLField<String> texte = new SQLField<>("texte", SQLType.TEXT, false);
public static final SQLFKField<Integer, SQLForumThread> threadId = SQLFKField.idFK("threadId", SQLType.INT, false, SQLForumThread.class); public static final SQLField<Integer> time = new SQLField<>("time", SQLType.INT, false);
public static final SQLField<Boolean> moderated = new SQLField<>("moderated", SQLType.BOOLEAN, false); public static final SQLFKField<Integer, SQLForumThread> threadId = SQLFKField.idFK("threadId", SQLType.INT, false,
SQLForumThread.class);
public static final SQLField<Boolean> moderated = new SQLField<>("moderated", SQLType.BOOLEAN, false);
public UUID getCreateurId() { public UUID getCreateurId() {
String id = (String)get(createur); String id = get(createur);
return (id == null) ? null : UUID.fromString(id); return (id == null) ? null : UUID.fromString(id);
} }
public void setCreateurId(UUID pName) { public void setCreateurId(UUID pName) {
set(createur, (pName == null) ? (String)null : pName.toString()); set(createur, (pName == null) ? (String) null : pName.toString());
} }
} }

View File

@ -9,36 +9,37 @@ import fr.pandacube.java.util.db2.sql_tools.SQLType;
public class SQLForumThread extends SQLElement { public class SQLForumThread extends SQLElement {
public SQLForumThread() {
public SQLForumThread() { super(); } super();
public SQLForumThread(int id) { super(id); } }
public SQLForumThread(int id) {
super(id);
}
@Override @Override
protected String tableName() { return "pandacube_forum_thread"; } protected String tableName() {
return "pandacube_forum_thread";
}
public static final SQLFKField<Integer, SQLForumForum> forumId = SQLFKField.idFK("forumId", SQLType.INT, false, SQLForumForum.class);
public static final SQLField<String> titre = new SQLField<>("titre", SQLType.VARCHAR(60), false); public static final SQLFKField<Integer, SQLForumForum> forumId = SQLFKField.idFK("forumId", SQLType.INT, false,
public static final SQLFKField<String, SQLPlayer> createur = new SQLFKField<>("createur", SQLType.CHAR(36), false, SQLPlayer.class, SQLPlayer.playerId); SQLForumForum.class);
public static final SQLField<Integer> vu = new SQLField<>("vu", SQLType.INT, false); public static final SQLField<String> titre = new SQLField<>("titre", SQLType.VARCHAR(60), false);
public static final SQLField<Long> time = new SQLField<>("time", SQLType.BIGINT, false); public static final SQLFKField<String, SQLPlayer> createur = new SQLFKField<>("createur", SQLType.CHAR(36), false,
public static final SQLField<Boolean> anchored = new SQLField<>("anchored", SQLType.BOOLEAN, false); SQLPlayer.class, SQLPlayer.playerId);
public static final SQLField<Boolean> locked = new SQLField<>("locked", SQLType.BOOLEAN, false); public static final SQLField<Integer> vu = new SQLField<>("vu", SQLType.INT, false);
public static final SQLField<Integer> nbMessages = new SQLField<>("nbMessages", SQLType.INT, false); public static final SQLField<Long> time = new SQLField<>("time", SQLType.BIGINT, false);
public static final SQLField<Boolean> anchored = new SQLField<>("anchored", SQLType.BOOLEAN, false);
public static final SQLField<Boolean> locked = new SQLField<>("locked", SQLType.BOOLEAN, false);
public static final SQLField<Integer> nbMessages = new SQLField<>("nbMessages", SQLType.INT, false);
public UUID getCreateurId() { public UUID getCreateurId() {
String id = (String)get(createur); String id = get(createur);
return (id == null) ? null : UUID.fromString(id); return (id == null) ? null : UUID.fromString(id);
} }
public void setCreateurId(UUID pName) { public void setCreateurId(UUID pName) {
set(createur, (pName == null) ? (String)null : pName.toString()); set(createur, (pName == null) ? (String) null : pName.toString());
} }
} }

View File

@ -9,40 +9,38 @@ import fr.pandacube.java.util.db2.sql_tools.SQLType;
public class SQLLoginHistory extends SQLElement { public class SQLLoginHistory extends SQLElement {
public SQLLoginHistory() {
public SQLLoginHistory() { super(); } super();
public SQLLoginHistory(int id) { super(id); } }
public SQLLoginHistory(int id) {
super(id);
}
@Override @Override
protected String tableName() { return "pandacube_login_history"; } protected String tableName() {
return "pandacube_login_history";
}
public static final SQLField<Long> time = new SQLField<>("time", SQLType.BIGINT, false);
public static final SQLFKField<String, SQLPlayer> playerId = new SQLFKField<>("playerId", SQLType.CHAR(36), false, SQLPlayer.class, SQLPlayer.playerId); public static final SQLField<Long> time = new SQLField<>("time", SQLType.BIGINT, false);
public static final SQLField<String> ip = new SQLField<>("ip", SQLType.VARCHAR(128), true); public static final SQLFKField<String, SQLPlayer> playerId = new SQLFKField<>("playerId", SQLType.CHAR(36), false,
public static final SQLField<ActionType> actionType = new SQLField<>("actionType", SQLType.ENUM(ActionType.class), false); SQLPlayer.class, SQLPlayer.playerId);
public static final SQLField<Integer> nbOnline = new SQLField<>("nbOnline", SQLType.INT, false); public static final SQLField<String> ip = new SQLField<>("ip", SQLType.VARCHAR(128), true);
public static final SQLField<String> playerName = new SQLField<>("playerName", SQLType.VARCHAR(16), true); public static final SQLField<ActionType> actionType = new SQLField<>("actionType", SQLType.ENUM(ActionType.class),
public static final SQLField<Integer> minecraftVersion = new SQLField<>("minecraftVersion", SQLType.INT, false, 0); false);
public static final SQLField<Integer> nbOnline = new SQLField<>("nbOnline", SQLType.INT, false);
public static final SQLField<String> playerName = new SQLField<>("playerName", SQLType.VARCHAR(16), true);
public static final SQLField<Integer> minecraftVersion = new SQLField<>("minecraftVersion", SQLType.INT, false, 0);
public UUID getPlayerId() { public UUID getPlayerId() {
String id = (String)get(playerId); String id = get(playerId);
return (id == null) ? null : UUID.fromString(id); return (id == null) ? null : UUID.fromString(id);
} }
public void setPlayerId(UUID pName) { 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 {
LOGIN, LOGOUT LOGIN, LOGOUT
} }

View File

@ -12,34 +12,30 @@ import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp.SQLComparator;
public class SQLMPGroup extends SQLElement { public class SQLMPGroup extends SQLElement {
public SQLMPGroup() {
public SQLMPGroup() { super(); } super();
public SQLMPGroup(int id) { super(id); } }
public SQLMPGroup(int id) {
super(id);
}
@Override @Override
protected String tableName() { return "pandacube_mp_group"; } protected String tableName() {
return "pandacube_mp_group";
}
public static final SQLField<String> groupName = new SQLField<>("groupName", SQLType.VARCHAR(16), false); public static final SQLField<String> groupName = new SQLField<>("groupName", SQLType.VARCHAR(16), false);
public SQLElementList<SQLMPGroupUser> getGroupUsers() throws ORMException { public SQLElementList<SQLMPGroupUser> getGroupUsers() throws ORMException {
return ORM.getAll(SQLMPGroupUser.class, return ORM.getAll(SQLMPGroupUser.class, new SQLWhereComp(SQLMPGroupUser.groupId, SQLComparator.EQ, getId()),
new SQLWhereComp(SQLMPGroupUser.groupId, SQLComparator.EQ, getId()),
new SQLOrderBy().addField(ORM.getSQLIdField(SQLMPGroupUser.class)), null, null); new SQLOrderBy().addField(ORM.getSQLIdField(SQLMPGroupUser.class)), null, null);
} }
public static SQLMPGroup getByName(String name) throws ORMException { public static SQLMPGroup getByName(String name) throws ORMException {
if (name == null) if (name == null) return null;
return null;
return ORM.getFirst(SQLMPGroup.class, new SQLWhereComp(groupName, SQLComparator.EQ, name), null); return ORM.getFirst(SQLMPGroup.class, new SQLWhereComp(groupName, SQLComparator.EQ, name), null);
} }
} }

View File

@ -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.SQLFKField;
import fr.pandacube.java.util.db2.sql_tools.SQLType; 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.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.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.SQLWhereComp.SQLComparator;
public class SQLMPGroupUser extends SQLElement { public class SQLMPGroupUser extends SQLElement {
public SQLMPGroupUser() {
public SQLMPGroupUser() { super(); } super();
public SQLMPGroupUser(int id) { super(id); } }
public SQLMPGroupUser(int id) {
super(id);
}
@Override @Override
protected String tableName() { return "pandacube_mp_group_user"; } protected String tableName() {
return "pandacube_mp_group_user";
}
public static final SQLFKField<Integer, SQLMPGroup> groupId = SQLFKField.idFK( "groupId", SQLType.INT, false, SQLMPGroup.class);
public static final SQLFKField<String, SQLPlayer> playerId = new SQLFKField<>("playerId", SQLType.CHAR(36), false, SQLPlayer.class, SQLPlayer.playerId); public static final SQLFKField<Integer, SQLMPGroup> groupId = SQLFKField.idFK("groupId", SQLType.INT, false,
SQLMPGroup.class);
public static final SQLFKField<String, SQLPlayer> 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 // TODO ajouter un champ qui dit si le joueur est admin du groupe
public UUID getPlayerId() { public UUID getPlayerId() {
String id = get(playerId); String id = get(playerId);
return (id == null) ? null : UUID.fromString(id); return (id == null) ? null : UUID.fromString(id);
} }
public void setPlayerId(UUID id) { public void setPlayerId(UUID id) {
set(playerId, (id == null) ? null : id.toString()); 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 group le groupe concerné, sous forme d'instance de SQLMPGroup
* @param player l'identifiant du joueur * @param player l'identifiant du joueur
* @return null si la correspondance n'a pas été trouvée * @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 { public static SQLMPGroupUser getPlayerInGroup(SQLMPGroup group, UUID player) throws Exception {
if (player == null || group == null) return null; if (player == null || group == null) return null;
return ORM.getFirst(SQLMPGroupUser.class, return ORM.getFirst(SQLMPGroupUser.class,
new SQLWhereChain(SQLBoolOp.AND) new SQLWhereChain(SQLBoolOp.AND).add(new SQLWhereComp(groupId, SQLComparator.EQ, group.getId()))
.add(new SQLWhereComp(groupId, SQLComparator.EQ, group.getId())) .add(new SQLWhereComp(playerId, SQLComparator.EQ, player.toString())),
.add(new SQLWhereComp(playerId, SQLComparator.EQ, player.toString())), null); null);
} }
} }

View File

@ -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.SQLFKField;
import fr.pandacube.java.util.db2.sql_tools.SQLField; 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;
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.SQLType;
import fr.pandacube.java.util.db2.sql_tools.SQLWhereChain; 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.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.SQLWhereComp.SQLComparator;
import fr.pandacube.java.util.db2.sql_tools.SQLWhereLike;
import fr.pandacube.java.util.db2.sql_tools.SQLWhereNull; import fr.pandacube.java.util.db2.sql_tools.SQLWhereNull;
public class SQLMPMessage extends SQLElement { public class SQLMPMessage extends SQLElement {
public SQLMPMessage() {
public SQLMPMessage() { super(); } super();
public SQLMPMessage(int id) { super(id); } }
public SQLMPMessage(int id) {
super(id);
}
@Override @Override
protected String tableName() { return "pandacube_mp_message"; } protected String tableName() {
return "pandacube_mp_message";
}
public static final SQLField<Long> time = new SQLField<>("time", SQLType.BIGINT, false);
public static final SQLField<Integer> securityKey = new SQLField<>("securityKey", SQLType.INT, false);
public static final SQLFKField<String, SQLPlayer> viewerId = new SQLFKField<>("viewerId", SQLType.CHAR(36), false, SQLPlayer.class, SQLPlayer.playerId);
public static final SQLFKField<String, SQLPlayer> sourceId = new SQLFKField<>("sourceId", SQLType.CHAR(36), true, SQLPlayer.class, SQLPlayer.playerId);
public static final SQLFKField<String, SQLPlayer> destId = new SQLFKField<>("destId", SQLType.CHAR(36), true, SQLPlayer.class, SQLPlayer.playerId);
public static final SQLFKField<Integer, SQLMPGroup> destGroup = SQLFKField.idFK("destGroup", SQLType.INT, true, SQLMPGroup.class);
public static final SQLField<String> message = new SQLField<>("message", SQLType.VARCHAR(512), false);
public static final SQLField<Boolean> wasRead = new SQLField<>("wasRead", SQLType.BOOLEAN, false);
public static final SQLField<Boolean> deleted = new SQLField<>("deleted", SQLType.BOOLEAN, false, (Boolean) false);
public static final SQLField<Boolean> serverSync = new SQLField<>("serverSync", SQLType.BOOLEAN, false);
public static final SQLField<Long> time = new SQLField<>("time", SQLType.BIGINT, false);
public static final SQLField<Integer> securityKey = new SQLField<>("securityKey", SQLType.INT, false);
public static final SQLFKField<String, SQLPlayer> viewerId = new SQLFKField<>("viewerId", SQLType.CHAR(36), false,
SQLPlayer.class, SQLPlayer.playerId);
public static final SQLFKField<String, SQLPlayer> sourceId = new SQLFKField<>("sourceId", SQLType.CHAR(36), true,
SQLPlayer.class, SQLPlayer.playerId);
public static final SQLFKField<String, SQLPlayer> destId = new SQLFKField<>("destId", SQLType.CHAR(36), true,
SQLPlayer.class, SQLPlayer.playerId);
public static final SQLFKField<Integer, SQLMPGroup> destGroup = SQLFKField.idFK("destGroup", SQLType.INT, true,
SQLMPGroup.class);
public static final SQLField<String> message = new SQLField<>("message", SQLType.VARCHAR(512), false);
public static final SQLField<Boolean> wasRead = new SQLField<>("wasRead", SQLType.BOOLEAN, false);
public static final SQLField<Boolean> deleted = new SQLField<>("deleted", SQLType.BOOLEAN, false, (Boolean) false);
public static final SQLField<Boolean> serverSync = new SQLField<>("serverSync", SQLType.BOOLEAN, false);
public UUID getViewerId() { public UUID getViewerId() {
String id = get(viewerId); String id = get(viewerId);
return (id == null) ? null : UUID.fromString(id); return (id == null) ? null : UUID.fromString(id);
} }
public void setViewerId(UUID id) { public void setViewerId(UUID id) {
set(viewerId, (id == null) ? null : id.toString()); set(viewerId, (id == null) ? null : id.toString());
} }
public UUID getSourceId() { public UUID getSourceId() {
String id = get(sourceId); String id = get(sourceId);
return (id == null) ? null : UUID.fromString(id); return (id == null) ? null : UUID.fromString(id);
} }
public void setSourceId(UUID id) { public void setSourceId(UUID id) {
set(sourceId, (id == null) ? null : id.toString()); set(sourceId, (id == null) ? null : id.toString());
} }
public UUID getDestId() { public UUID getDestId() {
String id = get(destId); String id = get(destId);
return (id == null) ? null : UUID.fromString(id); return (id == null) ? null : UUID.fromString(id);
} }
public void setDestId(UUID id) { public void setDestId(UUID id) {
set(destId, (id == null) ? null : id.toString()); set(destId, (id == null) ? null : id.toString());
} }
public static SQLElementList<SQLMPMessage> getAllUnsyncMessage() throws ORMException { public static SQLElementList<SQLMPMessage> getAllUnsyncMessage() throws ORMException {
return ORM.getAll(SQLMPMessage.class, return ORM.getAll(SQLMPMessage.class, new SQLWhereComp(SQLMPMessage.serverSync, SQLComparator.EQ, false),
new SQLWhereComp(SQLMPMessage.serverSync, SQLComparator.EQ, false), new SQLOrderBy().addField(SQLMPMessage.time), null, null);
new SQLOrderBy().addField(SQLMPMessage.time),
null, null);
} }
public static SQLElementList<SQLMPMessage> getAllUnreadForPlayer(UUID player) throws ORMException { public static SQLElementList<SQLMPMessage> getAllUnreadForPlayer(UUID player) throws ORMException {
return getForPlayer(player, true, null, false); return getForPlayer(player, true, null, false);
} }
public static SQLElementList<SQLMPMessage> getOneDiscussionForPlayer(UUID player, Object discussion,
public static SQLElementList<SQLMPMessage> getOneDiscussionForPlayer(UUID player, Object discussion, Integer numberLast, boolean revert) throws ORMException { Integer numberLast, boolean revert) throws ORMException {
if (player == null) return null; if (player == null) return null;
if (discussion != null && !(discussion instanceof String) && !(discussion instanceof UUID)) 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) SQLWhereChain where = new SQLWhereChain(SQLBoolOp.AND)
.add(new SQLWhereComp(SQLMPMessage.viewerId, SQLComparator.EQ, player.toString())); .add(new SQLWhereComp(SQLMPMessage.viewerId, SQLComparator.EQ, player.toString()));
if (discussion == null) // message de système if (discussion == null) // message de système
@ -103,42 +100,38 @@ public class SQLMPMessage extends SQLElement {
.add(new SQLWhereNull(SQLMPMessage.destGroup, true)); .add(new SQLWhereNull(SQLMPMessage.destGroup, true));
else if (discussion instanceof String) { // message de groupe else if (discussion instanceof String) { // message de groupe
SQLMPGroup groupEl = ORM.getFirst(SQLMPGroup.class, SQLMPGroup groupEl = ORM.getFirst(SQLMPGroup.class,
new SQLWhereComp(SQLMPGroup.groupName, SQLComparator.EQ, (String)discussion), null); new SQLWhereComp(SQLMPGroup.groupName, SQLComparator.EQ, (String) discussion), null);
if (groupEl == null) if (groupEl == null) return null;
return null;
where.add(new SQLWhereComp(SQLMPMessage.destGroup, SQLComparator.EQ, groupEl.getId())); 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())) where.add(new SQLWhereLike(SQLMPMessage.destId, discussion.toString()))
.add(new SQLWhereLike(SQLMPMessage.sourceId, discussion.toString())) .add(new SQLWhereLike(SQLMPMessage.sourceId, discussion.toString()))
.add(new SQLWhereNull(SQLMPMessage.destGroup, true)); .add(new SQLWhereNull(SQLMPMessage.destGroup, true));
else // discussion instanceof UUID else // discussion instanceof UUID
where.add(new SQLWhereChain(SQLBoolOp.OR) where.add(new SQLWhereChain(SQLBoolOp.OR).add(new SQLWhereLike(SQLMPMessage.destId, discussion.toString()))
.add(new SQLWhereLike(SQLMPMessage.destId, discussion.toString())) .add(new SQLWhereLike(SQLMPMessage.sourceId, discussion.toString())))
.add(new SQLWhereLike(SQLMPMessage.sourceId, discussion.toString())))
.add(new SQLWhereNull(SQLMPMessage.destGroup, true)); .add(new SQLWhereNull(SQLMPMessage.destGroup, true));
SQLOrderBy orderBy = new SQLOrderBy().addField(SQLMPMessage.time, revert ? Direction.DESC : Direction.ASC); SQLOrderBy orderBy = new SQLOrderBy().addField(SQLMPMessage.time, revert ? Direction.DESC : Direction.ASC);
return ORM.getAll(SQLMPMessage.class, where, orderBy, numberLast, null); return ORM.getAll(SQLMPMessage.class, where, orderBy, numberLast, null);
} }
public static SQLElementList<SQLMPMessage> getForPlayer(UUID player, boolean onlyUnread, Integer numberLast,
public static SQLElementList<SQLMPMessage> getForPlayer(UUID player, boolean onlyUnread, Integer numberLast, boolean revert) throws ORMException { boolean revert) throws ORMException {
if (player == null) return null; if (player == null) return null;
SQLWhereChain where = new SQLWhereChain(SQLBoolOp.AND); SQLWhereChain where = new SQLWhereChain(SQLBoolOp.AND);
where.add(new SQLWhereComp(SQLMPMessage.viewerId, SQLComparator.EQ, player.toString())); where.add(new SQLWhereComp(SQLMPMessage.viewerId, SQLComparator.EQ, player.toString()));
if (onlyUnread) if (onlyUnread) where.add(new SQLWhereComp(SQLMPMessage.wasRead, SQLComparator.EQ, false));
where.add(new SQLWhereComp(SQLMPMessage.wasRead, SQLComparator.EQ, false));
SQLOrderBy orderBy = new SQLOrderBy().addField(SQLMPMessage.time, revert ? Direction.DESC : Direction.ASC); SQLOrderBy orderBy = new SQLOrderBy().addField(SQLMPMessage.time, revert ? Direction.DESC : Direction.ASC);
return ORM.getAll(SQLMPMessage.class, where, orderBy, numberLast, null); return ORM.getAll(SQLMPMessage.class, where, orderBy, numberLast, null);
} }
} }

View File

@ -9,51 +9,48 @@ import fr.pandacube.java.util.db2.sql_tools.SQLType;
public class SQLModoHistory extends SQLElement { public class SQLModoHistory extends SQLElement {
public SQLModoHistory() {
public SQLModoHistory() { super(); } super();
public SQLModoHistory(int id) { super(id); } }
public SQLModoHistory(int id) {
super(id);
}
@Override @Override
protected String tableName() { return "pandacube_modo_history"; } protected String tableName() {
return "pandacube_modo_history";
}
public static final SQLFKField<String, SQLPlayer> modoId = new SQLFKField<>("modoId", SQLType.CHAR(36), true, SQLPlayer.class, SQLPlayer.playerId);
public static final SQLField<ActionType> actionType = new SQLField<>("actionType", SQLType.ENUM(ActionType.class), false); public static final SQLFKField<String, SQLPlayer> modoId = new SQLFKField<>("modoId", SQLType.CHAR(36), true,
public static final SQLField<Long> time = new SQLField<>("time", SQLType.BIGINT, false); SQLPlayer.class, SQLPlayer.playerId);
public static final SQLFKField<String, SQLPlayer> playerId = new SQLFKField<>("playerId", SQLType.CHAR(36), false, SQLPlayer.class, SQLPlayer.playerId); public static final SQLField<ActionType> actionType = new SQLField<>("actionType", SQLType.ENUM(ActionType.class),
public static final SQLField<Long> value = new SQLField<>("value", SQLType.BIGINT, true); false);
public static final SQLField<String> message = new SQLField<>("message", SQLType.VARCHAR(512), false); public static final SQLField<Long> time = new SQLField<>("time", SQLType.BIGINT, false);
public static final SQLFKField<String, SQLPlayer> playerId = new SQLFKField<>("playerId", SQLType.CHAR(36), false,
SQLPlayer.class, SQLPlayer.playerId);
public static final SQLField<Long> value = new SQLField<>("value", SQLType.BIGINT, true);
public static final SQLField<String> message = new SQLField<>("message", SQLType.VARCHAR(512), false);
public UUID getModoId() { public UUID getModoId() {
String id = (String)get(modoId); String id = get(modoId);
return (id == null) ? null : UUID.fromString(id); return (id == null) ? null : UUID.fromString(id);
} }
public void setModoId(UUID pName) { public void setModoId(UUID pName) {
set(modoId, (pName == null) ? (String)null : pName.toString()); set(modoId, (pName == null) ? (String) null : pName.toString());
} }
public UUID getPlayerId() { public UUID getPlayerId() {
String id = (String)get(playerId); String id = get(playerId);
return (id == null) ? null : UUID.fromString(id); return (id == null) ? null : UUID.fromString(id);
} }
public void setPlayerId(UUID pName) { 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 BAN, UNBAN, MUTE, UNMUTE, REPORT, KICK
} }

View File

@ -9,64 +9,57 @@ import fr.pandacube.java.util.db2.sql_tools.SQLType;
public class SQLOnlineshopHistory extends SQLElement { public class SQLOnlineshopHistory extends SQLElement {
public SQLOnlineshopHistory() {
public SQLOnlineshopHistory() { super(); } super();
public SQLOnlineshopHistory(int id) { super(id); } }
public SQLOnlineshopHistory(int id) {
super(id);
}
@Override @Override
protected String tableName() { return "pandacube_onlineshop_history"; } protected String tableName() {
return "pandacube_onlineshop_history";
}
public static final SQLField<Long> time = new SQLField<>("time", SQLType.BIGINT, false);
public static final SQLField<String> transactionId = new SQLField<>("transactionId", SQLType.VARCHAR(255), true); public static final SQLField<Long> time = new SQLField<>("time", SQLType.BIGINT, false);
public static final SQLField<SourceType> sourceType = new SQLField<>("sourceType", SQLType.ENUM(SourceType.class), false); public static final SQLField<String> transactionId = new SQLField<>("transactionId", SQLType.VARCHAR(255), true);
public static final SQLFKField<String, SQLPlayer> sourcePlayerId = new SQLFKField<>("sourcePlayerId", SQLType.CHAR(36), true, SQLPlayer.class, SQLPlayer.playerId); public static final SQLField<SourceType> sourceType = new SQLField<>("sourceType", SQLType.ENUM(SourceType.class),
public static final SQLField<Double> sourceQuantity = new SQLField<>("sourceQuantity", SQLType.DOUBLE, false); false);
public static final SQLField<String> sourceName = new SQLField<>("sourceName", SQLType.VARCHAR(64), false); public static final SQLFKField<String, SQLPlayer> sourcePlayerId = new SQLFKField<>("sourcePlayerId",
public static final SQLField<DestType> destType = new SQLField<>("destType", SQLType.ENUM(DestType.class), false); SQLType.CHAR(36), true, SQLPlayer.class, SQLPlayer.playerId);
public static final SQLFKField<String, SQLPlayer> destPlayerId = new SQLFKField<>("destPlayerId", SQLType.CHAR(36), false, SQLPlayer.class, SQLPlayer.playerId); public static final SQLField<Double> sourceQuantity = new SQLField<>("sourceQuantity", SQLType.DOUBLE, false);
public static final SQLField<Double> destQuantity = new SQLField<>("destQuantity", SQLType.DOUBLE, false); public static final SQLField<String> sourceName = new SQLField<>("sourceName", SQLType.VARCHAR(64), false);
public static final SQLField<String> destName = new SQLField<>("destName", SQLType.VARCHAR(64), false); public static final SQLField<DestType> destType = new SQLField<>("destType", SQLType.ENUM(DestType.class), false);
public static final SQLFKField<String, SQLPlayer> destPlayerId = new SQLFKField<>("destPlayerId", SQLType.CHAR(36),
false, SQLPlayer.class, SQLPlayer.playerId);
public static final SQLField<Double> destQuantity = new SQLField<>("destQuantity", SQLType.DOUBLE, false);
public static final SQLField<String> destName = new SQLField<>("destName", SQLType.VARCHAR(64), false);
public UUID getSourcePlayerId() { public UUID getSourcePlayerId() {
String id = (String)get(sourcePlayerId); String id = get(sourcePlayerId);
return (id == null) ? null : UUID.fromString(id); 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() { public UUID getDestPlayerId() {
String id = (String)get(destPlayerId); String id = get(destPlayerId);
return (id == null) ? null : UUID.fromString(id); return (id == null) ? null : UUID.fromString(id);
} }
public void setDestPlayerId(UUID pName) { 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 { public static enum SourceType {
REAL_MONEY, BAMBOU REAL_MONEY, BAMBOU
} }
public static enum DestType { public static enum DestType {
BAMBOU, GRADE BAMBOU, GRADE
} }
} }

View File

@ -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;
import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp.SQLComparator; import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp.SQLComparator;
public class SQLPlayer extends SQLElement { public class SQLPlayer extends SQLElement {
public SQLPlayer() { super(); } public SQLPlayer() {
public SQLPlayer(int id) { super(id); } super();
}
public SQLPlayer(int id) {
super(id);
}
/* /*
* Nom de la table * Nom de la table
*/ */
@Override @Override
protected String tableName() { return "pandacube_player"; } protected String tableName() {
return "pandacube_player";
}
/* /*
* Champs de la table * Champs de la table
*/ */
public static final SQLField<String> playerId = new SQLField<>("playerId", SQLType.CHAR(36), false); public static final SQLField<String> playerId = new SQLField<>("playerId", SQLType.CHAR(36), false);
public static final SQLField<String> token = new SQLField<>("token", SQLType.CHAR(36), true); public static final SQLField<String> token = new SQLField<>("token", SQLType.CHAR(36), true);
public static final SQLField<String> mailCheck = new SQLField<>("mailCheck", SQLType.VARCHAR(255), true); public static final SQLField<String> mailCheck = new SQLField<>("mailCheck", SQLType.VARCHAR(255), true);
public static final SQLField<String> password = new SQLField<>("password", SQLType.VARCHAR(255), true); public static final SQLField<String> password = new SQLField<>("password", SQLType.VARCHAR(255), true);
public static final SQLField<String> mail = new SQLField<>("mail", SQLType.VARCHAR(255), true); public static final SQLField<String> mail = new SQLField<>("mail", SQLType.VARCHAR(255), true);
public static final SQLField<String> playerDisplayName = new SQLField<>("playerDisplayName", SQLType.VARCHAR(255), false); public static final SQLField<String> playerDisplayName = new SQLField<>("playerDisplayName", SQLType.VARCHAR(255),
public static final SQLField<Long> firstTimeInGame = new SQLField<>("firstTimeInGame", SQLType.BIGINT, false, 0L); false);
public static final SQLField<Long> timeWebRegister = new SQLField<>("timeWebRegister", SQLType.BIGINT, true); public static final SQLField<Long> firstTimeInGame = new SQLField<>("firstTimeInGame", SQLType.BIGINT, false, 0L);
public static final SQLField<Long> lastTimeInGame = new SQLField<>("lastTimeInGame", SQLType.BIGINT, true); public static final SQLField<Long> timeWebRegister = new SQLField<>("timeWebRegister", SQLType.BIGINT, true);
public static final SQLField<Long> lastWebActivity = new SQLField<>("lastWebActivity", SQLType.BIGINT, false, 0L); public static final SQLField<Long> lastTimeInGame = new SQLField<>("lastTimeInGame", SQLType.BIGINT, true);
public static final SQLField<String> onlineInServer = new SQLField<>("onlineInServer", SQLType.VARCHAR(32), true); public static final SQLField<Long> lastWebActivity = new SQLField<>("lastWebActivity", SQLType.BIGINT, false, 0L);
public static final SQLField<String> skinURL = new SQLField<>("skinURL", SQLType.VARCHAR(255), true); public static final SQLField<String> onlineInServer = new SQLField<>("onlineInServer", SQLType.VARCHAR(32), true);
public static final SQLField<Boolean> isVanish = new SQLField<>("isVanish", SQLType.BOOLEAN, false, (Boolean)false); public static final SQLField<String> skinURL = new SQLField<>("skinURL", SQLType.VARCHAR(255), true);
public static final SQLField<Date> birthday = new SQLField<>("birthday", SQLType.DATE, true); public static final SQLField<Boolean> isVanish = new SQLField<>("isVanish", SQLType.BOOLEAN, false,
public static final SQLField<Integer> lastYearCelebBday = new SQLField<>("lastYearCelebratedBirthday", SQLType.INT, false, 0); (Boolean) false);
public static final SQLField<Long> banTimeout = new SQLField<>("banTimeout", SQLType.BIGINT, true); public static final SQLField<Date> birthday = new SQLField<>("birthday", SQLType.DATE, true);
public static final SQLField<Long> muteTimeout = new SQLField<>("muteTimeout", SQLType.BIGINT, true); public static final SQLField<Integer> lastYearCelebBday = new SQLField<>("lastYearCelebratedBirthday", SQLType.INT,
public static final SQLField<Boolean> isWhitelisted = new SQLField<>("isWhitelisted", SQLType.BOOLEAN, false, (Boolean)false); false, 0);
public static final SQLField<Long> bambou = new SQLField<>("bambou", SQLType.BIGINT, false, 0L); public static final SQLField<Long> banTimeout = new SQLField<>("banTimeout", SQLType.BIGINT, true);
public static final SQLField<String> grade = new SQLField<>("grade", SQLType.VARCHAR(36), false, "default"); public static final SQLField<Long> muteTimeout = new SQLField<>("muteTimeout", SQLType.BIGINT, true);
public static final SQLField<Boolean> isWhitelisted = new SQLField<>("isWhitelisted", SQLType.BOOLEAN, false,
(Boolean) false);
public static final SQLField<Long> bambou = new SQLField<>("bambou", SQLType.BIGINT, false, 0L);
public static final SQLField<String> grade = new SQLField<>("grade", SQLType.VARCHAR(36), false, "default");
/* /*
* Getteurs spécifique (encapsulation) * Getteurs spécifique (encapsulation)
*/ */
public UUID getPlayerId() { public UUID getPlayerId() {
String id = (String)get(playerId); String id = get(playerId);
return (id == null) ? null : UUID.fromString(id); return (id == null) ? null : UUID.fromString(id);
} }
public UUID getToken() { public UUID getToken() {
String id = (String)get(token); String id = get(token);
return (id == null) ? null : UUID.fromString(id); return (id == null) ? null : UUID.fromString(id);
} }
/* /*
* Setteurs spécifique (encapsulation) * Setteurs spécifique (encapsulation)
*/ */
public void setPlayerId(UUID pName) { 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) { 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 { public static SQLPlayer getPlayerFromUUID(UUID playerId) throws ORMException {
return ORM.getFirst(SQLPlayer.class, return ORM.getFirst(SQLPlayer.class,
new SQLWhereComp(SQLPlayer.playerId, SQLComparator.EQ, playerId.toString()), new SQLWhereComp(SQLPlayer.playerId, SQLComparator.EQ, playerId.toString()), null);
null);
} }
} }

View File

@ -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.SQLOrderBy;
import fr.pandacube.java.util.db2.sql_tools.SQLType; 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.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.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.SQLWhereComp.SQLComparator;
public class SQLPlayerIgnore extends SQLElement { public class SQLPlayerIgnore extends SQLElement {
public SQLPlayerIgnore() {
public SQLPlayerIgnore() { super(); } super();
public SQLPlayerIgnore(int id) { super(id); } }
public SQLPlayerIgnore(int id) {
super(id);
}
@Override @Override
protected String tableName() { return "pandacube_player_ignore"; } protected String tableName() {
return "pandacube_player_ignore";
}
public static final SQLFKField<String, SQLPlayer> ignorer = new SQLFKField<>("ignorer", SQLType.CHAR(36), false, SQLPlayer.class, SQLPlayer.playerId);
public static final SQLFKField<String, SQLPlayer> ignored = new SQLFKField<>("ignored", SQLType.CHAR(36), false, SQLPlayer.class, SQLPlayer.playerId); public static final SQLFKField<String, SQLPlayer> ignorer = new SQLFKField<>("ignorer", SQLType.CHAR(36), false,
SQLPlayer.class, SQLPlayer.playerId);
public static final SQLFKField<String, SQLPlayer> ignored = new SQLFKField<>("ignored", SQLType.CHAR(36), false,
SQLPlayer.class, SQLPlayer.playerId);
public UUID getIgnorerId() { public UUID getIgnorerId() {
String id = (String)get(ignorer); String id = get(ignorer);
return (id == null) ? null : UUID.fromString(id); 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() { public UUID getIgnoredId() {
String id = (String)get(ignored); String id = get(ignored);
return (id == null) ? null : UUID.fromString(id); return (id == null) ? null : UUID.fromString(id);
} }
public void setIgnoredId(UUID pName) { 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 { public static SQLPlayerIgnore getPlayerIgnoringPlayer(UUID ignorer, UUID ignored) throws Exception {
return ORM.getFirst(SQLPlayerIgnore.class, return ORM.getFirst(SQLPlayerIgnore.class,
new SQLWhereChain(SQLBoolOp.AND) new SQLWhereChain(SQLBoolOp.AND)
.add(new SQLWhereComp(SQLPlayerIgnore.ignorer, SQLComparator.EQ, ignorer.toString())) .add(new SQLWhereComp(SQLPlayerIgnore.ignorer, SQLComparator.EQ, ignorer.toString()))
.add(new SQLWhereComp(SQLPlayerIgnore.ignored, SQLComparator.EQ, ignored.toString())), .add(new SQLWhereComp(SQLPlayerIgnore.ignored, SQLComparator.EQ, ignored.toString())),
null); null);
} }
public static boolean isPlayerIgnoringPlayer(UUID ignorer, UUID ignored) throws Exception { public static boolean isPlayerIgnoringPlayer(UUID ignorer, UUID ignored) throws Exception {
return getPlayerIgnoringPlayer(ignorer, ignored) != null; return getPlayerIgnoringPlayer(ignorer, ignored) != null;
} }
public static void setPlayerIgnorePlayer(UUID ignorer, UUID ignored, boolean newIgnoreState) throws Exception { public static void setPlayerIgnorePlayer(UUID ignorer, UUID ignored, boolean newIgnoreState) throws Exception {
SQLPlayerIgnore el = getPlayerIgnoringPlayer(ignorer, ignored); SQLPlayerIgnore el = getPlayerIgnoringPlayer(ignorer, ignored);
if (el == null && newIgnoreState) { if (el == null && newIgnoreState) {
@ -78,21 +77,17 @@ public class SQLPlayerIgnore extends SQLElement {
el.delete(); el.delete();
return; return;
} }
}
}
public static List<UUID> getListIgnoredPlayer(UUID ignorer) throws Exception { public static List<UUID> getListIgnoredPlayer(UUID ignorer) throws Exception {
List<SQLPlayerIgnore> els = ORM.getAll(SQLPlayerIgnore.class, List<SQLPlayerIgnore> els = ORM.getAll(SQLPlayerIgnore.class,
new SQLWhereComp(SQLPlayerIgnore.ignorer, SQLComparator.EQ, ignorer.toString()), new SQLWhereComp(SQLPlayerIgnore.ignorer, SQLComparator.EQ, ignorer.toString()),
new SQLOrderBy().addField(ORM.getSQLIdField(SQLPlayerIgnore.class)), null, null); new SQLOrderBy().addField(ORM.getSQLIdField(SQLPlayerIgnore.class)), null, null);
List<UUID> ret = new ArrayList<>(els.size()); List<UUID> ret = new ArrayList<>(els.size());
for (SQLPlayerIgnore el : els) { for (SQLPlayerIgnore el : els)
ret.add(el.getIgnoredId()); ret.add(el.getIgnoredId());
}
return ret; return ret;
} }
} }

View File

@ -5,19 +5,23 @@ import fr.pandacube.java.util.db2.sql_tools.SQLField;
import fr.pandacube.java.util.db2.sql_tools.SQLType; import fr.pandacube.java.util.db2.sql_tools.SQLType;
public class SQLShopStock extends SQLElement { public class SQLShopStock extends SQLElement {
public SQLShopStock() {
public SQLShopStock() { super(); } super();
public SQLShopStock(int id) { super(id); } }
public SQLShopStock(int id) {
super(id);
}
@Override @Override
protected String tableName() { return "pandacube_shop_stock"; } protected String tableName() {
return "pandacube_shop_stock";
}
public static final SQLField<String> material = new SQLField<>("material", SQLType.VARCHAR(50), false); public static final SQLField<String> material = new SQLField<>("material", SQLType.VARCHAR(50), false);
public static final SQLField<Integer> damage = new SQLField<>("damage", SQLType.INT, false, 0); public static final SQLField<Integer> damage = new SQLField<>("damage", SQLType.INT, false, 0);
public static final SQLField<Double> quantity = new SQLField<>("quantity", SQLType.DOUBLE, false); public static final SQLField<Double> quantity = new SQLField<>("quantity", SQLType.DOUBLE, false);
public static final SQLField<String> server = new SQLField<>("server", SQLType.VARCHAR(50), false); public static final SQLField<String> server = new SQLField<>("server", SQLType.VARCHAR(50), false);
} }

View File

@ -9,39 +9,40 @@ import fr.pandacube.java.util.db2.sql_tools.SQLType;
public class SQLStaffTicket extends SQLElement { public class SQLStaffTicket extends SQLElement {
public SQLStaffTicket() {
public SQLStaffTicket() { super(); } super();
public SQLStaffTicket(int id) { super(id); } }
public SQLStaffTicket(int id) {
super(id);
}
@Override @Override
protected String tableName() { return "pandacube_staff_ticket"; } protected String tableName() {
return "pandacube_staff_ticket";
}
public static final SQLFKField<String, SQLPlayer> playerId = new SQLFKField<>("playerId", SQLType.CHAR(36), false, SQLPlayer.class, SQLPlayer.playerId);
public static final SQLFKField<String, SQLPlayer> playerId = new SQLFKField<>("playerId", SQLType.CHAR(36), false,
SQLPlayer.class, SQLPlayer.playerId);
public static final SQLField<String> message = new SQLField<>("message", SQLType.VARCHAR(1024), false); public static final SQLField<String> message = new SQLField<>("message", SQLType.VARCHAR(1024), false);
public static final SQLField<Long> creationTime = new SQLField<>("creationTime", SQLType.BIGINT, false); public static final SQLField<Long> creationTime = new SQLField<>("creationTime", SQLType.BIGINT, false);
public static final SQLFKField<String, SQLPlayer> staffPlayerId = new SQLFKField<>("staffPlayerId", SQLType.CHAR(36), true, SQLPlayer.class, SQLPlayer.playerId); public static final SQLFKField<String, SQLPlayer> staffPlayerId = new SQLFKField<>("staffPlayerId",
SQLType.CHAR(36), true, SQLPlayer.class, SQLPlayer.playerId);
public UUID getPlayerId() { public UUID getPlayerId() {
String id = get(playerId); String id = get(playerId);
return (id == null) ? null : UUID.fromString(id); return (id == null) ? null : UUID.fromString(id);
} }
public void setPlayerId(UUID id) { public void setPlayerId(UUID id) {
set(playerId, (id == null) ? null : id.toString()); set(playerId, (id == null) ? null : id.toString());
} }
public UUID getstaffPlayerId() { public UUID getstaffPlayerId() {
String id = get(staffPlayerId); String id = get(staffPlayerId);
return (id == null) ? null : UUID.fromString(id); return (id == null) ? null : UUID.fromString(id);
} }
public void setstaffPlayerId(UUID id) { public void setstaffPlayerId(UUID id) {
set(staffPlayerId, (id == null) ? null : id.toString()); set(staffPlayerId, (id == null) ? null : id.toString());
} }

View File

@ -6,19 +6,23 @@ import fr.pandacube.java.util.db2.sql_tools.SQLType;
public class SQLStaticPages extends SQLElement { public class SQLStaticPages extends SQLElement {
public SQLStaticPages() {
public SQLStaticPages() { super(); } super();
public SQLStaticPages(int id) { super(id); } }
public SQLStaticPages(int id) {
super(id);
}
@Override @Override
protected String tableName() { return "pandacube_static_pages"; } protected String tableName() {
return "pandacube_static_pages";
}
public static final SQLField<String> permalink = new SQLField<>("permalink", SQLType.VARCHAR(128), false); public static final SQLField<String> permalink = new SQLField<>("permalink", SQLType.VARCHAR(128), false);
public static final SQLField<String> titreHead = new SQLField<>("titreHead", SQLType.VARCHAR(128), false); public static final SQLField<String> titreHead = new SQLField<>("titreHead", SQLType.VARCHAR(128), false);
public static final SQLField<String> titreH2 = new SQLField<>("titreH2", SQLType.VARCHAR(255), false); public static final SQLField<String> titreH2 = new SQLField<>("titreH2", SQLType.VARCHAR(255), false);
public static final SQLField<String> texte = new SQLField<>("texte", SQLType.TEXT, false); public static final SQLField<String> texte = new SQLField<>("texte", SQLType.TEXT, false);
public static final SQLField<String> permissions = new SQLField<>("permissions", SQLType.VARCHAR(255), true); public static final SQLField<String> permissions = new SQLField<>("permissions", SQLType.VARCHAR(255), true);
} }

View File

@ -8,29 +8,31 @@ import fr.pandacube.java.util.db2.sql_tools.SQLField;
import fr.pandacube.java.util.db2.sql_tools.SQLType; import fr.pandacube.java.util.db2.sql_tools.SQLType;
public class SQLUUIDPlayer extends SQLElement { public class SQLUUIDPlayer extends SQLElement {
public SQLUUIDPlayer() { super(); } public SQLUUIDPlayer() {
public SQLUUIDPlayer(int id) { super(id); } super();
}
public SQLUUIDPlayer(int id) {
super(id);
}
@Override @Override
protected String tableName() { return "bungeeperms_uuidplayer"; } protected String tableName() {
return "bungeeperms_uuidplayer";
}
public static final SQLFKField<String, SQLPlayer> uuid = new SQLFKField<>("uuid", SQLType.CHAR(36), false, SQLPlayer.class, SQLPlayer.playerId); public static final SQLFKField<String, SQLPlayer> uuid = new SQLFKField<>("uuid", SQLType.CHAR(36), false,
public static final SQLField<String> player = new SQLField<>("player", SQLType.VARCHAR(16), false); SQLPlayer.class, SQLPlayer.playerId);
public static final SQLField<String> player = new SQLField<>("player", SQLType.VARCHAR(16), false);
public UUID getUUID() { public UUID getUUID() {
String id = get(uuid); String id = get(uuid);
return (id == null) ? null : UUID.fromString(id); return (id == null) ? null : UUID.fromString(id);
} }
public void setUUID(UUID id) { public void setUUID(UUID id) {
set(uuid, (id == null) ? null : id.toString()); set(uuid, (id == null) ? null : id.toString());
} }
} }

View File

@ -10,48 +10,42 @@ public class DBConnection {
String url; String url;
String login; String login;
String pass; 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"); Class.forName("com.mysql.jdbc.Driver");
url = "jdbc:mysql://"+host+":"+port+"/"+dbname; url = "jdbc:mysql://" + host + ":" + port + "/" + dbname;
login = l; login = l;
pass = p; pass = p;
connect(); connect();
} }
public void reconnectIfNecessary() throws SQLException {
public void reconnectIfNecessary() throws SQLException try {
{
try
{
Statement stmt = conn.createStatement(); Statement stmt = conn.createStatement();
stmt.close(); stmt.close();
} } catch (SQLException e) {
catch(SQLException e) try {
{ close();
try { close(); } catch(Exception ex) { } } catch (Exception ex) {}
connect(); connect();
} }
} }
public Connection getNativeConnection() throws SQLException public Connection getNativeConnection() throws SQLException {
{ if (!conn.isValid(1)) reconnectIfNecessary();
if (!conn.isValid(1))
reconnectIfNecessary();
return conn; return conn;
} }
private void connect() throws SQLException { private void connect() throws SQLException {
conn = DriverManager.getConnection(url, login, pass); conn = DriverManager.getConnection(url, login, pass);
} }
public void close() { public void close() {
try { try {
conn.close(); conn.close();
} catch (Exception e) { } } catch (Exception e) {}
} }
} }

View File

@ -33,30 +33,30 @@ import javafx.util.Pair;
/** /**
* <b>ORM = Object-Relational Mapping</b> * <b>ORM = Object-Relational Mapping</b>
*
* @author Marc Baloup * @author Marc Baloup
* *
*/ */
public final class ORM { public final class ORM {
private static List<Class<? extends SQLElement>> tables = new ArrayList<>(); private static List<Class<? extends SQLElement>> tables = new ArrayList<>();
private static DBConnection connection; private static DBConnection connection;
public static DBConnection getConnection() { public static DBConnection getConnection() {
return connection; return connection;
} }
public synchronized static void init(DBConnection conn) { public synchronized static void init(DBConnection conn) {
connection = conn; connection = conn;
/* /*
* Les tables à initialiser * Les tables à initialiser
* * utile des les initialiser ici, car on peut tout de suite déceler les
* utile des les initialiser ici, car on peut tout de suite déceler les bugs ou erreurs dans la déclaration des SQLFields * bugs ou erreurs dans la déclaration des SQLFields
*/ */
try { try {
initTable(SQLContact.class); initTable(SQLContact.class);
initTable(SQLForumCategorie.class); initTable(SQLForumCategorie.class);
@ -78,68 +78,49 @@ public final class ORM {
} catch (ORMInitTableException e) { } catch (ORMInitTableException e) {
Log.getLogger().log(Level.SEVERE, "Erreur d'initialisation d'une table dans l'ORM", e); Log.getLogger().log(Level.SEVERE, "Erreur d'initialisation d'une table dans l'ORM", e);
} }
} }
/* package */ static <T extends SQLElement> void initTable(Class<T> elemClass) throws ORMInitTableException { /* package */ static <T extends SQLElement> void initTable(Class<T> elemClass) throws ORMInitTableException {
if (tables.contains(elemClass)) if (tables.contains(elemClass)) return;
return;
try { try {
T instance = elemClass.newInstance(); T instance = elemClass.newInstance();
String tableName = instance.tableName(); String tableName = instance.tableName();
if (!tableExist(tableName)) if (!tableExist(tableName)) createTable(instance);
createTable(instance);
tables.add(elemClass); tables.add(elemClass);
} catch (Exception e) { } catch (Exception e) {
throw new ORMInitTableException(elemClass, e); throw new ORMInitTableException(elemClass, e);
} }
} }
private static <T extends SQLElement> void createTable(T elem) throws SQLException { private static <T extends SQLElement> 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<Object> params = new ArrayList<>(); List<Object> params = new ArrayList<>();
Collection<SQLField<?>> tableFields = elem.getFields().values(); Collection<SQLField<?>> tableFields = elem.getFields().values();
boolean first = true; boolean first = true;
for (SQLField<?> f : tableFields) { for (SQLField<?> f : tableFields) {
Pair<String, List<Object>> statementPart = f.forSQLPreparedStatement(); Pair<String, List<Object>> statementPart = f.forSQLPreparedStatement();
params.addAll(statementPart.getValue()); params.addAll(statementPart.getValue());
if (!first) sql += ", "; if (!first) sql += ", ";
first = false; first = false;
sql += statementPart.getKey(); sql += statementPart.getKey();
} }
sql += ", PRIMARY KEY id(id))"; sql += ", PRIMARY KEY id(id))";
PreparedStatement ps = connection.getNativeConnection().prepareStatement(sql); PreparedStatement ps = connection.getNativeConnection().prepareStatement(sql);
int i = 1; int i = 1;
for (Object val : params) { for (Object val : params)
ps.setObject(i++, val); ps.setObject(i++, val);
}
try { try {
Log.info("Creating table "+elem.tableName()+":\n"+ps.toString()); Log.info("Creating table " + elem.tableName() + ":\n" + ps.toString());
ps.executeUpdate(); ps.executeUpdate();
} finally { } finally {
ps.close(); ps.close();
} }
} }
private static boolean tableExist(String tableName) throws SQLException { private static boolean tableExist(String tableName) throws SQLException {
ResultSet set = null; ResultSet set = null;
@ -148,88 +129,78 @@ public final class ORM {
set = connection.getNativeConnection().getMetaData().getTables(null, null, tableName, null); set = connection.getNativeConnection().getMetaData().getTables(null, null, tableName, null);
exist = set.next(); exist = set.next();
} finally { } finally {
if (set != null) if (set != null) set.close();
set.close();
} }
return exist; return exist;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <T extends SQLElement> SQLField<Integer> getSQLIdField(Class<T> elemClass) throws ORMInitTableException { public static <T extends SQLElement> SQLField<Integer> getSQLIdField(Class<T> elemClass)
throws ORMInitTableException {
initTable(elemClass); initTable(elemClass);
return (SQLField<Integer>) SQLElement.fieldsCache.get(elemClass).get("id"); return (SQLField<Integer>) SQLElement.fieldsCache.get(elemClass).get("id");
} }
public static <T extends SQLElement> List<T> getByIds(Class<T> elemClass, Collection<Integer> ids) throws ORMException { public static <T extends SQLElement> List<T> getByIds(Class<T> elemClass, Collection<Integer> ids)
throws ORMException {
return getByIds(elemClass, ids.toArray(new Integer[ids.size()])); return getByIds(elemClass, ids.toArray(new Integer[ids.size()]));
} }
public static <T extends SQLElement> List<T> getByIds(Class<T> elemClass, Integer... ids) throws ORMException { public static <T extends SQLElement> List<T> getByIds(Class<T> elemClass, Integer... ids) throws ORMException {
SQLField<Integer> idField = getSQLIdField(elemClass); SQLField<Integer> idField = getSQLIdField(elemClass);
SQLWhereChain where = new SQLWhereChain(SQLBoolOp.OR); SQLWhereChain where = new SQLWhereChain(SQLBoolOp.OR);
for (Integer id : ids) for (Integer id : ids)
if (id != null) if (id != null) where.add(new SQLWhereComp(idField, SQLComparator.EQ, id));
where.add(new SQLWhereComp(idField, SQLComparator.EQ, id));
return getAll(elemClass, where, new SQLOrderBy().addField(idField), 1, null); return getAll(elemClass, where, new SQLOrderBy().addField(idField), 1, null);
} }
public static <T extends SQLElement> T getById(Class<T> elemClass, int id) throws ORMException { public static <T extends SQLElement> T getById(Class<T> elemClass, int id) throws ORMException {
return getFirst(elemClass, new SQLWhereComp(getSQLIdField(elemClass), SQLComparator.EQ, id), null); return getFirst(elemClass, new SQLWhereComp(getSQLIdField(elemClass), SQLComparator.EQ, id), null);
} }
public static <T extends SQLElement> T getFirst(Class<T> elemClass, SQLWhere where, SQLOrderBy orderBy) throws ORMException { public static <T extends SQLElement> T getFirst(Class<T> elemClass, SQLWhere where, SQLOrderBy orderBy)
throws ORMException {
SQLElementList<T> elts = getAll(elemClass, where, orderBy, 1, null); SQLElementList<T> 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 <T extends SQLElement> SQLElementList<T> getAll(Class<T> elemClass) throws ORMException { public static <T extends SQLElement> SQLElementList<T> getAll(Class<T> elemClass) throws ORMException {
return getAll(elemClass, null, null, null, null); return getAll(elemClass, null, null, null, null);
} }
public static <T extends SQLElement> SQLElementList<T> getAll(Class<T> elemClass, SQLWhere where, SQLOrderBy orderBy, Integer limit, Integer offset) throws ORMException { public static <T extends SQLElement> SQLElementList<T> getAll(Class<T> elemClass, SQLWhere where,
SQLOrderBy orderBy, Integer limit, Integer offset) throws ORMException {
initTable(elemClass); initTable(elemClass);
try { try {
String sql = "SELECT * FROM "+elemClass.newInstance().tableName(); String sql = "SELECT * FROM " + elemClass.newInstance().tableName();
List<Object> params = new ArrayList<>(); List<Object> params = new ArrayList<>();
if (where != null) { if (where != null) {
Pair<String, List<Object>> ret = where.toSQL(); Pair<String, List<Object>> ret = where.toSQL();
sql += " WHERE "+ret.getKey(); sql += " WHERE " + ret.getKey();
params.addAll(ret.getValue()); params.addAll(ret.getValue());
} }
if (orderBy != null) if (orderBy != null) sql += " ORDER BY " + orderBy.toSQL();
sql += " ORDER BY "+orderBy.toSQL(); if (limit != null) sql += " LIMIT " + limit;
if (limit != null) if (offset != null) sql += " OFFSET " + offset;
sql += " LIMIT "+limit;
if (offset != null)
sql += " OFFSET "+offset;
sql += ";"; sql += ";";
SQLElementList<T> elmts = new SQLElementList<T>(); SQLElementList<T> elmts = new SQLElementList<T>();
PreparedStatement ps = connection.getNativeConnection().prepareStatement(sql); PreparedStatement ps = connection.getNativeConnection().prepareStatement(sql);
try { try {
int i = 1; int i = 1;
for (Object val : params) { for (Object val : params) {
if (val instanceof Enum<?>) if (val instanceof Enum<?>) val = ((Enum<?>) val).name();
val = ((Enum<?>)val).name();
ps.setObject(i++, val); ps.setObject(i++, val);
} }
Log.debug(ps.toString()); Log.debug(ps.toString());
ResultSet set = ps.executeQuery(); ResultSet set = ps.executeQuery();
try { try {
while (set.next()) while (set.next())
elmts.add(getElementInstance(set, elemClass)); elmts.add(getElementInstance(set, elemClass));
@ -239,123 +210,91 @@ public final class ORM {
} finally { } finally {
ps.close(); ps.close();
} }
return elmts; return elmts;
} catch (ReflectiveOperationException | SQLException e) { } catch (ReflectiveOperationException | SQLException e) {
throw new ORMException(e); throw new ORMException(e);
} }
}
}
private static <T extends SQLElement> T getElementInstance(ResultSet set, Class<T> elemClass) throws ORMException { private static <T extends SQLElement> T getElementInstance(ResultSet set, Class<T> elemClass) throws ORMException {
try { try {
T instance = elemClass.getConstructor(int.class).newInstance(set.getInt("id")); T instance = elemClass.getConstructor(int.class).newInstance(set.getInt("id"));
int fieldCount = set.getMetaData().getColumnCount(); 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); String fieldName = set.getMetaData().getColumnLabel(c);
if (!instance.getFields().containsKey(fieldName)) if (!instance.getFields().containsKey(fieldName)) continue; // ignore
continue; // ignore when field is present in database but not handled by SQLElement instance // when
// field
// is
// present
// in
// database
// but
// not
// handled
// by
// SQLElement
// instance
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
SQLField<Object> sqlField = (SQLField<Object>) instance.getFields().get(fieldName); SQLField<Object> sqlField = (SQLField<Object>) instance.getFields().get(fieldName);
if (sqlField.type.getJavaType().isEnum()) { if (sqlField.type.getJavaType().isEnum()) {
// JDBC ne supporte pas les enums // JDBC ne supporte pas les enums
String enumStrValue = set.getString(c); String enumStrValue = set.getString(c);
if (enumStrValue == null || set.wasNull()) if (enumStrValue == null || set.wasNull()) instance.set(sqlField, null, false);
instance.set(sqlField, null, false);
else { else {
Enum<?> enumValue = EnumUtil.searchUncheckedEnum(sqlField.type.getJavaType(), enumStrValue); Enum<?> enumValue = EnumUtil.searchUncheckedEnum(sqlField.type.getJavaType(), enumStrValue);
if (enumValue == null) if (enumValue == null) throw new ORMException("The enum constant '" + enumStrValue
throw new ORMException("The enum constant '"+enumStrValue+"' is not found in enum class "+sqlField.type.getJavaType().getName()); + "' is not found in enum class " + sqlField.type.getJavaType().getName());
instance.set(sqlField, enumValue, false); instance.set(sqlField, enumValue, false);
} }
} }
else { else {
Object val = set.getObject(c, sqlField.type.getJavaType()); Object val = set.getObject(c, sqlField.type.getJavaType());
if (val == null || set.wasNull()) if (val == null || set.wasNull()) instance.set(sqlField, null, false);
instance.set(sqlField, null, false);
else else
instance.set(sqlField, val, false); instance.set(sqlField, val, false);
} }
// la valeur venant de la BDD est marqué comme "non modifié" dans l'instance // la valeur venant de la BDD est marqué comme "non modifié"
// car le constructeur de l'instance met tout les champs comme modifiés // dans l'instance
// car le constructeur de l'instance met tout les champs comme
// modifiés
instance.modifiedSinceLastSave.remove(sqlField.name); instance.modifiedSinceLastSave.remove(sqlField.name);
} }
if (!instance.isValidForSave()) if (!instance.isValidForSave()) throw new ORMException(
throw new ORMException("This SQLElement representing a database entry is not valid for save : "+instance.toString()); "This SQLElement representing a database entry is not valid for save : " + instance.toString());
return instance; return instance;
} catch (ReflectiveOperationException | IllegalArgumentException | SecurityException | SQLException e) { } catch (ReflectiveOperationException | IllegalArgumentException | SecurityException | SQLException e) {
throw new ORMException("Can't instanciate " + elemClass.getName(), 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 { * public static void main(String[] args) throws Throwable {
ORM.init(new DBConnection("localhost", 3306, "pandacube", "pandacube", "pandacube")); * ORM.init(new DBConnection("localhost", 3306, "pandacube", "pandacube",
* "pandacube"));
List<SQLPlayer> players = ORM.getAll(SQLPlayer.class, * List<SQLPlayer> players = ORM.getAll(SQLPlayer.class,
new SQLWhereChain(SQLBoolOp.AND) * new SQLWhereChain(SQLBoolOp.AND)
.add(new SQLWhereNull(SQLPlayer.banTimeout, true)) * .add(new SQLWhereNull(SQLPlayer.banTimeout, true))
.add(new SQLWhereChain(SQLBoolOp.OR) * .add(new SQLWhereChain(SQLBoolOp.OR)
.add(new SQLWhereComp(SQLPlayer.bambou, SQLComparator.EQ, 0L)) * .add(new SQLWhereComp(SQLPlayer.bambou, SQLComparator.EQ, 0L))
.add(new SQLWhereComp(SQLPlayer.grade, SQLComparator.EQ, "default")) * .add(new SQLWhereComp(SQLPlayer.grade, SQLComparator.EQ, "default"))
), * ),
new SQLOrderBy().addField(SQLPlayer.playerDisplayName), null, null); * new SQLOrderBy().addField(SQLPlayer.playerDisplayName), null, null);
* for(SQLPlayer p : players) {
for(SQLPlayer p : players) { * System.out.println(p.get(SQLPlayer.playerDisplayName));
System.out.println(p.get(SQLPlayer.playerDisplayName)); * }
} * // TODO LIST
* - Gérer mise à jour relative d'un champ (incrément / décrément)
* }
// TODO LIST */
* - Gérer mise à jour relative d'un champ (incrément / décrément)
}
*/
} }

View File

@ -6,11 +6,11 @@ public class ORMException extends Exception {
public ORMException(Throwable initCause) { public ORMException(Throwable initCause) {
super(initCause); super(initCause);
} }
public ORMException(String message, Throwable initCause) { public ORMException(String message, Throwable initCause) {
super(message, initCause); super(message, initCause);
} }
public ORMException(String message) { public ORMException(String message) {
super(message); super(message);
} }

View File

@ -3,16 +3,12 @@ package fr.pandacube.java.util.db2.sql_tools;
public class ORMInitTableException extends ORMException { public class ORMInitTableException extends ORMException {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/* package */ <T extends SQLElement> ORMInitTableException(Class<T> tableElem) { /* package */ <T extends SQLElement> ORMInitTableException(Class<T> tableElem) {
super("Error while initializing table "+tableElem.getName()); super("Error while initializing table " + tableElem.getName());
} }
/* package */ <T extends SQLElement> ORMInitTableException(Class<T> tableElem, Throwable t) { /* package */ <T extends SQLElement> ORMInitTableException(Class<T> tableElem, Throwable t) {
super("Error while initializing table "+tableElem.getName(), t); super("Error while initializing table " + tableElem.getName(), t);
} }
} }

View File

@ -24,258 +24,208 @@ import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp.SQLComparator;
public abstract class SQLElement { public abstract class SQLElement {
/** cache for fields for each subclass of SQLElement */ /** cache for fields for each subclass of SQLElement */
/* package */ static final Map<Class<? extends SQLElement>, SQLFieldMap> fieldsCache = new HashMap<>(); /* package */ static final Map<Class<? extends SQLElement>, SQLFieldMap> fieldsCache = new HashMap<>();
DBConnection db = ORM.getConnection(); DBConnection db = ORM.getConnection();
private boolean stored = false; private boolean stored = false;
private int id; private int id;
private final String tableName; private final String tableName;
private final SQLFieldMap fields; private final SQLFieldMap fields;
private final Map<SQLField<?>, Object> values; private final Map<SQLField<?>, Object> values;
/* package */ final Set<String> modifiedSinceLastSave; /* package */ final Set<String> modifiedSinceLastSave;
public SQLElement() { public SQLElement() {
tableName = tableName(); tableName = tableName();
if (fieldsCache.get(getClass()) == null) { if (fieldsCache.get(getClass()) == null) {
fields = new SQLFieldMap(getClass()); fields = new SQLFieldMap(getClass());
// le champ id commun à toutes les tables // le champ id commun à toutes les tables
fields.addField(new SQLField<>("id", SQLType.INT, false, true, 0)); fields.addField(new SQLField<>("id", SQLType.INT, false, true, 0));
generateFields(fields); generateFields(fields);
fieldsCache.put(getClass(), fields); fieldsCache.put(getClass(), fields);
} }
else { else
fields = fieldsCache.get(getClass()); fields = fieldsCache.get(getClass());
}
values = new LinkedHashMap<>(fields.size()); values = new LinkedHashMap<>(fields.size());
modifiedSinceLastSave = new HashSet<>(fields.size()); modifiedSinceLastSave = new HashSet<>(fields.size());
initDefaultValues(); initDefaultValues();
} }
protected SQLElement(int id) {
protected SQLElement(int id) {
this(); this();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
SQLField<Integer> idField = (SQLField<Integer>)fields.get("id"); SQLField<Integer> idField = (SQLField<Integer>) fields.get("id");
set(idField, id, false); set(idField, id, false);
this.id = id; this.id = id;
stored = true; stored = true;
} }
/** /**
* @return The name of the table in the database. * @return The name of the table in the database.
*/ */
protected abstract String tableName(); protected abstract String tableName();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private void initDefaultValues() { private void initDefaultValues() {
// remplissage des données par défaut (si peut être null ou si valeur par défaut existe) // remplissage des données par défaut (si peut être null ou si valeur
for (@SuppressWarnings("rawtypes") SQLField f : fields.values()) { // par défaut existe)
if (f.defaultValue != null) { for (@SuppressWarnings("rawtypes")
set(f, f.defaultValue); SQLField f : fields.values())
} else if (f.canBeNull || (f.autoIncrement && !stored)) { if (f.defaultValue != null) set(f, f.defaultValue);
set(f, null); else if (f.canBeNull || (f.autoIncrement && !stored)) set(f, null);
}
}
} }
protected void generateFields(SQLFieldMap listToFill) { protected void generateFields(SQLFieldMap listToFill) {
java.lang.reflect.Field[] declaredFields = getClass().getDeclaredFields(); java.lang.reflect.Field[] declaredFields = getClass().getDeclaredFields();
for (java.lang.reflect.Field field : declaredFields) { for (java.lang.reflect.Field field : declaredFields) {
if (!java.lang.reflect.Modifier.isStatic(field.getModifiers())) if (!java.lang.reflect.Modifier.isStatic(field.getModifiers())) continue;
continue;
try { try {
Object val = field.get(null); Object val = field.get(null);
if (val == null || !(val instanceof SQLField)) if (val == null || !(val instanceof SQLField)) continue;
continue;
listToFill.addField((SQLField<?>) val);
listToFill.addField((SQLField<?>)val);
} catch (IllegalArgumentException | IllegalAccessException e) { } 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<String, SQLField<?>> getFields() { /* package */ Map<String, SQLField<?>> getFields() {
return Collections.unmodifiableMap(fields); return Collections.unmodifiableMap(fields);
} }
public Map<SQLField<?>, Object> getValues() { public Map<SQLField<?>, Object> getValues() {
return Collections.unmodifiableMap(values); return Collections.unmodifiableMap(values);
} }
public <T> void set(SQLField<T> field, T value) { public <T> void set(SQLField<T> field, T value) {
set(field, value, true); set(field, value, true);
} }
/* package */ <T> void set(SQLField<T> sqlField, T value, boolean setModified) { /* package */ <T> void set(SQLField<T> sqlField, T value, boolean setModified) {
if (sqlField == null) if (sqlField == null) throw new IllegalArgumentException("sqlField can't be null");
throw new IllegalArgumentException("sqlField can't be null");
if (!fields.containsValue(sqlField)) if (!fields.containsValue(sqlField))
throw new IllegalArgumentException(sqlField.name + " is not a SQLField of " + getClass().getName()); throw new IllegalArgumentException(sqlField.name + " is not a SQLField of " + getClass().getName());
boolean modify = false; boolean modify = false;
if (value == null) { if (value == null) {
if (sqlField.canBeNull || (sqlField.autoIncrement && !stored)) if (sqlField.canBeNull || (sqlField.autoIncrement && !stored)) modify = true;
modify = true;
else else
throw new IllegalArgumentException("SQLField '" + sqlField.name + "' of " + getClass().getName() + " is a NOT NULL field"); throw new IllegalArgumentException(
} else { "SQLField '" + sqlField.name + "' of " + getClass().getName() + " is a NOT NULL field");
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());
} }
else if (sqlField.type.isAssignableFrom(value)) modify = true;
if (modify) { else
if (!values.containsKey(sqlField)) { 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); values.put(sqlField, value);
if (setModified) if (setModified) modifiedSinceLastSave.add(sqlField.name);
modifiedSinceLastSave.add(sqlField.name);
} }
else { // sinon, rien n'est modifié
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é
}
} }
} }
public <T> T get(SQLField<T> field) { public <T> T get(SQLField<T> field) {
if (field == null) if (field == null) throw new IllegalArgumentException("field can't be null");
throw new IllegalArgumentException("field can't be null");
if (values.containsKey(field)) { if (values.containsKey(field)) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
T val = (T) values.get(field); T val = (T) values.get(field);
return val; 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 <T, E extends SQLElement> E getForeign(SQLFKField<T, E> field) throws ORMException { public <T, E extends SQLElement> E getForeign(SQLFKField<T, E> field) throws ORMException {
T fkValue = get(field); T fkValue = get(field);
if (fkValue == null) return null; if (fkValue == null) return null;
return ORM.getFirst(field.getForeignElementClass(), return ORM.getFirst(field.getForeignElementClass(),
new SQLWhereComp(field.getForeignField(), SQLComparator.EQ, fkValue), null); new SQLWhereComp(field.getForeignField(), SQLComparator.EQ, fkValue), null);
} }
public boolean isValidForSave() { public boolean isValidForSave() {
return values.keySet().containsAll(fields.values()); return values.keySet().containsAll(fields.values());
} }
private Map<SQLField<?>, Object> getOnlyModifiedValues() { private Map<SQLField<?>, Object> getOnlyModifiedValues() {
Map<SQLField<?>, Object> modifiedValues = new LinkedHashMap<>(); Map<SQLField<?>, Object> modifiedValues = new LinkedHashMap<>();
values.forEach((k, v) -> { values.forEach((k, v) -> {
if (modifiedSinceLastSave.contains(k.name)) if (modifiedSinceLastSave.contains(k.name)) modifiedValues.put(k, v);
modifiedValues.put(k, v);
}); });
return modifiedValues; return modifiedValues;
} }
public boolean isModified(SQLField<?> field) { public boolean isModified(SQLField<?> field) {
return modifiedSinceLastSave.contains(field.name); return modifiedSinceLastSave.contains(field.name);
} }
public void save() throws ORMException { public void save() throws ORMException {
if (!isValidForSave()) if (!isValidForSave())
throw new IllegalStateException(toString() + " has at least one undefined value and can't be saved."); throw new IllegalStateException(toString() + " has at least one undefined value and can't be saved.");
ORM.initTable(getClass()); ORM.initTable(getClass());
String toStringStatement = ""; String toStringStatement = "";
try { try {
Connection conn = db.getNativeConnection(); Connection conn = db.getNativeConnection();
if (stored) { // mettre à jour les valeurs dans la base
if (stored)
{ // mettre à jour les valeurs dans la base // restaurer l'ID au cas il aurait été changé à la main dans
// values
// restaurer l'ID au cas il aurait été changé à la main dans values
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
SQLField<Integer> idField = (SQLField<Integer>) fields.get("id"); SQLField<Integer> idField = (SQLField<Integer>) fields.get("id");
values.put(idField, id); values.put(idField, id);
modifiedSinceLastSave.remove("id"); modifiedSinceLastSave.remove("id");
Map<SQLField<?>, Object> modifiedValues = getOnlyModifiedValues(); Map<SQLField<?>, Object> modifiedValues = getOnlyModifiedValues();
if (modifiedValues.isEmpty()) if (modifiedValues.isEmpty()) return;
return;
String sql = ""; String sql = "";
List<Object> psValues = new ArrayList<>(); List<Object> psValues = new ArrayList<>();
for(Map.Entry<SQLField<?>, Object> entry : modifiedValues.entrySet()) { for (Map.Entry<SQLField<?>, Object> entry : modifiedValues.entrySet()) {
sql += entry.getKey().name + " = ? ,"; sql += entry.getKey().name + " = ? ,";
if (entry.getKey().type.getJavaType().isEnum()) { if (entry.getKey().type.getJavaType().isEnum()) // prise en
// prise en charge enum (non prise en charge par JDBC) // charge
psValues.add(((Enum<?>)entry.getValue()).name()); // enum (non
} // prise en
// charge
// par JDBC)
psValues.add(((Enum<?>) entry.getValue()).name());
else else
psValues.add(entry.getValue()); psValues.add(entry.getValue());
} }
if (sql.length() > 0) if (sql.length() > 0) sql = sql.substring(0, sql.length() - 1);
sql = sql.substring(0, sql.length()-1);
PreparedStatement ps = conn.prepareStatement("UPDATE " + tableName + " SET " + sql + " WHERE id=" + id);
PreparedStatement ps = conn.prepareStatement("UPDATE "+tableName+" SET "+sql+" WHERE id="+id);
try { try {
int i = 1; int i = 1;
for (Object val : psValues) { for (Object val : psValues)
ps.setObject(i++, val); ps.setObject(i++, val);
}
toStringStatement = ps.toString(); toStringStatement = ps.toString();
ps.executeUpdate(); ps.executeUpdate();
@ -283,19 +233,18 @@ public abstract class SQLElement {
ps.close(); ps.close();
} }
} }
else else { // ajouter dans la base
{ // ajouter dans la base
// restaurer l'ID au cas il aurait été changé à la main dans
// restaurer l'ID au cas il aurait été changé à la main dans values // values
values.put(fields.get("id"), null); values.put(fields.get("id"), null);
String concat_vals = ""; String concat_vals = "";
String concat_fields = ""; String concat_fields = "";
List<Object> psValues = new ArrayList<>(); List<Object> psValues = new ArrayList<>();
boolean first = true; boolean first = true;
for(Map.Entry<SQLField<?>, Object> entry : values.entrySet()) { for (Map.Entry<SQLField<?>, Object> entry : values.entrySet()) {
if (!first) { if (!first) {
concat_vals += ","; concat_vals += ",";
concat_fields += ","; concat_fields += ",";
@ -303,33 +252,33 @@ public abstract class SQLElement {
first = false; first = false;
concat_vals += " ? "; concat_vals += " ? ";
concat_fields += entry.getKey().name; concat_fields += entry.getKey().name;
if (entry.getKey().type.getJavaType().isEnum()) { if (entry.getKey().type.getJavaType().isEnum()) // prise en
// prise en charge enum (non prise en charge par JDBC) // charge
psValues.add(((Enum<?>)entry.getValue()).name()); // enum (non
} // prise en
// charge
// par JDBC)
psValues.add(((Enum<?>) entry.getValue()).name());
else else
psValues.add(entry.getValue()); psValues.add(entry.getValue());
} }
PreparedStatement ps = conn.prepareStatement(
PreparedStatement ps = conn.prepareStatement("INSERT INTO "+tableName+" ("+concat_fields+") VALUES ("+concat_vals+")", Statement.RETURN_GENERATED_KEYS); "INSERT INTO " + tableName + " (" + concat_fields + ") VALUES (" + concat_vals + ")",
Statement.RETURN_GENERATED_KEYS);
try { try {
int i = 1; int i = 1;
for (Object val : psValues) { for (Object val : psValues)
ps.setObject(i++, val); ps.setObject(i++, val);
}
toStringStatement = ps.toString(); toStringStatement = ps.toString();
ps.executeUpdate(); ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys(); ResultSet rs = ps.getGeneratedKeys();
try { try {
if(rs.next()) if (rs.next()) id = rs.getInt(1);
{
id = rs.getInt(1);
}
stored = true; stored = true;
} finally { } finally {
rs.close(); rs.close();
@ -337,38 +286,35 @@ public abstract class SQLElement {
} finally { } finally {
ps.close(); ps.close();
} }
} }
modifiedSinceLastSave.clear(); modifiedSinceLastSave.clear();
} catch(SQLException e) { } catch (SQLException e) {
throw new ORMException("Error while executing SQL statement "+toStringStatement, e); throw new ORMException("Error while executing SQL statement " + toStringStatement, e);
} }
Log.debug(toStringStatement); Log.debug(toStringStatement);
} }
public boolean isStored() {
public boolean isStored() { return stored; } return stored;
}
public Integer getId() { public Integer getId() {
return (stored) ? id : null; return (stored) ? id : null;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public SQLField<Integer> getFieldId() { public SQLField<Integer> getFieldId() {
return (SQLField<Integer>) getFields().get("id"); return (SQLField<Integer>) getFields().get("id");
} }
public void delete() throws ORMException { public void delete() throws ORMException {
try { try {
if (stored) if (stored) { // supprimer la ligne de la base
{ // supprimer la ligne de la base PreparedStatement st = db.getNativeConnection()
PreparedStatement st = db.getNativeConnection().prepareStatement("DELETE FROM "+tableName+" WHERE id="+id); .prepareStatement("DELETE FROM " + tableName + " WHERE id=" + id);
try { try {
Log.debug(st.toString()); Log.debug(st.toString());
st.executeUpdate(); st.executeUpdate();
@ -380,11 +326,12 @@ public abstract class SQLElement {
} catch (SQLException e) { } catch (SQLException e) {
throw new ORMException(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() { /* package */ void markAsNotStored() {
stored = false; stored = false;
@ -392,50 +339,38 @@ public abstract class SQLElement {
modifiedSinceLastSave.clear(); modifiedSinceLastSave.clear();
values.forEach((k, v) -> modifiedSinceLastSave.add(k.name)); values.forEach((k, v) -> modifiedSinceLastSave.add(k.name));
} }
protected static class SQLFieldMap extends LinkedHashMap<String, SQLField<?>> { protected static class SQLFieldMap extends LinkedHashMap<String, SQLField<?>> {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private final Class<? extends SQLElement> sqlElemClass; private final Class<? extends SQLElement> sqlElemClass;
private SQLFieldMap(Class<? extends SQLElement> elemClass) { private SQLFieldMap(Class<? extends SQLElement> elemClass) {
sqlElemClass = elemClass; sqlElemClass = elemClass;
} }
private void addField(SQLField<?> f) { private void addField(SQLField<?> f) {
if (f == null) return; if (f == null) return;
if (containsKey(f.name)) if (containsKey(f.name)) throw new IllegalArgumentException(
throw new IllegalArgumentException("SQLField "+f.name+" already exist in "+sqlElemClass.getName()); "SQLField " + f.name + " already exist in " + sqlElemClass.getName());
f.setSQLElementType(sqlElemClass); f.setSQLElementType(sqlElemClass);
put(f.name, f); put(f.name, f);
} }
} }
@Override @Override
public String toString() { public String toString() {
ToStringBuilder b = new ToStringBuilder(this); ToStringBuilder b = new ToStringBuilder(this);
for (SQLField<?> f : fields.values()) { for (SQLField<?> f : fields.values())
try { try {
b.append(f.name, get(f)); b.append(f.name, get(f));
} catch(IllegalArgumentException e) { } catch (IllegalArgumentException e) {
b.append(f.name, "(Undefined)"); b.append(f.name, "(Undefined)");
} }
}
return b.toString(); return b.toString();
} }
} }

View File

@ -10,25 +10,29 @@ import java.util.Map;
import fr.pandacube.java.util.Log; import fr.pandacube.java.util.Log;
/** /**
* *
* @param <E> * @param <E>
*/ */
public class SQLElementList<E extends SQLElement> extends ArrayList<E> { public class SQLElementList<E extends SQLElement> extends ArrayList<E> {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private final Map<SQLField<?>, Object> modifiedValues = new LinkedHashMap<>(); private final Map<SQLField<?>, Object> modifiedValues = new LinkedHashMap<>();
@Override @Override
public synchronized boolean add(E e) { public synchronized boolean add(E e) {
if (e == null || !e.isStored()) return false; if (e == null || !e.isStored()) return false;
return super.add(e); return super.add(e);
} }
/** /**
* Défini une valeur à un champ qui sera appliquée dans la base de données à tous les * Défini une valeur à un champ qui sera appliquée dans la base de données à
* entrées présente dans cette liste lors de l'appel à {@link #saveCommon()}. * tous les
* Les valeurs stockés dans chaque élément de cette liste ne seront affectés que lors de * 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()} * l'appel à {@link #saveCommon()}
*
* @param <T> * @param <T>
* @param field le champs à modifier * @param field le champs à modifier
* @param value la valeur à lui appliquer * @param value la valeur à lui appliquer
@ -37,72 +41,73 @@ public class SQLElementList<E extends SQLElement> extends ArrayList<E> {
if (field != null && field.name == "id") if (field != null && field.name == "id")
throw new IllegalArgumentException("Can't modify id field in a SQLElementList"); throw new IllegalArgumentException("Can't modify id field in a SQLElementList");
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Class<E> elemClass = (Class<E>) field.getSQLElementType(); Class<E> elemClass = (Class<E>) field.getSQLElementType();
try { try {
E emptyElement = elemClass.newInstance(); E emptyElement = elemClass.newInstance();
emptyElement.set(field, value, false); emptyElement.set(field, value, false);
} catch (Exception e) { } 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 // ici, la valeur est bonne
modifiedValues.put(field, value); modifiedValues.put(field, value);
} }
/** /**
* Applique toutes les valeurs défini avec {@link #setCommon(SQLField, Object)} à toutes * Applique toutes les valeurs défini avec
* les entrées dans la base de données correspondants aux entrées de cette liste. Les nouvelles * {@link #setCommon(SQLField, Object)} à toutes
* 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)}.<br/> * les entrées dans la base de données correspondants aux entrées de cette
* Les objets de cette liste qui n'ont pas leur données en base de données sont ignorées. * liste. Les nouvelles
* @throws SQLException * 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)}.<br/>
* 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 { public synchronized void saveCommon() throws SQLException {
List<E> storedEl = getStoredEl(); List<E> storedEl = getStoredEl();
if (storedEl.isEmpty()) return; if (storedEl.isEmpty()) return;
String sqlSet = ""; String sqlSet = "";
List<Object> psValues = new ArrayList<>(); List<Object> psValues = new ArrayList<>();
for(Map.Entry<SQLField<?>, Object> entry : modifiedValues.entrySet()) { for (Map.Entry<SQLField<?>, Object> entry : modifiedValues.entrySet()) {
sqlSet += entry.getKey().name + " = ? ,"; sqlSet += entry.getKey().name + " = ? ,";
if (entry.getKey().type.getJavaType().isEnum()) { if (entry.getKey().type.getJavaType().isEnum()) // prise en charge
// prise en charge enum (non prise en charge par JDBC) // enum (non prise
psValues.add(((Enum<?>)entry.getValue()).name()); // en charge par
} // JDBC)
psValues.add(((Enum<?>) entry.getValue()).name());
else else
psValues.add(entry.getValue()); psValues.add(entry.getValue());
} }
if (sqlSet.length() > 0) if (sqlSet.length() > 0) sqlSet = sqlSet.substring(0, sqlSet.length() - 1);
sqlSet = sqlSet.substring(0, sqlSet.length()-1);
String sqlWhere = ""; String sqlWhere = "";
boolean first = true; boolean first = true;
for (E el : storedEl) { for (E el : storedEl) {
if (!first) sqlWhere += " OR "; if (!first) sqlWhere += " OR ";
first = false; 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 { try {
int i = 1; int i = 1;
for (Object val : psValues) { for (Object val : psValues)
ps.setObject(i++, val); ps.setObject(i++, val);
}
Log.debug(ps.toString()); Log.debug(ps.toString());
ps.executeUpdate(); ps.executeUpdate();
applyNewValuesToElements(storedEl); applyNewValuesToElements(storedEl);
} finally { } finally {
ps.close(); ps.close();
@ -112,16 +117,12 @@ public class SQLElementList<E extends SQLElement> extends ArrayList<E> {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private void applyNewValuesToElements(List<E> storedEl) { private void applyNewValuesToElements(List<E> storedEl) {
// applique les valeurs dans chaques objets de la liste // applique les valeurs dans chaques objets de la liste
for (E el : storedEl) { for (E el : storedEl)
for (@SuppressWarnings("rawtypes") SQLField entry : modifiedValues.keySet()) { for (@SuppressWarnings("rawtypes")
if (!el.isModified(entry)) SQLField entry : modifiedValues.keySet())
el.set(entry, modifiedValues.get(entry), false); if (!el.isModified(entry)) el.set(entry, modifiedValues.get(entry), false);
}
}
} }
private List<E> getStoredEl() { private List<E> getStoredEl() {
List<E> listStored = new ArrayList<>(); List<E> listStored = new ArrayList<>();
forEach(el -> { forEach(el -> {
@ -129,46 +130,38 @@ public class SQLElementList<E extends SQLElement> extends ArrayList<E> {
}); });
return listStored; return listStored;
} }
public synchronized void removeFromDB() { public synchronized void removeFromDB() {
List<E> storedEl = getStoredEl(); List<E> storedEl = getStoredEl();
if (storedEl.isEmpty()) return; if (storedEl.isEmpty()) return;
try { try {
String sqlWhere = ""; String sqlWhere = "";
boolean first = true; boolean first = true;
for (E el : storedEl) { for (E el : storedEl) {
if (!first) sqlWhere += " OR "; if (!first) sqlWhere += " OR ";
first = false; 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 { try {
Log.debug(st.toString()); Log.debug(st.toString());
st.executeUpdate(); st.executeUpdate();
for (E el : storedEl) { for (E el : storedEl)
el.markAsNotStored(); el.markAsNotStored();
}
} finally { } finally {
st.close(); st.close();
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }

View File

@ -6,39 +6,39 @@ public class SQLFKField<T, E extends SQLElement> extends SQLField<T> {
private SQLField<T> sqlForeignKeyField; private SQLField<T> sqlForeignKeyField;
private Class<E> sqlForeignKeyElement; private Class<E> sqlForeignKeyElement;
public SQLFKField(String n, SQLType<T> t, boolean nul, Class<E> fkEl, SQLField<T> fkF) { public SQLFKField(String n, SQLType<T> t, boolean nul, Class<E> fkEl, SQLField<T> fkF) {
super(n, t, nul); super(n, t, nul);
construct(fkEl, fkF); construct(fkEl, fkF);
} }
public SQLFKField(String n, SQLType<T> t, boolean nul, T deflt, Class<E> fkEl, SQLField<T> fkF) { public SQLFKField(String n, SQLType<T> t, boolean nul, T deflt, Class<E> fkEl, SQLField<T> fkF) {
super(n, t, nul, deflt); super(n, t, nul, deflt);
construct(fkEl, fkF); construct(fkEl, fkF);
} }
public static <E extends SQLElement> SQLFKField<Integer, E> idFK(String n, SQLType<Integer> t, boolean nul, Class<E> fkEl) { public static <E extends SQLElement> SQLFKField<Integer, E> idFK(String n, SQLType<Integer> t, boolean nul,
Class<E> fkEl) {
if (fkEl == null) throw new IllegalArgumentException("foreignKeyElement can't be null"); if (fkEl == null) throw new IllegalArgumentException("foreignKeyElement can't be null");
try { try {
return new SQLFKField<>(n, t, nul, fkEl, ORM.getSQLIdField(fkEl)); return new SQLFKField<>(n, t, nul, fkEl, ORM.getSQLIdField(fkEl));
} catch (ORMInitTableException e) { } 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; return null;
} }
} }
public static <E extends SQLElement> SQLFKField<Integer, E> idFKField(String n, SQLType<Integer> t, boolean nul, Integer deflt, Class<E> fkEl) { public static <E extends SQLElement> SQLFKField<Integer, E> idFKField(String n, SQLType<Integer> t, boolean nul,
Integer deflt, Class<E> fkEl) {
if (fkEl == null) throw new IllegalArgumentException("foreignKeyElement can't be null"); if (fkEl == null) throw new IllegalArgumentException("foreignKeyElement can't be null");
try { try {
return new SQLFKField<>(n, t, nul, deflt, fkEl, ORM.getSQLIdField(fkEl)); return new SQLFKField<>(n, t, nul, deflt, fkEl, ORM.getSQLIdField(fkEl));
} catch (ORMInitTableException e) { } 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; return null;
} }
} }
private void construct(Class<E> fkEl, SQLField<T> fkF) { private void construct(Class<E> fkEl, SQLField<T> fkF) {
if (fkEl == null) throw new IllegalArgumentException("foreignKeyElement can't be null"); if (fkEl == null) throw new IllegalArgumentException("foreignKeyElement can't be null");
if (fkF == null) throw new IllegalArgumentException("foreignKeyField can't be null"); if (fkF == null) throw new IllegalArgumentException("foreignKeyField can't be null");
@ -55,9 +55,13 @@ public class SQLFKField<T, E extends SQLElement> extends SQLField<T> {
sqlForeignKeyField = fkF; sqlForeignKeyField = fkF;
sqlForeignKeyElement = fkEl; sqlForeignKeyElement = fkEl;
} }
public SQLField<T> getForeignField() {
public SQLField<T> getForeignField() { return sqlForeignKeyField; } return sqlForeignKeyField;
public Class<E> getForeignElementClass() { return sqlForeignKeyElement; } }
public Class<E> getForeignElementClass() {
return sqlForeignKeyElement;
}
} }

View File

@ -6,14 +6,14 @@ import java.util.List;
import javafx.util.Pair; import javafx.util.Pair;
public class SQLField<T> { public class SQLField<T> {
private Class<? extends SQLElement> sqlElemClass; private Class<? extends SQLElement> sqlElemClass;
public final String name; public final String name;
public final SQLType<T> type; public final SQLType<T> type;
public final boolean canBeNull; public final boolean canBeNull;
public final boolean autoIncrement; public final boolean autoIncrement;
/* package */ final T defaultValue; /* package */ final T defaultValue;
public SQLField(String n, SQLType<T> t, boolean nul, boolean autoIncr, T deflt) { public SQLField(String n, SQLType<T> t, boolean nul, boolean autoIncr, T deflt) {
name = n; name = n;
type = t; type = t;
@ -21,52 +21,47 @@ public class SQLField<T> {
autoIncrement = autoIncr; autoIncrement = autoIncr;
defaultValue = deflt; defaultValue = deflt;
} }
public SQLField(String n, SQLType<T> t, boolean nul) { public SQLField(String n, SQLType<T> t, boolean nul) {
this(n, t, nul, false, null); this(n, t, nul, false, null);
} }
public SQLField(String n, SQLType<T> t, boolean nul, boolean autoIncr) { public SQLField(String n, SQLType<T> t, boolean nul, boolean autoIncr) {
this(n, t, nul, autoIncr, null); this(n, t, nul, autoIncr, null);
} }
public SQLField(String n, SQLType<T> t, boolean nul, T deflt) { public SQLField(String n, SQLType<T> t, boolean nul, T deflt) {
this(n, t, nul, false, deflt); this(n, t, nul, false, deflt);
} }
/* package */ Pair<String, List<Object>> forSQLPreparedStatement() { /* package */ Pair<String, List<Object>> forSQLPreparedStatement() {
List<Object> params = new ArrayList<>(1); List<Object> params = new ArrayList<>(1);
if (defaultValue != null && !autoIncrement) if (defaultValue != null && !autoIncrement) params.add(defaultValue);
params.add(defaultValue); return new Pair<>(name + " " + type.toString() + (canBeNull ? " NULL" : " NOT NULL")
return new Pair<>(name + (autoIncrement ? " AUTO_INCREMENT" : "")
+ " "+ type.toString() + ((defaultValue == null || autoIncrement) ? "" : " DEFAULT ?"), params);
+ (canBeNull ? " NULL" : " NOT NULL")
+ (autoIncrement ? " AUTO_INCREMENT" : "")
+ ((defaultValue == null || autoIncrement) ? "" : " DEFAULT ?"),
params);
} }
/* package */ void setSQLElementType(Class<? extends SQLElement> elemClass) { /* package */ void setSQLElementType(Class<? extends SQLElement> elemClass) {
sqlElemClass = elemClass; sqlElemClass = elemClass;
} }
public Class<? extends SQLElement> getSQLElementType() { public Class<? extends SQLElement> getSQLElementType() {
return sqlElemClass; return sqlElemClass;
} }
/** /**
* <b>Don't use this {@link #toString()} method in a SQL query, because * <b>Don't use this {@link #toString()} method in a SQL query, because
* the default value is not escaped correctly</b> * the default value is not escaped correctly</b>
*
* @see java.lang.Object#toString() * @see java.lang.Object#toString()
*/ */
@Override @Override
public String toString() { public String toString() {
return forSQLPreparedStatement().getKey().replaceFirst("\\?", (defaultValue != null && !autoIncrement) ? defaultValue.toString() : ""); return forSQLPreparedStatement().getKey().replaceFirst("\\?",
(defaultValue != null && !autoIncrement) ? defaultValue.toString() : "");
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj == null) return false; if (obj == null) return false;
@ -76,11 +71,10 @@ public class SQLField<T> {
if (!f.sqlElemClass.equals(sqlElemClass)) return false; if (!f.sqlElemClass.equals(sqlElemClass)) return false;
return true; return true;
} }
@Override @Override
public int hashCode() { public int hashCode() {
return name.hashCode() + sqlElemClass.hashCode(); return name.hashCode() + sqlElemClass.hashCode();
} }
} }

View File

@ -4,16 +4,17 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
public class SQLOrderBy { public class SQLOrderBy {
private List<OBField> orderByFields = new ArrayList<>(); private List<OBField> orderByFields = new ArrayList<>();
/** /**
* Construit une nouvelle clause ORDER BY * Construit une nouvelle clause ORDER BY
*/ */
public SQLOrderBy() {} public SQLOrderBy() {}
/** /**
* Ajoute un champ dans la clause ORDER BY en construction * Ajoute un champ dans la clause ORDER BY en construction
*
* @param field le champ SQL à ordonner * @param field le champ SQL à ordonner
* @param d le sens de tri (croissant ASC ou décroissant DESC) * @param d le sens de tri (croissant ASC ou décroissant DESC)
* @return l'objet courant (permet de chainer les ajouts de champs) * @return l'objet courant (permet de chainer les ajouts de champs)
@ -22,18 +23,18 @@ public class SQLOrderBy {
orderByFields.add(new OBField(field, d)); orderByFields.add(new OBField(field, d));
return this; return this;
} }
/** /**
* Ajoute un champ dans la clause ORDER BY en construction, * Ajoute un champ dans la clause ORDER BY en construction,
* avec comme ordre de tri croissant ASC par défaut * avec comme ordre de tri croissant ASC par défaut
*
* @param field le champ SQL à ordonner dans l'ordre croissant ASC * @param field le champ SQL à ordonner dans l'ordre croissant ASC
* @return l'objet courant (permet de chainer les ajouts de champs) * @return l'objet courant (permet de chainer les ajouts de champs)
*/ */
public SQLOrderBy addField(SQLField<?> field) { public SQLOrderBy addField(SQLField<?> field) {
return addField(field, Direction.ASC); return addField(field, Direction.ASC);
} }
/* package */ String toSQL() { /* package */ String toSQL() {
String ret = ""; String ret = "";
boolean first = true; boolean first = true;
@ -44,25 +45,23 @@ public class SQLOrderBy {
} }
return ret; return ret;
} }
@Override @Override
public String toString() { public String toString() {
return toSQL(); return toSQL();
} }
private class OBField { private class OBField {
public final SQLField<?> field; public final SQLField<?> field;
public final Direction direction; public final Direction direction;
public OBField(SQLField<?> f, Direction d) { public OBField(SQLField<?> f, Direction d) {
field = f; field = f;
direction = d; direction = d;
} }
} }
public enum Direction { public enum Direction {
ASC, DESC; ASC, DESC;
} }

View File

@ -3,97 +3,88 @@ package fr.pandacube.java.util.db2.sql_tools;
import java.sql.Date; import java.sql.Date;
public class SQLType<T> { public class SQLType<T> {
private final String sqlType; private final String sqlType;
private final String sqlTypeParam; private final String sqlTypeParam;
private final Class<T> javaTypes; private final Class<T> javaTypes;
public SQLType(String sqlT, String sqlP, Class<T> javaT) { public SQLType(String sqlT, String sqlP, Class<T> javaT) {
sqlType = sqlT; sqlType = sqlT;
sqlTypeParam = sqlP; sqlTypeParam = sqlP;
javaTypes = javaT; javaTypes = javaT;
} }
@Override @Override
public String toString() { public String toString() {
return sqlType + sqlTypeParam; return sqlType + sqlTypeParam;
} }
public boolean isAssignableFrom(Object val) { public boolean isAssignableFrom(Object val) {
if (javaTypes.isInstance(val)) if (javaTypes.isInstance(val)) return true;
return true;
return false; return false;
} }
@Override @Override
public int hashCode() { public int hashCode() {
return toString().hashCode(); return toString().hashCode();
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj == null || !(obj instanceof SQLType)) if (obj == null || !(obj instanceof SQLType)) return false;
return false; return toString().equals(((SQLType<?>) obj).toString());
return toString().equals(((SQLType<?>)obj).toString());
} }
public Class<T> getJavaType() { public Class<T> getJavaType() {
return javaTypes; return javaTypes;
} }
public static final SQLType<Boolean> BOOLEAN = new SQLType<>("BOOLEAN", "", Boolean.class); public static final SQLType<Boolean> BOOLEAN = new SQLType<>("BOOLEAN", "", Boolean.class);
public static final SQLType<Byte> TINYINT = new SQLType<>("TINYINT", "", Byte.class); public static final SQLType<Byte> TINYINT = new SQLType<>("TINYINT", "", Byte.class);
public static final SQLType<Byte> BYTE = TINYINT; public static final SQLType<Byte> BYTE = TINYINT;
public static final SQLType<Short> SMALLINT = new SQLType<>("SMALLINT", "", Short.class); public static final SQLType<Short> SMALLINT = new SQLType<>("SMALLINT", "", Short.class);
public static final SQLType<Short> SHORT = SMALLINT; public static final SQLType<Short> SHORT = SMALLINT;
public static final SQLType<Integer> INT = new SQLType<>("INT", "", Integer.class); public static final SQLType<Integer> INT = new SQLType<>("INT", "", Integer.class);
public static final SQLType<Integer> INTEGER = INT; public static final SQLType<Integer> INTEGER = INT;
public static final SQLType<Long> BIGINT = new SQLType<>("BIGINT", "", Long.class); public static final SQLType<Long> BIGINT = new SQLType<>("BIGINT", "", Long.class);
public static final SQLType<Long> LONG = BIGINT; public static final SQLType<Long> LONG = BIGINT;
public static final SQLType<Date> DATE = new SQLType<>("DATE", "", Date.class); public static final SQLType<Date> DATE = new SQLType<>("DATE", "", Date.class);
public static final SQLType<Float> FLOAT = new SQLType<>("FLOAT", "", Float.class); public static final SQLType<Float> FLOAT = new SQLType<>("FLOAT", "", Float.class);
public static final SQLType<Double> DOUBLE = new SQLType<>("DOUBLE", "", Double.class); public static final SQLType<Double> DOUBLE = new SQLType<>("DOUBLE", "", Double.class);
public static final SQLType<String> CHAR(int charCount) { public static final SQLType<String> CHAR(int charCount) {
if (charCount <= 0) throw new IllegalArgumentException("charCount must be positive."); 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<String> VARCHAR(int charCount) { public static final SQLType<String> VARCHAR(int charCount) {
if (charCount <= 0) throw new IllegalArgumentException("charCount must be positive."); 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<String> TEXT = new SQLType<>("TEXT", "", String.class); public static final SQLType<String> TEXT = new SQLType<>("TEXT", "", String.class);
public static final SQLType<String> STRING = TEXT; public static final SQLType<String> STRING = TEXT;
public static final <T extends Enum<T>> SQLType<T> ENUM(Class<T> enumType) { public static final <T extends Enum<T>> SQLType<T> ENUM(Class<T> enumType) {
if (enumType == null) throw new IllegalArgumentException("enumType can't be null."); if (enumType == null) throw new IllegalArgumentException("enumType can't be null.");
String enumStr = "'"; String enumStr = "'";
boolean first = true; boolean first = true;
for (T el : enumType.getEnumConstants()) { for (T el : enumType.getEnumConstants()) {
if (!first) if (!first) enumStr += "', '";
enumStr += "', '";
first = false; first = false;
enumStr += el.name(); enumStr += el.name();
} }
enumStr += "'"; enumStr += "'";
return new SQLType<>("VARCHAR", "("+enumStr+")", enumType); return new SQLType<>("VARCHAR", "(" + enumStr + ")", enumType);
} }
} }

View File

@ -5,17 +5,12 @@ import java.util.List;
import javafx.util.Pair; import javafx.util.Pair;
public abstract class SQLWhere { public abstract class SQLWhere {
public abstract Pair<String, List<Object>> toSQL(); public abstract Pair<String, List<Object>> toSQL();
@Override @Override
public String toString() { public String toString() {
return toSQL().getKey(); return toSQL().getKey();
} }
} }

View File

@ -6,55 +6,49 @@ import java.util.List;
import javafx.util.Pair; import javafx.util.Pair;
public class SQLWhereChain extends SQLWhere { public class SQLWhereChain extends SQLWhere {
private SQLBoolOp operator; private SQLBoolOp operator;
private List<SQLWhere> conditions = new ArrayList<>(); private List<SQLWhere> conditions = new ArrayList<>();
public SQLWhereChain(SQLBoolOp op) { public SQLWhereChain(SQLBoolOp op) {
if (op == null) if (op == null) throw new IllegalArgumentException("op can't be null");
throw new IllegalArgumentException("op can't be null");
operator = op; operator = op;
} }
public SQLWhereChain add(SQLWhere sqlWhere) { public SQLWhereChain add(SQLWhere sqlWhere) {
if (sqlWhere == null) if (sqlWhere == null) throw new IllegalArgumentException("sqlWhere can't be null");
throw new IllegalArgumentException("sqlWhere can't be null");
conditions.add(sqlWhere); conditions.add(sqlWhere);
return this; return this;
} }
@Override @Override
public Pair<String, List<Object>> toSQL() { public Pair<String, List<Object>> toSQL() {
String sql = ""; String sql = "";
List<Object> params = new ArrayList<>(); List<Object> params = new ArrayList<>();
boolean first = true; boolean first = true;
for (SQLWhere w : conditions) { for (SQLWhere w : conditions) {
if (!first) sql += " " + operator.sql + " "; if (!first) sql += " " + operator.sql + " ";
first = false; first = false;
Pair<String, List<Object>> ret = w.toSQL(); Pair<String, List<Object>> ret = w.toSQL();
sql += "(" + ret.getKey() + ")"; sql += "(" + ret.getKey() + ")";
params.addAll(ret.getValue()); params.addAll(ret.getValue());
} }
return new Pair<>(sql, params); return new Pair<>(sql, params);
} }
public enum SQLBoolOp { public enum SQLBoolOp {
/** Equivalent to SQL "<code>AND</code>" */ /** Equivalent to SQL "<code>AND</code>" */
AND("AND"), AND("AND"), /** Equivalent to SQL "<code>OR</code>" */
/** Equivalent to SQL "<code>OR</code>" */
OR("OR"); OR("OR");
public final String sql; public final String sql;
private SQLBoolOp(String s) { private SQLBoolOp(String s) {
sql = s; sql = s;
} }
} }
} }

View File

@ -6,13 +6,14 @@ import java.util.List;
import javafx.util.Pair; import javafx.util.Pair;
public class SQLWhereComp extends SQLWhere { public class SQLWhereComp extends SQLWhere {
private SQLField<?> left; private SQLField<?> left;
private SQLComparator comp; private SQLComparator comp;
private Object right; private Object right;
/** /**
* Compare a field with a value * Compare a field with a value
*
* @param l the field at left of the comparison operator. Can't be null * @param l the field at left of the comparison operator. Can't be null
* @param c the comparison operator, can't be null * @param c the comparison operator, can't be null
* @param r the value at right of the comparison operator. Can't be null * @param 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"); throw new IllegalArgumentException("All arguments for SQLWhereComp constructor can't be null");
left = l; left = l;
comp = c; comp = c;
right = r; right = r;
} }
@Override @Override
public Pair<String, List<Object>> toSQL() { public Pair<String, List<Object>> toSQL() {
List<Object> params = new ArrayList<>(); List<Object> params = new ArrayList<>();
params.add(right); params.add(right);
return new Pair<>(left.name + " " + comp.sql + " ? ", params); return new Pair<>(left.name + " " + comp.sql + " ? ", params);
} }
public enum SQLComparator { public enum SQLComparator {
/** Equivalent to SQL "<code>=</code>" */ /** Equivalent to SQL "<code>=</code>" */
EQ("="), EQ("="), /** Equivalent to SQL "<code>></code>" */
/** Equivalent to SQL "<code>></code>" */ GT(">"), /** Equivalent to SQL "<code>>=</code>" */
GT(">"), GEQ(">="), /** Equivalent to SQL "<code>&lt;</code>" */
/** Equivalent to SQL "<code>>=</code>" */ LT("<"), /** Equivalent to SQL "<code>&lt;=</code>" */
GEQ(">="), LEQ("<="), /** Equivalent to SQL "<code>!=</code>" */
/** Equivalent to SQL "<code>&lt;</code>" */
LT("<"),
/** Equivalent to SQL "<code>&lt;=</code>" */
LEQ("<="),
/** Equivalent to SQL "<code>!=</code>" */
NEQ("!="); NEQ("!=");
public final String sql; public final String sql;
private SQLComparator(String s) { private SQLComparator(String s) {
sql = s; sql = s;
} }
} }
} }

View File

@ -6,13 +6,13 @@ import java.util.List;
import javafx.util.Pair; import javafx.util.Pair;
public class SQLWhereLike extends SQLWhere { public class SQLWhereLike extends SQLWhere {
private SQLField<String> field; private SQLField<String> field;
private String likeExpr; private String likeExpr;
/** /**
* Compare a field with a value * Compare a field with a value
*
* @param f the field at left of the LIKE keyword. Can't be null * @param f the field at left of the LIKE keyword. Can't be null
* @param like the like expression. * @param like the like expression.
*/ */
@ -22,8 +22,7 @@ public class SQLWhereLike extends SQLWhere {
field = f; field = f;
likeExpr = like; likeExpr = like;
} }
@Override @Override
public Pair<String, List<Object>> toSQL() { public Pair<String, List<Object>> toSQL() {
ArrayList<Object> params = new ArrayList<>(); ArrayList<Object> params = new ArrayList<>();

View File

@ -8,30 +8,29 @@ import fr.pandacube.java.util.Log;
import javafx.util.Pair; import javafx.util.Pair;
public class SQLWhereNull extends SQLWhere { public class SQLWhereNull extends SQLWhere {
private SQLField<?> fild; private SQLField<?> fild;
private boolean nulll; private boolean nulll;
/** /**
* Init a IS NULL / IS NOT NULL expression for a SQL WHERE condition. * Init a IS NULL / IS NOT NULL expression for a SQL WHERE condition.
*
* @param field the field to check null / not null state * @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) { public SQLWhereNull(SQLField<?> field, boolean isNull) {
if (field == null) if (field == null) throw new IllegalArgumentException("field can't be null");
throw new IllegalArgumentException("field can't be null"); if (!field.canBeNull) Log.getLogger().log(Level.WARNING,
if (!field.canBeNull) "Useless : Trying to check IS [NOT] NULL on the field " + field.getSQLElementType().getName() + "#"
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'"); + field.name + " which is declared in the ORM as 'can't be null'");
fild = field; fild = field;
nulll = isNull; nulll = isNull;
} }
@Override @Override
public Pair<String, List<Object>> toSQL() { public Pair<String, List<Object>> 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<>());
} }
} }

View File

@ -6,58 +6,42 @@ import java.util.Arrays;
public class DistanceUtil { public class DistanceUtil {
public static String distanceToString(double meterDist, int precision, DistanceUnit... desiredUnits) { public static String distanceToString(double meterDist, int precision, DistanceUnit... desiredUnits) {
Arrays.sort(desiredUnits); Arrays.sort(desiredUnits);
DistanceUnit choosenUnit = desiredUnits[0]; // la plus petite unitée DistanceUnit choosenUnit = desiredUnits[0]; // la plus petite unitée
for (DistanceUnit unit : desiredUnits) { for (DistanceUnit unit : desiredUnits) {
if (meterDist / unit.multiplicator < 1) if (meterDist / unit.multiplicator < 1) continue;
continue;
choosenUnit = unit; choosenUnit = unit;
} }
if (choosenUnit != desiredUnits[0] && precision <= 2) if (choosenUnit != desiredUnits[0] && precision <= 2) precision = 2;
precision = 2;
String precisionFormat = "##0"; String precisionFormat = "##0";
if (precision > 0) if (precision > 0) precisionFormat += ".";
precisionFormat += "."; for (int i = 0; i < precision; i++)
for (int i=0;i<precision; i++)
precisionFormat += "0"; precisionFormat += "0";
DecimalFormat df = new DecimalFormat(precisionFormat); DecimalFormat df = new DecimalFormat(precisionFormat);
double dist = meterDist / choosenUnit.multiplicator; 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) { public static String distanceToString(double meterDist, int precision) {
return distanceToString(meterDist, precision, DistanceUnit.M, DistanceUnit.KM); return distanceToString(meterDist, precision, DistanceUnit.M, DistanceUnit.KM);
} }
public enum DistanceUnit implements Comparable<DistanceUnit> { public enum DistanceUnit implements Comparable<DistanceUnit> {
NM(0.000000001, "nm"), NM(0.000000001, "nm"), µM(0.000001, "µm"), MM(0.001, "mm"), CM(0.01, "cm"), M(1, "m"), KM(1000, "km");
µM(0.000001, "µm"),
MM(0.001, "mm"),
CM(0.01, "cm"),
M(1, "m"),
KM(1000, "km");
private final double multiplicator; private final double multiplicator;
private final String unitStr; private final String unitStr;
private DistanceUnit(double mult, String s) { private DistanceUnit(double mult, String s) {
multiplicator = mult; multiplicator = mult;
unitStr = s; unitStr = s;
} }
} }
} }

View File

@ -3,33 +3,26 @@ package fr.pandacube.java.util.measurement;
import java.text.DecimalFormat; import java.text.DecimalFormat;
public class MemoryUtil { public class MemoryUtil {
private static final DecimalFormat format = new DecimalFormat("#####0.00"); 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; double size = octet;
int diveBy = si ? 1000 : 1024; int diveBy = si ? 1000 : 1024;
if (size < diveBy) return size + "o";
if (size < diveBy)
return size+"o";
size /= diveBy; size /= diveBy;
if (size < diveBy) if (size < diveBy) return format.format(size) + (si ? "ko" : "kio");
return format.format(size) + (si ? "ko" : "kio");
size /= diveBy; size /= diveBy;
if (size < diveBy) if (size < diveBy) return format.format(size) + (si ? "Mo" : "Mio");
return format.format(size) + (si ? "Mo" : "Mio");
size /= diveBy; size /= diveBy;
if (size < diveBy) if (size < diveBy) return format.format(size) + (si ? "Go" : "Gio");
return format.format(size) + (si ? "Go" : "Gio");
size /= diveBy; size /= diveBy;
return format.format(size) + (si ? "To" : "Tio"); return format.format(size) + (si ? "To" : "Tio");
} }
public static String humanReadableSize(long octet) { public static String humanReadableSize(long octet) {
return humanReadableSize(octet, false); return humanReadableSize(octet, false);

View File

@ -1,41 +1,36 @@
package fr.pandacube.java.util.measurement; package fr.pandacube.java.util.measurement;
public class TimeUtil { 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; int j = 0, h = 0, m = 0, s = 0;
long msec = msec_time; long msec = msec_time;
j = (int) (msec / (1000 * 60 * 60 * 24)); 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)); h = (int) (msec / (1000 * 60 * 60));
msec -= (long)(1000 * 60 * 60) * h; msec -= (long) (1000 * 60 * 60) * h;
m = (int) (msec / (1000 * 60)); m = (int) (msec / (1000 * 60));
msec -= (long)(1000 * 60) * m; msec -= (long) (1000 * 60) * m;
s = (int) (msec / 1000); s = (int) (msec / 1000);
msec -= (long)1000 * s; msec -= (long) 1000 * s;
String result = ""; String result = "";
if (j>0) result = result.concat(j+"j "); if (j > 0) result = result.concat(j + "j ");
if (h>0) result = result.concat(h+"h "); if (h > 0) result = result.concat(h + "h ");
if (m>0) result = result.concat(m+"m "); if (m > 0) result = result.concat(m + "m ");
if (s>0 && !dec_seconde) result = result.concat(s+"s"); if (s > 0 && !dec_seconde) result = result.concat(s + "s");
else if (dec_seconde && (s>0 || msec > 0)) else if (dec_seconde && (s > 0 || msec > 0)) {
{ msec += s * 1000;
msec += s*1000; result = result.concat((msec / 1000D) + "s");
result = result.concat((msec/1000D)+"s");
} }
if (result.equals("")) if (result.equals("")) result = "0";
result = "0";
return result.trim(); return result.trim();
} }
public static String durationToString (long msec_time) public static String durationToString(long msec_time) {
{
return durationToString(msec_time, false); return durationToString(msec_time, false);
} }
} }

View File

@ -20,23 +20,19 @@ import fr.pandacube.java.util.network.packet.PacketException;
import fr.pandacube.java.util.network.packet.PacketServer; import fr.pandacube.java.util.network.packet.PacketServer;
public class TCPClient extends Thread implements Closeable { public class TCPClient extends Thread implements Closeable {
private Socket socket; private Socket socket;
private SocketAddress addr; private SocketAddress addr;
private TCPClientListener listener; private TCPClientListener listener;
private InputStream in; private InputStream in;
private OutputStream out; private OutputStream out;
private Object outSynchronizer = new Object(); private Object outSynchronizer = new Object();
private AtomicBoolean isClosed = new AtomicBoolean(false); private AtomicBoolean isClosed = new AtomicBoolean(false);
public TCPClient(InetSocketAddress a, String connName, TCPClientListener l) throws IOException { public TCPClient(InetSocketAddress a, String connName, TCPClientListener l) throws IOException {
super("TCPCl "+connName); super("TCPCl " + connName);
if (a == null || l == null) if (a == null || l == null) throw new IllegalArgumentException("les arguments ne peuvent pas être null");
throw new IllegalArgumentException("les arguments ne peuvent pas être null");
socket = new Socket(); socket = new Socket();
socket.setReceiveBufferSize(Pandacube.NETWORK_TCP_BUFFER_SIZE); socket.setReceiveBufferSize(Pandacube.NETWORK_TCP_BUFFER_SIZE);
socket.setSendBufferSize(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 = l;
listener.onConnect(this); listener.onConnect(this);
} }
@Override @Override
public void run() { public void run() {
try { try {
byte[] code = new byte[1]; byte[] code = new byte[1];
while(!socket.isClosed() && in.read(code) != -1) { while (!socket.isClosed() && in.read(code) != -1) {
byte[] sizeB = new byte[4]; byte[] sizeB = new byte[4];
if (in.read(sizeB) != 4) if (in.read(sizeB) != 4) throw new IOException("Socket " + addr + " fermé");
throw new IOException("Socket "+addr+" fermé");
int size = ByteBuffer.wrap(sizeB).getInt(); int size = ByteBuffer.wrap(sizeB).getInt();
byte[] content = new byte[size]; byte[] content = new byte[size];
forceReadBytes(content); 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 { try {
if (listener == null) if (listener == null) throw new InvalidServerMessage(
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"); "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); Packet p = Packet.constructPacket(packetData);
if (!(p instanceof PacketServer)) if (!(p instanceof PacketServer)) throw new InvalidServerMessage(
throw new InvalidServerMessage("Le type de packet reçu n'est pas un packet attendu : "+p.getClass().getCanonicalName()); "Le type de packet reçu n'est pas un packet attendu : " + p.getClass().getCanonicalName());
PacketServer ps = (PacketServer) p; PacketServer ps = (PacketServer) p;
listener.onPacketReceive(this, ps); listener.onPacketReceive(this, ps);
} catch (PacketException|InvalidServerMessage e) { } catch (PacketException | InvalidServerMessage e) {
Log.getLogger().log(Level.SEVERE, "Message du serveur mal formé", e); Log.getLogger().log(Level.SEVERE, "Message du serveur mal formé", e);
} catch (Exception 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);
} }
} }
} catch (SocketTimeoutException e) { } catch (SocketTimeoutException e) {
System.err.println("Le serveur a prit trop de temps à répondre"); System.err.println("Le serveur a prit trop de temps à répondre");
} catch (Exception e) { } catch (Exception e) {
@ -94,35 +86,28 @@ public class TCPClient extends Thread implements Closeable {
} }
close(); close();
} }
private void forceReadBytes(byte[] buff) throws IOException { private void forceReadBytes(byte[] buff) throws IOException {
int pos = 0; int pos = 0;
do { do {
int nbR = in.read(buff, pos, buff.length-pos); int nbR = in.read(buff, pos, buff.length - pos);
if (nbR == -1) if (nbR == -1) throw new IOException("Can't read required amount of byte");
throw new IOException("Can't read required amount of byte");
pos += nbR; pos += nbR;
} while (pos < buff.length); } while (pos < buff.length);
} }
public void send(PacketClient packet) throws IOException { public void send(PacketClient packet) throws IOException {
synchronized (outSynchronizer) { synchronized (outSynchronizer) {
out.write(packet.getFullSerializedPacket()); out.write(packet.getFullSerializedPacket());
out.flush(); out.flush();
} }
} }
@Override @Override
public void close() { public void close() {
try { try {
synchronized (outSynchronizer) { synchronized (outSynchronizer) {
if (isClosed.get()) if (isClosed.get()) return;
return;
socket.close(); socket.close();
isClosed.set(true); isClosed.set(true);
listener.onDisconnect(this); listener.onDisconnect(this);
@ -131,37 +116,27 @@ public class TCPClient extends Thread implements Closeable {
e.printStackTrace(); e.printStackTrace();
} }
} }
public void sendSilently(PacketClient packet) { public void sendSilently(PacketClient packet) {
try { try {
send(packet); send(packet);
} catch (IOException e) { } } catch (IOException e) {}
} }
public SocketAddress getServerAddress() { public SocketAddress getServerAddress() {
return addr; return addr;
} }
public boolean isClosed() { public boolean isClosed() {
return isClosed.get() || socket.isClosed(); return isClosed.get() || socket.isClosed();
} }
public static class InvalidServerMessage extends RuntimeException { public static class InvalidServerMessage extends RuntimeException {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public InvalidServerMessage(String message) { public InvalidServerMessage(String message) {
super(message); super(message);
} }
} }
} }

View File

@ -3,11 +3,11 @@ package fr.pandacube.java.util.network.client;
import fr.pandacube.java.util.network.packet.PacketServer; import fr.pandacube.java.util.network.packet.PacketServer;
public interface TCPClientListener { public interface TCPClientListener {
public void onConnect(TCPClient connection); public void onConnect(TCPClient connection);
public void onPacketReceive(TCPClient connection, PacketServer packet); public void onPacketReceive(TCPClient connection, PacketServer packet);
public void onDisconnect(TCPClient connection); public void onDisconnect(TCPClient connection);
} }

View File

@ -1,6 +1,5 @@
package fr.pandacube.java.util.network.packet; package fr.pandacube.java.util.network.packet;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; 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; import fr.pandacube.java.util.network.packet.bytebuffer.ByteSerializable;
public abstract class Packet implements ByteSerializable { public abstract class Packet implements ByteSerializable {
private final byte code; private final byte code;
public Packet(byte c) { public Packet(byte c) {
code = c; code = c;
} }
public byte getCode() { return code; } public byte getCode() {
return code;
}
public byte[] getFullSerializedPacket() { public byte[] getFullSerializedPacket() {
ByteBuffer internal = new ByteBuffer(CHARSET).putObject(this); ByteBuffer internal = new ByteBuffer(CHARSET).putObject(this);
byte[] data = Arrays.copyOfRange(internal.array(), 0, internal.getPosition()); 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; public static final Charset CHARSET = Pandacube.NETWORK_CHARSET;
private static Map<Byte, Class<? extends Packet>> packetTypes = new HashMap<Byte, Class<? extends Packet>>(); private static Map<Byte, Class<? extends Packet>> packetTypes = new HashMap<Byte, Class<? extends Packet>>();
public static Packet constructPacket(byte[] data) { public static Packet constructPacket(byte[] data) {
if (!packetTypes.containsKey(data[0])) 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 { try {
Packet p = packetTypes.get(data[0]).newInstance(); Packet p = packetTypes.get(data[0]).newInstance();
ByteBuffer dataBuffer = new ByteBuffer(Arrays.copyOfRange(data, 5, data.length), CHARSET); 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"); throw new PacketException("erreur lors de la construction du packet");
} }
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")
private static <T extends Packet> void addPacket(Class<T> packetClass) { private static <T extends Packet> void addPacket(Class<T> packetClass) {
try { try {
Packet p = (Packet)packetClass.newInstance(); Packet p = packetClass.newInstance();
packetTypes.put(p.code, packetClass); packetTypes.put(p.code, packetClass);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
static { static {
/* /*
* Ajout des types de packets (client + serveur) * Ajout des types de packets (client + serveur)
*/ */
// addPacket(PacketToto.class); // addPacket(PacketToto.class);
} }
} }

View File

@ -5,10 +5,9 @@ package fr.pandacube.java.util.network.packet;
* une connexion Client vers une connexion Serveur (d'un point de vue TCP) * une connexion Client vers une connexion Serveur (d'un point de vue TCP)
*/ */
public abstract class PacketClient extends Packet { public abstract class PacketClient extends Packet {
public PacketClient(byte c) { public PacketClient(byte c) {
super(c); super(c);
} }
} }

View File

@ -6,11 +6,11 @@ public class PacketException extends RuntimeException {
public PacketException(String m) { public PacketException(String m) {
super(m); super(m);
} }
public PacketException(String m, Throwable t) { public PacketException(String m, Throwable t) {
super(m, t); super(m, t);
} }
public PacketException(Throwable t) { public PacketException(Throwable t) {
super(t); super(t);
} }

View File

@ -9,5 +9,5 @@ public abstract class PacketServer extends Packet {
public PacketServer(byte c) { public PacketServer(byte c) {
super(c); super(c);
} }
} }

View File

@ -6,24 +6,24 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
public class ByteBuffer implements Cloneable { public class ByteBuffer implements Cloneable {
private java.nio.ByteBuffer buff; private java.nio.ByteBuffer buff;
private Charset charset; private Charset charset;
public ByteBuffer(Charset c) { public ByteBuffer(Charset c) {
this(16, c); this(16, c);
} }
public ByteBuffer(int initSize, Charset c) { public ByteBuffer(int initSize, Charset c) {
buff = java.nio.ByteBuffer.allocate(initSize); buff = java.nio.ByteBuffer.allocate(initSize);
charset = c; charset = c;
} }
public ByteBuffer(byte[] data, Charset c) { public ByteBuffer(byte[] data, Charset c) {
buff = java.nio.ByteBuffer.wrap(Arrays.copyOf(data, data.length)); buff = java.nio.ByteBuffer.wrap(Arrays.copyOf(data, data.length));
charset = c; charset = c;
} }
private void askForBufferExtension(int needed) { private void askForBufferExtension(int needed) {
if (buff.remaining() >= needed) return; if (buff.remaining() >= needed) return;
java.nio.ByteBuffer newBuff = java.nio.ByteBuffer.wrap(Arrays.copyOf(buff.array(), buff.array().length * 2)); 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[]) * @see java.nio.ByteBuffer#put(byte[])
*/ */
public ByteBuffer putBytes(byte[] b) { public ByteBuffer putBytes(byte[] b) {
askForBufferExtension(b.length*Byte.BYTES); askForBufferExtension(b.length * Byte.BYTES);
buff.put(b); buff.put(b);
return this; return this;
} }
@ -185,21 +185,21 @@ public class ByteBuffer implements Cloneable {
public int capacity() { public int capacity() {
return buff.capacity(); return buff.capacity();
} }
public ByteBuffer putString(String s) { public ByteBuffer putString(String s) {
byte[] charBytes = s.getBytes(charset); byte[] charBytes = s.getBytes(charset);
putInt(charBytes.length); putInt(charBytes.length);
putBytes(charBytes); putBytes(charBytes);
return this; return this;
} }
public String getString() { public String getString() {
return new String(getBytes(new byte[getInt()]), charset); return new String(getBytes(new byte[getInt()]), charset);
} }
/** /**
* The objet will be serialized and the data put in the current buffer * The objet will be serialized and the data put in the current buffer
*
* @param obj the object to serialize * @param obj the object to serialize
* @return the current buffer * @return the current buffer
*/ */
@ -207,11 +207,14 @@ public class ByteBuffer implements Cloneable {
obj.serializeToByteBuffer(this); obj.serializeToByteBuffer(this);
return 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 <T> * @param <T>
* @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 * @return obj a reference to the same object
*/ */
public <T extends ByteSerializable> T getObject(Class<T> clazz) { public <T extends ByteSerializable> T getObject(Class<T> clazz) {
@ -223,32 +226,27 @@ public class ByteBuffer implements Cloneable {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
public ByteBuffer putListObject(List<ByteSerializable> list) { public ByteBuffer putListObject(List<ByteSerializable> list) {
putInt(list.size()); putInt(list.size());
for (ByteSerializable obj : list) for (ByteSerializable obj : list)
putObject(obj); putObject(obj);
return this; return this;
} }
public <T extends ByteSerializable> List<T> getListObject(Class<T> clazz) { public <T extends ByteSerializable> List<T> getListObject(Class<T> clazz) {
List<T> list = new ArrayList<T>(); List<T> list = new ArrayList<T>();
int size = getInt(); int size = getInt();
for (int i=0; i<size; i++) { for (int i = 0; i < size; i++)
list.add(getObject(clazz)); list.add(getObject(clazz));
}
return list; return list;
} }
/** /**
* @see java.nio.ByteBuffer#array() * @see java.nio.ByteBuffer#array()
*/ */
public byte[] array() { public byte[] array() {
return buff.array(); return buff.array();
} }
} }

View File

@ -1,17 +1,19 @@
package fr.pandacube.java.util.network.packet.bytebuffer; package fr.pandacube.java.util.network.packet.bytebuffer;
/** /**
* Cette interface permet à un {@link ByteBuffer} de sérialiser sous forme de données binaire * Cette interface permet à un {@link ByteBuffer} de sérialiser sous forme de
* données binaire
* les attributs de la classe courante.<br/> * les attributs de la classe courante.<br/>
* <br/> * <br/>
* 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 * lors de la désérialisation
* *
*/ */
public interface ByteSerializable { public interface ByteSerializable {
public void serializeToByteBuffer(ByteBuffer buffer); public void serializeToByteBuffer(ByteBuffer buffer);
public void deserializeFromByteBuffer(ByteBuffer buffer); public void deserializeFromByteBuffer(ByteBuffer buffer);
} }

View File

@ -7,54 +7,44 @@ import java.util.List;
import fr.pandacube.java.util.network.server.TCPServer.TCPServerClientConnection; import fr.pandacube.java.util.network.server.TCPServer.TCPServerClientConnection;
public class BandwidthCalculation { public class BandwidthCalculation {
private List<PacketStat> packetHistory = new LinkedList<PacketStat>(); private List<PacketStat> packetHistory = new LinkedList<PacketStat>();
public synchronized void addPacket(TCPServerClientConnection co, boolean in, long size) { public synchronized void addPacket(TCPServerClientConnection co, boolean in, long size) {
packetHistory.add(new PacketStat(co, in, size)); packetHistory.add(new PacketStat(co, in, size));
} }
/** /**
* Get the instant bandwith in byte/s * 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 * @return
*/ */
public synchronized long getBandWidth(Boolean input, TCPServerClientConnection co) { public synchronized long getBandWidth(Boolean input, TCPServerClientConnection co) {
long currentTime = System.currentTimeMillis(); long currentTime = System.currentTimeMillis();
Iterator<PacketStat> it = packetHistory.iterator(); Iterator<PacketStat> it = packetHistory.iterator();
long sum = 0; long sum = 0;
while(it.hasNext()) { while (it.hasNext()) {
PacketStat el = it.next(); PacketStat el = it.next();
if (el.time < currentTime - 1000) { if (el.time < currentTime - 1000) {
it.remove(); it.remove();
continue; continue;
} }
if (input != null && el.input != input.booleanValue()) if (input != null && el.input != input.booleanValue()) continue;
continue; if (co != null && !co.equals(el.connection)) continue;
if (co != null && !co.equals(el.connection))
continue;
sum += el.packetSize; sum += el.packetSize;
} }
return sum; return sum;
} }
private class PacketStat { private class PacketStat {
public final long time; public final long time;
public final long packetSize; public final long packetSize;
public final boolean input; public final boolean input;
public final TCPServerClientConnection connection; public final TCPServerClientConnection connection;
public PacketStat(TCPServerClientConnection co, boolean input, long size) { public PacketStat(TCPServerClientConnection co, boolean input, long size) {
time = System.currentTimeMillis(); time = System.currentTimeMillis();
packetSize = size; packetSize = size;

View File

@ -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.PacketServer;
import fr.pandacube.java.util.network.packet.bytebuffer.ByteBuffer; import fr.pandacube.java.util.network.packet.bytebuffer.ByteBuffer;
/** /**
* *
* @author Marc Baloup * @author Marc Baloup
* *
*/ */
public class TCPServer extends Thread implements Closeable { public class TCPServer extends Thread implements Closeable {
private static AtomicInteger connectionCounterId = new AtomicInteger(0); private static AtomicInteger connectionCounterId = new AtomicInteger(0);
private ServerSocket socket; private ServerSocket socket;
private TCPServerListener listener; private TCPServerListener listener;
private String socketName; private String socketName;
private List<TCPServerClientConnection> clients = new ArrayList<>(); private List<TCPServerClientConnection> clients = new ArrayList<>();
private AtomicBoolean isClosed = new AtomicBoolean(false); private AtomicBoolean isClosed = new AtomicBoolean(false);
public final BandwidthCalculation bandwidthCalculation = new BandwidthCalculation(); public final BandwidthCalculation bandwidthCalculation = new BandwidthCalculation();
public TCPServer(int port, String sckName, TCPServerListener l) throws IOException { public TCPServer(int port, String sckName, TCPServerListener l) throws IOException {
super("TCPSv "+sckName); super("TCPSv " + sckName);
if (port <= 0 || port > 65535) if (port <= 0 || port > 65535) throw new IllegalArgumentException("le numéro de port est invalide");
throw new IllegalArgumentException("le numéro de port est invalide");
socket = new ServerSocket(); socket = new ServerSocket();
socket.setReceiveBufferSize(Pandacube.NETWORK_TCP_BUFFER_SIZE); socket.setReceiveBufferSize(Pandacube.NETWORK_TCP_BUFFER_SIZE);
socket.setPerformancePreferences(0, 2, 1); socket.setPerformancePreferences(0, 2, 1);
@ -60,51 +53,40 @@ public class TCPServer extends Thread implements Closeable {
listener.onSocketOpen(this); listener.onSocketOpen(this);
socketName = sckName; socketName = sckName;
} }
@Override @Override
public void run() { public void run() {
try { try {
while(true) { while (true) {
Socket socketClient = socket.accept(); Socket socketClient = socket.accept();
socketClient.setSendBufferSize(Pandacube.NETWORK_TCP_BUFFER_SIZE); socketClient.setSendBufferSize(Pandacube.NETWORK_TCP_BUFFER_SIZE);
socketClient.setSoTimeout(Pandacube.NETWORK_TIMEOUT); socketClient.setSoTimeout(Pandacube.NETWORK_TIMEOUT);
try { try {
TCPServerClientConnection co = new TCPServerClientConnection(socketClient, connectionCounterId.getAndIncrement()); TCPServerClientConnection co = new TCPServerClientConnection(socketClient,
connectionCounterId.getAndIncrement());
clients.add(co); clients.add(co);
listener.onClientConnect(this, co); listener.onClientConnect(this, co);
co.start(); co.start();
} catch(IOException e) { } catch (IOException e) {
Log.getLogger().log(Level.SEVERE, "Connexion impossible avec "+socketClient.getInetAddress()); Log.getLogger().log(Level.SEVERE, "Connexion impossible avec " + socketClient.getInetAddress());
} }
} }
} catch (Exception e) { } catch (Exception e) {
Log.getLogger().log(Level.WARNING, "Plus aucune connexion ne peux être acceptée", e); Log.getLogger().log(Level.WARNING, "Plus aucune connexion ne peux être acceptée", e);
} }
} }
public class TCPServerClientConnection extends Thread { public class TCPServerClientConnection extends Thread {
private Socket socket; private Socket socket;
private InputStream in; private InputStream in;
private OutputStream out; private OutputStream out;
private SocketAddress address; private SocketAddress address;
private TCPServerConnectionOutputThread outThread; private TCPServerConnectionOutputThread outThread;
public TCPServerClientConnection(Socket s, int coId) throws IOException { public TCPServerClientConnection(Socket s, int coId) throws IOException {
super("TCPSv "+socketName+" Conn#"+coId+" In"); super("TCPSv " + socketName + " Conn#" + coId + " In");
socket = s; socket = s;
in = socket.getInputStream(); in = socket.getInputStream();
out = socket.getOutputStream(); out = socket.getOutputStream();
@ -113,171 +95,148 @@ public class TCPServer extends Thread implements Closeable {
outThread = new TCPServerConnectionOutputThread(coId); outThread = new TCPServerConnectionOutputThread(coId);
outThread.start(); outThread.start();
} }
@Override @Override
public void run() { public void run() {
try { try {
byte[] code = new byte[1]; byte[] code = new byte[1];
while(!socket.isClosed() && in.read(code) != -1) { while (!socket.isClosed() && in.read(code) != -1) {
byte[] sizeB = new byte[4]; byte[] sizeB = new byte[4];
if (in.read(sizeB) != 4) if (in.read(sizeB) != 4) throw new IOException("Socket " + address + " fermé");
throw new IOException("Socket "+address+" fermé");
int size = new ByteBuffer(sizeB, Packet.CHARSET).getInt(); int size = new ByteBuffer(sizeB, Packet.CHARSET).getInt();
byte[] content = new byte[size]; byte[] content = new byte[size];
forceReadBytes(content); 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); bandwidthCalculation.addPacket(this, true, packetData.length);
try { try {
interpreteReceivedMessage(this, packetData); interpreteReceivedMessage(this, packetData);
} catch (InvalidClientMessage e) { } catch (InvalidClientMessage e) {
Log.getLogger().log(Level.SEVERE, "Erreur protocole de : ", e); Log.getLogger().log(Level.SEVERE, "Erreur protocole de : ", e);
} catch (Exception 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(); e.printStackTrace();
} }
} }
} catch (Exception e) { } 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(); close();
} }
public void send(PacketServer p) { public void send(PacketServer p) {
outThread.addPacket(p); outThread.addPacket(p);
} }
private void forceReadBytes(byte[] buff) throws IOException { private void forceReadBytes(byte[] buff) throws IOException {
int pos = 0; int pos = 0;
do { do {
int nbR = in.read(buff, pos, buff.length-pos); int nbR = in.read(buff, pos, buff.length - pos);
if (nbR == -1) if (nbR == -1) throw new IOException("Can't read required amount of byte");
throw new IOException("Can't read required amount of byte");
pos += nbR; pos += nbR;
} while (pos < buff.length); } while (pos < buff.length);
} }
public void close() { public void close() {
if (socket.isClosed()) return; if (socket.isClosed()) return;
listener.onClientDisconnect(TCPServer.this, this); listener.onClientDisconnect(TCPServer.this, this);
clients.remove(this); clients.remove(this);
try { try {
socket.close(); socket.close();
if (!Thread.currentThread().equals(outThread)) if (!Thread.currentThread().equals(outThread)) send(new PacketServer((byte) 0) {
send(new PacketServer((byte)0){ @Override
@Override public void serializeToByteBuffer(ByteBuffer buffer) {}
public void serializeToByteBuffer( ByteBuffer buffer) {}
@Override @Override
public void deserializeFromByteBuffer( ByteBuffer buffer) {} public void deserializeFromByteBuffer(ByteBuffer buffer) {}
}); });
// provoque une exception dans le thread de sortie, et la termine // provoque une exception dans le thread de sortie, et la
// termine
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
private class TCPServerConnectionOutputThread extends Thread { private class TCPServerConnectionOutputThread extends Thread {
private BlockingQueue<PacketServer> packetQueue = new LinkedBlockingDeque<PacketServer>(); private BlockingQueue<PacketServer> packetQueue = new LinkedBlockingDeque<PacketServer>();
public TCPServerConnectionOutputThread(int coId) { public TCPServerConnectionOutputThread(int coId) {
super("TCPSv "+socketName+" Conn#"+coId+" Out"); super("TCPSv " + socketName + " Conn#" + coId + " Out");
} }
private void addPacket(PacketServer packet) { private void addPacket(PacketServer packet) {
packetQueue.add(packet); packetQueue.add(packet);
} }
@Override @Override
public void run() { public void run() {
try { try {
while (!socket.isClosed()) { while (!socket.isClosed()) {
PacketServer packet = packetQueue.poll(1, TimeUnit.SECONDS); PacketServer packet = packetQueue.poll(1, TimeUnit.SECONDS);
byte[] data; byte[] data;
if (packet != null) { if (packet != null) {
data = packet.getFullSerializedPacket(); data = packet.getFullSerializedPacket();
bandwidthCalculation.addPacket(TCPServerClientConnection.this, false, data.length); bandwidthCalculation.addPacket(TCPServerClientConnection.this, false, data.length);
out.write(data); out.write(data);
out.flush(); out.flush();
} }
} }
} catch (InterruptedException e) { } catch (InterruptedException e) {} catch (IOException e) {}
} catch (IOException e) { }
close(); close();
} }
} }
} }
private void interpreteReceivedMessage(TCPServerClientConnection co, byte[] data) { private void interpreteReceivedMessage(TCPServerClientConnection co, byte[] data) {
Packet p = Packet.constructPacket(data); Packet p = Packet.constructPacket(data);
if (!(p instanceof PacketClient)) if (!(p instanceof PacketClient)) throw new InvalidClientMessage(
throw new InvalidClientMessage("Le type de packet reçu n'est pas un packet attendu : "+p.getClass().getCanonicalName()); "Le type de packet reçu n'est pas un packet attendu : " + p.getClass().getCanonicalName());
PacketClient pc = (PacketClient) p; PacketClient pc = (PacketClient) p;
listener.onPacketReceive(this, co, pc); listener.onPacketReceive(this, co, pc);
} }
@Override @Override
public void close() { public void close() {
try { try {
if (isClosed.get()) return; if (isClosed.get()) return;
clients.forEach(el -> el.close()); clients.forEach(el -> el.close());
socket.close(); socket.close();
isClosed.set(true); isClosed.set(true);
listener.onSocketClose(this); listener.onSocketClose(this);
} catch (IOException e) { } } catch (IOException e) {}
} }
public boolean isClosed() { public boolean isClosed() {
return isClosed.get() || socket.isClosed(); return isClosed.get() || socket.isClosed();
} }
public static class InvalidClientMessage extends RuntimeException { public static class InvalidClientMessage extends RuntimeException {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public InvalidClientMessage(String message) { public InvalidClientMessage(String message) {
super(message); super(message);
} }
} }
} }

View File

@ -4,15 +4,16 @@ import fr.pandacube.java.util.network.packet.PacketClient;
import fr.pandacube.java.util.network.server.TCPServer.TCPServerClientConnection; import fr.pandacube.java.util.network.server.TCPServer.TCPServerClientConnection;
public interface TCPServerListener { public interface TCPServerListener {
public void onSocketOpen(TCPServer svConnection); public void onSocketOpen(TCPServer svConnection);
public void onClientConnect(TCPServer svConnection, TCPServerClientConnection clientConnection); 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 onClientDisconnect(TCPServer svConnection, TCPServerClientConnection clientConnection);
public void onSocketClose(TCPServer svConnection); public void onSocketClose(TCPServer svConnection);
} }

View File

@ -3,29 +3,26 @@ package fr.pandacube.java.util.network_api.client;
import java.io.PrintStream; import java.io.PrintStream;
public abstract class AbstractRequest { public abstract class AbstractRequest {
private final String pass; private final String pass;
private String command; private String command;
private String data; private String data;
protected AbstractRequest(String cmd, String p) { protected AbstractRequest(String cmd, String p) {
if (cmd == null || cmd.isEmpty()) throw new IllegalArgumentException("Un message doit-être défini"); if (cmd == null || cmd.isEmpty()) throw new IllegalArgumentException("Un message doit-être défini");
command = cmd; command = cmd;
pass = p; pass = p;
} }
protected void setData(String d) { protected void setData(String d) {
if (d == null) d = ""; if (d == null) d = "";
data = d; data = d;
} }
public void sendPacket(PrintStream out) { public void sendPacket(PrintStream out) {
out.print(pass+"\n"); out.print(pass + "\n");
out.print(command+"\n"); out.print(command + "\n");
out.print(data.getBytes().length+"\n"); out.print(data.getBytes().length + "\n");
out.print(data); out.print(data);
out.flush(); out.flush();
} }

View File

@ -9,20 +9,17 @@ public class NetworkAPISender {
public static ResponseAnalyser sendRequest(InetSocketAddress cible, AbstractRequest request) throws IOException { public static ResponseAnalyser sendRequest(InetSocketAddress cible, AbstractRequest request) throws IOException {
Socket s = new Socket(cible.getAddress(), cible.getPort()); Socket s = new Socket(cible.getAddress(), cible.getPort());
PrintStream out = new PrintStream(s.getOutputStream()); PrintStream out = new PrintStream(s.getOutputStream());
request.sendPacket(out); request.sendPacket(out);
s.shutdownOutput(); s.shutdownOutput();
ResponseAnalyser response = new ResponseAnalyser(s); ResponseAnalyser response = new ResponseAnalyser(s);
s.close(); s.close();
return response; return response;
} }
} }

View File

@ -7,57 +7,47 @@ import java.net.Socket;
public class ResponseAnalyser { 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 boolean good;
public final String data; public final String data;
public ResponseAnalyser(Socket socket) throws IOException { 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 // on lis la réponse
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line; String line;
// lecture de la première ligne // lecture de la première ligne
line = in.readLine(); line = in.readLine();
good = line.equalsIgnoreCase("OK"); good = line.equalsIgnoreCase("OK");
// lecture de la deuxième ligne // lecture de la deuxième ligne
line = in.readLine(); line = in.readLine();
int data_size = 0; int data_size = 0;
try { try {
data_size = Integer.parseInt(line); 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 // lecture du reste
StringBuilder sB_data = new StringBuilder(); StringBuilder sB_data = new StringBuilder();
char[] c = new char[100]; char[] c = new char[100];
int nbC = 0; int nbC = 0;
while((nbC = in.read(c)) != -1) while ((nbC = in.read(c)) != -1)
sB_data.append(c, 0, nbC); sB_data.append(c, 0, nbC);
data = sB_data.toString(); data = sB_data.toString();
if (data.getBytes().length != data_size) if (data.getBytes().length != data_size) throw new RuntimeException("Réponse mal formée : " + 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."); + " caractères annoncée dans la requête, mais " + data.getBytes().length + " s'y trouvent.");
} }
} }

View File

@ -7,40 +7,35 @@ import java.net.Socket;
public abstract class AbstractRequestExecutor { public abstract class AbstractRequestExecutor {
public final String command; public final String command;
public AbstractRequestExecutor(String cmd, NetworkAPIListener napiListener) { public AbstractRequestExecutor(String cmd, NetworkAPIListener napiListener) {
command = cmd.toLowerCase(); command = cmd.toLowerCase();
napiListener.registerRequestExecutor(command, this); napiListener.registerRequestExecutor(command, this);
} }
public void execute(String data, Socket socket) throws IOException { 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 { try {
Response rep = run(socket.getInetAddress(), data); Response rep = run(socket.getInetAddress(), data);
rep.sendPacket(new PrintStream(socket.getOutputStream())); rep.sendPacket(new PrintStream(socket.getOutputStream()));
} catch(Exception e) { } catch (Exception e) {
new Response(false, e.toString()).sendPacket(new PrintStream(socket.getOutputStream())); new Response(false, e.toString()).sendPacket(new PrintStream(socket.getOutputStream()));
e.printStackTrace(); 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 * @return La réponse à retourner au client
*/ */
protected abstract Response run(InetAddress source, String data); protected abstract Response run(InetAddress source, String data);
} }

View File

@ -2,12 +2,13 @@ package fr.pandacube.java.util.network_api.server;
/** /**
* Interface permettant de gérer l'exécution asynchrone d'un PacketExecutor. * Interface permettant de gérer l'exécution asynchrone d'un PacketExecutor.
*
* @author Marc Baloup * @author Marc Baloup
* *
*/ */
@FunctionalInterface @FunctionalInterface
public interface NAPIExecutionHandler { public interface NAPIExecutionHandler {
public void handleRun(Runnable executor); public void handleRun(Runnable executor);
} }

View File

@ -7,32 +7,22 @@ import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
public class NetworkAPIListener implements Runnable { public class NetworkAPIListener implements Runnable {
private int port = 0; private int port = 0;
String pass; String pass;
private ServerSocket serverSocket; private ServerSocket serverSocket;
private HashMap<String, AbstractRequestExecutor> requestExecutors = new HashMap<String, AbstractRequestExecutor>(); private HashMap<String, AbstractRequestExecutor> requestExecutors = new HashMap<String, AbstractRequestExecutor>();
private String name; private String name;
private NAPIExecutionHandler nAPIExecutionHandler; private NAPIExecutionHandler nAPIExecutionHandler;
/** /**
* Instencie le côté serveur du NetworkAPI * Instencie le côté serveur du NetworkAPI
*
* @param n nom du networkAPI (permet l'identification dans les logs) * @param n nom du networkAPI (permet l'identification dans les logs)
* @param p le port d'écoute * @param p le port d'écoute
* @param pa le mot de passe réseau * @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) { public NetworkAPIListener(String n, int p, String pa, NAPIExecutionHandler peh) {
port = p; port = p;
@ -40,8 +30,7 @@ public class NetworkAPIListener implements Runnable {
name = n; name = n;
nAPIExecutionHandler = peh; nAPIExecutionHandler = peh;
} }
@Override @Override
public void run() { public void run() {
synchronized (this) { synchronized (this) {
@ -52,74 +41,51 @@ public class NetworkAPIListener implements Runnable {
return; return;
} }
} }
System.out.println("NetworkAPI '" + name + "' à l'écoute sur le port " + port);
System.out.println("NetworkAPI '"+name+"' à l'écoute sur le port "+port);
try { try {
// réception des connexion client // réception des connexion client
while (!serverSocket.isClosed()) { while (!serverSocket.isClosed()) {
Socket socketClient = serverSocket.accept(); Socket socketClient = serverSocket.accept();
nAPIExecutionHandler.handleRun(new PacketExecutor(socketClient, this)); nAPIExecutionHandler.handleRun(new PacketExecutor(socketClient, this));
} }
} catch(IOException e) { } } catch (IOException e) {}
synchronized (this) { synchronized (this) {
try { try {
if (!serverSocket.isClosed()) if (!serverSocket.isClosed()) serverSocket.close();
serverSocket.close(); } catch (IOException e) {}
} 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() { public synchronized void closeServerSocket() {
if (serverSocket != null) if (serverSocket != null) try {
{ serverSocket.close();
try { } catch (IOException e) {}
serverSocket.close(); }
} catch (IOException e) { }
} public int getPort() {
return port;
} }
public int getPort() { return port; }
public void registerRequestExecutor(String command, AbstractRequestExecutor executor) { public void registerRequestExecutor(String command, AbstractRequestExecutor executor) {
requestExecutors.put(command, executor); requestExecutors.put(command, executor);
} }
public AbstractRequestExecutor getRequestExecutor(String command) { public AbstractRequestExecutor getRequestExecutor(String command) {
return requestExecutors.get(command); return requestExecutors.get(command);
} }
public String getCommandList() { public String getCommandList() {
return Arrays.toString(requestExecutors.keySet().toArray()); return Arrays.toString(requestExecutors.keySet().toArray());
} }
} }

View File

@ -6,51 +6,50 @@ import java.net.Socket;
import fr.pandacube.java.util.Log; import fr.pandacube.java.util.Log;
/** /**
* Prends en charge un socket client et le transmet au gestionnaire de paquet correspondant.<br/> * Prends en charge un socket client et le transmet au gestionnaire de paquet
* La connexion est fermée après chaque requête du client (règle pouvant évoluer) * correspondant.<br/>
* La connexion est fermée après chaque requête du client (règle pouvant
* évoluer)
*
* @author Marc Baloup * @author Marc Baloup
* *
*/ */
public class PacketExecutor implements Runnable { public class PacketExecutor implements Runnable {
private Socket socket; private Socket socket;
private NetworkAPIListener networkAPIListener; private NetworkAPIListener networkAPIListener;
public PacketExecutor(Socket s, NetworkAPIListener napiListener) { public PacketExecutor(Socket s, NetworkAPIListener napiListener) {
socket = s; socket = s;
networkAPIListener = napiListener; networkAPIListener = napiListener;
} }
@Override @Override
public void run() { public void run() {
try { try {
// analyse de la requête // analyse de la requête
RequestAnalyser analyse = new RequestAnalyser(socket, networkAPIListener); RequestAnalyser analyse = new RequestAnalyser(socket, networkAPIListener);
AbstractRequestExecutor executor = networkAPIListener.getRequestExecutor(analyse.command); AbstractRequestExecutor executor = networkAPIListener.getRequestExecutor(analyse.command);
executor.execute(analyse.data, socket); executor.execute(analyse.data, socket);
} catch (Throwable e) {
} catch(Throwable e) {
Response rep = new Response(); Response rep = new Response();
rep.good = false; rep.good = false;
rep.data = e.toString(); rep.data = e.toString();
try { try {
rep.sendPacket(new PrintStream(socket.getOutputStream())); rep.sendPacket(new PrintStream(socket.getOutputStream()));
} catch (IOException e1) { } } catch (IOException e1) {}
if (e instanceof IOException) if (e instanceof IOException) Log.getLogger()
Log.getLogger().warning("Impossible de lire le packet reçu sur le socket "+socket+" : "+e.toString()); .warning("Impossible de lire le packet reçu sur le socket " + socket + " : " + e.toString());
else else
e.printStackTrace(); e.printStackTrace();
} }
try { try {
socket.close(); socket.close();
} catch (Exception e) { } } catch (Exception e) {}
} }
} }

View File

@ -10,75 +10,61 @@ public class RequestAnalyser {
private NetworkAPIListener networkAPIListener; private NetworkAPIListener networkAPIListener;
public final String command; public final String command;
public final String data; public final String data;
public RequestAnalyser(Socket socket, NetworkAPIListener napiListener) throws IOException, BadRequestException { 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; networkAPIListener = napiListener;
// on lis la réponse // on lis la réponse
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line; String line;
// lecture de la première ligne // lecture de la première ligne
line = in.readLine(); line = in.readLine();
if (line == null || !line.equals(networkAPIListener.pass)) if (line == null || !line.equals(networkAPIListener.pass)) throw new BadRequestException("wrong_password");
throw new BadRequestException("wrong_password");
// lecture de la deuxième ligne // lecture de la deuxième ligne
line = in.readLine(); line = in.readLine();
if (line == null || networkAPIListener.getRequestExecutor(line) == null) if (line == null || networkAPIListener.getRequestExecutor(line) == null)
throw new BadRequestException("command_not_exists"); throw new BadRequestException("command_not_exists");
command = line; command = line;
// lecture de la troisième ligne // lecture de la troisième ligne
line = in.readLine(); line = in.readLine();
int data_size = 0; int data_size = 0;
try { try {
data_size = Integer.parseInt(line); 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 // lecture du reste
StringBuilder sB_data = new StringBuilder(); StringBuilder sB_data = new StringBuilder();
char[] c = new char[100]; char[] c = new char[100];
int nbC = 0; int nbC = 0;
while((nbC = in.read(c)) != -1) while ((nbC = in.read(c)) != -1)
sB_data.append(c, 0, nbC); sB_data.append(c, 0, nbC);
data = sB_data.toString(); data = sB_data.toString();
if (data.getBytes().length != data_size) if (data.getBytes().length != data_size) throw new BadRequestException("wrong_data_size");
throw new BadRequestException("wrong_data_size");
socket.shutdownInput(); socket.shutdownInput();
} }
public class BadRequestException extends Exception { public class BadRequestException extends Exception {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public BadRequestException(String message) { public BadRequestException(String message) {
super(message); super(message);
} }
} }
} }

View File

@ -5,27 +5,24 @@ import java.io.PrintStream;
public class Response { public class Response {
public boolean good = true; public boolean good = true;
public String data = ""; public String data = "";
public Response(boolean good, String data) { public Response(boolean good, String data) {
this.good = good; this.good = good;
this.data = data; this.data = data;
} }
/** /**
* Construit une réponse positive avec aucune donnée. Équivaut à * Construit une réponse positive avec aucune donnée. Équivaut à
* <code>new Response(true, "")</code> * <code>new Response(true, "")</code>
*/ */
public Response() { public Response() {}
}
public void sendPacket(PrintStream out) { public void sendPacket(PrintStream out) {
if (data == null) data = ""; if (data == null) data = "";
out.print((good?"OK":"ERROR")+"\n"); out.print((good ? "OK" : "ERROR") + "\n");
out.print(data.getBytes().length+"\n"); out.print(data.getBytes().length + "\n");
out.print(data); out.print(data);
out.flush(); out.flush();
} }

View File

@ -8,78 +8,75 @@ import java.util.Map;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public enum ChatColor { public enum ChatColor {
BLACK('0', "black"), BLACK('0', "black"),
DARK_BLUE('1', "dark_blue"), DARK_BLUE('1', "dark_blue"),
DARK_GREEN('2', "dark_green"), DARK_GREEN('2', "dark_green"),
DARK_AQUA('3', "dark_aqua"), DARK_AQUA('3', "dark_aqua"),
DARK_RED('4', "dark_red"), DARK_RED('4', "dark_red"),
DARK_PURPLE('5', "dark_purple"), DARK_PURPLE('5', "dark_purple"),
GOLD('6', "gold"), GOLD('6', "gold"),
GRAY('7', "gray"), GRAY('7', "gray"),
DARK_GRAY('8', "dark_gray"), DARK_GRAY('8', "dark_gray"),
BLUE('9', "blue"), BLUE('9', "blue"),
GREEN('a', "green"), GREEN('a', "green"),
AQUA('b', "aqua"), AQUA('b', "aqua"),
RED('c', "red"), RED('c', "red"),
LIGHT_PURPLE('d', "light_purple"), LIGHT_PURPLE('d', "light_purple"),
YELLOW('e', "yellow"), YELLOW('e', "yellow"),
WHITE('f', "white"), WHITE('f', "white"),
MAGIC('k', "obfuscated"), MAGIC('k', "obfuscated"),
BOLD('l', "bold"), BOLD('l', "bold"),
STRIKETHROUGH('m', "strikethrough"), STRIKETHROUGH('m', "strikethrough"),
UNDERLINE('n', "underline"), UNDERLINE('n', "underline"),
ITALIC('o', "italic"), ITALIC('o', "italic"),
RESET('r', "reset"); 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<Character, ChatColor> BY_CHAR;
private final char code;
private final String toString;
private final String name;
private ChatColor(char code, String name) { public static final char COLOR_CHAR = '\u00a7';
this.code = code; public static final String ALL_CODES = "0123456789AaBbCcDdEeFfKkLlMmNnOoRr";
this.name = name; public static final Pattern STRIP_COLOR_PATTERN;
this.toString = new String(new char[]{'\u00a7', code}); private static final Map<Character, ChatColor> BY_CHAR;
} private final char code;
private final String toString;
private final String name;
public String toString() { private ChatColor(char code, String name) {
return this.toString; this.code = code;
} this.name = name;
toString = new String(new char[] { '\u00a7', code });
}
public static String stripColor(String input) { @Override
if (input == null) { public String toString() {
return null; return toString;
} }
return STRIP_COLOR_PATTERN.matcher(input).replaceAll("");
}
public static String translateAlternateColorCodes(char altColorChar, String textToTranslate) { public static String stripColor(String input) {
char[] b2 = textToTranslate.toCharArray(); if (input == null) return null;
for (int i = 0; i < b2.length - 1; ++i) { return STRIP_COLOR_PATTERN.matcher(input).replaceAll("");
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 ChatColor getByChar(char code) { public static String translateAlternateColorCodes(char altColorChar, String textToTranslate) {
return BY_CHAR.get(Character.valueOf(code)); 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() { public static ChatColor getByChar(char code) {
return this.name; return BY_CHAR.get(Character.valueOf(code));
} }
static { public String getName() {
STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + String.valueOf('\u00a7') + "[0-9A-FK-OR]"); return name;
BY_CHAR = new HashMap<Character, ChatColor>(); }
for (ChatColor colour : ChatColor.values()) {
BY_CHAR.put(Character.valueOf(colour.code), colour); static {
} STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + String.valueOf('\u00a7') + "[0-9A-FK-OR]");
} BY_CHAR = new HashMap<Character, ChatColor>();
for (ChatColor colour : ChatColor.values())
BY_CHAR.put(Character.valueOf(colour.code), colour);
}
} }

View File

@ -4,12 +4,7 @@
package net.md_5.bungee.api; package net.md_5.bungee.api;
public enum ChatMessageType { public enum ChatMessageType {
CHAT, CHAT, SYSTEM, ACTION_BAR;
SYSTEM,
ACTION_BAR;
private ChatMessageType() { private ChatMessageType() {}
}
} }

View File

@ -5,236 +5,211 @@ package net.md_5.bungee.api.chat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import net.md_5.bungee.api.ChatColor; 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 { public abstract class BaseComponent {
BaseComponent parent; BaseComponent parent;
private ChatColor color; private ChatColor color;
private Boolean bold; private Boolean bold;
private Boolean italic; private Boolean italic;
private Boolean underlined; private Boolean underlined;
private Boolean strikethrough; private Boolean strikethrough;
private Boolean obfuscated; private Boolean obfuscated;
private String insertion; private String insertion;
private List<BaseComponent> extra; private List<BaseComponent> extra;
private ClickEvent clickEvent; private ClickEvent clickEvent;
private HoverEvent hoverEvent; private HoverEvent hoverEvent;
BaseComponent(BaseComponent old) { BaseComponent(BaseComponent old) {
this.setColor(old.getColorRaw()); setColor(old.getColorRaw());
this.setBold(old.isBoldRaw()); setBold(old.isBoldRaw());
this.setItalic(old.isItalicRaw()); setItalic(old.isItalicRaw());
this.setUnderlined(old.isUnderlinedRaw()); setUnderlined(old.isUnderlinedRaw());
this.setStrikethrough(old.isStrikethroughRaw()); setStrikethrough(old.isStrikethroughRaw());
this.setObfuscated(old.isObfuscatedRaw()); setObfuscated(old.isObfuscatedRaw());
this.setInsertion(old.getInsertion()); setInsertion(old.getInsertion());
this.setClickEvent(old.getClickEvent()); setClickEvent(old.getClickEvent());
this.setHoverEvent(old.getHoverEvent()); setHoverEvent(old.getHoverEvent());
if (old.getExtra() != null) { if (old.getExtra() != null) for (BaseComponent component : old.getExtra())
for (BaseComponent component : old.getExtra()) { this.addExtra(component.duplicate());
this.addExtra(component.duplicate()); }
}
}
}
public abstract BaseComponent duplicate(); public abstract BaseComponent duplicate();
public static /* varargs */ String toLegacyText(BaseComponent ... components) { public static /* varargs */ String toLegacyText(BaseComponent... components) {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
for (BaseComponent msg : components) { for (BaseComponent msg : components)
builder.append(msg.toLegacyText()); builder.append(msg.toLegacyText());
} return builder.toString();
return builder.toString(); }
}
public static /* varargs */ String toPlainText(BaseComponent ... components) { public static /* varargs */ String toPlainText(BaseComponent... components) {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
for (BaseComponent msg : components) { for (BaseComponent msg : components)
builder.append(msg.toPlainText()); builder.append(msg.toPlainText());
} return builder.toString();
return builder.toString(); }
}
public ChatColor getColor() { public ChatColor getColor() {
if (this.color == null) { if (color == null) {
if (this.parent == null) { if (parent == null) return ChatColor.WHITE;
return ChatColor.WHITE; return parent.getColor();
} }
return this.parent.getColor(); return color;
} }
return this.color;
}
public ChatColor getColorRaw() { public ChatColor getColorRaw() {
return this.color; return color;
} }
public boolean isBold() { public boolean isBold() {
if (this.bold == null) { if (bold == null) return parent != null && parent.isBold();
return this.parent != null && this.parent.isBold(); return bold;
} }
return this.bold;
}
public Boolean isBoldRaw() { public Boolean isBoldRaw() {
return this.bold; return bold;
} }
public boolean isItalic() { public boolean isItalic() {
if (this.italic == null) { if (italic == null) return parent != null && parent.isItalic();
return this.parent != null && this.parent.isItalic(); return italic;
} }
return this.italic;
}
public Boolean isItalicRaw() { public Boolean isItalicRaw() {
return this.italic; return italic;
} }
public boolean isUnderlined() { public boolean isUnderlined() {
if (this.underlined == null) { if (underlined == null) return parent != null && parent.isUnderlined();
return this.parent != null && this.parent.isUnderlined(); return underlined;
} }
return this.underlined;
}
public Boolean isUnderlinedRaw() { public Boolean isUnderlinedRaw() {
return this.underlined; return underlined;
} }
public boolean isStrikethrough() { public boolean isStrikethrough() {
if (this.strikethrough == null) { if (strikethrough == null) return parent != null && parent.isStrikethrough();
return this.parent != null && this.parent.isStrikethrough(); return strikethrough;
} }
return this.strikethrough;
}
public Boolean isStrikethroughRaw() { public Boolean isStrikethroughRaw() {
return this.strikethrough; return strikethrough;
} }
public boolean isObfuscated() { public boolean isObfuscated() {
if (this.obfuscated == null) { if (obfuscated == null) return parent != null && parent.isObfuscated();
return this.parent != null && this.parent.isObfuscated(); return obfuscated;
} }
return this.obfuscated;
}
public Boolean isObfuscatedRaw() { public Boolean isObfuscatedRaw() {
return this.obfuscated; return obfuscated;
} }
public void setExtra(List<BaseComponent> components) { public void setExtra(List<BaseComponent> components) {
for (BaseComponent component : components) { for (BaseComponent component : components)
component.parent = this; component.parent = this;
} extra = components;
this.extra = components; }
}
public void addExtra(String text) { public void addExtra(String text) {
this.addExtra(new TextComponent(text)); this.addExtra(new TextComponent(text));
} }
public void addExtra(BaseComponent component) { public void addExtra(BaseComponent component) {
if (this.extra == null) { if (extra == null) extra = new ArrayList<BaseComponent>();
this.extra = new ArrayList<BaseComponent>(); component.parent = this;
} extra.add(component);
component.parent = this; }
this.extra.add(component);
}
public boolean hasFormatting() { 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; return color != null || bold != null || italic != null || underlined != null || strikethrough != null
} || obfuscated != null || hoverEvent != null || clickEvent != null;
}
public String toPlainText() { public String toPlainText() {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
this.toPlainText(builder); this.toPlainText(builder);
return builder.toString(); return builder.toString();
} }
void toPlainText(StringBuilder builder) { void toPlainText(StringBuilder builder) {
if (this.extra != null) { if (extra != null) for (BaseComponent e2 : extra)
for (BaseComponent e2 : this.extra) { e2.toPlainText(builder);
e2.toPlainText(builder); }
}
}
}
public String toLegacyText() { public String toLegacyText() {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
this.toLegacyText(builder); this.toLegacyText(builder);
return builder.toString(); return builder.toString();
} }
void toLegacyText(StringBuilder builder) { void toLegacyText(StringBuilder builder) {
if (this.extra != null) { if (extra != null) for (BaseComponent e2 : extra)
for (BaseComponent e2 : this.extra) { e2.toLegacyText(builder);
e2.toLegacyText(builder); }
}
}
}
public void setColor(ChatColor color) { public void setColor(ChatColor color) {
this.color = color; this.color = color;
} }
public void setBold(Boolean bold) { public void setBold(Boolean bold) {
this.bold = bold; this.bold = bold;
} }
public void setItalic(Boolean italic) { public void setItalic(Boolean italic) {
this.italic = italic; this.italic = italic;
} }
public void setUnderlined(Boolean underlined) { public void setUnderlined(Boolean underlined) {
this.underlined = underlined; this.underlined = underlined;
} }
public void setStrikethrough(Boolean strikethrough) { public void setStrikethrough(Boolean strikethrough) {
this.strikethrough = strikethrough; this.strikethrough = strikethrough;
} }
public void setObfuscated(Boolean obfuscated) { public void setObfuscated(Boolean obfuscated) {
this.obfuscated = obfuscated; this.obfuscated = obfuscated;
} }
public void setInsertion(String insertion) { public void setInsertion(String insertion) {
this.insertion = insertion; this.insertion = insertion;
} }
public void setClickEvent(ClickEvent clickEvent) { public void setClickEvent(ClickEvent clickEvent) {
this.clickEvent = clickEvent; this.clickEvent = clickEvent;
} }
public void setHoverEvent(HoverEvent hoverEvent) { public void setHoverEvent(HoverEvent hoverEvent) {
this.hoverEvent = hoverEvent; this.hoverEvent = hoverEvent;
} }
public String toString() { @Override
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() + ")"; 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() { public String getInsertion() {
return this.insertion; return insertion;
} }
public List<BaseComponent> getExtra() { public List<BaseComponent> getExtra() {
return this.extra; return extra;
} }
public ClickEvent getClickEvent() { public ClickEvent getClickEvent() {
return this.clickEvent; return clickEvent;
} }
public HoverEvent getHoverEvent() { public HoverEvent getHoverEvent() {
return this.hoverEvent; return hoverEvent;
} }
} }

View File

@ -6,38 +6,32 @@ package net.md_5.bungee.api.chat;
import java.beans.ConstructorProperties; import java.beans.ConstructorProperties;
public final class ClickEvent { public final class ClickEvent {
private final Action action; private final Action action;
private final String value; private final String value;
public Action getAction() { public Action getAction() {
return this.action; return action;
} }
public String getValue() { public String getValue() {
return this.value; return value;
} }
public String toString() { @Override
return "ClickEvent(action=" + (Object)((Object)this.getAction()) + ", value=" + this.getValue() + ")"; public String toString() {
} return "ClickEvent(action=" + (getAction()) + ", value=" + getValue() + ")";
}
@ConstructorProperties(value={"action", "value"}) @ConstructorProperties(value = { "action", "value" })
public ClickEvent(Action action, String value) { public ClickEvent(Action action, String value) {
this.action = action; this.action = action;
this.value = value; this.value = value;
} }
public static enum Action { public static enum Action {
OPEN_URL, OPEN_URL, OPEN_FILE, RUN_COMMAND, SUGGEST_COMMAND, CHANGE_PAGE;
OPEN_FILE,
RUN_COMMAND,
SUGGEST_COMMAND,
CHANGE_PAGE;
private Action() { private Action() {}
} }
}
} }

View File

@ -5,128 +5,118 @@ package net.md_5.bungee.api.chat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import net.md_5.bungee.api.ChatColor; 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 { public class ComponentBuilder {
private TextComponent current; private TextComponent current;
private final List<BaseComponent> parts = new ArrayList<BaseComponent>(); private final List<BaseComponent> parts = new ArrayList<BaseComponent>();
public ComponentBuilder(ComponentBuilder original) { public ComponentBuilder(ComponentBuilder original) {
this.current = new TextComponent(original.current); current = new TextComponent(original.current);
for (BaseComponent baseComponent : original.parts) { for (BaseComponent baseComponent : original.parts)
this.parts.add(baseComponent.duplicate()); parts.add(baseComponent.duplicate());
} }
}
public ComponentBuilder(String text) { public ComponentBuilder(String text) {
this.current = new TextComponent(text); current = new TextComponent(text);
} }
public ComponentBuilder append(String text) { public ComponentBuilder append(String text) {
return this.append(text, FormatRetention.ALL); return this.append(text, FormatRetention.ALL);
} }
public ComponentBuilder append(String text, FormatRetention retention) { public ComponentBuilder append(String text, FormatRetention retention) {
this.parts.add(this.current); parts.add(current);
this.current = new TextComponent(this.current); current = new TextComponent(current);
this.current.setText(text); current.setText(text);
this.retain(retention); retain(retention);
return this; return this;
} }
public ComponentBuilder color(ChatColor color) { public ComponentBuilder color(ChatColor color) {
this.current.setColor(color); current.setColor(color);
return this; return this;
} }
public ComponentBuilder bold(boolean bold) { public ComponentBuilder bold(boolean bold) {
this.current.setBold(bold); current.setBold(bold);
return this; return this;
} }
public ComponentBuilder italic(boolean italic) { public ComponentBuilder italic(boolean italic) {
this.current.setItalic(italic); current.setItalic(italic);
return this; return this;
} }
public ComponentBuilder underlined(boolean underlined) { public ComponentBuilder underlined(boolean underlined) {
this.current.setUnderlined(underlined); current.setUnderlined(underlined);
return this; return this;
} }
public ComponentBuilder strikethrough(boolean strikethrough) { public ComponentBuilder strikethrough(boolean strikethrough) {
this.current.setStrikethrough(strikethrough); current.setStrikethrough(strikethrough);
return this; return this;
} }
public ComponentBuilder obfuscated(boolean obfuscated) { public ComponentBuilder obfuscated(boolean obfuscated) {
this.current.setObfuscated(obfuscated); current.setObfuscated(obfuscated);
return this; return this;
} }
public ComponentBuilder insertion(String insertion) { public ComponentBuilder insertion(String insertion) {
this.current.setInsertion(insertion); current.setInsertion(insertion);
return this; return this;
} }
public ComponentBuilder event(ClickEvent clickEvent) { public ComponentBuilder event(ClickEvent clickEvent) {
this.current.setClickEvent(clickEvent); current.setClickEvent(clickEvent);
return this; return this;
} }
public ComponentBuilder event(HoverEvent hoverEvent) { public ComponentBuilder event(HoverEvent hoverEvent) {
this.current.setHoverEvent(hoverEvent); current.setHoverEvent(hoverEvent);
return this; return this;
} }
public ComponentBuilder reset() { public ComponentBuilder reset() {
return this.retain(FormatRetention.NONE); return retain(FormatRetention.NONE);
} }
public ComponentBuilder retain(FormatRetention retention) { public ComponentBuilder retain(FormatRetention retention) {
TextComponent previous = this.current; TextComponent previous = current;
switch (retention) { switch (retention) {
case NONE: { case NONE: {
this.current = new TextComponent(this.current.getText()); current = new TextComponent(current.getText());
break; break;
} }
case ALL: { case ALL: {
break; break;
} }
case EVENTS: { case EVENTS: {
this.current = new TextComponent(this.current.getText()); current = new TextComponent(current.getText());
this.current.setInsertion(previous.getInsertion()); current.setInsertion(previous.getInsertion());
this.current.setClickEvent(previous.getClickEvent()); current.setClickEvent(previous.getClickEvent());
this.current.setHoverEvent(previous.getHoverEvent()); current.setHoverEvent(previous.getHoverEvent());
break; break;
} }
case FORMATTING: { case FORMATTING: {
this.current.setClickEvent(null); current.setClickEvent(null);
this.current.setHoverEvent(null); current.setHoverEvent(null);
} }
} }
return this; return this;
} }
public BaseComponent[] create() { public BaseComponent[] create() {
this.parts.add(this.current); parts.add(current);
return this.parts.toArray(new BaseComponent[this.parts.size()]); return parts.toArray(new BaseComponent[parts.size()]);
} }
public static enum FormatRetention { public static enum FormatRetention {
NONE, NONE, FORMATTING, EVENTS, ALL;
FORMATTING,
EVENTS,
ALL;
private FormatRetention() { private FormatRetention() {}
} }
}
} }

Some files were not shown because too many files have changed in this diff Show More