Add GroupList route & Refractor DatabaseQuery

This commit is contained in:
jeffcheasey88 2023-03-27 16:30:01 +02:00
parent 1da9cfcb05
commit 05ff24de32
12 changed files with 192 additions and 107 deletions

View file

@ -22,6 +22,7 @@ import be.jeffcheasey88.peeratcode.routes.PuzzleElement;
import be.jeffcheasey88.peeratcode.routes.PuzzleResponse; import be.jeffcheasey88.peeratcode.routes.PuzzleResponse;
import be.jeffcheasey88.peeratcode.routes.Register; import be.jeffcheasey88.peeratcode.routes.Register;
import be.jeffcheasey88.peeratcode.routes.Result; import be.jeffcheasey88.peeratcode.routes.Result;
import be.jeffcheasey88.peeratcode.routes.groups.GroupList;
import be.jeffcheasey88.peeratcode.webserver.Client; import be.jeffcheasey88.peeratcode.webserver.Client;
import be.jeffcheasey88.peeratcode.webserver.HttpReader; import be.jeffcheasey88.peeratcode.webserver.HttpReader;
import be.jeffcheasey88.peeratcode.webserver.HttpUtil; import be.jeffcheasey88.peeratcode.webserver.HttpUtil;
@ -77,6 +78,8 @@ public class Main {
router.register(new Leaderboard(router.getDataBase())); router.register(new Leaderboard(router.getDataBase()));
router.register(new PlayerDetails(router.getDataBase())); router.register(new PlayerDetails(router.getDataBase()));
router.register(new BadgeDetails(router.getDataBase())); router.register(new BadgeDetails(router.getDataBase()));
router.register(new GroupList(router.getDataBase()));
} }
private static void startWebServer(Configuration config, Router router) throws IOException { private static void startWebServer(Configuration config, Router router) throws IOException {

View file

@ -37,7 +37,7 @@ public class Group {
this.linkToPuzzle = linkToPuzzle; this.linkToPuzzle = linkToPuzzle;
} }
public JSONObject getJson() { public JSONObject toJson() {
JSONObject groupJSON = new JSONObject(); JSONObject groupJSON = new JSONObject();
groupJSON.put("name", name); groupJSON.put("name", name);
if (linkToChapter > 0) groupJSON.put("chapter", linkToChapter); if (linkToChapter > 0) groupJSON.put("chapter", linkToChapter);

View file

@ -78,7 +78,7 @@ public class Player implements Comparable<Player> {
if (groups != null) { if (groups != null) {
JSONArray groupsJSON = new JSONArray(); JSONArray groupsJSON = new JSONArray();
for (Group group : groups) { for (Group group : groups) {
groupsJSON.add(group.getJson()); groupsJSON.add(group.toJson());
} }
return groupsJSON; return groupsJSON;
} }

View file

@ -38,14 +38,6 @@ public class Class {
int braces = indexOf(content,"\\{"); int braces = indexOf(content,"\\{");
int equals = indexOf(content,"="); int equals = indexOf(content,"=");
if(quotes < braces && quotes < equals){ if(quotes < braces && quotes < equals){
Variable variable = new Variable();
int index = variable.parse(content);
this.vars.add(variable);
content = content.substring(index);
}else if(equals < braces){
//variable with value
System.out.println(content);
System.out.println("equals < braces");
boolean quote = false; boolean quote = false;
Variable last = null; Variable last = null;
do { do {
@ -59,12 +51,33 @@ public class Class {
last = variable; last = variable;
} }
}while(quote); }while(quote);
break; }else if(equals < braces){
//variable with value
boolean quote = false;
Variable last = null;
do {
Variable variable = (last == null) ? new Variable() : new Variable(last.getModifier(), last.getType());
int index = variable.parse(content);
this.vars.add(variable);
content = content.substring(index);
quote = content.startsWith(",");
if(quote) {
content = content.substring(1);
last = variable;
}else if(indexOf(content, "=") < indexOf(content, ";")){
Operation operation = new Operation();
index = operation.parse(content);
content = content.substring(index);
break;
}
}while(quote);
}else{ }else{
System.out.println("Function "+content);
Function func = new Function(); Function func = new Function();
int index = func.parse(content); int index = func.parse(content);
this.functions.add(func); this.functions.add(func);
content = content.substring(index); content = content.substring(index);
System.out.println("End "+content);
} }
} }
@ -90,6 +103,8 @@ public class Class {
public void show(){ public void show(){
System.out.println(Modifier.toString(modifier)+" "+this.name+"{"); System.out.println(Modifier.toString(modifier)+" "+this.name+"{");
for(Variable v : this.vars) v.show(1); for(Variable v : this.vars) v.show(1);
System.out.println();
for(Function f : this.functions) f.show(1);
System.out.println("}"); System.out.println("}");
} }
} }

View file

@ -1,5 +1,8 @@
package be.jeffcheasey88.peeratcode.parser.java; package be.jeffcheasey88.peeratcode.parser.java;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@ -12,8 +15,12 @@ public class Function {
private String exceptions; private String exceptions;
private String parameters; private String parameters;
public Function(){ private List<Function> functions;
private List<Operation> operations;
public Function(){
this.functions = new ArrayList<>();
this.operations = new ArrayList<>();
} }
public int parse(String content) throws Exception{ public int parse(String content) throws Exception{
@ -32,20 +39,16 @@ public class Function {
int offset = 0; int offset = 0;
int index = 0; int index = 0;
do { do {
System.out.println();
int end = body.indexOf('}'); int end = body.indexOf('}');
int braces = body.indexOf('{'); int braces = body.indexOf('{');
int quotes = body.indexOf(';'); int quotes = body.indexOf(';');
if((end < 0) || (end < braces && end < quotes)){ if((end < 0) || (end < braces && end < quotes)){
// System.out.println("no INDEX in "+body); if(end > 0) offset+=end;
// if(end > 0) offset+=end;
break; break;
} }
// System.out.println(toString()+" - "+offset+" | "+end);
if(braces < 0 && quotes < 0){ if(braces < 0 && quotes < 0){
System.out.println("OUT "+body);
if(end > 0) offset+=end; if(end > 0) offset+=end;
break; break;
} }
@ -53,21 +56,28 @@ public class Function {
if(braces >= 0 && braces < quotes){ if(braces >= 0 && braces < quotes){
Function func = new Function(); Function func = new Function();
index = func.parse(body.substring(0, end+1)); index = func.parse(body.substring(0, end+1));
this.functions.add(func);
}else{ }else{
Operation op = new Operation(); Operation op = new Operation();
index = op.parse(body.substring(0, end)); index = op.parse(body.substring(0, end+1));
this.operations.add(op);
} }
offset+=index+1; offset+=index+1;
// System.out.println("SEEKINDEX "+index+" "+toString());
// System.out.println("FROM("+body.length()+") "+body);
// System.out.println();
body = body.substring(index); body = body.substring(index);
}while(offset > -1); }while(offset > -1);
// System.out.println(toString()+": "+(matcher.group(1).length()+offset+1));
// System.out.println("\t\t\t\t("+content.length()+")\t"+content);
return matcher.group(1).length()+offset; return matcher.group(1).length()+offset;
} }
public void show(int tab){
String start = "";
for(int i = 0; i < tab; i++) start+="\t";
System.out.println(start+Modifier.toString(modifier)+" "+name+"("+parameters+") "+exceptions+" {");
for(Operation o : this.operations) o.show(tab+1);
System.out.println();
for(Function f : this.functions) f.show(tab+1);
System.out.println(start+"}");
}
@Override @Override
public String toString(){ public String toString(){
return "Function[name="+name+",param="+parameters+",exception="+exceptions+"]"; return "Function[name="+name+",param="+parameters+",exception="+exceptions+"]";

View file

@ -10,11 +10,12 @@ import java.util.List;
public class JavaParser { public class JavaParser {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
File file = new File("C:\\Users\\jeffc\\eclipse-workspace\\JavaBenjaminCompiler\\src\\be\\jeffcheasey88\\parser\\rework\\Import.java"); File file = new File("C:\\Users\\jeffc\\eclipse-workspace\\peer-at-code-backend\\src\\be\\jeffcheasey88\\peeratcode\\parser\\java\\Import.java");
BufferedReader reader = new BufferedReader(new FileReader(file)); BufferedReader reader = new BufferedReader(new FileReader(file));
JavaParser parser = new JavaParser(reader); JavaParser parser = new JavaParser(reader);
parser.parse(); parser.parse();
System.out.println("SHOW-----------------");
parser.show(); parser.show();
} }

View file

@ -9,18 +9,21 @@ public class Operation {
private String tmp; private String tmp;
public Operation(){ public Operation(){}
}
public int parse(String content) throws Exception{ public int parse(String content) throws Exception{
Matcher matcher = VARIABLE_PATTERN.matcher(content); Matcher matcher = VARIABLE_PATTERN.matcher(content);
if(matcher.matches()){ if(matcher.matches()){
this.tmp = matcher.group(2); this.tmp = matcher.group(2);
System.out.println("parsed "+tmp);
return matcher.group(1).length()+1; return matcher.group(1).length()+1;
} }
return 0; return 0;
} }
public void show(int tab){
String start = "";
for(int i = 0; i < tab; i++) start+="\t";
System.out.println(start+tmp+";");
}
} }

View file

@ -29,8 +29,6 @@ public class Variable {
//int i =j=k=l=4; //int i =j=k=l=4;
public int parse(String content) throws Exception{ public int parse(String content) throws Exception{
System.out.println("Variable.parse");
System.out.println(content);
Matcher matcher = PATTERN.matcher(content); Matcher matcher = PATTERN.matcher(content);
matcher.matches(); matcher.matches();
@ -39,7 +37,11 @@ public class Variable {
boolean hasEquals = false; boolean hasEquals = false;
boolean fromMinus = false; boolean fromMinus = false;
String body = matcher.group(2); String body = matcher.group(2);
while(true){ while(body.length() > 0){
while(indexOf(body, "\\s+") == 0){
body = body.substring(1);
offset++;
}
int space = indexOf(body, "\\s+"); int space = indexOf(body, "\\s+");
int equals = indexOf(body, "="); int equals = indexOf(body, "=");
int quote = indexOf(body,","); int quote = indexOf(body,",");
@ -49,33 +51,17 @@ public class Variable {
int min = min(space, equals, quote, quotes, minus); int min = min(space, equals, quote, quotes, minus);
String value = body.substring(0,min); String value = body.substring(0,min);
System.out.println("'"+value+"'");
if(hasEquals){ if(hasEquals){
if(value.isEmpty()){
do {
body = body.substring(1);
offset++;
}while(indexOf(body, "\\s+") == 0);
continue;
}
this.value = new Value(value); this.value = new Value(value);
body = body.substring(value.length()+1); body = body.substring(value.length()+1);
offset+=value.length()+1; offset+=value.length()+1;
break; break;
}else if(fromMinus){ }else if(fromMinus){
System.out.println("fromMinus "+value);
this.name = value; this.name = value;
body = body.substring(value.length()+1); body = body.substring(value.length()+1);
offset+=value.length()+1; offset+=value.length()+1;
break; break;
} else if(min == space){ } else if(min == space){
if(value.isEmpty()){
do {
body = body.substring(1);
offset++;
}while(indexOf(body, "\\s+") == 0);
continue;
}
int mod = JavaParser.getModifier(value); int mod = JavaParser.getModifier(value);
if(mod > 0){ if(mod > 0){
this.modifier+=mod; this.modifier+=mod;
@ -95,7 +81,6 @@ public class Variable {
offset+=value.length()+1; offset+=value.length()+1;
}else if(min == minus){ }else if(min == minus){
value = value+"<"; value = value+"<";
System.out.println("MINUS");
int maxus = 1; int maxus = 1;
while(maxus > 0){ while(maxus > 0){
char current = body.charAt(value.length()); char current = body.charAt(value.length());
@ -115,12 +100,16 @@ public class Variable {
offset++; offset++;
} }
fromMinus = true; fromMinus = true;
System.out.println("fromMinus on "+body); }else if(min == quote || min == quotes){
}else if(min == quote){
if(this.name != null) break; if(this.name != null) break;
this.name = value; this.name = value;
body = body.substring(value.length()); body = body.substring(value.length());
offset+=value.length(); offset+=value.length();
if(min == quotes){
body = body.substring(1);
offset+=1;
}
break; break;
}else { }else {
offset+=value.length()+1; offset+=value.length()+1;
@ -128,10 +117,6 @@ public class Variable {
} }
} }
System.out.println("-------------");
show(0);
System.out.println("-------------");
return offset; return offset;
} }
@ -166,8 +151,7 @@ public class Variable {
public void show(int tab){ public void show(int tab){
String start = ""; String start = "";
for(int i = 0; i < tab; i++) start+="\t"; for(int i = 0; i < tab; i++) start+="\t";
System.out.println("type="+type+" | name="+name); System.out.println(start+Modifier.toString(modifier)+" "+type+" "+name+(value == null ? ";":"="+value+";"));
System.out.println(start+Modifier.toString(modifier)+" "+type+" "+name+";");
} }
public static class Value extends Variable{ public static class Value extends Variable{
@ -181,5 +165,10 @@ public class Variable {
public String value(){ public String value(){
return this.value; return this.value;
} }
@Override
public String toString(){
return this.value;
}
} }
} }

View file

@ -0,0 +1,48 @@
package be.jeffcheasey88.peeratcode.repository;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public enum DatabaseQuery {
SPECIFIC_PUZZLE_QUERY("SELECT p.*, np.origin, GROUP_CONCAT(t.name) AS tags FROM puzzles p LEFT JOIN nextPart np ON p.id_puzzle = np.next LEFT JOIN containsTags ct ON ct.fk_puzzle = p.id_puzzle LEFT JOIN tags t ON t.id_tag = ct.fk_tag WHERE p.id_puzzle = ? GROUP BY p.id_puzzle"),
SPECIFIC_CHAPTER_QUERY("SELECT * FROM chapters WHERE id_chapter = ?"),
PUZZLES_IN_CHAPTER_QUERY("SELECT p.*, GROUP_CONCAT(t.name) AS tags FROM puzzles p LEFT JOIN containsTags ct ON ct.fk_puzzle = p.id_puzzle LEFT JOIN tags t ON t.id_tag = ct.fk_tag WHERE fk_chapter = ? GROUP BY p.id_puzzle"),
ALL_CHAPTERS_QUERY("SELECT * FROM chapters WHERE id_chapter > 0"),
ALL_GROUPS("SELCT * FROM groups"),
CHECK_PSEUDO_AVAILABLE_QUERY("SELECT * FROM players WHERE pseudo = ?"),
CHECK_EMAIL_AVAILABLE_QUERY("SELECT * FROM players WHERE email = ?"),
REGISTER_QUERY("INSERT INTO players (pseudo, email, passwd, firstname, lastname, description, sgroup, avatar) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"),
CHECK_PASSWORD("SELECT id_player, passwd FROM players WHERE pseudo=?"),
SCORE("SELECT score FROM completions WHERE fk_player = ? AND fk_puzzle = ?"),
GET_COMPLETION("SELECT id_completion, tries, fileName, score FROM completions WHERE fk_puzzle = ? AND fk_player = ?"),
GET_PLAYER_SIMPLE("SELECT pseudo, email, firstname, lastname, description FROM players WHERE id_player = ?"),
GET_PLAYER_DETAILS("SELECT p.*, scores.score, scores.completions, scores.tries, scores.rank, g.* FROM players p, (SELECT fk_player, SUM(c.score) AS score, COUNT(c.id_completion) AS completions, SUM(c.tries) AS tries, rank() over(ORDER BY score DESC) AS rank FROM completions c GROUP BY c.fk_player) AS scores LEFT JOIN containsGroups cg ON scores.fk_player = cg.fk_player LEFT JOIN groups g ON cg.fk_group = g.id_group WHERE p.id_player = scores.fk_player AND "),
GET_PLAYER_DETAILS_BY_ID(GET_PLAYER_DETAILS," p.id_player = ? ORDER BY g.fk_chapter, g.fk_puzzle;"),
GET_PLAYER_DETAILS_BY_PSEUDO(GET_PLAYER_DETAILS,"p.pseudo = ? ORDER BY g.fk_chapter, g.fk_puzzle;"),
ALL_PLAYERS_FOR_LEADERBOARD("select p.*, scores.*, g.* from players p ,(SELECT fk_player, SUM(c.score) AS score, COUNT(c.id_completion) AS completions, SUM(c.tries) AS tries, rank() over(ORDER BY score DESC) AS rank FROM completions c GROUP BY c.fk_player) AS scores LEFT JOIN containsGroups cg ON scores.fk_player = cg.fk_player LEFT JOIN groups g ON cg.fk_group = g.id_group WHERE p.id_player = scores.fk_player ORDER BY g.fk_chapter, g.fk_puzzle"),
GET_BADGE("SELECT * FROM badges WHERE id_badge = ?"),
GET_BADGES_OF_PLAYER("SELECT * FROM badges b LEFT JOIN containsBadges cb ON cb.fk_badge = b.id_badge WHERE cb.fk_player = ?"),
INSERT_COMPLETION("INSERT INTO completions (fk_puzzle, fk_player, tries, code, fileName, score) values (?, ?, ?, ?, ?, ?)"),
UPDATE_COMPLETION("UPDATE completions SET tries = ?, filename = ?, score = ? WHERE fk_puzzle = ? AND fk_player = ?");
private String request;
DatabaseQuery(DatabaseQuery parent, String request){
this.request = parent.request+request;
}
DatabaseQuery(String request){
this.request = request;
}
public PreparedStatement prepare(Connection con) throws SQLException{
return con.prepareStatement(this.request);
}
@Override
public String toString(){
return this.request;
}
}

View file

@ -24,27 +24,6 @@ import be.jeffcheasey88.peeratcode.model.Player;
import be.jeffcheasey88.peeratcode.model.Puzzle; import be.jeffcheasey88.peeratcode.model.Puzzle;
public class DatabaseRepository { public class DatabaseRepository {
private static final String SPECIFIC_PUZZLE_QUERY = "SELECT p.*, np.origin, GROUP_CONCAT(t.name) AS tags FROM puzzles p LEFT JOIN nextPart np ON p.id_puzzle = np.next LEFT JOIN containsTags ct ON ct.fk_puzzle = p.id_puzzle LEFT JOIN tags t ON t.id_tag = ct.fk_tag WHERE p.id_puzzle = ? GROUP BY p.id_puzzle";
private static final String SPECIFIC_CHAPTER_QUERY = "SELECT * FROM chapters WHERE id_chapter = ?";
private static final String PUZZLES_IN_CHAPTER_QUERY = "SELECT p.*, GROUP_CONCAT(t.name) AS tags FROM puzzles p LEFT JOIN containsTags ct ON ct.fk_puzzle = p.id_puzzle LEFT JOIN tags t ON t.id_tag = ct.fk_tag WHERE fk_chapter = ? GROUP BY p.id_puzzle";
private static final String ALL_CHAPTERS_QUERY = "SELECT * FROM chapters WHERE id_chapter > 0";
private static final String CHECK_PSEUDO_AVAILABLE_QUERY = "SELECT * FROM players WHERE pseudo = ?";
private static final String CHECK_EMAIL_AVAILABLE_QUERY = "SELECT * FROM players WHERE email = ?";
private static final String REGISTER_QUERY = "INSERT INTO players (pseudo, email, passwd, firstname, lastname, description, sgroup, avatar) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
private static final String CHECK_PASSWORD = "SELECT id_player, passwd FROM players WHERE pseudo=?";
private static final String SCORE = "SELECT score FROM completions WHERE fk_player = ? AND fk_puzzle = ?";
private static final String GET_COMPLETION = "SELECT id_completion, tries, fileName, score FROM completions WHERE fk_puzzle = ? AND fk_player = ?";
private static final String GET_PLAYER_SIMPLE = "SELECT pseudo, email, firstname, lastname, description FROM players WHERE id_player = ?";
private static final String GET_PLAYER_DETAILS = "SELECT p.*, scores.score, scores.completions, scores.tries, scores.rank, g.* FROM players p, (SELECT fk_player, SUM(c.score) AS score, COUNT(c.id_completion) AS completions, SUM(c.tries) AS tries, rank() over(ORDER BY score DESC) AS rank FROM completions c GROUP BY c.fk_player) AS scores LEFT JOIN containsGroups cg ON scores.fk_player = cg.fk_player LEFT JOIN groups g ON cg.fk_group = g.id_group WHERE p.id_player = scores.fk_player AND ";
private static final String GET_PLAYER_DETAILS_BY_ID = GET_PLAYER_DETAILS
+ " p.id_player = ? ORDER BY g.fk_chapter, g.fk_puzzle;";
private static final String GET_PLAYER_DETAILS_BY_PSEUDO = GET_PLAYER_DETAILS
+ "p.pseudo = ? ORDER BY g.fk_chapter, g.fk_puzzle;";
private static final String ALL_PLAYERS_FOR_LEADERBOARD = "select p.*, scores.*, g.* from players p ,(SELECT fk_player, SUM(c.score) AS score, COUNT(c.id_completion) AS completions, SUM(c.tries) AS tries, rank() over(ORDER BY score DESC) AS rank FROM completions c GROUP BY c.fk_player) AS scores LEFT JOIN containsGroups cg ON scores.fk_player = cg.fk_player LEFT JOIN groups g ON cg.fk_group = g.id_group WHERE p.id_player = scores.fk_player ORDER BY g.fk_chapter, g.fk_puzzle";
private static final String GET_BADGE = "SELECT * FROM badges WHERE id_badge = ?";
private static final String GET_BADGES_OF_PLAYER = "SELECT * FROM badges b LEFT JOIN containsBadges cb ON cb.fk_badge = b.id_badge WHERE cb.fk_player = ?";
private static final String INSERT_COMPLETION = "INSERT INTO completions (fk_puzzle, fk_player, tries, code, fileName, score) values (?, ?, ?, ?, ?, ?)";
private static final String UPDATE_COMPLETION = "UPDATE completions SET tries = ?, filename = ?, score = ? WHERE fk_puzzle = ? AND fk_player = ?";
private Connection con; private Connection con;
private Configuration config; private Configuration config;
@ -101,9 +80,7 @@ public class DatabaseRepository {
} }
private Group makeGroup(ResultSet result) throws SQLException { private Group makeGroup(ResultSet result) throws SQLException {
Group gr = new Group(result.getString("name"), result.getInt("fk_chapter"), result.getInt("fk_puzzle")); return new Group(result.getString("name"), result.getInt("fk_chapter"), result.getInt("fk_puzzle"));
return gr;
} }
private Badge makeBadge(ResultSet rs) throws SQLException { private Badge makeBadge(ResultSet rs) throws SQLException {
@ -125,7 +102,7 @@ public class DatabaseRepository {
private List<Puzzle> getPuzzlesInChapter(int id) throws SQLException { private List<Puzzle> getPuzzlesInChapter(int id) throws SQLException {
List<Puzzle> puzzles = new ArrayList<>(); List<Puzzle> puzzles = new ArrayList<>();
ensureConnection(); ensureConnection();
PreparedStatement puzzleStmt = con.prepareStatement(PUZZLES_IN_CHAPTER_QUERY); PreparedStatement puzzleStmt = DatabaseQuery.PUZZLES_IN_CHAPTER_QUERY.prepare(this.con);
puzzleStmt.setInt(1, id); puzzleStmt.setInt(1, id);
ResultSet puzzleResult = puzzleStmt.executeQuery(); ResultSet puzzleResult = puzzleStmt.executeQuery();
while (puzzleResult.next()) { while (puzzleResult.next()) {
@ -143,7 +120,7 @@ public class DatabaseRepository {
public Puzzle getPuzzle(int id) { public Puzzle getPuzzle(int id) {
try { try {
ensureConnection(); ensureConnection();
PreparedStatement puzzleStmt = con.prepareStatement(SPECIFIC_PUZZLE_QUERY); PreparedStatement puzzleStmt = DatabaseQuery.SPECIFIC_PUZZLE_QUERY.prepare(this.con);
puzzleStmt.setInt(1, id); puzzleStmt.setInt(1, id);
ResultSet puzzleResult = puzzleStmt.executeQuery(); ResultSet puzzleResult = puzzleStmt.executeQuery();
if (puzzleResult.next()) { if (puzzleResult.next()) {
@ -155,10 +132,10 @@ public class DatabaseRepository {
return null; return null;
} }
public int getScore(int user, int puzzle) { public int getScore(int user, int puzzle){
try { try {
ensureConnection(); ensureConnection();
PreparedStatement stmt = this.con.prepareStatement(SCORE); PreparedStatement stmt = DatabaseQuery.SCORE.prepare(this.con);
stmt.setInt(1, user); stmt.setInt(1, user);
stmt.setInt(2, puzzle); stmt.setInt(2, puzzle);
@ -173,7 +150,7 @@ public class DatabaseRepository {
public Completion getCompletion(int playerId, int puzzleId) { public Completion getCompletion(int playerId, int puzzleId) {
try { try {
PreparedStatement completionsStmt = con.prepareStatement(GET_COMPLETION); PreparedStatement completionsStmt = DatabaseQuery.GET_COMPLETION.prepare(this.con);
completionsStmt.setInt(1, puzzleId); completionsStmt.setInt(1, puzzleId);
completionsStmt.setInt(2, playerId); completionsStmt.setInt(2, playerId);
ResultSet result = completionsStmt.executeQuery(); ResultSet result = completionsStmt.executeQuery();
@ -188,7 +165,7 @@ public class DatabaseRepository {
public Player getPlayer(int idPlayer) { public Player getPlayer(int idPlayer) {
try { try {
PreparedStatement completionsStmt = con.prepareStatement(GET_PLAYER_SIMPLE); PreparedStatement completionsStmt = DatabaseQuery.GET_PLAYER_SIMPLE.prepare(this.con);
completionsStmt.setInt(1, idPlayer); completionsStmt.setInt(1, idPlayer);
ResultSet result = completionsStmt.executeQuery(); ResultSet result = completionsStmt.executeQuery();
if (result.next()) { if (result.next()) {
@ -213,10 +190,10 @@ public class DatabaseRepository {
ensureConnection(); ensureConnection();
PreparedStatement completionsStmt; PreparedStatement completionsStmt;
if (pseudo != null) { if (pseudo != null) {
completionsStmt = con.prepareStatement(GET_PLAYER_DETAILS_BY_PSEUDO); completionsStmt = DatabaseQuery.GET_PLAYER_DETAILS_BY_PSEUDO.prepare(this.con);
completionsStmt.setString(1, pseudo); completionsStmt.setString(1, pseudo);
} else { } else {
completionsStmt = con.prepareStatement(GET_PLAYER_DETAILS_BY_ID); completionsStmt = DatabaseQuery.GET_PLAYER_DETAILS_BY_ID.prepare(this.con);
completionsStmt.setInt(1, id); completionsStmt.setInt(1, id);
} }
ResultSet result = completionsStmt.executeQuery(); ResultSet result = completionsStmt.executeQuery();
@ -224,7 +201,7 @@ public class DatabaseRepository {
while (result.next()) { while (result.next()) {
if (player == null) { if (player == null) {
player = makePlayer(result); player = makePlayer(result);
completionsStmt = con.prepareStatement(GET_BADGES_OF_PLAYER); completionsStmt = DatabaseQuery.GET_BADGES_OF_PLAYER.prepare(this.con);
completionsStmt.setInt(1, result.getInt("id_player")); completionsStmt.setInt(1, result.getInt("id_player"));
ResultSet resultBadges = completionsStmt.executeQuery(); ResultSet resultBadges = completionsStmt.executeQuery();
while (resultBadges.next()) { while (resultBadges.next()) {
@ -244,7 +221,7 @@ public class DatabaseRepository {
public SortedSet<Player> getAllPlayerForLeaderboard() { public SortedSet<Player> getAllPlayerForLeaderboard() {
try { try {
ensureConnection(); ensureConnection();
PreparedStatement playersStmt = con.prepareStatement(ALL_PLAYERS_FOR_LEADERBOARD); PreparedStatement playersStmt = DatabaseQuery.ALL_PLAYERS_FOR_LEADERBOARD.prepare(this.con);
ResultSet result = playersStmt.executeQuery(); ResultSet result = playersStmt.executeQuery();
ArrayList<Player> players = new ArrayList<Player>(); ArrayList<Player> players = new ArrayList<Player>();
Player tmpPlayer; Player tmpPlayer;
@ -266,7 +243,7 @@ public class DatabaseRepository {
public Badge getBadge(int badgeId) { public Badge getBadge(int badgeId) {
try { try {
ensureConnection(); ensureConnection();
PreparedStatement completionsStmt = con.prepareStatement(GET_BADGE); PreparedStatement completionsStmt = DatabaseQuery.GET_BADGE.prepare(this.con);
completionsStmt.setInt(1, badgeId); completionsStmt.setInt(1, badgeId);
ResultSet result = completionsStmt.executeQuery(); ResultSet result = completionsStmt.executeQuery();
if (result.next()) { if (result.next()) {
@ -287,7 +264,7 @@ public class DatabaseRepository {
public Chapter getChapter(int id) { public Chapter getChapter(int id) {
try { try {
ensureConnection(); ensureConnection();
PreparedStatement chapterStmt = con.prepareStatement(SPECIFIC_CHAPTER_QUERY); PreparedStatement chapterStmt = DatabaseQuery.SPECIFIC_CHAPTER_QUERY.prepare(this.con);
chapterStmt.setInt(1, id); chapterStmt.setInt(1, id);
ResultSet chapterResult = chapterStmt.executeQuery(); ResultSet chapterResult = chapterStmt.executeQuery();
if (chapterResult.next()) { if (chapterResult.next()) {
@ -311,7 +288,7 @@ public class DatabaseRepository {
try { try {
List<Chapter> chapterList = new ArrayList<>(); List<Chapter> chapterList = new ArrayList<>();
ensureConnection(); ensureConnection();
PreparedStatement chapterStmt = con.prepareStatement(ALL_CHAPTERS_QUERY); PreparedStatement chapterStmt = DatabaseQuery.ALL_CHAPTERS_QUERY.prepare(this.con);
ResultSet chapterResult = chapterStmt.executeQuery(); ResultSet chapterResult = chapterStmt.executeQuery();
while (chapterResult.next()) { while (chapterResult.next()) {
Chapter chapter = makeChapter(chapterResult); Chapter chapter = makeChapter(chapterResult);
@ -325,6 +302,19 @@ public class DatabaseRepository {
return null; return null;
} }
public List<Group> getAllGroups(){
try {
List<Group> list = new ArrayList<>();
PreparedStatement stmt = DatabaseQuery.ALL_GROUPS.prepare(this.con);
ResultSet groupResult = stmt.executeQuery();
while(groupResult.next()) list.add(makeGroup(groupResult));
return list;
}catch(Exception e){
e.printStackTrace();
}
return null;
}
/** /**
* Check if a pseudo is available * Check if a pseudo is available
* *
@ -332,7 +322,7 @@ public class DatabaseRepository {
* @return True if the pseudo is available, false if it's already taken * @return True if the pseudo is available, false if it's already taken
*/ */
public boolean checkPseudoAvailability(String pseudo) { public boolean checkPseudoAvailability(String pseudo) {
return checkAvailability(pseudo, CHECK_PSEUDO_AVAILABLE_QUERY); return checkAvailability(pseudo, DatabaseQuery.CHECK_PSEUDO_AVAILABLE_QUERY.toString());
} }
/** /**
@ -342,7 +332,7 @@ public class DatabaseRepository {
* @return True if the email is available, false if it's already taken * @return True if the email is available, false if it's already taken
*/ */
public boolean checkEmailAvailability(String email) { public boolean checkEmailAvailability(String email) {
return checkAvailability(email, CHECK_EMAIL_AVAILABLE_QUERY); return checkAvailability(email, DatabaseQuery.CHECK_EMAIL_AVAILABLE_QUERY.toString());
} }
private boolean checkAvailability(String queriedString, String correspondingQuery) { private boolean checkAvailability(String queriedString, String correspondingQuery) {
@ -376,7 +366,7 @@ public class DatabaseRepository {
Hash hash = Password.hash(password).withArgon2(); Hash hash = Password.hash(password).withArgon2();
try { try {
ensureConnection(); ensureConnection();
PreparedStatement statement = con.prepareStatement(REGISTER_QUERY, Statement.RETURN_GENERATED_KEYS); PreparedStatement statement = con.prepareStatement(DatabaseQuery.REGISTER_QUERY.toString(), Statement.RETURN_GENERATED_KEYS);
statement.setString(1, pseudo); statement.setString(1, pseudo);
statement.setString(2, email); statement.setString(2, email);
statement.setString(3, hash.getResult()); statement.setString(3, hash.getResult());
@ -406,7 +396,7 @@ public class DatabaseRepository {
public int login(String username, String password) { public int login(String username, String password) {
try { try {
ensureConnection(); ensureConnection();
PreparedStatement statement = con.prepareStatement(CHECK_PASSWORD); PreparedStatement statement = con.prepareStatement(DatabaseQuery.CHECK_PASSWORD.toString());DatabaseQuery.PUZZLES_IN_CHAPTER_QUERY.prepare(this.con);
statement.setString(1, username); statement.setString(1, username);
ResultSet result = statement.executeQuery(); ResultSet result = statement.executeQuery();
if (result.next()) { if (result.next()) {
@ -438,7 +428,7 @@ public class DatabaseRepository {
private void insertCompletion(Completion newCompletion) throws SQLException { private void insertCompletion(Completion newCompletion) throws SQLException {
// Insert completions // Insert completions
PreparedStatement statement = con.prepareStatement(INSERT_COMPLETION); PreparedStatement statement = DatabaseQuery.INSERT_COMPLETION.prepare(this.con);
statement.setInt(1, newCompletion.getPuzzleId()); statement.setInt(1, newCompletion.getPuzzleId());
statement.setInt(2, newCompletion.getPlayerId()); statement.setInt(2, newCompletion.getPlayerId());
statement.setInt(3, newCompletion.getTries()); statement.setInt(3, newCompletion.getTries());
@ -450,7 +440,7 @@ public class DatabaseRepository {
private void updateCompletion(Completion completionToUpdate) throws SQLException { private void updateCompletion(Completion completionToUpdate) throws SQLException {
// Update completions // Update completions
PreparedStatement statement = con.prepareStatement(UPDATE_COMPLETION); PreparedStatement statement = DatabaseQuery.UPDATE_COMPLETION.prepare(this.con);
statement.setInt(1, completionToUpdate.getTries()); statement.setInt(1, completionToUpdate.getTries());
statement.setString(2, completionToUpdate.getFileName()); statement.setString(2, completionToUpdate.getFileName());
statement.setInt(3, completionToUpdate.getScore()); statement.setInt(3, completionToUpdate.getScore());

View file

@ -0,0 +1,32 @@
package be.jeffcheasey88.peeratcode.routes.groups;
import java.util.regex.Matcher;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import be.jeffcheasey88.peeratcode.model.Group;
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;
import be.jeffcheasey88.peeratcode.webserver.HttpReader;
import be.jeffcheasey88.peeratcode.webserver.HttpWriter;
import be.jeffcheasey88.peeratcode.webserver.Response;
import be.jeffcheasey88.peeratcode.webserver.Route;
import be.jeffcheasey88.peeratcode.webserver.User;
public class GroupList implements Response{
private DatabaseRepository repo;
public GroupList(DatabaseRepository repo){
this.repo = repo;
}
@Route(path = "^\\/groups$", needLogin = true)
@Override
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
JSONArray result = new JSONArray();
for(Group group : this.repo.getAllGroups()) result.add(group.toJson());
writer.write(result.toJSONString());
}
}

View file

@ -124,22 +124,16 @@ class VariableTest {
void case7(){ void case7(){
try { try {
Class clazz = new Class(); Class clazz = new Class();
clazz.parse("public class Test{ int i =j=k=l=4; } "); clazz.parse("public class Test{ int i ,j,k; int l=i=k=l=4; } ");
List<Variable> vars = clazz.getVariables(); List<Variable> vars = clazz.getVariables();
assertEquals(vars.size(), 4); assertEquals(vars.size(), 4);
for(int i = 0; i < 3; i++){ for(int i = 0; i < 4; i++){
Variable v = vars.get(i); Variable v = vars.get(i);
assertEquals(0, v.getModifier()); assertEquals(0, v.getModifier());
assertEquals("int", v.getType()); assertEquals("int", v.getType());
assertEquals((char)('i'+i), v.getName().charAt(0)); assertEquals((char)('i'+i), v.getName().charAt(0));
assertEquals((char)('i'+i+1), ((Value)v.getValue()).value());
} }
Variable v = vars.get(3);
assertEquals(0, v.getModifier());
assertEquals("int", v.getType());
assertEquals('l', v.getName().charAt(0));
assertEquals("4", ((Value)v.getValue()).value());
}catch(Exception e){ }catch(Exception e){
fail(e); fail(e);
} }