Last active
October 12, 2015 23:17
-
-
Save SagaciousZed/4102258 to your computer and use it in GitHub Desktop.
Nontrivial callback example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.bukkit.command.Command; | |
import org.bukkit.command.CommandSender; | |
import org.bukkit.plugin.java.JavaPlugin; | |
import org.bukkit.scheduler.BukkitRunnable; | |
public final class CallbackExample extends JavaPlugin { | |
@Override | |
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { | |
if (args.length > 0) { | |
new AsyncRunnable(sender, args[0], new SenderCallbackFacatory() { | |
public SenderCallback newInstance(CommandSender sender, String payload) { | |
return new CommandSenderMessenger(sender, payload); | |
} | |
}, this).runTaskAsynchronously(this); | |
return true; | |
} else { | |
return false; | |
} | |
} | |
private static class AsyncRunnable extends BukkitRunnable { | |
private final CommandSender sender; | |
private final String url; | |
private final JavaPlugin plugin; | |
private final SenderCallbackFacatory factory; | |
public AsyncRunnable(CommandSender commandSender, String url, SenderCallbackFacatory factory, JavaPlugin plugin) { | |
this.sender = commandSender; | |
this.url = url; | |
this.plugin = plugin; | |
this.factory = factory; | |
} | |
public void run() { | |
// not going to load anything | |
plugin.getLogger().fine("Going to fetch " + this.url); | |
String payload = this.url; | |
this.factory.newInstance(sender, payload).runTask(plugin); | |
} | |
} | |
private interface SenderCallbackFacatory { | |
SenderCallback newInstance(CommandSender sender, String payload); | |
} | |
private static abstract class SenderCallback extends BukkitRunnable { | |
final protected CommandSender commandSender; | |
final protected String payload; | |
public SenderCallback(CommandSender commandSender, String payload) { | |
this.commandSender = commandSender; | |
this.payload = payload; | |
} | |
} | |
private static class CommandSenderMessenger extends SenderCallback { | |
CommandSenderMessenger(CommandSender commandSender, String payload) { | |
super(commandSender, payload); | |
} | |
public void run() { | |
commandSender.sendMessage(payload); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment