1
mirror of https://github.com/StarWishsama/Slimefun4.git synced 2024-09-21 04:05:48 +00:00
Slimefun4/src/me/mrCookieSlime/Slimefun/GitHub/GitHubConnector.java

100 lines
2.6 KiB
Java
Raw Normal View History

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;
2017-01-16 19:31:57 +00:00
import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
2017-01-16 15:28:41 +00:00
import java.util.HashSet;
import java.util.Set;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
2017-01-18 11:14:01 +00:00
public abstract class GitHubConnector implements Runnable {
2017-01-16 15:28:41 +00:00
public static Set<GitHubConnector> connectors = new HashSet<GitHubConnector>();
private File file;
public GitHubConnector() {
2017-01-16 15:28:41 +00:00
this.file = new File("plugins/Slimefun/cache/github/" + this.getFileName() + ".json");
connectors.add(this);
}
2017-01-16 15:28:41 +00:00
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() {
2017-01-16 15:28:41 +00:00
System.out.println("[Slimefun - GitHub] Downloading '" + this.getFileName() + ".json' from GitHub...");
try {
2017-01-16 15:28:41 +00:00
URL website = new URL("https://api.github.com/repos/" + this.getRepository() + this.getURLSuffix());
2017-01-16 19:31:57 +00:00
URLConnection connection = website.openConnection();
connection.setConnectTimeout(3000);
connection.addRequestProperty("User-Agent", "Slimefun 4 GitHub Agent (by TheBusyBiscuit)");
connection.setDoOutput(true);
ReadableByteChannel rbc = Channels.newChannel(connection.getInputStream());
FileOutputStream fos = new FileOutputStream(file);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
2017-01-16 15:28:41 +00:00
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.");
2017-01-16 15:28:41 +00:00
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);
2017-01-16 15:28:41 +00:00
this.onSuccess(element);
}
catch (IOException e) {
e.printStackTrace();
2017-01-16 15:28:41 +00:00
this.onFailure();
}
}
2017-01-18 11:14:01 +00:00
@Override
public void run() {
this.pullFile();
}
}