package me.mrCookieSlime.Slimefun.GitHub; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.HashSet; import java.util.Set; import com.google.gson.JsonElement; import com.google.gson.JsonParser; public abstract class GitHubConnector { public static Set connectors = new HashSet(); private File file; public GitHubConnector() { this.file = new File("plugins/Slimefun/cache/github/" + this.getFileName() + ".json"); this.pullFile(); connectors.add(this); } public abstract String getFileName(); public abstract String getRepository(); public abstract String getURLSuffix(); public abstract void onSuccess(JsonElement element); public abstract void onFailure(); public void pullFile() { System.out.println("[Slimefun - GitHub] Downloading '" + this.getFileName() + ".json' from GitHub..."); try { URL website = new URL("https://api.github.com/repos/" + this.getRepository() + this.getURLSuffix()); ReadableByteChannel rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(file); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); System.out.println("[Slimefun - GitHub] Finished download: '" + this.getFileName() + ".json'"); this.parseData(); } catch (IOException e) { System.err.println("[Slimefun - GitHub] ERROR - Could not connect to GitHub in time."); if (hasData()) { this.parseData(); } else { this.onFailure(); } } } public boolean hasData() { return this.getFile().exists(); } public File getFile() { return this.file; } public void parseData() { try { BufferedReader reader = new BufferedReader(new FileReader(this.getFile())); String full = ""; String line; while ((line = reader.readLine()) != null) { full = full + line; } reader.close(); JsonElement element = new JsonParser().parse(full); this.onSuccess(element); } catch (IOException e) { e.printStackTrace(); this.onFailure(); } } }