From 4854166383d80af5967fa534f862913a07e15e68 Mon Sep 17 00:00:00 2001 From: adb Date: Wed, 27 Jan 2021 19:10:38 +0100 Subject: [PATCH] edit CommunityHandler return all results as JSON --- build.gradle | 4 +-- .../CommunityHandler.java | 35 ++++++++++++++++--- 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/build.gradle b/build.gradle index 19269fe..7e2bfef 100644 --- a/build.gradle +++ b/build.gradle @@ -3,8 +3,8 @@ plugins { id 'maven' } -sourceCompatibility = 1.7 -targetCompatibility = 1.7 +sourceCompatibility = 1.8 +targetCompatibility = 1.8 configurations.all { } diff --git a/src/main/java/sh/adb/RandomRedditMemesAPI/CommunityHandler.java b/src/main/java/sh/adb/RandomRedditMemesAPI/CommunityHandler.java index 60d4f95..0e36819 100644 --- a/src/main/java/sh/adb/RandomRedditMemesAPI/CommunityHandler.java +++ b/src/main/java/sh/adb/RandomRedditMemesAPI/CommunityHandler.java @@ -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 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());