Fix formatting of the new Updater

This commit is contained in:
TfT_02 2013-09-15 19:40:09 +02:00
parent f6e60bebcc
commit ec6419f0ff

View File

@ -6,32 +6,37 @@
package net.h31ix.updater; package net.h31ix.updater;
import java.io.*; import javax.xml.stream.XMLEventReader;
import java.lang.IllegalThreadStateException; import javax.xml.stream.XMLInputFactory;
import java.lang.Runnable; import javax.xml.stream.XMLStreamException;
import java.lang.Thread; import javax.xml.stream.events.XMLEvent;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipFile; import java.util.zip.ZipFile;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
/** /**
* Check dev.bukkit.org to find updates for a given plugin, and download the updates if needed. * Check dev.bukkit.org to find updates for a given plugin, and download the updates if needed.
* <p> * <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. * <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> * <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>. * 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> * <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. * 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> * <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. * 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> * <br>
* If you are unsure about these rules, please read the plugin submission guidelines: http://goo.gl/8iU5l * If you are unsure about these rules, please read the plugin submission guidelines: http://goo.gl/8iU5l
@ -39,8 +44,7 @@ import org.bukkit.plugin.Plugin;
* @author H31IX * @author H31IX
*/ */
public class Updater public class Updater {
{
private Plugin plugin; private Plugin plugin;
private UpdateType type; private UpdateType type;
private String versionTitle; private String versionTitle;
@ -66,8 +70,7 @@ public class Updater
/** /**
* Gives the dev the result of the update process. Can be obtained by called getResult(). * Gives the dev the result of the update process. Can be obtained by called getResult().
*/ */
public enum UpdateResult public enum UpdateResult {
{
/** /**
* The updater found an update, and has readied it to be loaded the next time the server restarts/reloads. * The updater found an update, and has readied it to be loaded the next time the server restarts/reloads.
*/ */
@ -101,8 +104,7 @@ public class Updater
/** /**
* Allows the dev to specify the type of update that will be run. * Allows the dev to specify the type of update that will be run.
*/ */
public enum UpdateType public enum UpdateType {
{
/** /**
* Run a version check, and then if the file is out of date, download the newest version. * Run a version check, and then if the file is out of date, download the newest version.
*/ */
@ -120,30 +122,22 @@ public class Updater
/** /**
* Initialize the updater * Initialize the updater
* *
* @param plugin * @param plugin The plugin that is checking for an update.
* The plugin that is checking for an update. * @param slug The dev.bukkit.org slug of the project (http://dev.bukkit.org/server-mods/SLUG_IS_HERE)
* @param slug * @param file The file that the plugin is running from, get this by doing this.getFile() from within your main class.
* The dev.bukkit.org slug of the project (http://dev.bukkit.org/server-mods/SLUG_IS_HERE) * @param type Specify the type of update this will be. See {@link UpdateType}
* @param file * @param announce True if the program should announce the progress of new updates in console
* 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 Updater(Plugin plugin, String slug, File file, UpdateType type, boolean announce) public Updater(Plugin plugin, String slug, File file, UpdateType type, boolean announce) {
{
this.plugin = plugin; this.plugin = plugin;
this.type = type; this.type = type;
this.announce = announce; this.announce = announce;
this.file = file; this.file = file;
try try {
{
// Obtain the results of the project's file feed // Obtain the results of the project's file feed
url = new URL(DBOUrl + slug + "/files.rss"); url = new URL(DBOUrl + slug + "/files.rss");
} }
catch (MalformedURLException ex) catch (MalformedURLException ex) {
{
// Invalid slug // Invalid slug
plugin.getLogger().warning("The author of this plugin (" + plugin.getDescription().getAuthors().get(0) + ") has misconfigured their Auto Update system"); plugin.getLogger().warning("The author of this plugin (" + plugin.getDescription().getAuthors().get(0) + ") has misconfigured their Auto Update system");
plugin.getLogger().warning("The project slug given ('" + slug + "') is invalid. Please nag the author about this."); plugin.getLogger().warning("The project slug given ('" + slug + "') is invalid. Please nag the author about this.");
@ -156,8 +150,7 @@ public class Updater
/** /**
* Get the result of the update process. * Get the result of the update process.
*/ */
public Updater.UpdateResult getResult() public Updater.UpdateResult getResult() {
{
waitForThread(); waitForThread();
return result; return result;
} }
@ -165,8 +158,7 @@ public class Updater
/** /**
* Get the total bytes of the file (can only be used after running a version check or a normal run). * Get the total bytes of the file (can only be used after running a version check or a normal run).
*/ */
public long getFileSize() public long getFileSize() {
{
waitForThread(); waitForThread();
return totalSize; return totalSize;
} }
@ -174,8 +166,7 @@ public class Updater
/** /**
* Get the version string latest file avaliable online. * Get the version string latest file avaliable online.
*/ */
public String getLatestVersionString() public String getLatestVersionString() {
{
waitForThread(); waitForThread();
return versionTitle; return versionTitle;
} }
@ -188,7 +179,8 @@ public class Updater
if (thread.isAlive()) { if (thread.isAlive()) {
try { try {
thread.join(); thread.join();
} catch (InterruptedException e) { }
catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -197,16 +189,13 @@ public class Updater
/** /**
* Save an update from dev.bukkit.org into the server's update folder. * Save an update from dev.bukkit.org into the server's update folder.
*/ */
private void saveFile(File folder, String file, String u) private void saveFile(File folder, String file, String u) {
{ if (!folder.exists()) {
if(!folder.exists())
{
folder.mkdir(); folder.mkdir();
} }
BufferedInputStream in = null; BufferedInputStream in = null;
FileOutputStream fout = null; FileOutputStream fout = null;
try try {
{
// Download the file // Download the file
URL url = new URL(u); URL url = new URL(u);
int fileLength = url.openConnection().getContentLength(); int fileLength = url.openConnection().getContentLength();
@ -215,55 +204,48 @@ public class Updater
byte[] data = new byte[BYTE_SIZE]; byte[] data = new byte[BYTE_SIZE];
int count; int count;
if(announce) plugin.getLogger().info("About to download a new update: " + versionTitle); if (announce) {
plugin.getLogger().info("About to download a new update: " + versionTitle);
}
long downloaded = 0; long downloaded = 0;
while ((count = in.read(data, 0, BYTE_SIZE)) != -1) while ((count = in.read(data, 0, BYTE_SIZE)) != -1) {
{
downloaded += count; downloaded += count;
fout.write(data, 0, count); fout.write(data, 0, count);
int percent = (int) (downloaded * 100 / fileLength); int percent = (int) (downloaded * 100 / fileLength);
if(announce & (percent % 10 == 0)) if (announce & (percent % 10 == 0)) {
{
plugin.getLogger().info("Downloading update: " + percent + "% of " + fileLength + " bytes."); plugin.getLogger().info("Downloading update: " + percent + "% of " + fileLength + " bytes.");
} }
} }
//Just a quick check to make sure we didn't leave any files from last time... //Just a quick check to make sure we didn't leave any files from last time...
for(File xFile : new File("plugins/" + updateFolder).listFiles()) for (File xFile : new File("plugins/" + updateFolder).listFiles()) {
{ if (xFile.getName().endsWith(".zip")) {
if(xFile.getName().endsWith(".zip"))
{
xFile.delete(); xFile.delete();
} }
} }
// Check to see if it's a zip file, if it is, unzip it. // Check to see if it's a zip file, if it is, unzip it.
File dFile = new File(folder.getAbsolutePath() + "/" + file); File dFile = new File(folder.getAbsolutePath() + "/" + file);
if(dFile.getName().endsWith(".zip")) if (dFile.getName().endsWith(".zip")) {
{
// Unzip // Unzip
unzip(dFile.getCanonicalPath()); unzip(dFile.getCanonicalPath());
} }
if(announce) plugin.getLogger().info("Finished updating."); if (announce) {
plugin.getLogger().info("Finished updating.");
} }
catch (Exception ex) }
{ catch (Exception ex) {
plugin.getLogger().warning("The auto-updater tried to download a new update, but was unsuccessful."); plugin.getLogger().warning("The auto-updater tried to download a new update, but was unsuccessful.");
result = Updater.UpdateResult.FAIL_DOWNLOAD; result = Updater.UpdateResult.FAIL_DOWNLOAD;
} }
finally finally {
{ try {
try if (in != null) {
{
if (in != null)
{
in.close(); in.close();
} }
if (fout != null) if (fout != null) {
{
fout.close(); fout.close();
} }
} }
catch (Exception ex) catch (Exception ex) {
{
} }
} }
} }
@ -271,40 +253,33 @@ public class Updater
/** /**
* Part of Zip-File-Extractor, modified by H31IX for use with Bukkit * Part of Zip-File-Extractor, modified by H31IX for use with Bukkit
*/ */
private void unzip(String file) private void unzip(String file) {
{ try {
try
{
File fSourceZip = new File(file); File fSourceZip = new File(file);
String zipPath = file.substring(0, file.length() - 4); String zipPath = file.substring(0, file.length() - 4);
ZipFile zipFile = new ZipFile(fSourceZip); ZipFile zipFile = new ZipFile(fSourceZip);
Enumeration<? extends ZipEntry> e = zipFile.entries(); Enumeration<? extends ZipEntry> e = zipFile.entries();
while(e.hasMoreElements()) while (e.hasMoreElements()) {
{
ZipEntry entry = (ZipEntry) e.nextElement(); ZipEntry entry = (ZipEntry) e.nextElement();
File destinationFilePath = new File(zipPath, entry.getName()); File destinationFilePath = new File(zipPath, entry.getName());
destinationFilePath.getParentFile().mkdirs(); destinationFilePath.getParentFile().mkdirs();
if(entry.isDirectory()) if (entry.isDirectory()) {
{
continue; continue;
} }
else else {
{
BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
int b; int b;
byte buffer[] = new byte[BYTE_SIZE]; byte buffer[] = new byte[BYTE_SIZE];
FileOutputStream fos = new FileOutputStream(destinationFilePath); FileOutputStream fos = new FileOutputStream(destinationFilePath);
BufferedOutputStream bos = new BufferedOutputStream(fos, BYTE_SIZE); BufferedOutputStream bos = new BufferedOutputStream(fos, BYTE_SIZE);
while((b = bis.read(buffer, 0, BYTE_SIZE)) != -1) while ((b = bis.read(buffer, 0, BYTE_SIZE)) != -1) {
{
bos.write(buffer, 0, b); bos.write(buffer, 0, b);
} }
bos.flush(); bos.flush();
bos.close(); bos.close();
bis.close(); bis.close();
String name = destinationFilePath.getName(); String name = destinationFilePath.getName();
if(name.endsWith(".jar") && pluginFile(name)) if (name.endsWith(".jar") && pluginFile(name)) {
{
destinationFilePath.renameTo(new File("plugins/" + updateFolder + "/" + name)); destinationFilePath.renameTo(new File("plugins/" + updateFolder + "/" + name));
} }
} }
@ -315,12 +290,9 @@ public class Updater
zipFile.close(); zipFile.close();
zipFile = null; zipFile = null;
// Move any plugin data folders that were included to the right place, Bukkit won't do this for us. // Move any plugin data folders that were included to the right place, Bukkit won't do this for us.
for(File dFile : new File(zipPath).listFiles()) for (File dFile : new File(zipPath).listFiles()) {
{ if (dFile.isDirectory()) {
if(dFile.isDirectory()) if (pluginFile(dFile.getName())) {
{
if(pluginFile(dFile.getName()))
{
File oFile = new File("plugins/" + dFile.getName()); // Get current dir File oFile = new File("plugins/" + dFile.getName()); // Get current dir
File[] contents = oFile.listFiles(); // List of existing files in the current dir File[] contents = oFile.listFiles(); // List of existing files in the current dir
for (File cFile : dFile.listFiles()) // Loop through all the files in the new dir for (File cFile : dFile.listFiles()) // Loop through all the files in the new dir
@ -328,19 +300,16 @@ public class Updater
boolean found = false; boolean found = false;
for (File xFile : contents) // Loop through contents to see if it exists for (File xFile : contents) // Loop through contents to see if it exists
{ {
if(xFile.getName().equals(cFile.getName())) if (xFile.getName().equals(cFile.getName())) {
{
found = true; found = true;
break; break;
} }
} }
if(!found) if (!found) {
{
// Move the new file into the current dir // Move the new file into the current dir
cFile.renameTo(new File(oFile.getCanonicalFile() + "/" + cFile.getName())); cFile.renameTo(new File(oFile.getCanonicalFile() + "/" + cFile.getName()));
} }
else else {
{
// This file already exists, so we don't need it anymore. // This file already exists, so we don't need it anymore.
cFile.delete(); cFile.delete();
} }
@ -352,8 +321,7 @@ public class Updater
new File(zipPath).delete(); new File(zipPath).delete();
fSourceZip.delete(); fSourceZip.delete();
} }
catch(IOException ex) catch (IOException ex) {
{
ex.printStackTrace(); ex.printStackTrace();
plugin.getLogger().warning("The auto-updater tried to unzip a new update file, but was unsuccessful."); plugin.getLogger().warning("The auto-updater tried to unzip a new update file, but was unsuccessful.");
result = Updater.UpdateResult.FAIL_DOWNLOAD; result = Updater.UpdateResult.FAIL_DOWNLOAD;
@ -364,12 +332,9 @@ public class Updater
/** /**
* Check if the name of a jar is one of the plugins currently installed, used for extracting the correct files out of a zip. * Check if the name of a jar is one of the plugins currently installed, used for extracting the correct files out of a zip.
*/ */
public boolean pluginFile(String name) public boolean pluginFile(String name) {
{ for (File file : new File("plugins").listFiles()) {
for(File file : new File("plugins").listFiles()) if (file.getName().equals(name)) {
{
if(file.getName().equals(name))
{
return true; return true;
} }
} }
@ -379,11 +344,9 @@ public class Updater
/** /**
* Obtain the direct download file url from the file's page. * Obtain the direct download file url from the file's page.
*/ */
private String getFile(String link) private String getFile(String link) {
{
String download = null; String download = null;
try try {
{
// Open a connection to the page // Open a connection to the page
URL url = new URL(link); URL url = new URL(link);
URLConnection urlConn = url.openConnection(); URLConnection urlConn = url.openConnection();
@ -392,22 +355,18 @@ public class Updater
int counter = 0; int counter = 0;
String line; String line;
while((line = buff.readLine()) != null) while ((line = buff.readLine()) != null) {
{
counter++; counter++;
// Search for the download link // Search for the download link
if(line.contains("<li class=\"user-action user-action-download\">")) if (line.contains("<li class=\"user-action user-action-download\">")) {
{
// Get the raw link // Get the raw link
download = line.split("<a href=\"")[1].split("\">Download</a>")[0]; download = line.split("<a href=\"")[1].split("\">Download</a>")[0];
} }
// Search for size // Search for size
else if (line.contains("<dt>Size</dt>")) else if (line.contains("<dt>Size</dt>")) {
{
sizeLine = counter + 1; sizeLine = counter + 1;
} }
else if(counter == sizeLine) else if (counter == sizeLine) {
{
String size = line.replaceAll("<dd>", "").replaceAll("</dd>", ""); String size = line.replaceAll("<dd>", "").replaceAll("</dd>", "");
multiplier = size.contains("MiB") ? 1048576 : 1024; multiplier = size.contains("MiB") ? 1048576 : 1024;
size = size.replace(" KiB", "").replace(" MiB", ""); size = size.replace(" KiB", "").replace(" MiB", "");
@ -419,8 +378,7 @@ public class Updater
buff.close(); buff.close();
buff = null; buff = null;
} }
catch (Exception ex) catch (Exception ex) {
{
ex.printStackTrace(); ex.printStackTrace();
plugin.getLogger().warning("The auto-updater tried to contact dev.bukkit.org, but was unsuccessful."); plugin.getLogger().warning("The auto-updater tried to contact dev.bukkit.org, but was unsuccessful.");
result = Updater.UpdateResult.FAIL_DBO; result = Updater.UpdateResult.FAIL_DBO;
@ -432,10 +390,8 @@ public class Updater
/** /**
* Check to see if the program should continue by evaluation whether the plugin is already updated, or shouldn't be updated * Check to see if the program should continue by evaluation whether the plugin is already updated, or shouldn't be updated
*/ */
private boolean versionCheck(String title) private boolean versionCheck(String title) {
{ if (type != UpdateType.NO_VERSION_CHECK) {
if(type != UpdateType.NO_VERSION_CHECK)
{
String version = plugin.getDescription().getVersion(); String version = plugin.getDescription().getVersion();
title = title.substring(6); title = title.substring(6);
@ -488,16 +444,12 @@ public class Updater
/** /**
* Used to calculate the version string as an Integer * Used to calculate the version string as an Integer
*/ */
private Integer calVer(String s) throws NumberFormatException private Integer calVer(String s) throws NumberFormatException {
{ if (s.contains(".")) {
if(s.contains("."))
{
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (int i = 0; i <s.length(); i++) for (int i = 0; i < s.length(); i++) {
{
Character c = s.charAt(i); Character c = s.charAt(i);
if (Character.isLetterOrDigit(c)) if (Character.isLetterOrDigit(c)) {
{
sb.append(c); sb.append(c);
} }
} }
@ -505,15 +457,13 @@ public class Updater
} }
return Integer.parseInt(s); return Integer.parseInt(s);
} }
/** /**
* Evaluate whether the version number is marked showing that it should not be updated by this program * Evaluate whether the version number is marked showing that it should not be updated by this program
*/ */
private boolean hasTag(String version) private boolean hasTag(String version) {
{ for (String string : noUpdateTag) {
for(String string : noUpdateTag) if (version.contains(string)) {
{
if(version.contains(string))
{
return true; return true;
} }
} }
@ -523,10 +473,8 @@ public class Updater
/** /**
* Part of RSS Reader by Vogella, modified by H31IX for use with Bukkit * Part of RSS Reader by Vogella, modified by H31IX for use with Bukkit
*/ */
private boolean readFeed() private boolean readFeed() {
{ try {
try
{
// Set header values intial to the empty string // Set header values intial to the empty string
String title = ""; String title = "";
String link = ""; String link = "";
@ -534,32 +482,25 @@ public class Updater
XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLInputFactory inputFactory = XMLInputFactory.newInstance();
// Setup a new eventReader // Setup a new eventReader
InputStream in = read(); InputStream in = read();
if(in != null) if (in != null) {
{
XMLEventReader eventReader = inputFactory.createXMLEventReader(in); XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
// Read the XML document // Read the XML document
while (eventReader.hasNext()) while (eventReader.hasNext()) {
{
XMLEvent event = eventReader.nextEvent(); XMLEvent event = eventReader.nextEvent();
if (event.isStartElement()) if (event.isStartElement()) {
{ if (event.asStartElement().getName().getLocalPart().equals(TITLE)) {
if (event.asStartElement().getName().getLocalPart().equals(TITLE))
{
event = eventReader.nextEvent(); event = eventReader.nextEvent();
title = event.asCharacters().getData(); title = event.asCharacters().getData();
continue; continue;
} }
if (event.asStartElement().getName().getLocalPart().equals(LINK)) if (event.asStartElement().getName().getLocalPart().equals(LINK)) {
{
event = eventReader.nextEvent(); event = eventReader.nextEvent();
link = event.asCharacters().getData(); link = event.asCharacters().getData();
continue; continue;
} }
} }
else if (event.isEndElement()) else if (event.isEndElement()) {
{ if (event.asEndElement().getName().getLocalPart().equals(ITEM)) {
if (event.asEndElement().getName().getLocalPart().equals(ITEM))
{
// Store the title and link of the first entry we get - the first file on the list is all we need // Store the title and link of the first entry we get - the first file on the list is all we need
versionTitle = title; versionTitle = title;
versionLink = link; versionLink = link;
@ -570,13 +511,11 @@ public class Updater
} }
return true; return true;
} }
else else {
{
return false; return false;
} }
} }
catch (XMLStreamException e) catch (XMLStreamException e) {
{
plugin.getLogger().warning("Could not reach dev.bukkit.org for update checking. Is it offline?"); plugin.getLogger().warning("Could not reach dev.bukkit.org for update checking. Is it offline?");
return false; return false;
} }
@ -585,14 +524,11 @@ public class Updater
/** /**
* Open the RSS feed * Open the RSS feed
*/ */
private InputStream read() private InputStream read() {
{ try {
try
{
return url.openStream(); return url.openStream();
} }
catch (IOException e) catch (IOException e) {
{
plugin.getLogger().warning("Could not reach BukkitDev file stream for update checking. Is dev.bukkit.org offline?"); plugin.getLogger().warning("Could not reach BukkitDev file stream for update checking. Is dev.bukkit.org offline?");
return null; return null;
} }
@ -601,27 +537,21 @@ public class Updater
private class UpdateRunnable implements Runnable { private class UpdateRunnable implements Runnable {
public void run() { public void run() {
if(url != null) if (url != null) {
{
// Obtain the results of the project's file feed // Obtain the results of the project's file feed
if(readFeed()) if (readFeed()) {
{ if (versionCheck(versionTitle)) {
if(versionCheck(versionTitle))
{
String fileLink = getFile(versionLink); String fileLink = getFile(versionLink);
if(fileLink != null && type != UpdateType.NO_DOWNLOAD) if (fileLink != null && type != UpdateType.NO_DOWNLOAD) {
{
String name = file.getName(); String name = file.getName();
// If it's a zip file, it shouldn't be downloaded as the plugin's name // If it's a zip file, it shouldn't be downloaded as the plugin's name
if(fileLink.endsWith(".zip")) if (fileLink.endsWith(".zip")) {
{
String[] split = fileLink.split("/"); String[] split = fileLink.split("/");
name = split[split.length - 1]; name = split[split.length - 1];
} }
saveFile(new File("plugins/" + updateFolder), name, fileLink); saveFile(new File("plugins/" + updateFolder), name, fileLink);
} }
else else {
{
result = UpdateResult.UPDATE_AVAILABLE; result = UpdateResult.UPDATE_AVAILABLE;
} }
} }