58 lines
2.1 KiB
Java
58 lines
2.1 KiB
Java
package be.jeffcheasey88.peeratcode.routes;
|
|
|
|
import java.util.regex.Matcher;
|
|
|
|
import org.json.simple.JSONArray;
|
|
import org.json.simple.JSONObject;
|
|
|
|
import be.jeffcheasey88.peeratcode.framework.HttpReader;
|
|
import be.jeffcheasey88.peeratcode.framework.HttpUtil;
|
|
import be.jeffcheasey88.peeratcode.framework.HttpWriter;
|
|
import be.jeffcheasey88.peeratcode.framework.Response;
|
|
import be.jeffcheasey88.peeratcode.framework.Route;
|
|
import be.jeffcheasey88.peeratcode.framework.User;
|
|
import be.jeffcheasey88.peeratcode.model.Chapter;
|
|
import be.jeffcheasey88.peeratcode.model.Puzzle;
|
|
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;
|
|
|
|
public class ChapterElement implements Response {
|
|
|
|
private final DatabaseRepository databaseRepo;
|
|
|
|
public ChapterElement(DatabaseRepository databaseRepo) {
|
|
this.databaseRepo = databaseRepo;
|
|
}
|
|
|
|
@Route(path = "^\\/chapter\\/([0-9]+)$", needLogin = true)
|
|
@Override
|
|
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
|
|
Chapter chapter = databaseRepo.getChapter(extractId(matcher));
|
|
if (chapter != null) {
|
|
JSONObject chapterJSON = new JSONObject();
|
|
chapterJSON.put("id", chapter.getId());
|
|
chapterJSON.put("name", chapter.getName());
|
|
if (chapter.getStartDate() != null)
|
|
chapterJSON.put("startDate", chapter.getStartDate().toString());
|
|
if (chapter.getEndDate() != null)
|
|
chapterJSON.put("endDate", chapter.getEndDate().toString());
|
|
JSONArray puzzles = new JSONArray();
|
|
for (Puzzle puzzle : chapter.getPuzzles()) {
|
|
JSONObject puzzleJSON = new JSONObject();
|
|
puzzleJSON.put("id", puzzle.getId());
|
|
puzzleJSON.put("name", puzzle.getName());
|
|
if (puzzle.getTags() != null)
|
|
puzzleJSON.put("tags", puzzle.getJsonTags());
|
|
puzzles.add(puzzleJSON);
|
|
}
|
|
chapterJSON.put("puzzles", puzzles);
|
|
HttpUtil.responseHeaders(writer, 200, "Access-Control-Allow-Origin: *");
|
|
writer.write(chapterJSON.toJSONString());
|
|
} else {
|
|
HttpUtil.responseHeaders(writer, 400, "Access-Control-Allow-Origin: *");
|
|
}
|
|
}
|
|
|
|
private int extractId(Matcher matcher) {
|
|
return Integer.parseInt(matcher.group(1));
|
|
}
|
|
}
|