Java tutorial
/* * This file is part of UltimateCore, licensed under the MIT License (MIT). * * Copyright (c) Bammerbom * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package bammerbom.ultimatecore.bukkit; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Enumeration; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.bukkit.ChatColor; import org.bukkit.plugin.Plugin; import org.json.simple.JSONArray; import org.json.simple.JSONValue; /** * Check for updates on BukkitDev for a given plugin, and download the updates * if needed. * <p/> * <b>VERY, VERY IMPORTANT</b>: Because there are no standards for adding * auto-update toggles in your plugin's config, this system provides NO CHECK * WITH YOUR CONFIG to make sure the user has allowed auto-updating. * <br> * It is a <b>BUKKIT POLICY</b> that you include a boolean value in your config * that prevents the auto-updater from running <b>AT ALL</b>. * <br> * If you fail to include this option in your config, your plugin will be * <b>REJECTED</b> when you attempt to submit it to dev.bukkit.org. * <p/> * An example of a good configuration option would be something similar to * 'auto-update: true' - if this value is set to false you may NOT run the * auto-updater. * <br> * If you are unsure about these rules, please read the plugin submission * guidelines: http://goo.gl/8iU5l * * @author Gravity * @version 2.2 */ public class UltimateUpdater { /* Constants */ // Remote file's title private static final String TITLE_VALUE = "name"; // Remote file's download link private static final String LINK_VALUE = "downloadUrl"; // Remote file's release type private static final String TYPE_VALUE = "releaseType"; // Remote file's build version private static final String VERSION_VALUE = "gameVersion"; // Path to GET private static final String QUERY = "/servermods/files?projectIds="; // Slugs will be appended to this to get to the project's RSS feed private static final String HOST = "https://api.curseforge.com"; // User-agent when querying Curse private static final String USER_AGENT = "Updater (by Gravity)"; // Used for locating version numbers in file names private static final String DELIMETER = "^v|[\\s_-]v"; // If the version number contains one of these, don't update. private static final String[] NO_UPDATE_TAG = { "-DEV", "-PRE", "-SNAPSHOT" }; // Used for downloading files private static final int BYTE_SIZE = 1024; /* User-provided variables */ // Plugin running Updater private static Plugin plugin; private static String versionName; // Updater thread private static Thread thread; // Type of update check to run private final UpdateType type; // Whether to announce file downloads private final boolean announce; /* Collected from Curse API */ // The plugin file (jar) private final File file; // The folder that downloads will be placed in private final File updateFolder; private String versionLink; private String versionType; /* Update process variables */ private String versionGameVersion; // Connection to RSS private URL url; // Used for determining the outcome of the update process private UltimateUpdater.UpdateResult result = UltimateUpdater.UpdateResult.SUCCESS; /** * Initialize the updater. * * @param plugin The plugin that is checking for an update. * @param id The dev.bukkit.org id of the project. * @param file The file that the plugin is running from, get this by doing * this.getFile() from within your main class. * @param type Specify the type of update this will be. See * {@link UpdateType} * @param announce True if the program should announce the progress of new * updates in console. */ public UltimateUpdater(Plugin plugin, int id, File file, UpdateType type, boolean announce) { UltimateUpdater.plugin = plugin; this.type = type; this.announce = announce; this.file = file; this.updateFolder = new File(plugin.getDataFolder().getParent(), plugin.getServer().getUpdateFolder()); try { this.url = new URL(UltimateUpdater.HOST + UltimateUpdater.QUERY + id); } catch (final MalformedURLException e) { this.result = UpdateResult.FAIL_BADID; } UltimateUpdater.thread = new Thread(new UpdateRunnable()); thread.setName("UltimateCore Updater"); UltimateUpdater.thread.start(); } /** * Get the result of the update process. * * @return result of the update process. * @see UpdateResult */ public UltimateUpdater.UpdateResult getResult() { waitForThread(); return this.result; } /** * Get the latest version's release type. * * @return latest version's release type. * @see ReleaseType */ public ReleaseType getLatestType() { waitForThread(); if (this.versionType != null) { for (ReleaseType type : ReleaseType.values()) { if (this.versionType.equalsIgnoreCase(type.name())) { return type; } } } return null; } /** * Get the latest version's game version (such as "CB 1.2.5-R1.0"). * * @return latest version's game version. */ public String getLatestGameVersion() { waitForThread(); return this.versionGameVersion; } /** * Get the latest version's name (such as "Project v1.0"). * * @return latest version's name. */ public String getLatestName() { waitForThread(); return versionName; } /** * Get the latest version's direct file link. * * @return latest version's file link. */ public String getLatestFileLink() { waitForThread(); return this.versionLink; } public String getLatestUpdate() { if (thread != null && thread.isAlive()) { return ""; } String versionName = getLatestName(); if (versionName == null || versionName.equalsIgnoreCase("")) { return ""; } final String remoteVersion = versionName.split(DELIMETER)[1].split(" ")[0]; return remoteVersion; } /** * As the result of Updater output depends on the thread's completion, it is * necessary to wait for the thread to finish before allowing anyone to * check the result. */ public void waitForThread() { if ((thread != null) && thread.isAlive()) { try { thread.join(); } catch (final InterruptedException e) { } } } /** * Save an update from dev.bukkit.org into the server's update folder. * * @param folder the updates folder location. * @param file the name of the file to save it as. * @param link the url of the file. */ private void saveFile(File folder, String file, String link) { deleteOldFiles(); if (!folder.exists()) { folder.mkdir(); } downloadFile(link, folder); // Check to see if it's a zip file, if it is, unzip it. final File dFile = new File(folder.getAbsolutePath() + File.separator + file); if (dFile.getName().endsWith(".zip")) { // Unzip this.unzip(dFile.getAbsolutePath()); } if (this.announce) { r.log("Update completed."); r.log(ChatColor.GREEN + "Reload/Restart the server to activate the update."); } } /** * Download a file and save it to the specified folder. * * @param link link to file. * @param folder folder to save file to. */ private void downloadFile(String link, File folder) { BufferedInputStream in = null; FileOutputStream fout = null; try { URL fileUrl = new URL(link); final int fileLength = fileUrl.openConnection().getContentLength(); in = new BufferedInputStream(fileUrl.openStream()); fout = new FileOutputStream(folder.getAbsolutePath() + File.separator + file.getName()); final byte[] data = new byte[UltimateUpdater.BYTE_SIZE]; int count; r.log("Downloading new update: " + versionName); long downloaded = 0; int lastpercent = 0; while ((count = in.read(data, 0, UltimateUpdater.BYTE_SIZE)) != -1) { downloaded += count; fout.write(data, 0, count); final int percent = (int) ((downloaded * 100) / fileLength); if (this.announce && ((percent % 20) == 0) && !(lastpercent == percent)) { lastpercent = percent; r.log("Downloading new update... (" + percent + "%)"); } } } catch (Exception ex) { r.log("Failed to download new update. " + (ex.getCause() != null ? "(" + ex.getCause() + ")" : "")); this.result = UltimateUpdater.UpdateResult.FAIL_DOWNLOAD; } finally { try { if (in != null) { in.close(); } if (fout != null) { fout.close(); } } catch (final IOException ex) { } } } /** * Remove possibly leftover files from the update folder. */ private void deleteOldFiles() { //Just a quick check to make sure we didn't leave any files from last time... File[] list = listFilesOrError(updateFolder); for (final File xFile : list) { if (xFile.getName().endsWith(".zip")) { xFile.mkdir(); } } } /** * Part of Zip-File-Extractor, modified by Gravity for use with Updater. * * @param file the location of the file to extract. */ private void unzip(String file) { final File fSourceZip = new File(file); try { final String zipPath = file.substring(0, file.length() - 4); ZipFile zipFile = new ZipFile(fSourceZip); Enumeration<? extends ZipEntry> e = zipFile.entries(); while (e.hasMoreElements()) { ZipEntry entry = e.nextElement(); File destinationFilePath = new File(zipPath, entry.getName()); destinationFilePath.getParentFile().mkdirs(); if (!entry.isDirectory()) { final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); int b; final byte[] buffer = new byte[UltimateUpdater.BYTE_SIZE]; final FileOutputStream fos = new FileOutputStream(destinationFilePath); final BufferedOutputStream bos = new BufferedOutputStream(fos, UltimateUpdater.BYTE_SIZE); while ((b = bis.read(buffer, 0, UltimateUpdater.BYTE_SIZE)) != -1) { bos.write(buffer, 0, b); } bos.flush(); bos.close(); bis.close(); final String name = destinationFilePath.getName(); if (name.endsWith(".jar") && this.pluginExists(name)) { File output = new File(updateFolder, name); destinationFilePath.renameTo(output); } } } zipFile.close(); // Move any plugin data folders that were included to the right place, Bukkit won't do this for us. moveNewZipFiles(zipPath); } catch (final IOException e) { } finally { fSourceZip.delete(); } } /** * Find any new files extracted from an update into the plugin's data * directory. * * @param zipPath path of extracted files. */ private void moveNewZipFiles(String zipPath) { File[] list = listFilesOrError(new File(zipPath)); for (final File dFile : list) { if (dFile.isDirectory() && this.pluginExists(dFile.getName())) { // Current dir final File oFile = new File(UltimateUpdater.plugin.getDataFolder().getParent(), dFile.getName()); // List of existing files in the new dir final File[] dList = listFilesOrError(dFile); // List of existing files in the current dir final File[] oList = listFilesOrError(oFile); for (File cFile : dList) { // Loop through all the files in the new dir boolean found = false; for (final File xFile : oList) { // Loop through all the contents in the current dir to see if it exists if (xFile.getName().equals(cFile.getName())) { found = true; break; } } if (!found) { // Move the new file into the current dir File output = new File(oFile, cFile.getName()); cFile.renameTo(output); } else { // This file already exists, so we don't need it anymore. cFile.delete(); } } } dFile.delete(); } File zip = new File(zipPath); zip.delete(); } /** * Check if the name of a jar is one of the plugins currently installed, * used for extracting the correct files out of a zip. * * @param name a name to check for inside the plugins folder. * @return true if a file inside the plugins folder is named this. */ private boolean pluginExists(String name) { File[] plugins = listFilesOrError(new File("plugins")); for (final File file : plugins) { if (file.getName().equals(name)) { return true; } } return false; } /** * Check to see if the program should continue by evaluating whether the * plugin is already updated, or shouldn't be updated. * * @param title the plugin's title. * @return true if the version was located and is not the same as the * remote's newest. */ private boolean versionCheck(String title) { if (this.type != UpdateType.NO_VERSION_CHECK) { final String localVersion = UltimateUpdater.plugin.getDescription().getVersion(); if (title.split(DELIMETER).length == 2) { // Get the newest file's version number final String remoteVersion = title.split(DELIMETER)[1].split(" ")[0]; if (this.hasTag(localVersion) || !this.shouldUpdate(localVersion, remoteVersion)) { // We already have the latest version, or this build is tagged for no-update r.log("No update available."); this.result = UltimateUpdater.UpdateResult.NO_UPDATE; return false; } } else { // The file's name did not contain the string 'vVersion' this.result = UltimateUpdater.UpdateResult.FAIL_NOVERSION; return false; } } return true; } /** * <b>If you wish to run mathematical versioning checks, edit this * method.</b> * <p> * With default behavior, Updater will NOT verify that a remote version * available on BukkitDev which is not this version is indeed an "update". * If a version is present on BukkitDev that is not the version that is * currently running, Updater will assume that it is a newer version. This * is because there is no standard versioning scheme, and creating a * calculation that can determine whether a new update is actually an update * is sometimes extremely complicated. * </p> * <p> * Updater will call this method from {@link #versionCheck(String)} before * deciding whether the remote version is actually an update. If you have a * specific versioning scheme with which a mathematical determination can be * reliably made to decide whether one version is higher than another, you * may revise this method, using the local and remote version parameters, to * execute the appropriate check. * </p> * <p> * Returning a value of <b>false</b> will tell the update process that this * is NOT a new version. Without revision, this method will always consider * a remote version at all different from that of the local version a new * update. * </p> * * @param localVersion the current version * @param remoteVersion the remote version * @return true if Updater should consider the remote version an update, * false if not. */ public boolean shouldUpdate(String localVersion, String remoteVersion) { try { Integer l1 = Integer.parseInt(localVersion.split("\\.")[0]); Integer l2 = Integer.parseInt(localVersion.split("\\.")[1]); Integer l3; try { l3 = Integer.parseInt(localVersion.split("\\.")[2]); } catch (ArrayIndexOutOfBoundsException e) { l3 = 0; } Integer r1 = Integer.parseInt(remoteVersion.split("\\.")[0]); Integer r2 = Integer.parseInt(remoteVersion.split("\\.")[1]); Integer r3; try { r3 = Integer.parseInt(remoteVersion.split("\\.")[2]); } catch (ArrayIndexOutOfBoundsException e) { r3 = 0; } if (l1 < r1) { return true; } if (l2 < r2 && !(l1 > r1)) { return true; } return l3 < r3 && !(l2 > r2) && !(l1 > r1); } catch (Exception ex) { ex.printStackTrace(); return false; } } /** * Evaluate whether the version number is marked showing that it should not * be updated by this program. * * @param version a version number to check for tags in. * @return true if updating should be disabled. */ private boolean hasTag(String version) { for (final String string : UltimateUpdater.NO_UPDATE_TAG) { if (version.contains(string)) { return true; } } return false; } /** * Make a connection to the BukkitDev API and request the newest file's * details. * * @return true if successful. */ private boolean read() { try { final URLConnection conn = this.url.openConnection(); conn.setConnectTimeout(5000); conn.addRequestProperty("User-Agent", UltimateUpdater.USER_AGENT); conn.setDoOutput(true); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final String response = reader.readLine(); final JSONArray array = (JSONArray) JSONValue.parse(response); if (array.isEmpty()) { r.log("No updates found."); this.result = UpdateResult.FAIL_BADID; return false; } UltimateUpdater.versionName = (String) ((Map) array.get(array.size() - 1)) .get(UltimateUpdater.TITLE_VALUE); this.versionLink = (String) ((Map) array.get(array.size() - 1)).get(UltimateUpdater.LINK_VALUE); this.versionType = (String) ((Map) array.get(array.size() - 1)).get(UltimateUpdater.TYPE_VALUE); this.versionGameVersion = (String) ((Map) array.get(array.size() - 1)) .get(UltimateUpdater.VERSION_VALUE); return true; } catch (final IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { r.log("Invalid API key."); this.result = UpdateResult.FAIL_APIKEY; } else { r.log("Could not connect to bukkit.org, update check failed. " + (e.getCause() != null ? "(" + e.getCause() + ")" : "")); this.result = UpdateResult.FAIL_DBO; } return false; } } /** * Perform a file operation and log any errors if it fails. * * @param file file operation is performed on. * @param result result of file operation. * @param create true if a file is being created, false if deleted. */ private File[] listFilesOrError(File folder) { File[] contents = folder.listFiles(); if (contents == null) { return new File[0]; } else { return contents; } } /** * Gives the developer the result of the update process. Can be obtained by * called {@link #getResult()} */ public enum UpdateResult { /** * The updater found an update, and has readied it to be loaded the next * time the server restarts/reloads. */ SUCCESS, /** * The updater did not find an update, and nothing was downloaded. */ NO_UPDATE, /** * The server administrator has disabled the updating system. */ DISABLED, /** * The updater found an update, but was unable to download it. */ FAIL_DOWNLOAD, /** * For some reason, the updater was unable to contact dev.bukkit.org to * download the file. */ FAIL_DBO, /** * When running the version check, the file on DBO did not contain a * recognizable version. */ FAIL_NOVERSION, /** * The id provided by the plugin running the updater was invalid and * doesn't exist on DBO. */ FAIL_BADID, /** * The server administrator has improperly configured their API key in * the configuration. */ FAIL_APIKEY, /** * The updater found an update, but because of the UpdateType being set * to NO_DOWNLOAD, it wasn't downloaded. */ UPDATE_AVAILABLE } /** * Allows the developer to specify the type of update that will be run. */ public enum UpdateType { /** * Run a version check, and then if the file is out of date, download * the newest version. */ DEFAULT, /** * Don't run a version check, just find the latest update and download * it. */ NO_VERSION_CHECK, /** * Get information about the version and the download size, but don't * actually download anything. */ NO_DOWNLOAD } /** * Represents the various release types of a file on BukkitDev. */ public enum ReleaseType { /** * An "alpha" file. */ ALPHA, /** * A "beta" file. */ BETA, /** * A "release" file. */ RELEASE } private class UpdateRunnable implements Runnable { @Override public void run() { if (UltimateUpdater.this.url != null && (UltimateUpdater.this.read() && UltimateUpdater.this.versionCheck(UltimateUpdater.versionName))) { // Obtain the results of the project's file feed if ((UltimateUpdater.this.versionLink != null) && (UltimateUpdater.this.type != UpdateType.NO_DOWNLOAD)) { String name = UltimateUpdater.this.file.getName(); // If it's a zip file, it shouldn't be downloaded as the plugin's name if (UltimateUpdater.this.versionLink.endsWith(".zip")) { final String[] split = UltimateUpdater.this.versionLink.split("/"); name = split[split.length - 1]; } UltimateUpdater.this.saveFile(updateFolder, name, UltimateUpdater.this.versionLink); } else { UltimateUpdater.this.result = UpdateResult.UPDATE_AVAILABLE; } } } } }