Removing EssentialsUpdate from 2.9 branch.

Development may be continued in 3.x branch.
This commit is contained in:
KHobbits 2012-08-18 15:51:55 +01:00
parent 8a9353fd09
commit e42f7e4ffa
55 changed files with 0 additions and 8620 deletions

View File

@ -1,74 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- You may freely edit this file. See commented blocks below for -->
<!-- some examples of how to customize the build. -->
<!-- (If you delete it and reopen the project it will be recreated.) -->
<!-- By default, only the Clean and Build commands use this build script. -->
<!-- Commands such as Run, Debug, and Test only use this build script if -->
<!-- the Compile on Save feature is turned off for the project. -->
<!-- You can turn off the Compile on Save (or Deploy on Save) setting -->
<!-- in the project's Project Properties dialog box.-->
<project name="EssentialsUpdate" default="default" basedir=".">
<description>Builds, tests, and runs the project EssentialsUpdate.</description>
<import file="nbproject/build-impl.xml"/>
<!--
There exist several targets which are by default empty and which can be
used for execution of your tasks. These targets are usually executed
before and after some main targets. They are:
-pre-init: called before initialization of project properties
-post-init: called after initialization of project properties
-pre-compile: called before javac compilation
-post-compile: called after javac compilation
-pre-compile-single: called before javac compilation of single file
-post-compile-single: called after javac compilation of single file
-pre-compile-test: called before javac compilation of JUnit tests
-post-compile-test: called after javac compilation of JUnit tests
-pre-compile-test-single: called before javac compilation of single JUnit test
-post-compile-test-single: called after javac compilation of single JUunit test
-pre-jar: called before JAR building
-post-jar: called after JAR building
-post-clean: called after cleaning build products
(Targets beginning with '-' are not intended to be called on their own.)
Example of inserting an obfuscator after compilation could look like this:
<target name="-post-compile">
<obfuscate>
<fileset dir="${build.classes.dir}"/>
</obfuscate>
</target>
For list of available properties check the imported
nbproject/build-impl.xml file.
Another way to customize the build is by overriding existing main targets.
The targets of interest are:
-init-macrodef-javac: defines macro for javac compilation
-init-macrodef-junit: defines macro for junit execution
-init-macrodef-debug: defines macro for class debugging
-init-macrodef-java: defines macro for class execution
-do-jar-with-manifest: JAR building (if you are using a manifest)
-do-jar-without-manifest: JAR building (if you are not using a manifest)
run: execution of project
-javadoc-build: Javadoc generation
test-report: JUnit report generation
An example of overriding the target for project execution could look like this:
<target name="run" depends="EssentialsUpdate-impl.jar">
<exec dir="bin" executable="launcher.exe">
<arg file="${dist.jar}"/>
</exec>
</target>
Notice that the overridden target depends on the jar target and not only on
the compile target as the regular run target does. Again, for a list of available
properties which you can use, check the target you are overriding in the
nbproject/build-impl.xml file.
-->
</project>

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +0,0 @@
build.xml.data.CRC32=fd4b98a9
build.xml.script.CRC32=334f342d
build.xml.stylesheet.CRC32=28e38971@1.44.1.45
# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml.
# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you.
nbproject/build-impl.xml.data.CRC32=fd4b98a9
nbproject/build-impl.xml.script.CRC32=966cfa4e
nbproject/build-impl.xml.stylesheet.CRC32=6ddba6b6@1.53.1.46

View File

@ -1 +0,0 @@
DoNotUseThreads

View File

@ -1,112 +0,0 @@
annotation.processing.enabled=true
annotation.processing.enabled.in.editor=false
annotation.processing.run.all.processors=true
annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output
application.title=EssentialsUpdate
application.vendor=essentialsteam
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.expand-tabs=true
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.indent-shift-width=2
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.spaces-per-tab=2
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.tab-size=2
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width=120
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-line-wrap=none
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.usedProfile=project
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineAnnotationArgs=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineArrayInit=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineAssignment=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineBinaryOp=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineCallArgs=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineDisjunctiveCatchTypes=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineFor=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineImplements=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineMethodParams=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineParenthesized=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineTernaryOp=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineThrows=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineTryResources=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.blankLinesAfterClassHeader=0
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.blankLinesBeforeClass=2
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.classDeclBracePlacement=NEW_LINE
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.expand-tabs=false
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.importGroupsOrder=*
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indent-shift-width=4
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indentCasesFromSwitch=false
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.methodDeclBracePlacement=NEW_LINE
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.otherBracePlacement=NEW_LINE
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeCatchOnNewLine=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeElseOnNewLine=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeFinallyOnNewLine=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeWhileOnNewLine=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.separateImportGroups=false
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.spaceAfterTypeCast=false
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.spaces-per-tab=4
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.tab-size=4
build.classes.dir=${build.dir}/classes
build.classes.excludes=**/*.java,**/*.form
# This directory is removed when the project is cleaned:
build.dir=build
build.generated.dir=${build.dir}/generated
build.generated.sources.dir=${build.dir}/generated-sources
# Only compile against the classpath explicitly listed here:
build.sysclasspath=ignore
build.test.classes.dir=${build.dir}/test/classes
build.test.results.dir=${build.dir}/test/results
# Uncomment to specify the preferred debugger connection transport:
#debug.transport=dt_socket
debug.classpath=\
${run.classpath}
debug.test.classpath=\
${run.test.classpath}
# This directory is removed when the project is cleaned:
dist.dir=dist
dist.jar=${dist.dir}/EssentialsUpdate.jar
dist.javadoc.dir=${dist.dir}/javadoc
endorsed.classpath=
excludes=
file.reference.bukkit.jar=../lib/bukkit.jar
includes=**
jar.compress=true
javac.classpath=\
${file.reference.bukkit.jar}
# Space-separated list of extra javac options
javac.compilerargs=
javac.deprecation=false
javac.processorpath=\
${javac.classpath}
javac.source=1.6
javac.target=1.6
javac.test.classpath=\
${javac.classpath}:\
${build.classes.dir}:\
${libs.junit_4.10.classpath}
javac.test.processorpath=\
${javac.test.classpath}
javadoc.additionalparam=
javadoc.author=false
javadoc.encoding=${source.encoding}
javadoc.noindex=false
javadoc.nonavbar=false
javadoc.notree=false
javadoc.private=false
javadoc.splitindex=true
javadoc.use=true
javadoc.version=false
javadoc.windowtitle=
main.class=
manifest.file=manifest.mf
meta.inf.dir=${src.dir}/META-INF
mkdist.disabled=false
platform.active=default_platform
run.classpath=\
${javac.classpath}:\
${build.classes.dir}
# Space-separated list of JVM arguments used when running the project
# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value
# or test-sys-prop.name=value to set system properties for unit tests):
run.jvmargs=
run.test.classpath=\
${javac.test.classpath}:\
${build.test.classes.dir}
source.encoding=UTF-8
src.dir=src
test.src.dir=test

View File

@ -1,18 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
<type>org.netbeans.modules.java.j2seproject</type>
<configuration>
<data xmlns="http://www.netbeans.org/ns/j2se-project/3">
<name>EssentialsUpdate</name>
<source-roots>
<root id="src.dir"/>
</source-roots>
<test-roots>
<root id="test.src.dir"/>
</test-roots>
</data>
<libraries xmlns="http://www.netbeans.org/ns/ant-project-libraries/1">
<definitions>../lib/nblibraries.properties</definitions>
</libraries>
</configuration>
</project>

View File

@ -1,39 +0,0 @@
package com.earth2me.essentials.update;
import org.bukkit.plugin.Plugin;
public abstract class AbstractWorkListener
{
public AbstractWorkListener(final Plugin plugin, final VersionInfo newVersionInfo)
{
this.plugin = plugin;
this.newVersionInfo = newVersionInfo;
}
private final transient Plugin plugin;
private final transient VersionInfo newVersionInfo;
public final void onWorkAbort()
{
onWorkAbort(null);
}
public abstract void onWorkAbort(String message);
public final void onWorkDone()
{
onWorkDone(null);
}
public abstract void onWorkDone(String message);
public VersionInfo getNewVersionInfo()
{
return newVersionInfo;
}
public Plugin getPlugin()
{
return plugin;
}
}

View File

@ -1,171 +0,0 @@
package com.earth2me.essentials.update;
import com.earth2me.essentials.update.chat.*;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
public class EssentialsHelp implements Listener
{
private transient Player chatUser;
private final transient Server server;
private final transient Plugin plugin;
private transient IrcBot ircBot;
private final transient Map<String, Command> commands = new HashMap<String, Command>();
public EssentialsHelp(final Plugin plugin)
{
super();
this.plugin = plugin;
this.server = plugin.getServer();
commands.put("!help", new HelpCommand());
commands.put("!list", new ListCommand());
commands.put("!startup", new StartupCommand(plugin));
commands.put("!errors", new ErrorsCommand(plugin));
commands.put("!config", new ConfigCommand(plugin));
}
public void registerEvents()
{
final PluginManager pluginManager = server.getPluginManager();
pluginManager.registerEvents(this, plugin);
}
public void onCommand(final CommandSender sender)
{
if (sender instanceof Player && sender.hasPermission("essentials.helpchat"))
{
if (chatUser == null)
{
chatUser = (Player)sender;
ircBot = null;
sender.sendMessage("You will be connected to the Essentials Help Chat.");
sender.sendMessage("All your chat messages will be forwarded to the channel. You can't chat with other players on your server while in help chat, but you can use commands.");
sender.sendMessage("Please be patient, if noone is available, check back later.");
sender.sendMessage("Type !help to get a list of all commands.");
sender.sendMessage("Type !quit to leave the channel.");
sender.sendMessage("Do you want to join the channel now? (yes/no)");
}
if (!chatUser.equals(sender))
{
sender.sendMessage("The player " + chatUser.getDisplayName() + " is already using the essentialshelp.");
}
}
else
{
sender.sendMessage("Please run the command as op from in game.");
}
}
public void onDisable()
{
closeConnection();
}
private boolean sendChatMessage(final Player player, final String message)
{
final String messageCleaned = message.trim();
if (messageCleaned.isEmpty())
{
return false;
}
if (ircBot == null)
{
return handleAnswer(messageCleaned, player);
}
else
{
if (ircBot.isKicked())
{
closeConnection();
return false;
}
final String lowMessage = messageCleaned.toLowerCase(Locale.ENGLISH);
if (lowMessage.startsWith("!quit"))
{
closeConnection();
player.sendMessage("Connection closed.");
return true;
}
if (!ircBot.isConnected() || ircBot.getChannels().length == 0)
{
return false;
}
if (handleCommands(lowMessage, player))
{
return true;
}
ircBot.sendMessage(messageCleaned);
chatUser.sendMessage("§6" + ircBot.getNick() + ": §7" + messageCleaned);
return true;
}
}
private void closeConnection()
{
chatUser = null;
if (ircBot != null)
{
ircBot.quit();
ircBot = null;
}
}
private boolean handleAnswer(final String message, final Player player)
{
if (message.equalsIgnoreCase("yes"))
{
player.sendMessage("Connecting...");
connectToIRC(player);
return true;
}
if (message.equalsIgnoreCase("no") || message.equalsIgnoreCase("!quit"))
{
chatUser = null;
return true;
}
return false;
}
private boolean handleCommands(final String lowMessage, final Player player)
{
final String[] parts = lowMessage.split(" ");
if (commands.containsKey(parts[0]))
{
commands.get(parts[0]).run(ircBot, player);
return true;
}
return false;
}
private void connectToIRC(final Player player)
{
ircBot = new IrcBot(player, "Ess_" + player.getName(), UsernameUtil.createUsername(player));
}
@EventHandler
public void onPlayerChat(final AsyncPlayerChatEvent event)
{
if (event.getPlayer() == chatUser)
{
final boolean success = sendChatMessage(event.getPlayer(), event.getMessage());
event.setCancelled(success);
}
}
@EventHandler
public void onPlayerQuit(final PlayerQuitEvent event)
{
closeConnection();
}
}

View File

@ -1,61 +0,0 @@
package com.earth2me.essentials.update;
import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;
public class EssentialsUpdate extends JavaPlugin
{
private transient EssentialsHelp essentialsHelp;
private transient UpdateProcess updateProcess;
@Override
public void onEnable()
{
if (!getDataFolder().exists() && !getDataFolder().mkdirs())
{
Bukkit.getLogger().log(Level.SEVERE, "Could not create data folder: {0}", getDataFolder().getPath());
}
essentialsHelp = new EssentialsHelp(this);
essentialsHelp.registerEvents();
final UpdateCheck updateCheck = new UpdateCheck(this);
updateCheck.checkForUpdates();
updateProcess = new UpdateProcess(this, updateCheck);
updateProcess.registerEvents();
Bukkit.getLogger().log(Level.INFO, "EssentialsUpdate {0} loaded.", getDescription().getVersion());
if (updateCheck.isEssentialsInstalled())
{
updateCheck.scheduleUpdateTask();
}
else
{
Bukkit.getLogger().info("Essentials is ready for installation. Join the game and follow the instructions.");
}
}
@Override
public void onDisable()
{
essentialsHelp.onDisable();
}
@Override
public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args)
{
if (command.getName().equalsIgnoreCase("essentialsupdate"))
{
updateProcess.onCommand(sender);
}
if (command.getName().equalsIgnoreCase("essentialshelp"))
{
essentialsHelp.onCommand(sender);
}
return true;
}
}

View File

@ -1,113 +0,0 @@
package com.earth2me.essentials.update;
import java.io.*;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import org.bukkit.Bukkit;
public class GetFile
{
private transient URLConnection connection;
private transient MessageDigest digest;
public GetFile(final String urlString) throws MalformedURLException, IOException
{
this(new URL(urlString));
}
public GetFile(final URL url) throws IOException
{
this.connection = url.openConnection();
this.connection.setConnectTimeout(1000);
this.connection.setReadTimeout(5000);
this.connection.setUseCaches(false);
this.connection.connect();
final int respCode = ((HttpURLConnection)this.connection).getResponseCode();
if (respCode >= 300 && respCode < 400 && this.connection.getHeaderField("Location") != null)
{
connection.getInputStream().close();
final URL redirect = new URL(this.connection.getHeaderField("Location"));
this.connection = redirect.openConnection();
this.connection.setConnectTimeout(1000);
this.connection.setReadTimeout(5000);
this.connection.setUseCaches(false);
this.connection.connect();
}
}
public void saveTo(final File file) throws IOException
{
try
{
saveTo(file, null);
}
catch (NoSuchAlgorithmException ex)
{
throw new RuntimeException(ex);
}
}
public void saveTo(final File file, final String key) throws IOException, NoSuchAlgorithmException
{
if (key != null)
{
digest = MessageDigest.getInstance("SHA256");
}
final byte[] buffer = new byte[1024 * 8];
boolean brokenFile = false;
final BufferedInputStream input = new BufferedInputStream(connection.getInputStream());
try
{
final BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(file));
try
{
int length;
do
{
length = input.read(buffer);
if (length >= 0)
{
if (key != null)
{
digest.update(buffer, 0, length);
}
output.write(buffer, 0, length);
}
}
while (length >= 0);
if (key != null)
{
final byte[] checksum = digest.digest();
final String checksumString = new BigInteger(checksum).toString(36);
if (!checksumString.equals(key))
{
brokenFile = true;
}
}
}
finally
{
output.close();
}
if (brokenFile && !file.delete())
{
Bukkit.getLogger().log(Level.SEVERE, "Could not delete file {0}", file.getPath());
}
}
finally
{
input.close();
}
if (brokenFile)
{
throw new IOException("Checksum check failed.");
}
}
}

View File

@ -1,35 +0,0 @@
package com.earth2me.essentials.update;
import java.net.MalformedURLException;
import java.net.URL;
import org.bukkit.configuration.Configuration;
public class ModuleInfo
{
private final transient String url;
private final transient String version;
private final transient String hash;
public ModuleInfo(final Configuration updateConfig, final String path)
{
url = updateConfig.getString(path + ".url", null);
version = updateConfig.getString(path + ".version", null);
hash = updateConfig.getString(path + ".hash", null);
}
public URL getUrl() throws MalformedURLException
{
return new URL(url);
}
public String getVersion()
{
return version;
}
public String getHash()
{
return hash;
}
}

View File

@ -1,40 +0,0 @@
package com.earth2me.essentials.update;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PastieUpload
{
private final transient PostToUrl connection;
public PastieUpload() throws MalformedURLException
{
connection = new PostToUrl(new URL("http://pastie.org/pastes"));
}
public String send(final String data) throws IOException
{
final Map<String, Object> map = new HashMap<String, Object>();
map.put("paste[parser_id]", "19");
map.put("paste[authorization]", "burger");
map.put("paste[body]", data);
map.put("paste[restricted]", "1");
final String html = connection.send(map);
final Matcher matcher = Pattern.compile("(?s).*\\?key=([a-z0-9]+).*").matcher(html);
if (matcher.matches())
{
final String key = matcher.group(1);
return "http://pastie.org/private/" + key;
}
else
{
throw new IOException("Failed to upload to pastie.org");
}
}
}

View File

@ -1,66 +0,0 @@
package com.earth2me.essentials.update;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Random;
public class PostToUrl
{
private final transient URL url;
private final transient String boundary;
private final transient Random random = new Random();
private final static String CRLF = "\r\n";
private final static Charset UTF8 = Charset.forName("utf-8");
public PostToUrl(final URL url)
{
this.url = url;
final byte[] bytes = new byte[32];
random.nextBytes(bytes);
this.boundary = "----------" + new BigInteger(bytes).toString(Character.MAX_RADIX) + "_$";
}
public String send(final Map<String, Object> data) throws IOException
{
final URLConnection connection = url.openConnection();
connection.setRequestProperty("content-type", "multipart/form-data; boundary=" + boundary);
final StringBuilder dataBuilder = new StringBuilder();
for (Map.Entry<String, Object> entry : data.entrySet())
{
if (entry.getValue() instanceof String)
{
dataBuilder.append("--").append(boundary).append(CRLF);
dataBuilder.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append('"').append(CRLF);
dataBuilder.append(CRLF);
dataBuilder.append(entry.getValue()).append(CRLF);
}
// TODO: Add support for file upload
}
dataBuilder.append("--").append(boundary).append("--").append(CRLF);
dataBuilder.append(CRLF);
connection.setDoOutput(true);
final byte[] message = dataBuilder.toString().getBytes(UTF8);
connection.setRequestProperty("content-length", Integer.toString(message.length));
connection.connect();
final OutputStream stream = connection.getOutputStream();
stream.write(message);
stream.close();
final BufferedReader page = new BufferedReader(new InputStreamReader(connection.getInputStream(), UTF8));
final StringBuilder input = new StringBuilder();
String line;
while ((line = page.readLine()) != null)
{
input.append(line).append("\n");
}
page.close();
return input.toString();
}
}

View File

@ -1,202 +0,0 @@
package com.earth2me.essentials.update;
import java.io.File;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
public class UpdateCheck
{
private transient CheckResult result = CheckResult.UNKNOWN;
private transient Version currentVersion;
private transient Version newVersion = null;
private transient int bukkitResult = 0;
private transient UpdateFile updateFile;
private final static int CHECK_INTERVAL = 20 * 60 * 60 * 6;
private final transient Plugin plugin;
private transient boolean essentialsInstalled;
public UpdateCheck(final Plugin plugin)
{
this.plugin = plugin;
updateFile = new UpdateFile(plugin);
checkForEssentials();
}
private void checkForEssentials()
{
final PluginManager pluginManager = plugin.getServer().getPluginManager();
final Plugin essentials = pluginManager.getPlugin("Essentials");
essentialsInstalled = essentials != null;
if (essentialsInstalled)
{
currentVersion = new Version(essentials.getDescription().getVersion());
}
else
{
if (new File(plugin.getDataFolder().getParentFile(), "Essentials.jar").exists())
{
Bukkit.getLogger().severe("Essentials.jar found, but not recognized by Bukkit. Broken download?");
}
}
}
public void scheduleUpdateTask()
{
plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable()
{
@Override
public void run()
{
updateFile = new UpdateFile(plugin);
checkForUpdates();
}
}, CHECK_INTERVAL, CHECK_INTERVAL);
}
public boolean isEssentialsInstalled()
{
return essentialsInstalled;
}
public CheckResult getResult()
{
return result;
}
public int getNewBukkitVersion()
{
return bukkitResult;
}
public VersionInfo getNewVersionInfo()
{
return updateFile.getVersions().get(newVersion);
}
public enum CheckResult
{
NEW_ESS, NEW_ESS_BUKKIT, NEW_BUKKIT, OK, UNKNOWN
}
public void checkForUpdates()
{
if (currentVersion == null)
{
return;
}
final Map<Version, VersionInfo> versions = updateFile.getVersions();
final int bukkitVersion = getBukkitVersion();
Version higher = null;
Version found = null;
Version lower = null;
int bukkitHigher = 0;
int bukkitLower = 0;
for (Entry<Version, VersionInfo> entry : versions.entrySet())
{
final int minBukkit = entry.getValue().getMinBukkit();
final int maxBukkit = entry.getValue().getMaxBukkit();
if (minBukkit == 0 || maxBukkit == 0)
{
continue;
}
if (bukkitVersion <= maxBukkit)
{
if (bukkitVersion < minBukkit)
{
if (higher == null || higher.compareTo(entry.getKey()) < 0)
{
higher = entry.getKey();
bukkitHigher = minBukkit;
}
}
else
{
if (found == null || found.compareTo(entry.getKey()) < 0)
{
found = entry.getKey();
}
}
}
else
{
if (lower == null || lower.compareTo(entry.getKey()) < 0)
{
lower = entry.getKey();
bukkitLower = minBukkit;
}
}
}
if (found != null)
{
if (found.compareTo(currentVersion) > 0)
{
result = CheckResult.NEW_ESS;
newVersion = found;
}
else
{
result = CheckResult.OK;
}
}
else if (higher != null)
{
if (higher.compareTo(currentVersion) > 0)
{
newVersion = higher;
result = CheckResult.NEW_ESS_BUKKIT;
bukkitResult = bukkitHigher;
}
else if (higher.compareTo(currentVersion) < 0)
{
result = CheckResult.UNKNOWN;
}
else
{
result = CheckResult.NEW_BUKKIT;
bukkitResult = bukkitHigher;
}
}
else if (lower != null)
{
if (lower.compareTo(currentVersion) > 0)
{
result = CheckResult.NEW_ESS_BUKKIT;
newVersion = lower;
bukkitResult = bukkitLower;
}
else if (lower.compareTo(currentVersion) < 0)
{
result = CheckResult.UNKNOWN;
}
else
{
result = CheckResult.NEW_BUKKIT;
bukkitResult = bukkitLower;
}
}
}
private int getBukkitVersion()
{
final Matcher versionMatch = Pattern.compile("git-Bukkit-([0-9]+).([0-9]+).([0-9]+)-[0-9]+-[0-9a-z]+-b([0-9]+)jnks.*").matcher(plugin.getServer().getVersion());
if (versionMatch.matches())
{
return Integer.parseInt(versionMatch.group(4));
}
throw new NumberFormatException("Bukkit Version changed!");
}
public Version getNewVersion()
{
return newVersion;
}
}

View File

@ -1,205 +0,0 @@
package com.earth2me.essentials.update;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
public class UpdateFile
{
private final static Logger LOGGER = Bukkit.getLogger();
private final static String UPDATE_URL = "http://goo.gl/67jev";
private final static BigInteger PUBLIC_KEY = new BigInteger("5ha6a2d4qdy17ttkg8evh74sl5a87djojwenu12k1lvy8ui6003e6l06rntczpoh99mhc3txj8mqlxw111oyy9yl7s7qpyluyzix3j1odxrxx4u52gxvyu6qiteapczkzvi7rxgeqsozz7b19rdx73a7quo9ybwpz1cr82r7x5k0pg2a73pjjsv2j1awr13azo7klrcxp9y5xxwf5qv1s3tw4zqftli18u0ek5qkbzfbgk1v5n2f11pkwwk6p0mibrn26wnjbv11vyiqgu95o7busmt6vf5q7grpcenl637w83mbin56s3asj1131b2mscj9xep3cbj7la9tgsxl5bj87vzy8sk2d34kzwqdqgh9nry43nqqus12l1stmiv184r8r3jcy8w43e8h1u1mzklldb5eytkuhayqik8l3ns04hwt8sgacvw534be8sx26qrn5s1", 36);
private final transient File file;
private transient YamlConfiguration updateConfig;
private final transient Plugin plugin;
private final transient TreeMap<Version, VersionInfo> versions = new TreeMap<Version, VersionInfo>();
public UpdateFile(final Plugin plugin)
{
this.plugin = plugin;
final long lastUpdate = Long.parseLong(plugin.getConfig().getString("lastupdate", "0"));
file = new File(plugin.getDataFolder(), "update.yml");
if (lastUpdate < System.currentTimeMillis() - 1000 * 60 * 60 * 6 || !file.exists())
{
if (file.exists() && !file.delete())
{
LOGGER.log(Level.SEVERE, "Could not delete file update.yml!");
return;
}
if (!downloadFile() || !checkFile())
{
LOGGER.log(Level.SEVERE, "Could not download and verify file update.yml!");
return;
}
}
try
{
readVersions();
}
catch (Exception ex)
{
LOGGER.log(Level.SEVERE, "Could not load update.yml!");
return;
}
}
private boolean downloadFile()
{
GetFile getFile;
try
{
getFile = new GetFile(UPDATE_URL);
getFile.saveTo(file);
plugin.getConfig().set("lastupdate", System.currentTimeMillis());
plugin.getConfig().save(new File(plugin.getDataFolder(), "config.yml"));
return true;
}
catch (IOException ex)
{
LOGGER.log(Level.SEVERE, "Error while downloading update.yml", ex);
return false;
}
}
private boolean checkFile()
{
BufferedInputStream bis = null;
try
{
bis = new BufferedInputStream(new FileInputStream(file));
if (bis.read() != '#')
{
throw new IOException("File has to start with #");
}
final StringBuilder length = new StringBuilder();
final StringBuilder signature = new StringBuilder();
boolean isSignature = false;
do
{
final int cur = bis.read();
if (cur == -1)
{
break;
}
if (cur == ':')
{
isSignature = true;
}
else if (cur == '\n')
{
break;
}
else if ((cur >= '0' && cur <= '9')
|| (cur >= 'a' && cur <= 'z'))
{
if (isSignature)
{
signature.append((char)cur);
}
else
{
length.append((char)cur);
}
}
else
{
throw new IOException("Illegal character in signature!");
}
}
while (true);
if (length.length() == 0 || signature.length() == 0)
{
throw new IOException("Broken signature!");
}
final int sigLength = new BigInteger(length.toString(), 36).intValue();
if (sigLength < 0 || sigLength > 2048)
{
throw new IOException("Invalid signature length!");
}
final byte[] sigBytes = new BigInteger(signature.toString(), 36).toByteArray();
if (sigLength < sigBytes.length)
{
throw new IOException("Length is less then available bytes.");
}
byte[] realBytes;
if (sigLength == sigBytes.length)
{
realBytes = sigBytes;
}
else
{
realBytes = new byte[sigLength];
System.arraycopy(sigBytes, 0, realBytes, sigLength - sigBytes.length, sigBytes.length);
}
final X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(PUBLIC_KEY.toByteArray());
final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
final PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
final Signature rsa = Signature.getInstance("SHA256withRSA");
rsa.initVerify(pubKey);
final byte[] buffer = new byte[2048];
int readLength;
do
{
readLength = bis.read(buffer);
if (readLength >= 0)
{
rsa.update(buffer, 0, readLength);
}
}
while (readLength >= 0);
return rsa.verify(realBytes);
}
catch (Exception ex)
{
LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
}
finally
{
try
{
if (bis != null)
{
bis.close();
}
}
catch (IOException ex)
{
LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
}
}
return false;
}
private void readVersions() throws Exception
{
updateConfig = new YamlConfiguration();
updateConfig.load(file);
versions.clear();
for (String versionString : updateConfig.getKeys(false))
{
final Version version = new Version(versionString);
final VersionInfo info = new VersionInfo(updateConfig, versionString);
versions.put(version, info);
}
}
public Map<Version, VersionInfo> getVersions()
{
return Collections.unmodifiableMap(versions.descendingMap());
}
}

View File

@ -1,199 +0,0 @@
package com.earth2me.essentials.update;
import com.earth2me.essentials.update.states.InstallationFinishedEvent;
import com.earth2me.essentials.update.states.StateMachine;
import com.earth2me.essentials.update.tasks.SelfUpdate;
import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.Plugin;
public class UpdateProcess implements Listener
{
private transient Player currentPlayer;
private final transient Plugin plugin;
private final transient UpdateCheck updateCheck;
private transient StateMachine stateMachine;
public UpdateProcess(final Plugin plugin, final UpdateCheck updateCheck)
{
super();
this.plugin = plugin;
this.updateCheck = updateCheck;
}
public void registerEvents()
{
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
public boolean selfUpdate()
{
if (new Version(plugin.getDescription().getVersion()).compareTo(updateCheck.getNewVersion()) < 0)
{
if (currentPlayer != null)
{
currentPlayer.sendMessage("A newer version of EssentialsUpdate is found. Downloading new file and reloading server.");
}
Bukkit.getLogger().log(Level.INFO, "A newer version of EssentialsUpdate is found. Downloading new file and reloading server.");
new SelfUpdate(new AbstractWorkListener(plugin, updateCheck.getNewVersionInfo())
{
@Override
public void onWorkAbort(final String message)
{
if (message != null && !message.isEmpty()
&& UpdateProcess.this.currentPlayer != null
&& UpdateProcess.this.currentPlayer.isOnline())
{
UpdateProcess.this.currentPlayer.sendMessage(message);
}
if (message != null && !message.isEmpty())
{
Bukkit.getLogger().log(Level.SEVERE, message);
}
UpdateProcess.this.currentPlayer = null;
}
@Override
public void onWorkDone(final String message)
{
if (message != null && !message.isEmpty()
&& UpdateProcess.this.currentPlayer != null
&& UpdateProcess.this.currentPlayer.isOnline())
{
UpdateProcess.this.currentPlayer.sendMessage(message);
}
if (message != null && !message.isEmpty())
{
Bukkit.getLogger().log(Level.INFO, message);
}
UpdateProcess.this.currentPlayer = null;
}
}).start();
return true;
}
if (updateCheck.getResult() == UpdateCheck.CheckResult.NEW_ESS_BUKKIT)
{
final String message = "Please update bukkit to version " + updateCheck.getNewBukkitVersion() + " before updating Essentials.";
if (currentPlayer != null)
{
currentPlayer.sendMessage(message);
}
Bukkit.getLogger().log(Level.INFO, message);
currentPlayer = null;
return true;
}
return false;
}
@EventHandler
public void onInstallationFinished(final InstallationFinishedEvent event)
{
UpdateProcess.this.currentPlayer = null;
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerChat(final AsyncPlayerChatEvent event)
{
if (event.getPlayer() == currentPlayer)
{
final StateMachine.MachineResult result = stateMachine.reactOnMessage(event.getMessage());
if (result == StateMachine.MachineResult.ABORT)
{
currentPlayer.sendMessage("Installation wizard aborted. You can restart it using /essentialsupdate.");
currentPlayer = null;
}
if (result == StateMachine.MachineResult.DONE)
{
startWork();
}
event.setCancelled(true);
return;
}
}
@EventHandler
public void onPlayerJoin(final PlayerJoinEvent event)
{
final Player player = event.getPlayer();
if (currentPlayer.getName().equals(player.getName()))
{
currentPlayer = player;
player.sendMessage("You quit the game, while the installation wizard was running.");
player.sendMessage("The installation wizard will now resume.");
player.sendMessage("You can exit the wizard by typing quit into the chat.");
stateMachine.resumeInstallation(player);
}
if (player.hasPermission("essentials.update") && !updateCheck.isEssentialsInstalled())
{
player.sendMessage("Hello " + player.getDisplayName());
player.sendMessage("Please type /essentialsupdate into the chat to start the installation of Essentials.");
}
if (player.hasPermission("essentials.update"))
{
final UpdateCheck.CheckResult result = updateCheck.getResult();
switch (result)
{
case NEW_ESS:
player.sendMessage("The new version " + updateCheck.getNewVersion().toString() + " for Essentials is available. Please type /essentialsupdate to update.");
break;
case NEW_BUKKIT:
player.sendMessage("Your bukkit version is not the recommended build for Essentials, please update to version " + updateCheck.getNewBukkitVersion() + ".");
break;
case NEW_ESS_BUKKIT:
player.sendMessage("There is a new version " + updateCheck.getNewVersion().toString() + " of Essentials for Bukkit " + updateCheck.getNewBukkitVersion());
break;
default:
}
}
}
public void onCommand(final CommandSender sender)
{
if (sender instanceof Player && sender.hasPermission("essentials.update"))
{
if (currentPlayer == null)
{
currentPlayer = (Player)sender;
if (selfUpdate())
{
return;
}
stateMachine = new StateMachine(plugin, currentPlayer, updateCheck);
final StateMachine.MachineResult result = stateMachine.askQuestion();
if (result == StateMachine.MachineResult.DONE)
{
startWork();
}
}
if (!currentPlayer.equals(sender))
{
sender.sendMessage("The player " + currentPlayer.getDisplayName() + " is already using the wizard.");
}
}
else
{
sender.sendMessage("Please run the command as op from in game.");
}
}
private void startWork()
{
currentPlayer.sendMessage("Installation wizard done. Starting installation.");
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable()
{
@Override
public void run()
{
stateMachine.startWork();
}
});
}
}

View File

@ -1,173 +0,0 @@
package com.earth2me.essentials.update;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Version implements Comparable<Version>
{
public enum Type
{
STABLE, PREVIEW, DEVELOPER
}
public int getMajor()
{
return major;
}
public int getMinor()
{
return minor;
}
public int getBuild()
{
return build;
}
public Type getType()
{
return type;
}
private final transient int major;
private final transient int minor;
private final transient int build;
private final transient Type type;
public Version(final String versionString)
{
final Matcher matcher = Pattern.compile("(Pre|Dev)?([0-9]+)[_\\.]([0-9]+)[_\\.]([0-9]+).*").matcher(versionString);
if (!matcher.matches() || matcher.groupCount() < 4)
{
type = Type.DEVELOPER;
major = 99;
minor = build = 0;
return;
}
if (versionString.startsWith("Pre"))
{
type = Type.PREVIEW;
}
else if (versionString.startsWith("Dev"))
{
type = Type.DEVELOPER;
}
else
{
type = Type.STABLE;
}
major = Integer.parseInt(matcher.group(2));
minor = Integer.parseInt(matcher.group(3));
build = Integer.parseInt(matcher.group(4));
}
@Override
public int compareTo(final Version other)
{
int ret = 0;
if (other.getType() == Type.DEVELOPER && getType() != Type.DEVELOPER)
{
ret = -1;
}
else if (getType() == Type.DEVELOPER && other.getType() != Type.DEVELOPER)
{
ret = 1;
}
else if (other.getMajor() > getMajor())
{
ret = -1;
}
else if (getMajor() > other.getMajor())
{
ret = 1;
}
else if (other.getMinor() > getMinor())
{
ret = -1;
}
else if (getMinor() > other.getMinor())
{
ret = 1;
}
else if (other.getBuild() > getBuild())
{
ret = -1;
}
else if (getBuild() > other.getBuild())
{
ret = 1;
}
else if (other.getType() == Type.STABLE && getType() == Type.PREVIEW)
{
ret = -1;
}
else if (getType() == Type.STABLE && other.getType() == Type.PREVIEW)
{
ret = 1;
}
return ret;
}
@Override
public boolean equals(final Object obj)
{
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final Version other = (Version)obj;
if (this.major != other.major)
{
return false;
}
if (this.minor != other.minor)
{
return false;
}
if (this.build != other.build)
{
return false;
}
if (this.type != other.type)
{
return false;
}
return true;
}
@Override
public int hashCode()
{
int hash = 5;
hash = 71 * hash + this.major;
hash = 71 * hash + this.minor;
hash = 71 * hash + this.build;
hash = 71 * hash + (this.type == null ? 0 : this.type.hashCode());
return hash;
}
@Override
public String toString()
{
final StringBuilder builder = new StringBuilder();
if (type == Type.DEVELOPER)
{
builder.append("Dev");
}
if (type == Type.PREVIEW)
{
builder.append("Pre");
}
builder.append(major);
builder.append('.');
builder.append(minor);
builder.append('.');
builder.append(build);
return builder.toString();
}
}

View File

@ -1,49 +0,0 @@
package com.earth2me.essentials.update;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.configuration.Configuration;
public class VersionInfo
{
private final transient List<String> changelog;
private final transient int minBukkit;
private final transient int maxBukkit;
private final transient Map<String, ModuleInfo> modules;
public VersionInfo(final Configuration updateConfig, final String path)
{
changelog = updateConfig.getStringList(path + ".changelog");
minBukkit = updateConfig.getInt(path + ".min-bukkit", 0);
maxBukkit = updateConfig.getInt(path + ".max-bukkit", 0);
modules = new HashMap<String, ModuleInfo>();
final String modulesPath = path + ".modules";
for (String module : updateConfig.getKeys(false))
{
modules.put(module, new ModuleInfo(updateConfig, modulesPath + module));
}
}
public List<String> getChangelog()
{
return Collections.unmodifiableList(changelog);
}
public int getMinBukkit()
{
return minBukkit;
}
public int getMaxBukkit()
{
return maxBukkit;
}
public Map<String, ModuleInfo> getModules()
{
return Collections.unmodifiableMap(modules);
}
}

View File

@ -1,73 +0,0 @@
package com.earth2me.essentials.update.chat;
import com.earth2me.essentials.update.PastieUpload;
import java.io.*;
import java.nio.charset.Charset;
import org.bukkit.plugin.Plugin;
public abstract class AbstractFileCommand implements Command
{
private final transient Plugin plugin;
private final static Charset UTF8 = Charset.forName("utf-8");
public AbstractFileCommand(final Plugin plugin)
{
this.plugin = plugin;
}
protected BufferedReader getServerLogReader() throws IOException
{
final File bukkitFolder = plugin.getDataFolder().getAbsoluteFile().getParentFile().getParentFile();
if (bukkitFolder == null || !bukkitFolder.exists())
{
throw new IOException("Bukkit folder not found.");
}
final File logFile = new File(bukkitFolder, "server.log");
if (!logFile.exists())
{
throw new IOException("Server log not found.");
}
final FileInputStream fis = new FileInputStream(logFile);
try
{
if (logFile.length() > 1000000)
{
fis.skip(logFile.length() - 1000000);
}
return new BufferedReader(new InputStreamReader(fis));
}
catch (IOException ex)
{
fis.close();
throw ex;
}
}
protected BufferedReader getPluginConfig(final String pluginName, final String fileName) throws IOException
{
final File configFolder = new File(plugin.getDataFolder().getAbsoluteFile().getParentFile(), pluginName);
if (!configFolder.exists())
{
throw new IOException(pluginName + " plugin folder not found.");
}
final File configFile = new File(configFolder, fileName);
if (!configFile.exists())
{
throw new IOException(pluginName + " plugin file " + fileName + " not found.");
}
return new BufferedReader(new InputStreamReader(new FileInputStream(configFile), UTF8));
}
protected String uploadToPastie(final StringBuilder input) throws IOException
{
if (input.length() > 15000)
{
input.delete(0, input.length() - 15000);
input.append("## Cropped after 15000 bytes");
}
final PastieUpload pastie = new PastieUpload();
return pastie.send(input.toString());
}
}

View File

@ -1,9 +0,0 @@
package com.earth2me.essentials.update.chat;
import org.bukkit.entity.Player;
public interface Command
{
void run(final IrcBot ircBot, final Player player);
}

View File

@ -1,66 +0,0 @@
package com.earth2me.essentials.update.chat;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public class ConfigCommand extends AbstractFileCommand implements Command
{
public ConfigCommand(final Plugin plugin)
{
super(plugin);
}
@Override
public void run(final IrcBot ircBot, final Player player)
{
BufferedReader page = null;
try
{
page = getPluginConfig("Essentials", "config.yml");
final StringBuilder input = new StringBuilder();
do
{
final String line = page.readLine();
if (line == null)
{
break;
}
else
{
input.append(line).append("\n");
}
}
while (true);
page.close();
final String message = "Essentials config.yml: " + uploadToPastie(input);
player.sendMessage("§6" + ircBot.getNick() + ": §7" + message);
ircBot.sendMessage(message);
}
catch (IOException ex)
{
Bukkit.getLogger().log(Level.SEVERE, null, ex);
player.sendMessage(ex.getMessage());
}
finally
{
try
{
if (page != null)
{
page.close();
}
}
catch (IOException ex)
{
Bukkit.getLogger().log(Level.SEVERE, null, ex);
player.sendMessage(ex.getMessage());
}
}
}
}

View File

@ -1,71 +0,0 @@
package com.earth2me.essentials.update.chat;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public class ErrorsCommand extends AbstractFileCommand implements Command
{
private final transient Pattern pattern = Pattern.compile("^[0-9 :-]+\\[INFO\\].*");
public ErrorsCommand(final Plugin plugin)
{
super(plugin);
}
@Override
public void run(final IrcBot ircBot, final Player player)
{
BufferedReader page = null;
try
{
page = getServerLogReader();
final StringBuilder input = new StringBuilder();
do
{
final String line = page.readLine();
if (line == null)
{
break;
}
else
{
if (!pattern.matcher(line).matches())
{
input.append(line).append("\n");
}
}
}
while (true);
page.close();
final String message = "Errors: " + uploadToPastie(input);
player.sendMessage("§6" + ircBot.getNick() + ": §7" + message);
ircBot.sendMessage(message);
}
catch (IOException ex)
{
Bukkit.getLogger().log(Level.SEVERE, null, ex);
player.sendMessage(ex.getMessage());
}
finally
{
try
{
if (page != null)
{
page.close();
}
}
catch (IOException ex)
{
Bukkit.getLogger().log(Level.SEVERE, null, ex);
player.sendMessage(ex.getMessage());
}
}
}
}

View File

@ -1,18 +0,0 @@
package com.earth2me.essentials.update.chat;
import org.bukkit.entity.Player;
public class HelpCommand implements Command
{
@Override
public void run(final IrcBot ircBot, final Player player)
{
player.sendMessage("Commands: (Note: Files send to the chat will be public viewable.)");
player.sendMessage("!errors - Send the last server errors to the chat.");
player.sendMessage("!startup - Send the last startup messages to the chat.");
player.sendMessage("!config - Sends your Essentials config to the chat.");
player.sendMessage("!list - List all players in chat.");
player.sendMessage("!quit - Leave chat.");
}
}

View File

@ -1,198 +0,0 @@
package com.earth2me.essentials.update.chat;
import java.io.IOException;
import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.jibble.pircbot.Colors;
import org.jibble.pircbot.IrcException;
import org.jibble.pircbot.PircBot;
import org.jibble.pircbot.User;
public class IrcBot extends PircBot
{
private static final String CHANNEL = "#essentials";
private static final int PORT = 6667;
private static final String SERVER = "irc.esper.net";
private transient boolean reconnect = true;
private final transient Player player;
private transient boolean kicked = false;
public IrcBot(final Player player, final String nickName, final String versionString)
{
super();
this.player = player;
setName(nickName);
setLogin("esshelp");
setVersion(versionString);
connect();
joinChannel(CHANNEL);
}
private void connect()
{
try
{
connect(SERVER, PORT);
return;
}
catch (IOException ex)
{
Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
}
catch (IrcException ex)
{
Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
}
}
public void quit()
{
reconnect = false;
disconnect();
}
@Override
protected void onConnect()
{
reconnect = true;
}
@Override
protected void onDisconnect()
{
if (reconnect)
{
int tries = 10;
while (!isConnected())
{
try
{
tries--;
reconnect();
}
catch (Exception e)
{
Bukkit.getLogger().log(Level.WARNING, e.getMessage(), e);
try
{
Thread.sleep(10000);
}
catch (InterruptedException ex)
{
Bukkit.getLogger().log(Level.WARNING, e.getMessage(), e);
}
}
if (tries <= 0)
{
player.sendMessage("Connection lost to server.");
kicked = true;
break;
}
}
}
}
@Override
protected void onKick(final String channel, final String kickerNick,
final String kickerLogin, final String kickerHostname,
final String recipientNick, final String reason)
{
if (recipientNick.equals(getNick()))
{
player.sendMessage("You have been kicked from the channel: " + reason);
quit();
kicked = true;
}
}
public boolean isKicked()
{
return kicked;
}
@Override
protected void onMessage(final String channel, final String sender,
final String login, final String hostname,
final String message)
{
player.sendMessage(formatChatMessage(sender, message, false));
}
@Override
protected void onAction(final String sender, final String login,
final String hostname, final String target,
final String action)
{
player.sendMessage(formatChatMessage(sender, action, true));
}
@Override
protected void onNotice(final String sourceNick, final String sourceLogin,
final String sourceHostname, final String target,
final String notice)
{
player.sendMessage(formatChatMessage(sourceNick, notice, false));
}
@Override
protected void onTopic(final String channel, final String topic,
final String setBy, final long date,
final boolean changed)
{
player.sendMessage(formatChatMessage(channel, topic, false));
}
public String formatChatMessage(final String nick, final String message, final boolean action)
{
final StringBuilder builder = new StringBuilder();
builder.append("§6");
if (action)
{
builder.append('*');
}
builder.append(nick);
if (!action)
{
builder.append(':');
}
builder.append(" §7");
builder.append(replaceColors(message));
return builder.toString();
}
private String replaceColors(final String message)
{
String m = Colors.removeFormatting(message);
m = m.replaceAll("\u000310(,(0?[0-9]|1[0-5]))?", "§b");
m = m.replaceAll("\u000311(,(0?[0-9]|1[0-5]))?", "§f");
m = m.replaceAll("\u000312(,(0?[0-9]|1[0-5]))?", "§9");
m = m.replaceAll("\u000313(,(0?[0-9]|1[0-5]))?", "§d");
m = m.replaceAll("\u000314(,(0?[0-9]|1[0-5]))?", "§8");
m = m.replaceAll("\u000315(,(0?[0-9]|1[0-5]))?", "§7");
m = m.replaceAll("\u00030?1(,(0?[0-9]|1[0-5]))?", "§0");
m = m.replaceAll("\u00030?2(,(0?[0-9]|1[0-5]))?", "§1");
m = m.replaceAll("\u00030?3(,(0?[0-9]|1[0-5]))?", "§2");
m = m.replaceAll("\u00030?4(,(0?[0-9]|1[0-5]))?", "§c");
m = m.replaceAll("\u00030?5(,(0?[0-9]|1[0-5]))?", "§4");
m = m.replaceAll("\u00030?6(,(0?[0-9]|1[0-5]))?", "§5");
m = m.replaceAll("\u00030?7(,(0?[0-9]|1[0-5]))?", "§6");
m = m.replaceAll("\u00030?8(,(0?[0-9]|1[0-5]))?", "§e");
m = m.replaceAll("\u00030?9(,(0?[0-9]|1[0-5]))?", "§a");
m = m.replaceAll("\u00030?0(,(0?[0-9]|1[0-5]))?", "§f");
m = m.replace("\u000f", "§7");
m = Colors.removeColors(m);
return m;
}
public void sendMessage(final String message)
{
sendMessage(CHANNEL, message);
}
public User[] getUsers()
{
return getUsers(CHANNEL);
}
}

View File

@ -1,32 +0,0 @@
package com.earth2me.essentials.update.chat;
import org.bukkit.entity.Player;
import org.jibble.pircbot.User;
public class ListCommand implements Command
{
@Override
public void run(final IrcBot ircBot, final Player player)
{
final User[] members = ircBot.getUsers();
final StringBuilder message = new StringBuilder();
for (User user : members)
{
if (message.length() > 0)
{
message.append("§f, ");
}
if (user.isOp() || user.hasVoice())
{
message.append("§6");
}
else
{
message.append("§7");
}
message.append(user.getPrefix()).append(user.getNick());
}
player.sendMessage(message.toString());
}
}

View File

@ -1,77 +0,0 @@
package com.earth2me.essentials.update.chat;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public class StartupCommand extends AbstractFileCommand implements Command
{
private final transient Pattern patternStart = Pattern.compile("^[0-9 :-]+\\[INFO\\] Starting minecraft server version.*");
private final transient Pattern patternEnd = Pattern.compile("^[0-9 :-]+\\[INFO\\] Done \\([0-9.,]+s\\)! For help, type \"help\".*");
public StartupCommand(final Plugin plugin)
{
super(plugin);
}
@Override
public void run(final IrcBot ircBot, final Player player)
{
BufferedReader page = null;
try
{
page = getServerLogReader();
final StringBuilder input = new StringBuilder();
String line;
boolean log = false;
while ((line = page.readLine()) != null)
{
if (patternStart.matcher(line).matches())
{
if (input.length() > 0)
{
input.delete(0, input.length());
}
log = true;
}
if (log)
{
input.append(line).append("\n");
}
if (patternEnd.matcher(line).matches())
{
log = false;
}
}
page.close();
final String message = "Startup: " + uploadToPastie(input);
player.sendMessage("§6" + ircBot.getNick() + ": §7" + message);
ircBot.sendMessage(message);
}
catch (IOException ex)
{
Bukkit.getLogger().log(Level.SEVERE, null, ex);
player.sendMessage(ex.getMessage());
}
finally
{
try
{
if (page != null)
{
page.close();
}
}
catch (IOException ex)
{
Bukkit.getLogger().log(Level.SEVERE, null, ex);
player.sendMessage(ex.getMessage());
}
}
}
}

View File

@ -1,124 +0,0 @@
package com.earth2me.essentials.update.chat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public final class UsernameUtil
{
private static final Pattern CB_PATTERN = Pattern.compile("git-Bukkit-([0-9]+).([0-9]+).([0-9]+)-[0-9]+-[0-9a-z]+-b([0-9]+)jnks.*");
private UsernameUtil()
{
}
public static String createUsername(final Player player)
{
final StringBuilder nameBuilder = new StringBuilder();
final Server server = Bukkit.getServer();
nameBuilder.append(player.getName());
addCraftBukkitVersion(server, nameBuilder);
addEssentialsVersion(server, nameBuilder);
addGroupManagerVersion(server, nameBuilder);
addPermissionsExVersion(server, nameBuilder);
addPermissionsBukkitVersion(server, nameBuilder);
addBPermissionsVersion(server, nameBuilder);
addPermissionsVersion(server, nameBuilder);
return nameBuilder.toString();
}
private static void addPermissionsVersion(final Server server, final StringBuilder nameBuilder)
{
final Plugin perm = server.getPluginManager().getPlugin("Permissions");
if (perm != null)
{
nameBuilder.append(" P");
if (!perm.isEnabled())
{
nameBuilder.append('!');
}
nameBuilder.append(perm.getDescription().getVersion());
}
}
private static void addBPermissionsVersion(final Server server, final StringBuilder nameBuilder)
{
final Plugin bperm = server.getPluginManager().getPlugin("bPermissions");
if (bperm != null)
{
nameBuilder.append(" BP");
if (!bperm.isEnabled())
{
nameBuilder.append('!');
}
nameBuilder.append(bperm.getDescription().getVersion());
}
}
private static void addPermissionsBukkitVersion(final Server server, final StringBuilder nameBuilder)
{
final Plugin permb = server.getPluginManager().getPlugin("PermissionsBukkit");
if (permb != null)
{
nameBuilder.append(" PB");
if (!permb.isEnabled())
{
nameBuilder.append('!');
}
nameBuilder.append(permb.getDescription().getVersion());
}
}
private static void addPermissionsExVersion(final Server server, final StringBuilder nameBuilder)
{
final Plugin pex = server.getPluginManager().getPlugin("PermissionsEx");
if (pex != null)
{
nameBuilder.append(" PEX");
if (!pex.isEnabled())
{
nameBuilder.append('!');
}
nameBuilder.append(pex.getDescription().getVersion());
}
}
private static void addGroupManagerVersion(final Server server, final StringBuilder nameBuilder)
{
final Plugin groupManager = server.getPluginManager().getPlugin("GroupManager");
if (groupManager != null)
{
nameBuilder.append(" GM");
if (!groupManager.isEnabled())
{
nameBuilder.append('!');
}
}
}
private static void addEssentialsVersion(final Server server, final StringBuilder nameBuilder)
{
final Plugin essentials = server.getPluginManager().getPlugin("Essentials");
if (essentials != null)
{
nameBuilder.append(" ESS");
nameBuilder.append(essentials.getDescription().getVersion());
}
}
private static void addCraftBukkitVersion(final Server server, final StringBuilder nameBuilder)
{
final Matcher versionMatch = CB_PATTERN.matcher(server.getVersion());
if (versionMatch.matches())
{
nameBuilder.append(" CB");
nameBuilder.append(versionMatch.group(4));
}
}
}

View File

@ -1,112 +0,0 @@
package com.earth2me.essentials.update.states;
import com.earth2me.essentials.update.AbstractWorkListener;
import org.bukkit.entity.Player;
public abstract class AbstractState
{
private transient boolean abortion = false;
private final transient StateMap stateMap;
public AbstractState(final StateMap stateMap)
{
this.stateMap = stateMap;
}
public <T extends AbstractState> T getState(final Class<? extends T> stateClass)
{
if (!stateMap.containsKey(stateClass))
{
try
{
final AbstractState state = stateClass.getConstructor(StateMap.class).newInstance(stateMap);
stateMap.put(stateClass, state);
}
catch (Exception ex)
{
/*
* This should never happen. All states, that are added to the map automatically, have to have a
* Constructor that accepts the StateMap.
*/
throw new RuntimeException(ex);
}
}
return (T)stateMap.get(stateClass);
}
public abstract AbstractState getNextState();
/**
* Check if we already know the answer, so the user does not have to answer the question.
*
* @return true, if the answer could be guessed.
*/
public boolean guessAnswer()
{
return false;
}
/**
* Ask the user the question.
* @param sender
*/
public abstract void askQuestion(Player sender);
/**
* React on the answer and set internal variables
* @param answer
* @return true, if the answer could be recognized as a valid answer
*/
public abstract boolean reactOnAnswer(String answer);
public final AbstractState reactOnAnswer(final Player sender, final String answer)
{
final String trimmedAnswer = answer.trim();
if (trimmedAnswer.equalsIgnoreCase("quit")
|| trimmedAnswer.equalsIgnoreCase("bye")
|| trimmedAnswer.equalsIgnoreCase("abort")
|| trimmedAnswer.equalsIgnoreCase("cancel")
|| trimmedAnswer.equalsIgnoreCase("exit"))
{
abort();
return null;
}
try
{
final boolean found = reactOnAnswer(trimmedAnswer);
if (found)
{
return getNextState();
}
else
{
sender.sendMessage("Answer not recognized.");
return this;
}
}
catch (RuntimeException ex)
{
sender.sendMessage(ex.toString());
return this;
}
}
/**
* Do something based on the answer, that the user gave.
*/
public void doWork(final AbstractWorkListener listener)
{
listener.onWorkDone();
}
public boolean isAbortion()
{
return abortion;
}
protected void abort()
{
abortion = true;
}
}

View File

@ -1,57 +0,0 @@
package com.earth2me.essentials.update.states;
public abstract class AbstractYesNoState extends AbstractState
{
private boolean answer = false;
private final transient Class<? extends AbstractState> yesState;
private final transient Class<? extends AbstractState> noState;
public AbstractYesNoState(final StateMap states, final Class<? extends AbstractState> nextState)
{
this(states, nextState, nextState);
}
public AbstractYesNoState(final StateMap states, final Class<? extends AbstractState> yesState, final Class<? extends AbstractState> noState)
{
super(states);
this.yesState = yesState;
this.noState = noState;
}
@Override
public AbstractState getNextState()
{
return answer
? (yesState == null ? null : getState(yesState))
: (noState == null ? null : getState(noState));
}
@Override
public boolean reactOnAnswer(final String answer)
{
if (answer.equalsIgnoreCase("yes")
|| answer.equalsIgnoreCase("y"))
{
this.answer = true;
return true;
}
if (answer.equalsIgnoreCase("no")
|| answer.equalsIgnoreCase("n"))
{
this.answer = false;
return true;
}
return false;
}
public boolean getAnswer()
{
return answer;
}
protected void setAnswer(final boolean answer)
{
this.answer = answer;
}
}

View File

@ -1,20 +0,0 @@
package com.earth2me.essentials.update.states;
import org.bukkit.entity.Player;
public class AdvancedMode extends AbstractYesNoState
{
public AdvancedMode(final StateMap states)
{
super(states, EssentialsChat.class);
}
@Override
public void askQuestion(final Player sender)
{
sender.sendMessage("This installation mode has a lot of options.");
sender.sendMessage("Do you want use the advanced mode to see all questions?");
sender.sendMessage("Otherwise the default values will be used.");
}
}

View File

@ -1,91 +0,0 @@
package com.earth2me.essentials.update.states;
import com.earth2me.essentials.update.UpdateCheck;
import com.earth2me.essentials.update.VersionInfo;
import java.util.List;
import org.bukkit.entity.Player;
public class Changelog extends AbstractState
{
private static final int CHANGES_PER_PAGE = 5;
private transient int page = 0;
private transient boolean confirmed = false;
private transient final List<String> changes;
private transient final int pages;
public Changelog(final StateMap stateMap)
{
super(stateMap);
changes = getChanges();
pages = changes.size() / CHANGES_PER_PAGE + (changes.size() % CHANGES_PER_PAGE > 0 ? 1 : 0);
}
@Override
public AbstractState getNextState()
{
return confirmed ? getState(EssentialsChat.class) : this;
}
@Override
public boolean guessAnswer()
{
if (pages == 0)
{
confirmed = true;
}
return confirmed;
}
private List<String> getChanges()
{
final UpdateCheck updateCheck = getState(UpdateOrInstallation.class).getUpdateCheck();
final VersionInfo versionInfo = updateCheck.getNewVersionInfo();
return versionInfo.getChangelog();
}
@Override
public void askQuestion(final Player sender)
{
if (pages > 1)
{
sender.sendMessage("Changelog, page " + page + " of " + pages + ":");
}
else
{
sender.sendMessage("Changelog:");
}
for (int i = page * CHANGES_PER_PAGE; i < Math.min(page * CHANGES_PER_PAGE + CHANGES_PER_PAGE, changes.size()); i++)
{
sender.sendMessage(changes.get(i));
}
if (pages > 1)
{
sender.sendMessage("Select a page by typing the numbers 1 to " + pages + " to view all changes and then type confirm or abort.");
}
else
{
sender.sendMessage("Type confirm to update Essentials or abort to cancel the update.");
}
}
@Override
public boolean reactOnAnswer(final String answer)
{
if (answer.equalsIgnoreCase("confirm"))
{
confirmed = true;
return true;
}
if (answer.matches("[0-9]+"))
{
final int page = Integer.parseInt(answer);
if (page <= pages && page > 0)
{
this.page = page - 1;
return true;
}
}
return false;
}
}

View File

@ -1,47 +0,0 @@
package com.earth2me.essentials.update.states;
import com.earth2me.essentials.update.AbstractWorkListener;
import com.earth2me.essentials.update.tasks.InstallModule;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public class EssentialsChat extends AbstractYesNoState
{
public EssentialsChat(final StateMap states)
{
super(states, EssentialsChatSettings.class, EssentialsSpawn.class);
}
@Override
public boolean guessAnswer()
{
final Plugin plugin = Bukkit.getPluginManager().getPlugin("EssentialsChat");
if (plugin != null)
{
setAnswer(true);
return true;
}
return false;
}
@Override
public void askQuestion(final Player sender)
{
sender.sendMessage("Do you want to install EssentialsChat? (yes/no)");
sender.sendMessage("EssentialsChat is a simple chat formatting plugin");
sender.sendMessage("It allows you to make user prefixes and coloured text.");
}
@Override
public void doWork(final AbstractWorkListener listener)
{
if (getAnswer())
{
new InstallModule(listener, "EssentialsChat").start();
return;
}
listener.onWorkDone();
}
}

View File

@ -1,29 +0,0 @@
package com.earth2me.essentials.update.states;
import org.bukkit.entity.Player;
public class EssentialsChatSettings extends AbstractYesNoState
{
public EssentialsChatSettings(final StateMap states)
{
super(states, EssentialsSpawn.class);
}
@Override
public boolean guessAnswer()
{
if (getState(AdvancedMode.class).getAnswer())
{
setAnswer(false);
return true;
}
return false;
}
@Override
public void askQuestion(final Player sender)
{
sender.sendMessage("Would you like to configure EssentialsChat to prefix ingame messages with their group?");
}
}

View File

@ -1,47 +0,0 @@
package com.earth2me.essentials.update.states;
import com.earth2me.essentials.update.AbstractWorkListener;
import com.earth2me.essentials.update.tasks.InstallModule;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public class EssentialsGeoIP extends AbstractYesNoState
{
public EssentialsGeoIP(final StateMap states)
{
super(states, null);
}
@Override
public boolean guessAnswer()
{
final Plugin plugin = Bukkit.getPluginManager().getPlugin("EssentialsGeoIP");
if (plugin != null)
{
setAnswer(true);
return true;
}
return false;
}
@Override
public void askQuestion(final Player sender)
{
sender.sendMessage("Do you want to install EssentialsGeoIP? (yes/no)");
sender.sendMessage("EssentialsGeoIP performs a IP lookup on joining players");
sender.sendMessage("It allows you get a rough idea of where a player is from.");
}
@Override
public void doWork(final AbstractWorkListener listener)
{
if (getAnswer())
{
new InstallModule(listener, "EssentialsGeoIP").start();
return;
}
listener.onWorkDone();
}
}

View File

@ -1,47 +0,0 @@
package com.earth2me.essentials.update.states;
import com.earth2me.essentials.update.AbstractWorkListener;
import com.earth2me.essentials.update.tasks.InstallModule;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public class EssentialsProtect extends AbstractYesNoState
{
public EssentialsProtect(final StateMap states)
{
super(states, null);
}
@Override
public boolean guessAnswer()
{
final Plugin plugin = Bukkit.getPluginManager().getPlugin("EssentialsProtect");
if (plugin != null)
{
setAnswer(true);
return true;
}
return false;
}
@Override
public void askQuestion(final Player sender)
{
sender.sendMessage("Do you want to install EssentialsProtect? (yes/no)");
sender.sendMessage("EssentialsProtect is a basic world protection system");
sender.sendMessage("It allows you to set server wide rules, such as disabling creeper explosions, and preventing fire spread.");
}
@Override
public void doWork(final AbstractWorkListener listener)
{
if (getAnswer())
{
new InstallModule(listener, "EssentialsProtect").start();
return;
}
listener.onWorkDone();
}
}

View File

@ -1,47 +0,0 @@
package com.earth2me.essentials.update.states;
import com.earth2me.essentials.update.AbstractWorkListener;
import com.earth2me.essentials.update.tasks.InstallModule;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public class EssentialsSpawn extends AbstractYesNoState
{
public EssentialsSpawn(final StateMap states)
{
super(states, null);
}
@Override
public boolean guessAnswer()
{
final Plugin plugin = Bukkit.getPluginManager().getPlugin("EssentialsSpawn");
if (plugin != null)
{
setAnswer(true);
return true;
}
return false;
}
@Override
public void askQuestion(final Player sender)
{
sender.sendMessage("Do you want to install EssentialsSpawn? (yes/no)");
sender.sendMessage("EssentialsSpawn lets you control player spawning");
sender.sendMessage("It allows you to set different places where players spawn on death, new players join and allows players to return to spawn.");
}
@Override
public void doWork(final AbstractWorkListener listener)
{
if (getAnswer())
{
new InstallModule(listener, "EssentialsSpawn").start();
return;
}
listener.onWorkDone();
}
}

View File

@ -1,19 +0,0 @@
package com.earth2me.essentials.update.states;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
public class InstallationFinishedEvent extends Event
{
public InstallationFinishedEvent()
{
super();
}
@Override
public HandlerList getHandlers()
{
throw new UnsupportedOperationException("Not supported yet.");
}
}

View File

@ -1,183 +0,0 @@
package com.earth2me.essentials.update.states;
import com.earth2me.essentials.update.AbstractWorkListener;
import com.earth2me.essentials.update.UpdateCheck;
import java.util.Iterator;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public class StateMachine extends AbstractWorkListener implements Runnable
{
public enum MachineResult
{
ABORT, WAIT, DONE, NONE
}
private final transient StateMap states = new StateMap();
private transient AbstractState current;
private transient Player player;
private transient MachineResult result = MachineResult.NONE;
public StateMachine(final Plugin plugin, final Player player, final UpdateCheck updateCheck)
{
super(plugin, updateCheck.getNewVersionInfo());
this.player = player;
states.clear();
final UpdateOrInstallation state = new UpdateOrInstallation(states, updateCheck);
current = states.put(UpdateOrInstallation.class, state);
}
public MachineResult askQuestion()
{
try
{
while (current.guessAnswer())
{
current = current.getNextState();
if (current == null)
{
result = MachineResult.DONE;
break;
}
}
if (current != null)
{
if (player.isOnline())
{
current.askQuestion(player);
}
result = MachineResult.WAIT;
}
}
catch (RuntimeException ex)
{
player.sendMessage(ex.getMessage());
finish();
result = MachineResult.ABORT;
}
return result;
}
public MachineResult reactOnMessage(final String message)
{
result = MachineResult.NONE;
final AbstractState next = current.reactOnAnswer(player, message);
if (next == null)
{
if (current.isAbortion())
{
finish();
result = MachineResult.ABORT;
}
else
{
result = MachineResult.DONE;
}
}
else
{
current = next;
askQuestion();
}
return result;
}
private transient Iterator<AbstractState> iterator;
public void startWork()
{
iterator = states.values().iterator();
Bukkit.getScheduler().scheduleAsyncDelayedTask(getPlugin(), this);
}
@Override
public void run()
{
if (!iterator.hasNext())
{
Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), new Runnable()
{
@Override
public void run()
{
if (StateMachine.this.player.isOnline())
{
StateMachine.this.player.sendMessage("Installation done. Reloading server.");
}
finish();
Bukkit.getServer().reload();
}
});
return;
}
final AbstractState state = iterator.next();
state.doWork(this);
}
@Override
public void onWorkAbort(final String message)
{
finish();
Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), new Runnable()
{
@Override
public void run()
{
if (message != null && !message.isEmpty() && StateMachine.this.player.isOnline())
{
StateMachine.this.player.sendMessage(message);
}
}
});
}
@Override
public void onWorkDone(final String message)
{
Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), new Runnable()
{
@Override
public void run()
{
if (message != null && !message.isEmpty() && StateMachine.this.player.isOnline())
{
StateMachine.this.player.sendMessage(message);
}
Bukkit.getScheduler().scheduleAsyncDelayedTask(getPlugin(), StateMachine.this);
}
});
}
private void finish()
{
current = null;
iterator = null;
states.clear();
getPlugin().getServer().getPluginManager().callEvent(new InstallationFinishedEvent());
}
public void resumeInstallation(final Player player)
{
this.player = player;
if (result == MachineResult.WAIT)
{
if (current == null)
{
throw new RuntimeException("State is WAIT, but current state is null!");
}
current.askQuestion(player);
}
if (result == MachineResult.DONE && iterator != null)
{
player.sendMessage("Installation is still running.");
}
if (result == MachineResult.ABORT)
{
throw new RuntimeException("Player should not be able to resume an aborted installation.");
}
if (result == MachineResult.NONE)
{
throw new RuntimeException("State machine in an undefined state.");
}
}
}

View File

@ -1,12 +0,0 @@
package com.earth2me.essentials.update.states;
import java.util.LinkedHashMap;
public class StateMap extends LinkedHashMap<Class<? extends AbstractState>, AbstractState>
{
public StateMap()
{
super(50);
}
}

View File

@ -1,60 +0,0 @@
package com.earth2me.essentials.update.states;
import com.earth2me.essentials.update.UpdateCheck;
import org.bukkit.entity.Player;
public class UpdateOrInstallation extends AbstractState
{
private final transient UpdateCheck updateCheck;
private transient boolean update = false;
public UpdateOrInstallation(final StateMap stateMap, final UpdateCheck updateCheck)
{
super(stateMap);
this.updateCheck = updateCheck;
}
@Override
public boolean guessAnswer()
{
if (getUpdateCheck().isEssentialsInstalled())
{
update = true;
}
return update;
}
@Override
public AbstractState getNextState()
{
return update ? getState(Changelog.class) : getState(EssentialsChat.class);
}
@Override
public void askQuestion(final Player sender)
{
sender.sendMessage("Thank you for choosing Essentials.");
sender.sendMessage("The following installation wizard will guide you through the installation of Essentials.");
sender.sendMessage("Your answers will be saved for a later update.");
sender.sendMessage("Please answer the messages with yes or no, if not otherwise stated.");
sender.sendMessage("Write bye/exit/quit if you want to exit the wizard at anytime.");
sender.sendMessage("Type ok to continue...");
}
@Override
public boolean reactOnAnswer(final String answer)
{
return answer.equalsIgnoreCase("ok") || answer.equalsIgnoreCase("k") || answer.equalsIgnoreCase("continue");
}
public UpdateCheck getUpdateCheck()
{
return updateCheck;
}
public boolean isUpdate()
{
return update;
}
}

View File

@ -1,61 +0,0 @@
package com.earth2me.essentials.update.tasks;
import com.earth2me.essentials.update.AbstractWorkListener;
import com.earth2me.essentials.update.GetFile;
import com.earth2me.essentials.update.ModuleInfo;
import com.earth2me.essentials.update.VersionInfo;
import java.io.File;
import java.net.URL;
import java.util.logging.Level;
import org.bukkit.Bukkit;
public class InstallModule implements Runnable, Task
{
protected final transient AbstractWorkListener listener;
private final transient String moduleName;
private final transient String fileName;
public InstallModule(final AbstractWorkListener listener, final String moduleName)
{
this(listener, moduleName, moduleName + ".jar");
}
public InstallModule(final AbstractWorkListener listener, final String moduleName, final String fileName)
{
this.listener = listener;
this.moduleName = moduleName;
this.fileName = fileName;
}
@Override
public void start()
{
Bukkit.getScheduler().scheduleAsyncDelayedTask(listener.getPlugin(), this);
}
@Override
public void run()
{
final VersionInfo info = listener.getNewVersionInfo();
final ModuleInfo module = info.getModules().get(moduleName);
if (module == null)
{
listener.onWorkAbort("Module " + moduleName + " not found in VersionInfo.");
return;
}
try
{
final URL downloadUrl = module.getUrl();
final GetFile getFile = new GetFile(downloadUrl);
getFile.saveTo(new File(listener.getPlugin().getServer().getUpdateFolderFile(), fileName), module.getHash());
listener.onWorkDone("Module " + moduleName + " downloaded.");
}
catch (Exception ex)
{
Bukkit.getLogger().log(Level.SEVERE, "Failed to download module " + moduleName + " to " + fileName, ex);
listener.onWorkAbort("An error occured, please check your server log.");
return;
}
}
}

View File

@ -1,55 +0,0 @@
package com.earth2me.essentials.update.tasks;
import com.earth2me.essentials.update.AbstractWorkListener;
import org.bukkit.Bukkit;
public class SelfUpdate extends AbstractWorkListener implements Task, Runnable
{
private final transient AbstractWorkListener listener;
public SelfUpdate(final AbstractWorkListener listener)
{
super(listener.getPlugin(), listener.getNewVersionInfo());
this.listener = listener;
}
@Override
public void onWorkAbort(final String message)
{
listener.onWorkAbort(message);
}
@Override
public void onWorkDone(final String message)
{
listener.onWorkDone(message);
Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), new Runnable()
{
@Override
public void run()
{
Bukkit.getServer().reload();
}
});
}
@Override
public void start()
{
Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), this);
}
@Override
public void run()
{
Bukkit.getScheduler().scheduleAsyncDelayedTask(getPlugin(), new Runnable()
{
@Override
public void run()
{
new InstallModule(SelfUpdate.this, "EssentialsUpdate").start();
}
});
}
}

View File

@ -1,7 +0,0 @@
package com.earth2me.essentials.update.tasks;
public interface Task
{
void start();
}

View File

@ -1,293 +0,0 @@
/*
Copyright Paul James Mutton, 2001-2009, http://www.jibble.org/
This file is part of PircBot.
This software is dual-licensed, allowing you to choose between the GNU
General Public License (GPL) and the www.jibble.org Commercial License.
Since the GPL may be too restrictive for use in a proprietary application,
a commercial license is also provided. Full license information can be
found at http://www.jibble.org/licenses/
*/
package org.jibble.pircbot;
/**
* The Colors class provides several static fields and methods that you may
* find useful when writing an IRC Bot.
* <p>
* This class contains constants that are useful for formatting lines
* sent to IRC servers. These constants allow you to apply various
* formatting to the lines, such as colours, boldness, underlining
* and reverse text.
* <p>
* The class contains static methods to remove colours and formatting
* from lines of IRC text.
* <p>
* Here are some examples of how to use the contants from within a
* class that extends PircBot and imports org.jibble.pircbot.*;
*
* <pre> sendMessage("#cs", Colors.BOLD + "A bold hello!");
* <b>A bold hello!</b>
* sendMessage("#cs", Colors.RED + "Red" + Colors.NORMAL + " text");
* <font color="red">Red</font> text
* sendMessage("#cs", Colors.BOLD + Colors.RED + "Bold and red");
* <b><font color="red">Bold and red</font></b></pre>
*
* Please note that some IRC channels may be configured to reject any
* messages that use colours. Also note that older IRC clients may be
* unable to correctly display lines that contain colours and other
* control characters.
* <p>
* Note that this class name has been spelt in the American style in
* order to remain consistent with the rest of the Java API.
*
*
* @since 0.9.12
* @author Paul James Mutton,
* <a href="http://www.jibble.org/">http://www.jibble.org/</a>
* @version 1.5.0 (Build time: Mon Dec 14 20:07:17 2009)
*/
public class Colors {
/**
* Removes all previously applied color and formatting attributes.
*/
public static final String NORMAL = "\u000f";
/**
* Bold text.
*/
public static final String BOLD = "\u0002";
/**
* Underlined text.
*/
public static final String UNDERLINE = "\u001f";
/**
* Reversed text (may be rendered as italic text in some clients).
*/
public static final String REVERSE = "\u0016";
/**
* White coloured text.
*/
public static final String WHITE = "\u000300";
/**
* Black coloured text.
*/
public static final String BLACK = "\u000301";
/**
* Dark blue coloured text.
*/
public static final String DARK_BLUE = "\u000302";
/**
* Dark green coloured text.
*/
public static final String DARK_GREEN = "\u000303";
/**
* Red coloured text.
*/
public static final String RED = "\u000304";
/**
* Brown coloured text.
*/
public static final String BROWN = "\u000305";
/**
* Purple coloured text.
*/
public static final String PURPLE = "\u000306";
/**
* Olive coloured text.
*/
public static final String OLIVE = "\u000307";
/**
* Yellow coloured text.
*/
public static final String YELLOW = "\u000308";
/**
* Green coloured text.
*/
public static final String GREEN = "\u000309";
/**
* Teal coloured text.
*/
public static final String TEAL = "\u000310";
/**
* Cyan coloured text.
*/
public static final String CYAN = "\u000311";
/**
* Blue coloured text.
*/
public static final String BLUE = "\u000312";
/**
* Magenta coloured text.
*/
public static final String MAGENTA = "\u000313";
/**
* Dark gray coloured text.
*/
public static final String DARK_GRAY = "\u000314";
/**
* Light gray coloured text.
*/
public static final String LIGHT_GRAY = "\u000315";
/**
* This class should not be constructed.
*/
private Colors() {
}
/**
* Removes all colours from a line of IRC text.
*
* @since PircBot 1.2.0
*
* @param line the input text.
*
* @return the same text, but with all colours removed.
*/
public static String removeColors(String line) {
int length = line.length();
StringBuffer buffer = new StringBuffer();
int i = 0;
while (i < length) {
char ch = line.charAt(i);
if (ch == '\u0003') {
i++;
// Skip "x" or "xy" (foreground color).
if (i < length) {
ch = line.charAt(i);
if (Character.isDigit(ch)) {
i++;
if (i < length) {
ch = line.charAt(i);
if (Character.isDigit(ch)) {
i++;
}
}
// Now skip ",x" or ",xy" (background color).
if (i < length) {
ch = line.charAt(i);
if (ch == ',') {
i++;
if (i < length) {
ch = line.charAt(i);
if (Character.isDigit(ch)) {
i++;
if (i < length) {
ch = line.charAt(i);
if (Character.isDigit(ch)) {
i++;
}
}
}
else {
// Keep the comma.
i--;
}
}
else {
// Keep the comma.
i--;
}
}
}
}
}
}
else if (ch == '\u000f') {
i++;
}
else {
buffer.append(ch);
i++;
}
}
return buffer.toString();
}
/**
* Remove formatting from a line of IRC text.
*
* @since PircBot 1.2.0
*
* @param line the input text.
*
* @return the same text, but without any bold, underlining, reverse, etc.
*/
public static String removeFormatting(String line) {
int length = line.length();
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < length; i++) {
char ch = line.charAt(i);
if (ch == '\u000f' || ch == '\u0002' || ch == '\u001f' || ch == '\u0016') {
// Don't add this character.
}
else {
buffer.append(ch);
}
}
return buffer.toString();
}
/**
* Removes all formatting and colours from a line of IRC text.
*
* @since PircBot 1.2.0
*
* @param line the input text.
*
* @return the same text, but without formatting and colour characters.
*
*/
public static String removeFormattingAndColors(String line) {
return removeFormatting(removeColors(line));
}
}

View File

@ -1,169 +0,0 @@
/*
Copyright Paul James Mutton, 2001-2009, http://www.jibble.org/
This file is part of PircBot.
This software is dual-licensed, allowing you to choose between the GNU
General Public License (GPL) and the www.jibble.org Commercial License.
Since the GPL may be too restrictive for use in a proprietary application,
a commercial license is also provided. Full license information can be
found at http://www.jibble.org/licenses/
*/
package org.jibble.pircbot;
import java.io.*;
import java.net.Socket;
import java.util.StringTokenizer;
/**
* A Thread which reads lines from the IRC server. It then
* passes these lines to the PircBot without changing them.
* This running Thread also detects disconnection from the server
* and is thus used by the OutputThread to send lines to the server.
*
* @author Paul James Mutton,
* <a href="http://www.jibble.org/">http://www.jibble.org/</a>
* @version 1.5.0 (Build time: Mon Dec 14 20:07:17 2009)
*/
public class InputThread extends Thread {
/**
* The InputThread reads lines from the IRC server and allows the
* PircBot to handle them.
*
* @param bot An instance of the underlying PircBot.
* @param breader The BufferedReader that reads lines from the server.
* @param bwriter The BufferedWriter that sends lines to the server.
*/
InputThread(PircBot bot, Socket socket, BufferedReader breader, BufferedWriter bwriter) {
_bot = bot;
_socket = socket;
_breader = breader;
_bwriter = bwriter;
this.setName(this.getClass() + "-Thread");
}
/**
* Sends a raw line to the IRC server as soon as possible, bypassing the
* outgoing message queue.
*
* @param line The raw line to send to the IRC server.
*/
void sendRawLine(String line) {
OutputThread.sendRawLine(_bot, _bwriter, line);
}
/**
* Returns true if this InputThread is connected to an IRC server.
* The result of this method should only act as a rough guide,
* as the result may not be valid by the time you act upon it.
*
* @return True if still connected.
*/
boolean isConnected() {
return _isConnected;
}
/**
* Called to start this Thread reading lines from the IRC server.
* When a line is read, this method calls the handleLine method
* in the PircBot, which may subsequently call an 'onXxx' method
* in the PircBot subclass. If any subclass of Throwable (i.e.
* any Exception or Error) is thrown by your method, then this
* method will print the stack trace to the standard output. It
* is probable that the PircBot may still be functioning normally
* after such a problem, but the existance of any uncaught exceptions
* in your code is something you should really fix.
*/
public void run() {
try {
boolean running = true;
while (running) {
try {
String line = null;
while ((line = _breader.readLine()) != null) {
try {
_bot.handleLine(line);
}
catch (Throwable t) {
// Stick the whole stack trace into a String so we can output it nicely.
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
pw.flush();
StringTokenizer tokenizer = new StringTokenizer(sw.toString(), "\r\n");
synchronized (_bot) {
_bot.log("### Your implementation of PircBot is faulty and you have");
_bot.log("### allowed an uncaught Exception or Error to propagate in your");
_bot.log("### code. It may be possible for PircBot to continue operating");
_bot.log("### normally. Here is the stack trace that was produced: -");
_bot.log("### ");
while (tokenizer.hasMoreTokens()) {
_bot.log("### " + tokenizer.nextToken());
}
}
}
}
if (line == null) {
// The server must have disconnected us.
running = false;
}
}
catch (InterruptedIOException iioe) {
// This will happen if we haven't received anything from the server for a while.
// So we shall send it a ping to check that we are still connected.
this.sendRawLine("PING " + (System.currentTimeMillis() / 1000));
// Now we go back to listening for stuff from the server...
}
}
}
catch (Exception e) {
// Do nothing.
}
// If we reach this point, then we must have disconnected.
try {
_socket.close();
}
catch (Exception e) {
// Just assume the socket was already closed.
}
if (!_disposed) {
_bot.log("*** Disconnected.");
_isConnected = false;
_bot.onDisconnect();
}
}
/**
* Closes the socket without onDisconnect being called subsequently.
*/
public void dispose () {
try {
_disposed = true;
_socket.close();
}
catch (Exception e) {
// Do nothing.
}
}
private PircBot _bot = null;
private Socket _socket = null;
private BufferedReader _breader = null;
private BufferedWriter _bwriter = null;
private boolean _isConnected = true;
private boolean _disposed = false;
public static final int MAX_LINE_LENGTH = 512;
}

View File

@ -1,35 +0,0 @@
/*
Copyright Paul James Mutton, 2001-2009, http://www.jibble.org/
This file is part of PircBot.
This software is dual-licensed, allowing you to choose between the GNU
General Public License (GPL) and the www.jibble.org Commercial License.
Since the GPL may be too restrictive for use in a proprietary application,
a commercial license is also provided. Full license information can be
found at http://www.jibble.org/licenses/
*/
package org.jibble.pircbot;
/**
* An IrcException class.
*
* @since 0.9
* @author Paul James Mutton,
* <a href="http://www.jibble.org/">http://www.jibble.org/</a>
* @version 1.5.0 (Build time: Mon Dec 14 20:07:17 2009)
*/
public class IrcException extends Exception {
/**
* Constructs a new IrcException.
*
* @param e The error message to report.
*/
public IrcException(String e) {
super(e);
}
}

View File

@ -1,38 +0,0 @@
/*
Copyright Paul James Mutton, 2001-2009, http://www.jibble.org/
This file is part of PircBot.
This software is dual-licensed, allowing you to choose between the GNU
General Public License (GPL) and the www.jibble.org Commercial License.
Since the GPL may be too restrictive for use in a proprietary application,
a commercial license is also provided. Full license information can be
found at http://www.jibble.org/licenses/
*/
package org.jibble.pircbot;
/**
* A NickAlreadyInUseException class. This exception is
* thrown when the PircBot attempts to join an IRC server
* with a user name that is already in use.
*
* @since 0.9
* @author Paul James Mutton,
* <a href="http://www.jibble.org/">http://www.jibble.org/</a>
* @version 1.5.0 (Build time: Mon Dec 14 20:07:17 2009)
*/
public class NickAlreadyInUseException extends IrcException {
/**
* Constructs a new IrcException.
*
* @param e The error message to report.
*/
public NickAlreadyInUseException(String e) {
super(e);
}
}

View File

@ -1,104 +0,0 @@
/*
Copyright Paul James Mutton, 2001-2009, http://www.jibble.org/
This file is part of PircBot.
This software is dual-licensed, allowing you to choose between the GNU
General Public License (GPL) and the www.jibble.org Commercial License.
Since the GPL may be too restrictive for use in a proprietary application,
a commercial license is also provided. Full license information can be
found at http://www.jibble.org/licenses/
*/
package org.jibble.pircbot;
import java.io.BufferedWriter;
/**
* A Thread which is responsible for sending messages to the IRC server.
* Messages are obtained from the outgoing message queue and sent
* immediately if possible. If there is a flood of messages, then to
* avoid getting kicked from a channel, we put a small delay between
* each one.
*
* @author Paul James Mutton,
* <a href="http://www.jibble.org/">http://www.jibble.org/</a>
* @version 1.5.0 (Build time: Mon Dec 14 20:07:17 2009)
*/
public class OutputThread extends Thread {
/**
* Constructs an OutputThread for the underlying PircBot. All messages
* sent to the IRC server are sent by this OutputThread to avoid hammering
* the server. Messages are sent immediately if possible. If there are
* multiple messages queued, then there is a delay imposed.
*
* @param bot The underlying PircBot instance.
* @param outQueue The Queue from which we will obtain our messages.
*/
OutputThread(PircBot bot, Queue outQueue) {
_bot = bot;
_outQueue = outQueue;
this.setName(this.getClass() + "-Thread");
}
/**
* A static method to write a line to a BufferedOutputStream and then pass
* the line to the log method of the supplied PircBot instance.
*
* @param bot The underlying PircBot instance.
* @param out The BufferedOutputStream to write to.
* @param line The line to be written. "\r\n" is appended to the end.
* @param encoding The charset to use when encoing this string into a
* byte array.
*/
static void sendRawLine(PircBot bot, BufferedWriter bwriter, String line) {
if (line.length() > bot.getMaxLineLength() - 2) {
line = line.substring(0, bot.getMaxLineLength() - 2);
}
synchronized(bwriter) {
try {
bwriter.write(line + "\r\n");
bwriter.flush();
bot.log(">>>" + line);
}
catch (Exception e) {
// Silent response - just lose the line.
}
}
}
/**
* This method starts the Thread consuming from the outgoing message
* Queue and sending lines to the server.
*/
public void run() {
try {
boolean running = true;
while (running) {
// Small delay to prevent spamming of the channel
Thread.sleep(_bot.getMessageDelay());
String line = (String) _outQueue.next();
if (line != null) {
_bot.sendRawLine(line);
}
else {
running = false;
}
}
}
catch (InterruptedException e) {
// Just let the method return naturally...
}
}
private PircBot _bot = null;
private Queue _outQueue = null;
}

File diff suppressed because it is too large Load Diff

View File

@ -1,146 +0,0 @@
/*
Copyright Paul James Mutton, 2001-2009, http://www.jibble.org/
This file is part of PircBot.
This software is dual-licensed, allowing you to choose between the GNU
General Public License (GPL) and the www.jibble.org Commercial License.
Since the GPL may be too restrictive for use in a proprietary application,
a commercial license is also provided. Full license information can be
found at http://www.jibble.org/licenses/
*/
package org.jibble.pircbot;
import java.util.Vector;
/**
* Queue is a definition of a data structure that may
* act as a queue - that is, data can be added to one end of the
* queue and data can be requested from the head end of the queue.
* This class is thread safe for multiple producers and a single
* consumer. The next() method will block until there is data in
* the queue.
*
* This has now been modified so that it is compatible with
* the earlier JDK1.1 in order to be suitable for running on
* mobile appliances. This means replacing the LinkedList with
* a Vector, which is hardly ideal, but this Queue is typically
* only polled every second before dispatching messages.
*
* @author Paul James Mutton,
* <a href="http://www.jibble.org/">http://www.jibble.org/</a>
* @version 1.5.0 (Build time: Mon Dec 14 20:07:17 2009)
*/
public class Queue {
/**
* Constructs a Queue object of unlimited size.
*/
public Queue() {
}
/**
* Adds an Object to the end of the Queue.
*
* @param o The Object to be added to the Queue.
*/
public void add(Object o) {
synchronized(_queue) {
_queue.addElement(o);
_queue.notify();
}
}
/**
* Adds an Object to the front of the Queue.
*
* @param o The Object to be added to the Queue.
*/
public void addFront(Object o) {
synchronized(_queue) {
_queue.insertElementAt(o, 0);
_queue.notify();
}
}
/**
* Returns the Object at the front of the Queue. This
* Object is then removed from the Queue. If the Queue
* is empty, then this method shall block until there
* is an Object in the Queue to return.
*
* @return The next item from the front of the queue.
*/
public Object next() {
Object o = null;
// Block if the Queue is empty.
synchronized(_queue) {
if (_queue.size() == 0) {
try {
_queue.wait();
}
catch (InterruptedException e) {
return null;
}
}
// Return the Object.
try {
o = _queue.firstElement();
_queue.removeElementAt(0);
}
catch (ArrayIndexOutOfBoundsException e) {
throw new InternalError("Race hazard in Queue object.");
}
}
return o;
}
/**
* Returns true if the Queue is not empty. If another
* Thread empties the Queue before <b>next()</b> is
* called, then the call to <b>next()</b> shall block
* until the Queue has been populated again.
*
* @return True only if the Queue not empty.
*/
public boolean hasNext() {
return (this.size() != 0);
}
/**
* Clears the contents of the Queue.
*/
public void clear() {
synchronized(_queue) {
_queue.removeAllElements();
}
}
/**
* Returns the size of the Queue.
*
* @return The current size of the queue.
*/
public int size() {
return _queue.size();
}
private Vector _queue = new Vector();
}

View File

@ -1,176 +0,0 @@
/*
Copyright Paul James Mutton, 2001-2009, http://www.jibble.org/
This file is part of PircBot.
This software is dual-licensed, allowing you to choose between the GNU
General Public License (GPL) and the www.jibble.org Commercial License.
Since the GPL may be too restrictive for use in a proprietary application,
a commercial license is also provided. Full license information can be
found at http://www.jibble.org/licenses/
*/
package org.jibble.pircbot;
/**
* This interface contains the values of all numeric replies specified
* in section 6 of RFC 1459. Refer to RFC 1459 for further information.
* <p>
* If you override the onServerResponse method in the PircBot class,
* you may find these constants useful when comparing the numeric
* value of a given code.
*
* @since 1.0.0
* @author Paul James Mutton,
* <a href="http://www.jibble.org/">http://www.jibble.org/</a>
* @version 1.5.0 (Build time: Mon Dec 14 20:07:17 2009)
*/
public interface ReplyConstants {
// Error Replies.
public static final int ERR_NOSUCHNICK = 401;
public static final int ERR_NOSUCHSERVER = 402;
public static final int ERR_NOSUCHCHANNEL = 403;
public static final int ERR_CANNOTSENDTOCHAN = 404;
public static final int ERR_TOOMANYCHANNELS = 405;
public static final int ERR_WASNOSUCHNICK = 406;
public static final int ERR_TOOMANYTARGETS = 407;
public static final int ERR_NOORIGIN = 409;
public static final int ERR_NORECIPIENT = 411;
public static final int ERR_NOTEXTTOSEND = 412;
public static final int ERR_NOTOPLEVEL = 413;
public static final int ERR_WILDTOPLEVEL = 414;
public static final int ERR_UNKNOWNCOMMAND = 421;
public static final int ERR_NOMOTD = 422;
public static final int ERR_NOADMININFO = 423;
public static final int ERR_FILEERROR = 424;
public static final int ERR_NONICKNAMEGIVEN = 431;
public static final int ERR_ERRONEUSNICKNAME = 432;
public static final int ERR_NICKNAMEINUSE = 433;
public static final int ERR_NICKCOLLISION = 436;
public static final int ERR_USERNOTINCHANNEL = 441;
public static final int ERR_NOTONCHANNEL = 442;
public static final int ERR_USERONCHANNEL = 443;
public static final int ERR_NOLOGIN = 444;
public static final int ERR_SUMMONDISABLED = 445;
public static final int ERR_USERSDISABLED = 446;
public static final int ERR_NOTREGISTERED = 451;
public static final int ERR_NEEDMOREPARAMS = 461;
public static final int ERR_ALREADYREGISTRED = 462;
public static final int ERR_NOPERMFORHOST = 463;
public static final int ERR_PASSWDMISMATCH = 464;
public static final int ERR_YOUREBANNEDCREEP = 465;
public static final int ERR_KEYSET = 467;
public static final int ERR_CHANNELISFULL = 471;
public static final int ERR_UNKNOWNMODE = 472;
public static final int ERR_INVITEONLYCHAN = 473;
public static final int ERR_BANNEDFROMCHAN = 474;
public static final int ERR_BADCHANNELKEY = 475;
public static final int ERR_NOPRIVILEGES = 481;
public static final int ERR_CHANOPRIVSNEEDED = 482;
public static final int ERR_CANTKILLSERVER = 483;
public static final int ERR_NOOPERHOST = 491;
public static final int ERR_UMODEUNKNOWNFLAG = 501;
public static final int ERR_USERSDONTMATCH = 502;
// Command Responses.
public static final int RPL_TRACELINK = 200;
public static final int RPL_TRACECONNECTING = 201;
public static final int RPL_TRACEHANDSHAKE = 202;
public static final int RPL_TRACEUNKNOWN = 203;
public static final int RPL_TRACEOPERATOR = 204;
public static final int RPL_TRACEUSER = 205;
public static final int RPL_TRACESERVER = 206;
public static final int RPL_TRACENEWTYPE = 208;
public static final int RPL_STATSLINKINFO = 211;
public static final int RPL_STATSCOMMANDS = 212;
public static final int RPL_STATSCLINE = 213;
public static final int RPL_STATSNLINE = 214;
public static final int RPL_STATSILINE = 215;
public static final int RPL_STATSKLINE = 216;
public static final int RPL_STATSYLINE = 218;
public static final int RPL_ENDOFSTATS = 219;
public static final int RPL_UMODEIS = 221;
public static final int RPL_STATSLLINE = 241;
public static final int RPL_STATSUPTIME = 242;
public static final int RPL_STATSOLINE = 243;
public static final int RPL_STATSHLINE = 244;
public static final int RPL_LUSERCLIENT = 251;
public static final int RPL_LUSEROP = 252;
public static final int RPL_LUSERUNKNOWN = 253;
public static final int RPL_LUSERCHANNELS = 254;
public static final int RPL_LUSERME = 255;
public static final int RPL_ADMINME = 256;
public static final int RPL_ADMINLOC1 = 257;
public static final int RPL_ADMINLOC2 = 258;
public static final int RPL_ADMINEMAIL = 259;
public static final int RPL_TRACELOG = 261;
public static final int RPL_NONE = 300;
public static final int RPL_AWAY = 301;
public static final int RPL_USERHOST = 302;
public static final int RPL_ISON = 303;
public static final int RPL_UNAWAY = 305;
public static final int RPL_NOWAWAY = 306;
public static final int RPL_WHOISUSER = 311;
public static final int RPL_WHOISSERVER = 312;
public static final int RPL_WHOISOPERATOR = 313;
public static final int RPL_WHOWASUSER = 314;
public static final int RPL_ENDOFWHO = 315;
public static final int RPL_WHOISIDLE = 317;
public static final int RPL_ENDOFWHOIS = 318;
public static final int RPL_WHOISCHANNELS = 319;
public static final int RPL_LISTSTART = 321;
public static final int RPL_LIST = 322;
public static final int RPL_LISTEND = 323;
public static final int RPL_CHANNELMODEIS = 324;
public static final int RPL_NOTOPIC = 331;
public static final int RPL_TOPIC = 332;
public static final int RPL_TOPICINFO = 333;
public static final int RPL_INVITING = 341;
public static final int RPL_SUMMONING = 342;
public static final int RPL_VERSION = 351;
public static final int RPL_WHOREPLY = 352;
public static final int RPL_NAMREPLY = 353;
public static final int RPL_LINKS = 364;
public static final int RPL_ENDOFLINKS = 365;
public static final int RPL_ENDOFNAMES = 366;
public static final int RPL_BANLIST = 367;
public static final int RPL_ENDOFBANLIST = 368;
public static final int RPL_ENDOFWHOWAS = 369;
public static final int RPL_INFO = 371;
public static final int RPL_MOTD = 372;
public static final int RPL_ENDOFINFO = 374;
public static final int RPL_MOTDSTART = 375;
public static final int RPL_ENDOFMOTD = 376;
public static final int RPL_YOUREOPER = 381;
public static final int RPL_REHASHING = 382;
public static final int RPL_TIME = 391;
public static final int RPL_USERSSTART = 392;
public static final int RPL_USERS = 393;
public static final int RPL_ENDOFUSERS = 394;
public static final int RPL_NOUSERS = 395;
// Reserved Numerics.
public static final int RPL_TRACECLASS = 209;
public static final int RPL_STATSQLINE = 217;
public static final int RPL_SERVICEINFO = 231;
public static final int RPL_ENDOFSERVICES = 232;
public static final int RPL_SERVICE = 233;
public static final int RPL_SERVLIST = 234;
public static final int RPL_SERVLISTEND = 235;
public static final int RPL_WHOISCHANOP = 316;
public static final int RPL_KILLDONE = 361;
public static final int RPL_CLOSING = 362;
public static final int RPL_CLOSEEND = 363;
public static final int RPL_INFOSTART = 373;
public static final int RPL_MYPORTIS = 384;
public static final int ERR_YOUWILLBEBANNED = 466;
public static final int ERR_BADCHANMASK = 476;
public static final int ERR_NOSERVICEHOST = 492;
}

View File

@ -1,163 +0,0 @@
/*
Copyright Paul James Mutton, 2001-2009, http://www.jibble.org/
This file is part of PircBot.
This software is dual-licensed, allowing you to choose between the GNU
General Public License (GPL) and the www.jibble.org Commercial License.
Since the GPL may be too restrictive for use in a proprietary application,
a commercial license is also provided. Full license information can be
found at http://www.jibble.org/licenses/
*/
package org.jibble.pircbot;
import java.util.Locale;
/**
* This class is used to represent a user on an IRC server.
* Instances of this class are returned by the getUsers method
* in the PircBot class.
* <p>
* Note that this class no longer implements the Comparable interface
* for Java 1.1 compatibility reasons.
*
* @since 1.0.0
* @author Paul James Mutton,
* <a href="http://www.jibble.org/">http://www.jibble.org/</a>
* @version 1.5.0 (Build time: Mon Dec 14 20:07:17 2009)
*/
public class User {
/**
* Constructs a User object with a known prefix and nick.
*
* @param prefix The status of the user, for example, "@".
* @param nick The nick of the user.
*/
User(String prefix, String nick) {
_prefix = prefix;
_nick = nick;
_lowerNick = nick.toLowerCase(Locale.ENGLISH);
}
/**
* Returns the prefix of the user. If the User object has been obtained
* from a list of users in a channel, then this will reflect the user's
* status in that channel.
*
* @return The prefix of the user. If there is no prefix, then an empty
* String is returned.
*/
public String getPrefix() {
return _prefix;
}
/**
* Returns whether or not the user represented by this object is an
* operator. If the User object has been obtained from a list of users
* in a channel, then this will reflect the user's operator status in
* that channel.
*
* @return true if the user is an operator in the channel.
*/
public boolean isOp() {
return _prefix.indexOf('@') >= 0;
}
/**
* Returns whether or not the user represented by this object has
* voice. If the User object has been obtained from a list of users
* in a channel, then this will reflect the user's voice status in
* that channel.
*
* @return true if the user has voice in the channel.
*/
public boolean hasVoice() {
return _prefix.indexOf('+') >= 0;
}
/**
* Returns the nick of the user.
*
* @return The user's nick.
*/
public String getNick() {
return _nick;
}
/**
* Returns the nick of the user complete with their prefix if they
* have one, e.g. "@Dave".
*
* @return The user's prefix and nick.
*/
public String toString() {
return this.getPrefix() + this.getNick();
}
/**
* Returns true if the nick represented by this User object is the same
* as the argument. A case insensitive comparison is made.
*
* @return true if the nicks are identical (case insensitive).
*/
public boolean equals(String nick) {
return nick.toLowerCase(Locale.ENGLISH).equals(_lowerNick);
}
/**
* Returns true if the nick represented by this User object is the same
* as the nick of the User object given as an argument.
* A case insensitive comparison is made.
*
* @return true if o is a User object with a matching lowercase nick.
*/
public boolean equals(Object o) {
if (o instanceof User) {
User other = (User) o;
return other._lowerNick.equals(_lowerNick);
}
return false;
}
/**
* Returns the hash code of this User object.
*
* @return the hash code of the User object.
*/
public int hashCode() {
return _lowerNick.hashCode();
}
/**
* Returns the result of calling the compareTo method on lowercased
* nicks. This is useful for sorting lists of User objects.
*
* @return the result of calling compareTo on lowercased nicks.
*/
public int compareTo(Object o) {
if (o instanceof User) {
User other = (User) o;
return other._lowerNick.compareTo(_lowerNick);
}
return -1;
}
private String _prefix;
private String _nick;
private String _lowerNick;
}

View File

@ -1,21 +0,0 @@
# This determines the command prefix when there are conflicts (/name:home, /name:help, etc.)
name: EssentialsUpdate
main: com.earth2me.essentials.update.EssentialsUpdate
# Note to developers: This next line cannot change, or the automatic versioning system will break.
version: TeamCity
description: This plugin allows to install or update all Essentials plugins
authors: [snowleo]
commands:
essentialsupdate:
description: Install or update the Essentials plugins.
usage: /<command>
essentialshelp:
description: Get help from the Essentials support chat.
usage: /<command>
permissions:
essentials.update:
description: Allows you to update Essentials
default: op
essentials.helpchat:
description: Allows you to join Essentials help chat
default: op

View File

@ -1,27 +0,0 @@
package com.earth2me.essentials.update;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import junit.framework.TestCase;
import org.junit.Test;
public class UploadTest extends TestCase
{
@Test
public void testPastieUpload()
{
try
{
final PastieUpload pastie = new PastieUpload();
assertNotNull(pastie);
//final String url = pastie.send("test");
//System.out.println(url);
}
catch (IOException ex)
{
Logger.getLogger(UploadTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

View File

@ -1,86 +0,0 @@
package com.earth2me.essentials.update;
import com.earth2me.essentials.update.Version.Type;
import java.util.TreeSet;
import junit.framework.TestCase;
import org.junit.Test;
public class VersionTest extends TestCase
{
@Test
public void testStable()
{
final Version instance = new Version("1.2.3");
assertEquals("Testing Major", 1, instance.getMajor());
assertEquals("Testing Minor", 2, instance.getMinor());
assertEquals("Testing Build", 3, instance.getBuild());
assertEquals("Testing Type", Type.STABLE, instance.getType());
}
@Test
public void testDev()
{
final Version instance = new Version("Dev2.3.4");
assertEquals("Testing Major", 2, instance.getMajor());
assertEquals("Testing Minor", 3, instance.getMinor());
assertEquals("Testing Build", 4, instance.getBuild());
assertEquals("Testing Type", Type.DEVELOPER, instance.getType());
}
@Test
public void testTeamCity()
{
final Version instance = new Version("Teamcity");
assertEquals("Testing Type", Type.DEVELOPER, instance.getType());
}
@Test
public void testPre()
{
final Version instance = new Version("Pre5.7.400.2");
assertEquals("Testing Major", 5, instance.getMajor());
assertEquals("Testing Minor", 7, instance.getMinor());
assertEquals("Testing Build", 400, instance.getBuild());
assertEquals("Testing Type", Type.PREVIEW, instance.getType());
}
@Test
public void testCompareTo()
{
final Version verA = new Version("1.1.1");
final Version verB = new Version("Dev1.1.2");
final Version verC = new Version("1.1.2");
final Version verD = new Version("1.2.0");
final Version verE = new Version("2.0.0");
final Version verF = new Version("Pre1.1.1.1");
final Version verG = new Version("Dev1.2.2");
assertTrue("Testing dev", verA.compareTo(verB) < 0);
assertTrue("Testing dev", verB.compareTo(verA) > 0);
assertTrue("Testing build", verA.compareTo(verC) < 0);
assertTrue("Testing build", verC.compareTo(verA) > 0);
assertTrue("Testing minor", verA.compareTo(verD) < 0);
assertTrue("Testing minor", verD.compareTo(verA) > 0);
assertTrue("Testing major", verA.compareTo(verE) < 0);
assertTrue("Testing major", verE.compareTo(verA) > 0);
assertTrue("Testing pre", verF.compareTo(verA) < 0);
assertTrue("Testing pre", verA.compareTo(verF) > 0);
assertTrue("Testing dev vs dev", verB.compareTo(verG) < 0);
assertTrue("Testing dev vs dev", verG.compareTo(verB) > 0);
final TreeSet<Version> set = new TreeSet<Version>();
set.add(verA);
set.add(verB);
set.add(verC);
set.add(verD);
set.add(verE);
set.add(verF);
set.add(verG);
assertEquals("Testing sorting", verF, set.pollFirst());
assertEquals("Testing sorting", verA, set.pollFirst());
assertEquals("Testing sorting", verC, set.pollFirst());
assertEquals("Testing sorting", verD, set.pollFirst());
assertEquals("Testing sorting", verE, set.pollFirst());
assertEquals("Testing sorting", verB, set.pollFirst());
assertEquals("Testing sorting", verG, set.pollFirst());
}
}