Changed all commands to use MF.

This commit is contained in:
Mateus 2019-09-25 16:44:32 +01:00
parent 0a346e9a6d
commit d8667de780
25 changed files with 471 additions and 1659 deletions

31
pom.xml
View File

@ -19,7 +19,7 @@
<papi.version>2.10.2</papi.version>
<vault.version>da407c0059</vault.version>
<jsonmsg.version>1.0.0</jsonmsg.version>
<utils.version>c3166ac</utils.version>
<utils.version>8dd15fc8cd</utils.version>
</properties>
<build>
@ -38,6 +38,18 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<relocations>
<relocation>
<pattern>org.bstats</pattern>
<shadedPattern>me.mattstudios.citizenscmd.metrics</shadedPattern>
</relocation>
<relocation>
<pattern>me.mattstudios.mf</pattern>
<shadedPattern>me.mattstudios.citizenscmd.mf</shadedPattern>
</relocation>
</relocations>
</configuration>
<executions>
<execution>
<phase>package</phase>
@ -81,6 +93,10 @@
<id>jitpack.io</id>
<url>http://jitpack.io</url>
</repository>
<repository>
<id>CodeMC</id>
<url>https://repo.codemc.org/repository/maven-public</url>
</repository>
</repositories>
<dependencies>
@ -129,5 +145,18 @@
<scope>compile</scope>
</dependency>
<dependency>
<groupId>me.mattstudios.utils</groupId>
<artifactId>matts-framework</artifactId>
<version>1.0.8-BETA</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.bstats</groupId>
<artifactId>bstats-bukkit</artifactId>
<version>1.5</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>

View File

@ -19,36 +19,37 @@
package me.mattstudios.citizenscmd;
import me.mattstudios.citizenscmd.api.CitizensCMDAPI;
import me.mattstudios.citizenscmd.commands.CMDAdd;
import me.mattstudios.citizenscmd.commands.CMDCooldown;
import me.mattstudios.citizenscmd.commands.CMDEdit;
import me.mattstudios.citizenscmd.commands.CMDHelp;
import me.mattstudios.citizenscmd.commands.CMDList;
import me.mattstudios.citizenscmd.commands.CMDPermission;
import me.mattstudios.citizenscmd.commands.CMDPrice;
import me.mattstudios.citizenscmd.commands.CMDReload;
import me.mattstudios.citizenscmd.commands.CMDRemove;
import me.mattstudios.citizenscmd.commands.base.CommandHandler;
import me.mattstudios.citizenscmd.commands.AddCommand;
import me.mattstudios.citizenscmd.commands.CooldownCommand;
import me.mattstudios.citizenscmd.commands.EditCommand;
import me.mattstudios.citizenscmd.commands.HelpCommand;
import me.mattstudios.citizenscmd.commands.ListCommand;
import me.mattstudios.citizenscmd.commands.PermissionCommand;
import me.mattstudios.citizenscmd.commands.PriceCommand;
import me.mattstudios.citizenscmd.commands.ReloadCommand;
import me.mattstudios.citizenscmd.commands.RemoveCommand;
import me.mattstudios.citizenscmd.files.CooldownHandler;
import me.mattstudios.citizenscmd.files.DataHandler;
import me.mattstudios.citizenscmd.files.LangHandler;
import me.mattstudios.citizenscmd.listeners.NPCClickListener;
import me.mattstudios.citizenscmd.listeners.NPCListener;
import me.mattstudios.citizenscmd.listeners.UpdateEvent;
import me.mattstudios.citizenscmd.metrics.Metrics;
import me.mattstudios.citizenscmd.permissions.PermissionsManager;
import me.mattstudios.citizenscmd.schedulers.CooldownScheduler;
import me.mattstudios.citizenscmd.schedulers.UpdateScheduler;
import me.mattstudios.citizenscmd.updater.SpigotUpdater;
import me.mattstudios.citizenscmd.utility.DisplayFormat;
import me.mattstudios.citizenscmd.utility.paths.Path;
import me.mattstudios.mf.base.CommandManager;
import net.milkbowl.vault.economy.Economy;
import org.bstats.bukkit.Metrics;
import org.bukkit.Bukkit;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Objects;
import java.util.stream.Stream;
@ -65,13 +66,13 @@ public final class CitizensCMD extends JavaPlugin {
private LangHandler lang;
private DataHandler dataHandler;
private CooldownHandler cooldownHandler;
private PermissionsManager permissionsManager ;
private PermissionsManager permissionsManager;
private static CitizensCMDAPI api;
private static Economy economy;
private boolean papi = false;
private CommandHandler commandHandler;
private CommandManager commandManager;
private boolean updateStatus = false;
private boolean shift = false;
@ -81,8 +82,8 @@ public final class CitizensCMD extends JavaPlugin {
private HashMap<String, Boolean> waitingList;
@Override
public void onEnable() {
saveDefaultConfig();
copyDefaults(getClassLoader().getResourceAsStream("config.yml"), new File(getDataFolder().getPath(), "config.yml"));
@ -93,10 +94,36 @@ public final class CitizensCMD extends JavaPlugin {
return;
}
commandHandler = new CommandHandler(this);
commandHandler.enable();
commandManager = new CommandManager(this);
new Metrics(this);
Metrics metrics = new Metrics(this);
metrics.addCustomChart(new Metrics.SimplePie("lang", () -> {
switch (Objects.requireNonNull(getConfig().getString("lang", "en")).toLowerCase()) {
case "en":
return "English";
case "bg":
return "Bulgarian";
case "fr":
return "French";
case "no":
return "Norwegian";
case "pt":
return "Portuguese";
case "Ro":
return "Romanian";
case "ch":
return "Chinese";
default:
return "Other";
}
}));
info(color(TAG + "&3Citizens&cCMD &8&o" + getDescription().getVersion() + " &8By &3Mateus Moreira &c@LichtHund"));
@ -132,6 +159,7 @@ public final class CitizensCMD extends JavaPlugin {
break;
default:
displayFormat = DisplayFormat.MEDIUM;
break;
}
} else {
displayFormat = DisplayFormat.MEDIUM;
@ -160,14 +188,6 @@ public final class CitizensCMD extends JavaPlugin {
new CooldownScheduler(this).runTaskTimerAsynchronously(this, 36000L, 36000L);
}
@Override
public void onDisable() {
if (commandHandler != null) {
commandHandler.disable();
cooldownHandler.saveToFile();
}
}
private boolean hasCitizens() {
return Bukkit.getPluginManager().isPluginEnabled("Citizens");
}
@ -185,18 +205,22 @@ public final class CitizensCMD extends JavaPlugin {
* Registers all the commands to be used
*/
private void registerCommands() {
Objects.requireNonNull(getCommand("npcmd")).setExecutor(commandHandler);
commandManager.getCompletionHandler().register("#permissions", input -> Arrays.asList("console", "player", "permission", "server", "message", "sound"));
commandManager.getCompletionHandler().register("#type", input -> Arrays.asList("cmd", "perm"));
commandManager.getCompletionHandler().register("#click", input -> Arrays.asList("left", "right"));
commandManager.getCompletionHandler().register("#set", input -> Arrays.asList("set", "remove"));
Stream.of(
new CMDHelp(this),
new CMDAdd(this),
new CMDCooldown(this),
new CMDList(this),
new CMDReload(this),
new CMDRemove(this),
new CMDEdit(this),
new CMDPrice(this),
new CMDPermission(this)
).forEach(commandHandler::register);
new AddCommand(this),
new HelpCommand(this),
new EditCommand(this),
new ListCommand(this),
new CooldownCommand(this),
new PermissionCommand(this),
new PriceCommand(this),
new ReloadCommand(this),
new RemoveCommand(this)
).forEach(commandManager::register);
}
/**
@ -374,7 +398,7 @@ public final class CitizensCMD extends JavaPlugin {
this.displayFormat = displayFormat;
}
public CitizensCMDAPI getApi() {
public static CitizensCMDAPI getApi() {
return api;
}

View File

@ -0,0 +1,109 @@
package me.mattstudios.citizenscmd.commands;
import me.mattstudios.citizenscmd.CitizensCMD;
import me.mattstudios.citizenscmd.utility.paths.Path;
import me.mattstudios.mf.annotations.Command;
import me.mattstudios.mf.annotations.Completion;
import me.mattstudios.mf.annotations.Permission;
import me.mattstudios.mf.annotations.SubCommand;
import me.mattstudios.mf.base.CommandBase;
import org.bukkit.entity.Player;
import static me.mattstudios.citizenscmd.utility.Util.HEADER;
import static me.mattstudios.citizenscmd.utility.Util.getSelectedNpcId;
import static me.mattstudios.citizenscmd.utility.Util.npcNotSelected;
import static me.mattstudios.utils.MessageUtils.color;
import static me.mattstudios.utils.NumbersUtils.isDouble;
@Command("npcmd")
public class AddCommand extends CommandBase {
private CitizensCMD plugin;
public AddCommand(CitizensCMD plugin) {
this.plugin = plugin;
}
/**
* Adds a command to an NPC via ingame command
*
* @param player Gets the player to check for which NPC is selected and send messages.
* @param permission The permission node or other to add.
* @param arguments Gets the command to be added to the NPC.
*/
@SubCommand("add")
@Permission("citizenscmd.add")
public void addCommand(Player player, @Completion("#permissions") String permission, String[] arguments) {
if (npcNotSelected(plugin, player)) return;
StringBuilder permissionBuilder = new StringBuilder(permission);
boolean left = false;
boolean displayName = false;
boolean hasDelayError = false;
StringBuilder stringBuilder = new StringBuilder();
arguments[0] = arguments[0].replace("/", "");
for (int i = 0; i < arguments.length; i++) {
if (arguments[i].equalsIgnoreCase("")) continue;
if (arguments[i].equalsIgnoreCase("-n")) {
displayName = true;
continue;
}
if (arguments[i].equalsIgnoreCase("-l")) {
left = true;
continue;
}
if (arguments[i].equalsIgnoreCase("-d")) {
if (i + 1 >= arguments.length) {
hasDelayError = true;
continue;
}
if (!isDouble(arguments[i + 1])) {
hasDelayError = true;
continue;
}
permissionBuilder.append("(").append(arguments[i + 1]).append(")");
arguments[i + 1] = "";
continue;
}
if (i == arguments.length - 1) stringBuilder.append(arguments[i]);
else stringBuilder.append(arguments[i]).append(" ");
}
if (hasDelayError) {
player.sendMessage(color(HEADER));
player.sendMessage(plugin.getLang().getMessage(Path.NPC_ADD_DELAY_FAIL));
return;
}
String finalString;
if (displayName) {
finalString = "{display} " + stringBuilder.toString().trim();
} else {
finalString = stringBuilder.toString().trim();
}
if (permissionBuilder.toString().equalsIgnoreCase("sound")) {
if (arguments.length < 2) {
finalString += " 1 1";
} else {
if (arguments.length < 3) {
finalString += " 1";
}
}
}
plugin.getDataHandler().addCommand(getSelectedNpcId(player), permissionBuilder.toString(), finalString, player, left);
}
}

View File

@ -1,125 +0,0 @@
/*
CitizensCMD - Add-on for Citizens
Copyright (C) 2018 Mateus Moreira
<p>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
<p>
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
<p>
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package me.mattstudios.citizenscmd.commands;
import me.mattstudios.citizenscmd.CitizensCMD;
import me.mattstudios.citizenscmd.commands.base.CommandBase;
import me.mattstudios.citizenscmd.utility.paths.Path;
import org.bukkit.entity.Player;
import java.util.Arrays;
import static me.mattstudios.citizenscmd.utility.Util.HEADER;
import static me.mattstudios.citizenscmd.utility.Util.getSelectedNpcId;
import static me.mattstudios.citizenscmd.utility.Util.npcNotSelected;
import static me.mattstudios.utils.MessageUtils.color;
import static me.mattstudios.utils.NumbersUtils.isDouble;
public class CMDAdd extends CommandBase {
private CitizensCMD plugin;
public CMDAdd(CitizensCMD plugin) {
super("add", "citizenscmd.add", false, null, 2, 2048);
this.plugin = plugin;
}
/**
* Adds a command to an NPC via ingame command
*
* @param player Gets the player to check for which NPC is selected and send messages
* @param args Gets the command to be added to the NPC
*/
@Override
public void execute(Player player, String[] args) {
if (npcNotSelected(plugin, player)) return;
StringBuilder permission = new StringBuilder(args[0]);
boolean left = false;
boolean displayName = false;
boolean hasDelayError = false;
StringBuilder stringBuilder = new StringBuilder();
String[] commandsArray = Arrays.copyOfRange(args, 1, args.length);
commandsArray[0] = commandsArray[0].replace("/", "");
for (int i = 0; i < commandsArray.length; i++) {
if (commandsArray[i].equalsIgnoreCase("")) continue;
if (commandsArray[i].equalsIgnoreCase("-n")) {
displayName = true;
continue;
}
if (commandsArray[i].equalsIgnoreCase("-l")) {
left = true;
continue;
}
if (commandsArray[i].equalsIgnoreCase("-d")) {
if (i + 1 >= commandsArray.length) {
hasDelayError = true;
continue;
}
if (!isDouble(commandsArray[i + 1])) {
hasDelayError = true;
continue;
}
permission.append("(").append(commandsArray[i + 1]).append(")");
commandsArray[i + 1] = "";
continue;
}
if (i == commandsArray.length - 1) stringBuilder.append(commandsArray[i]);
else stringBuilder.append(commandsArray[i]).append(" ");
}
if (hasDelayError) {
player.sendMessage(color(HEADER));
player.sendMessage(plugin.getLang().getMessage(Path.NPC_ADD_DELAY_FAIL));
return;
}
String finalString;
if (displayName) {
finalString = "{display} " + stringBuilder.toString().trim();
} else {
finalString = stringBuilder.toString().trim();
}
if (permission.toString().equalsIgnoreCase("sound")) {
if (commandsArray.length < 2) {
finalString += " 1 1";
} else {
if (commandsArray.length < 3) {
finalString += " 1";
}
}
}
plugin.getDataHandler().addCommand(getSelectedNpcId(player), permission.toString(), finalString, player, left);
}
}

View File

@ -1,55 +0,0 @@
/*
CitizensCMD - Add-on for Citizens
Copyright (C) 2018 Mateus Moreira
<p>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
<p>
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
<p>
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package me.mattstudios.citizenscmd.commands;
import me.mattstudios.citizenscmd.CitizensCMD;
import me.mattstudios.citizenscmd.commands.base.CommandBase;
import me.mattstudios.citizenscmd.utility.paths.Path;
import org.bukkit.entity.Player;
import static me.mattstudios.citizenscmd.utility.Util.HEADER;
import static me.mattstudios.citizenscmd.utility.Util.getSelectedNpcId;
import static me.mattstudios.citizenscmd.utility.Util.npcNotSelected;
import static me.mattstudios.utils.MessageUtils.color;
import static me.mattstudios.utils.NumbersUtils.isInteger;
public class CMDCooldown extends CommandBase {
private CitizensCMD plugin;
public CMDCooldown(CitizensCMD plugin) {
super("cooldown", "citizenscmd.cooldown", false, new String[]{"cd"}, 1, 1);
this.plugin = plugin;
}
@Override
public void execute(Player player, String[] args) {
if (npcNotSelected(plugin, player)) return;
if (!isInteger(args[0])) {
player.sendMessage(color(HEADER));
player.sendMessage(plugin.getLang().getMessage(Path.INVALID_COOLDOWN));
return;
}
plugin.getDataHandler().setCooldown(getSelectedNpcId(player), Integer.valueOf(args[0]), player);
}
}

View File

@ -1,70 +0,0 @@
/*
CitizensCMD - Add-on for Citizens
Copyright (C) 2018 Mateus Moreira
<p>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
<p>
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
<p>
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package me.mattstudios.citizenscmd.commands;
import me.mattstudios.citizenscmd.CitizensCMD;
import me.mattstudios.citizenscmd.commands.base.CommandBase;
import me.mattstudios.citizenscmd.utility.paths.Path;
import org.bukkit.entity.Player;
import static me.mattstudios.citizenscmd.utility.Util.HEADER;
import static me.mattstudios.citizenscmd.utility.Util.getSelectedNpcId;
import static me.mattstudios.citizenscmd.utility.Util.npcNotSelected;
import static me.mattstudios.utils.MessageUtils.color;
public class CMDPermission extends CommandBase {
private CitizensCMD plugin;
public CMDPermission(CitizensCMD plugin) {
super("permission", "citizenscmd.permission", false, null, 1, 2);
this.plugin = plugin;
}
@Override
public void execute(Player player, String[] args) {
if (npcNotSelected(plugin, player)) return;
switch (args[0]) {
case "set":
if (args.length < 2) {
player.sendMessage(color(HEADER));
player.sendMessage(plugin.getLang().getMessage(Path.WRONG_USAGE));
return;
}
plugin.getDataHandler().setCustomPermission(getSelectedNpcId(player), args[1], player);
break;
case "remove":
if (args.length > 1) {
player.sendMessage(color(HEADER));
player.sendMessage(plugin.getLang().getMessage(Path.WRONG_USAGE));
return;
}
plugin.getDataHandler().removeCustomPermission(getSelectedNpcId(player), player);
break;
default:
player.sendMessage(color(HEADER));
player.sendMessage(plugin.getLang().getMessage(Path.WRONG_USAGE));
}
}
}

View File

@ -1,56 +0,0 @@
/*
CitizensCMD - Add-on for Citizens
Copyright (C) 2018 Mateus Moreira
<p>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
<p>
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
<p>
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package me.mattstudios.citizenscmd.commands;
import me.mattstudios.citizenscmd.CitizensCMD;
import me.mattstudios.citizenscmd.commands.base.CommandBase;
import me.mattstudios.citizenscmd.utility.paths.Path;
import org.bukkit.entity.Player;
import static me.mattstudios.citizenscmd.utility.Util.HEADER;
import static me.mattstudios.citizenscmd.utility.Util.getSelectedNpcId;
import static me.mattstudios.citizenscmd.utility.Util.npcNotSelected;
import static me.mattstudios.utils.MessageUtils.color;
import static me.mattstudios.utils.NumbersUtils.isDouble;
public class CMDPrice extends CommandBase {
private CitizensCMD plugin;
public CMDPrice(CitizensCMD plugin) {
super("price", "citizenscmd.price", false, new String[]{"p"}, 1, 1);
this.plugin = plugin;
}
@Override
public void execute(Player player, String[] args) {
if (npcNotSelected(plugin, player)) return;
if (!isDouble(args[0])) {
player.sendMessage(color(HEADER));
player.sendMessage(plugin.getLang().getMessage(Path.INVALID_PRICE));
return;
}
plugin.getDataHandler().setPrice(getSelectedNpcId(player), Double.valueOf(args[0]), player);
}
}

View File

@ -1,104 +0,0 @@
/*
CitizensCMD - Add-on for Citizens
Copyright (C) 2018 Mateus Moreira
<p>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
<p>
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
<p>
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package me.mattstudios.citizenscmd.commands;
import me.mattstudios.citizenscmd.CitizensCMD;
import me.mattstudios.citizenscmd.commands.base.CommandBase;
import me.mattstudios.citizenscmd.utility.DisplayFormat;
import me.mattstudios.citizenscmd.utility.paths.Path;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.Objects;
import static me.mattstudios.citizenscmd.utility.Util.HEADER;
import static me.mattstudios.utils.MessageUtils.color;
public class CMDReload extends CommandBase {
private CitizensCMD plugin;
public CMDReload(CitizensCMD plugin) {
super("reload", "citizenscmd.reload", true, null, 0, 0);
this.plugin = plugin;
}
@Override
public void execute(Player player, String[] args) {
plugin.reloadConfig();
plugin.saveDefaultConfig();
plugin.setLang(Objects.requireNonNull(plugin.getConfig().getString("lang")));
if (plugin.getConfig().contains("cooldown-time-display")) {
switch (Objects.requireNonNull(plugin.getConfig().getString("cooldown-time-display")).toLowerCase()) {
case "short":
plugin.setDisplayFormat(DisplayFormat.SHORT);
break;
case "full":
plugin.setDisplayFormat(DisplayFormat.FULL);
break;
default:
plugin.setDisplayFormat(DisplayFormat.MEDIUM);
break;
}
} else
plugin.setDisplayFormat(DisplayFormat.MEDIUM);
if (CitizensCMD.getEconomy() != null)
plugin.setShift(plugin.getConfig().getBoolean("shift-confirm"));
plugin.getDataHandler().reload();
plugin.getCooldownHandler().reload();
player.sendMessage(color(HEADER));
player.sendMessage(plugin.getLang().getMessage(Path.RELOAD));
}
@Override
public void execute(CommandSender sender, String[] args) {
plugin.reloadConfig();
plugin.saveConfig();
plugin.setLang(Objects.requireNonNull(plugin.getConfig().getString("lang")));
if (plugin.getConfig().contains("cooldown-time-display")) {
switch (Objects.requireNonNull(plugin.getConfig().getString("cooldown-time-display")).toLowerCase()) {
case "short":
plugin.setDisplayFormat(DisplayFormat.SHORT);
break;
case "full":
plugin.setDisplayFormat(DisplayFormat.FULL);
break;
default:
plugin.setDisplayFormat(DisplayFormat.MEDIUM);
break;
}
} else
plugin.setDisplayFormat(DisplayFormat.MEDIUM);
if (CitizensCMD.getEconomy() != null)
plugin.setShift(plugin.getConfig().getBoolean("shift-confirm"));
plugin.getDataHandler().reload();
plugin.getCooldownHandler().reload();
sender.sendMessage(color(HEADER));
sender.sendMessage(plugin.getLang().getMessage(Path.RELOAD));
}
}

View File

@ -0,0 +1,32 @@
package me.mattstudios.citizenscmd.commands;
import me.mattstudios.citizenscmd.CitizensCMD;
import me.mattstudios.mf.annotations.Command;
import me.mattstudios.mf.annotations.Completion;
import me.mattstudios.mf.annotations.Permission;
import me.mattstudios.mf.annotations.SubCommand;
import me.mattstudios.mf.base.CommandBase;
import org.bukkit.entity.Player;
import static me.mattstudios.citizenscmd.utility.Util.getSelectedNpcId;
import static me.mattstudios.citizenscmd.utility.Util.npcNotSelected;
@Command("npcmd")
public class CooldownCommand extends CommandBase {
private CitizensCMD plugin;
public CooldownCommand(CitizensCMD plugin) {
this.plugin = plugin;
}
@SubCommand("cooldown")
@Permission("citizenscmd.cooldown")
public void cooldown(Player player, @Completion("#range:9") int cooldown) {
if (npcNotSelected(plugin, player)) return;
plugin.getDataHandler().setCooldown(getSelectedNpcId(player), cooldown, player);
}
}

View File

@ -1,69 +1,47 @@
/*
CitizensCMD - Add-on for Citizens
Copyright (C) 2018 Mateus Moreira
<p>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
<p>
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
<p>
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package me.mattstudios.citizenscmd.commands;
import me.mattstudios.citizenscmd.CitizensCMD;
import me.mattstudios.citizenscmd.commands.base.CommandBase;
import me.mattstudios.citizenscmd.utility.EnumTypes;
import me.mattstudios.citizenscmd.utility.paths.Path;
import me.mattstudios.mf.annotations.Command;
import me.mattstudios.mf.annotations.Completion;
import me.mattstudios.mf.annotations.Permission;
import me.mattstudios.mf.annotations.SubCommand;
import me.mattstudios.mf.base.CommandBase;
import org.bukkit.entity.Player;
import java.util.Arrays;
import static me.mattstudios.citizenscmd.utility.Util.HEADER;
import static me.mattstudios.citizenscmd.utility.Util.getSelectedNpcId;
import static me.mattstudios.citizenscmd.utility.Util.npcNotSelected;
import static me.mattstudios.utils.MessageUtils.color;
import static me.mattstudios.utils.NumbersUtils.isInteger;
public class CMDEdit extends CommandBase {
@Command("npcmd")
public class EditCommand extends CommandBase {
private CitizensCMD plugin;
public CMDEdit(CitizensCMD plugin) {
super("edit", "citizenscmd.edit", false, null, 4, 512);
public EditCommand(CitizensCMD plugin) {
this.plugin = plugin;
}
@Override
public void execute(Player player, String[] args) {
@SubCommand("edit")
@Permission("citizenscmd.edit")
@Completion({"#type", "#click"})
public void edit(Player player, String typeString, String clickString, int id, String[] arguments) {
if (npcNotSelected(plugin, player)) return;
if (!isInteger(args[2])) {
player.sendMessage(color(HEADER));
player.sendMessage(plugin.getLang().getMessage(Path.INVALID_ID_NUMBER));
return;
}
int commandID = Integer.parseInt(args[2]);
int npc = getSelectedNpcId(player);
EnumTypes.ClickType click;
EnumTypes.EditType type;
switch (args[0].toLowerCase()) {
switch (typeString.toLowerCase()) {
case "cmd":
type = EnumTypes.EditType.CMD;
break;
case "perm":
if (args.length > 4) {
if (arguments.length > 1) {
player.sendMessage(color(HEADER));
player.sendMessage(plugin.getLang().getMessage(Path.INVALID_PERMISSION));
return;
@ -76,35 +54,42 @@ public class CMDEdit extends CommandBase {
return;
}
switch (args[1].toLowerCase()) {
switch (clickString.toLowerCase()) {
case "left":
int leftCommandSize = plugin.getDataHandler().getClickCommandsData(npc, EnumTypes.ClickType.LEFT).size();
if (leftCommandSize == 0) {
player.sendMessage(color(HEADER));
player.sendMessage(plugin.getLang().getMessage(Path.NO_COMMANDS));
return;
}
if (commandID < 1 || commandID > leftCommandSize) {
if (id < 1 || id > leftCommandSize) {
player.sendMessage(color(HEADER));
player.sendMessage(plugin.getLang().getMessage(Path.INVALID_ID_NUMBER));
return;
}
click = EnumTypes.ClickType.LEFT;
break;
case "right":
int rightCommandSize = plugin.getDataHandler().getClickCommandsData(npc, EnumTypes.ClickType.RIGHT).size();
if (rightCommandSize == 0) {
player.sendMessage(color(HEADER));
player.sendMessage(plugin.getLang().getMessage(Path.NO_COMMANDS));
return;
}
if (commandID < 1 || commandID > rightCommandSize) {
if (id < 1 || id > rightCommandSize) {
player.sendMessage(color(HEADER));
player.sendMessage(plugin.getLang().getMessage(Path.INVALID_ID_NUMBER));
return;
}
click = EnumTypes.ClickType.RIGHT;
break;
default:
player.sendMessage(color(HEADER));
player.sendMessage(plugin.getLang().getMessage(Path.INVALID_CLICK_TYPE));
@ -112,14 +97,14 @@ public class CMDEdit extends CommandBase {
}
StringBuilder stringBuilder = new StringBuilder();
String[] commandsArray = Arrays.copyOfRange(args, 3, args.length);
commandsArray[0] = commandsArray[0].replace("/", "");
arguments[0] = arguments[0].replace("/", "");
for (int i = 0; i < commandsArray.length; i++) {
if (i == commandsArray.length - 1) stringBuilder.append(commandsArray[i]);
else stringBuilder.append(commandsArray[i]).append(" ");
for (int i = 0; i < arguments.length; i++) {
if (i == arguments.length - 1) stringBuilder.append(arguments[i]);
else stringBuilder.append(arguments[i]).append(" ");
}
plugin.getDataHandler().edit(npc, commandID, click, type, stringBuilder.toString().trim(), player);
plugin.getDataHandler().edit(npc, id, click, type, stringBuilder.toString().trim(), player);
}
}

View File

@ -1,50 +1,35 @@
/*
CitizensCMD - Add-on for Citizens
Copyright (C) 2018 Mateus Moreira
<p>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
<p>
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
<p>
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package me.mattstudios.citizenscmd.commands;
import me.mattstudios.citizenscmd.CitizensCMD;
import me.mattstudios.citizenscmd.commands.base.CommandBase;
import me.mattstudios.citizenscmd.utility.paths.Path;
import me.mattstudios.mf.annotations.Alias;
import me.mattstudios.mf.annotations.Command;
import me.mattstudios.mf.annotations.Default;
import me.mattstudios.mf.annotations.Permission;
import me.mattstudios.mf.base.CommandBase;
import me.rayzr522.jsonmessage.JSONMessage;
import org.bukkit.entity.Player;
import static me.mattstudios.citizenscmd.utility.Util.HEADER;
import static me.mattstudios.utils.MessageUtils.color;
/**
* Thank you GlareMasters for creating this class as an example!
*/
public class CMDHelp extends CommandBase {
@Command("npcmd")
public class HelpCommand extends CommandBase {
private CitizensCMD plugin;
public CMDHelp(CitizensCMD plugin) {
super("help", "citizenscmd.npcmd", false, null, 0, 0);
public HelpCommand(CitizensCMD plugin) {
this.plugin = plugin;
}
@Override
public void execute(Player player, String[] args) {
@Default
@Alias("help")
@Permission("citizenscmd.npcmd")
public void help(Player player) {
JSONMessage.create(color(HEADER)).send(player);
JSONMessage.create(color(plugin.getLang().getUncoloredMessage(Path.HELP_VERSION) + " &c&o" + plugin.getDescription().getVersion())).send(player);
JSONMessage.create(color(plugin.getLang().getUncoloredMessage(Path.HELP_INFO))).send(player);
JSONMessage.create(color("&3/npcmd &cadd &b<console &b| &bmessage &b| &bnone | &bpermission &b| &bserver &b| &bsound &b> &6<command> &d[-l]")).suggestCommand("/npcmd add ").tooltip(color(plugin.getLang().getUncoloredMessage(Path.HELP_DESCRIPTION_ADD) + "\n" + plugin.getLang().getUncoloredMessage(Path.HELP_EXAMPLE) + "\n&3&o/npcmd &c&oadd &b&ossentials.heal &6&oheal")).send(player);
JSONMessage.create(color("&3/npcmd &cadd &b<console &b| &bmessage &b| &bplayer | &bpermission &b| &bserver &b| &bsound &b> &6<command> &d[-l]")).suggestCommand("/npcmd add ").tooltip(color(plugin.getLang().getUncoloredMessage(Path.HELP_DESCRIPTION_ADD) + "\n" + plugin.getLang().getUncoloredMessage(Path.HELP_EXAMPLE) + "\n&3&o/npcmd &c&oadd &b&ossentials.heal &6&oheal")).send(player);
JSONMessage.create(color("&3/npcmd &ccooldown &6<time>")).suggestCommand("/npcmd cooldown ").tooltip(color(plugin.getLang().getUncoloredMessage(Path.HELP_DESCRIPTION_COOLDOWN) + "\n" + plugin.getLang().getUncoloredMessage(Path.HELP_EXAMPLE) + "\n&3&o/npcmd &c&ocooldown &6&o15")).send(player);
JSONMessage.create(color("&3/npcmd &cprice &6<price>")).suggestCommand("/npcmd price ").tooltip(color(plugin.getLang().getUncoloredMessage(Path.HELP_DESCRIPTION_PRICE) + "\n" + plugin.getLang().getUncoloredMessage(Path.HELP_EXAMPLE) + "\n&3&o/npcmd &c&oprice &6&o250")).send(player);
JSONMessage.create(color("&3/npcmd &clist")).suggestCommand("/npcmd list").tooltip(color(plugin.getLang().getUncoloredMessage(Path.HELP_DESCRIPTION_LIST) + "\n&8" + plugin.getLang().getUncoloredMessage(Path.HELP_EXAMPLE) + "\n&3&o/npcmd &c&olist")).send(player);
@ -52,7 +37,6 @@ public class CMDHelp extends CommandBase {
JSONMessage.create(color("&3/npcmd &cremove &b<left | right> &6<id>")).suggestCommand("/npcmd remove ").tooltip(color(plugin.getLang().getUncoloredMessage(Path.HELP_DESCRIPTION_REMOVE) + "\n" + plugin.getLang().getUncoloredMessage(Path.HELP_EXAMPLE) + "\n&3&o/npcmd &c&oremove &b&oright &6&o1")).send(player);
JSONMessage.create(color("&3/npcmd &cpermission &b<set | remove> &6<custom.permission>")).suggestCommand("/npcmd permission ").send(player);
JSONMessage.create(color("&3/npcmd &creload")).suggestCommand("/npcmd reload").tooltip(color(plugin.getLang().getUncoloredMessage(Path.HELP_DESCRIPTION_RELOAD) + "\n" + plugin.getLang().getUncoloredMessage(Path.HELP_EXAMPLE) + "\n&3&o/npcmd &c&oreload")).send(player);
}
}

View File

@ -1,27 +1,12 @@
/*
CitizensCMD - Add-on for Citizens
Copyright (C) 2018 Mateus Moreira
<p>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
<p>
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
<p>
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package me.mattstudios.citizenscmd.commands;
import me.mattstudios.citizenscmd.CitizensCMD;
import me.mattstudios.citizenscmd.commands.base.CommandBase;
import me.mattstudios.citizenscmd.utility.EnumTypes;
import me.mattstudios.citizenscmd.utility.paths.Path;
import me.mattstudios.mf.annotations.Command;
import me.mattstudios.mf.annotations.Permission;
import me.mattstudios.mf.annotations.SubCommand;
import me.mattstudios.mf.base.CommandBase;
import me.rayzr522.jsonmessage.JSONMessage;
import org.bukkit.entity.Player;
@ -33,17 +18,18 @@ import static me.mattstudios.citizenscmd.utility.Util.getSelectedNpcId;
import static me.mattstudios.citizenscmd.utility.Util.npcNotSelected;
import static me.mattstudios.utils.MessageUtils.color;
public class CMDList extends CommandBase {
@Command("npcmd")
public class ListCommand extends CommandBase {
private CitizensCMD plugin;
public CMDList(CitizensCMD plugin) {
super("list", "citizenscmd.list", false, new String[]{"l"}, 0, 0);
public ListCommand(CitizensCMD plugin) {
this.plugin = plugin;
}
@Override
public void execute(Player player, String[] args) {
@SubCommand("list")
@Permission("citizenscmd.list")
public void list(Player player) {
if (npcNotSelected(plugin, player)) return;
@ -74,4 +60,4 @@ public class CMDList extends CommandBase {
}
}
}
}

View File

@ -0,0 +1,47 @@
package me.mattstudios.citizenscmd.commands;
import me.mattstudios.citizenscmd.CitizensCMD;
import me.mattstudios.citizenscmd.utility.paths.Path;
import me.mattstudios.mf.annotations.Command;
import me.mattstudios.mf.annotations.Completion;
import me.mattstudios.mf.annotations.Permission;
import me.mattstudios.mf.annotations.SubCommand;
import me.mattstudios.mf.base.CommandBase;
import org.bukkit.entity.Player;
import static me.mattstudios.citizenscmd.utility.Util.HEADER;
import static me.mattstudios.citizenscmd.utility.Util.getSelectedNpcId;
import static me.mattstudios.citizenscmd.utility.Util.npcNotSelected;
import static me.mattstudios.utils.MessageUtils.color;
@Command("npcmd")
public class PermissionCommand extends CommandBase {
private CitizensCMD plugin;
public PermissionCommand(CitizensCMD plugin) {
this.plugin = plugin;
}
@SubCommand("permission")
@Permission("citizenscmd.permission")
public void permission(Player player, @Completion("#set") String set, String permission) {
if (npcNotSelected(plugin, player)) return;
switch (set.toLowerCase()) {
case "set":
plugin.getDataHandler().setCustomPermission(getSelectedNpcId(player), permission, player);
break;
case "remove":
plugin.getDataHandler().removeCustomPermission(getSelectedNpcId(player), player);
break;
default:
player.sendMessage(color(HEADER));
player.sendMessage(plugin.getLang().getMessage(Path.WRONG_USAGE));
}
}
}

View File

@ -0,0 +1,33 @@
package me.mattstudios.citizenscmd.commands;
import me.mattstudios.citizenscmd.CitizensCMD;
import me.mattstudios.mf.annotations.Command;
import me.mattstudios.mf.annotations.Completion;
import me.mattstudios.mf.annotations.Permission;
import me.mattstudios.mf.annotations.SubCommand;
import me.mattstudios.mf.base.CommandBase;
import org.bukkit.entity.Player;
import static me.mattstudios.citizenscmd.utility.Util.getSelectedNpcId;
import static me.mattstudios.citizenscmd.utility.Util.npcNotSelected;
@Command("npcmd")
public class PriceCommand extends CommandBase {
private CitizensCMD plugin;
public PriceCommand(CitizensCMD plugin) {
this.plugin = plugin;
}
@SubCommand("price")
@Permission("citizenscmd.price")
@Completion("#range:9")
public void price(Player player, double price) {
if (npcNotSelected(plugin, player)) return;
plugin.getDataHandler().setPrice(getSelectedNpcId(player), price, player);
}
}

View File

@ -0,0 +1,59 @@
package me.mattstudios.citizenscmd.commands;
import me.mattstudios.citizenscmd.CitizensCMD;
import me.mattstudios.citizenscmd.utility.DisplayFormat;
import me.mattstudios.citizenscmd.utility.paths.Path;
import me.mattstudios.mf.annotations.Command;
import me.mattstudios.mf.annotations.Permission;
import me.mattstudios.mf.annotations.SubCommand;
import me.mattstudios.mf.base.CommandBase;
import org.bukkit.command.CommandSender;
import java.util.Objects;
import static me.mattstudios.citizenscmd.utility.Util.HEADER;
import static me.mattstudios.utils.MessageUtils.color;
@Command("npcmd")
public class ReloadCommand extends CommandBase {
private CitizensCMD plugin;
public ReloadCommand(CitizensCMD plugin) {
this.plugin = plugin;
}
@SubCommand("reload")
@Permission("citizenscmd.reload")
public void reload(CommandSender player) {
plugin.reloadConfig();
plugin.saveDefaultConfig();
plugin.setLang(Objects.requireNonNull(plugin.getConfig().getString("lang")));
if (plugin.getConfig().contains("cooldown-time-display")) {
switch (Objects.requireNonNull(plugin.getConfig().getString("cooldown-time-display")).toLowerCase()) {
case "short":
plugin.setDisplayFormat(DisplayFormat.SHORT);
break;
case "full":
plugin.setDisplayFormat(DisplayFormat.FULL);
break;
default:
plugin.setDisplayFormat(DisplayFormat.MEDIUM);
break;
}
} else
plugin.setDisplayFormat(DisplayFormat.MEDIUM);
if (CitizensCMD.getEconomy() != null)
plugin.setShift(plugin.getConfig().getBoolean("shift-confirm"));
plugin.getDataHandler().reload();
plugin.getCooldownHandler().reload();
player.sendMessage(color(HEADER));
player.sendMessage(plugin.getLang().getMessage(Path.RELOAD));
}
}

View File

@ -1,96 +1,84 @@
/*
CitizensCMD - Add-on for Citizens
Copyright (C) 2018 Mateus Moreira
<p>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
<p>
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
<p>
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package me.mattstudios.citizenscmd.commands;
import me.mattstudios.citizenscmd.CitizensCMD;
import me.mattstudios.citizenscmd.commands.base.CommandBase;
import me.mattstudios.citizenscmd.utility.EnumTypes;
import me.mattstudios.citizenscmd.utility.paths.Path;
import me.mattstudios.mf.annotations.Command;
import me.mattstudios.mf.annotations.Completion;
import me.mattstudios.mf.annotations.Permission;
import me.mattstudios.mf.annotations.SubCommand;
import me.mattstudios.mf.base.CommandBase;
import org.bukkit.entity.Player;
import static me.mattstudios.citizenscmd.utility.Util.HEADER;
import static me.mattstudios.citizenscmd.utility.Util.getSelectedNpcId;
import static me.mattstudios.citizenscmd.utility.Util.npcNotSelected;
import static me.mattstudios.utils.MessageUtils.color;
import static me.mattstudios.utils.NumbersUtils.isInteger;
public class CMDRemove extends CommandBase {
@Command("npcmd")
public class RemoveCommand extends CommandBase {
private CitizensCMD plugin;
public CMDRemove(CitizensCMD plugin) {
super("remove", "citizenscmd.remove", false, new String[]{"delete", "del", "rem"}, 2, 2);
public RemoveCommand(CitizensCMD plugin) {
this.plugin = plugin;
}
@Override
public void execute(Player player, String[] args) {
@SubCommand("remove")
@Permission("citizenscmd.remove")
@Completion("#click")
public void remove(Player player, String clickString, int id) {
if (npcNotSelected(plugin, player)) return;
if (!isInteger(args[1])) {
player.sendMessage(color(HEADER));
player.sendMessage(plugin.getLang().getMessage(Path.INVALID_ID_NUMBER));
return;
}
int commandID = Integer.parseInt(args[1]);
int npc = getSelectedNpcId(player);
EnumTypes.ClickType click;
switch (args[0]) {
switch (clickString.toLowerCase()) {
case "left":
int leftCommandSize = plugin.getDataHandler().getClickCommandsData(npc, EnumTypes.ClickType.LEFT).size();
if (leftCommandSize == 0) {
player.sendMessage(color(HEADER));
player.sendMessage(plugin.getLang().getMessage(Path.NO_COMMANDS));
return;
}
if (commandID < 1 || commandID > leftCommandSize) {
if (id < 1 || id > leftCommandSize) {
player.sendMessage(color(HEADER));
player.sendMessage(plugin.getLang().getMessage(Path.INVALID_ID_NUMBER));
return;
}
click = EnumTypes.ClickType.LEFT;
break;
case "right":
int rightCommandSize = plugin.getDataHandler().getClickCommandsData(npc, EnumTypes.ClickType.RIGHT).size();
if (rightCommandSize == 0) {
player.sendMessage(color(HEADER));
player.sendMessage(plugin.getLang().getMessage(Path.NO_COMMANDS));
return;
}
if (commandID < 0 || commandID > rightCommandSize) {
if (id < 0 || id > rightCommandSize) {
player.sendMessage(color(HEADER));
player.sendMessage(plugin.getLang().getMessage(Path.INVALID_ID_NUMBER));
return;
}
click = EnumTypes.ClickType.RIGHT;
break;
default:
player.sendMessage(color(HEADER));
player.sendMessage(plugin.getLang().getMessage(Path.INVALID_CLICK_TYPE));
return;
}
plugin.getDataHandler().removeCommand(npc, commandID, click, player);
plugin.getDataHandler().removeCommand(npc, id, click, player);
}
}

View File

@ -1,87 +0,0 @@
/*
CitizensCMD - Add-on for Citizens
Copyright (C) 2018 Mateus Moreira
<p>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
<p>
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
<p>
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package me.mattstudios.citizenscmd.commands.base;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Thank you GlareMasters for creating this class!
*/
public abstract class CommandBase {
private String name;
private String permission;
private boolean allowConsole;
private List<String> aliases;
private int minimumArguments;
private int maximumArguments;
protected CommandBase(String name, String permission, boolean allowConsole,
String[] aliases, int minimumArguments, int maximumArguments) {
this.name = name;
this.permission = permission;
this.allowConsole = allowConsole;
this.aliases = aliases == null ? new ArrayList<>() : Arrays.asList(aliases);
this.minimumArguments = minimumArguments;
this.maximumArguments = maximumArguments;
}
public void execute(CommandSender sender, String[] args) {
throw new UnsupportedOperationException("Method not implemented");
}
public void execute(Player sender, String[] args) {
throw new UnsupportedOperationException("Method not implemented");
}
public String getName() {
return name;
}
public String getPermission() {
return permission;
}
public boolean allowConsole() {
return allowConsole;
}
public List<String> getAliases() {
return aliases;
}
public int getMinimumArguments() {
return minimumArguments;
}
public int getMaximumArguments() {
return maximumArguments;
}
}

View File

@ -1,234 +0,0 @@
/*
CitizensCMD - Add-on for Citizens
Copyright (C) 2018 Mateus Moreira
<p>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
<p>
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
<p>
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package me.mattstudios.citizenscmd.commands.base;
import me.mattstudios.citizenscmd.CitizensCMD;
import me.mattstudios.citizenscmd.utility.IHandler;
import me.mattstudios.citizenscmd.utility.paths.Path;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import static me.mattstudios.citizenscmd.utility.Util.HEADER;
import static me.mattstudios.citizenscmd.utility.Util.getTabCompleteArgs;
import static me.mattstudios.citizenscmd.utility.Util.npcNotSelectedNM;
import static me.mattstudios.utils.MessageUtils.color;
/**
* Thank you GlareMasters for creating this class!
*/
public class CommandHandler implements CommandExecutor, TabCompleter, IHandler {
private CitizensCMD plugin;
private List<CommandBase> commands;
public CommandHandler(CitizensCMD plugin) {
this.plugin = plugin;
}
@Override
public void enable() {
commands = new ArrayList<>();
}
@Override
public void disable() {
commands.clear();
commands = null;
}
public void register(CommandBase command) {
commands.add(command);
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] aguments) {
if (!cmd.getName().equalsIgnoreCase("npcmd")) {
return true;
}
if (aguments.length == 0 || aguments[0].isEmpty()) {
if (sender.hasPermission("citizenscmd.npcmd") && sender instanceof Player) {
getCommand().execute((Player) sender, aguments);
}
return true;
}
for (CommandBase command : commands) {
if (!command.getName().equalsIgnoreCase(aguments[0]) && !command.getAliases()
.contains(aguments[0].toLowerCase())) {
continue;
}
if (!command.allowConsole() && !(sender instanceof Player)) {
sender.sendMessage(color(HEADER));
sender.sendMessage(plugin.getLang().getMessage(Path.CONSOLE_NOT_ALLOWED));
return true;
}
if (!sender.hasPermission(command.getPermission())) {
sender.sendMessage(color(HEADER));
sender.sendMessage(plugin.getLang().getMessage(Path.NO_PERMISSION));
return true;
}
aguments = Arrays.copyOfRange(aguments, 1, aguments.length);
if ((command.getMinimumArguments() != -1 && command.getMinimumArguments() > aguments.length)
|| (command.getMaximumArguments() != -1
&& command.getMaximumArguments() < aguments.length)) {
sender.sendMessage(color(HEADER));
sender.sendMessage(plugin.getLang().getMessage(Path.WRONG_USAGE));
return true;
}
if (command.allowConsole()) {
if (sender instanceof Player)
command.execute((Player) sender, aguments);
else
command.execute(sender, aguments);
return true;
} else {
command.execute((Player) sender, aguments);
return true;
}
}
sender.sendMessage(color(HEADER));
sender.sendMessage(plugin.getLang().getMessage(Path.WRONG_USAGE));
return true;
}
private CommandBase getCommand() {
return commands.stream().filter(
command -> command.getName() != null && command.getName().equalsIgnoreCase("help"))
.findFirst().orElse(null);
}
public List<CommandBase> getCommands() {
return commands;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (cmd.getName().equalsIgnoreCase("npcmd")) {
if (args.length == 1) {
List<String> commandNames = new ArrayList<>();
if (!args[0].equals("")) {
for (String commandName : commands.stream().map(CommandBase::getName)
.collect(Collectors.toList())) {
if (!commandName.startsWith(args[0].toLowerCase())) continue;
commandNames.add(commandName);
}
} else {
commandNames =
commands.stream().map(CommandBase::getName)
.collect(Collectors.toList());
}
Collections.sort(commandNames);
return commandNames;
} else {
String subCMD = args[0].toLowerCase();
switch (subCMD) {
case "add":
if (args.length == 2) return getCommandNames(subCMD, args, 1, (Player) sender);
if (args[1].equalsIgnoreCase("sound")) {
if (args.length == 3) return getCommandNames(subCMD, args, 2, (Player) sender);
if (args.length == 4) return getCommandNames(subCMD, args, 3, (Player) sender);
if (args.length == 5) return getCommandNames(subCMD, args, 4, (Player) sender);
}
break;
case "permission":
case "cooldown":
if (args.length == 2) return getCommandNames(subCMD, args, 1, (Player) sender);
break;
case "remove":
if (npcNotSelectedNM((Player) sender)) break;
if (args.length == 2) return getCommandNames(subCMD, args, 1, (Player) sender);
if (args.length == 3) {
if (args[1].equalsIgnoreCase("left"))
return getCommandNames(subCMD, args, 2, (Player) sender);
else if (args[1].equalsIgnoreCase("right"))
return getCommandNames(subCMD, args, 3, (Player) sender);
}
break;
case "edit":
if (npcNotSelectedNM((Player) sender)) break;
if (args.length == 2) return getCommandNames(subCMD, args, 1, (Player) sender);
if (args.length == 3) return getCommandNames(subCMD, args, 2, (Player) sender);
if (args.length == 4) {
if (args[2].equalsIgnoreCase("left"))
return getCommandNames(subCMD, args, 3, (Player) sender);
else if (args[2].equalsIgnoreCase("right"))
return getCommandNames(subCMD, args, 4, (Player) sender);
}
if (args.length == 5 && args[1].equalsIgnoreCase("perm")) {
return getCommandNames(subCMD, args, 5, (Player) sender);
}
break;
}
}
}
return null;
}
/**
* Gets the subcomands to tab complete
*
* @param subCMD Gets the sub command, example, add, list, etc
* @param args Arguments from the command
* @param arg Number of arguments to get the correct from the getTabCompleteArgs()
* @return Returns list with Strings to the tab complete
*/
private List<String> getCommandNames(String subCMD, String[] args, int arg, Player player) {
List<String> commandNames = new ArrayList<>();
String[][] argsComplete = getTabCompleteArgs(plugin, subCMD.toLowerCase(), player);
if (!args[arg - 1].equals("")) {
for (String commandName : argsComplete[arg - 1]) {
if (arg + 1 > args.length) break;
if (!commandName.toLowerCase().startsWith(args[arg].toLowerCase())) continue;
commandNames.add(commandName);
}
} else {
commandNames = Arrays.asList(argsComplete[arg - 1]);
}
Collections.sort(commandNames);
return commandNames;
}
}

View File

@ -30,7 +30,7 @@ import java.util.HashMap;
import java.util.Objects;
import static me.mattstudios.utils.MessageUtils.color;
import static me.mattstudios.utils.YamlUtils.copyPathDefaults;
import static me.mattstudios.utils.YamlUtils.copyDefaults;
@SuppressWarnings("ResultOfMethodCallIgnored")
public class LangHandler {
@ -46,6 +46,8 @@ public class LangHandler {
messages = new HashMap<>();
cacheMessage();
System.out.println("Using " + lang);
}
/**
@ -61,15 +63,15 @@ public class LangHandler {
if (!langFile.exists()) {
if (langStream == null) {
langFile.createNewFile();
copyPathDefaults(CitizensCMD.class.getClassLoader().getResourceAsStream("lang/en.yml"), langFile, "messages");
copyDefaults(CitizensCMD.class.getClassLoader().getResourceAsStream("lang/en.yml"), langFile);
} else {
plugin.saveResource("lang/" + lang + ".yml", false);
}
} else {
if (langStream == null) {
copyPathDefaults(CitizensCMD.class.getClassLoader().getResourceAsStream("lang/en.yml"), langFile, "messages");
copyDefaults(CitizensCMD.class.getClassLoader().getResourceAsStream("lang/en.yml"), langFile);
} else {
copyPathDefaults(langStream, langFile, "messages");
copyDefaults(langStream, langFile);
}
}

View File

@ -20,5 +20,4 @@ public class NPCListener implements Listener {
plugin.getDataHandler().cloneData(event.getNPC().getId(), event.getClone().getId());
}
}

View File

@ -1,662 +0,0 @@
package me.mattstudios.citizenscmd.metrics;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.ServicePriority;
import org.bukkit.plugin.java.JavaPlugin;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import javax.net.ssl.HttpsURLConnection;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;
/**
* bStats collects some data for plugin authors.
*
* Check out https://bStats.org/ to learn more about bStats!
*/
@SuppressWarnings("all")
public class Metrics {
static {
// You can use the property to disable the check in your test environment
if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) {
// Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D
final String defaultPackage = new String(
new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'});
final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});
// We want to make sure nobody just copy & pastes the example and use the wrong package names
if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) {
throw new IllegalStateException("bStats Metrics class has not been relocated correctly!");
}
}
}
// The version of this bStats class
public static final int B_STATS_VERSION = 1;
// The url to which the data is sent
private static final String URL = "https://bStats.org/submitData/bukkit";
// Should failed requests be logged?
private static boolean logFailedRequests;
// The uuid of the server
private static String serverUUID;
// The plugin
private final JavaPlugin plugin;
// A list with all custom charts
private final List<CustomChart> charts = new ArrayList<>();
/**
* Class constructor.
*
* @param plugin The plugin which stats should be submitted.
*/
public Metrics(JavaPlugin plugin) {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null!");
}
this.plugin = plugin;
// Get the config file
File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
File configFile = new File(bStatsFolder, "config.yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
// Check if the config file exists
if (!config.isSet("serverUuid")) {
// Add default values
config.addDefault("enabled", true);
// Every server gets it's unique random id.
config.addDefault("serverUuid", UUID.randomUUID().toString());
// Should failed request be logged?
config.addDefault("logFailedRequests", false);
// Inform the server owners about bStats
config.options().header(
"bStats collects some data for plugin authors like how many servers are using their plugins.\n" +
"To honor their work, you should not disable it.\n" +
"This has nearly no effect on the server performance!\n" +
"Check out https://bStats.org/ to learn more :)"
).copyDefaults(true);
try {
config.save(configFile);
} catch (IOException ignored) { }
}
// Load the data
serverUUID = config.getString("serverUuid");
logFailedRequests = config.getBoolean("logFailedRequests", false);
if (config.getBoolean("enabled", true)) {
boolean found = false;
// Search for all other bStats Metrics classes to see if we are the first one
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
found = true; // We aren't the first
break;
} catch (NoSuchFieldException ignored) { }
}
// Register our service
Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal);
if (!found) {
// We are the first!
startSubmitting();
}
}
}
/**
* Adds a custom chart.
*
* @param chart The chart to add.
*/
public void addCustomChart(CustomChart chart) {
if (chart == null) {
throw new IllegalArgumentException("Chart cannot be null!");
}
charts.add(chart);
}
/**
* Starts the Scheduler which submits our data every 30 minutes.
*/
private void startSubmitting() {
final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (!plugin.isEnabled()) { // Plugin was disabled
timer.cancel();
return;
}
// Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
// Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
Bukkit.getScheduler().runTask(plugin, new Runnable() {
@Override
public void run() {
submitData();
}
});
}
}, 1000*60*5, 1000*60*30);
// Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
// WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
// WARNING: Just don't do it!
}
/**
* Gets the plugin specific data.
* This method is called using Reflection.
*
* @return The plugin specific data.
*/
public JSONObject getPluginData() {
JSONObject data = new JSONObject();
String pluginName = plugin.getDescription().getName();
String pluginVersion = plugin.getDescription().getVersion();
data.put("pluginName", pluginName); // Append the name of the plugin
data.put("pluginVersion", pluginVersion); // Append the version of the plugin
JSONArray customCharts = new JSONArray();
for (CustomChart customChart : charts) {
// Add the data of the custom charts
JSONObject chart = customChart.getRequestJsonObject();
if (chart == null) { // If the chart is null, we skip it
continue;
}
customCharts.add(chart);
}
data.put("customCharts", customCharts);
return data;
}
/**
* Gets the server specific data.
*
* @return The server specific data.
*/
private JSONObject getServerData() {
// Minecraft specific data
int playerAmount;
try {
// Around MC 1.8 the return type was changed to a collection from an array,
// This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class)
? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
: ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
} catch (Exception e) {
playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed
}
int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
String bukkitVersion = org.bukkit.Bukkit.getVersion();
bukkitVersion = bukkitVersion.substring(bukkitVersion.indexOf("MC: ") + 4, bukkitVersion.length() - 1);
// OS/Java specific data
String javaVersion = System.getProperty("java.version");
String osName = System.getProperty("os.name");
String osArch = System.getProperty("os.arch");
String osVersion = System.getProperty("os.version");
int coreCount = Runtime.getRuntime().availableProcessors();
JSONObject data = new JSONObject();
data.put("serverUUID", serverUUID);
data.put("playerAmount", playerAmount);
data.put("onlineMode", onlineMode);
data.put("bukkitVersion", bukkitVersion);
data.put("javaVersion", javaVersion);
data.put("osName", osName);
data.put("osArch", osArch);
data.put("osVersion", osVersion);
data.put("coreCount", coreCount);
return data;
}
/**
* Collects the data and sends it afterwards.
*/
private void submitData() {
final JSONObject data = getServerData();
JSONArray pluginData = new JSONArray();
// Search for all other bStats Metrics classes to get their plugin data
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
for (RegisteredServiceProvider<?> provider : Bukkit.getServicesManager().getRegistrations(service)) {
try {
pluginData.add(provider.getService().getMethod("getPluginData").invoke(provider.getProvider()));
} catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { }
}
} catch (NoSuchFieldException ignored) { }
}
data.put("plugins", pluginData);
// Create a new thread for the connection to the bStats server
new Thread(new Runnable() {
@Override
public void run() {
try {
// Send the data
sendData(data);
} catch (Exception e) {
// Something went wrong! :(
if (logFailedRequests) {
plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e);
}
}
}
}).start();
}
/**
* Sends the data to the bStats server.
*
* @param data The data to send.
* @throws Exception If the request failed.
*/
private static void sendData(JSONObject data) throws Exception {
if (data == null) {
throw new IllegalArgumentException("Data cannot be null!");
}
if (Bukkit.isPrimaryThread()) {
throw new IllegalAccessException("This method must not be called from the main thread!");
}
HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
// Compress the data to save bandwidth
byte[] compressedData = compress(data.toString());
// Add headers
connection.setRequestMethod("POST");
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
// Send data
connection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.write(compressedData);
outputStream.flush();
outputStream.close();
connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}
/**
* Gzips the given String.
*
* @param str The string to gzip.
* @return The gzipped String.
* @throws IOException If the compression failed.
*/
private static byte[] compress(final String str) throws IOException {
if (str == null) {
return null;
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(outputStream);
gzip.write(str.getBytes("UTF-8"));
gzip.close();
return outputStream.toByteArray();
}
/**
* Represents a custom chart.
*/
public static abstract class CustomChart {
// The id of the chart
final String chartId;
/**
* Class constructor.
*
* @param chartId The id of the chart.
*/
CustomChart(String chartId) {
if (chartId == null || chartId.isEmpty()) {
throw new IllegalArgumentException("ChartId cannot be null or empty!");
}
this.chartId = chartId;
}
private JSONObject getRequestJsonObject() {
JSONObject chart = new JSONObject();
chart.put("chartId", chartId);
try {
JSONObject data = getChartData();
if (data == null) {
// If the data is null we don't send the chart.
return null;
}
chart.put("data", data);
} catch (Throwable t) {
if (logFailedRequests) {
Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t);
}
return null;
}
return chart;
}
protected abstract JSONObject getChartData() throws Exception;
}
/**
* Represents a custom simple pie.
*/
public static class SimplePie extends CustomChart {
private final Callable<String> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SimplePie(String chartId, Callable<String> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
String value = callable.call();
if (value == null || value.isEmpty()) {
// Null = skip the chart
return null;
}
data.put("value", value);
return data;
}
}
/**
* Represents a custom advanced pie.
*/
public static class AdvancedPie extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public AdvancedPie(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
continue; // Skip this invalid
}
allSkipped = false;
values.put(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
}
/**
* Represents a custom drilldown pie.
*/
public static class DrilldownPie extends CustomChart {
private final Callable<Map<String, Map<String, Integer>>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public DrilldownPie(String chartId, Callable<Map<String, Map<String, Integer>>> callable) {
super(chartId);
this.callable = callable;
}
@Override
public JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, Map<String, Integer>> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean reallyAllSkipped = true;
for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {
JSONObject value = new JSONObject();
boolean allSkipped = true;
for (Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) {
value.put(valueEntry.getKey(), valueEntry.getValue());
allSkipped = false;
}
if (!allSkipped) {
reallyAllSkipped = false;
values.put(entryValues.getKey(), value);
}
}
if (reallyAllSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
}
/**
* Represents a custom single line chart.
*/
public static class SingleLineChart extends CustomChart {
private final Callable<Integer> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SingleLineChart(String chartId, Callable<Integer> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
int value = callable.call();
if (value == 0) {
// Null = skip the chart
return null;
}
data.put("value", value);
return data;
}
}
/**
* Represents a custom multi line chart.
*/
public static class MultiLineChart extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public MultiLineChart(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
continue; // Skip this invalid
}
allSkipped = false;
values.put(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
}
/**
* Represents a custom simple bar chart.
*/
public static class SimpleBarChart extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SimpleBarChart(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
JSONArray categoryValues = new JSONArray();
categoryValues.add(entry.getValue());
values.put(entry.getKey(), categoryValues);
}
data.put("values", values);
return data;
}
}
/**
* Represents a custom advanced bar chart.
*/
public static class AdvancedBarChart extends CustomChart {
private final Callable<Map<String, int[]>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public AdvancedBarChart(String chartId, Callable<Map<String, int[]>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, int[]> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, int[]> entry : map.entrySet()) {
if (entry.getValue().length == 0) {
continue; // Skip this invalid
}
allSkipped = false;
JSONArray categoryValues = new JSONArray();
for (int categoryValue : entry.getValue()) {
categoryValues.add(categoryValue);
}
values.put(entry.getKey(), categoryValues);
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
}
}

View File

@ -1,30 +0,0 @@
/*
CitizensCMD - Add-on for Citizens
Copyright (C) 2018 Mateus Moreira
<p>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
<p>
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
<p>
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package me.mattstudios.citizenscmd.utility;
/**
* Created by GlareMasters on 5/30/2018.
*/
public interface IHandler {
void enable();
void disable();
}

View File

@ -101,58 +101,6 @@ public class Util {
return plugin.getConfig().getInt("default-cooldown");
}
/**
* Gets arguments from each command for the tab completion
*
* @return Returns 2d string array with arguments for tab completion
*/
public static String[][] getTabCompleteArgs(CitizensCMD plugin, String subCMD, Player player) {
String[][] argComplete = new String[5][];
switch (subCMD) {
case "add":
argComplete[0] = new String[]{"console", "none", "permission", "server", "message", "sound"};
argComplete[1] = getSoundsList();
argComplete[2] = new String[]{"1", "0.5"};
argComplete[3] = new String[]{"1", "0.5"};
break;
case "remove":
argComplete[0] = new String[]{"left", "right"};
argComplete[1] = plugin.getDataHandler().getCompleteCommandsNumbers(getSelectedNpcId(player), EnumTypes.ClickType.LEFT);
argComplete[2] = plugin.getDataHandler().getCompleteCommandsNumbers(getSelectedNpcId(player), EnumTypes.ClickType.RIGHT);
break;
case "cooldown":
argComplete[0] = new String[]{"1", "2", "5", "10"};
break;
case "permission":
argComplete[0] = new String[]{"set", "remove"};
break;
case "edit":
argComplete[0] = new String[]{"perm", "cmd"};
argComplete[1] = new String[]{"left", "right"};
argComplete[2] = plugin.getDataHandler().getCompleteCommandsNumbers(getSelectedNpcId(player), EnumTypes.ClickType.LEFT);
argComplete[3] = plugin.getDataHandler().getCompleteCommandsNumbers(getSelectedNpcId(player), EnumTypes.ClickType.RIGHT);
argComplete[4] = new String[]{"console", "none", "permission", "server", "message"};
break;
}
return argComplete;
}
private static String[] getSoundsList() {
Sound[] sounds = Sound.values();
String[] soundString = new String[sounds.length];
for (int i = 0; i < sounds.length; i++) {
soundString[i] = sounds[i].name();
}
return soundString;
}
/**
* Gets the difference in seconds between times
*

View File

@ -7,6 +7,14 @@
# Alguns placeholders podem ser removidos mas podem não funcionar corretamente.
# Os placeholders do cooldown podem ser removidos com segurança.
messages:
# Start up comments test
start-up:
using-language: "&7Using &aEnglish &7messages!"
new-version: "&cA new version of CitizensCMD is now available:"
# In between comment test
papi-available: "&7Using &aPlaceholderAPI&7!"
vault-available: "&7Using &aVault&7!"
# Command comments test
commands:
npc-add-command-added: "&aVocê adicionou um comando ao NPC com sucesso!"
npc-add-command-failed: "&cFalha ao adicionar comando ao NPC!"

View File

@ -12,16 +12,16 @@ softdepend: [Citizens, PlaceholderAPI, Vault]
api-version: 1.13
commands:
npcmd:
description: Performs all npcmd commands.
npcmd add:
description: Adds command to the NPC.
npcmd help:
description: Displays help
npcmd add:
description: Adds a new command to the NPC
npcmd cooldown:
description: Sets the cooldown for the NPC
npcmd price:
description: Sets the price for the NPC
npcmd permission:
description: Sets the permission for the NPC
npcmd list:
description: Gets the list of commands
npcmd reload:
@ -47,6 +47,8 @@ permissions:
default: op
citizenscmd.reload:
default: op
citizenscmd.permission:
default: op
citizenscmd.remove:
default: op
citizenscmd.edit: