You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
2.2 KiB
Java

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;
import java.io.OutputStream;
import java.util.List;
class CommunityHandler implements HttpHandler {
RedditAPI api;
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 {
System.out.println("request at > "+t.getRequestURI().toString());
String[] pathArray = t.getRequestURI().toString().split("/", -1);
List<Submission> submissions = null;
try {
submissions = this.api.getSub(pathArray[4]);
} catch (RedditParseException e) {
e.printStackTrace();
}
assert submissions != null;
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());
os.close();
}
}