|
|
|
@ -2,8 +2,11 @@ package sh.adb.RandomRedditMemesAPI;
|
|
|
|
|
|
|
|
|
|
import com.github.jreddit.parser.entity.Submission;
|
|
|
|
|
import com.github.jreddit.parser.exception.RedditParseException;
|
|
|
|
|
import com.sun.net.httpserver.Headers;
|
|
|
|
|
import com.sun.net.httpserver.HttpExchange;
|
|
|
|
|
import com.sun.net.httpserver.HttpHandler;
|
|
|
|
|
import org.json.JSONArray;
|
|
|
|
|
import org.json.JSONObject;
|
|
|
|
|
|
|
|
|
|
import java.io.IOException;
|
|
|
|
|
import java.io.InputStream;
|
|
|
|
@ -15,20 +18,44 @@ class CommunityHandler implements HttpHandler {
|
|
|
|
|
public CommunityHandler(RedditAPI redditClient) {
|
|
|
|
|
this.api = redditClient;
|
|
|
|
|
}
|
|
|
|
|
private JSONObject subToJSON(Submission sub){
|
|
|
|
|
JSONObject subJSON = new JSONObject();
|
|
|
|
|
subJSON.put("title", sub.getTitle());
|
|
|
|
|
subJSON.put("text", sub.getSelftext());
|
|
|
|
|
subJSON.put("author", sub.getAuthor());
|
|
|
|
|
subJSON.put("subreddit", sub.getSubreddit());
|
|
|
|
|
subJSON.put("time", sub.getCreatedUTC());
|
|
|
|
|
subJSON.put("score", sub.getScore());
|
|
|
|
|
subJSON.put("downvotes", sub.getDownVotes());
|
|
|
|
|
subJSON.put("nsfw", sub.isNSFW());
|
|
|
|
|
subJSON.put("url", sub.getURL());
|
|
|
|
|
subJSON.put("permalink", sub.getPermalink());
|
|
|
|
|
return subJSON;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@Override
|
|
|
|
|
public void handle(HttpExchange t) throws IOException {
|
|
|
|
|
//InputStream is = t.getRequestBody();
|
|
|
|
|
//is.read();
|
|
|
|
|
System.out.println("request at > "+t.getRequestURI().toString());
|
|
|
|
|
String[] pathArray = t.getRequestURI().toString().split("/", -1);
|
|
|
|
|
|
|
|
|
|
List<Submission> submissions = null;
|
|
|
|
|
try {
|
|
|
|
|
submissions = this.api.getSub("ProgrammerHumor");
|
|
|
|
|
submissions = this.api.getSub(pathArray[4]);
|
|
|
|
|
} catch (RedditParseException e) {
|
|
|
|
|
e.printStackTrace();
|
|
|
|
|
}
|
|
|
|
|
assert submissions != null;
|
|
|
|
|
String response = submissions.get(0).getURL();
|
|
|
|
|
|
|
|
|
|
JSONArray subsJSON = new JSONArray();
|
|
|
|
|
submissions.forEach(sub -> {
|
|
|
|
|
subsJSON.put(subToJSON(sub));
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
String response = subsJSON.toString(0);
|
|
|
|
|
System.out.println("response > "+response);
|
|
|
|
|
Headers headers = t.getResponseHeaders();
|
|
|
|
|
headers.add("Content-Type", "application/json");
|
|
|
|
|
System.out.println(response.length());
|
|
|
|
|
t.sendResponseHeaders(200, response.length());
|
|
|
|
|
OutputStream os = t.getResponseBody();
|
|
|
|
|
os.write(response.getBytes());
|
|
|
|
|