PageRenderTime 50ms CodeModel.GetById 32ms app.highlight 15ms RepoModel.GetById 0ms app.codeStats 0ms

/worldguard-legacy/src/main/java/com/sk89q/worldguard/bukkit/commands/WorldGuardCommands.java

https://gitlab.com/igserfurtmcschulserver/CustomWorldGuard
Java | 296 lines | 240 code | 36 blank | 20 comment | 32 complexity | e10661b790b9e27f56cd8398e8c92022 MD5 | raw file
  1/*
  2 * WorldGuard, a suite of tools for Minecraft
  3 * Copyright (C) sk89q <http://www.sk89q.com>
  4 * Copyright (C) WorldGuard team and contributors
  5 *
  6 * This program is free software: you can redistribute it and/or modify it
  7 * under the terms of the GNU Lesser General Public License as published by the
  8 * Free Software Foundation, either version 3 of the License, or
  9 * (at your option) any later version.
 10 *
 11 * This program is distributed in the hope that it will be useful, but WITHOUT
 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 14 * for more details.
 15 *
 16 * You should have received a copy of the GNU Lesser General Public License
 17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 18 */
 19
 20package com.sk89q.worldguard.bukkit.commands;
 21
 22import com.google.common.base.Predicate;
 23import com.google.common.base.Predicates;
 24import com.google.common.io.Files;
 25import com.google.common.util.concurrent.FutureCallback;
 26import com.google.common.util.concurrent.Futures;
 27import com.google.common.util.concurrent.MoreExecutors;
 28import com.sk89q.minecraft.util.commands.*;
 29import com.sk89q.worldguard.bukkit.ConfigurationManager;
 30import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
 31import com.sk89q.worldguard.bukkit.util.logging.LoggerToChatHandler;
 32import com.sk89q.worldguard.bukkit.util.report.*;
 33import com.sk89q.worldguard.util.profiler.SamplerBuilder;
 34import com.sk89q.worldguard.util.profiler.SamplerBuilder.Sampler;
 35import com.sk89q.worldguard.util.profiler.ThreadIdFilter;
 36import com.sk89q.worldguard.util.profiler.ThreadNameFilter;
 37import com.sk89q.worldguard.util.report.ReportList;
 38import com.sk89q.worldguard.util.report.SystemInfoReport;
 39import com.sk89q.worldguard.util.task.Task;
 40import com.sk89q.worldguard.util.task.TaskStateComparator;
 41import org.bukkit.Bukkit;
 42import org.bukkit.ChatColor;
 43import org.bukkit.World;
 44import org.bukkit.command.CommandSender;
 45import org.bukkit.entity.Player;
 46
 47import javax.annotation.Nullable;
 48import java.io.File;
 49import java.io.IOException;
 50import java.lang.management.ThreadInfo;
 51import java.nio.charset.Charset;
 52import java.util.Collections;
 53import java.util.List;
 54import java.util.concurrent.TimeUnit;
 55import java.util.logging.Level;
 56import java.util.logging.Logger;
 57
 58public class WorldGuardCommands {
 59
 60    private static final Logger log = Logger.getLogger(WorldGuardCommands.class.getCanonicalName());
 61
 62    private final WorldGuardPlugin plugin;
 63    @Nullable
 64    private Sampler activeSampler;
 65
 66    public WorldGuardCommands(WorldGuardPlugin plugin) {
 67        this.plugin = plugin;
 68    }
 69
 70    @Command(aliases = {"version"}, desc = "Get the WorldGuard version", max = 0)
 71    public void version(CommandContext args, CommandSender sender) throws CommandException {
 72        sender.sendMessage(ChatColor.YELLOW
 73                + "WorldGuard " + plugin.getDescription().getVersion());
 74        sender.sendMessage(ChatColor.YELLOW
 75                + "http://www.sk89q.com");
 76    }
 77
 78    @Command(aliases = {"reload"}, desc = "Reload WorldGuard configuration", max = 0)
 79    @CommandPermissions({"worldguard.reload"})
 80    public void reload(CommandContext args, CommandSender sender) throws CommandException {
 81        // TODO: This is subject to a race condition, but at least other commands are not being processed concurrently
 82        List<Task<?>> tasks = plugin.getSupervisor().getTasks();
 83        if (!tasks.isEmpty()) {
 84            throw new CommandException("There are currently pending tasks. Use /wg running to monitor these tasks first.");
 85        }
 86        
 87        LoggerToChatHandler handler = null;
 88        Logger minecraftLogger = null;
 89        
 90        if (sender instanceof Player) {
 91            handler = new LoggerToChatHandler(sender);
 92            handler.setLevel(Level.ALL);
 93            minecraftLogger = Logger.getLogger("com.sk89q.worldguard");
 94            minecraftLogger.addHandler(handler);
 95        }
 96
 97        try {
 98            ConfigurationManager config = plugin.getGlobalStateManager();
 99            config.unload();
100            config.load();
101            for (World world : Bukkit.getServer().getWorlds()) {
102                config.get(world);
103            }
104            plugin.getRegionContainer().reload();
105            // WGBukkit.cleanCache();
106            sender.sendMessage("WorldGuard configuration reloaded.");
107        } catch (Throwable t) {
108            sender.sendMessage("Error while reloading: "
109                    + t.getMessage());
110        } finally {
111            if (minecraftLogger != null) {
112                minecraftLogger.removeHandler(handler);
113            }
114        }
115    }
116    
117    @Command(aliases = {"report"}, desc = "Writes a report on WorldGuard", flags = "p", max = 0)
118    @CommandPermissions({"worldguard.report"})
119    public void report(CommandContext args, final CommandSender sender) throws CommandException {
120        ReportList report = new ReportList("Report");
121        report.add(new SystemInfoReport());
122        report.add(new ServerReport());
123        report.add(new PluginReport());
124        report.add(new SchedulerReport());
125        report.add(new ServicesReport());
126        report.add(new WorldReport());
127        report.add(new PerformanceReport());
128        report.add(new ConfigReport(plugin));
129        String result = report.toString();
130
131        try {
132            File dest = new File(plugin.getDataFolder(), "report.txt");
133            Files.write(result, dest, Charset.forName("UTF-8"));
134            sender.sendMessage(ChatColor.YELLOW + "WorldGuard report written to " + dest.getAbsolutePath());
135        } catch (IOException e) {
136            throw new CommandException("Failed to write report: " + e.getMessage());
137        }
138        
139        if (args.hasFlag('p')) {
140            plugin.checkPermission(sender, "worldguard.report.pastebin");
141            CommandUtils.pastebin(plugin, sender, result, "WorldGuard report: %s.report");
142        }
143    }
144
145    @Command(aliases = {"profile"}, usage = "[<minutes>]",
146            desc = "Profile the CPU usage of the server", min = 0, max = 1,
147            flags = "t:p")
148    @CommandPermissions("worldguard.profile")
149    public void profile(final CommandContext args, final CommandSender sender) throws CommandException {
150        Predicate<ThreadInfo> threadFilter;
151        String threadName = args.getFlag('t');
152        final boolean pastebin;
153
154        if (args.hasFlag('p')) {
155            plugin.checkPermission(sender, "worldguard.report.pastebin");
156            pastebin = true;
157        } else {
158            pastebin = false;
159        }
160
161        if (threadName == null) {
162            threadFilter = new ThreadIdFilter(Thread.currentThread().getId());
163        } else if (threadName.equals("*")) {
164            threadFilter = Predicates.alwaysTrue();
165        } else {
166            threadFilter = new ThreadNameFilter(threadName);
167        }
168
169        int minutes;
170        if (args.argsLength() == 0) {
171            minutes = 5;
172        } else {
173            minutes = args.getInteger(0);
174            if (minutes < 1) {
175                throw new CommandException("You must run the profile for at least 1 minute.");
176            } else if (minutes > 10) {
177                throw new CommandException("You can profile for, at maximum, 10 minutes.");
178            }
179        }
180
181        Sampler sampler;
182
183        synchronized (this) {
184            if (activeSampler != null) {
185                throw new CommandException("A profile is currently in progress! Please use /wg stopprofile to stop the current profile.");
186            }
187
188            SamplerBuilder builder = new SamplerBuilder();
189            builder.setThreadFilter(threadFilter);
190            builder.setRunTime(minutes, TimeUnit.MINUTES);
191            sampler = activeSampler = builder.start();
192        }
193
194        AsyncCommandHelper.wrap(sampler.getFuture(), plugin, sender)
195                .formatUsing(minutes)
196                .registerWithSupervisor("Running CPU profiler for %d minute(s)...")
197                .sendMessageAfterDelay("(Please wait... profiling for %d minute(s)...)")
198                .thenTellErrorsOnly("CPU profiling failed.");
199
200        sampler.getFuture().addListener(new Runnable() {
201            @Override
202            public void run() {
203                synchronized (WorldGuardCommands.this) {
204                    activeSampler = null;
205                }
206            }
207        }, MoreExecutors.sameThreadExecutor());
208
209        Futures.addCallback(sampler.getFuture(), new FutureCallback<Sampler>() {
210            @Override
211            public void onSuccess(Sampler result) {
212                String output = result.toString();
213
214                try {
215                    File dest = new File(plugin.getDataFolder(), "profile.txt");
216                    Files.write(output, dest, Charset.forName("UTF-8"));
217                    sender.sendMessage(ChatColor.YELLOW + "CPU profiling data written to " + dest.getAbsolutePath());
218                } catch (IOException e) {
219                    sender.sendMessage(ChatColor.RED + "Failed to write CPU profiling data: " + e.getMessage());
220                }
221
222                if (pastebin) {
223                    CommandUtils.pastebin(plugin, sender, output, "Profile result: %s.profile");
224                }
225            }
226
227            @Override
228            public void onFailure(Throwable throwable) {
229            }
230        });
231    }
232
233    @Command(aliases = {"stopprofile"}, usage = "",desc = "Stop a running profile", min = 0, max = 0)
234    @CommandPermissions("worldguard.profile")
235    public void stopProfile(CommandContext args, final CommandSender sender) throws CommandException {
236        synchronized (this) {
237            if (activeSampler == null) {
238                throw new CommandException("No CPU profile is currently running.");
239            }
240
241            activeSampler.cancel();
242            activeSampler = null;
243        }
244
245        sender.sendMessage("The running CPU profile has been stopped.");
246    }
247
248    @Command(aliases = {"flushstates", "clearstates"},
249            usage = "[player]", desc = "Flush the state manager", max = 1)
250    @CommandPermissions("worldguard.flushstates")
251    public void flushStates(CommandContext args, CommandSender sender) throws CommandException {
252        if (args.argsLength() == 0) {
253            plugin.getSessionManager().resetAllStates();
254            sender.sendMessage("Cleared all states.");
255        } else {
256            Player player = plugin.getServer().getPlayer(args.getString(0));
257            if (player != null) {
258                plugin.getSessionManager().resetState(player);
259                sender.sendMessage("Cleared states for player \"" + player.getName() + "\".");
260            }
261        }
262    }
263
264    @Command(aliases = {"running", "queue"}, desc = "List running tasks", max = 0)
265    @CommandPermissions("worldguard.running")
266    public void listRunningTasks(CommandContext args, CommandSender sender) throws CommandException {
267        List<Task<?>> tasks = plugin.getSupervisor().getTasks();
268
269        if (!tasks.isEmpty()) {
270            Collections.sort(tasks, new TaskStateComparator());
271            StringBuilder builder = new StringBuilder();
272            builder.append(ChatColor.GRAY);
273            builder.append("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");
274            builder.append(" Running tasks ");
275            builder.append("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");
276            builder.append("\n").append(ChatColor.GRAY).append("Note: Some 'running' tasks may be waiting to be start.");
277            for (Task task : tasks) {
278                builder.append("\n");
279                builder.append(ChatColor.BLUE).append("(").append(task.getState().name()).append(") ");
280                builder.append(ChatColor.YELLOW);
281                builder.append(CommandUtils.getOwnerName(task.getOwner()));
282                builder.append(": ");
283                builder.append(ChatColor.WHITE);
284                builder.append(task.getName());
285            }
286            sender.sendMessage(builder.toString());
287        } else {
288            sender.sendMessage(ChatColor.YELLOW + "There are currently no running tasks.");
289        }
290    }
291
292    @Command(aliases = {"debug"}, desc = "Debugging commands")
293    @NestedCommand({DebuggingCommands.class})
294    public void debug(CommandContext args, CommandSender sender) {}
295
296}