|
|
|
@ -9,9 +9,10 @@ import org.json.JSONArray;
|
|
|
|
|
import org.json.JSONObject;
|
|
|
|
|
|
|
|
|
|
import java.io.IOException;
|
|
|
|
|
import java.io.InputStream;
|
|
|
|
|
import java.io.OutputStream;
|
|
|
|
|
import java.nio.charset.StandardCharsets;
|
|
|
|
|
import java.util.List;
|
|
|
|
|
import java.util.Random;
|
|
|
|
|
|
|
|
|
|
class CommunityHandler implements HttpHandler {
|
|
|
|
|
RedditAPI api;
|
|
|
|
@ -46,19 +47,45 @@ class CommunityHandler implements HttpHandler {
|
|
|
|
|
}
|
|
|
|
|
assert submissions != null;
|
|
|
|
|
|
|
|
|
|
JSONObject responseJSON = new JSONObject();
|
|
|
|
|
JSONArray subsJSON = new JSONArray();
|
|
|
|
|
submissions.forEach(sub -> {
|
|
|
|
|
subsJSON.put(subToJSON(sub));
|
|
|
|
|
});
|
|
|
|
|
if ( pathArray.length < 6 || pathArray[5].equals("") || pathArray[5].equals("random")) {
|
|
|
|
|
Random rand = new Random();
|
|
|
|
|
subsJSON.put(subToJSON(
|
|
|
|
|
submissions.get(rand.nextInt(submissions.size()))
|
|
|
|
|
));
|
|
|
|
|
responseJSON.put("error", "false");
|
|
|
|
|
responseJSON.put("type", "random");
|
|
|
|
|
} else if (pathArray[5].equals("all")) {
|
|
|
|
|
submissions.forEach(sub -> {
|
|
|
|
|
subsJSON.put(subToJSON(sub));
|
|
|
|
|
});
|
|
|
|
|
responseJSON.put("error", "false");
|
|
|
|
|
responseJSON.put("type", "all");
|
|
|
|
|
} else {
|
|
|
|
|
try{
|
|
|
|
|
int subNum = Integer.parseInt(pathArray[5]);
|
|
|
|
|
if (subNum >= submissions.size()) responseJSON.put("error", "invalid input");
|
|
|
|
|
else{
|
|
|
|
|
subsJSON.put(subToJSON(submissions.get(subNum)));
|
|
|
|
|
responseJSON.put("error", "false");
|
|
|
|
|
responseJSON.put("type", "specific");
|
|
|
|
|
}
|
|
|
|
|
}catch (NumberFormatException ignored){
|
|
|
|
|
responseJSON.put("error", "invalid input");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
responseJSON.put("subs", subsJSON);
|
|
|
|
|
|
|
|
|
|
String response = subsJSON.toString(0);
|
|
|
|
|
String response = responseJSON.toString();
|
|
|
|
|
System.out.println("response > "+response);
|
|
|
|
|
Headers headers = t.getResponseHeaders();
|
|
|
|
|
headers.add("Content-Type", "application/json");
|
|
|
|
|
headers.set("Content-Type", "application/json; charset=UTF-8");
|
|
|
|
|
System.out.println(response.length());
|
|
|
|
|
t.sendResponseHeaders(200, response.length());
|
|
|
|
|
OutputStream os = t.getResponseBody();
|
|
|
|
|
os.write(response.getBytes());
|
|
|
|
|
headers.add("Connection", "close");
|
|
|
|
|
t.sendResponseHeaders(200, response.length());
|
|
|
|
|
os.write(response.getBytes(StandardCharsets.UTF_8));
|
|
|
|
|
os.close();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|