Skip to content

Instantly share code, notes, and snippets.

@bristermitten
Last active April 7, 2019 14:18
Show Gist options
  • Save bristermitten/10e148a110f79b0b3bda637a805d4c72 to your computer and use it in GitHub Desktop.
Save bristermitten/10e148a110f79b0b3bda637a805d4c72 to your computer and use it in GitHub Desktop.
KnightzAPI Downloader
public class Downloader {
public static void downloadKnightzAPI(Plugin yourPlugin) {
try {
URL gitHubURL = new URL("https://api.github.com/repos/knightzmc/knightzapi/releases/latest");
HttpURLConnection connection = (HttpURLConnection) gitHubURL.openConnection();
connection.setRequestMethod("GET");
if (connection.getResponseCode() == 200) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String content = in.lines().collect(Collectors.joining());
in.close();
connection.disconnect();
JsonParser parser = new JsonParser();
JsonElement parsed = parser.parse(content);
String releaseURL = parsed.getAsJsonObject().get("url").getAsString() + "/knightzapi.jar";
URL release = new URL(releaseURL);
ReadableByteChannel releaseByteChannel = Channels.newChannel(release.openStream());
File knightzAPIFile = new File(yourPlugin.getDataFolder(), "knightzapi.jar");
//If it exists but has not been loaded assume it is corrupt
if (knightzAPIFile.exists()) {
knightzAPIFile.delete();
}
FileOutputStream outputKA = new FileOutputStream(knightzAPIFile);
FileChannel channel = outputKA.getChannel();
channel.transferFrom(releaseByteChannel, 0, Long.MAX_VALUE);
Logger logger = yourPlugin.getLogger();
logger.info("----------------------------------------------------------------");
logger.info("KnightzAPI successfully downloaded! You should restart your server to enable the plugin.");
logger.info("/reload or plugin managers are not supported in this context.");
logger.info(yourPlugin.getName() + " will not be enabled until the server is reloaded");
logger.info("----------------------------------------------------------------");
} else {
throw new RuntimeException(yourPlugin.getName() + " failed to download KnightzAPI! GitHub returned code " + connection.getResponseCode());
}
} catch (IOException e) {
throw new RuntimeException(yourPlugin.getName() + " failed to download KnightzAPI! Reason: " + e.getMessage());
}
}
}
//call this when you want to get the API
if (getServer().getPluginManager().getPlugin("KnightzAPI") == null) {
getLogger().warning("KnightzAPI not found - downloading now!");
Downloader.downloadKnightzAPI(this);
getPluginLoader().disablePlugin(this);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment