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

@ -4,13 +4,10 @@ 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,31 +1,24 @@
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) if (args.length == 0)
throw new IllegalArgumentException("no argument given. Please give at least one argument."); throw new IllegalArgumentException("no argument given. Please give at least one argument.");
} }
public static UUID getFromNickName(String nickname) public static UUID getFromNickName(String nickname) {
{
String str = "OfflinePlayer:" + nickname; String str = "OfflinePlayer:" + nickname;
byte[] from_str = str.getBytes(Charset.forName("UTF-8")); byte[] from_str = str.getBytes(Charset.forName("UTF-8"));
return UUID.nameUUIDFromBytes(from_str); return UUID.nameUUIDFromBytes(from_str);
} }
public static UUID[] getFromNickName(String[] nicknames) {
if (nicknames == null) 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++)

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,6 +4,7 @@ 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.
@ -14,9 +15,7 @@ public class EnumUtil {
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();
@ -24,10 +23,12 @@ public class EnumUtil {
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.
*/ */
@ -36,7 +37,9 @@ public class EnumUtil {
} }
/** /**
* 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
@ -45,35 +48,36 @@ public class EnumUtil {
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
*/ */

View File

@ -71,13 +71,15 @@ public class JArithmeticInterpreter {
// Methods // Methods
//.................................................................................... Node // ....................................................................................
// Node
private JArithmeticInterpreter() { private JArithmeticInterpreter() {
this(0, 0, null, null); this(0, 0, null, null);
} }
//.................................................................................... Node // ....................................................................................
// Node
private JArithmeticInterpreter(int Operator, double Value, JArithmeticInterpreter Fg, JArithmeticInterpreter Fd) { private JArithmeticInterpreter(int Operator, double Value, JArithmeticInterpreter Fg, JArithmeticInterpreter Fd) {
mOperator = Operator; mOperator = Operator;
@ -90,7 +92,8 @@ public class JArithmeticInterpreter {
this(Operator, Value, null, null); this(Operator, Value, null, null);
} }
//.................................................................................... Construct_Tree // ....................................................................................
// Construct_Tree
private static JArithmeticInterpreter constructTree(StringBuffer string, int length, int error) { private static JArithmeticInterpreter constructTree(StringBuffer string, int length, int error) {
int imbric, Bimbric; int imbric, Bimbric;
@ -110,15 +113,15 @@ public class JArithmeticInterpreter {
} }
ope = 0; ope = 0;
imbric=0;Bimbric=128; imbric = 0;
Bimbric = 128;
priorite = 6; priorite = 6;
i = 0; i = 0;
positionv = position = 0; positionv = position = 0;
// Mise en place des donnees sur le morceau de chaine // Mise en place des donnees sur le morceau de chaine
while (i<length) { while (i < length)
if (((string.charAt(i) > 47) && (string.charAt(i) < 58)) || (string.charAt(i) == '<27>')) { if (((string.charAt(i) > 47) && (string.charAt(i) < 58)) || (string.charAt(i) == '<27>')) {
if (priorite > 5) { if (priorite > 5) {
priorite = 5; priorite = 5;
@ -126,8 +129,7 @@ public class JArithmeticInterpreter {
} }
i++; i++;
} }
else { else if ((string.charAt(i) > 96) && (string.charAt(i) < 117)) {
if ((string.charAt(i)>96) && (string.charAt(i)<117)) {
VariableInt Vopetemp, Vespat; VariableInt Vopetemp, Vespat;
Vopetemp = new VariableInt(); Vopetemp = new VariableInt();
@ -182,7 +184,7 @@ public class JArithmeticInterpreter {
return null; return null;
} }
} }
else { else
switch (string.charAt(i)) { switch (string.charAt(i)) {
case '(': case '(':
imbric++; imbric++;
@ -236,8 +238,7 @@ public class JArithmeticInterpreter {
caspp = 0; caspp = 0;
} }
} }
else if ((imbric==Bimbric) && (priorite>=1)) { else if ((imbric == Bimbric) && (priorite >= 1)) if ((i - 1) < 0) {
if ((i-1)<0) {
if (priorite > 5) { if (priorite > 5) {
priorite = 1; priorite = 1;
position = i; position = i;
@ -259,7 +260,6 @@ public class JArithmeticInterpreter {
position = i; position = i;
caspp = 0; caspp = 0;
} }
}
i++; i++;
break; break;
case '*': case '*':
@ -311,9 +311,6 @@ public class JArithmeticInterpreter {
error = 2; // symbole non reconnu error = 2; // symbole non reconnu
return null; return null;
} }
}
}
}
if (imbric != 0) { if (imbric != 0) {
error = 1; // erreur de "parenthesage" error = 1; // erreur de "parenthesage"
@ -411,14 +408,16 @@ public class JArithmeticInterpreter {
case 7: // ln case 7: // ln
if (valueL <= 0) { if (valueL <= 0) {
if (valueL < 0) error = 2; if (valueL < 0) error = 2;
else error=1; else
error = 1;
return 0; return 0;
} }
return (Math.log(valueL) / Math.log(2)); return (Math.log(valueL) / Math.log(2));
case 8: // log case 8: // log
if (valueL <= 0) { if (valueL <= 0) {
if (valueL < 0) error = 2; if (valueL < 0) error = 2;
else error=1; else
error = 1;
return 0; return 0;
} }
return Math.log(valueL); return Math.log(valueL);
@ -447,7 +446,8 @@ public class JArithmeticInterpreter {
} }
} }
//.................................................................................... Write_Tree // ....................................................................................
// Write_Tree
private void writeTree(StringBuffer string) { private void writeTree(StringBuffer string) {
boolean parenthese = false; boolean parenthese = false;
@ -463,16 +463,15 @@ public class JArithmeticInterpreter {
break; break;
case 2: case 2:
if ((fg.mOperator == 0) && (fg.mValue == 0)) ; if ((fg.mOperator == 0) && (fg.mValue == 0)) ;
else fg.writeTree(string); else
fg.writeTree(string);
string.append('-'); string.append('-');
if ((fd.mOperator == 1) || (fd.mOperator == 2)) { if ((fd.mOperator == 1) || (fd.mOperator == 2)) {
parenthese = true; parenthese = true;
string.append('('); string.append('(');
} }
fd.writeTree(string); fd.writeTree(string);
if (parenthese==true) { if (parenthese == true) string.append(')');
string.append(')');
}
break; break;
case 3: case 3:
if ((fg.mOperator == 1) || (fg.mOperator == 2)) { if ((fg.mOperator == 1) || (fg.mOperator == 2)) {
@ -480,8 +479,7 @@ public class JArithmeticInterpreter {
string.append('('); string.append('(');
} }
fg.writeTree(string); fg.writeTree(string);
if (parenthese==true) if (parenthese == true) string.append(')');
string.append(')');
parenthese = false; parenthese = false;
string.append('*'); string.append('*');
if ((fd.mOperator == 1) || (fd.mOperator == 2)) { if ((fd.mOperator == 1) || (fd.mOperator == 2)) {
@ -489,8 +487,7 @@ public class JArithmeticInterpreter {
string.append('('); string.append('(');
} }
fd.writeTree(string); fd.writeTree(string);
if (parenthese==true) if (parenthese == true) string.append(')');
string.append(')');
break; break;
case 4: case 4:
if ((fg.mOperator == 1) || (fg.mOperator == 2)) { if ((fg.mOperator == 1) || (fg.mOperator == 2)) {
@ -498,8 +495,7 @@ public class JArithmeticInterpreter {
string.append('('); string.append('(');
} }
fg.writeTree(string); fg.writeTree(string);
if (parenthese==true) if (parenthese == true) string.append(')');
string.append(')');
parenthese = false; parenthese = false;
string.append('/'); string.append('/');
if ((fd.mOperator > 0) && (fd.mOperator < 5)) { if ((fd.mOperator > 0) && (fd.mOperator < 5)) {
@ -507,8 +503,7 @@ public class JArithmeticInterpreter {
string.append('('); string.append('(');
} }
fd.writeTree(string); fd.writeTree(string);
if (parenthese==true) if (parenthese == true) string.append(')');
string.append(')');
break; break;
case 5: case 5:
if ((fg.mOperator > 0) && (fg.mOperator < 5)) { if ((fg.mOperator > 0) && (fg.mOperator < 5)) {
@ -516,8 +511,7 @@ public class JArithmeticInterpreter {
string.append('('); string.append('(');
} }
fg.writeTree(string); fg.writeTree(string);
if (parenthese==true) if (parenthese == true) string.append(')');
string.append(')');
parenthese = false; parenthese = false;
string.append('^'); string.append('^');
if ((fd.mOperator > 0) && (fd.mOperator < 5)) { if ((fd.mOperator > 0) && (fd.mOperator < 5)) {
@ -525,8 +519,7 @@ public class JArithmeticInterpreter {
string.append('('); string.append('(');
} }
fd.writeTree(string); fd.writeTree(string);
if (parenthese==true) if (parenthese == true) string.append(')');
string.append(')');
break; break;
case 6: case 6:
string.append("exp("); string.append("exp(");
@ -586,7 +579,8 @@ public class JArithmeticInterpreter {
} }
} }
//.................................................................................... calc_const // ....................................................................................
// calc_const
private static double calc_const(StringBuffer chaine, int pos) { private static double calc_const(StringBuffer chaine, int pos) {
int i = pos, j; int i = pos, j;
@ -594,7 +588,6 @@ public class JArithmeticInterpreter {
int signe = 1; int signe = 1;
int longueur = chaine.length(); int longueur = chaine.length();
if (chaine.charAt(i) == '-') { if (chaine.charAt(i) == '-') {
signe = -1; signe = -1;
i++; i++;
@ -617,7 +610,8 @@ public class JArithmeticInterpreter {
return (signe * temp); return (signe * temp);
} }
//.................................................................................... FindOperator // ....................................................................................
// FindOperator
private static void FindOperator(VariableInt oper, VariableInt esp, StringBuffer chaine, int pos) { private static void FindOperator(VariableInt oper, VariableInt esp, StringBuffer chaine, int pos) {
switch (chaine.charAt(pos)) { switch (chaine.charAt(pos)) {
@ -646,7 +640,7 @@ public class JArithmeticInterpreter {
esp.mValue = 2; esp.mValue = 2;
oper.mValue = 18; oper.mValue = 18;
} }
else if ((chaine.charAt(pos+1)=='o') && (chaine.charAt(pos+2)=='s')) { else if ((chaine.charAt(pos + 1) == 'o') && (chaine.charAt(pos + 2) == 's'))
if (chaine.charAt(pos + 3) == 'h') { if (chaine.charAt(pos + 3) == 'h') {
esp.mValue = 4; esp.mValue = 4;
oper.mValue = 18; oper.mValue = 18;
@ -655,14 +649,14 @@ public class JArithmeticInterpreter {
esp.mValue = 3; esp.mValue = 3;
oper.mValue = 12; oper.mValue = 12;
} }
}
break; break;
case 'e': case 'e':
if ((chaine.charAt(pos + 1) == 'x') && (chaine.charAt(pos + 2) == 'p')) { if ((chaine.charAt(pos + 1) == 'x') && (chaine.charAt(pos + 2) == 'p')) {
esp.mValue = 3; esp.mValue = 3;
oper.mValue = 6; oper.mValue = 6;
} }
else oper.mValue=-10; else
oper.mValue = -10;
break; break;
case 'l': case 'l':
if (chaine.charAt(pos + 1) == 'n') { if (chaine.charAt(pos + 1) == 'n') {
@ -673,7 +667,8 @@ public class JArithmeticInterpreter {
esp.mValue = 3; esp.mValue = 3;
oper.mValue = 8; oper.mValue = 8;
} }
else oper.mValue=-10; else
oper.mValue = -10;
break; break;
case 's': case 's':
if (chaine.charAt(pos + 1) == 'h') { if (chaine.charAt(pos + 1) == 'h') {
@ -684,8 +679,7 @@ public class JArithmeticInterpreter {
esp.mValue = 4; esp.mValue = 4;
oper.mValue = 9; oper.mValue = 9;
} }
else { else if (chaine.charAt(pos + 3) == 'h') {
if (chaine.charAt(pos+3)=='h') {
esp.mValue = 4; esp.mValue = 4;
oper.mValue = 17; oper.mValue = 17;
} }
@ -693,7 +687,6 @@ public class JArithmeticInterpreter {
esp.mValue = 3; esp.mValue = 3;
oper.mValue = 11; oper.mValue = 11;
} }
}
break; break;
case 't': case 't':
if (chaine.charAt(pos + 1) == 'h') { if (chaine.charAt(pos + 1) == 'h') {
@ -710,7 +703,8 @@ public class JArithmeticInterpreter {
oper.mValue = 13; oper.mValue = 13;
} }
} }
else oper.mValue=-10; else
oper.mValue = -10;
break; break;
default: default:
oper.mValue = -10; oper.mValue = -10;
@ -718,21 +712,21 @@ public class JArithmeticInterpreter {
} }
} }
//.................................................................................... CopyPartialString // ....................................................................................
// CopyPartialString
private static StringBuffer CopyPartialString(StringBuffer chaine, int debut, int fin) { private static StringBuffer CopyPartialString(StringBuffer chaine, int debut, int fin) {
StringBuffer chartemp; StringBuffer chartemp;
int a = fin - debut + 1; int a = fin - debut + 1;
chartemp = new StringBuffer(a + 1); chartemp = new StringBuffer(a + 1);
for(int i=0;i<a;i++) chartemp.append(chaine.charAt(debut+i)); for (int i = 0; i < a; i++)
chartemp.append(chaine.charAt(debut + i));
return chartemp; return chartemp;
} }
public static double getResultFromExpression(String expr, StringBuffer writeTree) {
public static double getResultFromExpression(String expr, StringBuffer writeTree)
{
StringBuffer input = new StringBuffer(expr); StringBuffer input = new StringBuffer(expr);
JArithmeticInterpreter jai = null; JArithmeticInterpreter jai = null;
@ -741,11 +735,9 @@ public class JArithmeticInterpreter {
jai = JArithmeticInterpreter.constructTree(input, input.length(), 0); jai = JArithmeticInterpreter.constructTree(input, input.length(), 0);
} catch (Exception e) {} } catch (Exception e) {}
if (jai==null) if (jai == null) throw new IllegalArgumentException("Le calcul passé en paramètre est invalide");
throw new IllegalArgumentException("Le calcul passé en paramètre est invalide");
if (writeTree != null) if (writeTree != null) {
{
writeTree.setLength(0); writeTree.setLength(0);
jai.writeTree(writeTree); jai.writeTree(writeTree);
} }
@ -753,12 +745,10 @@ public class JArithmeticInterpreter {
return jai.computeTree(); return jai.computeTree();
} }
public static double getResultFromExpression(String expr) public static double getResultFromExpression(String expr) {
{
return getResultFromExpression(expr, null); return getResultFromExpression(expr, null);
} }
public static void main(String args[]) { public static void main(String args[]) {
StringBuffer b = new StringBuffer(0); StringBuffer b = new StringBuffer(0);

View File

@ -17,7 +17,6 @@ public class Log {
return logDebug.get(); return logDebug.get();
} }
public static Logger getLogger() { public static Logger getLogger() {
return logger; return logger;
} }

View File

@ -18,15 +18,14 @@ public enum MinecraftVersion {
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;
/* /*
@ -32,22 +32,18 @@ public class PlayerFinder {
} }
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);
} }
@ -56,27 +52,22 @@ public class PlayerFinder {
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);
} }
@ -88,33 +79,32 @@ public class PlayerFinder {
} }
/** /**
* 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);
} }
@ -123,9 +113,10 @@ public class PlayerFinder {
// 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);
} }
@ -135,13 +126,10 @@ public class PlayerFinder {
} }
/** /**
* *
* @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
*/ */
@ -152,45 +140,42 @@ public class PlayerFinder {
// 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;
@ -204,35 +189,20 @@ public class PlayerFinder {
} }
@Override @Override
public int hashCode() { return uuid.hashCode(); } 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

@ -13,8 +13,12 @@ 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).
* <br/>
* <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 * @since 25-3-2016
* @author mine-care (AKA fillpant) * @author mine-care (AKA fillpant)
* *
@ -29,9 +33,13 @@ public class PlayerNameHistoryLookup {
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
* thread!It blocks while attempting to get a response from Mojang servers!
* </h1>
*
* @param player The UUID of the player to be looked up. * @param player The UUID of the player to be looked up.
* @return Returns an array of {@link PreviousPlayerNameEntry} objects, or null if the response couldn't be interpreted. * @return Returns an array of {@link PreviousPlayerNameEntry} objects, or
* null if the response couldn't be interpreted.
* @throws IOException {@link #getPlayerPreviousNames(String)} * @throws IOException {@link #getPlayerPreviousNames(String)}
*/ */
public static PreviousPlayerNameEntry[] getPlayerPreviousNames(UUID player) throws IOException { public static PreviousPlayerNameEntry[] getPlayerPreviousNames(UUID player) throws IOException {
@ -39,15 +47,19 @@ public class PlayerNameHistoryLookup {
} }
/** /**
* <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
* Alternative method accepting an {@link OfflinePlayer} (and therefore {@link Player}) objects as parameter. * thread! It blocks while attempting to get a response from Mojang servers!
* </h1>
* Alternative method accepting an {@link OfflinePlayer} (and therefore
* {@link Player}) objects as parameter.
*
* @param uuid The UUID String to lookup * @param uuid The UUID String to lookup
* @return Returns an array of {@link PreviousPlayerNameEntry} objects, or null if the response couldn't be interpreted. * @return Returns an array of {@link PreviousPlayerNameEntry} objects, or
* null if the response couldn't be interpreted.
* @throws IOException {@link #getRawJsonResponse(String)} * @throws IOException {@link #getRawJsonResponse(String)}
*/ */
public static PreviousPlayerNameEntry[] getPlayerPreviousNames(String uuid) throws IOException { public static PreviousPlayerNameEntry[] getPlayerPreviousNames(String uuid) throws IOException {
if (uuid == null || uuid.isEmpty()) if (uuid == null || uuid.isEmpty()) return null;
return null;
uuid = uuid.replace("-", ""); uuid = uuid.replace("-", "");
String response = getRawJsonResponse(new URL(String.format(LOOKUP_URL, uuid))); String response = getRawJsonResponse(new URL(String.format(LOOKUP_URL, uuid)));
PreviousPlayerNameEntry[] names = JSON_PARSER.fromJson(response, PreviousPlayerNameEntry[].class); PreviousPlayerNameEntry[] names = JSON_PARSER.fromJson(response, PreviousPlayerNameEntry[].class);
@ -55,10 +67,14 @@ public class PlayerNameHistoryLookup {
} }
/** /**
* This is a helper method used to read the response of Mojang's API webservers. * This is a helper method used to read the response of Mojang's API
* webservers.
*
* @param u the URL to connect to * @param u the URL to connect to
* @return a String with the data read. * @return a String with the data read.
* @throws IOException Inherited by {@link BufferedReader#readLine()}, {@link BufferedReader#close()}, {@link URL}, {@link HttpURLConnection#getInputStream()} * @throws IOException Inherited by {@link BufferedReader#readLine()},
* {@link BufferedReader#close()}, {@link URL},
* {@link HttpURLConnection#getInputStream()}
*/ */
private static String getRawJsonResponse(URL u) throws IOException { private static String getRawJsonResponse(URL u) throws IOException {
HttpURLConnection con = (HttpURLConnection) u.openConnection(); HttpURLConnection con = (HttpURLConnection) u.openConnection();
@ -73,7 +89,8 @@ public class PlayerNameHistoryLookup {
} }
/** /**
* This class represents the typical response expected by Mojang servers when requesting the name history of a player. * This class represents the typical response expected by Mojang servers
* when requesting the name history of a player.
*/ */
public class PreviousPlayerNameEntry { public class PreviousPlayerNameEntry {
private String name; private String name;
@ -82,6 +99,7 @@ public class PlayerNameHistoryLookup {
/** /**
* Gets the player name of this entry. * Gets the player name of this entry.
*
* @return The name of the player. * @return The name of the player.
*/ */
public String getPlayerName() { public String getPlayerName() {
@ -90,17 +108,25 @@ public class PlayerNameHistoryLookup {
/** /**
* Get the time of change of the name. * Get the time of change of the 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! * <br>
* <br>Parsing 0 to a Date will result in the date "01/01/1970".</b> * <b>Note: This will return 0 if the name is the original (initial)
* @return a timestamp in miliseconds that you can turn into a date or handle however you want :) * name of the player! Make sure you check if it is 0 before handling!
* <br>
* 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 long getChangeTime() {
return changeTime; return changeTime;
} }
/** /**
* Check if this name is the name used to register the account (the initial/original name) * Check if this name is the name used to register the account (the
* @return a boolean, true if it is the the very first name of the player, otherwise false. * initial/original name)
*
* @return a boolean, true if it is the the very first name of the
* player, otherwise false.
*/ */
public boolean isPlayersInitialName() { public boolean isPlayersInitialName() {
return getChangeTime() == 0; return getChangeTime() == 0;
@ -112,8 +138,6 @@ public class PlayerNameHistoryLookup {
} }
} }
public static void main(String[] args) throws IOException { 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

@ -6,12 +6,10 @@ 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

@ -17,7 +17,6 @@ public class ServerPropertyFile {
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;
@ -31,9 +30,9 @@ public class ServerPropertyFile {
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() {
@ -41,36 +40,28 @@ public class ServerPropertyFile {
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)) if (!dataFile.containsKey("isLobby") || !(dataFile.get("isLobby") instanceof Boolean)) return false;
return false;
data = dataFile; data = dataFile;
return true; return true;
} } catch (IOException e) {
catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} } finally {
finally {
try { try {
in.close(); in.close();
} catch (Exception e) {} } catch (Exception e) {}
@ -78,8 +69,6 @@ public class ServerPropertyFile {
return false; return false;
} }
public boolean save() { public boolean save() {
BufferedWriter out = null; BufferedWriter out = null;
try { try {
@ -94,8 +83,7 @@ public class ServerPropertyFile {
return true; return true;
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} } finally {
finally {
try { try {
out.close(); out.close();
} catch (Exception e) {} } catch (Exception e) {}
@ -104,58 +92,52 @@ public class ServerPropertyFile {
return false; 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);
} }
@ -163,5 +145,4 @@ public class ServerPropertyFile {
data.put("isLobby", l); data.put("isLobby", l);
} }
} }

View File

@ -1,10 +1,8 @@
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)
return String.format("%d",(long)d);
else else
return String.valueOf(d); return String.valueOf(d);
} }
@ -14,13 +12,11 @@ public class StringUtil {
* @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

@ -14,71 +14,66 @@ public class Display {
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 = "";
@ -86,9 +81,6 @@ public class Display {
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,7 +89,8 @@ 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();
@ -155,28 +148,11 @@ public class Display {
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

@ -8,16 +8,18 @@ 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(-6, "§");
put(2, "!.,:;i|¡"); put(2, "!.,:;i|¡");
put(3, "'`lìí"); put(3, "'`lìí");
put(4, " I[]tï×"); put(4, " I[]tï×");
put(5, "\"()*<>fk{}"); put(5, "\"()*<>fk{}");
put(7, "@~®"); put(7, "@~®");
}}; }
};
private static final int defaultChatMaxWidth = 320; private static final int defaultChatMaxWidth = 320;
private static int chatMaxWidth = defaultChatMaxWidth; private static int chatMaxWidth = defaultChatMaxWidth;
@ -29,49 +31,34 @@ public class DisplayUtil {
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 {
@ -85,23 +72,21 @@ public class DisplayUtil {
for (int i = 0; i < count; i++) for (int i = 0; i < count; i++)
finalLeftOrRight += repeatedChar; finalLeftOrRight += repeatedChar;
Display d = new Display().nextComponent(finalLeftOrRight).setColor(decorationColor) Display d = new Display().nextComponent(finalLeftOrRight).setColor(decorationColor).addComponent(text);
.addComponent(text);
if (repeatedChar != ' ') {
d.nextComponent(finalLeftOrRight).setColor(decorationColor);
}
if (repeatedChar != ' ') d.nextComponent(finalLeftOrRight).setColor(decorationColor);
return d.get(); return d.get();
} }
public static BaseComponent leftText(BaseComponent text, char repeatedChar, ChatColor decorationColor, int nbLeft,
public static BaseComponent leftText(BaseComponent text, char repeatedChar, ChatColor decorationColor, int nbLeft, boolean console) { 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();
@ -113,7 +98,6 @@ public class DisplayUtil {
} }
d.addComponent(text); d.addComponent(text);
int count = 0; int count = 0;
String current = finalLeft + text.toPlainText(); String current = finalLeft + text.toPlainText();
do { do {
@ -122,7 +106,6 @@ public class DisplayUtil {
} 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++)
@ -133,11 +116,14 @@ public class DisplayUtil {
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) {
@ -158,9 +144,7 @@ public class DisplayUtil {
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 = "";
@ -182,8 +166,6 @@ public class DisplayUtil {
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())
@ -191,33 +173,29 @@ public class DisplayUtil {
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

@ -11,21 +11,20 @@ public class TextProgressBar {
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;
@ -36,15 +35,12 @@ public class TextProgressBar {
} }
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;
@ -60,11 +56,8 @@ public class TextProgressBar {
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 SQLField<Integer> time = new SQLField<>("time", SQLType.INT, false);
public static final SQLFKField<String, SQLPlayer> playerId = new SQLFKField<>("playerId", SQLType.CHAR(36), true, 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

@ -6,15 +6,20 @@ 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<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<Integer> ordre = new SQLField<>("ordre", SQLType.INT, false);
} }

View File

@ -7,15 +7,21 @@ import fr.pandacube.java.util.db2.sql_tools.SQLType;
public class SQLForumForum extends SQLElement { public class SQLForumForum extends SQLElement {
public SQLForumForum() {
super();
}
public SQLForumForum() { super(); } public SQLForumForum(int id) {
public SQLForumForum(int id) { super(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,
public static final SQLFKField<Integer, SQLForumCategorie> catId = SQLFKField.idFK("catId", SQLType.INT, false, SQLForumCategorie.class); SQLForumCategorie.class);
public static final SQLField<String> nom = new SQLField<>("nom", SQLType.VARCHAR(100), false); public static final SQLField<String> nom = new SQLField<>("nom", SQLType.VARCHAR(100), false);
public static final SQLField<String> description = new SQLField<>("description", SQLType.TEXT, false); public static final SQLField<String> description = new SQLField<>("description", SQLType.TEXT, false);
public static final SQLField<Integer> ordre = new SQLField<>("ordre", SQLType.INT, false); public static final SQLField<Integer> ordre = new SQLField<>("ordre", SQLType.INT, false);
@ -27,6 +33,4 @@ public class SQLForumForum extends SQLElement {
public static final SQLField<Integer> nbThreads = new SQLField<>("nbThreads", 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); 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() {
super();
}
public SQLForumPost() { super(); } public SQLForumPost(int id) {
public SQLForumPost(int id) { super(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> 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> texte = new SQLField<>("texte", SQLType.TEXT, false);
public static final SQLField<Integer> time = new SQLField<>("time", SQLType.INT, false); public static final SQLField<Integer> time = new SQLField<>("time", SQLType.INT, false);
public static final SQLFKField<Integer, SQLForumThread> threadId = SQLFKField.idFK("threadId", SQLType.INT, false, SQLForumThread.class); 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 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() {
super();
}
public SQLForumThread() { super(); } public SQLForumThread(int id) {
public SQLForumThread(int id) { super(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,
public static final SQLFKField<Integer, SQLForumForum> forumId = SQLFKField.idFK("forumId", SQLType.INT, false, SQLForumForum.class); SQLForumForum.class);
public static final SQLField<String> titre = new SQLField<>("titre", SQLType.VARCHAR(60), false); public static final SQLField<String> titre = new SQLField<>("titre", SQLType.VARCHAR(60), false);
public static final SQLFKField<String, SQLPlayer> createur = new SQLFKField<>("createur", SQLType.CHAR(36), false, SQLPlayer.class, SQLPlayer.playerId); public static final SQLFKField<String, SQLPlayer> createur = new SQLFKField<>("createur", SQLType.CHAR(36), false,
SQLPlayer.class, SQLPlayer.playerId);
public static final SQLField<Integer> vu = new SQLField<>("vu", SQLType.INT, false); public static final SQLField<Integer> vu = new SQLField<>("vu", SQLType.INT, false);
public static final SQLField<Long> time = new SQLField<>("time", SQLType.BIGINT, 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> anchored = new SQLField<>("anchored", SQLType.BOOLEAN, false);
public static final SQLField<Boolean> locked = new SQLField<>("locked", 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 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() {
super();
}
public SQLLoginHistory() { super(); } public SQLLoginHistory(int id) {
public SQLLoginHistory(int id) { super(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 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 SQLFKField<String, SQLPlayer> playerId = new SQLFKField<>("playerId", SQLType.CHAR(36), false,
SQLPlayer.class, SQLPlayer.playerId);
public static final SQLField<String> ip = new SQLField<>("ip", SQLType.VARCHAR(128), true); public static final SQLField<String> ip = new SQLField<>("ip", SQLType.VARCHAR(128), true);
public static final SQLField<ActionType> actionType = new SQLField<>("actionType", SQLType.ENUM(ActionType.class), false); public static final SQLField<ActionType> actionType = new SQLField<>("actionType", SQLType.ENUM(ActionType.class),
false);
public static final SQLField<Integer> nbOnline = new SQLField<>("nbOnline", SQLType.INT, 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<String> playerName = new SQLField<>("playerName", SQLType.VARCHAR(16), true);
public static final SQLField<Integer> minecraftVersion = new SQLField<>("minecraftVersion", SQLType.INT, false, 0); 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,32 +12,28 @@ import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp.SQLComparator;
public class SQLMPGroup extends SQLElement { public class SQLMPGroup extends SQLElement {
public SQLMPGroup() {
super();
}
public SQLMPGroup() { super(); } public SQLMPGroup(int id) {
public SQLMPGroup(int id) { super(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() {
super();
}
public SQLMPGroupUser() { super(); } public SQLMPGroupUser(int id) {
public SQLMPGroupUser(int id) { super(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,
public static final SQLFKField<Integer, SQLMPGroup> groupId = SQLFKField.idFK( "groupId", SQLType.INT, false, SQLMPGroup.class); SQLMPGroup.class);
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);
// 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,91 +10,88 @@ 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() {
super();
}
public SQLMPMessage() { super(); } public SQLMPMessage(int id) {
public SQLMPMessage(int id) { super(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<Long> time = new SQLField<>("time", SQLType.BIGINT, false);
public static final SQLField<Integer> securityKey = new SQLField<>("securityKey", SQLType.INT, 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> viewerId = new SQLFKField<>("viewerId", SQLType.CHAR(36), false,
public static final SQLFKField<String, SQLPlayer> sourceId = new SQLFKField<>("sourceId", SQLType.CHAR(36), true, SQLPlayer.class, SQLPlayer.playerId); 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<String, SQLPlayer> sourceId = new SQLFKField<>("sourceId", SQLType.CHAR(36), true,
public static final SQLFKField<Integer, SQLMPGroup> destGroup = SQLFKField.idFK("destGroup", SQLType.INT, true, SQLMPGroup.class); 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<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> 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> 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<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()));
@ -104,41 +101,37 @@ public class SQLMPMessage extends SQLElement {
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,50 +9,47 @@ import fr.pandacube.java.util.db2.sql_tools.SQLType;
public class SQLModoHistory extends SQLElement { public class SQLModoHistory extends SQLElement {
public SQLModoHistory() {
super();
}
public SQLModoHistory() { super(); } public SQLModoHistory(int id) {
public SQLModoHistory(int id) { super(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,
public static final SQLFKField<String, SQLPlayer> modoId = new SQLFKField<>("modoId", SQLType.CHAR(36), true, SQLPlayer.class, SQLPlayer.playerId); SQLPlayer.class, SQLPlayer.playerId);
public static final SQLField<ActionType> actionType = new SQLField<>("actionType", SQLType.ENUM(ActionType.class), false); public static final SQLField<ActionType> actionType = new SQLField<>("actionType", SQLType.ENUM(ActionType.class),
false);
public static final SQLField<Long> time = new SQLField<>("time", SQLType.BIGINT, 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 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<Long> value = new SQLField<>("value", SQLType.BIGINT, true);
public static final SQLField<String> message = new SQLField<>("message", SQLType.VARCHAR(512), false); 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,57 +9,51 @@ import fr.pandacube.java.util.db2.sql_tools.SQLType;
public class SQLOnlineshopHistory extends SQLElement { public class SQLOnlineshopHistory extends SQLElement {
public SQLOnlineshopHistory() {
super();
}
public SQLOnlineshopHistory() { super(); } public SQLOnlineshopHistory(int id) {
public SQLOnlineshopHistory(int id) { super(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<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<String> transactionId = new SQLField<>("transactionId", SQLType.VARCHAR(255), true);
public static final SQLField<SourceType> sourceType = new SQLField<>("sourceType", SQLType.ENUM(SourceType.class), false); public static final SQLField<SourceType> sourceType = new SQLField<>("sourceType", SQLType.ENUM(SourceType.class),
public static final SQLFKField<String, SQLPlayer> sourcePlayerId = new SQLFKField<>("sourcePlayerId", SQLType.CHAR(36), true, SQLPlayer.class, SQLPlayer.playerId); false);
public static final SQLFKField<String, SQLPlayer> sourcePlayerId = new SQLFKField<>("sourcePlayerId",
SQLType.CHAR(36), true, SQLPlayer.class, SQLPlayer.playerId);
public static final SQLField<Double> sourceQuantity = new SQLField<>("sourceQuantity", SQLType.DOUBLE, false); public static final SQLField<Double> sourceQuantity = new SQLField<>("sourceQuantity", SQLType.DOUBLE, false);
public static final SQLField<String> sourceName = new SQLField<>("sourceName", SQLType.VARCHAR(64), false); public static final SQLField<String> sourceName = new SQLField<>("sourceName", SQLType.VARCHAR(64), false);
public static final SQLField<DestType> destType = new SQLField<>("destType", SQLType.ENUM(DestType.class), 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 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<Double> destQuantity = new SQLField<>("destQuantity", SQLType.DOUBLE, false);
public static final SQLField<String> destName = new SQLField<>("destName", SQLType.VARCHAR(64), 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) { public void setSourcePlayerId(UUID pName) {
set(sourcePlayerId, (pName == null) ? (String) null : pName.toString()); 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
} }
@ -68,5 +62,4 @@ public class SQLOnlineshopHistory extends SQLElement {
BAMBOU, GRADE BAMBOU, GRADE
} }
} }

View File

@ -11,18 +11,23 @@ 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
@ -32,69 +37,55 @@ public class SQLPlayer extends SQLElement {
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),
false);
public static final SQLField<Long> firstTimeInGame = new SQLField<>("firstTimeInGame", SQLType.BIGINT, false, 0L); public static final SQLField<Long> firstTimeInGame = new SQLField<>("firstTimeInGame", SQLType.BIGINT, false, 0L);
public static final SQLField<Long> timeWebRegister = new SQLField<>("timeWebRegister", SQLType.BIGINT, true); public static final SQLField<Long> timeWebRegister = new SQLField<>("timeWebRegister", SQLType.BIGINT, true);
public static final SQLField<Long> lastTimeInGame = new SQLField<>("lastTimeInGame", SQLType.BIGINT, true); public static final SQLField<Long> lastTimeInGame = new SQLField<>("lastTimeInGame", SQLType.BIGINT, true);
public static final SQLField<Long> lastWebActivity = new SQLField<>("lastWebActivity", SQLType.BIGINT, false, 0L); public static final SQLField<Long> lastWebActivity = new SQLField<>("lastWebActivity", SQLType.BIGINT, false, 0L);
public static final SQLField<String> onlineInServer = new SQLField<>("onlineInServer", SQLType.VARCHAR(32), true); public static final SQLField<String> onlineInServer = new SQLField<>("onlineInServer", SQLType.VARCHAR(32), true);
public static final SQLField<String> skinURL = new SQLField<>("skinURL", SQLType.VARCHAR(255), true); public static final SQLField<String> skinURL = new SQLField<>("skinURL", SQLType.VARCHAR(255), true);
public static final SQLField<Boolean> isVanish = new SQLField<>("isVanish", SQLType.BOOLEAN, false, (Boolean)false); public static final SQLField<Boolean> isVanish = new SQLField<>("isVanish", SQLType.BOOLEAN, false,
(Boolean) false);
public static final SQLField<Date> birthday = new SQLField<>("birthday", SQLType.DATE, true); public static final SQLField<Date> birthday = new SQLField<>("birthday", SQLType.DATE, true);
public static final SQLField<Integer> lastYearCelebBday = new SQLField<>("lastYearCelebratedBirthday", SQLType.INT, false, 0); public static final SQLField<Integer> lastYearCelebBday = new SQLField<>("lastYearCelebratedBirthday", SQLType.INT,
false, 0);
public static final SQLField<Long> banTimeout = new SQLField<>("banTimeout", SQLType.BIGINT, true); public static final SQLField<Long> banTimeout = new SQLField<>("banTimeout", SQLType.BIGINT, true);
public static final SQLField<Long> muteTimeout = new SQLField<>("muteTimeout", SQLType.BIGINT, true); 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<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<Long> bambou = new SQLField<>("bambou", SQLType.BIGINT, false, 0L);
public static final SQLField<String> grade = new SQLField<>("grade", SQLType.VARCHAR(36), false, "default"); 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,50 +10,48 @@ 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); }
@Override
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 UUID getIgnorerId() {
String id = (String)get(ignorer);
return (id == null) ? null : UUID.fromString(id);
} }
public SQLPlayerIgnore(int id) {
super(id);
}
@Override
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 UUID getIgnorerId() {
String id = get(ignorer);
return (id == null) ? null : UUID.fromString(id);
}
public void setIgnorerId(UUID pName) { public void setIgnorerId(UUID pName) {
set(ignorer, (pName == null) ? (String) null : pName.toString()); 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)
@ -61,6 +59,7 @@ public class SQLPlayerIgnore extends SQLElement {
.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;
} }
@ -81,18 +80,14 @@ public class SQLPlayerIgnore extends SQLElement {
} }
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

@ -6,18 +6,22 @@ import fr.pandacube.java.util.db2.sql_tools.SQLType;
public class SQLShopStock extends SQLElement { public class SQLShopStock extends SQLElement {
public SQLShopStock() {
super();
}
public SQLShopStock() { super(); } public SQLShopStock(int id) {
public SQLShopStock(int id) { super(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() {
super();
}
public SQLStaffTicket() { super(); } public SQLStaffTicket(int id) {
public SQLStaffTicket(int id) { super(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,
public static final SQLFKField<String, SQLPlayer> playerId = new SQLFKField<>("playerId", SQLType.CHAR(36), false, SQLPlayer.class, SQLPlayer.playerId); 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,13 +6,18 @@ import fr.pandacube.java.util.db2.sql_tools.SQLType;
public class SQLStaticPages extends SQLElement { public class SQLStaticPages extends SQLElement {
public SQLStaticPages() {
super();
}
public SQLStaticPages() { super(); } public SQLStaticPages(int id) {
public SQLStaticPages(int id) { super(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);
@ -20,5 +25,4 @@ public class SQLStaticPages extends SQLElement {
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

@ -9,26 +9,28 @@ 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, SQLPlayer.class, SQLPlayer.playerId);
public static final SQLField<String> player = new SQLField<>("player", SQLType.VARCHAR(16), false); 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

@ -11,7 +11,8 @@ public class DBConnection {
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;
@ -19,34 +20,27 @@ public class DBConnection {
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();

View File

@ -33,6 +33,7 @@ import javafx.util.Pair;
/** /**
* <b>ORM = Object-Relational Mapping</b> * <b>ORM = Object-Relational Mapping</b>
*
* @author Marc Baloup * @author Marc Baloup
* *
*/ */
@ -46,15 +47,14 @@ public final class ORM {
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 {
@ -79,29 +79,20 @@ public final class ORM {
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() + " (";
@ -118,15 +109,11 @@ public final class ORM {
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();
@ -135,12 +122,6 @@ public final class ORM {
} }
} }
private static boolean tableExist(String tableName) throws SQLException { private static boolean tableExist(String tableName) throws SQLException {
ResultSet set = null; ResultSet set = null;
boolean exist = false; boolean exist = false;
@ -148,25 +129,20 @@ 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)
public static <T extends SQLElement> List<T> getByIds(Class<T> elemClass, Collection<Integer> ids) throws ORMException { throws ORMException {
return getByIds(elemClass, ids.toArray(new Integer[ids.size()])); return getByIds(elemClass, ids.toArray(new Integer[ids.size()]));
} }
@ -174,8 +150,7 @@ public final class ORM {
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);
} }
@ -183,18 +158,18 @@ public final class ORM {
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 {
@ -207,12 +182,9 @@ public final class ORM {
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>();
@ -223,8 +195,7 @@ public final class ORM {
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());
@ -247,19 +218,6 @@ public final class ORM {
} }
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"));
@ -268,37 +226,48 @@ public final class ORM {
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) {
@ -306,56 +275,26 @@ public final class ORM {
} }
} }
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
// TODO LIST
* - Gérer mise à jour relative d'un champ (incrément / décrément) * - Gérer mise à jour relative d'un champ (incrément / décrément)
* }
}
*/ */
} }

View File

@ -3,8 +3,6 @@ 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());
} }
@ -13,6 +11,4 @@ public class ORMInitTableException extends ORMException {
super("Error while initializing table " + tableElem.getName(), t); super("Error while initializing table " + tableElem.getName(), t);
} }
} }

View File

@ -25,9 +25,6 @@ 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;
@ -39,11 +36,9 @@ public abstract class SQLElement {
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());
@ -53,19 +48,16 @@ public abstract class SQLElement {
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")
@ -80,35 +72,25 @@ public abstract class SQLElement {
*/ */
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) {
@ -116,86 +98,64 @@ public abstract class SQLElement {
} }
} }
} }
/* 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;
else
throw new IllegalArgumentException("SQLField '" + sqlField.name + "' of " + getClass().getName()
+ " type is '" + sqlField.type.toString() + "' and can't accept values of type "
+ value.getClass().getName());
if (modify) { if (modify) if (!values.containsKey(sqlField)) {
if (!values.containsKey(sqlField)) {
values.put(sqlField, value); values.put(sqlField, value);
if (setModified) if (setModified) modifiedSinceLastSave.add(sqlField.name);
modifiedSinceLastSave.add(sqlField.name);
} }
else { else {
Object oldVal = values.get(sqlField); Object oldVal = values.get(sqlField);
if (!Objects.equals(oldVal, value)) { 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);
} }
// sinon, rien n'est modifié // 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;
@ -203,31 +163,22 @@ public abstract class SQLElement {
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.");
@ -238,44 +189,43 @@ public abstract class SQLElement {
Connection conn = db.getNativeConnection(); Connection conn = db.getNativeConnection();
if (stored) { // mettre à jour les valeurs dans la base
if (stored) // restaurer l'ID au cas il aurait été changé à la main dans
{ // mettre à jour les valeurs dans la base // 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
// enum (non
// prise en
// charge
// par JDBC)
psValues.add(((Enum<?>) entry.getValue()).name()); 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,13 +233,12 @@ 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 values // restaurer l'ID au cas il aurait été changé à la main dans
// 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<>();
@ -303,32 +252,32 @@ 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
// enum (non
// prise en
// charge
// par JDBC)
psValues.add(((Enum<?>) entry.getValue()).name()); 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 {
@ -347,8 +296,9 @@ public abstract class SQLElement {
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;
@ -359,16 +309,12 @@ public abstract class SQLElement {
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();
@ -384,7 +330,8 @@ public abstract class SQLElement {
} }
/** /**
* 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;
@ -393,9 +340,6 @@ public abstract class SQLElement {
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;
@ -407,35 +351,26 @@ public abstract class SQLElement {
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

@ -25,10 +25,14 @@ public class SQLElementList<E extends SQLElement> extends ArrayList<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
@ -43,7 +47,8 @@ public class SQLElementList<E extends SQLElement> extends ArrayList<E> {
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
@ -51,17 +56,17 @@ public class SQLElementList<E extends SQLElement> extends ArrayList<E> {
} }
/** /**
* 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
* 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 * @throws SQLException
*/ */
public synchronized void saveCommon() throws SQLException { public synchronized void saveCommon() throws SQLException {
@ -73,16 +78,16 @@ public class SQLElementList<E extends SQLElement> extends ArrayList<E> {
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
// en charge par
// JDBC)
psValues.add(((Enum<?>) entry.getValue()).name()); 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;
@ -92,13 +97,13 @@ public class SQLElementList<E extends SQLElement> extends ArrayList<E> {
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();
@ -112,15 +117,11 @@ 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<>();
@ -130,8 +131,6 @@ 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;
@ -146,14 +145,14 @@ public class SQLElementList<E extends SQLElement> extends ArrayList<E> {
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();
@ -165,10 +164,4 @@ public class SQLElementList<E extends SQLElement> extends ArrayList<E> {
} }
} }

View File

@ -7,8 +7,6 @@ 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);
@ -19,7 +17,8 @@ public class SQLFKField<T, E extends SQLElement> extends SQLField<T> {
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));
@ -29,7 +28,8 @@ public class SQLFKField<T, E extends SQLElement> extends SQLField<T> {
} }
} }
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));
@ -56,8 +56,12 @@ public class SQLFKField<T, E extends SQLElement> extends SQLField<T> {
sqlForeignKeyElement = fkEl; sqlForeignKeyElement = fkEl;
} }
public SQLField<T> getForeignField() {
return sqlForeignKeyField;
}
public SQLField<T> getForeignField() { return sqlForeignKeyField; } public Class<E> getForeignElementClass() {
public Class<E> getForeignElementClass() { return sqlForeignKeyElement; } return sqlForeignKeyElement;
}
} }

View File

@ -36,14 +36,10 @@ public class SQLField<T> {
/* 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
+ " "+ type.toString()
+ (canBeNull ? " NULL" : " NOT NULL")
+ (autoIncrement ? " AUTO_INCREMENT" : "") + (autoIncrement ? " AUTO_INCREMENT" : "")
+ ((defaultValue == null || autoIncrement) ? "" : " DEFAULT ?"), + ((defaultValue == null || autoIncrement) ? "" : " DEFAULT ?"), params);
params);
} }
/* package */ void setSQLElementType(Class<? extends SQLElement> elemClass) { /* package */ void setSQLElementType(Class<? extends SQLElement> elemClass) {
@ -54,19 +50,18 @@ public class SQLField<T> {
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;
@ -82,5 +77,4 @@ public class SQLField<T> {
return name.hashCode() + sqlElemClass.hashCode(); return name.hashCode() + sqlElemClass.hashCode();
} }
} }

View File

@ -14,6 +14,7 @@ public class 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)
@ -26,6 +27,7 @@ public class SQLOrderBy {
/** /**
* 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)
*/ */
@ -33,7 +35,6 @@ public class SQLOrderBy {
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;
@ -50,7 +51,6 @@ public class SQLOrderBy {
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;
@ -60,7 +60,6 @@ public class SQLOrderBy {
direction = d; direction = d;
} }
} }
public enum Direction { public enum Direction {

View File

@ -20,8 +20,7 @@ public class SQLType<T> {
} }
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;
} }
@ -32,8 +31,7 @@ public class SQLType<T> {
@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());
} }
@ -41,11 +39,6 @@ public class SQLType<T> {
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);
@ -84,8 +77,7 @@ public class SQLType<T> {
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();
@ -95,5 +87,4 @@ public class SQLType<T> {
return new SQLType<>("VARCHAR", "(" + enumStr + ")", enumType); return new SQLType<>("VARCHAR", "(" + enumStr + ")", enumType);
} }
} }

View File

@ -6,13 +6,8 @@ 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

@ -11,20 +11,16 @@ public class SQLWhereChain extends SQLWhere {
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 = "";
@ -43,11 +39,9 @@ public class SQLWhereChain extends SQLWhere {
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;

View File

@ -13,6 +13,7 @@ public class SQLWhereComp extends SQLWhere {
/** /**
* 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
@ -25,9 +26,6 @@ public class SQLWhereComp extends SQLWhere {
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<>();
@ -35,19 +33,13 @@ public class SQLWhereComp extends SQLWhere {
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;
@ -58,5 +50,4 @@ public class SQLWhereComp extends SQLWhere {
} }
} }

View File

@ -7,12 +7,12 @@ 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.
*/ */
@ -23,7 +23,6 @@ public class SQLWhereLike extends SQLWhere {
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

@ -14,24 +14,23 @@ public class SQLWhereNull extends SQLWhere {
/** /**
* 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

@ -7,23 +7,18 @@ 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);
@ -37,19 +32,8 @@ public class DistanceUtil {
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;

View File

@ -6,31 +6,24 @@ 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,8 +1,7 @@
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;
@ -20,22 +19,18 @@ public class TimeUtil {
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

@ -30,13 +30,9 @@ public class TCPClient extends Thread implements Closeable {
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);
@ -47,7 +43,6 @@ public class TCPClient extends Thread implements Closeable {
listener.onConnect(this); listener.onConnect(this);
} }
@Override @Override
public void run() { public void run() {
@ -55,8 +50,7 @@ public class TCPClient extends Thread implements Closeable {
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();
@ -66,15 +60,14 @@ public class TCPClient extends Thread implements Closeable {
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;
@ -86,7 +79,6 @@ public class TCPClient extends Thread implements Closeable {
} }
} }
} 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) {
@ -95,21 +87,15 @@ 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());
@ -121,8 +107,7 @@ public class TCPClient extends Thread implements Closeable {
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);
@ -132,33 +117,23 @@ public class TCPClient extends Thread implements Closeable {
} }
} }
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

@ -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;
@ -18,7 +17,9 @@ public abstract class Packet implements ByteSerializable {
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);
@ -27,21 +28,6 @@ public abstract class Packet implements ByteSerializable {
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>>();
@ -64,15 +50,13 @@ public abstract class Packet implements ByteSerializable {
@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 {
/* /*
@ -81,5 +65,4 @@ public abstract class Packet implements ByteSerializable {
// addPacket(PacketToto.class); // addPacket(PacketToto.class);
} }
} }

View File

@ -10,5 +10,4 @@ public abstract class PacketClient extends Packet {
super(c); super(c);
} }
} }

View File

@ -186,7 +186,6 @@ public class ByteBuffer implements Cloneable {
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);
@ -200,6 +199,7 @@ public class ByteBuffer implements Cloneable {
/** /**
* 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
*/ */
@ -209,9 +209,12 @@ public class ByteBuffer implements Cloneable {
} }
/** /**
* 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) {
@ -234,14 +237,11 @@ public class ByteBuffer implements Cloneable {
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()
*/ */
@ -249,6 +249,4 @@ public class ByteBuffer implements Cloneable {
return buff.array(); return buff.array();
} }
} }

View File

@ -1,10 +1,12 @@
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
* *
*/ */

View File

@ -10,14 +10,15 @@ 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 input true if getting input bw, false if getting output, null if
* getting input + output
* @param co * @param co
* @return * @return
*/ */
@ -31,30 +32,19 @@ public class BandwidthCalculation {
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,7 +24,6 @@ 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
@ -33,7 +32,6 @@ import fr.pandacube.java.util.network.packet.bytebuffer.ByteBuffer;
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;
@ -42,16 +40,11 @@ public class TCPServer extends Thread implements Closeable {
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);
@ -61,7 +54,6 @@ public class TCPServer extends Thread implements Closeable {
socketName = sckName; socketName = sckName;
} }
@Override @Override
public void run() { public void run() {
@ -72,7 +64,8 @@ public class TCPServer extends Thread implements Closeable {
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();
@ -85,16 +78,6 @@ public class TCPServer extends Thread implements Closeable {
} }
} }
public class TCPServerClientConnection extends Thread { public class TCPServerClientConnection extends Thread {
private Socket socket; private Socket socket;
private InputStream in; private InputStream in;
@ -102,7 +85,6 @@ public class TCPServer extends Thread implements Closeable {
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;
@ -120,8 +102,7 @@ public class TCPServer extends Thread implements Closeable {
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();
@ -129,7 +110,8 @@ public class TCPServer extends Thread implements Closeable {
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);
@ -138,19 +120,16 @@ public class TCPServer extends Thread implements Closeable {
} 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();
} }
@ -162,8 +141,7 @@ public class TCPServer extends Thread implements Closeable {
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);
} }
@ -176,20 +154,20 @@ public class TCPServer extends Thread implements Closeable {
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>();
@ -197,12 +175,10 @@ public class TCPServer extends Thread implements Closeable {
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 {
@ -216,39 +192,28 @@ public class TCPServer extends Thread implements Closeable {
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 {
@ -266,15 +231,9 @@ public class TCPServer extends Thread implements Closeable {
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

@ -9,7 +9,8 @@ public interface TCPServerListener {
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);

View File

@ -8,20 +8,17 @@ public abstract class AbstractRequest {
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");

View File

@ -22,7 +22,4 @@ public class NetworkAPISender {
return response; return response;
} }
} }

View File

@ -7,42 +7,35 @@ 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();
@ -52,12 +45,9 @@ public class ResponseAnalyser {
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,20 +7,16 @@ 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 {
@ -34,13 +30,12 @@ public abstract class AbstractRequestExecutor {
} }
/** /**
* *
* @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,6 +2,7 @@ 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
* *
*/ */

View File

@ -8,18 +8,6 @@ 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;
@ -29,10 +17,12 @@ public class NetworkAPIListener implements Runnable {
/** /**
* 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;
@ -41,7 +31,6 @@ public class NetworkAPIListener implements Runnable {
nAPIExecutionHandler = peh; nAPIExecutionHandler = peh;
} }
@Override @Override
public void run() { public void run() {
synchronized (this) { synchronized (this) {
@ -53,11 +42,8 @@ public class NetworkAPIListener implements Runnable {
} }
} }
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()) {
@ -68,38 +54,28 @@ public class NetworkAPIListener implements Runnable {
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 {
{
try {
serverSocket.close(); serverSocket.close();
} catch (IOException e) {} } 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);
} }
@ -108,18 +84,8 @@ public class NetworkAPIListener implements Runnable {
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,10 +6,12 @@ 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
* *
*/ */
@ -29,13 +31,10 @@ public class PacketExecutor implements Runnable {
// 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;
@ -43,8 +42,8 @@ public class PacketExecutor implements Runnable {
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();
} }

View File

@ -12,7 +12,9 @@ public class RequestAnalyser {
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;
@ -21,16 +23,9 @@ public class RequestAnalyser {
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();
@ -38,16 +33,15 @@ public class RequestAnalyser {
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();
@ -58,18 +52,11 @@ public class RequestAnalyser {
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;
@ -80,5 +67,4 @@ public class RequestAnalyser {
} }
} }

View File

@ -6,7 +6,6 @@ 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;
@ -16,9 +15,7 @@ public class Response {
* 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) {

View File

@ -42,17 +42,16 @@ public enum ChatColor {
private ChatColor(char code, String name) { private ChatColor(char code, String name) {
this.code = code; this.code = code;
this.name = name; this.name = name;
this.toString = new String(new char[]{'\u00a7', code}); toString = new String(new char[] { '\u00a7', code });
} }
@Override
public String toString() { public String toString() {
return this.toString; return toString;
} }
public static String stripColor(String input) { public static String stripColor(String input) {
if (input == null) { if (input == null) return null;
return null;
}
return STRIP_COLOR_PATTERN.matcher(input).replaceAll(""); return STRIP_COLOR_PATTERN.matcher(input).replaceAll("");
} }
@ -71,15 +70,13 @@ public enum ChatColor {
} }
public String getName() { public String getName() {
return this.name; return name;
} }
static { static {
STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + String.valueOf('\u00a7') + "[0-9A-FK-OR]"); STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + String.valueOf('\u00a7') + "[0-9A-FK-OR]");
BY_CHAR = new HashMap<Character, ChatColor>(); BY_CHAR = new HashMap<Character, ChatColor>();
for (ChatColor colour : ChatColor.values()) { for (ChatColor colour : ChatColor.values())
BY_CHAR.put(Character.valueOf(colour.code), colour); 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,10 +5,8 @@ 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;
@ -24,114 +22,96 @@ public abstract class BaseComponent {
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) {
@ -139,15 +119,14 @@ public abstract class BaseComponent {
} }
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; component.parent = this;
this.extra.add(component); 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() {
@ -157,12 +136,9 @@ public abstract class BaseComponent {
} }
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();
@ -171,12 +147,9 @@ public abstract class BaseComponent {
} }
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;
@ -214,27 +187,29 @@ public abstract class BaseComponent {
this.hoverEvent = hoverEvent; this.hoverEvent = hoverEvent;
} }
@Override
public String toString() { public String toString() {
return "BaseComponent(color=" + (Object)((Object)this.getColor()) + ", bold=" + this.bold + ", italic=" + this.italic + ", underlined=" + this.underlined + ", strikethrough=" + this.strikethrough + ", obfuscated=" + this.obfuscated + ", insertion=" + this.getInsertion() + ", extra=" + this.getExtra() + ", clickEvent=" + this.getClickEvent() + ", hoverEvent=" + this.getHoverEvent() + ")"; 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

@ -10,15 +10,16 @@ public final class ClickEvent {
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;
} }
@Override
public String toString() { public String toString() {
return "ClickEvent(action=" + (Object)((Object)this.getAction()) + ", value=" + this.getValue() + ")"; return "ClickEvent(action=" + (getAction()) + ", value=" + getValue() + ")";
} }
@ConstructorProperties(value = { "action", "value" }) @ConstructorProperties(value = { "action", "value" })
@ -28,16 +29,9 @@ public final class ClickEvent {
} }
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,25 +5,21 @@ 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) {
@ -31,102 +27,96 @@ public class ComponentBuilder {
} }
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() {
}
} }
} }

View File

@ -5,22 +5,22 @@ package net.md_5.bungee.api.chat;
import java.beans.ConstructorProperties; import java.beans.ConstructorProperties;
import java.util.Arrays; import java.util.Arrays;
import net.md_5.bungee.api.chat.BaseComponent;
public final class HoverEvent { public final class HoverEvent {
private final Action action; private final Action action;
private final BaseComponent[] value; private final BaseComponent[] value;
public Action getAction() { public Action getAction() {
return this.action; return action;
} }
public BaseComponent[] getValue() { public BaseComponent[] getValue() {
return this.value; return value;
} }
@Override
public String toString() { public String toString() {
return "HoverEvent(action=" + (Object)((Object)this.getAction()) + ", value=" + Arrays.deepToString(this.getValue()) + ")"; return "HoverEvent(action=" + (getAction()) + ", value=" + Arrays.deepToString(getValue()) + ")";
} }
@ConstructorProperties(value = { "action", "value" }) @ConstructorProperties(value = { "action", "value" })
@ -30,15 +30,9 @@ public final class HoverEvent {
} }
public static enum Action { public static enum Action {
SHOW_TEXT, SHOW_TEXT, SHOW_ACHIEVEMENT, SHOW_ITEM, SHOW_ENTITY;
SHOW_ACHIEVEMENT,
SHOW_ITEM,
SHOW_ENTITY;
private Action() {}
private Action() {
}
} }
} }

View File

@ -8,12 +8,10 @@ import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ClickEvent;
public class TextComponent import net.md_5.bungee.api.ChatColor;
extends BaseComponent {
public class TextComponent extends BaseComponent {
private static final Pattern url = Pattern.compile("^(?:(https?)://)?([-\\w_\\.]{2,}\\.[a-z]{2,4})(/\\S*)?$"); private static final Pattern url = Pattern.compile("^(?:(https?)://)?([-\\w_\\.]{2,}\\.[a-z]{2,4})(/\\S*)?$");
private String text; private String text;
@ -22,14 +20,13 @@ extends BaseComponent {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
TextComponent component = new TextComponent(); TextComponent component = new TextComponent();
Matcher matcher = url.matcher(message); Matcher matcher = url.matcher(message);
block8 : for (int i = 0; i < message.length(); ++i) { block8:
for (int i = 0; i < message.length(); ++i) {
TextComponent old; TextComponent old;
char c2 = message.charAt(i); char c2 = message.charAt(i);
if (c2 == '\u00a7') { if (c2 == '\u00a7') {
ChatColor format; ChatColor format;
if ((c2 = message.charAt(++i)) >= 'A' && c2 <= 'Z') { if ((c2 = message.charAt(++i)) >= 'A' && c2 <= 'Z') c2 = (char) (c2 + 32);
c2 = (char)(c2 + 32);
}
if ((format = ChatColor.getByChar(c2)) == null) continue; if ((format = ChatColor.getByChar(c2)) == null) continue;
if (builder.length() > 0) { if (builder.length() > 0) {
old = component; old = component;
@ -69,9 +66,7 @@ extends BaseComponent {
continue; continue;
} }
int pos = message.indexOf(32, i); int pos = message.indexOf(32, i);
if (pos == -1) { if (pos == -1) pos = message.length();
pos = message.length();
}
if (matcher.region(i, pos).find()) { if (matcher.region(i, pos).find()) {
if (builder.length() > 0) { if (builder.length() > 0) {
old = component; old = component;
@ -84,7 +79,8 @@ extends BaseComponent {
component = new TextComponent(old); component = new TextComponent(old);
String urlString = message.substring(i, pos); String urlString = message.substring(i, pos);
component.setText(urlString); component.setText(urlString);
component.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, urlString.startsWith("http") ? urlString : "http://" + urlString)); component.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL,
urlString.startsWith("http") ? urlString : "http://" + urlString));
components.add(component); components.add(component);
i += pos - i - 1; i += pos - i - 1;
component = old; component = old;
@ -96,20 +92,18 @@ extends BaseComponent {
component.setText(builder.toString()); component.setText(builder.toString());
components.add(component); components.add(component);
} }
if (components.isEmpty()) { if (components.isEmpty()) components.add(new TextComponent(""));
components.add(new TextComponent(""));
}
return components.toArray(new BaseComponent[components.size()]); return components.toArray(new BaseComponent[components.size()]);
} }
public TextComponent(TextComponent textComponent) { public TextComponent(TextComponent textComponent) {
super(textComponent); super(textComponent);
this.setText(textComponent.getText()); setText(textComponent.getText());
} }
public /* varargs */ TextComponent(BaseComponent... extras) { public /* varargs */ TextComponent(BaseComponent... extras) {
this.setText(""); setText("");
this.setExtra(new ArrayList<BaseComponent>(Arrays.asList(extras))); setExtra(new ArrayList<BaseComponent>(Arrays.asList(extras)));
} }
@Override @Override
@ -119,39 +113,29 @@ extends BaseComponent {
@Override @Override
protected void toPlainText(StringBuilder builder) { protected void toPlainText(StringBuilder builder) {
builder.append(this.text); builder.append(text);
super.toPlainText(builder); super.toPlainText(builder);
} }
@Override @Override
protected void toLegacyText(StringBuilder builder) { protected void toLegacyText(StringBuilder builder) {
builder.append((Object)this.getColor()); builder.append(getColor());
if (this.isBold()) { if (isBold()) builder.append(ChatColor.BOLD);
builder.append((Object)ChatColor.BOLD); if (isItalic()) builder.append(ChatColor.ITALIC);
} if (isUnderlined()) builder.append(ChatColor.UNDERLINE);
if (this.isItalic()) { if (isStrikethrough()) builder.append(ChatColor.STRIKETHROUGH);
builder.append((Object)ChatColor.ITALIC); if (isObfuscated()) builder.append(ChatColor.MAGIC);
} builder.append(text);
if (this.isUnderlined()) {
builder.append((Object)ChatColor.UNDERLINE);
}
if (this.isStrikethrough()) {
builder.append((Object)ChatColor.STRIKETHROUGH);
}
if (this.isObfuscated()) {
builder.append((Object)ChatColor.MAGIC);
}
builder.append(this.text);
super.toLegacyText(builder); super.toLegacyText(builder);
} }
@Override @Override
public String toString() { public String toString() {
return String.format("TextComponent{text=%s, %s}", this.text, super.toString()); return String.format("TextComponent{text=%s, %s}", text, super.toString());
} }
public String getText() { public String getText() {
return this.text; return text;
} }
public void setText(String text) { public void setText(String text) {
@ -163,8 +147,6 @@ extends BaseComponent {
this.text = text; this.text = text;
} }
public TextComponent() { public TextComponent() {}
}
} }

View File

@ -9,12 +9,10 @@ import java.util.MissingResourceException;
import java.util.ResourceBundle; import java.util.ResourceBundle;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
public class TranslatableComponent import net.md_5.bungee.api.ChatColor;
extends BaseComponent {
public class TranslatableComponent extends BaseComponent {
private final ResourceBundle locales = ResourceBundle.getBundle("mojang-translations/en_US"); private final ResourceBundle locales = ResourceBundle.getBundle("mojang-translations/en_US");
private final Pattern format = Pattern.compile("%(?:(\\d+)\\$)?([A-Za-z%]|$)"); private final Pattern format = Pattern.compile("%(?:(\\d+)\\$)?([A-Za-z%]|$)");
private String translate; private String translate;
@ -22,18 +20,17 @@ extends BaseComponent {
public TranslatableComponent(TranslatableComponent original) { public TranslatableComponent(TranslatableComponent original) {
super(original); super(original);
this.setTranslate(original.getTranslate()); setTranslate(original.getTranslate());
if (original.getWith() != null) { if (original.getWith() != null) {
ArrayList<BaseComponent> temp = new ArrayList<BaseComponent>(); ArrayList<BaseComponent> temp = new ArrayList<BaseComponent>();
for (BaseComponent baseComponent : original.getWith()) { for (BaseComponent baseComponent : original.getWith())
temp.add(baseComponent.duplicate()); temp.add(baseComponent.duplicate());
} setWith(temp);
this.setWith(temp);
} }
} }
public /* varargs */ TranslatableComponent(String translate, Object... with) { public /* varargs */ TranslatableComponent(String translate, Object... with) {
this.setTranslate(translate); setTranslate(translate);
ArrayList<BaseComponent> temp = new ArrayList<BaseComponent>(); ArrayList<BaseComponent> temp = new ArrayList<BaseComponent>();
for (Object w : with) { for (Object w : with) {
if (w instanceof String) { if (w instanceof String) {
@ -42,7 +39,7 @@ extends BaseComponent {
} }
temp.add((BaseComponent) w); temp.add((BaseComponent) w);
} }
this.setWith(temp); setWith(temp);
} }
@Override @Override
@ -51,10 +48,9 @@ extends BaseComponent {
} }
public void setWith(List<BaseComponent> components) { public void setWith(List<BaseComponent> components) {
for (BaseComponent component : components) { for (BaseComponent component : components)
component.parent = this; component.parent = this;
} with = components;
this.with = components;
} }
public void addWith(String text) { public void addWith(String text) {
@ -62,37 +58,32 @@ extends BaseComponent {
} }
public void addWith(BaseComponent component) { public void addWith(BaseComponent component) {
if (this.with == null) { if (with == null) with = new ArrayList<BaseComponent>();
this.with = new ArrayList<BaseComponent>();
}
component.parent = this; component.parent = this;
this.with.add(component); with.add(component);
} }
@Override @Override
protected void toPlainText(StringBuilder builder) { protected void toPlainText(StringBuilder builder) {
String trans; String trans;
try { try {
trans = this.locales.getString(this.translate); trans = locales.getString(translate);
} catch (MissingResourceException ex) {
trans = translate;
} }
catch (MissingResourceException ex) { Matcher matcher = format.matcher(trans);
trans = this.translate;
}
Matcher matcher = this.format.matcher(trans);
int position = 0; int position = 0;
int i = 0; int i = 0;
while (matcher.find(position)) { while (matcher.find(position)) {
int pos = matcher.start(); int pos = matcher.start();
if (pos != position) { if (pos != position) builder.append(trans.substring(position, pos));
builder.append(trans.substring(position, pos));
}
position = matcher.end(); position = matcher.end();
String formatCode = matcher.group(2); String formatCode = matcher.group(2);
switch (formatCode.charAt(0)) { switch (formatCode.charAt(0)) {
case 'd': case 'd':
case 's': { case 's': {
String withIndex = matcher.group(1); String withIndex = matcher.group(1);
this.with.get(withIndex != null ? Integer.parseInt(withIndex) - 1 : i++).toPlainText(builder); with.get(withIndex != null ? Integer.parseInt(withIndex) - 1 : i++).toPlainText(builder);
break; break;
} }
case '%': { case '%': {
@ -100,9 +91,7 @@ extends BaseComponent {
} }
} }
} }
if (trans.length() != position) { if (trans.length() != position) builder.append(trans.substring(position, trans.length()));
builder.append(trans.substring(position, trans.length()));
}
super.toPlainText(builder); super.toPlainText(builder);
} }
@ -110,18 +99,17 @@ extends BaseComponent {
protected void toLegacyText(StringBuilder builder) { protected void toLegacyText(StringBuilder builder) {
String trans; String trans;
try { try {
trans = this.locales.getString(this.translate); trans = locales.getString(translate);
} catch (MissingResourceException e) {
trans = translate;
} }
catch (MissingResourceException e) { Matcher matcher = format.matcher(trans);
trans = this.translate;
}
Matcher matcher = this.format.matcher(trans);
int position = 0; int position = 0;
int i = 0; int i = 0;
while (matcher.find(position)) { while (matcher.find(position)) {
int pos = matcher.start(); int pos = matcher.start();
if (pos != position) { if (pos != position) {
this.addFormat(builder); addFormat(builder);
builder.append(trans.substring(position, pos)); builder.append(trans.substring(position, pos));
} }
position = matcher.end(); position = matcher.end();
@ -130,55 +118,45 @@ extends BaseComponent {
case 'd': case 'd':
case 's': { case 's': {
String withIndex = matcher.group(1); String withIndex = matcher.group(1);
this.with.get(withIndex != null ? Integer.parseInt(withIndex) - 1 : i++).toLegacyText(builder); with.get(withIndex != null ? Integer.parseInt(withIndex) - 1 : i++).toLegacyText(builder);
break; break;
} }
case '%': { case '%': {
this.addFormat(builder); addFormat(builder);
builder.append('%'); builder.append('%');
} }
} }
} }
if (trans.length() != position) { if (trans.length() != position) {
this.addFormat(builder); addFormat(builder);
builder.append(trans.substring(position, trans.length())); builder.append(trans.substring(position, trans.length()));
} }
super.toLegacyText(builder); super.toLegacyText(builder);
} }
private void addFormat(StringBuilder builder) { private void addFormat(StringBuilder builder) {
builder.append((Object)this.getColor()); builder.append(getColor());
if (this.isBold()) { if (isBold()) builder.append(ChatColor.BOLD);
builder.append((Object)ChatColor.BOLD); if (isItalic()) builder.append(ChatColor.ITALIC);
} if (isUnderlined()) builder.append(ChatColor.UNDERLINE);
if (this.isItalic()) { if (isStrikethrough()) builder.append(ChatColor.STRIKETHROUGH);
builder.append((Object)ChatColor.ITALIC); if (isObfuscated()) builder.append(ChatColor.MAGIC);
}
if (this.isUnderlined()) {
builder.append((Object)ChatColor.UNDERLINE);
}
if (this.isStrikethrough()) {
builder.append((Object)ChatColor.STRIKETHROUGH);
}
if (this.isObfuscated()) {
builder.append((Object)ChatColor.MAGIC);
}
} }
public ResourceBundle getLocales() { public ResourceBundle getLocales() {
return this.locales; return locales;
} }
public Pattern getFormat() { public Pattern getFormat() {
return this.format; return format;
} }
public String getTranslate() { public String getTranslate() {
return this.translate; return translate;
} }
public List<BaseComponent> getWith() { public List<BaseComponent> getWith() {
return this.with; return with;
} }
public void setTranslate(String translate) { public void setTranslate(String translate) {
@ -187,10 +165,9 @@ extends BaseComponent {
@Override @Override
public String toString() { public String toString() {
return "TranslatableComponent(locales=" + this.getLocales() + ", format=" + this.getFormat() + ", translate=" + this.getTranslate() + ", with=" + this.getWith() + ")"; return "TranslatableComponent(locales=" + getLocales() + ", format=" + getFormat() + ", translate="
+ getTranslate() + ", with=" + getWith() + ")";
} }
public TranslatableComponent() { public TranslatableComponent() {}
} }
}