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

View File

@ -4,13 +4,10 @@ import java.nio.charset.Charset;
public class Pandacube {
public static final Charset NETWORK_CHARSET = Charset.forName("UTF-8");
public static final int NETWORK_TCP_BUFFER_SIZE = 1024 * 1024;
public static final int NETWORK_TIMEOUT = 30 * 1000; // 30 secondes
}

View File

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

View File

@ -4,4 +4,3 @@ package fr.pandacube.java.util;
public interface Callback<T> {
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.
*
* @param enumType the enum class.
* @param separator a string which will be used as a separator
* @return a string representation of the enum class.
@ -14,9 +15,7 @@ public class EnumUtil {
String out = "";
boolean first = true;
for (T el : elements) {
if (!first) {
out += separator;
}
if (!first) out += separator;
first = false;
out += el.name();
@ -24,10 +23,12 @@ public class EnumUtil {
return out;
}
/**
* List all enum constants which are in the specified enum class. It is equivalent to call
* {@link #enumList(Class, String)} with the second parameter <code>", "</code>
* List all enum constants which are in the specified enum class. It is
* equivalent to call
* {@link #enumList(Class, String)} with the second parameter
* <code>", "</code>
*
* @param enumType 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 search l'élément à rechercher, insensible à la casse
* @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();
for (T el : elements)
if (el.name().equalsIgnoreCase(search))
return el;
if (el.name().equalsIgnoreCase(search)) return el;
return null;
}
/**
* Permet de rechercher l'existance d'un élément dans un enum, de façon insensible à la casse
* La validité de la classe passé en premier paramètre est vérifiée dynamiquement et non
* statiquement. Préférez l'utilisation de {@link #searchEnum(Class, String)} quand c'est possible.
* Permet de rechercher l'existance d'un élément dans un enum, de façon
* insensible à la casse
* La validité de la classe passé en premier paramètre est vérifiée
* dynamiquement et non
* statiquement. Préférez l'utilisation de
* {@link #searchEnum(Class, String)} quand c'est possible.
*
* @param enumType la classe correpondant à l'enum à lister
* @param search l'élément à rechercher, insensible à la casse
* @return l'élément de l'énumération, si elle a été trouvée et si la classe passée en paramètre est un enum, null dans les autres cas
* @return l'élément de l'énumération, si elle a été trouvée et si la classe
* passée en paramètre est un enum, null dans les autres cas
*/
public static Enum<?> searchUncheckedEnum(Class<?> enumType, String search) {
if (!enumType.isEnum())
return null;
if (!enumType.isEnum()) return null;
Enum<?>[] elements = (Enum<?>[]) enumType.getEnumConstants();
for (Enum<?> el : elements)
if (el.name().equalsIgnoreCase(search))
return el;
if (el.name().equalsIgnoreCase(search)) return el;
return null;
}
/**
* Retourne une valeur aléatoire parmis les élément de l'Enum spécifié en paramètre.
* Retourne une valeur aléatoire parmis les élément de l'Enum spécifié en
* paramètre.
*
* @param enumType l'enum dans lequel piocher la valeur
* @return une des valeurs de l'enum
*/

View File

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

View File

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

View File

@ -18,15 +18,14 @@ public enum MinecraftVersion {
versionDisplay = d;
}
@Override
public String toString() {
return versionDisplay;
}
public static MinecraftVersion getVersion(int v) {
for (MinecraftVersion mcV : MinecraftVersion.values())
if (mcV.versionNumber == v)
return mcV;
if (mcV.versionNumber == v) return mcV;
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.Direction;
import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp;
import fr.pandacube.java.util.db2.sql_tools.SQLWhereLike;
import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp.SQLComparator;
import fr.pandacube.java.util.db2.sql_tools.SQLWhereLike;
import net.alpenblock.bungeeperms.BungeePerms;
/*
@ -32,22 +32,18 @@ public class PlayerFinder {
}
public static String getLastKnownName(UUID id) {
if (id == null)
return null;
if (id == null) return null;
// on passe par le plugin de permission (mise en cache ? )
BungeePerms pl = getPermPlugin();
if (pl != null)
return pl.getPermissionsManager().getUUIDPlayerDB().getPlayerName(id);
if (pl != null) return pl.getPermissionsManager().getUUIDPlayerDB().getPlayerName(id);
// on tente en accédant directement à la table des identifiants
try {
SQLUUIDPlayer el = ORM.getFirst(SQLUUIDPlayer.class, new SQLWhereComp(SQLUUIDPlayer.uuid, SQLComparator.EQ, id.toString()), null);
if (el != null)
return el.get(SQLUUIDPlayer.player);
SQLUUIDPlayer el = ORM.getFirst(SQLUUIDPlayer.class,
new SQLWhereComp(SQLUUIDPlayer.uuid, SQLComparator.EQ, id.toString()), null);
if (el != null) return el.get(SQLUUIDPlayer.player);
} catch (Exception e) {
Log.severe("Can't search for player name from uuid in database", e);
}
@ -56,27 +52,22 @@ public class PlayerFinder {
return null;
}
public static List<String> getLocalNameHistory(UUID id) {
List<String> ret = new ArrayList<>();
if (id == null)
return ret;
if (id == null) return ret;
String last = getLastKnownName(id);
if (last != null)
ret.add(last);
if (last != null) ret.add(last);
try {
List<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) {
String name = el.get(SQLLoginHistory.playerName);
if (ret.contains(name))
continue;
if (ret.contains(name)) continue;
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
* cherchera d'abord dans les derniers pseudos connus. Puis, cherchera la dernière personne à
* Cherche un identifiant de compte en se basant sur le pseudo passé en
* paramètre. La méthode
* cherchera d'abord dans les derniers pseudos connus. Puis, cherchera la
* dernière personne à
* s'être connecté avec ce pseudo sur le serveur.
* @param exactName le pseudo complet, insensible à la casse, et dans un format de pseudo valide
*
* @param exactName le pseudo complet, insensible à la casse, et dans un
* format de pseudo valide
* @param old si on doit chercher dans les anciens pseudos de joueurs
* @return l'UUID du joueur si trouvé, null sinon
*/
public static UUID getPlayerId(String exactName, boolean old) {
if (!isValidPlayerName(exactName)) return null; // évite une recherche inutile dans la base de donnée
if (!isValidPlayerName(exactName)) return null; // évite une recherche
// inutile dans la base
// de donnée
// on tente d'abord via le plugin de permission
BungeePerms pl = getPermPlugin();
if (pl != null)
return pl.getPermissionsManager().getUUIDPlayerDB().getUUID(exactName);
if (pl != null) return pl.getPermissionsManager().getUUIDPlayerDB().getUUID(exactName);
// on tente en accédant directement à la table des identifiants
try {
SQLUUIDPlayer el = ORM.getFirst(SQLUUIDPlayer.class, new SQLWhereLike(SQLUUIDPlayer.player, exactName.replace("_", "\\_")), null);
if (el != null)
return el.getUUID();
SQLUUIDPlayer el = ORM.getFirst(SQLUUIDPlayer.class,
new SQLWhereLike(SQLUUIDPlayer.player, exactName.replace("_", "\\_")), null);
if (el != null) return el.getUUID();
} catch (Exception e) {
Log.severe("Can't search for uuid from player name in database", e);
}
@ -123,9 +113,10 @@ public class PlayerFinder {
// on recherche dans les anciens pseudos
try {
SQLLoginHistory el = ORM.getFirst(SQLLoginHistory.class, new SQLWhereLike(SQLLoginHistory.playerName, exactName.replace("_", "\\_")), new SQLOrderBy().addField(SQLLoginHistory.time, Direction.DESC));
if (el != null)
return el.getPlayerId();
SQLLoginHistory el = ORM.getFirst(SQLLoginHistory.class,
new SQLWhereLike(SQLLoginHistory.playerName, exactName.replace("_", "\\_")),
new SQLOrderBy().addField(SQLLoginHistory.time, Direction.DESC));
if (el != null) return el.getPlayerId();
} catch (Exception e) {
Log.severe("Can't search for uuid from old player name in database", e);
}
@ -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
* @return
*/
@ -152,45 +140,42 @@ public class PlayerFinder {
// rechercher parmis les derniers pseudos connus de chaque joueurs
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));
}
} catch (Exception e) {
Log.severe("Can't search for players names in database", e);
}
if (!old) return res;
// rechercher parmi les anciens pseudos de joueurs
try {
List<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) {
if (res.contains(new PlayerSearchResult(el.getPlayerId(), null, null)))
continue;
res.add(new PlayerSearchResult(el.getPlayerId(), getLastKnownName(el.getPlayerId()), el.get(SQLLoginHistory.playerName)));
if (res.contains(new PlayerSearchResult(el.getPlayerId(), null, null))) continue;
res.add(new PlayerSearchResult(el.getPlayerId(), getLastKnownName(el.getPlayerId()),
el.get(SQLLoginHistory.playerName)));
}
} catch (Exception e) {
Log.severe("Can't search for uuid from player name in database", e);
}
return res;
}
public static class PlayerSearchResult {
public final UUID uuid;
public String lastName;
public final String nameFound;
PlayerSearchResult(UUID id, String last, String found) {
uuid = id;
lastName = last;
@ -204,35 +189,20 @@ public class PlayerFinder {
}
@Override
public int hashCode() { return uuid.hashCode(); }
public int hashCode() {
return uuid.hashCode();
}
}
public static boolean isValidPlayerName(String name) {
if (name == null) return false;
return name.matches("[0-9a-zA-Z_]{2,16}");
}
public static SQLPlayer getDBPlayer(UUID id) throws Exception {
if (id == null) return null;
return ORM.getFirst(SQLPlayer.class, new SQLWhereComp(SQLPlayer.playerId, SQLComparator.EQ, id.toString()), null);
return ORM.getFirst(SQLPlayer.class, new SQLWhereComp(SQLPlayer.playerId, SQLComparator.EQ, id.toString()),
null);
}
}

View File

@ -13,8 +13,12 @@ import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
/**
* This class performs a name lookup for a player and gets back all the name changes of the player (if any).
* <br/><a href="https://bukkit.org/threads/player-name-history-lookup.412679/">https://bukkit.org/threads/player-name-history-lookup.412679/</a>
* This class performs a name lookup for a player and gets back all the name
* 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
* @author mine-care (AKA fillpant)
*
@ -29,9 +33,13 @@ public class PlayerNameHistoryLookup {
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.
* @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)}
*/
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>
* Alternative method accepting an {@link OfflinePlayer} (and therefore {@link Player}) objects as parameter.
* <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>
* Alternative method accepting an {@link OfflinePlayer} (and therefore
* {@link Player}) objects as parameter.
*
* @param uuid The UUID String to lookup
* @return Returns an array of {@link PreviousPlayerNameEntry} objects, or null if the response couldn't be interpreted.
* @return Returns an array of {@link PreviousPlayerNameEntry} objects, or
* null if the response couldn't be interpreted.
* @throws IOException {@link #getRawJsonResponse(String)}
*/
public static PreviousPlayerNameEntry[] getPlayerPreviousNames(String uuid) throws IOException {
if (uuid == null || uuid.isEmpty())
return null;
if (uuid == null || uuid.isEmpty()) return null;
uuid = uuid.replace("-", "");
String response = getRawJsonResponse(new URL(String.format(LOOKUP_URL, uuid)));
PreviousPlayerNameEntry[] names = JSON_PARSER.fromJson(response, PreviousPlayerNameEntry[].class);
@ -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
* @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 {
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 {
private String name;
@ -82,6 +99,7 @@ public class PlayerNameHistoryLookup {
/**
* Gets the player name of this entry.
*
* @return The name of the player.
*/
public String getPlayerName() {
@ -90,17 +108,25 @@ public class PlayerNameHistoryLookup {
/**
* 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>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 :)
* <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>
* 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() {
return changeTime;
}
/**
* Check if this name is the name used to register the account (the initial/original name)
* @return a boolean, true if it is the the very first name of the player, otherwise false.
* Check if this name is the name used to register the account (the
* initial/original name)
*
* @return a boolean, true if it is the the very first name of the
* player, otherwise false.
*/
public boolean isPlayersInitialName() {
return getChangeTime() == 0;
@ -112,8 +138,6 @@ public class PlayerNameHistoryLookup {
}
}
public static void main(String[] args) throws IOException {
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 int nextIntBetween(int minInclu, int maxExclu) {
return rand.nextInt(maxExclu - minInclu) + minInclu;
}
public static double nextDoubleBetween(double minInclu, double maxExclu) {
return rand.nextDouble() * (maxExclu - minInclu) + minInclu;
}

View File

@ -17,7 +17,6 @@ public class ServerPropertyFile {
private Map<String, Object> data;
public ServerPropertyFile(File f) {
if (f == null) throw new IllegalArgumentException("f ne doit pas être null");
file = f;
@ -31,9 +30,9 @@ public class ServerPropertyFile {
data.put("isLobby", false);
}
/**
* Charge le fichier de configuration dans cette instance de la classe
*
* @return true si le chargement a réussi, false sinon
*/
public boolean loadFromFile() {
@ -41,36 +40,28 @@ public class ServerPropertyFile {
try {
in = new BufferedReader(new FileReader(file));
@SuppressWarnings("unchecked")
Map<String, Object> dataFile = new Gson().fromJson(in, Map.class);
if (!dataFile.containsKey("name") || !(dataFile.get("name") instanceof String))
return false;
if (!dataFile.containsKey("name") || !(dataFile.get("name") instanceof String)) return false;
if (!dataFile.containsKey("memory") || !(dataFile.get("memory") instanceof String))
return false;
if (!dataFile.containsKey("memory") || !(dataFile.get("memory") instanceof String)) return false;
if (!dataFile.containsKey("javaArgs") || !(dataFile.get("javaArgs") instanceof String))
return false;
if (!dataFile.containsKey("javaArgs") || !(dataFile.get("javaArgs") instanceof String)) return false;
if (!dataFile.containsKey("MinecraftArgs") || !(dataFile.get("MinecraftArgs") instanceof String))
return false;
if (!dataFile.containsKey("jarFile") || !(dataFile.get("jarFile") instanceof String))
return false;
if (!dataFile.containsKey("jarFile") || !(dataFile.get("jarFile") instanceof String)) return false;
if (!dataFile.containsKey("isLobby") || !(dataFile.get("isLobby") instanceof Boolean))
return false;
if (!dataFile.containsKey("isLobby") || !(dataFile.get("isLobby") instanceof Boolean)) return false;
data = dataFile;
return true;
}
catch (IOException e) {
} catch (IOException e) {
e.printStackTrace();
}
finally {
} finally {
try {
in.close();
} catch (Exception e) {}
@ -78,8 +69,6 @@ public class ServerPropertyFile {
return false;
}
public boolean save() {
BufferedWriter out = null;
try {
@ -94,8 +83,7 @@ public class ServerPropertyFile {
return true;
} catch (IOException e) {
e.printStackTrace();
}
finally {
} finally {
try {
out.close();
} catch (Exception e) {}
@ -104,58 +92,52 @@ public class ServerPropertyFile {
return false;
}
public String getName() {
return (String) data.get("name");
}
public String getMemory() {
return (String) data.get("memory");
}
public String getJavaArgs() {
return (String) data.get("javaArgs");
}
public String getMinecraftArgs() {
return (String) data.get("MinecraftArgs");
}
public String getJarFile() {
return (String) data.get("jarFile");
}
public boolean getIsLobby() {
return (boolean) data.get("isLobby");
}
public void setName(String n) {
if (n == null || !n.matches("^[a-zA-Z]$"))
throw new IllegalArgumentException();
if (n == null || !n.matches("^[a-zA-Z]$")) throw new IllegalArgumentException();
data.put("name", n);
}
public void setMemory(String m) {
if (m == null || !m.matches("^[0-9]+[mgMG]$"))
throw new IllegalArgumentException();
if (m == null || !m.matches("^[0-9]+[mgMG]$")) throw new IllegalArgumentException();
data.put("memory", m);
}
public void setJavaArgs(String ja) {
if (ja == null)
throw new IllegalArgumentException();
if (ja == null) throw new IllegalArgumentException();
data.put("javaArgs", ja);
}
public void setMinecraftArgs(String ma) {
if (ma == null)
throw new IllegalArgumentException();
if (ma == null) throw new IllegalArgumentException();
data.put("MinecraftArgs", ma);
}
public void setJarFile(String j) {
if (j == null)
throw new IllegalArgumentException();
if (j == null) throw new IllegalArgumentException();
data.put("jarFile", j);
}
@ -163,5 +145,4 @@ public class ServerPropertyFile {
data.put("isLobby", l);
}
}

View File

@ -1,10 +1,8 @@
package fr.pandacube.java.util;
public class StringUtil {
public static String formatDouble(double d)
{
if(d == (long) d)
return String.format("%d",(long)d);
public static String formatDouble(double d) {
if (d == (long) d) return String.format("%d", (long) d);
else
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
* @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();
int count = 0;
for (char c : chars)
if (c == c_match)
count++;
if (c == c_match) count++;
return count;
}
}

View File

@ -14,71 +14,66 @@ public class Display {
private BaseComponent current = null;
public Display() {
}
public Display() {}
/**
* Après l'appel de ce contructeur, vous devez appeler nextComponent() pour initialiser la composante suivante
* Après l'appel de ce contructeur, vous devez appeler nextComponent() pour
* initialiser la composante suivante
*/
public Display(String legacyText) {
convertAndAddLegacy(legacyText);
}
/**
* Construit un message en mettant à la ligne après chaque chaine passé en paramètre.<br/>
* Après l'appel de ce contructeur, vous devez appeler nextComponent() pour initialiser la composante suivante
* Construit un message en mettant à la ligne après chaque chaine passé en
* paramètre.<br/>
* Après l'appel de ce contructeur, vous devez appeler nextComponent() pour
* initialiser la composante suivante
*/
public Display(String[] legacyText) {
boolean f = true;
for (String s : legacyText) {
if (s == null) s = "";
if (!f)
first.addExtra("\n");
if (!f) first.addExtra("\n");
f = false;
convertAndAddLegacy(s);
}
}
/**
* Construit un message en mettant à la ligne après chaque chaine passé en paramètre.<br/>
* Après l'appel de ce contructeur, vous devez appeler nextComponent() pour initialiser la composante suivante
* Construit un message en mettant à la ligne après chaque chaine passé en
* paramètre.<br/>
* Après l'appel de ce contructeur, vous devez appeler nextComponent() pour
* initialiser la composante suivante
*/
public Display(List<String> legacyText) {
this(legacyText.toArray(new String[legacyText.size()]));
}
/**
* Après l'appel de ce contructeur, vous devez appeler nextComponent() pour initialiser la composante suivante
* Après l'appel de ce contructeur, vous devez appeler nextComponent() pour
* initialiser la composante suivante
*/
public Display(BaseComponent firstComponent) {
if (firstComponent == null) throw new IllegalArgumentException("le paramètre ne doit pas être null");
first.addExtra(firstComponent);
}
/**
* Après l'appel de cette méthode, vous devez appeler nextComponent() pour initialiser la composante suivante
* Après l'appel de cette méthode, vous devez appeler nextComponent() pour
* initialiser la composante suivante
*/
public Display convertAndAddLegacy(String legacyText) {
finalizeCurrentComponent();
if (legacyText == null)
return this;
if (legacyText == null) return this;
BaseComponent[] compo = TextComponent.fromLegacyText(legacyText);
for (BaseComponent c : compo) {
for (BaseComponent c : compo)
first.addExtra(c);
}
return this;
}
public Display nextComponent(String str) {
finalizeCurrentComponent();
if (str == null) str = "";
@ -86,9 +81,6 @@ public class Display {
return this;
}
public Display addComponent(BaseComponent cmp) {
if (cmp == null) throw new IllegalArgumentException("le paramètre ne doit pas être null");
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() {
finalizeCurrentComponent();
@ -155,28 +148,11 @@ public class Display {
return this;
}
private void finalizeCurrentComponent() {
if (current != null)
first.addExtra(current);
if (current != null) first.addExtra(current);
current = null;
}
public BaseComponent get() {
finalizeCurrentComponent();
return first;

View File

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

View File

@ -11,21 +11,20 @@ public class TextProgressBar {
private static String pattern_empty = ".";
private static String pattern_full = "|";
public static String progressBar(double[] values, ChatColor[] colors, double total, int nbCar)
{
public static String progressBar(double[] values, ChatColor[] colors, double total, int nbCar) {
long[] sizes = new long[values.length];
int max_size = nbCar - pattern_start.length() - pattern_end.length();
for (int i=0; i<values.length; i++)
{
for (int i = 0; i < values.length; i++) {
double sum_values_before = 0;
for (int j = i; j >= 0; j--)
sum_values_before += values[j];
long car_position = Math.round(max_size * sum_values_before / total);
// évite les barre de progressions plus grandes que la taille demandée
// évite les barre de progressions plus grandes que la taille
// demandée
if (car_position > max_size) car_position = max_size;
long sum_sizes_before = 0;
@ -36,15 +35,12 @@ public class TextProgressBar {
}
int sum_sizes = 0;
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];
ChatColor color = color_default;
if (colors != null && i < colors.length && colors[i] != null)
color = colors[i];
if (colors != null && i < colors.length && colors[i] != null) color = colors[i];
bar = bar + color;
@ -60,11 +56,8 @@ public class TextProgressBar {
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);
}
}

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

View File

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

View File

@ -7,15 +7,21 @@ import fr.pandacube.java.util.db2.sql_tools.SQLType;
public class SQLForumForum extends SQLElement {
public SQLForumForum() {
super();
}
public SQLForumForum() { super(); }
public SQLForumForum(int id) { super(id); }
public SQLForumForum(int id) {
super(id);
}
@Override
protected String tableName() { return "pandacube_forum_forum"; }
protected String tableName() {
return "pandacube_forum_forum";
}
public static final SQLFKField<Integer, SQLForumCategorie> catId = SQLFKField.idFK("catId", SQLType.INT, false, SQLForumCategorie.class);
public static final SQLFKField<Integer, SQLForumCategorie> catId = SQLFKField.idFK("catId", SQLType.INT, false,
SQLForumCategorie.class);
public static final SQLField<String> nom = new SQLField<>("nom", SQLType.VARCHAR(100), false);
public static final SQLField<String> description = new SQLField<>("description", SQLType.TEXT, 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> 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 SQLForumPost() {
super();
}
public SQLForumPost() { super(); }
public SQLForumPost(int id) { super(id); }
public SQLForumPost(int id) {
super(id);
}
@Override
protected String tableName() { return "pandacube_forum_post"; }
protected String tableName() {
return "pandacube_forum_post";
}
public static final SQLField<String> createur = new SQLField<>("createur", SQLType.CHAR(36), false);
public static final SQLField<String> texte = new SQLField<>("texte", SQLType.TEXT, false);
public static final SQLField<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 UUID getCreateurId() {
String id = (String)get(createur);
String id = get(createur);
return (id == null) ? null : UUID.fromString(id);
}
public void setCreateurId(UUID pName) {
set(createur, (pName == null) ? (String) null : pName.toString());
}
}

View File

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

View File

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

View File

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

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

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

View File

@ -9,50 +9,47 @@ import fr.pandacube.java.util.db2.sql_tools.SQLType;
public class SQLModoHistory extends SQLElement {
public SQLModoHistory() {
super();
}
public SQLModoHistory() { super(); }
public SQLModoHistory(int id) { super(id); }
public SQLModoHistory(int id) {
super(id);
}
@Override
protected String tableName() { return "pandacube_modo_history"; }
protected String tableName() {
return "pandacube_modo_history";
}
public static final SQLFKField<String, SQLPlayer> modoId = new SQLFKField<>("modoId", SQLType.CHAR(36), true, SQLPlayer.class, SQLPlayer.playerId);
public static final SQLField<ActionType> actionType = new SQLField<>("actionType", SQLType.ENUM(ActionType.class), false);
public static final SQLFKField<String, SQLPlayer> modoId = new SQLFKField<>("modoId", SQLType.CHAR(36), true,
SQLPlayer.class, SQLPlayer.playerId);
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 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<String> message = new SQLField<>("message", SQLType.VARCHAR(512), false);
public UUID getModoId() {
String id = (String)get(modoId);
String id = get(modoId);
return (id == null) ? null : UUID.fromString(id);
}
public void setModoId(UUID pName) {
set(modoId, (pName == null) ? (String) null : pName.toString());
}
public UUID getPlayerId() {
String id = (String)get(playerId);
String id = get(playerId);
return (id == null) ? null : UUID.fromString(id);
}
public void setPlayerId(UUID pName) {
set(playerId, (pName == null) ? (String) null : pName.toString());
}
public enum ActionType {
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 SQLOnlineshopHistory() {
super();
}
public SQLOnlineshopHistory() { super(); }
public SQLOnlineshopHistory(int id) { super(id); }
public SQLOnlineshopHistory(int id) {
super(id);
}
@Override
protected String tableName() { return "pandacube_onlineshop_history"; }
protected String tableName() {
return "pandacube_onlineshop_history";
}
public static final SQLField<Long> time = new SQLField<>("time", SQLType.BIGINT, false);
public static final SQLField<String> transactionId = new SQLField<>("transactionId", SQLType.VARCHAR(255), true);
public static final SQLField<SourceType> sourceType = new SQLField<>("sourceType", SQLType.ENUM(SourceType.class), false);
public static final SQLFKField<String, SQLPlayer> sourcePlayerId = new SQLFKField<>("sourcePlayerId", SQLType.CHAR(36), true, SQLPlayer.class, SQLPlayer.playerId);
public static final SQLField<SourceType> sourceType = new SQLField<>("sourceType", SQLType.ENUM(SourceType.class),
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<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 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<String> destName = new SQLField<>("destName", SQLType.VARCHAR(64), false);
public UUID getSourcePlayerId() {
String id = (String)get(sourcePlayerId);
String id = get(sourcePlayerId);
return (id == null) ? null : UUID.fromString(id);
}
public void setSourcePlayerId(UUID pName) {
set(sourcePlayerId, (pName == null) ? (String) null : pName.toString());
}
public UUID getDestPlayerId() {
String id = (String)get(destPlayerId);
String id = get(destPlayerId);
return (id == null) ? null : UUID.fromString(id);
}
public void setDestPlayerId(UUID pName) {
set(destPlayerId, (pName == null) ? (String) null : pName.toString());
}
public static enum SourceType {
REAL_MONEY, BAMBOU
}
@ -68,5 +62,4 @@ public class SQLOnlineshopHistory extends SQLElement {
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.SQLComparator;
public class SQLPlayer extends SQLElement {
public SQLPlayer() { super(); }
public SQLPlayer(int id) { super(id); }
public SQLPlayer() {
super();
}
public SQLPlayer(int id) {
super(id);
}
/*
* Nom de la table
*/
@Override
protected String tableName() { return "pandacube_player"; }
protected String tableName() {
return "pandacube_player";
}
/*
* Champs de la table
@ -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> 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> 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> timeWebRegister = new SQLField<>("timeWebRegister", 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<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<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<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> 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<String> grade = new SQLField<>("grade", SQLType.VARCHAR(36), false, "default");
/*
* Getteurs spécifique (encapsulation)
*/
public UUID getPlayerId() {
String id = (String)get(playerId);
String id = get(playerId);
return (id == null) ? null : UUID.fromString(id);
}
public UUID getToken() {
String id = (String)get(token);
String id = get(token);
return (id == null) ? null : UUID.fromString(id);
}
/*
* Setteurs spécifique (encapsulation)
*/
public void setPlayerId(UUID pName) {
set(playerId, (pName == null) ? (String) null : pName.toString());
}
public void setToken(UUID t) {
set(token, (t == null) ? (String) null : t.toString());
}
public static SQLPlayer getPlayerFromUUID(UUID playerId) throws ORMException {
return ORM.getFirst(SQLPlayer.class,
new SQLWhereComp(SQLPlayer.playerId, SQLComparator.EQ, playerId.toString()),
null);
new SQLWhereComp(SQLPlayer.playerId, SQLComparator.EQ, playerId.toString()), null);
}
}

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.SQLType;
import fr.pandacube.java.util.db2.sql_tools.SQLWhereChain;
import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp;
import fr.pandacube.java.util.db2.sql_tools.SQLWhereChain.SQLBoolOp;
import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp;
import fr.pandacube.java.util.db2.sql_tools.SQLWhereComp.SQLComparator;
public class SQLPlayerIgnore extends SQLElement {
public SQLPlayerIgnore() { super(); }
public SQLPlayerIgnore(int id) { super(id); }
@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() {
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 = get(ignorer);
return (id == null) ? null : UUID.fromString(id);
}
public void setIgnorerId(UUID pName) {
set(ignorer, (pName == null) ? (String) null : pName.toString());
}
public UUID getIgnoredId() {
String id = (String)get(ignored);
String id = get(ignored);
return (id == null) ? null : UUID.fromString(id);
}
public void setIgnoredId(UUID pName) {
set(ignored, (pName == null) ? (String) null : pName.toString());
}
public static SQLPlayerIgnore getPlayerIgnoringPlayer(UUID ignorer, UUID ignored) throws Exception {
return ORM.getFirst(SQLPlayerIgnore.class,
new SQLWhereChain(SQLBoolOp.AND)
@ -61,6 +59,7 @@ public class SQLPlayerIgnore extends SQLElement {
.add(new SQLWhereComp(SQLPlayerIgnore.ignored, SQLComparator.EQ, ignored.toString())),
null);
}
public static boolean isPlayerIgnoringPlayer(UUID ignorer, UUID ignored) throws Exception {
return getPlayerIgnoringPlayer(ignorer, ignored) != null;
}
@ -81,18 +80,14 @@ public class SQLPlayerIgnore extends SQLElement {
}
public static List<UUID> getListIgnoredPlayer(UUID ignorer) throws Exception {
List<SQLPlayerIgnore> els = ORM.getAll(SQLPlayerIgnore.class,
new SQLWhereComp(SQLPlayerIgnore.ignorer, SQLComparator.EQ, ignorer.toString()),
new SQLOrderBy().addField(ORM.getSQLIdField(SQLPlayerIgnore.class)), null, null);
List<UUID> ret = new ArrayList<>(els.size());
for (SQLPlayerIgnore el : els) {
for (SQLPlayerIgnore el : els)
ret.add(el.getIgnoredId());
}
return ret;
}
}

View File

@ -6,18 +6,22 @@ import fr.pandacube.java.util.db2.sql_tools.SQLType;
public class SQLShopStock extends SQLElement {
public SQLShopStock() {
super();
}
public SQLShopStock() { super(); }
public SQLShopStock(int id) { super(id); }
public SQLShopStock(int id) {
super(id);
}
@Override
protected String tableName() { return "pandacube_shop_stock"; }
protected String tableName() {
return "pandacube_shop_stock";
}
public static final SQLField<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<Double> quantity = new SQLField<>("quantity", SQLType.DOUBLE, 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 SQLStaffTicket() {
super();
}
public SQLStaffTicket() { super(); }
public SQLStaffTicket(int id) { super(id); }
public SQLStaffTicket(int id) {
super(id);
}
@Override
protected String tableName() { return "pandacube_staff_ticket"; }
protected String tableName() {
return "pandacube_staff_ticket";
}
public static final SQLFKField<String, SQLPlayer> playerId = new SQLFKField<>("playerId", SQLType.CHAR(36), false, SQLPlayer.class, SQLPlayer.playerId);
public static final SQLFKField<String, SQLPlayer> playerId = new SQLFKField<>("playerId", SQLType.CHAR(36), false,
SQLPlayer.class, SQLPlayer.playerId);
public static final SQLField<String> message = new SQLField<>("message", SQLType.VARCHAR(1024), false);
public static final SQLField<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() {
String id = get(playerId);
return (id == null) ? null : UUID.fromString(id);
}
public void setPlayerId(UUID id) {
set(playerId, (id == null) ? null : id.toString());
}
public UUID getstaffPlayerId() {
String id = get(staffPlayerId);
return (id == null) ? null : UUID.fromString(id);
}
public void setstaffPlayerId(UUID id) {
set(staffPlayerId, (id == null) ? null : id.toString());
}

View File

@ -6,13 +6,18 @@ import fr.pandacube.java.util.db2.sql_tools.SQLType;
public class SQLStaticPages extends SQLElement {
public SQLStaticPages() {
super();
}
public SQLStaticPages() { super(); }
public SQLStaticPages(int id) { super(id); }
public SQLStaticPages(int id) {
super(id);
}
@Override
protected String tableName() { return "pandacube_static_pages"; }
protected String tableName() {
return "pandacube_static_pages";
}
public static final SQLField<String> permalink = new SQLField<>("permalink", 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> 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 SQLUUIDPlayer() { super(); }
public SQLUUIDPlayer(int id) { super(id); }
public SQLUUIDPlayer() {
super();
}
public SQLUUIDPlayer(int id) {
super(id);
}
@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 UUID getUUID() {
String id = get(uuid);
return (id == null) ? null : UUID.fromString(id);
}
public void setUUID(UUID id) {
set(uuid, (id == null) ? null : id.toString());
}

View File

@ -11,7 +11,8 @@ public class DBConnection {
String login;
String pass;
public DBConnection(String host, int port, String dbname, String l, String p) throws ClassNotFoundException, SQLException {
public DBConnection(String host, int port, String dbname, String l, String p)
throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
url = "jdbc:mysql://" + host + ":" + port + "/" + dbname;
login = l;
@ -19,34 +20,27 @@ public class DBConnection {
connect();
}
public void reconnectIfNecessary() throws SQLException
{
try
{
public void reconnectIfNecessary() throws SQLException {
try {
Statement stmt = conn.createStatement();
stmt.close();
}
catch(SQLException e)
{
try { close(); } catch(Exception ex) { }
} catch (SQLException e) {
try {
close();
} catch (Exception ex) {}
connect();
}
}
public Connection getNativeConnection() throws SQLException
{
if (!conn.isValid(1))
reconnectIfNecessary();
public Connection getNativeConnection() throws SQLException {
if (!conn.isValid(1)) reconnectIfNecessary();
return conn;
}
private void connect() throws SQLException {
conn = DriverManager.getConnection(url, login, pass);
}
public void close() {
try {
conn.close();

View File

@ -33,6 +33,7 @@ import javafx.util.Pair;
/**
* <b>ORM = Object-Relational Mapping</b>
*
* @author Marc Baloup
*
*/
@ -46,15 +47,14 @@ public final class ORM {
return connection;
}
public synchronized static void init(DBConnection conn) {
connection = conn;
/*
* Les tables à initialiser
*
* utile des les initialiser ici, car on peut tout de suite déceler les bugs ou erreurs dans la déclaration des SQLFields
* utile des les initialiser ici, car on peut tout de suite déceler les
* bugs ou erreurs dans la déclaration des SQLFields
*/
try {
@ -79,29 +79,20 @@ public final class ORM {
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 {
if (tables.contains(elemClass))
return;
if (tables.contains(elemClass)) return;
try {
T instance = elemClass.newInstance();
String tableName = instance.tableName();
if (!tableExist(tableName))
createTable(instance);
if (!tableExist(tableName)) createTable(instance);
tables.add(elemClass);
} catch (Exception e) {
throw new ORMInitTableException(elemClass, e);
}
}
private static <T extends SQLElement> void createTable(T elem) throws SQLException {
String sql = "CREATE TABLE IF NOT EXISTS " + elem.tableName() + " (";
@ -118,15 +109,11 @@ public final class ORM {
sql += statementPart.getKey();
}
sql += ", PRIMARY KEY id(id))";
PreparedStatement ps = connection.getNativeConnection().prepareStatement(sql);
int i = 1;
for (Object val : params) {
for (Object val : params)
ps.setObject(i++, val);
}
try {
Log.info("Creating table " + elem.tableName() + ":\n" + ps.toString());
ps.executeUpdate();
@ -135,12 +122,6 @@ public final class ORM {
}
}
private static boolean tableExist(String tableName) throws SQLException {
ResultSet set = null;
boolean exist = false;
@ -148,25 +129,20 @@ public final class ORM {
set = connection.getNativeConnection().getMetaData().getTables(null, null, tableName, null);
exist = set.next();
} finally {
if (set != null)
set.close();
if (set != null) set.close();
}
return exist;
}
@SuppressWarnings("unchecked")
public static <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);
return (SQLField<Integer>) SQLElement.fieldsCache.get(elemClass).get("id");
}
public static <T extends SQLElement> List<T> getByIds(Class<T> elemClass, Collection<Integer> ids) throws ORMException {
public static <T extends SQLElement> List<T> getByIds(Class<T> elemClass, Collection<Integer> ids)
throws ORMException {
return getByIds(elemClass, ids.toArray(new Integer[ids.size()]));
}
@ -174,8 +150,7 @@ public final class ORM {
SQLField<Integer> idField = getSQLIdField(elemClass);
SQLWhereChain where = new SQLWhereChain(SQLBoolOp.OR);
for (Integer id : ids)
if (id != null)
where.add(new SQLWhereComp(idField, SQLComparator.EQ, id));
if (id != null) where.add(new SQLWhereComp(idField, SQLComparator.EQ, id));
return getAll(elemClass, where, new SQLOrderBy().addField(idField), 1, null);
}
@ -183,18 +158,18 @@ public final class ORM {
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);
return (elts.size() == 0) ? null : elts.get(0);
}
public static <T extends SQLElement> SQLElementList<T> getAll(Class<T> elemClass) throws ORMException {
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);
try {
@ -207,12 +182,9 @@ public final class ORM {
sql += " WHERE " + ret.getKey();
params.addAll(ret.getValue());
}
if (orderBy != null)
sql += " ORDER BY "+orderBy.toSQL();
if (limit != null)
sql += " LIMIT "+limit;
if (offset != null)
sql += " OFFSET "+offset;
if (orderBy != null) sql += " ORDER BY " + orderBy.toSQL();
if (limit != null) sql += " LIMIT " + limit;
if (offset != null) sql += " OFFSET " + offset;
sql += ";";
SQLElementList<T> elmts = new SQLElementList<T>();
@ -223,8 +195,7 @@ public final class ORM {
int i = 1;
for (Object val : params) {
if (val instanceof Enum<?>)
val = ((Enum<?>)val).name();
if (val instanceof Enum<?>) val = ((Enum<?>) val).name();
ps.setObject(i++, val);
}
Log.debug(ps.toString());
@ -247,19 +218,6 @@ public final class ORM {
}
private static <T extends SQLElement> T getElementInstance(ResultSet set, Class<T> elemClass) throws ORMException {
try {
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++) {
String fieldName = set.getMetaData().getColumnLabel(c);
if (!instance.getFields().containsKey(fieldName))
continue; // ignore when field is present in database but not handled by SQLElement instance
if (!instance.getFields().containsKey(fieldName)) continue; // ignore
// when
// field
// is
// present
// in
// database
// but
// not
// handled
// by
// SQLElement
// instance
@SuppressWarnings("unchecked")
SQLField<Object> sqlField = (SQLField<Object>) instance.getFields().get(fieldName);
if (sqlField.type.getJavaType().isEnum()) {
// JDBC ne supporte pas les enums
String enumStrValue = set.getString(c);
if (enumStrValue == null || set.wasNull())
instance.set(sqlField, null, false);
if (enumStrValue == null || set.wasNull()) instance.set(sqlField, null, false);
else {
Enum<?> enumValue = EnumUtil.searchUncheckedEnum(sqlField.type.getJavaType(), enumStrValue);
if (enumValue == null)
throw new ORMException("The enum constant '"+enumStrValue+"' is not found in enum class "+sqlField.type.getJavaType().getName());
if (enumValue == null) throw new ORMException("The enum constant '" + enumStrValue
+ "' is not found in enum class " + sqlField.type.getJavaType().getName());
instance.set(sqlField, enumValue, false);
}
}
else {
Object val = set.getObject(c, sqlField.type.getJavaType());
if (val == null || set.wasNull())
instance.set(sqlField, null, false);
if (val == null || set.wasNull()) instance.set(sqlField, null, false);
else
instance.set(sqlField, val, false);
}
// la valeur venant de la BDD est marqué comme "non modifié" dans l'instance
// car le constructeur de l'instance met tout les champs comme modifiés
// la valeur venant de la BDD est marqué comme "non modifié"
// dans l'instance
// car le constructeur de l'instance met tout les champs comme
// modifiés
instance.modifiedSinceLastSave.remove(sqlField.name);
}
if (!instance.isValidForSave())
throw new ORMException("This SQLElement representing a database entry is not valid for save : "+instance.toString());
if (!instance.isValidForSave()) throw new ORMException(
"This SQLElement representing a database entry is not valid for save : " + instance.toString());
return instance;
} catch (ReflectiveOperationException | IllegalArgumentException | SecurityException | SQLException e) {
@ -306,56 +275,26 @@ public final class ORM {
}
}
private ORM() {} // rend la classe non instanciable
/*
public static void main(String[] args) throws Throwable {
ORM.init(new DBConnection("localhost", 3306, "pandacube", "pandacube", "pandacube"));
List<SQLPlayer> players = ORM.getAll(SQLPlayer.class,
new SQLWhereChain(SQLBoolOp.AND)
.add(new SQLWhereNull(SQLPlayer.banTimeout, true))
.add(new SQLWhereChain(SQLBoolOp.OR)
.add(new SQLWhereComp(SQLPlayer.bambou, SQLComparator.EQ, 0L))
.add(new SQLWhereComp(SQLPlayer.grade, SQLComparator.EQ, "default"))
),
new SQLOrderBy().addField(SQLPlayer.playerDisplayName), null, null);
for(SQLPlayer p : players) {
System.out.println(p.get(SQLPlayer.playerDisplayName));
}
// TODO LIST
* public static void main(String[] args) throws Throwable {
* ORM.init(new DBConnection("localhost", 3306, "pandacube", "pandacube",
* "pandacube"));
* List<SQLPlayer> players = ORM.getAll(SQLPlayer.class,
* new SQLWhereChain(SQLBoolOp.AND)
* .add(new SQLWhereNull(SQLPlayer.banTimeout, true))
* .add(new SQLWhereChain(SQLBoolOp.OR)
* .add(new SQLWhereComp(SQLPlayer.bambou, SQLComparator.EQ, 0L))
* .add(new SQLWhereComp(SQLPlayer.grade, SQLComparator.EQ, "default"))
* ),
* new SQLOrderBy().addField(SQLPlayer.playerDisplayName), null, null);
* for(SQLPlayer p : players) {
* System.out.println(p.get(SQLPlayer.playerDisplayName));
* }
* // TODO LIST
* - Gérer mise à jour relative d'un champ (incrément / décrément)
}
* }
*/
}

View File

@ -3,8 +3,6 @@ package fr.pandacube.java.util.db2.sql_tools;
public class ORMInitTableException extends ORMException {
private static final long serialVersionUID = 1L;
/* package */ <T extends SQLElement> ORMInitTableException(Class<T> tableElem) {
super("Error while initializing table " + tableElem.getName());
}
@ -13,6 +11,4 @@ public class ORMInitTableException extends ORMException {
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 */
/* package */ static final Map<Class<? extends SQLElement>, SQLFieldMap> fieldsCache = new HashMap<>();
DBConnection db = ORM.getConnection();
private boolean stored = false;
@ -39,11 +36,9 @@ public abstract class SQLElement {
private final Map<SQLField<?>, Object> values;
/* package */ final Set<String> modifiedSinceLastSave;
public SQLElement() {
tableName = tableName();
if (fieldsCache.get(getClass()) == null) {
fields = new SQLFieldMap(getClass());
@ -53,19 +48,16 @@ public abstract class SQLElement {
generateFields(fields);
fieldsCache.put(getClass(), fields);
}
else {
else
fields = fieldsCache.get(getClass());
}
values = new LinkedHashMap<>(fields.size());
modifiedSinceLastSave = new HashSet<>(fields.size());
initDefaultValues();
}
protected SQLElement(int id) {
this();
@SuppressWarnings("unchecked")
@ -80,35 +72,25 @@ public abstract class SQLElement {
*/
protected abstract String tableName();
@SuppressWarnings("unchecked")
private void initDefaultValues() {
// remplissage des données par défaut (si peut être null ou si valeur par défaut existe)
for (@SuppressWarnings("rawtypes") SQLField f : fields.values()) {
if (f.defaultValue != null) {
set(f, f.defaultValue);
} else if (f.canBeNull || (f.autoIncrement && !stored)) {
set(f, null);
}
}
// remplissage des données par défaut (si peut être null ou si valeur
// par défaut existe)
for (@SuppressWarnings("rawtypes")
SQLField f : fields.values())
if (f.defaultValue != null) set(f, f.defaultValue);
else if (f.canBeNull || (f.autoIncrement && !stored)) set(f, null);
}
protected void generateFields(SQLFieldMap listToFill) {
java.lang.reflect.Field[] declaredFields = getClass().getDeclaredFields();
for (java.lang.reflect.Field field : declaredFields) {
if (!java.lang.reflect.Modifier.isStatic(field.getModifiers()))
continue;
if (!java.lang.reflect.Modifier.isStatic(field.getModifiers())) continue;
try {
Object val = field.get(null);
if (val == null || !(val instanceof SQLField))
continue;
if (val == null || !(val instanceof SQLField)) continue;
listToFill.addField((SQLField<?>) val);
} catch (IllegalArgumentException | IllegalAccessException e) {
@ -116,86 +98,64 @@ public abstract class SQLElement {
}
}
}
/* package */ Map<String, SQLField<?>> getFields() {
return Collections.unmodifiableMap(fields);
}
public Map<SQLField<?>, Object> getValues() {
return Collections.unmodifiableMap(values);
}
public <T> void set(SQLField<T> field, T value) {
set(field, value, true);
}
/* package */ <T> void set(SQLField<T> sqlField, T value, boolean setModified) {
if (sqlField == null)
throw new IllegalArgumentException("sqlField can't be null");
if (sqlField == null) throw new IllegalArgumentException("sqlField can't be null");
if (!fields.containsValue(sqlField))
throw new IllegalArgumentException(sqlField.name + " is not a SQLField of " + getClass().getName());
boolean modify = false;
if (value == null) {
if (sqlField.canBeNull || (sqlField.autoIncrement && !stored))
modify = true;
if (sqlField.canBeNull || (sqlField.autoIncrement && !stored)) modify = true;
else
throw new IllegalArgumentException("SQLField '" + sqlField.name + "' of " + getClass().getName() + " is a NOT NULL field");
} else {
if (sqlField.type.isAssignableFrom(value))
modify = true;
else
throw new IllegalArgumentException("SQLField '" + sqlField.name + "' of " + getClass().getName() + " type is '" + sqlField.type.toString() + "' and can't accept values of type " + value.getClass().getName());
throw new IllegalArgumentException(
"SQLField '" + sqlField.name + "' of " + getClass().getName() + " is a NOT NULL field");
}
else if (sqlField.type.isAssignableFrom(value)) modify = true;
else
throw new IllegalArgumentException("SQLField '" + sqlField.name + "' of " + getClass().getName()
+ " type is '" + sqlField.type.toString() + "' and can't accept values of type "
+ value.getClass().getName());
if (modify) {
if (!values.containsKey(sqlField)) {
if (modify) if (!values.containsKey(sqlField)) {
values.put(sqlField, value);
if (setModified)
modifiedSinceLastSave.add(sqlField.name);
if (setModified) modifiedSinceLastSave.add(sqlField.name);
}
else {
Object oldVal = values.get(sqlField);
if (!Objects.equals(oldVal, value)) {
values.put(sqlField, value);
if (setModified)
modifiedSinceLastSave.add(sqlField.name);
if (setModified) modifiedSinceLastSave.add(sqlField.name);
}
// sinon, rien n'est modifié
}
}
}
public <T> T get(SQLField<T> field) {
if (field == null)
throw new IllegalArgumentException("field can't be null");
if (field == null) throw new IllegalArgumentException("field can't be null");
if (values.containsKey(field)) {
@SuppressWarnings("unchecked")
T val = (T) values.get(field);
return val;
}
throw new IllegalArgumentException("The field '" + field.name + "' in this instance of " + getClass().getName() + " does not exist or is not set");
throw new IllegalArgumentException("The field '" + field.name + "' in this instance of " + getClass().getName()
+ " does not exist or is not set");
}
public <T, E extends SQLElement> E getForeign(SQLFKField<T, E> field) throws ORMException {
T fkValue = get(field);
if (fkValue == null) return null;
@ -203,31 +163,22 @@ public abstract class SQLElement {
new SQLWhereComp(field.getForeignField(), SQLComparator.EQ, fkValue), null);
}
public boolean isValidForSave() {
return values.keySet().containsAll(fields.values());
}
private Map<SQLField<?>, Object> getOnlyModifiedValues() {
Map<SQLField<?>, Object> modifiedValues = new LinkedHashMap<>();
values.forEach((k, v) -> {
if (modifiedSinceLastSave.contains(k.name))
modifiedValues.put(k, v);
if (modifiedSinceLastSave.contains(k.name)) modifiedValues.put(k, v);
});
return modifiedValues;
}
public boolean isModified(SQLField<?> field) {
return modifiedSinceLastSave.contains(field.name);
}
public void save() throws ORMException {
if (!isValidForSave())
throw new IllegalStateException(toString() + " has at least one undefined value and can't be saved.");
@ -238,44 +189,43 @@ public abstract class SQLElement {
Connection conn = db.getNativeConnection();
if (stored) { // mettre à jour les valeurs dans la base
if (stored)
{ // mettre à jour les valeurs dans la base
// restaurer l'ID au cas il aurait été changé à la main dans values
// restaurer l'ID au cas il aurait été changé à la main dans
// values
@SuppressWarnings("unchecked")
SQLField<Integer> idField = (SQLField<Integer>) fields.get("id");
values.put(idField, id);
modifiedSinceLastSave.remove("id");
Map<SQLField<?>, Object> modifiedValues = getOnlyModifiedValues();
if (modifiedValues.isEmpty())
return;
if (modifiedValues.isEmpty()) return;
String sql = "";
List<Object> psValues = new ArrayList<>();
for (Map.Entry<SQLField<?>, Object> entry : modifiedValues.entrySet()) {
sql += entry.getKey().name + " = ? ,";
if (entry.getKey().type.getJavaType().isEnum()) {
// prise en charge enum (non prise en charge par JDBC)
if (entry.getKey().type.getJavaType().isEnum()) // prise en
// charge
// enum (non
// prise en
// charge
// par JDBC)
psValues.add(((Enum<?>) entry.getValue()).name());
}
else
psValues.add(entry.getValue());
}
if (sql.length() > 0)
sql = sql.substring(0, sql.length()-1);
if (sql.length() > 0) sql = sql.substring(0, sql.length() - 1);
PreparedStatement ps = conn.prepareStatement("UPDATE " + tableName + " SET " + sql + " WHERE id=" + id);
try {
int i = 1;
for (Object val : psValues) {
for (Object val : psValues)
ps.setObject(i++, val);
}
toStringStatement = ps.toString();
ps.executeUpdate();
@ -283,13 +233,12 @@ public abstract class SQLElement {
ps.close();
}
}
else
{ // ajouter dans la base
else { // 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);
String concat_vals = "";
String concat_fields = "";
List<Object> psValues = new ArrayList<>();
@ -303,32 +252,32 @@ public abstract class SQLElement {
first = false;
concat_vals += " ? ";
concat_fields += entry.getKey().name;
if (entry.getKey().type.getJavaType().isEnum()) {
// prise en charge enum (non prise en charge par JDBC)
if (entry.getKey().type.getJavaType().isEnum()) // prise en
// charge
// enum (non
// prise en
// charge
// par JDBC)
psValues.add(((Enum<?>) entry.getValue()).name());
}
else
psValues.add(entry.getValue());
}
PreparedStatement ps = conn.prepareStatement("INSERT INTO "+tableName+" ("+concat_fields+") VALUES ("+concat_vals+")", Statement.RETURN_GENERATED_KEYS);
PreparedStatement ps = conn.prepareStatement(
"INSERT INTO " + tableName + " (" + concat_fields + ") VALUES (" + concat_vals + ")",
Statement.RETURN_GENERATED_KEYS);
try {
int i = 1;
for (Object val : psValues) {
for (Object val : psValues)
ps.setObject(i++, val);
}
toStringStatement = ps.toString();
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
try {
if(rs.next())
{
id = rs.getInt(1);
}
if (rs.next()) id = rs.getInt(1);
stored = true;
} finally {
@ -347,8 +296,9 @@ public abstract class SQLElement {
Log.debug(toStringStatement);
}
public boolean isStored() { return stored; }
public boolean isStored() {
return stored;
}
public Integer getId() {
return (stored) ? id : null;
@ -359,16 +309,12 @@ public abstract class SQLElement {
return (SQLField<Integer>) getFields().get("id");
}
public void delete() throws ORMException {
try {
if (stored)
{ // supprimer la ligne de la base
PreparedStatement st = db.getNativeConnection().prepareStatement("DELETE FROM "+tableName+" WHERE id="+id);
if (stored) { // supprimer la ligne de la base
PreparedStatement st = db.getNativeConnection()
.prepareStatement("DELETE FROM " + tableName + " WHERE id=" + id);
try {
Log.debug(st.toString());
st.executeUpdate();
@ -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() {
stored = false;
@ -393,9 +340,6 @@ public abstract class SQLElement {
values.forEach((k, v) -> modifiedSinceLastSave.add(k.name));
}
protected static class SQLFieldMap extends LinkedHashMap<String, SQLField<?>> {
private static final long serialVersionUID = 1L;
@ -407,35 +351,26 @@ public abstract class SQLElement {
private void addField(SQLField<?> f) {
if (f == null) return;
if (containsKey(f.name))
throw new IllegalArgumentException("SQLField "+f.name+" already exist in "+sqlElemClass.getName());
if (containsKey(f.name)) throw new IllegalArgumentException(
"SQLField " + f.name + " already exist in " + sqlElemClass.getName());
f.setSQLElementType(sqlElemClass);
put(f.name, f);
}
}
@Override
public String toString() {
ToStringBuilder b = new ToStringBuilder(this);
for (SQLField<?> f : fields.values()) {
for (SQLField<?> f : fields.values())
try {
b.append(f.name, get(f));
} catch (IllegalArgumentException e) {
b.append(f.name, "(Undefined)");
}
}
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
* entrées présente dans cette liste lors de l'appel à {@link #saveCommon()}.
* Les valeurs stockés dans chaque élément de cette liste ne seront affectés que lors de
* Défini une valeur à un champ qui sera appliquée dans la base de données à
* tous les
* entrées présente dans cette liste lors de l'appel à {@link #saveCommon()}
* .
* Les valeurs stockés dans chaque élément de cette liste ne seront affectés
* que lors de
* l'appel à {@link #saveCommon()}
*
* @param <T>
* @param field le champs à modifier
* @param value la valeur à lui appliquer
@ -43,7 +47,8 @@ public class SQLElementList<E extends SQLElement> extends ArrayList<E> {
E emptyElement = elemClass.newInstance();
emptyElement.set(field, value, false);
} catch (Exception e) {
throw new IllegalArgumentException("Illegal field or value or can't instanciante an empty instance of " + elemClass.getName() + ". (the instance is only created to test validity of field and value)", e);
throw new IllegalArgumentException("Illegal field or value or can't instanciante an empty instance of "
+ elemClass.getName() + ". (the instance is only created to test validity of field and value)", e);
}
// ici, la valeur est bonne
@ -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
* les entrées dans la base de données correspondants aux entrées de cette liste. Les nouvelles
* valeurs sont aussi mises à jour dans les objets contenus dans cette liste, si la valeur n'a pas été modifiée individuellement avec {@link SQLElement#set(SQLField, Object)}.<br/>
* Les objets de cette liste qui n'ont pas leur données en base de données sont ignorées.
* Applique toutes les valeurs défini avec
* {@link #setCommon(SQLField, Object)} à toutes
* les entrées dans la base de données correspondants aux entrées de cette
* liste. Les nouvelles
* valeurs sont aussi mises à jour dans les objets contenus dans cette
* liste, si la valeur n'a pas été modifiée individuellement avec
* {@link SQLElement#set(SQLField, Object)}.<br/>
* Les objets de cette liste qui n'ont pas leur données en base de données
* sont ignorées.
*
* @throws SQLException
*/
public synchronized void saveCommon() throws SQLException {
@ -73,16 +78,16 @@ public class SQLElementList<E extends SQLElement> extends ArrayList<E> {
for (Map.Entry<SQLField<?>, Object> entry : modifiedValues.entrySet()) {
sqlSet += entry.getKey().name + " = ? ,";
if (entry.getKey().type.getJavaType().isEnum()) {
// prise en charge enum (non prise en charge par JDBC)
if (entry.getKey().type.getJavaType().isEnum()) // prise en charge
// enum (non prise
// en charge par
// JDBC)
psValues.add(((Enum<?>) entry.getValue()).name());
}
else
psValues.add(entry.getValue());
}
if (sqlSet.length() > 0)
sqlSet = sqlSet.substring(0, sqlSet.length()-1);
if (sqlSet.length() > 0) sqlSet = sqlSet.substring(0, sqlSet.length() - 1);
String sqlWhere = "";
boolean first = true;
@ -92,13 +97,13 @@ public class SQLElementList<E extends SQLElement> extends ArrayList<E> {
sqlWhere += "id = " + el.getId();
}
PreparedStatement ps = ORM.getConnection().getNativeConnection().prepareStatement("UPDATE "+storedEl.get(0).tableName()+" SET "+sqlSet+" WHERE "+sqlWhere);
PreparedStatement ps = ORM.getConnection().getNativeConnection()
.prepareStatement("UPDATE " + storedEl.get(0).tableName() + " SET " + sqlSet + " WHERE " + sqlWhere);
try {
int i = 1;
for (Object val : psValues) {
for (Object val : psValues)
ps.setObject(i++, val);
}
Log.debug(ps.toString());
ps.executeUpdate();
@ -112,15 +117,11 @@ public class SQLElementList<E extends SQLElement> extends ArrayList<E> {
@SuppressWarnings("unchecked")
private void applyNewValuesToElements(List<E> storedEl) {
// applique les valeurs dans chaques objets de la liste
for (E el : storedEl) {
for (@SuppressWarnings("rawtypes") SQLField entry : modifiedValues.keySet()) {
if (!el.isModified(entry))
el.set(entry, modifiedValues.get(entry), false);
for (E el : storedEl)
for (@SuppressWarnings("rawtypes")
SQLField entry : modifiedValues.keySet())
if (!el.isModified(entry)) el.set(entry, modifiedValues.get(entry), false);
}
}
}
private List<E> getStoredEl() {
List<E> listStored = new ArrayList<>();
@ -130,8 +131,6 @@ public class SQLElementList<E extends SQLElement> extends ArrayList<E> {
return listStored;
}
public synchronized void removeFromDB() {
List<E> storedEl = getStoredEl();
if (storedEl.isEmpty()) return;
@ -146,14 +145,14 @@ public class SQLElementList<E extends SQLElement> extends ArrayList<E> {
sqlWhere += "id = " + el.getId();
}
PreparedStatement st = ORM.getConnection().getNativeConnection().prepareStatement("DELETE FROM "+storedEl.get(0).tableName()+" WHERE "+sqlWhere);
PreparedStatement st = ORM.getConnection().getNativeConnection()
.prepareStatement("DELETE FROM " + storedEl.get(0).tableName() + " WHERE " + sqlWhere);
try {
Log.debug(st.toString());
st.executeUpdate();
for (E el : storedEl) {
for (E el : storedEl)
el.markAsNotStored();
}
} finally {
st.close();
@ -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 Class<E> sqlForeignKeyElement;
public SQLFKField(String n, SQLType<T> t, boolean nul, Class<E> fkEl, SQLField<T> fkF) {
super(n, t, nul);
construct(fkEl, fkF);
@ -19,7 +17,8 @@ public class SQLFKField<T, E extends SQLElement> extends SQLField<T> {
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");
try {
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");
try {
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;
}
public SQLField<T> getForeignField() {
return sqlForeignKeyField;
}
public SQLField<T> getForeignField() { return sqlForeignKeyField; }
public Class<E> getForeignElementClass() { return sqlForeignKeyElement; }
public Class<E> getForeignElementClass() {
return sqlForeignKeyElement;
}
}

View File

@ -36,14 +36,10 @@ public class SQLField<T> {
/* package */ Pair<String, List<Object>> forSQLPreparedStatement() {
List<Object> params = new ArrayList<>(1);
if (defaultValue != null && !autoIncrement)
params.add(defaultValue);
return new Pair<>(name
+ " "+ type.toString()
+ (canBeNull ? " NULL" : " NOT NULL")
if (defaultValue != null && !autoIncrement) params.add(defaultValue);
return new Pair<>(name + " " + type.toString() + (canBeNull ? " NULL" : " NOT NULL")
+ (autoIncrement ? " AUTO_INCREMENT" : "")
+ ((defaultValue == null || autoIncrement) ? "" : " DEFAULT ?"),
params);
+ ((defaultValue == null || autoIncrement) ? "" : " DEFAULT ?"), params);
}
/* package */ void setSQLElementType(Class<? extends SQLElement> elemClass) {
@ -54,19 +50,18 @@ public class SQLField<T> {
return sqlElemClass;
}
/**
* <b>Don't use this {@link #toString()} method in a SQL query, because
* the default value is not escaped correctly</b>
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return forSQLPreparedStatement().getKey().replaceFirst("\\?", (defaultValue != null && !autoIncrement) ? defaultValue.toString() : "");
return forSQLPreparedStatement().getKey().replaceFirst("\\?",
(defaultValue != null && !autoIncrement) ? defaultValue.toString() : "");
}
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
@ -82,5 +77,4 @@ public class SQLField<T> {
return name.hashCode() + sqlElemClass.hashCode();
}
}

View File

@ -14,6 +14,7 @@ public class SQLOrderBy {
/**
* Ajoute un champ dans la clause ORDER BY en construction
*
* @param field le champ SQL à ordonner
* @param d le sens de tri (croissant ASC ou décroissant DESC)
* @return l'objet courant (permet de chainer les ajouts de champs)
@ -26,6 +27,7 @@ public class SQLOrderBy {
/**
* Ajoute un champ dans la clause ORDER BY en construction,
* avec comme ordre de tri croissant ASC par défaut
*
* @param field le champ SQL à ordonner dans l'ordre croissant ASC
* @return l'objet courant (permet de chainer les ajouts de champs)
*/
@ -33,7 +35,6 @@ public class SQLOrderBy {
return addField(field, Direction.ASC);
}
/* package */ String toSQL() {
String ret = "";
boolean first = true;
@ -50,7 +51,6 @@ public class SQLOrderBy {
return toSQL();
}
private class OBField {
public final SQLField<?> field;
public final Direction direction;
@ -60,7 +60,6 @@ public class SQLOrderBy {
direction = d;
}
}
public enum Direction {

View File

@ -20,8 +20,7 @@ public class SQLType<T> {
}
public boolean isAssignableFrom(Object val) {
if (javaTypes.isInstance(val))
return true;
if (javaTypes.isInstance(val)) return true;
return false;
}
@ -32,8 +31,7 @@ public class SQLType<T> {
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof SQLType))
return false;
if (obj == null || !(obj instanceof SQLType)) return false;
return toString().equals(((SQLType<?>) obj).toString());
}
@ -41,11 +39,6 @@ public class SQLType<T> {
return javaTypes;
}
public static final SQLType<Boolean> BOOLEAN = new SQLType<>("BOOLEAN", "", Boolean.class);
public static final SQLType<Byte> TINYINT = new SQLType<>("TINYINT", "", Byte.class);
@ -84,8 +77,7 @@ public class SQLType<T> {
String enumStr = "'";
boolean first = true;
for (T el : enumType.getEnumConstants()) {
if (!first)
enumStr += "', '";
if (!first) enumStr += "', '";
first = false;
enumStr += el.name();
@ -95,5 +87,4 @@ public class SQLType<T> {
return new SQLType<>("VARCHAR", "(" + enumStr + ")", enumType);
}
}

View File

@ -6,13 +6,8 @@ import javafx.util.Pair;
public abstract class SQLWhere {
public abstract Pair<String, List<Object>> toSQL();
@Override
public String toString() {
return toSQL().getKey();

View File

@ -11,20 +11,16 @@ public class SQLWhereChain extends SQLWhere {
private List<SQLWhere> conditions = new ArrayList<>();
public SQLWhereChain(SQLBoolOp op) {
if (op == null)
throw new IllegalArgumentException("op can't be null");
if (op == null) throw new IllegalArgumentException("op can't be null");
operator = op;
}
public SQLWhereChain add(SQLWhere sqlWhere) {
if (sqlWhere == null)
throw new IllegalArgumentException("sqlWhere can't be null");
if (sqlWhere == null) throw new IllegalArgumentException("sqlWhere can't be null");
conditions.add(sqlWhere);
return this;
}
@Override
public Pair<String, List<Object>> toSQL() {
String sql = "";
@ -43,11 +39,9 @@ public class SQLWhereChain extends SQLWhere {
return new Pair<>(sql, params);
}
public enum SQLBoolOp {
/** Equivalent to SQL "<code>AND</code>" */
AND("AND"),
/** Equivalent to SQL "<code>OR</code>" */
AND("AND"), /** Equivalent to SQL "<code>OR</code>" */
OR("OR");
public final String sql;

View File

@ -13,6 +13,7 @@ public class SQLWhereComp extends SQLWhere {
/**
* Compare a field with a value
*
* @param l the field at left of the comparison operator. Can't be null
* @param c the comparison operator, can't be null
* @param r the value at right of the comparison operator. Can't be null
@ -25,9 +26,6 @@ public class SQLWhereComp extends SQLWhere {
right = r;
}
@Override
public Pair<String, List<Object>> toSQL() {
List<Object> params = new ArrayList<>();
@ -35,19 +33,13 @@ public class SQLWhereComp extends SQLWhere {
return new Pair<>(left.name + " " + comp.sql + " ? ", params);
}
public enum SQLComparator {
/** Equivalent to SQL "<code>=</code>" */
EQ("="),
/** Equivalent to SQL "<code>></code>" */
GT(">"),
/** Equivalent to SQL "<code>>=</code>" */
GEQ(">="),
/** Equivalent to SQL "<code>&lt;</code>" */
LT("<"),
/** Equivalent to SQL "<code>&lt;=</code>" */
LEQ("<="),
/** Equivalent to SQL "<code>!=</code>" */
EQ("="), /** Equivalent to SQL "<code>></code>" */
GT(">"), /** Equivalent to SQL "<code>>=</code>" */
GEQ(">="), /** Equivalent to SQL "<code>&lt;</code>" */
LT("<"), /** Equivalent to SQL "<code>&lt;=</code>" */
LEQ("<="), /** Equivalent to SQL "<code>!=</code>" */
NEQ("!=");
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 {
private SQLField<String> field;
private String likeExpr;
/**
* Compare a field with a value
*
* @param f the field at left of the LIKE keyword. Can't be null
* @param like the like expression.
*/
@ -23,7 +23,6 @@ public class SQLWhereLike extends SQLWhere {
likeExpr = like;
}
@Override
public Pair<String, List<Object>> toSQL() {
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.
*
* @param field the field to check null / not null state
* @param isNull true if we want to ckeck if "IS NULL", or false to check if "IS NOT NULL"
* @param isNull true if we want to ckeck if "IS NULL", or false to check if
* "IS NOT NULL"
*/
public SQLWhereNull(SQLField<?> field, boolean isNull) {
if (field == null)
throw new IllegalArgumentException("field can't be null");
if (!field.canBeNull)
Log.getLogger().log(Level.WARNING, "Useless : Trying to check IS [NOT] NULL on the field "+field.getSQLElementType().getName()+"#"+field.name+" which is declared in the ORM as 'can't be null'");
if (field == null) throw new IllegalArgumentException("field can't be null");
if (!field.canBeNull) Log.getLogger().log(Level.WARNING,
"Useless : Trying to check IS [NOT] NULL on the field " + field.getSQLElementType().getName() + "#"
+ field.name + " which is declared in the ORM as 'can't be null'");
fild = field;
nulll = isNull;
}
@Override
public Pair<String, List<Object>> toSQL() {
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) {
Arrays.sort(desiredUnits);
DistanceUnit choosenUnit = desiredUnits[0]; // la plus petite unitée
for (DistanceUnit unit : desiredUnits) {
if (meterDist / unit.multiplicator < 1)
continue;
if (meterDist / unit.multiplicator < 1) continue;
choosenUnit = unit;
}
if (choosenUnit != desiredUnits[0] && precision <= 2)
precision = 2;
if (choosenUnit != desiredUnits[0] && precision <= 2) precision = 2;
String precisionFormat = "##0";
if (precision > 0)
precisionFormat += ".";
if (precision > 0) precisionFormat += ".";
for (int i = 0; i < precision; i++)
precisionFormat += "0";
DecimalFormat df = new DecimalFormat(precisionFormat);
@ -37,19 +32,8 @@ public class DistanceUtil {
return distanceToString(meterDist, precision, DistanceUnit.M, DistanceUnit.KM);
}
public enum DistanceUnit implements Comparable<DistanceUnit> {
NM(0.000000001, "nm"),
µM(0.000001, "µm"),
MM(0.001, "mm"),
CM(0.01, "cm"),
M(1, "m"),
KM(1000, "km");
NM(0.000000001, "nm"), µM(0.000001, "µm"), MM(0.001, "mm"), CM(0.01, "cm"), M(1, "m"), KM(1000, "km");
private final double multiplicator;
private final String unitStr;

View File

@ -6,31 +6,24 @@ public class MemoryUtil {
private static final DecimalFormat format = new DecimalFormat("#####0.00");
public static String humanReadableSize(long octet, boolean si)
{
public static String humanReadableSize(long octet, boolean si) {
double size = octet;
int diveBy = si ? 1000 : 1024;
if (size < diveBy)
return size+"o";
if (size < diveBy) return size + "o";
size /= diveBy;
if (size < diveBy)
return format.format(size) + (si ? "ko" : "kio");
if (size < diveBy) return format.format(size) + (si ? "ko" : "kio");
size /= diveBy;
if (size < diveBy)
return format.format(size) + (si ? "Mo" : "Mio");
if (size < diveBy) return format.format(size) + (si ? "Mo" : "Mio");
size /= diveBy;
if (size < diveBy)
return format.format(size) + (si ? "Go" : "Gio");
if (size < diveBy) return format.format(size) + (si ? "Go" : "Gio");
size /= diveBy;
return format.format(size) + (si ? "To" : "Tio");
}
public static String humanReadableSize(long octet) {
return humanReadableSize(octet, false);
}

View File

@ -1,8 +1,7 @@
package fr.pandacube.java.util.measurement;
public class TimeUtil {
public static String durationToString (long msec_time, boolean dec_seconde)
{
public static String durationToString(long msec_time, boolean dec_seconde) {
int j = 0, h = 0, m = 0, s = 0;
long msec = msec_time;
@ -20,22 +19,18 @@ public class TimeUtil {
if (h > 0) result = result.concat(h + "h ");
if (m > 0) result = result.concat(m + "m ");
if (s > 0 && !dec_seconde) result = result.concat(s + "s");
else if (dec_seconde && (s>0 || msec > 0))
{
else if (dec_seconde && (s > 0 || msec > 0)) {
msec += s * 1000;
result = result.concat((msec / 1000D) + "s");
}
if (result.equals(""))
result = "0";
if (result.equals("")) result = "0";
return result.trim();
}
public static String durationToString (long msec_time)
{
public static String durationToString(long msec_time) {
return durationToString(msec_time, false);
}
}

View File

@ -30,13 +30,9 @@ public class TCPClient extends Thread implements Closeable {
private AtomicBoolean isClosed = new AtomicBoolean(false);
public TCPClient(InetSocketAddress a, String connName, TCPClientListener l) throws IOException {
super("TCPCl " + connName);
if (a == null || l == null)
throw new IllegalArgumentException("les arguments ne peuvent pas être null");
if (a == null || l == null) throw new IllegalArgumentException("les arguments ne peuvent pas être null");
socket = new Socket();
socket.setReceiveBufferSize(Pandacube.NETWORK_TCP_BUFFER_SIZE);
socket.setSendBufferSize(Pandacube.NETWORK_TCP_BUFFER_SIZE);
@ -47,7 +43,6 @@ public class TCPClient extends Thread implements Closeable {
listener.onConnect(this);
}
@Override
public void run() {
@ -55,8 +50,7 @@ public class TCPClient extends Thread implements Closeable {
byte[] code = new byte[1];
while (!socket.isClosed() && in.read(code) != -1) {
byte[] sizeB = new byte[4];
if (in.read(sizeB) != 4)
throw new IOException("Socket "+addr+" fermé");
if (in.read(sizeB) != 4) throw new IOException("Socket " + addr + " fermé");
int size = ByteBuffer.wrap(sizeB).getInt();
@ -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();
try {
if (listener == null)
throw new InvalidServerMessage("Le serveur ne peut actuellement pas prendre en charge de nouvelles requêtes. Les listeners n'ont pas encore été définis");
if (listener == null) throw new InvalidServerMessage(
"Le serveur ne peut actuellement pas prendre en charge de nouvelles requêtes. Les listeners n'ont pas encore été définis");
Packet p = Packet.constructPacket(packetData);
if (!(p instanceof PacketServer))
throw new InvalidServerMessage("Le type de packet reçu n'est pas un packet attendu : "+p.getClass().getCanonicalName());
if (!(p instanceof PacketServer)) throw new InvalidServerMessage(
"Le type de packet reçu n'est pas un packet attendu : " + p.getClass().getCanonicalName());
PacketServer ps = (PacketServer) p;
@ -86,7 +79,6 @@ public class TCPClient extends Thread implements Closeable {
}
}
} catch (SocketTimeoutException e) {
System.err.println("Le serveur a prit trop de temps à répondre");
} catch (Exception e) {
@ -95,21 +87,15 @@ public class TCPClient extends Thread implements Closeable {
close();
}
private void forceReadBytes(byte[] buff) throws IOException {
int pos = 0;
do {
int nbR = in.read(buff, pos, buff.length - pos);
if (nbR == -1)
throw new IOException("Can't read required amount of byte");
if (nbR == -1) throw new IOException("Can't read required amount of byte");
pos += nbR;
} while (pos < buff.length);
}
public void send(PacketClient packet) throws IOException {
synchronized (outSynchronizer) {
out.write(packet.getFullSerializedPacket());
@ -121,8 +107,7 @@ public class TCPClient extends Thread implements Closeable {
public void close() {
try {
synchronized (outSynchronizer) {
if (isClosed.get())
return;
if (isClosed.get()) return;
socket.close();
isClosed.set(true);
listener.onDisconnect(this);
@ -132,33 +117,23 @@ public class TCPClient extends Thread implements Closeable {
}
}
public void sendSilently(PacketClient packet) {
try {
send(packet);
} catch (IOException e) {}
}
public SocketAddress getServerAddress() {
return addr;
}
public boolean isClosed() {
return isClosed.get() || socket.isClosed();
}
public static class InvalidServerMessage extends RuntimeException {
private static final long serialVersionUID = 1L;
public InvalidServerMessage(String message) {
super(message);
}

View File

@ -1,6 +1,5 @@
package fr.pandacube.java.util.network.packet;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.HashMap;
@ -18,7 +17,9 @@ public abstract class Packet implements ByteSerializable {
code = c;
}
public byte getCode() { return code; }
public byte getCode() {
return code;
}
public byte[] getFullSerializedPacket() {
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();
}
public static final Charset CHARSET = Pandacube.NETWORK_CHARSET;
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")
private static <T extends Packet> void addPacket(Class<T> packetClass) {
try {
Packet p = (Packet)packetClass.newInstance();
Packet p = packetClass.newInstance();
packetTypes.put(p.code, packetClass);
} catch (Exception e) {
e.printStackTrace();
}
}
static {
/*
@ -81,5 +65,4 @@ public abstract class Packet implements ByteSerializable {
// addPacket(PacketToto.class);
}
}

View File

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

View File

@ -186,7 +186,6 @@ public class ByteBuffer implements Cloneable {
return buff.capacity();
}
public ByteBuffer putString(String s) {
byte[] charBytes = s.getBytes(charset);
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
*
* @param obj the object to serialize
* @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 obj the objet to fill with his method {@link ByteSerializable#deserializeFromByteBuffer(ByteBuffer)}
* @param obj the objet to fill with his method
* {@link ByteSerializable#deserializeFromByteBuffer(ByteBuffer)}
* @return obj a reference to the same object
*/
public <T 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) {
List<T> list = new ArrayList<T>();
int size = getInt();
for (int i=0; i<size; i++) {
for (int i = 0; i < size; i++)
list.add(getObject(clazz));
}
return list;
}
/**
* @see java.nio.ByteBuffer#array()
*/
@ -249,6 +249,4 @@ public class ByteBuffer implements Cloneable {
return buff.array();
}
}

View File

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

View File

@ -10,14 +10,15 @@ public class BandwidthCalculation {
private List<PacketStat> packetHistory = new LinkedList<PacketStat>();
public synchronized void addPacket(TCPServerClientConnection co, boolean in, long size) {
packetHistory.add(new PacketStat(co, in, size));
}
/**
* Get the instant bandwith in byte/s
* @param input true if getting input bw, false if getting output, null if getting input + output
*
* @param input true if getting input bw, false if getting output, null if
* getting input + output
* @param co
* @return
*/
@ -31,30 +32,19 @@ public class BandwidthCalculation {
it.remove();
continue;
}
if (input != null && el.input != input.booleanValue())
continue;
if (co != null && !co.equals(el.connection))
continue;
if (input != null && el.input != input.booleanValue()) continue;
if (co != null && !co.equals(el.connection)) continue;
sum += el.packetSize;
}
return sum;
}
private class PacketStat {
public final long time;
public final long packetSize;
public final boolean input;
public final TCPServerClientConnection connection;
public PacketStat(TCPServerClientConnection co, boolean input, long size) {
time = System.currentTimeMillis();
packetSize = size;

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.bytebuffer.ByteBuffer;
/**
*
* @author Marc Baloup
@ -33,7 +32,6 @@ import fr.pandacube.java.util.network.packet.bytebuffer.ByteBuffer;
public class TCPServer extends Thread implements Closeable {
private static AtomicInteger connectionCounterId = new AtomicInteger(0);
private ServerSocket socket;
private TCPServerListener listener;
private String socketName;
@ -42,16 +40,11 @@ public class TCPServer extends Thread implements Closeable {
private AtomicBoolean isClosed = new AtomicBoolean(false);
public final BandwidthCalculation bandwidthCalculation = new BandwidthCalculation();
public TCPServer(int port, String sckName, TCPServerListener l) throws IOException {
super("TCPSv " + sckName);
if (port <= 0 || port > 65535)
throw new IllegalArgumentException("le numéro de port est invalide");
if (port <= 0 || port > 65535) throw new IllegalArgumentException("le numéro de port est invalide");
socket = new ServerSocket();
socket.setReceiveBufferSize(Pandacube.NETWORK_TCP_BUFFER_SIZE);
socket.setPerformancePreferences(0, 2, 1);
@ -61,7 +54,6 @@ public class TCPServer extends Thread implements Closeable {
socketName = sckName;
}
@Override
public void run() {
@ -72,7 +64,8 @@ public class TCPServer extends Thread implements Closeable {
socketClient.setSoTimeout(Pandacube.NETWORK_TIMEOUT);
try {
TCPServerClientConnection co = new TCPServerClientConnection(socketClient, connectionCounterId.getAndIncrement());
TCPServerClientConnection co = new TCPServerClientConnection(socketClient,
connectionCounterId.getAndIncrement());
clients.add(co);
listener.onClientConnect(this, co);
co.start();
@ -85,16 +78,6 @@ public class TCPServer extends Thread implements Closeable {
}
}
public class TCPServerClientConnection extends Thread {
private Socket socket;
private InputStream in;
@ -102,7 +85,6 @@ public class TCPServer extends Thread implements Closeable {
private SocketAddress address;
private TCPServerConnectionOutputThread outThread;
public TCPServerClientConnection(Socket s, int coId) throws IOException {
super("TCPSv " + socketName + " Conn#" + coId + " In");
socket = s;
@ -120,8 +102,7 @@ public class TCPServer extends Thread implements Closeable {
byte[] code = new byte[1];
while (!socket.isClosed() && in.read(code) != -1) {
byte[] sizeB = new byte[4];
if (in.read(sizeB) != 4)
throw new IOException("Socket "+address+" fermé");
if (in.read(sizeB) != 4) throw new IOException("Socket " + address + " fermé");
int size = new ByteBuffer(sizeB, Packet.CHARSET).getInt();
@ -129,7 +110,8 @@ public class TCPServer extends Thread implements Closeable {
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);
@ -138,19 +120,16 @@ public class TCPServer extends Thread implements Closeable {
} catch (InvalidClientMessage e) {
Log.getLogger().log(Level.SEVERE, "Erreur protocole de : ", e);
} catch (Exception e) {
Log.getLogger().log(Level.SEVERE, "Erreur lors de la prise en charge du message par le serveur", e);
Log.getLogger().log(Level.SEVERE, "Erreur lors de la prise en charge du message par le serveur",
e);
e.printStackTrace();
}
}
} catch (Exception e) {
Log.getLogger().log(Level.SEVERE, "Fermeture de la connexion de " + address, e);
}
close();
}
@ -162,8 +141,7 @@ public class TCPServer extends Thread implements Closeable {
int pos = 0;
do {
int nbR = in.read(buff, pos, buff.length - pos);
if (nbR == -1)
throw new IOException("Can't read required amount of byte");
if (nbR == -1) throw new IOException("Can't read required amount of byte");
pos += nbR;
} while (pos < buff.length);
}
@ -176,20 +154,20 @@ public class TCPServer extends Thread implements Closeable {
try {
socket.close();
if (!Thread.currentThread().equals(outThread))
send(new PacketServer((byte)0){
if (!Thread.currentThread().equals(outThread)) send(new PacketServer((byte) 0) {
@Override
public void serializeToByteBuffer(ByteBuffer buffer) {}
@Override
public void deserializeFromByteBuffer(ByteBuffer buffer) {}
});
// provoque une exception dans le thread de sortie, et la termine
// provoque une exception dans le thread de sortie, et la
// termine
} catch (IOException e) {
e.printStackTrace();
}
}
private class TCPServerConnectionOutputThread extends Thread {
private BlockingQueue<PacketServer> packetQueue = new LinkedBlockingDeque<PacketServer>();
@ -197,12 +175,10 @@ public class TCPServer extends Thread implements Closeable {
super("TCPSv " + socketName + " Conn#" + coId + " Out");
}
private void addPacket(PacketServer packet) {
packetQueue.add(packet);
}
@Override
public void run() {
try {
@ -216,39 +192,28 @@ public class TCPServer extends Thread implements Closeable {
out.flush();
}
}
} catch (InterruptedException e) {
} catch (IOException e) { }
} catch (InterruptedException e) {} catch (IOException e) {}
close();
}
}
}
private void interpreteReceivedMessage(TCPServerClientConnection co, byte[] data) {
Packet p = Packet.constructPacket(data);
if (!(p instanceof PacketClient))
throw new InvalidClientMessage("Le type de packet reçu n'est pas un packet attendu : "+p.getClass().getCanonicalName());
if (!(p instanceof PacketClient)) throw new InvalidClientMessage(
"Le type de packet reçu n'est pas un packet attendu : " + p.getClass().getCanonicalName());
PacketClient pc = (PacketClient) p;
listener.onPacketReceive(this, co, pc);
}
@Override
public void close() {
try {
@ -266,15 +231,9 @@ public class TCPServer extends Thread implements Closeable {
return isClosed.get() || socket.isClosed();
}
public static class InvalidClientMessage extends RuntimeException {
private static final long serialVersionUID = 1L;
public InvalidClientMessage(String message) {
super(message);
}

View File

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

View File

@ -8,20 +8,17 @@ public abstract class AbstractRequest {
private String command;
private String data;
protected AbstractRequest(String cmd, String p) {
if (cmd == null || cmd.isEmpty()) throw new IllegalArgumentException("Un message doit-être défini");
command = cmd;
pass = p;
}
protected void setData(String d) {
if (d == null) d = "";
data = d;
}
public void sendPacket(PrintStream out) {
out.print(pass + "\n");
out.print(command + "\n");

View File

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

View File

@ -7,42 +7,35 @@ import java.net.Socket;
public class ResponseAnalyser {
/**
* Indique si la requête s'est bien exécutée (l'entête de la réponse est 'ok')
* Indique si la requête s'est bien exécutée (l'entête de la réponse est
* 'ok')
*/
public final boolean good;
public final String data;
public ResponseAnalyser(Socket socket) throws IOException {
if (socket == null || socket.isClosed() || socket.isInputShutdown()) throw new IllegalArgumentException("le socket doit être non null et doit être ouvert sur le flux d'entrée");
if (socket == null || socket.isClosed() || socket.isInputShutdown())
throw new IllegalArgumentException("le socket doit être non null et doit être ouvert sur le flux d'entrée");
// on lis la réponse
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
// lecture de la première ligne
line = in.readLine();
good = line.equalsIgnoreCase("OK");
// lecture de la deuxième ligne
line = in.readLine();
int data_size = 0;
try {
data_size = Integer.parseInt(line);
} catch (NumberFormatException e) { throw new RuntimeException("Réponse mal formée : la deuxième ligne doit-être un nombre entier"); }
} catch (NumberFormatException e) {
throw new RuntimeException("Réponse mal formée : la deuxième ligne doit-être un nombre entier");
}
// lecture du reste
StringBuilder sB_data = new StringBuilder();
@ -52,12 +45,9 @@ public class ResponseAnalyser {
sB_data.append(c, 0, nbC);
data = sB_data.toString();
if (data.getBytes().length != data_size)
throw new RuntimeException("Réponse mal formée : "+data_size+" caractères annoncée dans la requête, mais "+data.getBytes().length+" s'y trouvent.");
if (data.getBytes().length != data_size) throw new RuntimeException("Réponse mal formée : " + data_size
+ " caractères annoncée dans la requête, mais " + data.getBytes().length + " s'y trouvent.");
}
}

View File

@ -7,20 +7,16 @@ import java.net.Socket;
public abstract class AbstractRequestExecutor {
public final String command;
public AbstractRequestExecutor(String cmd, NetworkAPIListener napiListener) {
command = cmd.toLowerCase();
napiListener.registerRequestExecutor(command, this);
}
public void execute(String data, Socket socket) throws IOException {
if (socket == null || socket.isClosed() || socket.isOutputShutdown()) throw new IllegalArgumentException("le socket doit être non null et doit être ouvert sur le flux d'entrée");
if (socket == null || socket.isClosed() || socket.isOutputShutdown())
throw new IllegalArgumentException("le socket doit être non null et doit être ouvert sur le flux d'entrée");
try {
@ -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
*/
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.
*
* @author Marc Baloup
*
*/

View File

@ -8,18 +8,6 @@ import java.util.HashMap;
public class NetworkAPIListener implements Runnable {
private int port = 0;
String pass;
private ServerSocket serverSocket;
@ -29,10 +17,12 @@ public class NetworkAPIListener implements Runnable {
/**
* Instencie le côté serveur du NetworkAPI
*
* @param n nom du networkAPI (permet l'identification dans les logs)
* @param p le port d'écoute
* @param pa le mot de passe réseau
* @param peh PacketExecutionHandler permettant de prendre en charge l'exécution asynchrone d'une requête reçu pas un client
* @param peh PacketExecutionHandler permettant de prendre en charge
* l'exécution asynchrone d'une requête reçu pas un client
*/
public NetworkAPIListener(String n, int p, String pa, NAPIExecutionHandler peh) {
port = p;
@ -41,7 +31,6 @@ public class NetworkAPIListener implements Runnable {
nAPIExecutionHandler = peh;
}
@Override
public void run() {
synchronized (this) {
@ -53,11 +42,8 @@ public class NetworkAPIListener implements Runnable {
}
}
System.out.println("NetworkAPI '" + name + "' à l'écoute sur le port " + port);
try {
// réception des connexion client
while (!serverSocket.isClosed()) {
@ -68,38 +54,28 @@ public class NetworkAPIListener implements Runnable {
synchronized (this) {
try {
if (!serverSocket.isClosed())
serverSocket.close();
if (!serverSocket.isClosed()) serverSocket.close();
} catch (IOException e) {}
}
System.out.println("NetworkAPI '" + name + "' ferme le port " + port);
}
/**
* Ferme le ServerSocket. Ceci provoque l'arrêt du thread associé à l'instance de la classe
* Ferme le ServerSocket. Ceci provoque l'arrêt du thread associé à
* l'instance de la classe
*/
public synchronized void closeServerSocket() {
if (serverSocket != null)
{
try {
if (serverSocket != null) try {
serverSocket.close();
} catch (IOException e) {}
}
public int getPort() {
return port;
}
public int getPort() { return port; }
public void registerRequestExecutor(String command, AbstractRequestExecutor executor) {
requestExecutors.put(command, executor);
}
@ -108,18 +84,8 @@ public class NetworkAPIListener implements Runnable {
return requestExecutors.get(command);
}
public String getCommandList() {
return Arrays.toString(requestExecutors.keySet().toArray());
}
}

View File

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

View File

@ -12,7 +12,9 @@ public class RequestAnalyser {
public final String data;
public RequestAnalyser(Socket socket, NetworkAPIListener napiListener) throws IOException, BadRequestException {
if (socket == null || socket.isClosed() || socket.isInputShutdown() || napiListener == null) throw new IllegalArgumentException("le socket doit être non null et doit être ouvert sur le flux d'entrée et napiListener ne doit pas être null");
if (socket == null || socket.isClosed() || socket.isInputShutdown() || napiListener == null)
throw new IllegalArgumentException(
"le socket doit être non null et doit être ouvert sur le flux d'entrée et napiListener ne doit pas être null");
networkAPIListener = napiListener;
@ -21,16 +23,9 @@ public class RequestAnalyser {
String line;
// lecture de la première ligne
line = in.readLine();
if (line == null || !line.equals(networkAPIListener.pass))
throw new BadRequestException("wrong_password");
if (line == null || !line.equals(networkAPIListener.pass)) throw new BadRequestException("wrong_password");
// lecture de la deuxième ligne
line = in.readLine();
@ -38,16 +33,15 @@ public class RequestAnalyser {
throw new BadRequestException("command_not_exists");
command = line;
// lecture de la troisième ligne
line = in.readLine();
int data_size = 0;
try {
data_size = Integer.parseInt(line);
} catch (NumberFormatException e) { throw new BadRequestException("wrong_data_size_format"); }
} catch (NumberFormatException e) {
throw new BadRequestException("wrong_data_size_format");
}
// lecture du reste
StringBuilder sB_data = new StringBuilder();
@ -58,18 +52,11 @@ public class RequestAnalyser {
data = sB_data.toString();
if (data.getBytes().length != data_size)
throw new BadRequestException("wrong_data_size");
if (data.getBytes().length != data_size) throw new BadRequestException("wrong_data_size");
socket.shutdownInput();
}
public class BadRequestException extends Exception {
private static final long serialVersionUID = 1L;
@ -80,5 +67,4 @@ public class RequestAnalyser {
}
}

View File

@ -6,7 +6,6 @@ public class Response {
public boolean good = true;
public String data = "";
public Response(boolean good, String data) {
this.good = good;
this.data = data;
@ -16,9 +15,7 @@ public class Response {
* Construit une réponse positive avec aucune donnée. Équivaut à
* <code>new Response(true, "")</code>
*/
public Response() {
}
public Response() {}
public void sendPacket(PrintStream out) {

View File

@ -42,17 +42,16 @@ public enum ChatColor {
private ChatColor(char code, String name) {
this.code = code;
this.name = name;
this.toString = new String(new char[]{'\u00a7', code});
toString = new String(new char[] { '\u00a7', code });
}
@Override
public String toString() {
return this.toString;
return toString;
}
public static String stripColor(String input) {
if (input == null) {
return null;
}
if (input == null) return null;
return STRIP_COLOR_PATTERN.matcher(input).replaceAll("");
}
@ -71,15 +70,13 @@ public enum ChatColor {
}
public String getName() {
return this.name;
return name;
}
static {
STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + String.valueOf('\u00a7') + "[0-9A-FK-OR]");
BY_CHAR = new HashMap<Character, ChatColor>();
for (ChatColor colour : ChatColor.values()) {
for (ChatColor colour : ChatColor.values())
BY_CHAR.put(Character.valueOf(colour.code), colour);
}
}
}

View File

@ -4,12 +4,7 @@
package net.md_5.bungee.api;
public enum ChatMessageType {
CHAT,
SYSTEM,
ACTION_BAR;
CHAT, 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.List;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
public abstract class BaseComponent {
BaseComponent parent;
@ -24,114 +22,96 @@ public abstract class BaseComponent {
private HoverEvent hoverEvent;
BaseComponent(BaseComponent old) {
this.setColor(old.getColorRaw());
this.setBold(old.isBoldRaw());
this.setItalic(old.isItalicRaw());
this.setUnderlined(old.isUnderlinedRaw());
this.setStrikethrough(old.isStrikethroughRaw());
this.setObfuscated(old.isObfuscatedRaw());
this.setInsertion(old.getInsertion());
this.setClickEvent(old.getClickEvent());
this.setHoverEvent(old.getHoverEvent());
if (old.getExtra() != null) {
for (BaseComponent component : old.getExtra()) {
setColor(old.getColorRaw());
setBold(old.isBoldRaw());
setItalic(old.isItalicRaw());
setUnderlined(old.isUnderlinedRaw());
setStrikethrough(old.isStrikethroughRaw());
setObfuscated(old.isObfuscatedRaw());
setInsertion(old.getInsertion());
setClickEvent(old.getClickEvent());
setHoverEvent(old.getHoverEvent());
if (old.getExtra() != null) for (BaseComponent component : old.getExtra())
this.addExtra(component.duplicate());
}
}
}
public abstract BaseComponent duplicate();
public static /* varargs */ String toLegacyText(BaseComponent... components) {
StringBuilder builder = new StringBuilder();
for (BaseComponent msg : components) {
for (BaseComponent msg : components)
builder.append(msg.toLegacyText());
}
return builder.toString();
}
public static /* varargs */ String toPlainText(BaseComponent... components) {
StringBuilder builder = new StringBuilder();
for (BaseComponent msg : components) {
for (BaseComponent msg : components)
builder.append(msg.toPlainText());
}
return builder.toString();
}
public ChatColor getColor() {
if (this.color == null) {
if (this.parent == null) {
return ChatColor.WHITE;
if (color == null) {
if (parent == null) return ChatColor.WHITE;
return parent.getColor();
}
return this.parent.getColor();
}
return this.color;
return color;
}
public ChatColor getColorRaw() {
return this.color;
return color;
}
public boolean isBold() {
if (this.bold == null) {
return this.parent != null && this.parent.isBold();
}
return this.bold;
if (bold == null) return parent != null && parent.isBold();
return bold;
}
public Boolean isBoldRaw() {
return this.bold;
return bold;
}
public boolean isItalic() {
if (this.italic == null) {
return this.parent != null && this.parent.isItalic();
}
return this.italic;
if (italic == null) return parent != null && parent.isItalic();
return italic;
}
public Boolean isItalicRaw() {
return this.italic;
return italic;
}
public boolean isUnderlined() {
if (this.underlined == null) {
return this.parent != null && this.parent.isUnderlined();
}
return this.underlined;
if (underlined == null) return parent != null && parent.isUnderlined();
return underlined;
}
public Boolean isUnderlinedRaw() {
return this.underlined;
return underlined;
}
public boolean isStrikethrough() {
if (this.strikethrough == null) {
return this.parent != null && this.parent.isStrikethrough();
}
return this.strikethrough;
if (strikethrough == null) return parent != null && parent.isStrikethrough();
return strikethrough;
}
public Boolean isStrikethroughRaw() {
return this.strikethrough;
return strikethrough;
}
public boolean isObfuscated() {
if (this.obfuscated == null) {
return this.parent != null && this.parent.isObfuscated();
}
return this.obfuscated;
if (obfuscated == null) return parent != null && parent.isObfuscated();
return obfuscated;
}
public Boolean isObfuscatedRaw() {
return this.obfuscated;
return obfuscated;
}
public void setExtra(List<BaseComponent> components) {
for (BaseComponent component : components) {
for (BaseComponent component : components)
component.parent = this;
}
this.extra = components;
extra = components;
}
public void addExtra(String text) {
@ -139,15 +119,14 @@ public abstract class BaseComponent {
}
public void addExtra(BaseComponent component) {
if (this.extra == null) {
this.extra = new ArrayList<BaseComponent>();
}
if (extra == null) extra = new ArrayList<BaseComponent>();
component.parent = this;
this.extra.add(component);
extra.add(component);
}
public boolean hasFormatting() {
return this.color != null || this.bold != null || this.italic != null || this.underlined != null || this.strikethrough != null || this.obfuscated != null || this.hoverEvent != null || this.clickEvent != null;
return color != null || bold != null || italic != null || underlined != null || strikethrough != null
|| obfuscated != null || hoverEvent != null || clickEvent != null;
}
public String toPlainText() {
@ -157,12 +136,9 @@ public abstract class BaseComponent {
}
void toPlainText(StringBuilder builder) {
if (this.extra != null) {
for (BaseComponent e2 : this.extra) {
if (extra != null) for (BaseComponent e2 : extra)
e2.toPlainText(builder);
}
}
}
public String toLegacyText() {
StringBuilder builder = new StringBuilder();
@ -171,12 +147,9 @@ public abstract class BaseComponent {
}
void toLegacyText(StringBuilder builder) {
if (this.extra != null) {
for (BaseComponent e2 : this.extra) {
if (extra != null) for (BaseComponent e2 : extra)
e2.toLegacyText(builder);
}
}
}
public void setColor(ChatColor color) {
this.color = color;
@ -214,27 +187,29 @@ public abstract class BaseComponent {
this.hoverEvent = hoverEvent;
}
@Override
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() {
return this.insertion;
return insertion;
}
public List<BaseComponent> getExtra() {
return this.extra;
return extra;
}
public ClickEvent getClickEvent() {
return this.clickEvent;
return clickEvent;
}
public HoverEvent getHoverEvent() {
return this.hoverEvent;
return hoverEvent;
}
}

View File

@ -10,15 +10,16 @@ public final class ClickEvent {
private final String value;
public Action getAction() {
return this.action;
return action;
}
public String getValue() {
return this.value;
return value;
}
@Override
public String toString() {
return "ClickEvent(action=" + (Object)((Object)this.getAction()) + ", value=" + this.getValue() + ")";
return "ClickEvent(action=" + (getAction()) + ", value=" + getValue() + ")";
}
@ConstructorProperties(value = { "action", "value" })
@ -28,16 +29,9 @@ public final class ClickEvent {
}
public static enum Action {
OPEN_URL,
OPEN_FILE,
RUN_COMMAND,
SUGGEST_COMMAND,
CHANGE_PAGE;
OPEN_URL, 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.List;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
public class ComponentBuilder {
private TextComponent current;
private final List<BaseComponent> parts = new ArrayList<BaseComponent>();
public ComponentBuilder(ComponentBuilder original) {
this.current = new TextComponent(original.current);
for (BaseComponent baseComponent : original.parts) {
this.parts.add(baseComponent.duplicate());
}
current = new TextComponent(original.current);
for (BaseComponent baseComponent : original.parts)
parts.add(baseComponent.duplicate());
}
public ComponentBuilder(String text) {
this.current = new TextComponent(text);
current = new TextComponent(text);
}
public ComponentBuilder append(String text) {
@ -31,102 +27,96 @@ public class ComponentBuilder {
}
public ComponentBuilder append(String text, FormatRetention retention) {
this.parts.add(this.current);
this.current = new TextComponent(this.current);
this.current.setText(text);
this.retain(retention);
parts.add(current);
current = new TextComponent(current);
current.setText(text);
retain(retention);
return this;
}
public ComponentBuilder color(ChatColor color) {
this.current.setColor(color);
current.setColor(color);
return this;
}
public ComponentBuilder bold(boolean bold) {
this.current.setBold(bold);
current.setBold(bold);
return this;
}
public ComponentBuilder italic(boolean italic) {
this.current.setItalic(italic);
current.setItalic(italic);
return this;
}
public ComponentBuilder underlined(boolean underlined) {
this.current.setUnderlined(underlined);
current.setUnderlined(underlined);
return this;
}
public ComponentBuilder strikethrough(boolean strikethrough) {
this.current.setStrikethrough(strikethrough);
current.setStrikethrough(strikethrough);
return this;
}
public ComponentBuilder obfuscated(boolean obfuscated) {
this.current.setObfuscated(obfuscated);
current.setObfuscated(obfuscated);
return this;
}
public ComponentBuilder insertion(String insertion) {
this.current.setInsertion(insertion);
current.setInsertion(insertion);
return this;
}
public ComponentBuilder event(ClickEvent clickEvent) {
this.current.setClickEvent(clickEvent);
current.setClickEvent(clickEvent);
return this;
}
public ComponentBuilder event(HoverEvent hoverEvent) {
this.current.setHoverEvent(hoverEvent);
current.setHoverEvent(hoverEvent);
return this;
}
public ComponentBuilder reset() {
return this.retain(FormatRetention.NONE);
return retain(FormatRetention.NONE);
}
public ComponentBuilder retain(FormatRetention retention) {
TextComponent previous = this.current;
TextComponent previous = current;
switch (retention) {
case NONE: {
this.current = new TextComponent(this.current.getText());
current = new TextComponent(current.getText());
break;
}
case ALL: {
break;
}
case EVENTS: {
this.current = new TextComponent(this.current.getText());
this.current.setInsertion(previous.getInsertion());
this.current.setClickEvent(previous.getClickEvent());
this.current.setHoverEvent(previous.getHoverEvent());
current = new TextComponent(current.getText());
current.setInsertion(previous.getInsertion());
current.setClickEvent(previous.getClickEvent());
current.setHoverEvent(previous.getHoverEvent());
break;
}
case FORMATTING: {
this.current.setClickEvent(null);
this.current.setHoverEvent(null);
current.setClickEvent(null);
current.setHoverEvent(null);
}
}
return this;
}
public BaseComponent[] create() {
this.parts.add(this.current);
return this.parts.toArray(new BaseComponent[this.parts.size()]);
parts.add(current);
return parts.toArray(new BaseComponent[parts.size()]);
}
public static enum FormatRetention {
NONE,
FORMATTING,
EVENTS,
ALL;
NONE, 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.util.Arrays;
import net.md_5.bungee.api.chat.BaseComponent;
public final class HoverEvent {
private final Action action;
private final BaseComponent[] value;
public Action getAction() {
return this.action;
return action;
}
public BaseComponent[] getValue() {
return this.value;
return value;
}
@Override
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" })
@ -30,15 +30,9 @@ public final class HoverEvent {
}
public static enum Action {
SHOW_TEXT,
SHOW_ACHIEVEMENT,
SHOW_ITEM,
SHOW_ENTITY;
SHOW_TEXT, 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.regex.Matcher;
import java.util.regex.Pattern;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ClickEvent;
public class TextComponent
extends BaseComponent {
import net.md_5.bungee.api.ChatColor;
public class TextComponent extends BaseComponent {
private static final Pattern url = Pattern.compile("^(?:(https?)://)?([-\\w_\\.]{2,}\\.[a-z]{2,4})(/\\S*)?$");
private String text;
@ -22,14 +20,13 @@ extends BaseComponent {
StringBuilder builder = new StringBuilder();
TextComponent component = new TextComponent();
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;
char c2 = message.charAt(i);
if (c2 == '\u00a7') {
ChatColor format;
if ((c2 = message.charAt(++i)) >= 'A' && c2 <= 'Z') {
c2 = (char)(c2 + 32);
}
if ((c2 = message.charAt(++i)) >= 'A' && c2 <= 'Z') c2 = (char) (c2 + 32);
if ((format = ChatColor.getByChar(c2)) == null) continue;
if (builder.length() > 0) {
old = component;
@ -69,9 +66,7 @@ extends BaseComponent {
continue;
}
int pos = message.indexOf(32, i);
if (pos == -1) {
pos = message.length();
}
if (pos == -1) pos = message.length();
if (matcher.region(i, pos).find()) {
if (builder.length() > 0) {
old = component;
@ -84,7 +79,8 @@ extends BaseComponent {
component = new TextComponent(old);
String urlString = message.substring(i, pos);
component.setText(urlString);
component.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, urlString.startsWith("http") ? urlString : "http://" + urlString));
component.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL,
urlString.startsWith("http") ? urlString : "http://" + urlString));
components.add(component);
i += pos - i - 1;
component = old;
@ -96,20 +92,18 @@ extends BaseComponent {
component.setText(builder.toString());
components.add(component);
}
if (components.isEmpty()) {
components.add(new TextComponent(""));
}
if (components.isEmpty()) components.add(new TextComponent(""));
return components.toArray(new BaseComponent[components.size()]);
}
public TextComponent(TextComponent textComponent) {
super(textComponent);
this.setText(textComponent.getText());
setText(textComponent.getText());
}
public /* varargs */ TextComponent(BaseComponent... extras) {
this.setText("");
this.setExtra(new ArrayList<BaseComponent>(Arrays.asList(extras)));
setText("");
setExtra(new ArrayList<BaseComponent>(Arrays.asList(extras)));
}
@Override
@ -119,39 +113,29 @@ extends BaseComponent {
@Override
protected void toPlainText(StringBuilder builder) {
builder.append(this.text);
builder.append(text);
super.toPlainText(builder);
}
@Override
protected void toLegacyText(StringBuilder builder) {
builder.append((Object)this.getColor());
if (this.isBold()) {
builder.append((Object)ChatColor.BOLD);
}
if (this.isItalic()) {
builder.append((Object)ChatColor.ITALIC);
}
if (this.isUnderlined()) {
builder.append((Object)ChatColor.UNDERLINE);
}
if (this.isStrikethrough()) {
builder.append((Object)ChatColor.STRIKETHROUGH);
}
if (this.isObfuscated()) {
builder.append((Object)ChatColor.MAGIC);
}
builder.append(this.text);
builder.append(getColor());
if (isBold()) builder.append(ChatColor.BOLD);
if (isItalic()) builder.append(ChatColor.ITALIC);
if (isUnderlined()) builder.append(ChatColor.UNDERLINE);
if (isStrikethrough()) builder.append(ChatColor.STRIKETHROUGH);
if (isObfuscated()) builder.append(ChatColor.MAGIC);
builder.append(text);
super.toLegacyText(builder);
}
@Override
public String toString() {
return String.format("TextComponent{text=%s, %s}", this.text, super.toString());
return String.format("TextComponent{text=%s, %s}", text, super.toString());
}
public String getText() {
return this.text;
return text;
}
public void setText(String text) {
@ -163,8 +147,6 @@ extends BaseComponent {
this.text = text;
}
public TextComponent() {
}
public TextComponent() {}
}

View File

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