Skip to content
This repository was archived by the owner on Jan 30, 2023. It is now read-only.

Commit

Permalink
Merge pull request #11 from Crsuh2er0/main
Browse files Browse the repository at this point in the history
修复reload指令 增加request指令 #9
  • Loading branch information
Crsuh2er0 authored Oct 27, 2022
2 parents 3b4f1ea + a63dea8 commit 9c4445d
Show file tree
Hide file tree
Showing 15 changed files with 237 additions and 109 deletions.
6 changes: 1 addition & 5 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<groupId>cn.lingsmc</groupId>
<artifactId>LingsHTTPUtils</artifactId>
<version>1.2.4</version>
<version>1.2.5</version>
<packaging>jar</packaging>

<name>LingsHTTPUtils</name>
Expand Down Expand Up @@ -64,10 +64,6 @@
<id>spigotmc-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
<repository>
<id>sonatype</id>
<url>https://oss.sonatype.org/content/groups/public/</url>
</repository>
<repository>
<id>placeholderapi</id>
<url>https://repo.extendedclip.com/content/repositories/placeholderapi/</url>
Expand Down
2 changes: 2 additions & 0 deletions src/main/java/cn/lingsmc/lingshttputils/LingsHttpUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,10 @@
// TODO 使间隔适用于intime类
// TODO 支持脚本化操作
// TODO 支持模块分文件
// TODO 添加多语言支持

public final class LingsHttpUtils extends JavaPlugin {

public static FileConfiguration config;
@Getter
private static LingsHttpUtils instance;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@
import cn.lingsmc.lingshttputils.LingsHttpUtils;
import cn.lingsmc.lingshttputils.utils.HttpUtils;
import cn.lingsmc.lingshttputils.utils.JsonUtils;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;

import java.util.Objects;
Expand All @@ -19,32 +17,31 @@
*/
public class AsyncWorkers {
static Plugin plugin = LingsHttpUtils.getInstance();
Runnable task;

public void asyncworker(String module, int reqTime, String url, String method, int refInterval, String[] keys) {
task = new BukkitRunnable() {
public void runAsyncWorker(String module, int reqTime, String url, String method, int refInterval, String[] keys) {
if (refInterval < 0) {
plugin.getLogger().log(Level.SEVERE, "Worker: {0} 出现错误!模块请求间隔必须为正值!", module);
return;
}
new BukkitRunnable() {
@Override
public void run() {
String res = HttpUtils.request(url, reqTime, method);
if (res == null) {
// plugin.getLogger().info(String.format("%s进行了一次请求!",module));
String res = HttpUtils.httpRequest(url, reqTime, method);
if (Objects.isNull(res)) {
return;
}
if ("json".equalsIgnoreCase(LingsHttpUtils.config.getString(String.format("%s.mode", module)))) {
res = JsonUtils.getValue(res, keys);
if (Objects.isNull(res)) {
plugin.getLogger().log(Level.WARNING, "Worker: {0} 获取Json内容时出现错误! 请检查是否符合格式要求!", module);
plugin.getLogger().log(Level.SEVERE, "Worker: {0} 获取Json内容时出现错误! 请检查是否符合格式要求!", module);
}
}
LingsHttpUtils.getInstance().getHttpData().put(module, res);
try {
Thread.sleep(refInterval);
} catch (InterruptedException e) {
plugin.getLogger().log(Level.WARNING, "Worker: {0} 出现错误!模块请求间隔必须为正值!", module);
e.printStackTrace();
LingsHttpUtils.getInstance().getHttpData().put(module, res);
} catch (Exception ignored) {
}
Bukkit.getScheduler().runTaskAsynchronously(JavaPlugin.getPlugin(LingsHttpUtils.class), task);
}
};
Bukkit.getScheduler().runTaskAsynchronously(JavaPlugin.getPlugin(LingsHttpUtils.class), task);
}.runTaskTimerAsynchronously(plugin, 0, (long) refInterval / 1000 * 20);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

import cn.lingsmc.lingshttputils.LingsHttpUtils;
import lombok.Getter;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;

import java.util.Objects;
import java.util.Set;
import java.util.concurrent.*;
import java.util.logging.Level;

/**
Expand All @@ -16,8 +16,7 @@
*/
public class WorkerOptions {
@Getter
static boolean started = true;
static ExecutorService threadPool;
static boolean started = false;

static LingsHttpUtils plugin = LingsHttpUtils.getInstance();

Expand All @@ -26,52 +25,45 @@ private WorkerOptions() {
}

public static void runWorkers() {
started = true;
FileConfiguration config = LingsHttpUtils.config;
Set<String> modules = config.getKeys(false);
modules.remove("version");
modules.removeIf(module -> !Objects.equals(config.getString(String.format("%s.reqMode", module)), "Cycle"));
modules.removeIf(module -> Objects.equals(config.getBoolean(String.format("%s.enabled", module)), false));
if (modules.isEmpty()) {
return;
}

threadPool = new ThreadPoolExecutor(1, modules.size(),
1L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(Integer.MAX_VALUE),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());

for (String module : modules) {
// 一定要为每个module设置一个worker
AsyncWorkers asyncWorkers = new AsyncWorkers();
final int reqTime = config.getInt(String.format("%s.reqTime", module));
final String url = config.getString(String.format("%s.url", module));
final String method;
final int refInterval = config.getInt(String.format("%s.refInterval", module));
if (Objects.nonNull(config.getString(String.format("%s.method", module)))) {
method = config.getString(String.format("%s.method", module));
} else {
method = "GET";
if (!started) {
started = true;
FileConfiguration config = LingsHttpUtils.config;
Set<String> modules = config.getKeys(false);
modules.remove("version");
modules.removeIf(module -> !Objects.equals(config.getString(String.format("%s.reqMode", module)), "Cycle"));
modules.removeIf(module -> Objects.equals(config.getBoolean(String.format("%s.enabled", module)), false));
if (modules.isEmpty()) {
return;
}
String[] keys = new String[0];
if ("json".equalsIgnoreCase(config.getString(String.format("%s.mode", module)))) {
keys = config.getString(String.format("%s.key", module)).split("\\.");

for (String module : modules) {
// 一定要为每个module设置一个worker
AsyncWorkers asyncWorkers = new AsyncWorkers();
final int reqTime = config.getInt(String.format("%s.reqTime", module));
final String url = config.getString(String.format("%s.url", module));
final String method;
final int refInterval = config.getInt(String.format("%s.refInterval", module));
if (Objects.nonNull(config.getString(String.format("%s.method", module)))) {
method = config.getString(String.format("%s.method", module));
} else {
method = "GET";
}
String[] keys = new String[0];
if ("json".equalsIgnoreCase(config.getString(String.format("%s.mode", module)))) {
keys = config.getString(String.format("%s.key", module)).split("\\.");
}
String[] finalKeys = keys;
LingsHttpUtils.getInstance().getLogger().log(Level.INFO, "尝试启动{0}...", module);
asyncWorkers.runAsyncWorker(module, reqTime, url, method, refInterval, finalKeys);
}
String[] finalKeys = keys;
Runnable runnable = () -> asyncWorkers.asyncworker(module, reqTime, url, method, refInterval, finalKeys);
LingsHttpUtils.getInstance().getLogger().log(Level.INFO, "尝试启动{0}...", module);
threadPool.execute(runnable);
}
}

public static void stopWorkers() {
plugin.getLogger().info("尝试关闭Cycle Workers...");
try {
threadPool.shutdownNow();
} catch (Exception ignored) {
plugin.getLogger().info("没有Cycle Workers被关闭,因为没有已启用的Cycle Workers");
if (started) {
plugin.getLogger().info("尝试关闭Cycle Workers...");
Bukkit.getScheduler().cancelTasks(plugin);
started = false;
}
started = false;
}
}
25 changes: 23 additions & 2 deletions src/main/java/cn/lingsmc/lingshttputils/commands/Commands.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ public class Commands implements CommandExecutor {
static String rootMessage1 = String.format("%s此服务器正在运行 %s%s %s%s by %s", ChatColor.DARK_AQUA, ChatColor.AQUA, LingsHttpUtils.getInstance().getName(), LingsHttpUtils.getInstance().getDescription().getVersion(), ChatColor.DARK_AQUA, "§aC§br§cs§du§eh§a2§be§cr§d0");
static String rootMessage2 = String.format("%s命令列表: %s/lhu help", ChatColor.DARK_AQUA, ChatColor.AQUA);
static String permission = "lingshttputils.admin";
static String notEnoughArgs = String.format("%s参数错误! 正确用法:", ChatColor.RED);
static String requestMessage = String.format("%s/lhu request <module> %s请求配置文件中某模块的数据", ChatColor.AQUA, ChatColor.GREEN);
static String workersMessage = String.format("%s/lhu workers <start/stop> %s启动/关闭Cycle Workers", ChatColor.AQUA, ChatColor.GREEN);

@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String @NotNull [] args) {
Expand All @@ -27,13 +30,31 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command
}
switch (args[0]) {
case "reload":
ReloadCommand.reloadCommand(sender);
try {
ReloadCommand.reloadCommand(sender);
} catch (Exception e) {
e.printStackTrace();
}
break;
case "help":
HelpCommand.helpCommand(sender);
break;
case "workers":
WorkerOptionCommands.workerOptionCommands(sender, args);
// 检查参数是否充足
if (args.length < 2) {
sender.sendMessage(notEnoughArgs);
sender.sendMessage(workersMessage);
} else {
WorkerOptionCommands.workerOptionCommands(sender, args);
}
break;
case "request":
if (args.length == 2) {
RequestCommand.request(args[1], sender);
} else {
sender.sendMessage(notEnoughArgs);
sender.sendMessage(requestMessage);
}
break;
default:
sender.sendMessage(helpMessage);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ private HelpCommand() {
public static void helpCommand(@NotNull CommandSender sender) {
sender.sendMessage(String.format("%s%s----- LingsHttpUtils指令 -----", ChatColor.DARK_AQUA, ChatColor.BOLD));
sender.sendMessage(String.format("%s/lhu workers <start/stop> %s启动/关闭Cycle Workers", ChatColor.AQUA, ChatColor.GREEN));
sender.sendMessage(String.format("%s/lhu request <module> %s请求配置文件中某模块的数据", ChatColor.AQUA, ChatColor.GREEN));
sender.sendMessage(String.format("%s/lhu reload %s重载插件", ChatColor.AQUA, ChatColor.GREEN));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,14 @@ public static void reloadCommand(@NotNull CommandSender sender) {
sender.sendMessage(String.format("%s你没有执行此命令的权限.", ChatColor.RED));
return;
}
sender.sendMessage(String.format("%s正在重载中...", ChatColor.AQUA));
WorkerOptions.stopWorkers();
File file = new File(plugin.getDataFolder(), "config.yml");
if (!file.exists()) {
plugin.saveDefaultConfig();
}
plugin.reloadConfig();
LingsHttpUtils.config = plugin.getConfig();
WorkerOptions.runWorkers();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package cn.lingsmc.lingshttputils.commands;

import cn.lingsmc.lingshttputils.LingsHttpUtils;
import cn.lingsmc.lingshttputils.utils.HttpUtils;
import cn.lingsmc.lingshttputils.utils.JsonUtils;
import cn.lingsmc.lingshttputils.utils.MessageUtils;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.scheduler.BukkitRunnable;
import org.jetbrains.annotations.NotNull;

import java.util.Objects;
import java.util.Set;
import java.util.logging.Level;

/**
* @author Crsuh2er0
* @apiNote
* @since 2022/10/20
*/
public class RequestCommand {
private static final FileConfiguration CONFIG = LingsHttpUtils.getInstance().getConfig();
static LingsHttpUtils plugin = LingsHttpUtils.getInstance();

private RequestCommand() {
}

public static void request(String module, @NotNull CommandSender sender) {
if (!sender.hasPermission(Commands.permission)) {
sender.sendMessage(String.format("%s你没有执行此命令的权限.", ChatColor.RED));
return;
}
// 判断是否有此模块
Set<String> modules = CONFIG.getKeys(false);
if (!modules.contains(module)) {
MessageUtils.sendMessage(sender, String.format("%s错误:未找到此模块. 请检查拼写以及是否已重载配置文件.", ChatColor.RED));
return;
}
// 不管是循环还是及时都直接请求一次
new BukkitRunnable() {
@Override
public void run() {
int reqTime = CONFIG.getInt(String.format("%s.reqTime", module));
String url = CONFIG.getString(String.format("%s.url", module));
String method;
try {
method = CONFIG.getString(String.format("%s.method", module));
} catch (Exception ignored) {
method = "GET";
}
String res = HttpUtils.httpRequest(url, reqTime, method);
if (Objects.isNull(res)) {
return;
}
if ("json".equalsIgnoreCase(LingsHttpUtils.config.getString(String.format("%s.mode", module)))) {
String[] keys = CONFIG.getString(String.format("%s.key", module)).split("\\.");
res = JsonUtils.getValue(res, keys);
if (Objects.isNull(res)) {
plugin.getLogger().log(Level.SEVERE, "Worker: {0} 获取Json内容时出现错误! 请检查是否符合格式要求!", module);
}
}
// 判断结果是否为null或空值
if (Objects.isNull(res) || res.isEmpty()) {
MessageUtils.sendMessage(sender, String.format("%s%s %s获取到的结果为 %snull", ChatColor.YELLOW, module, ChatColor.GREEN, ChatColor.GOLD));
} else {
MessageUtils.sendMessage(sender, String.format("%s%s %s获取到的结果为 %s%s", ChatColor.YELLOW, module, ChatColor.GREEN, ChatColor.GOLD, res));
}
}
}.runTaskAsynchronously(plugin);
}
}
32 changes: 24 additions & 8 deletions src/main/java/cn/lingsmc/lingshttputils/commands/TabComplete.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
package cn.lingsmc.lingshttputils.commands;

import cn.lingsmc.lingshttputils.LingsHttpUtils;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
* @author Crsuh2er0
Expand All @@ -17,7 +20,7 @@ public class TabComplete implements org.bukkit.command.TabCompleter {
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String @NotNull [] args) {

final String[] root = new String[]{"workers", "help", "reload"};
final String[] root = new String[]{"workers", "help", "reload", "request"};
final String[] worker = new String[]{"start", "stop"};

if (args.length == 1) {
Expand All @@ -30,16 +33,29 @@ public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Comman
return res;
}

if (args.length == 2 && root[0].equalsIgnoreCase(args[0])) {
List<String> res = new ArrayList<>();
for (String val : worker) {
if (val.contains(args[1])) {
res.add(val);
if (args.length == 2) {
if (root[0].equalsIgnoreCase(args[0])) {
List<String> res = new ArrayList<>();
for (String val : worker) {
if (val.contains(args[1])) {
res.add(val);
}
}
return res;
}
if (root[3].equalsIgnoreCase(args[0])) {
List<String> res = new ArrayList<>();
FileConfiguration config = LingsHttpUtils.config;
Set<String> modules = config.getKeys(false);
modules.remove("version");
for (String module : modules) {
if (module.contains(args[1])) {
res.add(module);
}
}
return res;
}
return res;
}

return Collections.emptyList();
}
}
Loading

0 comments on commit 9c4445d

Please sign in to comment.