add random and specific output

master
adb 3 years ago
parent 4854166383
commit 897fdf5be6

@ -3,6 +3,10 @@ plugins {
id 'maven'
}
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
@ -24,6 +28,7 @@ dependencies {
compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.3.3'
compile group: 'org.apache.oltu.oauth2', name: 'org.apache.oltu.oauth2.client', version: '1.0.0'
compile group: 'javax.xml.bind', name : 'jaxb-api', version: '2.3.1'
compile group: 'org.slf4j', name : 'nlog4j', version: '1.2.25'
testCompile group: 'commons-validator', name: 'commons-validator', version: '1.4.1'
testCompile group: 'junit', name: 'junit', version: '4.8.1'
testCompile group: 'org.mockito', name: 'mockito-core', version: '1.9.5'

@ -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();
}
}

Loading…
Cancel
Save