prefix
stringlengths
82
32.6k
middle
stringlengths
5
470
suffix
stringlengths
0
81.2k
file_path
stringlengths
6
168
repo_name
stringlengths
16
77
context
listlengths
5
5
lang
stringclasses
4 values
ground_truth
stringlengths
5
470
package de.cubeattack.neoprotect.core.executor; import de.cubeattack.api.API; import de.cubeattack.api.language.Localization; import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration; import de.cubeattack.api.libraries.org.json.JSONObject; import de.cubeattack.neoprotect.core.Config; import de.cubeattack.neoprotect.core.NeoProtectPlugin; import de.cubeattack.neoprotect.core.model.Backend; import de.cubeattack.neoprotect.core.model.Gameshield; import de.cubeattack.neoprotect.core.model.Stats; import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse; import java.io.File; import java.nio.file.Files; import java.sql.Timestamp; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.atomic.AtomicReference; public class NeoProtectExecutor { private static Timer debugTimer = new Timer(); private NeoProtectPlugin instance; private Localization localization; private Object sender; private Locale locale; private String msg; private String[] args; private boolean isViaConsole; private void initials(ExecutorBuilder executeBuilder) { this.instance = executeBuilder.getInstance(); this.localization = instance.getCore().getLocalization(); this.sender = executeBuilder.getSender(); this.locale = executeBuilder.getLocal(); this.args = executeBuilder.getArgs(); this.msg = executeBuilder.getMsg(); this.isViaConsole = executeBuilder.isViaConsole(); } private void chatEvent(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (instance.getCore().getRestAPI().isAPIInvalid(msg)) { instance.sendMessage(sender, localization.get(locale, "apikey.invalid")); return; } Config.setAPIKey(msg); instance.sendMessage(sender, localization.get(locale, "apikey.valid")); gameshieldSelector(); } private void command(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (args.length == 0) { showHelp(); return; } if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) { instance.sendMessage(sender, localization.get(locale, "setup.command.required")); return; } switch (args[0].toLowerCase()) { case "setup": { if (isViaConsole) { instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command")); } else { setup(); } break; } case "ipanic": { iPanic(args); break; } case "directconnectwhitelist": { directConnectWhitelist(args); break; } case "toggle": { toggle(args); break; } case "analytics": { analytics(); break; } case "whitelist": case "blacklist": { firewall(args); break; } case "debugtool": { debugTool(args); break; } case "setgameshield": { if (args.length == 1 && !isViaConsole) { gameshieldSelector(); } else if (args.length == 2) { setGameshield(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgameshield")); } break; } case "setbackend": { if (args.length == 1 && !isViaConsole) { javaBackendSelector(); } else if (args.length == 2) { setJavaBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setbackend")); } break; } case "setgeyserbackend": { if (args.length == 1 && !isViaConsole) { bedrockBackendSelector(); } else if (args.length == 2) { setBedrockBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend")); } break; } default: { showHelp(); } } } private void setup() { instance.getCore().getPlayerInSetup().add(sender); instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"), "OPEN_URL", "https://panel.neoprotect.net/profile", "SHOW_TEXT", localization.get(locale, "apikey.find")); } private void iPanic(String[] args) { if (args.length != 1) { instance.sendMessage(sender, localization.get(locale, "usage.ipanic")); } else { instance.sendMessage(sender, localization.get(locale, "command.ipanic", localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated"))); } } private void directConnectWhitelist(String[] args) { if (args.length == 2) { instance.getCore().getDirectConnectWhitelist().add(args[1]); instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1])); } else { instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist")); } } private void toggle(String[] args) { if (args.length != 2) { instance.sendMessage(sender, localization.get(locale, "usage.toggle")); } else { int response = instance.getCore().getRestAPI().toggle(args[1]); if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } if (response == -1) { instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'"); return; } instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1], localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated"))); } } private void analytics() { instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------"); JSONObject analytics = instance.getCore().getRestAPI().getAnalytics(); instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> { if (ak.equals("bandwidth")) { return; } if (ak.equals("traffic")) { instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " + new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s"); JSONObject traffic = instance.getCore().getRestAPI().getTraffic(); AtomicReference<String> trafficUsed = new AtomicReference<>(); AtomicReference<String> trafficAvailable = new AtomicReference<>(); traffic.keySet().forEach(bk -> { if (bk.equals("used")) { trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb"); } if (bk.equals("available")) { trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb"); } }); instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get()); return; } instance.sendMessage(sender, ak .replace("onlinePlayers", "online players") .replace("cps", "connections/s") + ": " + analytics.get(ak)); }); } private void firewall(String[] args) { if (args.length == 1) { instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----"); instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall -> instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")"))); } else if (args.length == 3) { String ip = args[2]; String action = args[1]; String mode = args[0].toUpperCase(); int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode); if (response == -1) { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); return; } if (response == 0) { instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode)); return; } if (response == 400) { instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip)); return; } if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")"); } else { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); } } @SuppressWarnings("ResultOfMethodCallIgnored") private void debugTool(String[] args) { if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) { instance.sendMessage(sender, localization.get(locale, "debug.spigot")); return; } if (args.length == 2) { if (args[1].equals("cancel")) { debugTimer.cancel(); instance.getCore().setDebugRunning(false); instance.sendMessage(sender, localization.get(locale, "debug.cancelled")); return; } if (!isInteger(args[1])) { instance.sendMessage(sender, localization.get(locale, "usage.debug")); return; } } if (instance.getCore().isDebugRunning()) { instance.sendMessage(sender, localization.get(locale, "debug.running")); return; } instance.getCore().setDebugRunning(true); instance.sendMessage(sender, localization.get(locale, "debug.starting")); int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5; debugTimer = new Timer(); debugTimer.schedule(new TimerTask() { int counter = 0; @Override public void run() { counter++; instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis())); instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")"); if (counter >= amount) this.cancel(); } }, 500, 2000); debugTimer.schedule(new TimerTask() { @Override public void run() { API.getExecutorService().submit(() -> { try { long startTime = System.currentTimeMillis(); Stats stats = instance.getStats(); File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml"); YamlConfiguration configuration = new YamlConfiguration(); if (!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } configuration.load(file); configuration.set("general.osName", System.getProperty("os.name")); configuration.set("general.javaVersion", System.getProperty("java.version")); configuration.set("general.pluginVersion", stats.getPluginVersion()); configuration.set("general.ProxyName", stats.getServerName()); configuration.set("general.ProxyVersion", stats.getServerVersion()); configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName); long maxPlayerToProxyLatenz = 0; long maxNeoToProxyLatenz = 0; long maxProxyToBackendLatenz = 0; long maxPlayerToNeoLatenz = 0; long avgPlayerToProxyLatenz = 0; long avgNeoToProxyLatenz = 0; long avgProxyToBackendLatenz = 0; long avgPlayerToNeoLatenz = 0; long minPlayerToProxyLatenz = Long.MAX_VALUE; long minNeoToProxyLatenz = Long.MAX_VALUE; long minProxyToBackendLatenz = Long.MAX_VALUE; long minPlayerToNeoLatenz = Long.MAX_VALUE; configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress()); configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress()); for (DebugPingResponse response : list) { if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz()) maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz()) maxNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz()) maxProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz()) maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz(); avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz(); avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz(); avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz(); if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz()) minPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (minNeoToProxyLatenz > response.getNeoToProxyLatenz()) minNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (minProxyToBackendLatenz > response.getProxyToBackendLatenz()) minProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz()) minPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); } configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz); configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size()); configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz); })); configuration.save(file); final String content = new String(Files.readAllBytes(file.toPath())); final String pasteKey = instance.getCore().getRestAPI().paste(content); instance.getCore().getDebugPingResponses().clear(); instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)"); if(pasteKey != null) { final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml"; instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null); } else { instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null); } instance.getCore().setDebugRunning(false); } catch (Exception ex) { instance.getCore().severe(ex.getMessage(), ex); } }); } }, 2000L * amount + 500); } private void gameshieldSelector() { instance.sendMessage(sender, localization.get(locale, "select.gameshield")); List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields(); for (Gameshield gameshield : gameshieldList) { instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgameshield " + gameshield.getId(), "SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId())); } } private void setGameshield(String[] args) { if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1])); return; } Config.setGameShieldID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1])); javaBackendSelector(); } private void javaBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); instance.sendMessage(sender, localization.get(locale, "select.backend", "java")); for (Backend backend : backendList) { if(backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setJavaBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1])); return; } Config.setBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1])); instance.getCore().getRestAPI().testCredentials(); bedrockBackendSelector(); } private void bedrockBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); if(backendList.stream().noneMatch(Backend::isGeyser))return; instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser")); for (Backend backend : backendList) { if(!backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgeyserbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setBedrockBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1])); return; } Config.setGeyserBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1])); if (instance.getCore().getPlayerInSetup().remove(sender)) { instance.sendMessage(sender, localization.get(locale, "setup.finished")); } } private void showHelp() { instance.sendMessage(sender, localization.get(locale, "available.commands")); instance.sendMessage(sender, " - /np setup"); instance.sendMessage(sender, " - /np ipanic"); instance.sendMessage(sender, " - /np analytics"); instance.sendMessage(sender, " - /np toggle (option)"); instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)"); instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)"); instance.sendMessage(sender, " - /np debugTool (cancel / amount)"); instance.sendMessage(sender, " - /np directConnectWhitelist (ip)"); instance.sendMessage(sender, " - /np setgameshield [id]"); instance.sendMessage(sender, " - /np setbackend [id]"); instance.sendMessage(sender, " - /np setgeyserbackend [id]"); } public static class ExecutorBuilder { private NeoProtectPlugin instance; private Object sender; private String[] args; private Locale local; private String msg; private boolean viaConsole; public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) { this.instance = instance; return this; } public ExecutorBuilder sender(Object sender) { this.sender = sender; return this; } public ExecutorBuilder args(String[] args) { this.args = args; return this; } public ExecutorBuilder local(Locale local) { this.local = local; return this; } public ExecutorBuilder msg(String msg) { this.msg = msg; return this; } public ExecutorBuilder viaConsole(boolean viaConsole) { this.viaConsole = viaConsole; return this; } public void executeChatEvent() { API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this)); } public void executeCommand() { API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this)); } public NeoProtectPlugin getInstance() { return instance; } public Object getSender() { return sender; } public String[] getArgs() { return args; } public Locale getLocal() { return local; } public String getMsg() { return msg; } public boolean isViaConsole() { return viaConsole; } } public static boolean isInteger(String input) { try { Integer.parseInt(input); return true; } catch (NumberFormatException e) { return false; } } }
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
NeoProtect-NeoPlugin-a71f673
[ { "filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java", "retrieved_chunk": " \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +\n \"§bProxyProtocol§7: \" + Config.isProxyProtocol() + \" \\n\" +\n \"§bNeoProtectPlan§7: \" + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\") + \" \\n\" +\n \"§bVelocityName§7: \" + stats.getServerName() + \" \\n\" +\n \"§bVelocityVersion§7: \" + stats.getServerVersion() + \" \\n\" +\n \"§bVelocityPlugins§7: \" + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray());\n instance.sendMessage(player, \"§bHello \" + player.getUsername() + \" ;)\", null, null, \"SHOW_TEXT\", infos);\n instance.sendMessage(player, \"§bThis server uses your NeoPlugin\", null, null, \"SHOW_TEXT\", infos);", "score": 0.8426227569580078 }, { "filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java", "retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +", "score": 0.8422815799713135 }, { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java", "retrieved_chunk": " \"§bProxyProtocol§7: \" + Config.isProxyProtocol() + \" \\n\" +\n \"§bNeoProtectPlan§7: \" + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\") + \" \\n\" +\n \"§bSpigotName§7: \" + stats.getServerName() + \" \\n\" +\n \"§bSpigotVersion§7: \" + stats.getServerVersion() + \" \\n\" +\n \"§bSpigotPlugins§7: \" + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray());\n instance.sendMessage(player, \"§bHello \" + player.getName() + \" ;)\", null, null, \"SHOW_TEXT\", infos);\n instance.sendMessage(player, \"§bThis server uses your NeoPlugin\", null, null, \"SHOW_TEXT\", infos);\n }\n }\n}", "score": 0.8409779071807861 }, { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java", "retrieved_chunk": " \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +\n \"§bProxyProtocol§7: \" + Config.isProxyProtocol() + \" \\n\" +\n \"§bNeoProtectPlan§7: \" + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\") + \" \\n\" +\n \"§bBungeecordName§7: \" + stats.getServerName() + \" \\n\" +\n \"§bBungeecordVersion§7: \" + stats.getServerVersion()+ \" \\n\" +\n \"§bBungeecordPlugins§7: \" + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray());\n instance.sendMessage(player, \"§bHello \" + player.getName() + \" ;)\", null, null, \"SHOW_TEXT\", infos);\n instance.sendMessage(player, \"§bThis server uses your NeoPlugin\", null, null, \"SHOW_TEXT\", infos);", "score": 0.8395262956619263 }, { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java", "retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfig().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +", "score": 0.8392347097396851 } ]
java
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
package de.cubeattack.neoprotect.core.executor; import de.cubeattack.api.API; import de.cubeattack.api.language.Localization; import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration; import de.cubeattack.api.libraries.org.json.JSONObject; import de.cubeattack.neoprotect.core.Config; import de.cubeattack.neoprotect.core.NeoProtectPlugin; import de.cubeattack.neoprotect.core.model.Backend; import de.cubeattack.neoprotect.core.model.Gameshield; import de.cubeattack.neoprotect.core.model.Stats; import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse; import java.io.File; import java.nio.file.Files; import java.sql.Timestamp; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.atomic.AtomicReference; public class NeoProtectExecutor { private static Timer debugTimer = new Timer(); private NeoProtectPlugin instance; private Localization localization; private Object sender; private Locale locale; private String msg; private String[] args; private boolean isViaConsole; private void initials(ExecutorBuilder executeBuilder) { this.instance = executeBuilder.getInstance(); this.localization = instance.getCore().getLocalization(); this.sender = executeBuilder.getSender(); this.locale = executeBuilder.getLocal(); this.args = executeBuilder.getArgs(); this.msg = executeBuilder.getMsg(); this.isViaConsole = executeBuilder.isViaConsole(); } private void chatEvent(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (instance.getCore().getRestAPI().isAPIInvalid(msg)) { instance.sendMessage(sender, localization.get(locale, "apikey.invalid")); return; } Config.setAPIKey(msg); instance.sendMessage(sender, localization.get(locale, "apikey.valid")); gameshieldSelector(); } private void command(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (args.length == 0) { showHelp(); return; } if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) { instance.sendMessage(sender, localization.get(locale, "setup.command.required")); return; } switch (args[0].toLowerCase()) { case "setup": { if (isViaConsole) { instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command")); } else { setup(); } break; } case "ipanic": { iPanic(args); break; } case "directconnectwhitelist": { directConnectWhitelist(args); break; } case "toggle": { toggle(args); break; } case "analytics": { analytics(); break; } case "whitelist": case "blacklist": { firewall(args); break; } case "debugtool": { debugTool(args); break; } case "setgameshield": { if (args.length == 1 && !isViaConsole) { gameshieldSelector(); } else if (args.length == 2) { setGameshield(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgameshield")); } break; } case "setbackend": { if (args.length == 1 && !isViaConsole) { javaBackendSelector(); } else if (args.length == 2) { setJavaBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setbackend")); } break; } case "setgeyserbackend": { if (args.length == 1 && !isViaConsole) { bedrockBackendSelector(); } else if (args.length == 2) { setBedrockBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend")); } break; } default: { showHelp(); } } } private void setup() { instance.getCore().getPlayerInSetup().add(sender); instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"), "OPEN_URL", "https://panel.neoprotect.net/profile", "SHOW_TEXT", localization.get(locale, "apikey.find")); } private void iPanic(String[] args) { if (args.length != 1) { instance.sendMessage(sender, localization.get(locale, "usage.ipanic")); } else { instance.sendMessage(sender, localization.get(locale, "command.ipanic", localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated"))); } } private void directConnectWhitelist(String[] args) { if (args.length == 2) { instance.getCore().getDirectConnectWhitelist().add(args[1]); instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1])); } else { instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist")); } } private void toggle(String[] args) { if (args.length != 2) { instance.sendMessage(sender, localization.get(locale, "usage.toggle")); } else { int response = instance.getCore().getRestAPI().toggle(args[1]); if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } if (response == -1) { instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'"); return; } instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1], localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated"))); } } private void analytics() { instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------"); JSONObject analytics = instance.getCore().getRestAPI().getAnalytics(); instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> { if (ak.equals("bandwidth")) { return; } if (ak.equals("traffic")) { instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " + new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s"); JSONObject traffic = instance.getCore().getRestAPI().getTraffic(); AtomicReference<String> trafficUsed = new AtomicReference<>(); AtomicReference<String> trafficAvailable = new AtomicReference<>(); traffic.keySet().forEach(bk -> { if (bk.equals("used")) { trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb"); } if (bk.equals("available")) { trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb"); } }); instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get()); return; } instance.sendMessage(sender, ak .replace("onlinePlayers", "online players") .replace("cps", "connections/s") + ": " + analytics.get(ak)); }); } private void firewall(String[] args) { if (args.length == 1) { instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----"); instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall -> instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")"))); } else if (args.length == 3) { String ip = args[2]; String action = args[1]; String mode = args[0].toUpperCase(); int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode); if (response == -1) { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); return; } if (response == 0) { instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode)); return; } if (response == 400) { instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip)); return; } if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")"); } else { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); } } @SuppressWarnings("ResultOfMethodCallIgnored") private void debugTool(String[] args) { if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) { instance.sendMessage(sender, localization.get(locale, "debug.spigot")); return; } if (args.length == 2) { if (args[1].equals("cancel")) { debugTimer.cancel(); instance.getCore().setDebugRunning(false); instance.sendMessage(sender, localization.get(locale, "debug.cancelled")); return; } if (!isInteger(args[1])) { instance.sendMessage(sender, localization.get(locale, "usage.debug")); return; } } if (instance.getCore().isDebugRunning()) { instance.sendMessage(sender, localization.get(locale, "debug.running")); return; } instance.getCore().setDebugRunning(true); instance.sendMessage(sender, localization.get(locale, "debug.starting")); int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5; debugTimer = new Timer(); debugTimer.schedule(new TimerTask() { int counter = 0; @Override public void run() { counter++; instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis())); instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")"); if (counter >= amount) this.cancel(); } }, 500, 2000); debugTimer.schedule(new TimerTask() { @Override public void run() { API.getExecutorService().submit(() -> { try { long startTime = System.currentTimeMillis(); Stats stats = instance.getStats(); File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml"); YamlConfiguration configuration = new YamlConfiguration(); if (!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } configuration.load(file); configuration.set("general.osName", System.getProperty("os.name")); configuration.set("general.javaVersion", System.getProperty("java.version")); configuration.set("general.pluginVersion", stats.getPluginVersion()); configuration.set("general.ProxyName", stats.getServerName()); configuration.set("general.ProxyVersion", stats.getServerVersion()); configuration.set("general.ProxyPlugins", instance.getPlugins()); instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> { List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName); long maxPlayerToProxyLatenz = 0; long maxNeoToProxyLatenz = 0; long maxProxyToBackendLatenz = 0; long maxPlayerToNeoLatenz = 0; long avgPlayerToProxyLatenz = 0; long avgNeoToProxyLatenz = 0; long avgProxyToBackendLatenz = 0; long avgPlayerToNeoLatenz = 0; long minPlayerToProxyLatenz = Long.MAX_VALUE; long minNeoToProxyLatenz = Long.MAX_VALUE; long minProxyToBackendLatenz = Long.MAX_VALUE; long minPlayerToNeoLatenz = Long.MAX_VALUE; configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress()); configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress()); for (DebugPingResponse response : list) { if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz()) maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz()) maxNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz()) maxProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz()) maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz(); avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz(); avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz(); avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz(); if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz()) minPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (minNeoToProxyLatenz > response.getNeoToProxyLatenz()) minNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (minProxyToBackendLatenz > response.getProxyToBackendLatenz()) minProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz()) minPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); } configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz); configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size()); configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz); })); configuration.save(file); final String content = new String(Files.readAllBytes(file.toPath())); final String pasteKey = instance.getCore().getRestAPI().paste(content); instance.getCore().getDebugPingResponses().clear(); instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)"); if(pasteKey != null) { final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml"; instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null); } else { instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null); } instance.getCore().setDebugRunning(false); } catch (Exception ex) { instance.getCore().severe(ex.getMessage(), ex); } }); } }, 2000L * amount + 500); } private void gameshieldSelector() { instance.sendMessage(sender, localization.get(locale, "select.gameshield")); List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields(); for (Gameshield gameshield : gameshieldList) { instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgameshield " + gameshield.getId(), "SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId())); } } private void setGameshield(String[] args) { if (
instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1])); return; } Config.setGameShieldID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1])); javaBackendSelector(); } private void javaBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); instance.sendMessage(sender, localization.get(locale, "select.backend", "java")); for (Backend backend : backendList) { if(backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setJavaBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1])); return; } Config.setBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1])); instance.getCore().getRestAPI().testCredentials(); bedrockBackendSelector(); } private void bedrockBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); if(backendList.stream().noneMatch(Backend::isGeyser))return; instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser")); for (Backend backend : backendList) { if(!backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgeyserbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setBedrockBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1])); return; } Config.setGeyserBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1])); if (instance.getCore().getPlayerInSetup().remove(sender)) { instance.sendMessage(sender, localization.get(locale, "setup.finished")); } } private void showHelp() { instance.sendMessage(sender, localization.get(locale, "available.commands")); instance.sendMessage(sender, " - /np setup"); instance.sendMessage(sender, " - /np ipanic"); instance.sendMessage(sender, " - /np analytics"); instance.sendMessage(sender, " - /np toggle (option)"); instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)"); instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)"); instance.sendMessage(sender, " - /np debugTool (cancel / amount)"); instance.sendMessage(sender, " - /np directConnectWhitelist (ip)"); instance.sendMessage(sender, " - /np setgameshield [id]"); instance.sendMessage(sender, " - /np setbackend [id]"); instance.sendMessage(sender, " - /np setgeyserbackend [id]"); } public static class ExecutorBuilder { private NeoProtectPlugin instance; private Object sender; private String[] args; private Locale local; private String msg; private boolean viaConsole; public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) { this.instance = instance; return this; } public ExecutorBuilder sender(Object sender) { this.sender = sender; return this; } public ExecutorBuilder args(String[] args) { this.args = args; return this; } public ExecutorBuilder local(Locale local) { this.local = local; return this; } public ExecutorBuilder msg(String msg) { this.msg = msg; return this; } public ExecutorBuilder viaConsole(boolean viaConsole) { this.viaConsole = viaConsole; return this; } public void executeChatEvent() { API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this)); } public void executeCommand() { API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this)); } public NeoProtectPlugin getInstance() { return instance; } public Object getSender() { return sender; } public String[] getArgs() { return args; } public Locale getLocal() { return local; } public String getMsg() { return msg; } public boolean isViaConsole() { return viaConsole; } } public static boolean isInteger(String input) { try { Integer.parseInt(input); return true; } catch (NumberFormatException e) { return false; } } }
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
NeoProtect-NeoPlugin-a71f673
[ { "filename": "src/main/java/de/cubeattack/neoprotect/core/model/Gameshield.java", "retrieved_chunk": "package de.cubeattack.neoprotect.core.model;\npublic class Gameshield {\n private final String id;\n private final String name;\n public Gameshield(String id, String name) {\n this.id = id;\n this.name = name;\n }\n public String getId() {\n return id;", "score": 0.8296698927879333 }, { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java", "retrieved_chunk": " }\n }\n if (args.length <= 1) {\n list.add(\"setup\");\n if (instance.getCore().isSetup()) {\n list.add(\"directConnectWhitelist\");\n list.add(\"setgameshield\");\n list.add(\"setbackend\");\n list.add(\"analytics\");\n list.add(\"debugTool\");", "score": 0.8270751237869263 }, { "filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java", "retrieved_chunk": " return;\n }\n if (!attackRunning[0]) {\n core.warn(\"Gameshield ID '\" + Config.getGameShieldID() + \"' is under attack\");\n core.getPlugin().sendAdminMessage(Permission.NOTIFY, \"Gameshield ID '\" + Config.getGameShieldID() + \"' is under attack\", null, null, null, null);\n attackRunning[0] = true;\n }\n }\n }, 1000 * 5, 1000 * 10);\n }", "score": 0.8249300122261047 }, { "filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java", "retrieved_chunk": " core.severe(\"Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield\");\n setup = false;\n return;\n } else if (isBackendInvalid(Config.getBackendID())) {\n core.severe(\"Backend is not valid! Please run /neoprotect setbackend to set the backend\");\n setup = false;\n return;\n }\n this.setup = true;\n setProxyProtocol(Config.isProxyProtocol());", "score": 0.8169558048248291 }, { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/command/NeoProtectTabCompleter.java", "retrieved_chunk": " completorList.add(\"remove\");\n }\n if (args.length != 1) {\n return completorList;\n }\n list.add(\"setup\");\n if (instance.getCore().isSetup()) {\n list.add(\"directConnectWhitelist\");\n list.add(\"setgameshield\");\n list.add(\"setbackend\");", "score": 0.8102748394012451 } ]
java
instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
package de.cubeattack.neoprotect.core.executor; import de.cubeattack.api.API; import de.cubeattack.api.language.Localization; import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration; import de.cubeattack.api.libraries.org.json.JSONObject; import de.cubeattack.neoprotect.core.Config; import de.cubeattack.neoprotect.core.NeoProtectPlugin; import de.cubeattack.neoprotect.core.model.Backend; import de.cubeattack.neoprotect.core.model.Gameshield; import de.cubeattack.neoprotect.core.model.Stats; import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse; import java.io.File; import java.nio.file.Files; import java.sql.Timestamp; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.atomic.AtomicReference; public class NeoProtectExecutor { private static Timer debugTimer = new Timer(); private NeoProtectPlugin instance; private Localization localization; private Object sender; private Locale locale; private String msg; private String[] args; private boolean isViaConsole; private void initials(ExecutorBuilder executeBuilder) { this.instance = executeBuilder.getInstance(); this.localization = instance.getCore().getLocalization(); this.sender = executeBuilder.getSender(); this.locale = executeBuilder.getLocal(); this.args = executeBuilder.getArgs(); this.msg = executeBuilder.getMsg(); this.isViaConsole = executeBuilder.isViaConsole(); } private void chatEvent(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (instance.getCore().getRestAPI().isAPIInvalid(msg)) { instance.sendMessage(sender, localization.get(locale, "apikey.invalid")); return; } Config.setAPIKey(msg); instance.sendMessage(sender, localization.get(locale, "apikey.valid")); gameshieldSelector(); } private void command(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (args.length == 0) { showHelp(); return; } if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) { instance.sendMessage(sender, localization.get(locale, "setup.command.required")); return; } switch (args[0].toLowerCase()) { case "setup": { if (isViaConsole) { instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command")); } else { setup(); } break; } case "ipanic": { iPanic(args); break; } case "directconnectwhitelist": { directConnectWhitelist(args); break; } case "toggle": { toggle(args); break; } case "analytics": { analytics(); break; } case "whitelist": case "blacklist": { firewall(args); break; } case "debugtool": { debugTool(args); break; } case "setgameshield": { if (args.length == 1 && !isViaConsole) { gameshieldSelector(); } else if (args.length == 2) { setGameshield(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgameshield")); } break; } case "setbackend": { if (args.length == 1 && !isViaConsole) { javaBackendSelector(); } else if (args.length == 2) { setJavaBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setbackend")); } break; } case "setgeyserbackend": { if (args.length == 1 && !isViaConsole) { bedrockBackendSelector(); } else if (args.length == 2) { setBedrockBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend")); } break; } default: { showHelp(); } } } private void setup() { instance.getCore().getPlayerInSetup().add(sender); instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"), "OPEN_URL", "https://panel.neoprotect.net/profile", "SHOW_TEXT", localization.get(locale, "apikey.find")); } private void iPanic(String[] args) { if (args.length != 1) { instance.sendMessage(sender, localization.get(locale, "usage.ipanic")); } else { instance.sendMessage(sender, localization.get(locale, "command.ipanic", localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated"))); } } private void directConnectWhitelist(String[] args) { if (args.length == 2) { instance.getCore().getDirectConnectWhitelist().add(args[1]); instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1])); } else { instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist")); } } private void toggle(String[] args) { if (args.length != 2) { instance.sendMessage(sender, localization.get(locale, "usage.toggle")); } else { int response = instance.getCore().getRestAPI().toggle(args[1]); if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } if (response == -1) { instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'"); return; } instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1], localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated"))); } } private void analytics() { instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------"); JSONObject analytics = instance.getCore().getRestAPI().getAnalytics(); instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> { if (ak.equals("bandwidth")) { return; } if (ak.equals("traffic")) { instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " + new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s"); JSONObject traffic = instance.getCore().getRestAPI().getTraffic(); AtomicReference<String> trafficUsed = new AtomicReference<>(); AtomicReference<String> trafficAvailable = new AtomicReference<>(); traffic.keySet().forEach(bk -> { if (bk.equals("used")) { trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb"); } if (bk.equals("available")) { trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb"); } }); instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get()); return; } instance.sendMessage(sender, ak .replace("onlinePlayers", "online players") .replace("cps", "connections/s") + ": " + analytics.get(ak)); }); } private void firewall(String[] args) { if (args.length == 1) { instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----"); instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall -> instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")"))); } else if (args.length == 3) { String ip = args[2]; String action = args[1]; String mode = args[0].toUpperCase(); int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode); if (response == -1) { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); return; } if (response == 0) { instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode)); return; } if (response == 400) { instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip)); return; } if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")"); } else { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); } } @SuppressWarnings("ResultOfMethodCallIgnored") private void debugTool(String[] args) { if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) { instance.sendMessage(sender, localization.get(locale, "debug.spigot")); return; } if (args.length == 2) { if (args[1].equals("cancel")) { debugTimer.cancel(); instance.getCore().setDebugRunning(false); instance.sendMessage(sender, localization.get(locale, "debug.cancelled")); return; } if (!isInteger(args[1])) { instance.sendMessage(sender, localization.get(locale, "usage.debug")); return; } } if (instance.getCore().isDebugRunning()) { instance.sendMessage(sender, localization.get(locale, "debug.running")); return; } instance.getCore().setDebugRunning(true); instance.sendMessage(sender, localization.get(locale, "debug.starting")); int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5; debugTimer = new Timer(); debugTimer.schedule(new TimerTask() { int counter = 0; @Override public void run() { counter++; instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis())); instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")"); if (counter >= amount) this.cancel(); } }, 500, 2000); debugTimer.schedule(new TimerTask() { @Override public void run() { API.getExecutorService().submit(() -> { try { long startTime = System.currentTimeMillis(); Stats stats = instance.getStats(); File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml"); YamlConfiguration configuration = new YamlConfiguration(); if (!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } configuration.load(file); configuration.set("general.osName", System.getProperty("os.name")); configuration.set("general.javaVersion", System.getProperty("java.version")); configuration.set("general.pluginVersion", stats.getPluginVersion()); configuration.set("general.ProxyName", stats.getServerName()); configuration.set("general.ProxyVersion", stats.getServerVersion()); configuration.set("general.ProxyPlugins", instance.getPlugins()); instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0; long maxNeoToProxyLatenz = 0; long maxProxyToBackendLatenz = 0; long maxPlayerToNeoLatenz = 0; long avgPlayerToProxyLatenz = 0; long avgNeoToProxyLatenz = 0; long avgProxyToBackendLatenz = 0; long avgPlayerToNeoLatenz = 0; long minPlayerToProxyLatenz = Long.MAX_VALUE; long minNeoToProxyLatenz = Long.MAX_VALUE; long minProxyToBackendLatenz = Long.MAX_VALUE; long minPlayerToNeoLatenz = Long.MAX_VALUE; configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress()); configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress()); for (DebugPingResponse response : list) { if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz()) maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz()) maxNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz()) maxProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz()) maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz(); avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz(); avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz(); avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz(); if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz()) minPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (minNeoToProxyLatenz > response.getNeoToProxyLatenz()) minNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (minProxyToBackendLatenz > response.getProxyToBackendLatenz()) minProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz()) minPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); } configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz); configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size()); configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz); })); configuration.save(file); final String content = new String(Files.readAllBytes(file.toPath())); final String pasteKey = instance.getCore().getRestAPI().paste(content); instance.getCore().getDebugPingResponses().clear(); instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)"); if(pasteKey != null) { final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml"; instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null); } else { instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null); } instance.getCore().setDebugRunning(false); } catch (Exception ex) { instance.getCore().severe(ex.getMessage(), ex); } }); } }, 2000L * amount + 500); } private void gameshieldSelector() { instance.sendMessage(sender, localization.get(locale, "select.gameshield")); List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields(); for (Gameshield gameshield : gameshieldList) { instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgameshield " + gameshield.getId(), "SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId())); } } private void setGameshield(String[] args) { if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1])); return; } Config.setGameShieldID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1])); javaBackendSelector(); } private void javaBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); instance.sendMessage(sender, localization.get(locale, "select.backend", "java")); for (Backend backend : backendList) { if(backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setJavaBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1])); return; } Config.setBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1])); instance.getCore().getRestAPI().testCredentials(); bedrockBackendSelector(); } private void bedrockBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); if(backendList.stream().noneMatch(Backend::isGeyser))return; instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser")); for (Backend backend : backendList) { if(!backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgeyserbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setBedrockBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1])); return; } Config.setGeyserBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1])); if (instance.getCore().getPlayerInSetup().remove(sender)) { instance.sendMessage(sender, localization.get(locale, "setup.finished")); } } private void showHelp() { instance.sendMessage(sender, localization.get(locale, "available.commands")); instance.sendMessage(sender, " - /np setup"); instance.sendMessage(sender, " - /np ipanic"); instance.sendMessage(sender, " - /np analytics"); instance.sendMessage(sender, " - /np toggle (option)"); instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)"); instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)"); instance.sendMessage(sender, " - /np debugTool (cancel / amount)"); instance.sendMessage(sender, " - /np directConnectWhitelist (ip)"); instance.sendMessage(sender, " - /np setgameshield [id]"); instance.sendMessage(sender, " - /np setbackend [id]"); instance.sendMessage(sender, " - /np setgeyserbackend [id]"); } public static class ExecutorBuilder { private NeoProtectPlugin instance; private Object sender; private String[] args; private Locale local; private String msg; private boolean viaConsole; public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) { this.instance = instance; return this; } public ExecutorBuilder sender(Object sender) { this.sender = sender; return this; } public ExecutorBuilder args(String[] args) { this.args = args; return this; } public ExecutorBuilder local(Locale local) { this.local = local; return this; } public ExecutorBuilder msg(String msg) { this.msg = msg; return this; } public ExecutorBuilder viaConsole(boolean viaConsole) { this.viaConsole = viaConsole; return this; } public void executeChatEvent() { API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this)); } public void executeCommand() { API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this)); } public NeoProtectPlugin getInstance() { return instance; } public Object getSender() { return sender; } public String[] getArgs() { return args; } public Locale getLocal() { return local; } public String getMsg() { return msg; } public boolean isViaConsole() { return viaConsole; } } public static boolean isInteger(String input) { try { Integer.parseInt(input); return true; } catch (NumberFormatException e) { return false; } } }
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
NeoProtect-NeoPlugin-a71f673
[ { "filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java", "retrieved_chunk": " \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +\n \"§bProxyProtocol§7: \" + Config.isProxyProtocol() + \" \\n\" +\n \"§bNeoProtectPlan§7: \" + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\") + \" \\n\" +\n \"§bVelocityName§7: \" + stats.getServerName() + \" \\n\" +\n \"§bVelocityVersion§7: \" + stats.getServerVersion() + \" \\n\" +\n \"§bVelocityPlugins§7: \" + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray());\n instance.sendMessage(player, \"§bHello \" + player.getUsername() + \" ;)\", null, null, \"SHOW_TEXT\", infos);\n instance.sendMessage(player, \"§bThis server uses your NeoPlugin\", null, null, \"SHOW_TEXT\", infos);", "score": 0.8564117550849915 }, { "filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java", "retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +", "score": 0.8527237176895142 }, { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java", "retrieved_chunk": " \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +\n \"§bProxyProtocol§7: \" + Config.isProxyProtocol() + \" \\n\" +\n \"§bNeoProtectPlan§7: \" + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\") + \" \\n\" +\n \"§bBungeecordName§7: \" + stats.getServerName() + \" \\n\" +\n \"§bBungeecordVersion§7: \" + stats.getServerVersion()+ \" \\n\" +\n \"§bBungeecordPlugins§7: \" + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray());\n instance.sendMessage(player, \"§bHello \" + player.getName() + \" ;)\", null, null, \"SHOW_TEXT\", infos);\n instance.sendMessage(player, \"§bThis server uses your NeoPlugin\", null, null, \"SHOW_TEXT\", infos);", "score": 0.8526047468185425 }, { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java", "retrieved_chunk": " \"§bProxyProtocol§7: \" + Config.isProxyProtocol() + \" \\n\" +\n \"§bNeoProtectPlan§7: \" + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\") + \" \\n\" +\n \"§bSpigotName§7: \" + stats.getServerName() + \" \\n\" +\n \"§bSpigotVersion§7: \" + stats.getServerVersion() + \" \\n\" +\n \"§bSpigotPlugins§7: \" + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray());\n instance.sendMessage(player, \"§bHello \" + player.getName() + \" ;)\", null, null, \"SHOW_TEXT\", infos);\n instance.sendMessage(player, \"§bThis server uses your NeoPlugin\", null, null, \"SHOW_TEXT\", infos);\n }\n }\n}", "score": 0.8524527549743652 }, { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java", "retrieved_chunk": " if (tcpInfoBackend != null) {\n backendRTT = tcpInfoBackend.rtt() / 1000;\n }\n ConcurrentHashMap<String, ArrayList<DebugPingResponse>> map = instance.getCore().getDebugPingResponses();\n if (!map.containsKey(player.getName())) {\n instance.getCore().getDebugPingResponses().put(player.getName(), new ArrayList<>());\n }\n map.get(player.getName()).add(new DebugPingResponse(ping, neoRTT, backendRTT, inetAddress.get(), channel.remoteAddress()));\n instance.getCore().debug(\"Loading completed\");\n instance.getCore().debug(\" \");", "score": 0.8498135209083557 } ]
java
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
package de.cubeattack.neoprotect.core.executor; import de.cubeattack.api.API; import de.cubeattack.api.language.Localization; import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration; import de.cubeattack.api.libraries.org.json.JSONObject; import de.cubeattack.neoprotect.core.Config; import de.cubeattack.neoprotect.core.NeoProtectPlugin; import de.cubeattack.neoprotect.core.model.Backend; import de.cubeattack.neoprotect.core.model.Gameshield; import de.cubeattack.neoprotect.core.model.Stats; import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse; import java.io.File; import java.nio.file.Files; import java.sql.Timestamp; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.atomic.AtomicReference; public class NeoProtectExecutor { private static Timer debugTimer = new Timer(); private NeoProtectPlugin instance; private Localization localization; private Object sender; private Locale locale; private String msg; private String[] args; private boolean isViaConsole; private void initials(ExecutorBuilder executeBuilder) { this.instance = executeBuilder.getInstance(); this.localization = instance.getCore().getLocalization(); this.sender = executeBuilder.getSender(); this.locale = executeBuilder.getLocal(); this.args = executeBuilder.getArgs(); this.msg = executeBuilder.getMsg(); this.isViaConsole = executeBuilder.isViaConsole(); } private void chatEvent(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (instance.getCore().getRestAPI().isAPIInvalid(msg)) { instance.sendMessage(sender, localization.get(locale, "apikey.invalid")); return; } Config.setAPIKey(msg); instance.sendMessage(sender, localization.get(locale, "apikey.valid")); gameshieldSelector(); } private void command(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (args.length == 0) { showHelp(); return; } if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) { instance.sendMessage(sender, localization.get(locale, "setup.command.required")); return; } switch (args[0].toLowerCase()) { case "setup": { if (isViaConsole) { instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command")); } else { setup(); } break; } case "ipanic": { iPanic(args); break; } case "directconnectwhitelist": { directConnectWhitelist(args); break; } case "toggle": { toggle(args); break; } case "analytics": { analytics(); break; } case "whitelist": case "blacklist": { firewall(args); break; } case "debugtool": { debugTool(args); break; } case "setgameshield": { if (args.length == 1 && !isViaConsole) { gameshieldSelector(); } else if (args.length == 2) { setGameshield(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgameshield")); } break; } case "setbackend": { if (args.length == 1 && !isViaConsole) { javaBackendSelector(); } else if (args.length == 2) { setJavaBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setbackend")); } break; } case "setgeyserbackend": { if (args.length == 1 && !isViaConsole) { bedrockBackendSelector(); } else if (args.length == 2) { setBedrockBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend")); } break; } default: { showHelp(); } } } private void setup() { instance.getCore().getPlayerInSetup().add(sender); instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"), "OPEN_URL", "https://panel.neoprotect.net/profile", "SHOW_TEXT", localization.get(locale, "apikey.find")); } private void iPanic(String[] args) { if (args.length != 1) { instance.sendMessage(sender, localization.get(locale, "usage.ipanic")); } else { instance.sendMessage(sender, localization.get(locale, "command.ipanic", localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated"))); } } private void directConnectWhitelist(String[] args) { if (args.length == 2) { instance.getCore().getDirectConnectWhitelist().add(args[1]); instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1])); } else { instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist")); } } private void toggle(String[] args) { if (args.length != 2) { instance.sendMessage(sender, localization.get(locale, "usage.toggle")); } else { int response = instance.getCore().getRestAPI().toggle(args[1]); if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } if (response == -1) { instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'"); return; } instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1], localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated"))); } } private void analytics() { instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------"); JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) { return; } if (ak.equals("traffic")) { instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " + new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s"); JSONObject traffic = instance.getCore().getRestAPI().getTraffic(); AtomicReference<String> trafficUsed = new AtomicReference<>(); AtomicReference<String> trafficAvailable = new AtomicReference<>(); traffic.keySet().forEach(bk -> { if (bk.equals("used")) { trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb"); } if (bk.equals("available")) { trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb"); } }); instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get()); return; } instance.sendMessage(sender, ak .replace("onlinePlayers", "online players") .replace("cps", "connections/s") + ": " + analytics.get(ak)); }); } private void firewall(String[] args) { if (args.length == 1) { instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----"); instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall -> instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")"))); } else if (args.length == 3) { String ip = args[2]; String action = args[1]; String mode = args[0].toUpperCase(); int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode); if (response == -1) { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); return; } if (response == 0) { instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode)); return; } if (response == 400) { instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip)); return; } if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")"); } else { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); } } @SuppressWarnings("ResultOfMethodCallIgnored") private void debugTool(String[] args) { if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) { instance.sendMessage(sender, localization.get(locale, "debug.spigot")); return; } if (args.length == 2) { if (args[1].equals("cancel")) { debugTimer.cancel(); instance.getCore().setDebugRunning(false); instance.sendMessage(sender, localization.get(locale, "debug.cancelled")); return; } if (!isInteger(args[1])) { instance.sendMessage(sender, localization.get(locale, "usage.debug")); return; } } if (instance.getCore().isDebugRunning()) { instance.sendMessage(sender, localization.get(locale, "debug.running")); return; } instance.getCore().setDebugRunning(true); instance.sendMessage(sender, localization.get(locale, "debug.starting")); int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5; debugTimer = new Timer(); debugTimer.schedule(new TimerTask() { int counter = 0; @Override public void run() { counter++; instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis())); instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")"); if (counter >= amount) this.cancel(); } }, 500, 2000); debugTimer.schedule(new TimerTask() { @Override public void run() { API.getExecutorService().submit(() -> { try { long startTime = System.currentTimeMillis(); Stats stats = instance.getStats(); File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml"); YamlConfiguration configuration = new YamlConfiguration(); if (!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } configuration.load(file); configuration.set("general.osName", System.getProperty("os.name")); configuration.set("general.javaVersion", System.getProperty("java.version")); configuration.set("general.pluginVersion", stats.getPluginVersion()); configuration.set("general.ProxyName", stats.getServerName()); configuration.set("general.ProxyVersion", stats.getServerVersion()); configuration.set("general.ProxyPlugins", instance.getPlugins()); instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> { List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName); long maxPlayerToProxyLatenz = 0; long maxNeoToProxyLatenz = 0; long maxProxyToBackendLatenz = 0; long maxPlayerToNeoLatenz = 0; long avgPlayerToProxyLatenz = 0; long avgNeoToProxyLatenz = 0; long avgProxyToBackendLatenz = 0; long avgPlayerToNeoLatenz = 0; long minPlayerToProxyLatenz = Long.MAX_VALUE; long minNeoToProxyLatenz = Long.MAX_VALUE; long minProxyToBackendLatenz = Long.MAX_VALUE; long minPlayerToNeoLatenz = Long.MAX_VALUE; configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress()); configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress()); for (DebugPingResponse response : list) { if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz()) maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz()) maxNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz()) maxProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz()) maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz(); avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz(); avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz(); avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz(); if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz()) minPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (minNeoToProxyLatenz > response.getNeoToProxyLatenz()) minNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (minProxyToBackendLatenz > response.getProxyToBackendLatenz()) minProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz()) minPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); } configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz); configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size()); configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz); })); configuration.save(file); final String content = new String(Files.readAllBytes(file.toPath())); final String pasteKey = instance.getCore().getRestAPI().paste(content); instance.getCore().getDebugPingResponses().clear(); instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)"); if(pasteKey != null) { final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml"; instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null); } else { instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null); } instance.getCore().setDebugRunning(false); } catch (Exception ex) { instance.getCore().severe(ex.getMessage(), ex); } }); } }, 2000L * amount + 500); } private void gameshieldSelector() { instance.sendMessage(sender, localization.get(locale, "select.gameshield")); List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields(); for (Gameshield gameshield : gameshieldList) { instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgameshield " + gameshield.getId(), "SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId())); } } private void setGameshield(String[] args) { if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1])); return; } Config.setGameShieldID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1])); javaBackendSelector(); } private void javaBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); instance.sendMessage(sender, localization.get(locale, "select.backend", "java")); for (Backend backend : backendList) { if(backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setJavaBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1])); return; } Config.setBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1])); instance.getCore().getRestAPI().testCredentials(); bedrockBackendSelector(); } private void bedrockBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); if(backendList.stream().noneMatch(Backend::isGeyser))return; instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser")); for (Backend backend : backendList) { if(!backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgeyserbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setBedrockBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1])); return; } Config.setGeyserBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1])); if (instance.getCore().getPlayerInSetup().remove(sender)) { instance.sendMessage(sender, localization.get(locale, "setup.finished")); } } private void showHelp() { instance.sendMessage(sender, localization.get(locale, "available.commands")); instance.sendMessage(sender, " - /np setup"); instance.sendMessage(sender, " - /np ipanic"); instance.sendMessage(sender, " - /np analytics"); instance.sendMessage(sender, " - /np toggle (option)"); instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)"); instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)"); instance.sendMessage(sender, " - /np debugTool (cancel / amount)"); instance.sendMessage(sender, " - /np directConnectWhitelist (ip)"); instance.sendMessage(sender, " - /np setgameshield [id]"); instance.sendMessage(sender, " - /np setbackend [id]"); instance.sendMessage(sender, " - /np setgeyserbackend [id]"); } public static class ExecutorBuilder { private NeoProtectPlugin instance; private Object sender; private String[] args; private Locale local; private String msg; private boolean viaConsole; public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) { this.instance = instance; return this; } public ExecutorBuilder sender(Object sender) { this.sender = sender; return this; } public ExecutorBuilder args(String[] args) { this.args = args; return this; } public ExecutorBuilder local(Locale local) { this.local = local; return this; } public ExecutorBuilder msg(String msg) { this.msg = msg; return this; } public ExecutorBuilder viaConsole(boolean viaConsole) { this.viaConsole = viaConsole; return this; } public void executeChatEvent() { API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this)); } public void executeCommand() { API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this)); } public NeoProtectPlugin getInstance() { return instance; } public Object getSender() { return sender; } public String[] getArgs() { return args; } public Locale getLocal() { return local; } public String getMsg() { return msg; } public boolean isViaConsole() { return viaConsole; } } public static boolean isInteger(String input) { try { Integer.parseInt(input); return true; } catch (NumberFormatException e) { return false; } } }
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
NeoProtect-NeoPlugin-a71f673
[ { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java", "retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +\n \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +", "score": 0.8491624593734741 }, { "filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java", "retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +", "score": 0.8434814214706421 }, { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java", "retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfig().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +", "score": 0.8431380987167358 }, { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java", "retrieved_chunk": " \"§bProxyProtocol§7: \" + Config.isProxyProtocol() + \" \\n\" +\n \"§bNeoProtectPlan§7: \" + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\") + \" \\n\" +\n \"§bSpigotName§7: \" + stats.getServerName() + \" \\n\" +\n \"§bSpigotVersion§7: \" + stats.getServerVersion() + \" \\n\" +\n \"§bSpigotPlugins§7: \" + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray());\n instance.sendMessage(player, \"§bHello \" + player.getName() + \" ;)\", null, null, \"SHOW_TEXT\", infos);\n instance.sendMessage(player, \"§bThis server uses your NeoPlugin\", null, null, \"SHOW_TEXT\", infos);\n }\n }\n}", "score": 0.8307838439941406 }, { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java", "retrieved_chunk": " \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +\n \"§bProxyProtocol§7: \" + Config.isProxyProtocol() + \" \\n\" +\n \"§bNeoProtectPlan§7: \" + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\") + \" \\n\" +\n \"§bBungeecordName§7: \" + stats.getServerName() + \" \\n\" +\n \"§bBungeecordVersion§7: \" + stats.getServerVersion()+ \" \\n\" +\n \"§bBungeecordPlugins§7: \" + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray());\n instance.sendMessage(player, \"§bHello \" + player.getName() + \" ;)\", null, null, \"SHOW_TEXT\", infos);\n instance.sendMessage(player, \"§bThis server uses your NeoPlugin\", null, null, \"SHOW_TEXT\", infos);", "score": 0.8259784579277039 } ]
java
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
package de.cubeattack.neoprotect.core.executor; import de.cubeattack.api.API; import de.cubeattack.api.language.Localization; import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration; import de.cubeattack.api.libraries.org.json.JSONObject; import de.cubeattack.neoprotect.core.Config; import de.cubeattack.neoprotect.core.NeoProtectPlugin; import de.cubeattack.neoprotect.core.model.Backend; import de.cubeattack.neoprotect.core.model.Gameshield; import de.cubeattack.neoprotect.core.model.Stats; import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse; import java.io.File; import java.nio.file.Files; import java.sql.Timestamp; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.atomic.AtomicReference; public class NeoProtectExecutor { private static Timer debugTimer = new Timer(); private NeoProtectPlugin instance; private Localization localization; private Object sender; private Locale locale; private String msg; private String[] args; private boolean isViaConsole; private void initials(ExecutorBuilder executeBuilder) { this.instance = executeBuilder.getInstance(); this.localization = instance.getCore().getLocalization(); this.sender = executeBuilder.getSender(); this.locale = executeBuilder.getLocal(); this.args = executeBuilder.getArgs(); this.msg = executeBuilder.getMsg(); this.isViaConsole = executeBuilder.isViaConsole(); } private void chatEvent(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (instance.getCore().getRestAPI().isAPIInvalid(msg)) { instance.sendMessage(sender, localization.get(locale, "apikey.invalid")); return; } Config.setAPIKey(msg); instance.sendMessage(sender, localization.get(locale, "apikey.valid")); gameshieldSelector(); } private void command(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (args.length == 0) { showHelp(); return; } if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) { instance.sendMessage(sender, localization.get(locale, "setup.command.required")); return; } switch (args[0].toLowerCase()) { case "setup": { if (isViaConsole) { instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command")); } else { setup(); } break; } case "ipanic": { iPanic(args); break; } case "directconnectwhitelist": { directConnectWhitelist(args); break; } case "toggle": { toggle(args); break; } case "analytics": { analytics(); break; } case "whitelist": case "blacklist": { firewall(args); break; } case "debugtool": { debugTool(args); break; } case "setgameshield": { if (args.length == 1 && !isViaConsole) { gameshieldSelector(); } else if (args.length == 2) { setGameshield(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgameshield")); } break; } case "setbackend": { if (args.length == 1 && !isViaConsole) { javaBackendSelector(); } else if (args.length == 2) { setJavaBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setbackend")); } break; } case "setgeyserbackend": { if (args.length == 1 && !isViaConsole) { bedrockBackendSelector(); } else if (args.length == 2) { setBedrockBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend")); } break; } default: { showHelp(); } } } private void setup() { instance.getCore().getPlayerInSetup().add(sender); instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"), "OPEN_URL", "https://panel.neoprotect.net/profile", "SHOW_TEXT", localization.get(locale, "apikey.find")); } private void iPanic(String[] args) { if (args.length != 1) { instance.sendMessage(sender, localization.get(locale, "usage.ipanic")); } else { instance.sendMessage(sender, localization.get(locale, "command.ipanic", localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated"))); } } private void directConnectWhitelist(String[] args) { if (args.length == 2) { instance.getCore().getDirectConnectWhitelist().add(args[1]); instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1])); } else { instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist")); } } private void toggle(String[] args) { if (args.length != 2) { instance.sendMessage(sender, localization.get(locale, "usage.toggle")); } else { int response = instance.getCore().getRestAPI().toggle(args[1]); if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } if (response == -1) { instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'"); return; } instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1], localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated"))); } } private void analytics() { instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------"); JSONObject analytics = instance.getCore().getRestAPI().getAnalytics(); instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> { if (ak.equals("bandwidth")) { return; } if (ak.equals("traffic")) { instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " + new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s"); JSONObject traffic = instance.getCore().getRestAPI().getTraffic(); AtomicReference<String> trafficUsed = new AtomicReference<>(); AtomicReference<String> trafficAvailable = new AtomicReference<>(); traffic.keySet().forEach(bk -> { if (bk.equals("used")) { trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb"); } if (bk.equals("available")) { trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb"); } }); instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get()); return; } instance.sendMessage(sender, ak .replace("onlinePlayers", "online players") .replace("cps", "connections/s") + ": " + analytics.get(ak)); }); } private void firewall(String[] args) { if (args.length == 1) { instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----"); instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall -> instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")"))); } else if (args.length == 3) { String ip = args[2]; String action = args[1]; String mode = args[0].toUpperCase(); int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode); if (response == -1) { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); return; } if (response == 0) { instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode)); return; } if (response == 400) { instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip)); return; } if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")"); } else { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); } } @SuppressWarnings("ResultOfMethodCallIgnored") private void debugTool(String[] args) { if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) { instance.sendMessage(sender, localization.get(locale, "debug.spigot")); return; } if (args.length == 2) { if (args[1].equals("cancel")) { debugTimer.cancel(); instance.getCore().setDebugRunning(false); instance.sendMessage(sender, localization.get(locale, "debug.cancelled")); return; } if (!isInteger(args[1])) { instance.sendMessage(sender, localization.get(locale, "usage.debug")); return; } } if (instance.getCore().isDebugRunning()) { instance.sendMessage(sender, localization.get(locale, "debug.running")); return; } instance.getCore().setDebugRunning(true); instance.sendMessage(sender, localization.get(locale, "debug.starting")); int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5; debugTimer = new Timer(); debugTimer.schedule(new TimerTask() { int counter = 0; @Override public void run() { counter++; instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis())); instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")"); if (counter >= amount) this.cancel(); } }, 500, 2000); debugTimer.schedule(new TimerTask() { @Override public void run() { API.getExecutorService().submit(() -> { try { long startTime = System.currentTimeMillis(); Stats stats = instance.getStats(); File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml"); YamlConfiguration configuration = new YamlConfiguration(); if (!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } configuration.load(file); configuration.set("general.osName", System.getProperty("os.name")); configuration.set("general.javaVersion", System.getProperty("java.version")); configuration.set("general.pluginVersion", stats.getPluginVersion()); configuration.set("general.ProxyName", stats.getServerName()); configuration.set("general.ProxyVersion", stats.getServerVersion()); configuration.set("general.ProxyPlugins", instance.getPlugins()); instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> { List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName); long maxPlayerToProxyLatenz = 0; long maxNeoToProxyLatenz = 0; long maxProxyToBackendLatenz = 0; long maxPlayerToNeoLatenz = 0; long avgPlayerToProxyLatenz = 0; long avgNeoToProxyLatenz = 0; long avgProxyToBackendLatenz = 0; long avgPlayerToNeoLatenz = 0; long minPlayerToProxyLatenz = Long.MAX_VALUE; long minNeoToProxyLatenz = Long.MAX_VALUE; long minProxyToBackendLatenz = Long.MAX_VALUE; long minPlayerToNeoLatenz = Long.MAX_VALUE; configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress()); configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress()); for (DebugPingResponse response : list) { if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz()) maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz()) maxNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz()) maxProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz()) maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz(); avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz(); avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz(); avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz(); if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz()) minPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (minNeoToProxyLatenz > response.getNeoToProxyLatenz()) minNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (minProxyToBackendLatenz > response.getProxyToBackendLatenz()) minProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz()) minPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); } configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz); configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size()); configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz); })); configuration.save(file); final String content = new String(Files.readAllBytes(file.toPath())); final String pasteKey = instance.getCore().getRestAPI().paste(content); instance.getCore().getDebugPingResponses().clear(); instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)"); if(pasteKey != null) { final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml"; instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null); } else { instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null); } instance.getCore().setDebugRunning(false); } catch (Exception ex) { instance.getCore().severe(ex.getMessage(), ex); } }); } }, 2000L * amount + 500); } private void gameshieldSelector() { instance.sendMessage(sender, localization.get(locale, "select.gameshield")); List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields(); for (Gameshield gameshield : gameshieldList) { instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgameshield " + gameshield.getId(), "SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId())); } } private void setGameshield(String[] args) { if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1])); return; } Config.setGameShieldID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1])); javaBackendSelector(); } private void javaBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); instance.sendMessage(sender, localization.get(locale, "select.backend", "java")); for (Backend backend : backendList) { if(backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setJavaBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1])); return; } Config.setBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1])); instance.getCore().getRestAPI().testCredentials(); bedrockBackendSelector(); } private void bedrockBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); if(backendList.stream().noneMatch(Backend::isGeyser))return; instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser")); for (Backend backend : backendList) { if(!backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgeyserbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setBedrockBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1])); return; } Config.setGeyserBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1])); if (instance.getCore().getPlayerInSetup().remove(sender)) { instance.sendMessage(sender, localization.get(locale, "setup.finished")); } } private void showHelp() { instance.sendMessage(sender, localization.get(locale, "available.commands")); instance.sendMessage(sender, " - /np setup"); instance.sendMessage(sender, " - /np ipanic"); instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)"); instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)"); instance.sendMessage(sender, " - /np debugTool (cancel / amount)"); instance.sendMessage(sender, " - /np directConnectWhitelist (ip)"); instance.sendMessage(sender, " - /np setgameshield [id]"); instance.sendMessage(sender, " - /np setbackend [id]"); instance.sendMessage(sender, " - /np setgeyserbackend [id]"); } public static class ExecutorBuilder { private NeoProtectPlugin instance; private Object sender; private String[] args; private Locale local; private String msg; private boolean viaConsole; public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) { this.instance = instance; return this; } public ExecutorBuilder sender(Object sender) { this.sender = sender; return this; } public ExecutorBuilder args(String[] args) { this.args = args; return this; } public ExecutorBuilder local(Locale local) { this.local = local; return this; } public ExecutorBuilder msg(String msg) { this.msg = msg; return this; } public ExecutorBuilder viaConsole(boolean viaConsole) { this.viaConsole = viaConsole; return this; } public void executeChatEvent() { API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this)); } public void executeCommand() { API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this)); } public NeoProtectPlugin getInstance() { return instance; } public Object getSender() { return sender; } public String[] getArgs() { return args; } public Locale getLocal() { return local; } public String getMsg() { return msg; } public boolean isViaConsole() { return viaConsole; } } public static boolean isInteger(String input) { try { Integer.parseInt(input); return true; } catch (NumberFormatException e) { return false; } } }
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
NeoProtect-NeoPlugin-a71f673
[ { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java", "retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +\n \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +", "score": 0.8797580599784851 }, { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java", "retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfig().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +", "score": 0.8713281154632568 }, { "filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java", "retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +", "score": 0.8695532083511353 }, { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java", "retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"plugin.outdated.message\", result.getCurrentVersion(), result.getLatestVersion()));\n instance.sendMessage(player, MessageFormat.format(\"§7-> §b{0}\",\n result.getReleaseUrl().replace(\"/NeoPlugin\", \"\").replace(\"/releases/tag\", \"\")),\n \"OPEN_URL\", result.getReleaseUrl(), null, null);\n }\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.restart-required.message\", result.getCurrentVersion(), result.getLatestVersion()));\n }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));", "score": 0.8642600774765015 }, { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java", "retrieved_chunk": " \"§bProxyProtocol§7: \" + Config.isProxyProtocol() + \" \\n\" +\n \"§bNeoProtectPlan§7: \" + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\") + \" \\n\" +\n \"§bSpigotName§7: \" + stats.getServerName() + \" \\n\" +\n \"§bSpigotVersion§7: \" + stats.getServerVersion() + \" \\n\" +\n \"§bSpigotPlugins§7: \" + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray());\n instance.sendMessage(player, \"§bHello \" + player.getName() + \" ;)\", null, null, \"SHOW_TEXT\", infos);\n instance.sendMessage(player, \"§bThis server uses your NeoPlugin\", null, null, \"SHOW_TEXT\", infos);\n }\n }\n}", "score": 0.8406351208686829 } ]
java
instance.sendMessage(sender, " - /np toggle (option)");
package de.cubeattack.neoprotect.core.executor; import de.cubeattack.api.API; import de.cubeattack.api.language.Localization; import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration; import de.cubeattack.api.libraries.org.json.JSONObject; import de.cubeattack.neoprotect.core.Config; import de.cubeattack.neoprotect.core.NeoProtectPlugin; import de.cubeattack.neoprotect.core.model.Backend; import de.cubeattack.neoprotect.core.model.Gameshield; import de.cubeattack.neoprotect.core.model.Stats; import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse; import java.io.File; import java.nio.file.Files; import java.sql.Timestamp; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.atomic.AtomicReference; public class NeoProtectExecutor { private static Timer debugTimer = new Timer(); private NeoProtectPlugin instance; private Localization localization; private Object sender; private Locale locale; private String msg; private String[] args; private boolean isViaConsole; private void initials(ExecutorBuilder executeBuilder) { this.instance = executeBuilder.getInstance(); this.localization = instance.getCore().getLocalization(); this.sender = executeBuilder.getSender(); this.locale = executeBuilder.getLocal(); this.args = executeBuilder.getArgs(); this.msg = executeBuilder.getMsg(); this.isViaConsole = executeBuilder.isViaConsole(); } private void chatEvent(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (instance.getCore().getRestAPI().isAPIInvalid(msg)) { instance.sendMessage(sender, localization.get(locale, "apikey.invalid")); return; } Config.setAPIKey(msg); instance.sendMessage(sender, localization.get(locale, "apikey.valid")); gameshieldSelector(); } private void command(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (args.length == 0) { showHelp(); return; } if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) { instance.sendMessage(sender, localization.get(locale, "setup.command.required")); return; } switch (args[0].toLowerCase()) { case "setup": { if (isViaConsole) { instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command")); } else { setup(); } break; } case "ipanic": { iPanic(args); break; } case "directconnectwhitelist": { directConnectWhitelist(args); break; } case "toggle": { toggle(args); break; } case "analytics": { analytics(); break; } case "whitelist": case "blacklist": { firewall(args); break; } case "debugtool": { debugTool(args); break; } case "setgameshield": { if (args.length == 1 && !isViaConsole) { gameshieldSelector(); } else if (args.length == 2) { setGameshield(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgameshield")); } break; } case "setbackend": { if (args.length == 1 && !isViaConsole) { javaBackendSelector(); } else if (args.length == 2) { setJavaBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setbackend")); } break; } case "setgeyserbackend": { if (args.length == 1 && !isViaConsole) { bedrockBackendSelector(); } else if (args.length == 2) { setBedrockBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend")); } break; } default: { showHelp(); } } } private void setup() { instance.getCore().getPlayerInSetup().add(sender); instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"), "OPEN_URL", "https://panel.neoprotect.net/profile", "SHOW_TEXT", localization.get(locale, "apikey.find")); } private void iPanic(String[] args) { if (args.length != 1) { instance.sendMessage(sender, localization.get(locale, "usage.ipanic")); } else { instance.sendMessage(sender, localization.get(locale, "command.ipanic", localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated"))); } } private void directConnectWhitelist(String[] args) { if (args.length == 2) { instance.getCore().getDirectConnectWhitelist().add(args[1]); instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1])); } else { instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist")); } } private void toggle(String[] args) { if (args.length != 2) { instance.sendMessage(sender, localization.get(locale, "usage.toggle")); } else { int response = instance.getCore().getRestAPI().toggle(args[1]); if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } if (response == -1) { instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'"); return; } instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1], localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated"))); } } private void analytics() { instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------"); JSONObject analytics = instance.getCore().getRestAPI().getAnalytics(); instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> { if (ak.equals("bandwidth")) { return; } if (ak.equals("traffic")) { instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " + new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s"); JSONObject traffic = instance.getCore().getRestAPI().getTraffic(); AtomicReference<String> trafficUsed = new AtomicReference<>(); AtomicReference<String> trafficAvailable = new AtomicReference<>(); traffic.keySet().forEach(bk -> { if (bk.equals("used")) { trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb"); } if (bk.equals("available")) { trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb"); } }); instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get()); return; } instance.sendMessage(sender, ak .replace("onlinePlayers", "online players") .replace("cps", "connections/s") + ": " + analytics.get(ak)); }); } private void firewall(String[] args) { if (args.length == 1) { instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----"); instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall -> instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")"))); } else if (args.length == 3) { String ip = args[2]; String action = args[1]; String mode = args[0].toUpperCase(); int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode); if (response == -1) { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); return; } if (response == 0) { instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode)); return; } if (response == 400) { instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip)); return; } if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")"); } else { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); } } @SuppressWarnings("ResultOfMethodCallIgnored") private void debugTool(String[] args) { if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) { instance.sendMessage(sender, localization.get(locale, "debug.spigot")); return; } if (args.length == 2) { if (args[1].equals("cancel")) { debugTimer.cancel(); instance.getCore().setDebugRunning(false); instance.sendMessage(sender, localization.get(locale, "debug.cancelled")); return; } if (!isInteger(args[1])) { instance.sendMessage(sender, localization.get(locale, "usage.debug")); return; } } if (instance.getCore().isDebugRunning()) { instance.sendMessage(sender, localization.get(locale, "debug.running")); return; } instance.getCore().setDebugRunning(true); instance.sendMessage(sender, localization.get(locale, "debug.starting")); int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5; debugTimer = new Timer(); debugTimer.schedule(new TimerTask() { int counter = 0; @Override public void run() { counter++; instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis())); instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")"); if (counter >= amount) this.cancel(); } }, 500, 2000); debugTimer.schedule(new TimerTask() { @Override public void run() { API.getExecutorService().submit(() -> { try { long startTime = System.currentTimeMillis(); Stats stats = instance.getStats(); File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml"); YamlConfiguration configuration = new YamlConfiguration(); if (!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } configuration.load(file); configuration.set("general.osName", System.getProperty("os.name")); configuration.set("general.javaVersion", System.getProperty("java.version")); configuration.set("general.pluginVersion", stats.getPluginVersion()); configuration.set("general.ProxyName", stats.getServerName()); configuration.set("general.ProxyVersion", stats.getServerVersion()); configuration.set("general.ProxyPlugins", instance.getPlugins()); instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> { List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName); long maxPlayerToProxyLatenz = 0; long maxNeoToProxyLatenz = 0; long maxProxyToBackendLatenz = 0; long maxPlayerToNeoLatenz = 0; long avgPlayerToProxyLatenz = 0; long avgNeoToProxyLatenz = 0; long avgProxyToBackendLatenz = 0; long avgPlayerToNeoLatenz = 0; long minPlayerToProxyLatenz = Long.MAX_VALUE; long minNeoToProxyLatenz = Long.MAX_VALUE; long minProxyToBackendLatenz = Long.MAX_VALUE; long minPlayerToNeoLatenz = Long.MAX_VALUE; configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress()); configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress()); for (DebugPingResponse response : list) { if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz()) maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz()) maxNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz()) maxProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz()) maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz(); avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz(); avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz(); avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz(); if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz()) minPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (minNeoToProxyLatenz > response.getNeoToProxyLatenz()) minNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (minProxyToBackendLatenz > response.getProxyToBackendLatenz()) minProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz()) minPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); } configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz); configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size()); configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz); })); configuration.save(file); final String content = new String(Files.readAllBytes(file.toPath())); final String pasteKey = instance.getCore().getRestAPI().paste(content); instance.getCore().getDebugPingResponses().clear(); instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)"); if(pasteKey != null) { final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml"; instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null); } else { instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null); } instance.getCore().setDebugRunning(false); } catch (Exception ex) { instance.getCore().severe(ex.getMessage(), ex); } }); } }, 2000L * amount + 500); } private void gameshieldSelector() { instance.sendMessage(sender, localization.get(locale, "select.gameshield")); List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields(); for (Gameshield gameshield : gameshieldList) { instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgameshield " + gameshield.getId(), "SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId())); } } private void setGameshield(String[] args) { if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1])); return; } Config.setGameShieldID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1])); javaBackendSelector(); } private void javaBackendSelector() { List<Backend>
backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java")); for (Backend backend : backendList) { if(backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setJavaBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1])); return; } Config.setBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1])); instance.getCore().getRestAPI().testCredentials(); bedrockBackendSelector(); } private void bedrockBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); if(backendList.stream().noneMatch(Backend::isGeyser))return; instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser")); for (Backend backend : backendList) { if(!backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgeyserbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setBedrockBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1])); return; } Config.setGeyserBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1])); if (instance.getCore().getPlayerInSetup().remove(sender)) { instance.sendMessage(sender, localization.get(locale, "setup.finished")); } } private void showHelp() { instance.sendMessage(sender, localization.get(locale, "available.commands")); instance.sendMessage(sender, " - /np setup"); instance.sendMessage(sender, " - /np ipanic"); instance.sendMessage(sender, " - /np analytics"); instance.sendMessage(sender, " - /np toggle (option)"); instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)"); instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)"); instance.sendMessage(sender, " - /np debugTool (cancel / amount)"); instance.sendMessage(sender, " - /np directConnectWhitelist (ip)"); instance.sendMessage(sender, " - /np setgameshield [id]"); instance.sendMessage(sender, " - /np setbackend [id]"); instance.sendMessage(sender, " - /np setgeyserbackend [id]"); } public static class ExecutorBuilder { private NeoProtectPlugin instance; private Object sender; private String[] args; private Locale local; private String msg; private boolean viaConsole; public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) { this.instance = instance; return this; } public ExecutorBuilder sender(Object sender) { this.sender = sender; return this; } public ExecutorBuilder args(String[] args) { this.args = args; return this; } public ExecutorBuilder local(Locale local) { this.local = local; return this; } public ExecutorBuilder msg(String msg) { this.msg = msg; return this; } public ExecutorBuilder viaConsole(boolean viaConsole) { this.viaConsole = viaConsole; return this; } public void executeChatEvent() { API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this)); } public void executeCommand() { API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this)); } public NeoProtectPlugin getInstance() { return instance; } public Object getSender() { return sender; } public String[] getArgs() { return args; } public Locale getLocal() { return local; } public String getMsg() { return msg; } public boolean isViaConsole() { return viaConsole; } } public static boolean isInteger(String input) { try { Integer.parseInt(input); return true; } catch (NumberFormatException e) { return false; } } }
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
NeoProtect-NeoPlugin-a71f673
[ { "filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java", "retrieved_chunk": " core.severe(\"Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield\");\n setup = false;\n return;\n } else if (isBackendInvalid(Config.getBackendID())) {\n core.severe(\"Backend is not valid! Please run /neoprotect setbackend to set the backend\");\n setup = false;\n return;\n }\n this.setup = true;\n setProxyProtocol(Config.isProxyProtocol());", "score": 0.854132890701294 }, { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java", "retrieved_chunk": " }\n }\n if (args.length <= 1) {\n list.add(\"setup\");\n if (instance.getCore().isSetup()) {\n list.add(\"directConnectWhitelist\");\n list.add(\"setgameshield\");\n list.add(\"setbackend\");\n list.add(\"analytics\");\n list.add(\"debugTool\");", "score": 0.8362745642662048 }, { "filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java", "retrieved_chunk": " return new ResponseManager(rest.callRequest(new Request.Builder().url(statsServer).header(\"GameshieldID\", gameshieldID).header(\"BackendID\", backendID).post(requestBody).build())).checkCode(200);\n }\n private boolean updateBackend(RequestBody requestBody, String backendID) {\n return rest.request(RequestType.POST_GAMESHIELD_BACKEND_UPDATE, requestBody, Config.getGameShieldID(),backendID).checkCode(200);\n }\n public void setProxyProtocol(boolean setting) {\n rest.request(RequestType.POST_GAMESHIELD_UPDATE, RequestBody.create(MediaType.parse(\"application/json\"), new JsonBuilder().appendField(\"proxyProtocol\", String.valueOf(setting)).build().toString()), Config.getGameShieldID());\n }\n public JSONObject getAnalytics() {\n return rest.request(RequestType.GET_GAMESHIELD_LASTSTATS, null, Config.getGameShieldID()).getResponseBodyObject();", "score": 0.8247792720794678 }, { "filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java", "retrieved_chunk": " public List<Gameshield> getGameshields() {\n List<Gameshield> list = new ArrayList<>();\n JSONArray gameshields = rest.request(RequestType.GET_GAMESHIELDS, null).getResponseBodyArray();\n for (Object object : gameshields) {\n JSONObject jsonObject = (JSONObject) object;\n list.add(new Gameshield(jsonObject.getString(\"id\"), jsonObject.getString(\"name\")));\n }\n return list;\n }\n public List<Backend> getBackends() {", "score": 0.8245607614517212 }, { "filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java", "retrieved_chunk": " if (backendID.isEmpty()) {\n core.severe(\"Failed to load BackendID. ID is null\");\n return;\n }\n core.info(\"API-Key loaded successful '\" + \"******************************\" + APIKey.substring(32) + \"'\");\n core.info(\"GameshieldID loaded successful '\" + gameShieldID + \"'\");\n core.info(\"BackendID loaded successful '\" + backendID + \"'\");\n }\n public static String getAPIKey() {\n return APIKey;", "score": 0.8230197429656982 } ]
java
backendList = instance.getCore().getRestAPI().getBackends();
package de.cubeattack.neoprotect.core.executor; import de.cubeattack.api.API; import de.cubeattack.api.language.Localization; import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration; import de.cubeattack.api.libraries.org.json.JSONObject; import de.cubeattack.neoprotect.core.Config; import de.cubeattack.neoprotect.core.NeoProtectPlugin; import de.cubeattack.neoprotect.core.model.Backend; import de.cubeattack.neoprotect.core.model.Gameshield; import de.cubeattack.neoprotect.core.model.Stats; import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse; import java.io.File; import java.nio.file.Files; import java.sql.Timestamp; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.atomic.AtomicReference; public class NeoProtectExecutor { private static Timer debugTimer = new Timer(); private NeoProtectPlugin instance; private Localization localization; private Object sender; private Locale locale; private String msg; private String[] args; private boolean isViaConsole; private void initials(ExecutorBuilder executeBuilder) { this.instance = executeBuilder.getInstance(); this.localization = instance.getCore().getLocalization(); this.sender = executeBuilder.getSender(); this.locale = executeBuilder.getLocal(); this.args = executeBuilder.getArgs(); this.msg = executeBuilder.getMsg(); this.isViaConsole = executeBuilder.isViaConsole(); } private void chatEvent(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (instance.getCore().getRestAPI().isAPIInvalid(msg)) { instance.sendMessage(sender, localization.get(locale, "apikey.invalid")); return; } Config.setAPIKey(msg); instance.sendMessage(sender, localization.get(locale, "apikey.valid")); gameshieldSelector(); } private void command(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (args.length == 0) { showHelp(); return; } if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) { instance.sendMessage(sender, localization.get(locale, "setup.command.required")); return; } switch (args[0].toLowerCase()) { case "setup": { if (isViaConsole) { instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command")); } else { setup(); } break; } case "ipanic": { iPanic(args); break; } case "directconnectwhitelist": { directConnectWhitelist(args); break; } case "toggle": { toggle(args); break; } case "analytics": { analytics(); break; } case "whitelist": case "blacklist": { firewall(args); break; } case "debugtool": { debugTool(args); break; } case "setgameshield": { if (args.length == 1 && !isViaConsole) { gameshieldSelector(); } else if (args.length == 2) { setGameshield(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgameshield")); } break; } case "setbackend": { if (args.length == 1 && !isViaConsole) { javaBackendSelector(); } else if (args.length == 2) { setJavaBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setbackend")); } break; } case "setgeyserbackend": { if (args.length == 1 && !isViaConsole) { bedrockBackendSelector(); } else if (args.length == 2) { setBedrockBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend")); } break; } default: { showHelp(); } } } private void setup() { instance.getCore().getPlayerInSetup().add(sender); instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"), "OPEN_URL", "https://panel.neoprotect.net/profile", "SHOW_TEXT", localization.get(locale, "apikey.find")); } private void iPanic(String[] args) { if (args.length != 1) { instance.sendMessage(sender, localization.get(locale, "usage.ipanic")); } else { instance.sendMessage(sender, localization.get(locale, "command.ipanic", localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated"))); } } private void directConnectWhitelist(String[] args) { if (args.length == 2) { instance.getCore().getDirectConnectWhitelist().add(args[1]); instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1])); } else { instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist")); } } private void toggle(String[] args) { if (args.length != 2) { instance.sendMessage(sender, localization.get(locale, "usage.toggle")); } else { int response = instance.getCore().getRestAPI().toggle(args[1]); if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } if (response == -1) { instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'"); return; } instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1], localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated"))); } } private void analytics() { instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------"); JSONObject analytics = instance.getCore().getRestAPI().getAnalytics(); instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> { if (ak.equals("bandwidth")) { return; } if (ak.equals("traffic")) { instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " + new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s"); JSONObject traffic = instance.getCore().getRestAPI().getTraffic(); AtomicReference<String> trafficUsed = new AtomicReference<>(); AtomicReference<String> trafficAvailable = new AtomicReference<>(); traffic.keySet().forEach(bk -> { if (bk.equals("used")) { trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb"); } if (bk.equals("available")) { trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb"); } }); instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get()); return; } instance.sendMessage(sender, ak .replace("onlinePlayers", "online players") .replace("cps", "connections/s") + ": " + analytics.get(ak)); }); } private void firewall(String[] args) { if (args.length == 1) { instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----"); instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall -> instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")"))); } else if (args.length == 3) { String ip = args[2]; String action = args[1]; String mode = args[0].toUpperCase(); int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode); if (response == -1) { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); return; } if (response == 0) { instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode)); return; } if (response == 400) { instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip)); return; } if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")"); } else { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); } } @SuppressWarnings("ResultOfMethodCallIgnored") private void debugTool(String[] args) { if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) { instance.sendMessage(sender, localization.get(locale, "debug.spigot")); return; } if (args.length == 2) { if (args[1].equals("cancel")) { debugTimer.cancel(); instance.getCore().setDebugRunning(false); instance.sendMessage(sender, localization.get(locale, "debug.cancelled")); return; } if (!isInteger(args[1])) { instance.sendMessage(sender, localization.get(locale, "usage.debug")); return; } } if (instance.getCore().isDebugRunning()) { instance.sendMessage(sender, localization.get(locale, "debug.running")); return; } instance.getCore().setDebugRunning(true); instance.sendMessage(sender, localization.get(locale, "debug.starting")); int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5; debugTimer = new Timer(); debugTimer.schedule(new TimerTask() { int counter = 0; @Override public void run() { counter++; instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis())); instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")"); if (counter >= amount) this.cancel(); } }, 500, 2000); debugTimer.schedule(new TimerTask() { @Override public void run() { API.getExecutorService().submit(() -> { try { long startTime = System.currentTimeMillis(); Stats stats = instance.getStats(); File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml"); YamlConfiguration configuration = new YamlConfiguration(); if (!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } configuration.load(file); configuration.set("general.osName", System.getProperty("os.name")); configuration.set("general.javaVersion", System.getProperty("java.version")); configuration.set("general.pluginVersion", stats.getPluginVersion()); configuration.set("general.ProxyName", stats.getServerName()); configuration.set("general.ProxyVersion", stats.getServerVersion()); configuration.set("general.ProxyPlugins", instance.getPlugins()); instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> { List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName); long maxPlayerToProxyLatenz = 0; long maxNeoToProxyLatenz = 0; long maxProxyToBackendLatenz = 0; long maxPlayerToNeoLatenz = 0; long avgPlayerToProxyLatenz = 0; long avgNeoToProxyLatenz = 0; long avgProxyToBackendLatenz = 0; long avgPlayerToNeoLatenz = 0; long minPlayerToProxyLatenz = Long.MAX_VALUE; long minNeoToProxyLatenz = Long.MAX_VALUE; long minProxyToBackendLatenz = Long.MAX_VALUE; long minPlayerToNeoLatenz = Long.MAX_VALUE; configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress()); configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress()); for (DebugPingResponse response : list) { if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz()) maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz()) maxNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz()) maxProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz()) maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz(); avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz(); avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz(); avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz(); if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz()) minPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (minNeoToProxyLatenz > response.getNeoToProxyLatenz()) minNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (minProxyToBackendLatenz > response.getProxyToBackendLatenz()) minProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz()) minPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); } configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz); configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size()); configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz); })); configuration.save(file); final String content = new String(Files.readAllBytes(file.toPath())); final String pasteKey = instance.getCore().getRestAPI().paste(content); instance.getCore().getDebugPingResponses().clear(); instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)"); if(pasteKey != null) { final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml"; instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null); } else { instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null); } instance.getCore().setDebugRunning(false); } catch (Exception ex) { instance.getCore().severe(ex.getMessage(), ex); } }); } }, 2000L * amount + 500); } private void gameshieldSelector() { instance.sendMessage(sender, localization.get(locale, "select.gameshield")); List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields(); for (Gameshield gameshield : gameshieldList) { instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgameshield " + gameshield.getId(), "SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId())); } } private void setGameshield(String[] args) { if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1])); return; } Config.setGameShieldID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1])); javaBackendSelector(); } private void javaBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); instance.sendMessage(sender, localization.get(locale, "select.backend", "java")); for (Backend backend : backendList) { if(backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setJavaBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1])); return; } Config.setBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1])); instance.getCore().getRestAPI().testCredentials(); bedrockBackendSelector(); } private void bedrockBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); if(backendList.stream().noneMatch(Backend::isGeyser))return; instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser")); for (Backend backend : backendList) { if(!backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgeyserbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setBedrockBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1])); return; } Config.setGeyserBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1])); if (instance.getCore().getPlayerInSetup().remove(sender)) { instance.sendMessage(sender, localization.get(locale, "setup.finished")); } } private void showHelp() { instance.sendMessage(sender, localization.get(locale, "available.commands")); instance.sendMessage(sender, " - /np setup"); instance.sendMessage(sender, " - /np ipanic"); instance.sendMessage(sender, " - /np analytics"); instance.sendMessage(sender, " - /np toggle (option)"); instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)"); instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)"); instance.sendMessage(sender, " - /np setgameshield [id]"); instance.sendMessage(sender, " - /np setbackend [id]"); instance.sendMessage(sender, " - /np setgeyserbackend [id]"); } public static class ExecutorBuilder { private NeoProtectPlugin instance; private Object sender; private String[] args; private Locale local; private String msg; private boolean viaConsole; public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) { this.instance = instance; return this; } public ExecutorBuilder sender(Object sender) { this.sender = sender; return this; } public ExecutorBuilder args(String[] args) { this.args = args; return this; } public ExecutorBuilder local(Locale local) { this.local = local; return this; } public ExecutorBuilder msg(String msg) { this.msg = msg; return this; } public ExecutorBuilder viaConsole(boolean viaConsole) { this.viaConsole = viaConsole; return this; } public void executeChatEvent() { API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this)); } public void executeCommand() { API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this)); } public NeoProtectPlugin getInstance() { return instance; } public Object getSender() { return sender; } public String[] getArgs() { return args; } public Locale getLocal() { return local; } public String getMsg() { return msg; } public boolean isViaConsole() { return viaConsole; } } public static boolean isInteger(String input) { try { Integer.parseInt(input); return true; } catch (NumberFormatException e) { return false; } } }
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
NeoProtect-NeoPlugin-a71f673
[ { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java", "retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +\n \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +", "score": 0.842098593711853 }, { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java", "retrieved_chunk": " \"§bProxyProtocol§7: \" + Config.isProxyProtocol() + \" \\n\" +\n \"§bNeoProtectPlan§7: \" + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\") + \" \\n\" +\n \"§bSpigotName§7: \" + stats.getServerName() + \" \\n\" +\n \"§bSpigotVersion§7: \" + stats.getServerVersion() + \" \\n\" +\n \"§bSpigotPlugins§7: \" + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray());\n instance.sendMessage(player, \"§bHello \" + player.getName() + \" ;)\", null, null, \"SHOW_TEXT\", infos);\n instance.sendMessage(player, \"§bThis server uses your NeoPlugin\", null, null, \"SHOW_TEXT\", infos);\n }\n }\n}", "score": 0.8349746465682983 }, { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java", "retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfig().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +", "score": 0.834258496761322 }, { "filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java", "retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +", "score": 0.8340008854866028 }, { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java", "retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"plugin.outdated.message\", result.getCurrentVersion(), result.getLatestVersion()));\n instance.sendMessage(player, MessageFormat.format(\"§7-> §b{0}\",\n result.getReleaseUrl().replace(\"/NeoPlugin\", \"\").replace(\"/releases/tag\", \"\")),\n \"OPEN_URL\", result.getReleaseUrl(), null, null);\n }\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.restart-required.message\", result.getCurrentVersion(), result.getLatestVersion()));\n }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));", "score": 0.8242539167404175 } ]
java
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
package de.cubeattack.neoprotect.core.executor; import de.cubeattack.api.API; import de.cubeattack.api.language.Localization; import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration; import de.cubeattack.api.libraries.org.json.JSONObject; import de.cubeattack.neoprotect.core.Config; import de.cubeattack.neoprotect.core.NeoProtectPlugin; import de.cubeattack.neoprotect.core.model.Backend; import de.cubeattack.neoprotect.core.model.Gameshield; import de.cubeattack.neoprotect.core.model.Stats; import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse; import java.io.File; import java.nio.file.Files; import java.sql.Timestamp; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.atomic.AtomicReference; public class NeoProtectExecutor { private static Timer debugTimer = new Timer(); private NeoProtectPlugin instance; private Localization localization; private Object sender; private Locale locale; private String msg; private String[] args; private boolean isViaConsole; private void initials(ExecutorBuilder executeBuilder) { this.instance = executeBuilder.getInstance(); this.localization = instance.getCore().getLocalization(); this.sender = executeBuilder.getSender(); this.locale = executeBuilder.getLocal(); this.args = executeBuilder.getArgs(); this.msg = executeBuilder.getMsg(); this.isViaConsole = executeBuilder.isViaConsole(); } private void chatEvent(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (instance.getCore().getRestAPI().isAPIInvalid(msg)) { instance.sendMessage(sender, localization.get(locale, "apikey.invalid")); return; } Config.setAPIKey(msg); instance.sendMessage(sender, localization.get(locale, "apikey.valid")); gameshieldSelector(); } private void command(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (args.length == 0) { showHelp(); return; } if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) { instance.sendMessage(sender, localization.get(locale, "setup.command.required")); return; } switch (args[0].toLowerCase()) { case "setup": { if (isViaConsole) { instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command")); } else { setup(); } break; } case "ipanic": { iPanic(args); break; } case "directconnectwhitelist": { directConnectWhitelist(args); break; } case "toggle": { toggle(args); break; } case "analytics": { analytics(); break; } case "whitelist": case "blacklist": { firewall(args); break; } case "debugtool": { debugTool(args); break; } case "setgameshield": { if (args.length == 1 && !isViaConsole) { gameshieldSelector(); } else if (args.length == 2) { setGameshield(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgameshield")); } break; } case "setbackend": { if (args.length == 1 && !isViaConsole) { javaBackendSelector(); } else if (args.length == 2) { setJavaBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setbackend")); } break; } case "setgeyserbackend": { if (args.length == 1 && !isViaConsole) { bedrockBackendSelector(); } else if (args.length == 2) { setBedrockBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend")); } break; } default: { showHelp(); } } } private void setup() { instance.getCore().getPlayerInSetup().add(sender); instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"), "OPEN_URL", "https://panel.neoprotect.net/profile", "SHOW_TEXT", localization.get(locale, "apikey.find")); } private void iPanic(String[] args) { if (args.length != 1) { instance.sendMessage(sender, localization.get(locale, "usage.ipanic")); } else { instance.sendMessage(sender, localization.get(locale, "command.ipanic", localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated"))); } } private void directConnectWhitelist(String[] args) { if (args.length == 2) { instance.getCore().getDirectConnectWhitelist().add(args[1]); instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1])); } else { instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist")); } } private void toggle(String[] args) { if (args.length != 2) { instance.sendMessage(sender, localization.get(locale, "usage.toggle")); } else { int response = instance.getCore().getRestAPI().toggle(args[1]); if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } if (response == -1) { instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'"); return; } instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1], localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated"))); } } private void analytics() { instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------"); JSONObject analytics = instance.getCore().getRestAPI().getAnalytics(); instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> { if (ak.equals("bandwidth")) { return; } if (ak.equals("traffic")) { instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " + new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s"); JSONObject traffic = instance.getCore().getRestAPI().getTraffic(); AtomicReference<String> trafficUsed = new AtomicReference<>(); AtomicReference<String> trafficAvailable = new AtomicReference<>(); traffic.keySet().forEach(bk -> { if (bk.equals("used")) { trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb"); } if (bk.equals("available")) { trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb"); } }); instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get()); return; } instance.sendMessage(sender, ak .replace("onlinePlayers", "online players") .replace("cps", "connections/s") + ": " + analytics.get(ak)); }); } private void firewall(String[] args) { if (args.length == 1) { instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----"); instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall -> instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")"))); } else if (args.length == 3) { String ip = args[2]; String action = args[1]; String mode = args[0].toUpperCase(); int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode); if (response == -1) { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); return; } if (response == 0) { instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode)); return; } if (response == 400) { instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip)); return; } if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")"); } else { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); } } @SuppressWarnings("ResultOfMethodCallIgnored") private void debugTool(String[] args) { if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) { instance.sendMessage(sender, localization.get(locale, "debug.spigot")); return; } if (args.length == 2) { if (args[1].equals("cancel")) { debugTimer.cancel(); instance.getCore().setDebugRunning(false); instance.sendMessage(sender, localization.get(locale, "debug.cancelled")); return; } if (!isInteger(args[1])) { instance.sendMessage(sender, localization.get(locale, "usage.debug")); return; } } if (instance.getCore().isDebugRunning()) { instance.sendMessage(sender, localization.get(locale, "debug.running")); return; } instance.getCore().setDebugRunning(true); instance.sendMessage(sender, localization.get(locale, "debug.starting")); int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5; debugTimer = new Timer(); debugTimer.schedule(new TimerTask() { int counter = 0; @Override public void run() { counter++; instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis())); instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")"); if (counter >= amount) this.cancel(); } }, 500, 2000); debugTimer.schedule(new TimerTask() { @Override public void run() { API.getExecutorService().submit(() -> { try { long startTime = System.currentTimeMillis(); Stats stats = instance.getStats(); File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml"); YamlConfiguration configuration = new YamlConfiguration(); if (!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } configuration.load(file); configuration.set("general.osName", System.getProperty("os.name")); configuration.set("general.javaVersion", System.getProperty("java.version")); configuration.set("general.pluginVersion", stats.getPluginVersion()); configuration.set("general.ProxyName", stats.getServerName()); configuration.set("general.ProxyVersion", stats.getServerVersion()); configuration.set("general.ProxyPlugins", instance.getPlugins()); instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> { List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName); long maxPlayerToProxyLatenz = 0; long maxNeoToProxyLatenz = 0; long maxProxyToBackendLatenz = 0; long maxPlayerToNeoLatenz = 0; long avgPlayerToProxyLatenz = 0; long avgNeoToProxyLatenz = 0; long avgProxyToBackendLatenz = 0; long avgPlayerToNeoLatenz = 0; long minPlayerToProxyLatenz = Long.MAX_VALUE; long minNeoToProxyLatenz = Long.MAX_VALUE; long minProxyToBackendLatenz = Long.MAX_VALUE; long minPlayerToNeoLatenz = Long.MAX_VALUE; configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress()); configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress()); for (DebugPingResponse response : list) { if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz()) maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz()) maxNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz()) maxProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz()) maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz(); avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz(); avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz(); avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz(); if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz()) minPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (minNeoToProxyLatenz > response.getNeoToProxyLatenz()) minNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (minProxyToBackendLatenz > response.getProxyToBackendLatenz()) minProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz()) minPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); } configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz); configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size()); configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz); })); configuration.save(file); final String content = new String(Files.readAllBytes(file.toPath())); final String pasteKey = instance.getCore().getRestAPI().paste(content); instance.getCore().getDebugPingResponses().clear(); instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)"); if(pasteKey != null) { final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml"; instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null); } else { instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null); } instance.getCore().setDebugRunning(false); } catch (Exception ex) { instance.getCore().severe(ex.getMessage(), ex); } }); } }, 2000L * amount + 500); } private void gameshieldSelector() { instance.sendMessage(sender, localization.get(locale, "select.gameshield")); List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields(); for (Gameshield gameshield : gameshieldList) { instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgameshield " + gameshield.getId(), "SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId())); } } private void setGameshield(String[] args) { if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1])); return; } Config.setGameShieldID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1])); javaBackendSelector(); } private void javaBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); instance.sendMessage(sender, localization.get(locale, "select.backend", "java")); for (Backend backend : backendList) { if(backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setJavaBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1])); return; } Config.setBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1])); instance.getCore().getRestAPI().testCredentials(); bedrockBackendSelector(); } private void bedrockBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); if(backendList.stream().noneMatch(Backend::isGeyser))return; instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser")); for (Backend backend : backendList) { if(!backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgeyserbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setBedrockBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1])); return; } Config.setGeyserBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1])); if (instance.getCore().getPlayerInSetup().remove(sender)) { instance.sendMessage(sender, localization.get(locale, "setup.finished")); } } private void showHelp() { instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic"); instance.sendMessage(sender, " - /np analytics"); instance.sendMessage(sender, " - /np toggle (option)"); instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)"); instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)"); instance.sendMessage(sender, " - /np debugTool (cancel / amount)"); instance.sendMessage(sender, " - /np directConnectWhitelist (ip)"); instance.sendMessage(sender, " - /np setgameshield [id]"); instance.sendMessage(sender, " - /np setbackend [id]"); instance.sendMessage(sender, " - /np setgeyserbackend [id]"); } public static class ExecutorBuilder { private NeoProtectPlugin instance; private Object sender; private String[] args; private Locale local; private String msg; private boolean viaConsole; public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) { this.instance = instance; return this; } public ExecutorBuilder sender(Object sender) { this.sender = sender; return this; } public ExecutorBuilder args(String[] args) { this.args = args; return this; } public ExecutorBuilder local(Locale local) { this.local = local; return this; } public ExecutorBuilder msg(String msg) { this.msg = msg; return this; } public ExecutorBuilder viaConsole(boolean viaConsole) { this.viaConsole = viaConsole; return this; } public void executeChatEvent() { API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this)); } public void executeCommand() { API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this)); } public NeoProtectPlugin getInstance() { return instance; } public Object getSender() { return sender; } public String[] getArgs() { return args; } public Locale getLocal() { return local; } public String getMsg() { return msg; } public boolean isViaConsole() { return viaConsole; } } public static boolean isInteger(String input) { try { Integer.parseInt(input); return true; } catch (NumberFormatException e) { return false; } } }
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
NeoProtect-NeoPlugin-a71f673
[ { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java", "retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +\n \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +", "score": 0.8482009172439575 }, { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java", "retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"plugin.outdated.message\", result.getCurrentVersion(), result.getLatestVersion()));\n instance.sendMessage(player, MessageFormat.format(\"§7-> §b{0}\",\n result.getReleaseUrl().replace(\"/NeoPlugin\", \"\").replace(\"/releases/tag\", \"\")),\n \"OPEN_URL\", result.getReleaseUrl(), null, null);\n }\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.restart-required.message\", result.getCurrentVersion(), result.getLatestVersion()));\n }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));", "score": 0.835199236869812 }, { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java", "retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfig().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +", "score": 0.8340529203414917 }, { "filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java", "retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +", "score": 0.8335942029953003 }, { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java", "retrieved_chunk": " }\n }\n if (args.length <= 1) {\n list.add(\"setup\");\n if (instance.getCore().isSetup()) {\n list.add(\"directConnectWhitelist\");\n list.add(\"setgameshield\");\n list.add(\"setbackend\");\n list.add(\"analytics\");\n list.add(\"debugTool\");", "score": 0.8324522972106934 } ]
java
instance.sendMessage(sender, " - /np setup");
package de.cubeattack.neoprotect.core.executor; import de.cubeattack.api.API; import de.cubeattack.api.language.Localization; import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration; import de.cubeattack.api.libraries.org.json.JSONObject; import de.cubeattack.neoprotect.core.Config; import de.cubeattack.neoprotect.core.NeoProtectPlugin; import de.cubeattack.neoprotect.core.model.Backend; import de.cubeattack.neoprotect.core.model.Gameshield; import de.cubeattack.neoprotect.core.model.Stats; import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse; import java.io.File; import java.nio.file.Files; import java.sql.Timestamp; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.atomic.AtomicReference; public class NeoProtectExecutor { private static Timer debugTimer = new Timer(); private NeoProtectPlugin instance; private Localization localization; private Object sender; private Locale locale; private String msg; private String[] args; private boolean isViaConsole; private void initials(ExecutorBuilder executeBuilder) { this.instance = executeBuilder.getInstance(); this.localization = instance.getCore().getLocalization(); this.sender = executeBuilder.getSender(); this.locale = executeBuilder.getLocal(); this.args = executeBuilder.getArgs(); this.msg = executeBuilder.getMsg(); this.isViaConsole = executeBuilder.isViaConsole(); } private void chatEvent(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (instance.getCore().getRestAPI().isAPIInvalid(msg)) { instance.sendMessage(sender, localization.get(locale, "apikey.invalid")); return; } Config.setAPIKey(msg); instance.sendMessage(sender, localization.get(locale, "apikey.valid")); gameshieldSelector(); } private void command(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (args.length == 0) { showHelp(); return; } if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) { instance.sendMessage(sender, localization.get(locale, "setup.command.required")); return; } switch (args[0].toLowerCase()) { case "setup": { if (isViaConsole) { instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command")); } else { setup(); } break; } case "ipanic": { iPanic(args); break; } case "directconnectwhitelist": { directConnectWhitelist(args); break; } case "toggle": { toggle(args); break; } case "analytics": { analytics(); break; } case "whitelist": case "blacklist": { firewall(args); break; } case "debugtool": { debugTool(args); break; } case "setgameshield": { if (args.length == 1 && !isViaConsole) { gameshieldSelector(); } else if (args.length == 2) { setGameshield(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgameshield")); } break; } case "setbackend": { if (args.length == 1 && !isViaConsole) { javaBackendSelector(); } else if (args.length == 2) { setJavaBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setbackend")); } break; } case "setgeyserbackend": { if (args.length == 1 && !isViaConsole) { bedrockBackendSelector(); } else if (args.length == 2) { setBedrockBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend")); } break; } default: { showHelp(); } } } private void setup() { instance.getCore().getPlayerInSetup().add(sender); instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"), "OPEN_URL", "https://panel.neoprotect.net/profile", "SHOW_TEXT", localization.get(locale, "apikey.find")); } private void iPanic(String[] args) { if (args.length != 1) { instance.sendMessage(sender, localization.get(locale, "usage.ipanic")); } else { instance.sendMessage(sender, localization.get(locale, "command.ipanic", localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated"))); } } private void directConnectWhitelist(String[] args) { if (args.length == 2) { instance.getCore().getDirectConnectWhitelist().add(args[1]); instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1])); } else { instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist")); } } private void toggle(String[] args) { if (args.length != 2) { instance.sendMessage(sender, localization.get(locale, "usage.toggle")); } else { int response = instance.getCore().getRestAPI().toggle(args[1]); if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } if (response == -1) { instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'"); return; } instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1], localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated"))); } } private void analytics() { instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------"); JSONObject analytics = instance.getCore().getRestAPI().getAnalytics(); instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> { if (ak.equals("bandwidth")) { return; } if (ak.equals("traffic")) { instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " + new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s"); JSONObject traffic = instance.getCore().getRestAPI().getTraffic(); AtomicReference<String> trafficUsed = new AtomicReference<>(); AtomicReference<String> trafficAvailable = new AtomicReference<>(); traffic.keySet().forEach(bk -> { if (bk.equals("used")) { trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb"); } if (bk.equals("available")) { trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb"); } }); instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get()); return; } instance.sendMessage(sender, ak .replace("onlinePlayers", "online players") .replace("cps", "connections/s") + ": " + analytics.get(ak)); }); } private void firewall(String[] args) { if (args.length == 1) { instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----"); instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall -> instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")"))); } else if (args.length == 3) { String ip = args[2]; String action = args[1]; String mode = args[0].toUpperCase(); int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode); if (response == -1) { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); return; } if (response == 0) { instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode)); return; } if (response == 400) { instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip)); return; } if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")"); } else { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); } } @SuppressWarnings("ResultOfMethodCallIgnored") private void debugTool(String[] args) { if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) { instance.sendMessage(sender, localization.get(locale, "debug.spigot")); return; } if (args.length == 2) { if (args[1].equals("cancel")) { debugTimer.cancel(); instance.getCore().setDebugRunning(false); instance.sendMessage(sender, localization.get(locale, "debug.cancelled")); return; } if (!isInteger(args[1])) { instance.sendMessage(sender, localization.get(locale, "usage.debug")); return; } } if (instance.getCore().isDebugRunning()) { instance.sendMessage(sender, localization.get(locale, "debug.running")); return; } instance.getCore().setDebugRunning(true); instance.sendMessage(sender, localization.get(locale, "debug.starting")); int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5; debugTimer = new Timer(); debugTimer.schedule(new TimerTask() { int counter = 0; @Override public void run() { counter++; instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis())); instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")"); if (counter >= amount) this.cancel(); } }, 500, 2000); debugTimer.schedule(new TimerTask() { @Override public void run() { API.getExecutorService().submit(() -> { try { long startTime = System.currentTimeMillis(); Stats stats = instance.getStats(); File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml"); YamlConfiguration configuration = new YamlConfiguration(); if (!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } configuration.load(file); configuration.set("general.osName", System.getProperty("os.name")); configuration.set("general.javaVersion", System.getProperty("java.version")); configuration.set("general.pluginVersion", stats.getPluginVersion()); configuration.set("general.ProxyName", stats.getServerName()); configuration.set("general.ProxyVersion", stats.getServerVersion()); configuration.set("general.ProxyPlugins", instance.getPlugins()); instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> { List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName); long maxPlayerToProxyLatenz = 0; long maxNeoToProxyLatenz = 0; long maxProxyToBackendLatenz = 0; long maxPlayerToNeoLatenz = 0; long avgPlayerToProxyLatenz = 0; long avgNeoToProxyLatenz = 0; long avgProxyToBackendLatenz = 0; long avgPlayerToNeoLatenz = 0; long minPlayerToProxyLatenz = Long.MAX_VALUE; long minNeoToProxyLatenz = Long.MAX_VALUE; long minProxyToBackendLatenz = Long.MAX_VALUE; long minPlayerToNeoLatenz = Long.MAX_VALUE; configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress()); configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress()); for (DebugPingResponse response : list) { if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz()) maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz()) maxNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz()) maxProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz()) maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz(); avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz(); avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz(); avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz(); if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz()) minPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (minNeoToProxyLatenz > response.getNeoToProxyLatenz()) minNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (minProxyToBackendLatenz > response.getProxyToBackendLatenz()) minProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz()) minPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); } configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz); configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size()); configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz); })); configuration.save(file); final String content = new String(Files.readAllBytes(file.toPath())); final String pasteKey = instance.getCore().getRestAPI().paste(content); instance.getCore().getDebugPingResponses().clear(); instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)"); if(pasteKey != null) { final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml"; instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null); } else { instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null); } instance.getCore().setDebugRunning(false); } catch (Exception ex) { instance.getCore().severe(ex.getMessage(), ex); } }); } }, 2000L * amount + 500); } private void gameshieldSelector() { instance.sendMessage(sender, localization.get(locale, "select.gameshield")); List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields(); for (Gameshield gameshield : gameshieldList) { instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgameshield " + gameshield.getId(), "SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId())); } } private void setGameshield(String[] args) { if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1])); return; } Config.setGameShieldID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1])); javaBackendSelector(); } private void javaBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); instance.sendMessage(sender, localization.get(locale, "select.backend", "java")); for (Backend backend : backendList) { if(backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setJavaBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1])); return; } Config.setBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1])); instance.getCore().getRestAPI().testCredentials(); bedrockBackendSelector(); } private void bedrockBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); if(backendList.stream().noneMatch(Backend::isGeyser))return; instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser")); for (Backend backend : backendList) { if(!backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgeyserbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setBedrockBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1])); return; } Config.setGeyserBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1])); if (
instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished")); } } private void showHelp() { instance.sendMessage(sender, localization.get(locale, "available.commands")); instance.sendMessage(sender, " - /np setup"); instance.sendMessage(sender, " - /np ipanic"); instance.sendMessage(sender, " - /np analytics"); instance.sendMessage(sender, " - /np toggle (option)"); instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)"); instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)"); instance.sendMessage(sender, " - /np debugTool (cancel / amount)"); instance.sendMessage(sender, " - /np directConnectWhitelist (ip)"); instance.sendMessage(sender, " - /np setgameshield [id]"); instance.sendMessage(sender, " - /np setbackend [id]"); instance.sendMessage(sender, " - /np setgeyserbackend [id]"); } public static class ExecutorBuilder { private NeoProtectPlugin instance; private Object sender; private String[] args; private Locale local; private String msg; private boolean viaConsole; public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) { this.instance = instance; return this; } public ExecutorBuilder sender(Object sender) { this.sender = sender; return this; } public ExecutorBuilder args(String[] args) { this.args = args; return this; } public ExecutorBuilder local(Locale local) { this.local = local; return this; } public ExecutorBuilder msg(String msg) { this.msg = msg; return this; } public ExecutorBuilder viaConsole(boolean viaConsole) { this.viaConsole = viaConsole; return this; } public void executeChatEvent() { API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this)); } public void executeCommand() { API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this)); } public NeoProtectPlugin getInstance() { return instance; } public Object getSender() { return sender; } public String[] getArgs() { return args; } public Locale getLocal() { return local; } public String getMsg() { return msg; } public boolean isViaConsole() { return viaConsole; } } public static boolean isInteger(String input) { try { Integer.parseInt(input); return true; } catch (NumberFormatException e) { return false; } } }
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
NeoProtect-NeoPlugin-a71f673
[ { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java", "retrieved_chunk": " }\n }\n if (args.length <= 1) {\n list.add(\"setup\");\n if (instance.getCore().isSetup()) {\n list.add(\"directConnectWhitelist\");\n list.add(\"setgameshield\");\n list.add(\"setbackend\");\n list.add(\"analytics\");\n list.add(\"debugTool\");", "score": 0.8337332606315613 }, { "filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java", "retrieved_chunk": " }\n if (geyserBackend != null) {\n if (!ip.equals(geyserBackend.getIp())) {\n RequestBody requestBody = RequestBody.create(MediaType.parse(\"application/json\"), new JsonBuilder().appendField(\"ipv4\", ip).build().toString());\n if (!updateBackend(requestBody, Config.getGeyserBackendID())) {\n core.warn(\"Update geyser backendserver ID '\" + Config.getGeyserBackendID() + \"' to IP '\" + ip + \"' failed\");\n } else {\n core.info(\"Update geyser backendserver ID '\" + Config.getGeyserBackendID() + \"' to IP '\" + ip + \"' success\");\n geyserBackend.setIp(ip);\n }", "score": 0.8300394415855408 }, { "filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java", "retrieved_chunk": " core.severe(\"Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield\");\n setup = false;\n return;\n } else if (isBackendInvalid(Config.getBackendID())) {\n core.severe(\"Backend is not valid! Please run /neoprotect setbackend to set the backend\");\n setup = false;\n return;\n }\n this.setup = true;\n setProxyProtocol(Config.isProxyProtocol());", "score": 0.8299877047538757 }, { "filename": "src/main/java/de/cubeattack/neoprotect/core/model/Backend.java", "retrieved_chunk": "package de.cubeattack.neoprotect.core.model;\npublic class Backend {\n private final String id;\n private String ip;\n private final String port;\n private final boolean geyser;\n public Backend(String id, String ip, String port, boolean geyser) {\n this.id = id;\n this.ip = ip;\n this.port = port;", "score": 0.8186407089233398 }, { "filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java", "retrieved_chunk": " private void backendServerIPUpdater() {\n core.info(\"BackendServerIPUpdate scheduler started\");\n new Timer().schedule(new TimerTask() {\n @Override\n public void run() {\n if (!setup) return;\n Backend javaBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getBackendID())).findAny().orElse(null);\n Backend geyserBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getGeyserBackendID())).findAny().orElse(null);\n String ip = getIpv4();\n if (ip == null) return;", "score": 0.8167981505393982 } ]
java
instance.getCore().getPlayerInSetup().remove(sender)) {
package de.cubeattack.neoprotect.core.executor; import de.cubeattack.api.API; import de.cubeattack.api.language.Localization; import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration; import de.cubeattack.api.libraries.org.json.JSONObject; import de.cubeattack.neoprotect.core.Config; import de.cubeattack.neoprotect.core.NeoProtectPlugin; import de.cubeattack.neoprotect.core.model.Backend; import de.cubeattack.neoprotect.core.model.Gameshield; import de.cubeattack.neoprotect.core.model.Stats; import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse; import java.io.File; import java.nio.file.Files; import java.sql.Timestamp; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.atomic.AtomicReference; public class NeoProtectExecutor { private static Timer debugTimer = new Timer(); private NeoProtectPlugin instance; private Localization localization; private Object sender; private Locale locale; private String msg; private String[] args; private boolean isViaConsole; private void initials(ExecutorBuilder executeBuilder) { this.instance = executeBuilder.getInstance(); this.localization = instance.getCore().getLocalization(); this.sender = executeBuilder.getSender(); this.locale = executeBuilder.getLocal(); this.args = executeBuilder.getArgs(); this.msg = executeBuilder.getMsg(); this.isViaConsole = executeBuilder.isViaConsole(); } private void chatEvent(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (instance.getCore().getRestAPI().isAPIInvalid(msg)) { instance.sendMessage(sender, localization.get(locale, "apikey.invalid")); return; } Config.setAPIKey(msg); instance.sendMessage(sender, localization.get(locale, "apikey.valid")); gameshieldSelector(); } private void command(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (args.length == 0) { showHelp(); return; } if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) { instance.sendMessage(sender, localization.get(locale, "setup.command.required")); return; } switch (args[0].toLowerCase()) { case "setup": { if (isViaConsole) { instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command")); } else { setup(); } break; } case "ipanic": { iPanic(args); break; } case "directconnectwhitelist": { directConnectWhitelist(args); break; } case "toggle": { toggle(args); break; } case "analytics": { analytics(); break; } case "whitelist": case "blacklist": { firewall(args); break; } case "debugtool": { debugTool(args); break; } case "setgameshield": { if (args.length == 1 && !isViaConsole) { gameshieldSelector(); } else if (args.length == 2) { setGameshield(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgameshield")); } break; } case "setbackend": { if (args.length == 1 && !isViaConsole) { javaBackendSelector(); } else if (args.length == 2) { setJavaBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setbackend")); } break; } case "setgeyserbackend": { if (args.length == 1 && !isViaConsole) { bedrockBackendSelector(); } else if (args.length == 2) { setBedrockBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend")); } break; } default: { showHelp(); } } } private void setup() { instance.getCore().getPlayerInSetup().add(sender); instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"), "OPEN_URL", "https://panel.neoprotect.net/profile", "SHOW_TEXT", localization.get(locale, "apikey.find")); } private void iPanic(String[] args) { if (args.length != 1) { instance.sendMessage(sender, localization.get(locale, "usage.ipanic")); } else { instance.sendMessage(sender, localization.get(locale, "command.ipanic", localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated"))); } } private void directConnectWhitelist(String[] args) { if (args.length == 2) { instance.getCore().getDirectConnectWhitelist().add(args[1]); instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1])); } else { instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist")); } } private void toggle(String[] args) { if (args.length != 2) { instance.sendMessage(sender, localization.get(locale, "usage.toggle")); } else { int response = instance.getCore().getRestAPI().toggle(args[1]); if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } if (response == -1) { instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'"); return; } instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1], localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated"))); } } private void analytics() { instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------"); JSONObject analytics = instance.getCore().getRestAPI().getAnalytics(); instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> { if (ak.equals("bandwidth")) { return; } if (ak.equals("traffic")) { instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " + new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s"); JSONObject traffic = instance.getCore().getRestAPI().getTraffic(); AtomicReference<String> trafficUsed = new AtomicReference<>(); AtomicReference<String> trafficAvailable = new AtomicReference<>(); traffic.keySet().forEach(bk -> { if (bk.equals("used")) { trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb"); } if (bk.equals("available")) { trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb"); } }); instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get()); return; } instance.sendMessage(sender, ak .replace("onlinePlayers", "online players") .replace("cps", "connections/s") + ": " + analytics.get(ak)); }); } private void firewall(String[] args) { if (args.length == 1) { instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----"); instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall -> instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")"))); } else if (args.length == 3) { String ip = args[2]; String action = args[1]; String mode = args[0].toUpperCase(); int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode); if (response == -1) { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); return; } if (response == 0) { instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode)); return; } if (response == 400) { instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip)); return; } if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")"); } else { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); } } @SuppressWarnings("ResultOfMethodCallIgnored") private void debugTool(String[] args) { if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) { instance.sendMessage(sender, localization.get(locale, "debug.spigot")); return; } if (args.length == 2) { if (args[1].equals("cancel")) { debugTimer.cancel(); instance.getCore().setDebugRunning(false); instance.sendMessage(sender, localization.get(locale, "debug.cancelled")); return; } if (!isInteger(args[1])) { instance.sendMessage(sender, localization.get(locale, "usage.debug")); return; } } if (instance.getCore().isDebugRunning()) { instance.sendMessage(sender, localization.get(locale, "debug.running")); return; } instance.getCore().setDebugRunning(true); instance.sendMessage(sender, localization.get(locale, "debug.starting")); int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5; debugTimer = new Timer(); debugTimer.schedule(new TimerTask() { int counter = 0; @Override public void run() { counter++; instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis())); instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")"); if (counter >= amount) this.cancel(); } }, 500, 2000); debugTimer.schedule(new TimerTask() { @Override public void run() { API.getExecutorService().submit(() -> { try { long startTime = System.currentTimeMillis(); Stats stats = instance.getStats(); File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml"); YamlConfiguration configuration = new YamlConfiguration(); if (!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } configuration.load(file); configuration.set("general.osName", System.getProperty("os.name")); configuration.set("general.javaVersion", System.getProperty("java.version")); configuration.set("general.pluginVersion", stats.getPluginVersion()); configuration.set("general.ProxyName", stats.getServerName()); configuration.set("general.ProxyVersion", stats.getServerVersion()); configuration.set("general.ProxyPlugins", instance.getPlugins()); instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> { List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName); long maxPlayerToProxyLatenz = 0; long maxNeoToProxyLatenz = 0; long maxProxyToBackendLatenz = 0; long maxPlayerToNeoLatenz = 0; long avgPlayerToProxyLatenz = 0; long avgNeoToProxyLatenz = 0; long avgProxyToBackendLatenz = 0; long avgPlayerToNeoLatenz = 0; long minPlayerToProxyLatenz = Long.MAX_VALUE; long minNeoToProxyLatenz = Long.MAX_VALUE; long minProxyToBackendLatenz = Long.MAX_VALUE; long minPlayerToNeoLatenz = Long.MAX_VALUE; configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress()); configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress()); for (DebugPingResponse response : list) { if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz()) maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz()) maxNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz()) maxProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz()) maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz(); avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz(); avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz(); avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz(); if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz()) minPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (minNeoToProxyLatenz > response.getNeoToProxyLatenz()) minNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (minProxyToBackendLatenz > response.getProxyToBackendLatenz()) minProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz()) minPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); } configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz); configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size()); configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz); })); configuration.save(file); final String content = new String(Files.readAllBytes(file.toPath())); final String pasteKey = instance.getCore().getRestAPI().paste(content); instance.getCore().getDebugPingResponses().clear(); instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)"); if(pasteKey != null) { final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml"; instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null); } else { instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null); } instance.getCore().setDebugRunning(false); } catch (Exception ex) { instance.getCore().severe(ex.getMessage(), ex); } }); } }, 2000L * amount + 500); } private void gameshieldSelector() { instance.sendMessage(sender, localization.get(locale, "select.gameshield")); List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields(); for (Gameshield gameshield : gameshieldList) { instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgameshield " + gameshield.getId(), "SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId())); } } private void setGameshield(String[] args) { if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1])); return; } Config.setGameShieldID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1])); javaBackendSelector(); } private void javaBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); instance.sendMessage(sender, localization.get(locale, "select.backend", "java")); for (Backend backend : backendList) { if(backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setJavaBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1])); return; } Config.setBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector(); } private void bedrockBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); if(backendList.stream().noneMatch(Backend::isGeyser))return; instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser")); for (Backend backend : backendList) { if(!backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgeyserbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setBedrockBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1])); return; } Config.setGeyserBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1])); if (instance.getCore().getPlayerInSetup().remove(sender)) { instance.sendMessage(sender, localization.get(locale, "setup.finished")); } } private void showHelp() { instance.sendMessage(sender, localization.get(locale, "available.commands")); instance.sendMessage(sender, " - /np setup"); instance.sendMessage(sender, " - /np ipanic"); instance.sendMessage(sender, " - /np analytics"); instance.sendMessage(sender, " - /np toggle (option)"); instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)"); instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)"); instance.sendMessage(sender, " - /np debugTool (cancel / amount)"); instance.sendMessage(sender, " - /np directConnectWhitelist (ip)"); instance.sendMessage(sender, " - /np setgameshield [id]"); instance.sendMessage(sender, " - /np setbackend [id]"); instance.sendMessage(sender, " - /np setgeyserbackend [id]"); } public static class ExecutorBuilder { private NeoProtectPlugin instance; private Object sender; private String[] args; private Locale local; private String msg; private boolean viaConsole; public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) { this.instance = instance; return this; } public ExecutorBuilder sender(Object sender) { this.sender = sender; return this; } public ExecutorBuilder args(String[] args) { this.args = args; return this; } public ExecutorBuilder local(Locale local) { this.local = local; return this; } public ExecutorBuilder msg(String msg) { this.msg = msg; return this; } public ExecutorBuilder viaConsole(boolean viaConsole) { this.viaConsole = viaConsole; return this; } public void executeChatEvent() { API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this)); } public void executeCommand() { API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this)); } public NeoProtectPlugin getInstance() { return instance; } public Object getSender() { return sender; } public String[] getArgs() { return args; } public Locale getLocal() { return local; } public String getMsg() { return msg; } public boolean isViaConsole() { return viaConsole; } } public static boolean isInteger(String input) { try { Integer.parseInt(input); return true; } catch (NumberFormatException e) { return false; } } }
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
NeoProtect-NeoPlugin-a71f673
[ { "filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java", "retrieved_chunk": " if (javaBackend != null) {\n if (!ip.equals(javaBackend.getIp())) {\n RequestBody requestBody = RequestBody.create(MediaType.parse(\"application/json\"), new JsonBuilder().appendField(\"ipv4\", ip).build().toString());\n if (!updateBackend(requestBody, Config.getBackendID())) {\n core.warn(\"Update java backendserver ID '\" + Config.getBackendID() + \"' to IP '\" + ip + \"' failed\");\n } else {\n core.info(\"Update java backendserver ID '\" + Config.getBackendID() + \"' to IP '\" + ip + \"' success\");\n javaBackend.setIp(ip);\n }\n }", "score": 0.8293184041976929 }, { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java", "retrieved_chunk": " }\n }\n if (args.length <= 1) {\n list.add(\"setup\");\n if (instance.getCore().isSetup()) {\n list.add(\"directConnectWhitelist\");\n list.add(\"setgameshield\");\n list.add(\"setbackend\");\n list.add(\"analytics\");\n list.add(\"debugTool\");", "score": 0.8251361846923828 }, { "filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java", "retrieved_chunk": " core.severe(\"Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield\");\n setup = false;\n return;\n } else if (isBackendInvalid(Config.getBackendID())) {\n core.severe(\"Backend is not valid! Please run /neoprotect setbackend to set the backend\");\n setup = false;\n return;\n }\n this.setup = true;\n setProxyProtocol(Config.isProxyProtocol());", "score": 0.8167800903320312 }, { "filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java", "retrieved_chunk": " private void backendServerIPUpdater() {\n core.info(\"BackendServerIPUpdate scheduler started\");\n new Timer().schedule(new TimerTask() {\n @Override\n public void run() {\n if (!setup) return;\n Backend javaBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getBackendID())).findAny().orElse(null);\n Backend geyserBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getGeyserBackendID())).findAny().orElse(null);\n String ip = getIpv4();\n if (ip == null) return;", "score": 0.810172975063324 }, { "filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java", "retrieved_chunk": " }\n if (geyserBackend != null) {\n if (!ip.equals(geyserBackend.getIp())) {\n RequestBody requestBody = RequestBody.create(MediaType.parse(\"application/json\"), new JsonBuilder().appendField(\"ipv4\", ip).build().toString());\n if (!updateBackend(requestBody, Config.getGeyserBackendID())) {\n core.warn(\"Update geyser backendserver ID '\" + Config.getGeyserBackendID() + \"' to IP '\" + ip + \"' failed\");\n } else {\n core.info(\"Update geyser backendserver ID '\" + Config.getGeyserBackendID() + \"' to IP '\" + ip + \"' success\");\n geyserBackend.setIp(ip);\n }", "score": 0.802906334400177 } ]
java
instance.getCore().getRestAPI().testCredentials();
package de.cubeattack.neoprotect.core.executor; import de.cubeattack.api.API; import de.cubeattack.api.language.Localization; import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration; import de.cubeattack.api.libraries.org.json.JSONObject; import de.cubeattack.neoprotect.core.Config; import de.cubeattack.neoprotect.core.NeoProtectPlugin; import de.cubeattack.neoprotect.core.model.Backend; import de.cubeattack.neoprotect.core.model.Gameshield; import de.cubeattack.neoprotect.core.model.Stats; import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse; import java.io.File; import java.nio.file.Files; import java.sql.Timestamp; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.atomic.AtomicReference; public class NeoProtectExecutor { private static Timer debugTimer = new Timer(); private NeoProtectPlugin instance; private Localization localization; private Object sender; private Locale locale; private String msg; private String[] args; private boolean isViaConsole; private void initials(ExecutorBuilder executeBuilder) { this.instance = executeBuilder.getInstance(); this.localization = instance.getCore().getLocalization(); this.sender = executeBuilder.getSender(); this.locale = executeBuilder.getLocal(); this.args = executeBuilder.getArgs(); this.msg = executeBuilder.getMsg(); this.isViaConsole = executeBuilder.isViaConsole(); } private void chatEvent(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (instance.getCore().getRestAPI().isAPIInvalid(msg)) { instance.sendMessage(sender, localization.get(locale, "apikey.invalid")); return; } Config.setAPIKey(msg); instance.sendMessage(sender, localization.get(locale, "apikey.valid")); gameshieldSelector(); } private void command(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (args.length == 0) { showHelp(); return; } if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) { instance.sendMessage(sender, localization.get(locale, "setup.command.required")); return; } switch (args[0].toLowerCase()) { case "setup": { if (isViaConsole) { instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command")); } else { setup(); } break; } case "ipanic": { iPanic(args); break; } case "directconnectwhitelist": { directConnectWhitelist(args); break; } case "toggle": { toggle(args); break; } case "analytics": { analytics(); break; } case "whitelist": case "blacklist": { firewall(args); break; } case "debugtool": { debugTool(args); break; } case "setgameshield": { if (args.length == 1 && !isViaConsole) { gameshieldSelector(); } else if (args.length == 2) { setGameshield(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgameshield")); } break; } case "setbackend": { if (args.length == 1 && !isViaConsole) { javaBackendSelector(); } else if (args.length == 2) { setJavaBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setbackend")); } break; } case "setgeyserbackend": { if (args.length == 1 && !isViaConsole) { bedrockBackendSelector(); } else if (args.length == 2) { setBedrockBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend")); } break; } default: { showHelp(); } } } private void setup() { instance.getCore().getPlayerInSetup().add(sender); instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"), "OPEN_URL", "https://panel.neoprotect.net/profile", "SHOW_TEXT", localization.get(locale, "apikey.find")); } private void iPanic(String[] args) { if (args.length != 1) { instance.sendMessage(sender, localization.get(locale, "usage.ipanic")); } else { instance.sendMessage(sender, localization.get(locale, "command.ipanic", localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated"))); } } private void directConnectWhitelist(String[] args) { if (args.length == 2) { instance.getCore().getDirectConnectWhitelist().add(args[1]); instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1])); } else { instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist")); } } private void toggle(String[] args) { if (args.length != 2) { instance.sendMessage(sender, localization.get(locale, "usage.toggle")); } else { int response = instance.getCore().getRestAPI().toggle(args[1]); if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } if (response == -1) { instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'"); return; } instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1], localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated"))); } } private void analytics() { instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------"); JSONObject analytics = instance.getCore().getRestAPI().getAnalytics(); instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> { if (ak.equals("bandwidth")) { return; } if (ak.equals("traffic")) { instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " + new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s"); JSONObject traffic = instance.getCore().getRestAPI().getTraffic(); AtomicReference<String> trafficUsed = new AtomicReference<>(); AtomicReference<String> trafficAvailable = new AtomicReference<>(); traffic.keySet().forEach(bk -> { if (bk.equals("used")) { trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb"); } if (bk.equals("available")) { trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb"); } }); instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get()); return; } instance.sendMessage(sender, ak .replace("onlinePlayers", "online players") .replace("cps", "connections/s") + ": " + analytics.get(ak)); }); } private void firewall(String[] args) { if (args.length == 1) { instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----"); instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall -> instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")"))); } else if (args.length == 3) { String ip = args[2]; String action = args[1]; String mode = args[0].toUpperCase(); int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode); if (response == -1) { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); return; } if (response == 0) { instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode)); return; } if (response == 400) { instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip)); return; } if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")"); } else { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); } } @SuppressWarnings("ResultOfMethodCallIgnored") private void debugTool(String[] args) { if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) { instance.sendMessage(sender, localization.get(locale, "debug.spigot")); return; } if (args.length == 2) { if (args[1].equals("cancel")) { debugTimer.cancel(); instance.getCore().setDebugRunning(false); instance.sendMessage(sender, localization.get(locale, "debug.cancelled")); return; } if (!isInteger(args[1])) { instance.sendMessage(sender, localization.get(locale, "usage.debug")); return; } } if (instance.getCore().isDebugRunning()) { instance.sendMessage(sender, localization.get(locale, "debug.running")); return; } instance.getCore().setDebugRunning(true); instance.sendMessage(sender, localization.get(locale, "debug.starting")); int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5; debugTimer = new Timer(); debugTimer.schedule(new TimerTask() { int counter = 0; @Override public void run() { counter++; instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis())); instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")"); if (counter >= amount) this.cancel(); } }, 500, 2000); debugTimer.schedule(new TimerTask() { @Override public void run() { API.getExecutorService().submit(() -> { try { long startTime = System.currentTimeMillis(); Stats stats = instance.getStats(); File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml"); YamlConfiguration configuration = new YamlConfiguration(); if (!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } configuration.load(file); configuration.set("general.osName", System.getProperty("os.name")); configuration.set("general.javaVersion", System.getProperty("java.version")); configuration.set("general.pluginVersion", stats.getPluginVersion()); configuration.set("general.ProxyName", stats.getServerName()); configuration.set("general.ProxyVersion", stats.getServerVersion()); configuration.set("general.ProxyPlugins", instance.getPlugins()); instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> { List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName); long maxPlayerToProxyLatenz = 0; long maxNeoToProxyLatenz = 0; long maxProxyToBackendLatenz = 0; long maxPlayerToNeoLatenz = 0; long avgPlayerToProxyLatenz = 0; long avgNeoToProxyLatenz = 0; long avgProxyToBackendLatenz = 0; long avgPlayerToNeoLatenz = 0; long minPlayerToProxyLatenz = Long.MAX_VALUE; long minNeoToProxyLatenz = Long.MAX_VALUE; long minProxyToBackendLatenz = Long.MAX_VALUE; long minPlayerToNeoLatenz = Long.MAX_VALUE; configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress()); configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress()); for (DebugPingResponse response : list) { if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz()) maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz()) maxNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz()) maxProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz()) maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz(); avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz(); avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz(); avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz(); if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz()) minPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (minNeoToProxyLatenz > response.getNeoToProxyLatenz()) minNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (minProxyToBackendLatenz > response.getProxyToBackendLatenz()) minProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz()) minPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); } configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz); configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size()); configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz); })); configuration.save(file); final String content = new String(Files.readAllBytes(file.toPath())); final String pasteKey = instance.getCore().getRestAPI().paste(content); instance.getCore().getDebugPingResponses().clear(); instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)"); if(pasteKey != null) { final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml"; instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null); } else { instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null); } instance.getCore().setDebugRunning(false); } catch (Exception ex) { instance.getCore().severe(ex.getMessage(), ex); } }); } }, 2000L * amount + 500); } private void gameshieldSelector() { instance.sendMessage(sender, localization.get(locale, "select.gameshield")); List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields(); for (Gameshield gameshield : gameshieldList) { instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgameshield " + gameshield.getId(), "SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId())); } } private void setGameshield(String[] args) { if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1])); return; } Config.setGameShieldID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1])); javaBackendSelector(); } private void javaBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); instance.sendMessage(sender, localization.get(locale, "select.backend", "java")); for (Backend backend : backendList) { if(backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setJavaBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1])); return; } Config.setBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1])); instance.getCore().getRestAPI().testCredentials(); bedrockBackendSelector(); } private void bedrockBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); if(backendList.stream().noneMatch(Backend::isGeyser))return; instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser")); for (Backend backend : backendList) { if(!backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgeyserbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setBedrockBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1])); return; } Config.setGeyserBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1])); if (instance.getCore().getPlayerInSetup().remove(sender)) { instance.sendMessage(sender, localization.get(locale, "setup.finished")); } } private void showHelp() { instance.sendMessage(sender, localization.get(locale, "available.commands")); instance.sendMessage(sender, " - /np setup"); instance.sendMessage(sender, " - /np ipanic"); instance.sendMessage(sender, " - /np analytics"); instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)"); instance.sendMessage(sender, " - /np debugTool (cancel / amount)"); instance.sendMessage(sender, " - /np directConnectWhitelist (ip)"); instance.sendMessage(sender, " - /np setgameshield [id]"); instance.sendMessage(sender, " - /np setbackend [id]"); instance.sendMessage(sender, " - /np setgeyserbackend [id]"); } public static class ExecutorBuilder { private NeoProtectPlugin instance; private Object sender; private String[] args; private Locale local; private String msg; private boolean viaConsole; public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) { this.instance = instance; return this; } public ExecutorBuilder sender(Object sender) { this.sender = sender; return this; } public ExecutorBuilder args(String[] args) { this.args = args; return this; } public ExecutorBuilder local(Locale local) { this.local = local; return this; } public ExecutorBuilder msg(String msg) { this.msg = msg; return this; } public ExecutorBuilder viaConsole(boolean viaConsole) { this.viaConsole = viaConsole; return this; } public void executeChatEvent() { API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this)); } public void executeCommand() { API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this)); } public NeoProtectPlugin getInstance() { return instance; } public Object getSender() { return sender; } public String[] getArgs() { return args; } public Locale getLocal() { return local; } public String getMsg() { return msg; } public boolean isViaConsole() { return viaConsole; } } public static boolean isInteger(String input) { try { Integer.parseInt(input); return true; } catch (NumberFormatException e) { return false; } } }
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
NeoProtect-NeoPlugin-a71f673
[ { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java", "retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +\n \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +", "score": 0.8736287355422974 }, { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java", "retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"plugin.outdated.message\", result.getCurrentVersion(), result.getLatestVersion()));\n instance.sendMessage(player, MessageFormat.format(\"§7-> §b{0}\",\n result.getReleaseUrl().replace(\"/NeoPlugin\", \"\").replace(\"/releases/tag\", \"\")),\n \"OPEN_URL\", result.getReleaseUrl(), null, null);\n }\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.restart-required.message\", result.getCurrentVersion(), result.getLatestVersion()));\n }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));", "score": 0.8584864139556885 }, { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java", "retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfig().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +", "score": 0.8558350801467896 }, { "filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java", "retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +", "score": 0.8551145792007446 }, { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java", "retrieved_chunk": " \"§bProxyProtocol§7: \" + Config.isProxyProtocol() + \" \\n\" +\n \"§bNeoProtectPlan§7: \" + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\") + \" \\n\" +\n \"§bSpigotName§7: \" + stats.getServerName() + \" \\n\" +\n \"§bSpigotVersion§7: \" + stats.getServerVersion() + \" \\n\" +\n \"§bSpigotPlugins§7: \" + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray());\n instance.sendMessage(player, \"§bHello \" + player.getName() + \" ;)\", null, null, \"SHOW_TEXT\", infos);\n instance.sendMessage(player, \"§bThis server uses your NeoPlugin\", null, null, \"SHOW_TEXT\", infos);\n }\n }\n}", "score": 0.8388220071792603 } ]
java
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
package de.cubeattack.neoprotect.core.executor; import de.cubeattack.api.API; import de.cubeattack.api.language.Localization; import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration; import de.cubeattack.api.libraries.org.json.JSONObject; import de.cubeattack.neoprotect.core.Config; import de.cubeattack.neoprotect.core.NeoProtectPlugin; import de.cubeattack.neoprotect.core.model.Backend; import de.cubeattack.neoprotect.core.model.Gameshield; import de.cubeattack.neoprotect.core.model.Stats; import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse; import java.io.File; import java.nio.file.Files; import java.sql.Timestamp; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.atomic.AtomicReference; public class NeoProtectExecutor { private static Timer debugTimer = new Timer(); private NeoProtectPlugin instance; private Localization localization; private Object sender; private Locale locale; private String msg; private String[] args; private boolean isViaConsole; private void initials(ExecutorBuilder executeBuilder) { this.instance = executeBuilder.getInstance(); this.localization = instance.getCore().getLocalization(); this.sender = executeBuilder.getSender(); this.locale = executeBuilder.getLocal(); this.args = executeBuilder.getArgs(); this.msg = executeBuilder.getMsg(); this.isViaConsole = executeBuilder.isViaConsole(); } private void chatEvent(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (instance.getCore().getRestAPI().isAPIInvalid(msg)) { instance.sendMessage(sender, localization.get(locale, "apikey.invalid")); return; } Config.setAPIKey(msg); instance.sendMessage(sender, localization.get(locale, "apikey.valid")); gameshieldSelector(); } private void command(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (args.length == 0) { showHelp(); return; } if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) { instance.sendMessage(sender, localization.get(locale, "setup.command.required")); return; } switch (args[0].toLowerCase()) { case "setup": { if (isViaConsole) { instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command")); } else { setup(); } break; } case "ipanic": { iPanic(args); break; } case "directconnectwhitelist": { directConnectWhitelist(args); break; } case "toggle": { toggle(args); break; } case "analytics": { analytics(); break; } case "whitelist": case "blacklist": { firewall(args); break; } case "debugtool": { debugTool(args); break; } case "setgameshield": { if (args.length == 1 && !isViaConsole) { gameshieldSelector(); } else if (args.length == 2) { setGameshield(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgameshield")); } break; } case "setbackend": { if (args.length == 1 && !isViaConsole) { javaBackendSelector(); } else if (args.length == 2) { setJavaBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setbackend")); } break; } case "setgeyserbackend": { if (args.length == 1 && !isViaConsole) { bedrockBackendSelector(); } else if (args.length == 2) { setBedrockBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend")); } break; } default: { showHelp(); } } } private void setup() { instance.getCore().getPlayerInSetup().add(sender); instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"), "OPEN_URL", "https://panel.neoprotect.net/profile", "SHOW_TEXT", localization.get(locale, "apikey.find")); } private void iPanic(String[] args) { if (args.length != 1) { instance.sendMessage(sender, localization.get(locale, "usage.ipanic")); } else { instance.sendMessage(sender, localization.get(locale, "command.ipanic", localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated"))); } } private void directConnectWhitelist(String[] args) { if (args.length == 2) { instance.getCore().getDirectConnectWhitelist().add(args[1]); instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1])); } else { instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist")); } } private void toggle(String[] args) { if (args.length != 2) { instance.sendMessage(sender, localization.get(locale, "usage.toggle")); } else { int response = instance.getCore().getRestAPI().toggle(args[1]); if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } if (response == -1) { instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'"); return; } instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1], localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated"))); } } private void analytics() { instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------"); JSONObject analytics = instance.getCore().getRestAPI().getAnalytics(); instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> { if (ak.equals("bandwidth")) { return; } if (ak.equals("traffic")) { instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " + new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s"); JSONObject traffic = instance.getCore().getRestAPI().getTraffic(); AtomicReference<String> trafficUsed = new AtomicReference<>(); AtomicReference<String> trafficAvailable = new AtomicReference<>(); traffic.keySet().forEach(bk -> { if (bk.equals("used")) { trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb"); } if (bk.equals("available")) { trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb"); } }); instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get()); return; } instance.sendMessage(sender, ak .replace("onlinePlayers", "online players") .replace("cps", "connections/s") + ": " + analytics.get(ak)); }); } private void firewall(String[] args) { if (args.length == 1) { instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----"); instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall -> instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")"))); } else if (args.length == 3) { String ip = args[2]; String action = args[1]; String mode = args[0].toUpperCase(); int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode); if (response == -1) { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); return; } if (response == 0) { instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode)); return; } if (response == 400) { instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip)); return; } if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")"); } else { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); } } @SuppressWarnings("ResultOfMethodCallIgnored") private void debugTool(String[] args) { if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) { instance.sendMessage(sender, localization.get(locale, "debug.spigot")); return; } if (args.length == 2) { if (args[1].equals("cancel")) { debugTimer.cancel(); instance.getCore().setDebugRunning(false); instance.sendMessage(sender, localization.get(locale, "debug.cancelled")); return; } if (!isInteger(args[1])) { instance.sendMessage(sender, localization.get(locale, "usage.debug")); return; } } if (instance.getCore().isDebugRunning()) { instance.sendMessage(sender, localization.get(locale, "debug.running")); return; } instance.getCore().setDebugRunning(true); instance.sendMessage(sender, localization.get(locale, "debug.starting")); int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5; debugTimer = new Timer(); debugTimer.schedule(new TimerTask() { int counter = 0; @Override public void run() { counter++; instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis())); instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")"); if (counter >= amount) this.cancel(); } }, 500, 2000); debugTimer.schedule(new TimerTask() { @Override public void run() { API.getExecutorService().submit(() -> { try { long startTime = System.currentTimeMillis(); Stats stats = instance.getStats(); File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml"); YamlConfiguration configuration = new YamlConfiguration(); if (!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } configuration.load(file); configuration.set("general.osName", System.getProperty("os.name")); configuration.set("general.javaVersion", System.getProperty("java.version")); configuration.set("general.pluginVersion", stats.getPluginVersion()); configuration.set("general.ProxyName", stats.getServerName()); configuration.set("general.ProxyVersion", stats.getServerVersion()); configuration.set("general.ProxyPlugins", instance.getPlugins()); instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> { List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName); long maxPlayerToProxyLatenz = 0; long maxNeoToProxyLatenz = 0; long maxProxyToBackendLatenz = 0; long maxPlayerToNeoLatenz = 0; long avgPlayerToProxyLatenz = 0; long avgNeoToProxyLatenz = 0; long avgProxyToBackendLatenz = 0; long avgPlayerToNeoLatenz = 0; long minPlayerToProxyLatenz = Long.MAX_VALUE; long minNeoToProxyLatenz = Long.MAX_VALUE; long minProxyToBackendLatenz = Long.MAX_VALUE; long minPlayerToNeoLatenz = Long.MAX_VALUE; configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress()); configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress()); for (DebugPingResponse response : list) { if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz()) maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz()) maxNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz()) maxProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz()) maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz(); avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz(); avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz(); avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz(); if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz()) minPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (minNeoToProxyLatenz > response.getNeoToProxyLatenz()) minNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (minProxyToBackendLatenz > response.getProxyToBackendLatenz()) minProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz()) minPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); } configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz); configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size()); configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz); })); configuration.save(file); final String content = new String(Files.readAllBytes(file.toPath())); final String pasteKey = instance.getCore().getRestAPI().paste(content); instance.getCore().getDebugPingResponses().clear(); instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)"); if(pasteKey != null) { final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml"; instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null); } else { instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null); } instance.getCore().setDebugRunning(false); } catch (Exception ex) { instance.getCore().severe(ex.getMessage(), ex); } }); } }, 2000L * amount + 500); } private void gameshieldSelector() { instance.sendMessage(sender, localization.get(locale, "select.gameshield")); List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields(); for (Gameshield gameshield : gameshieldList) { instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgameshield " + gameshield.getId(), "SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId())); } } private void setGameshield(String[] args) { if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1])); return; } Config.setGameShieldID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1])); javaBackendSelector(); } private void javaBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); instance.sendMessage(sender, localization.get(locale, "select.backend", "java")); for (Backend backend : backendList) { if(backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setJavaBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1])); return; } Config.setBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1])); instance.getCore().getRestAPI().testCredentials(); bedrockBackendSelector(); } private void bedrockBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); if(backendList.stream().noneMatch(Backend::isGeyser))return; instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser")); for (Backend backend : backendList) { if(!backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgeyserbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setBedrockBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1])); return; } Config.setGeyserBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1])); if (instance.getCore().getPlayerInSetup().remove(sender)) { instance.sendMessage(sender, localization.get(locale, "setup.finished")); } } private void showHelp() { instance.sendMessage(sender, localization.get(locale, "available.commands")); instance.sendMessage(sender, " - /np setup"); instance.sendMessage(sender, " - /np ipanic"); instance.sendMessage(sender, " - /np analytics"); instance.sendMessage(sender, " - /np toggle (option)"); instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)"); instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)"); instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]"); instance.sendMessage(sender, " - /np setbackend [id]"); instance.sendMessage(sender, " - /np setgeyserbackend [id]"); } public static class ExecutorBuilder { private NeoProtectPlugin instance; private Object sender; private String[] args; private Locale local; private String msg; private boolean viaConsole; public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) { this.instance = instance; return this; } public ExecutorBuilder sender(Object sender) { this.sender = sender; return this; } public ExecutorBuilder args(String[] args) { this.args = args; return this; } public ExecutorBuilder local(Locale local) { this.local = local; return this; } public ExecutorBuilder msg(String msg) { this.msg = msg; return this; } public ExecutorBuilder viaConsole(boolean viaConsole) { this.viaConsole = viaConsole; return this; } public void executeChatEvent() { API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this)); } public void executeCommand() { API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this)); } public NeoProtectPlugin getInstance() { return instance; } public Object getSender() { return sender; } public String[] getArgs() { return args; } public Locale getLocal() { return local; } public String getMsg() { return msg; } public boolean isViaConsole() { return viaConsole; } } public static boolean isInteger(String input) { try { Integer.parseInt(input); return true; } catch (NumberFormatException e) { return false; } } }
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
NeoProtect-NeoPlugin-a71f673
[ { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java", "retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +\n \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +", "score": 0.844803512096405 }, { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java", "retrieved_chunk": " \"§bProxyProtocol§7: \" + Config.isProxyProtocol() + \" \\n\" +\n \"§bNeoProtectPlan§7: \" + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\") + \" \\n\" +\n \"§bSpigotName§7: \" + stats.getServerName() + \" \\n\" +\n \"§bSpigotVersion§7: \" + stats.getServerVersion() + \" \\n\" +\n \"§bSpigotPlugins§7: \" + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray());\n instance.sendMessage(player, \"§bHello \" + player.getName() + \" ;)\", null, null, \"SHOW_TEXT\", infos);\n instance.sendMessage(player, \"§bThis server uses your NeoPlugin\", null, null, \"SHOW_TEXT\", infos);\n }\n }\n}", "score": 0.8409169912338257 }, { "filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java", "retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +", "score": 0.8365545868873596 }, { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java", "retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfig().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +", "score": 0.8362770080566406 }, { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java", "retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"plugin.outdated.message\", result.getCurrentVersion(), result.getLatestVersion()));\n instance.sendMessage(player, MessageFormat.format(\"§7-> §b{0}\",\n result.getReleaseUrl().replace(\"/NeoPlugin\", \"\").replace(\"/releases/tag\", \"\")),\n \"OPEN_URL\", result.getReleaseUrl(), null, null);\n }\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.restart-required.message\", result.getCurrentVersion(), result.getLatestVersion()));\n }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));", "score": 0.8270927667617798 } ]
java
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
package de.cubeattack.neoprotect.core.executor; import de.cubeattack.api.API; import de.cubeattack.api.language.Localization; import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration; import de.cubeattack.api.libraries.org.json.JSONObject; import de.cubeattack.neoprotect.core.Config; import de.cubeattack.neoprotect.core.NeoProtectPlugin; import de.cubeattack.neoprotect.core.model.Backend; import de.cubeattack.neoprotect.core.model.Gameshield; import de.cubeattack.neoprotect.core.model.Stats; import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse; import java.io.File; import java.nio.file.Files; import java.sql.Timestamp; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.atomic.AtomicReference; public class NeoProtectExecutor { private static Timer debugTimer = new Timer(); private NeoProtectPlugin instance; private Localization localization; private Object sender; private Locale locale; private String msg; private String[] args; private boolean isViaConsole; private void initials(ExecutorBuilder executeBuilder) { this.instance = executeBuilder.getInstance(); this.localization = instance.getCore().getLocalization(); this.sender = executeBuilder.getSender(); this.locale = executeBuilder.getLocal(); this.args = executeBuilder.getArgs(); this.msg = executeBuilder.getMsg(); this.isViaConsole = executeBuilder.isViaConsole(); } private void chatEvent(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (instance.getCore().getRestAPI().isAPIInvalid(msg)) { instance.sendMessage(sender, localization.get(locale, "apikey.invalid")); return; } Config.setAPIKey(msg); instance.sendMessage(sender, localization.get(locale, "apikey.valid")); gameshieldSelector(); } private void command(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (args.length == 0) { showHelp(); return; } if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) { instance.sendMessage(sender, localization.get(locale, "setup.command.required")); return; } switch (args[0].toLowerCase()) { case "setup": { if (isViaConsole) { instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command")); } else { setup(); } break; } case "ipanic": { iPanic(args); break; } case "directconnectwhitelist": { directConnectWhitelist(args); break; } case "toggle": { toggle(args); break; } case "analytics": { analytics(); break; } case "whitelist": case "blacklist": { firewall(args); break; } case "debugtool": { debugTool(args); break; } case "setgameshield": { if (args.length == 1 && !isViaConsole) { gameshieldSelector(); } else if (args.length == 2) { setGameshield(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgameshield")); } break; } case "setbackend": { if (args.length == 1 && !isViaConsole) { javaBackendSelector(); } else if (args.length == 2) { setJavaBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setbackend")); } break; } case "setgeyserbackend": { if (args.length == 1 && !isViaConsole) { bedrockBackendSelector(); } else if (args.length == 2) { setBedrockBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend")); } break; } default: { showHelp(); } } } private void setup() { instance.getCore().getPlayerInSetup().add(sender); instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"), "OPEN_URL", "https://panel.neoprotect.net/profile", "SHOW_TEXT", localization.get(locale, "apikey.find")); } private void iPanic(String[] args) { if (args.length != 1) { instance.sendMessage(sender, localization.get(locale, "usage.ipanic")); } else { instance.sendMessage(sender, localization.get(locale, "command.ipanic", localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated"))); } } private void directConnectWhitelist(String[] args) { if (args.length == 2) { instance.getCore().getDirectConnectWhitelist().add(args[1]); instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1])); } else { instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist")); } } private void toggle(String[] args) { if (args.length != 2) { instance.sendMessage(sender, localization.get(locale, "usage.toggle")); } else { int response = instance.getCore().getRestAPI().toggle(args[1]); if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } if (response == -1) { instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'"); return; } instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1], localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated"))); } } private void analytics() { instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------"); JSONObject analytics = instance.getCore().getRestAPI().getAnalytics(); instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> { if (ak.equals("bandwidth")) { return; } if (ak.equals("traffic")) { instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " + new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s"); JSONObject traffic = instance.getCore().getRestAPI().getTraffic(); AtomicReference<String> trafficUsed = new AtomicReference<>(); AtomicReference<String> trafficAvailable = new AtomicReference<>(); traffic.keySet().forEach(bk -> { if (bk.equals("used")) { trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb"); } if (bk.equals("available")) { trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb"); } }); instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get()); return; } instance.sendMessage(sender, ak .replace("onlinePlayers", "online players") .replace("cps", "connections/s") + ": " + analytics.get(ak)); }); } private void firewall(String[] args) { if (args.length == 1) { instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----"); instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall -> instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")"))); } else if (args.length == 3) { String ip = args[2]; String action = args[1]; String mode = args[0].toUpperCase(); int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode); if (response == -1) { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); return; } if (response == 0) { instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode)); return; } if (response == 400) { instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip)); return; } if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")"); } else { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); } } @SuppressWarnings("ResultOfMethodCallIgnored") private void debugTool(String[] args) { if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) { instance.sendMessage(sender, localization.get(locale, "debug.spigot")); return; } if (args.length == 2) { if (args[1].equals("cancel")) { debugTimer.cancel(); instance.getCore().setDebugRunning(false); instance.sendMessage(sender, localization.get(locale, "debug.cancelled")); return; } if (!isInteger(args[1])) { instance.sendMessage(sender, localization.get(locale, "usage.debug")); return; } } if (instance.getCore().isDebugRunning()) { instance.sendMessage(sender, localization.get(locale, "debug.running")); return; } instance.getCore().setDebugRunning(true); instance.sendMessage(sender, localization.get(locale, "debug.starting")); int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5; debugTimer = new Timer(); debugTimer.schedule(new TimerTask() { int counter = 0; @Override public void run() { counter++; instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis())); instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")"); if (counter >= amount) this.cancel(); } }, 500, 2000); debugTimer.schedule(new TimerTask() { @Override public void run() { API.getExecutorService().submit(() -> { try { long startTime = System.currentTimeMillis(); Stats stats = instance.getStats(); File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml"); YamlConfiguration configuration = new YamlConfiguration(); if (!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } configuration.load(file); configuration.set("general.osName", System.getProperty("os.name")); configuration.set("general.javaVersion", System.getProperty("java.version")); configuration.set("general.pluginVersion", stats.getPluginVersion()); configuration.set("general.ProxyName", stats.getServerName()); configuration.set("general.ProxyVersion", stats.getServerVersion()); configuration.set("general.ProxyPlugins", instance.getPlugins()); instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> { List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName); long maxPlayerToProxyLatenz = 0; long maxNeoToProxyLatenz = 0; long maxProxyToBackendLatenz = 0; long maxPlayerToNeoLatenz = 0; long avgPlayerToProxyLatenz = 0; long avgNeoToProxyLatenz = 0; long avgProxyToBackendLatenz = 0; long avgPlayerToNeoLatenz = 0; long minPlayerToProxyLatenz = Long.MAX_VALUE; long minNeoToProxyLatenz = Long.MAX_VALUE; long minProxyToBackendLatenz = Long.MAX_VALUE; long minPlayerToNeoLatenz = Long.MAX_VALUE; configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress()); configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress()); for (DebugPingResponse response : list) { if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz()) maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz()) maxNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz()) maxProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz()) maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz(); avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz(); avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz(); avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz(); if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz()) minPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (minNeoToProxyLatenz > response.getNeoToProxyLatenz()) minNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (minProxyToBackendLatenz > response.getProxyToBackendLatenz()) minProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz()) minPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); } configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz); configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size()); configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz); })); configuration.save(file); final String content = new String(Files.readAllBytes(file.toPath())); final String pasteKey = instance.getCore().getRestAPI().paste(content); instance.getCore().getDebugPingResponses().clear(); instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)"); if(pasteKey != null) { final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml"; instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null); } else { instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null); } instance.getCore().setDebugRunning(false); } catch (Exception ex) { instance.getCore().severe(ex.getMessage(), ex); } }); } }, 2000L * amount + 500); } private void gameshieldSelector() { instance.sendMessage(sender, localization.get(locale, "select.gameshield")); List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields(); for (Gameshield gameshield : gameshieldList) { instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgameshield " + gameshield.getId(), "SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId())); } } private void setGameshield(String[] args) { if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1])); return; } Config.setGameShieldID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1])); javaBackendSelector(); } private void javaBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); instance.sendMessage(sender, localization.get(locale, "select.backend", "java")); for (Backend backend : backendList) { if(backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setJavaBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1])); return; } Config.setBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1])); instance.getCore().getRestAPI().testCredentials(); bedrockBackendSelector(); } private void bedrockBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); if(backendList.stream().noneMatch(Backend::isGeyser))return; instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser")); for (Backend backend : backendList) { if(!backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgeyserbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setBedrockBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1])); return; } Config.setGeyserBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1])); if (instance.getCore().getPlayerInSetup().remove(sender)) { instance.sendMessage(sender, localization.get(locale, "setup.finished")); } } private void showHelp() { instance.sendMessage(sender, localization.get(locale, "available.commands")); instance.sendMessage(sender, " - /np setup"); instance.sendMessage(sender, " - /np ipanic"); instance.sendMessage(sender, " - /np analytics"); instance.sendMessage(sender, " - /np toggle (option)"); instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)"); instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)"); instance.sendMessage(sender, " - /np debugTool (cancel / amount)"); instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]"); instance.sendMessage(sender, " - /np setgeyserbackend [id]"); } public static class ExecutorBuilder { private NeoProtectPlugin instance; private Object sender; private String[] args; private Locale local; private String msg; private boolean viaConsole; public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) { this.instance = instance; return this; } public ExecutorBuilder sender(Object sender) { this.sender = sender; return this; } public ExecutorBuilder args(String[] args) { this.args = args; return this; } public ExecutorBuilder local(Locale local) { this.local = local; return this; } public ExecutorBuilder msg(String msg) { this.msg = msg; return this; } public ExecutorBuilder viaConsole(boolean viaConsole) { this.viaConsole = viaConsole; return this; } public void executeChatEvent() { API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this)); } public void executeCommand() { API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this)); } public NeoProtectPlugin getInstance() { return instance; } public Object getSender() { return sender; } public String[] getArgs() { return args; } public Locale getLocal() { return local; } public String getMsg() { return msg; } public boolean isViaConsole() { return viaConsole; } } public static boolean isInteger(String input) { try { Integer.parseInt(input); return true; } catch (NumberFormatException e) { return false; } } }
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
NeoProtect-NeoPlugin-a71f673
[ { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java", "retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +\n \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +", "score": 0.8605660796165466 }, { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java", "retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfig().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +", "score": 0.8500552773475647 }, { "filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java", "retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +", "score": 0.8493595123291016 }, { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java", "retrieved_chunk": " \"§bProxyProtocol§7: \" + Config.isProxyProtocol() + \" \\n\" +\n \"§bNeoProtectPlan§7: \" + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\") + \" \\n\" +\n \"§bSpigotName§7: \" + stats.getServerName() + \" \\n\" +\n \"§bSpigotVersion§7: \" + stats.getServerVersion() + \" \\n\" +\n \"§bSpigotPlugins§7: \" + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray());\n instance.sendMessage(player, \"§bHello \" + player.getName() + \" ;)\", null, null, \"SHOW_TEXT\", infos);\n instance.sendMessage(player, \"§bThis server uses your NeoPlugin\", null, null, \"SHOW_TEXT\", infos);\n }\n }\n}", "score": 0.8461425304412842 }, { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java", "retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"plugin.outdated.message\", result.getCurrentVersion(), result.getLatestVersion()));\n instance.sendMessage(player, MessageFormat.format(\"§7-> §b{0}\",\n result.getReleaseUrl().replace(\"/NeoPlugin\", \"\").replace(\"/releases/tag\", \"\")),\n \"OPEN_URL\", result.getReleaseUrl(), null, null);\n }\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.restart-required.message\", result.getCurrentVersion(), result.getLatestVersion()));\n }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));", "score": 0.840172290802002 } ]
java
instance.sendMessage(sender, " - /np setgameshield [id]");
package de.cubeattack.neoprotect.core.executor; import de.cubeattack.api.API; import de.cubeattack.api.language.Localization; import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration; import de.cubeattack.api.libraries.org.json.JSONObject; import de.cubeattack.neoprotect.core.Config; import de.cubeattack.neoprotect.core.NeoProtectPlugin; import de.cubeattack.neoprotect.core.model.Backend; import de.cubeattack.neoprotect.core.model.Gameshield; import de.cubeattack.neoprotect.core.model.Stats; import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse; import java.io.File; import java.nio.file.Files; import java.sql.Timestamp; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.atomic.AtomicReference; public class NeoProtectExecutor { private static Timer debugTimer = new Timer(); private NeoProtectPlugin instance; private Localization localization; private Object sender; private Locale locale; private String msg; private String[] args; private boolean isViaConsole; private void initials(ExecutorBuilder executeBuilder) { this.instance = executeBuilder.getInstance(); this.localization = instance.getCore().getLocalization(); this.sender = executeBuilder.getSender(); this.locale = executeBuilder.getLocal(); this.args = executeBuilder.getArgs(); this.msg = executeBuilder.getMsg(); this.isViaConsole = executeBuilder.isViaConsole(); } private void chatEvent(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (instance.getCore().getRestAPI().isAPIInvalid(msg)) { instance.sendMessage(sender, localization.get(locale, "apikey.invalid")); return; } Config.setAPIKey(msg); instance.sendMessage(sender, localization.get(locale, "apikey.valid")); gameshieldSelector(); } private void command(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (args.length == 0) { showHelp(); return; } if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) { instance.sendMessage(sender, localization.get(locale, "setup.command.required")); return; } switch (args[0].toLowerCase()) { case "setup": { if (isViaConsole) { instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command")); } else { setup(); } break; } case "ipanic": { iPanic(args); break; } case "directconnectwhitelist": { directConnectWhitelist(args); break; } case "toggle": { toggle(args); break; } case "analytics": { analytics(); break; } case "whitelist": case "blacklist": { firewall(args); break; } case "debugtool": { debugTool(args); break; } case "setgameshield": { if (args.length == 1 && !isViaConsole) { gameshieldSelector(); } else if (args.length == 2) { setGameshield(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgameshield")); } break; } case "setbackend": { if (args.length == 1 && !isViaConsole) { javaBackendSelector(); } else if (args.length == 2) { setJavaBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setbackend")); } break; } case "setgeyserbackend": { if (args.length == 1 && !isViaConsole) { bedrockBackendSelector(); } else if (args.length == 2) { setBedrockBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend")); } break; } default: { showHelp(); } } } private void setup() { instance.getCore().getPlayerInSetup().add(sender); instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"), "OPEN_URL", "https://panel.neoprotect.net/profile", "SHOW_TEXT", localization.get(locale, "apikey.find")); } private void iPanic(String[] args) { if (args.length != 1) { instance.sendMessage(sender, localization.get(locale, "usage.ipanic")); } else { instance.sendMessage(sender, localization.get(locale, "command.ipanic", localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated"))); } } private void directConnectWhitelist(String[] args) { if (args.length == 2) { instance.getCore().getDirectConnectWhitelist().add(args[1]); instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1])); } else { instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist")); } } private void toggle(String[] args) { if (args.length != 2) { instance.sendMessage(sender, localization.get(locale, "usage.toggle")); } else { int response = instance.getCore().getRestAPI().toggle(args[1]); if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } if (response == -1) { instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'"); return; } instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1], localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated"))); } } private void analytics() { instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------"); JSONObject analytics = instance.getCore().getRestAPI().getAnalytics(); instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> { if (ak.equals("bandwidth")) { return; } if (ak.equals("traffic")) { instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " + new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s"); JSONObject traffic = instance.getCore().getRestAPI().getTraffic(); AtomicReference<String> trafficUsed = new AtomicReference<>(); AtomicReference<String> trafficAvailable = new AtomicReference<>(); traffic.keySet().forEach(bk -> { if (bk.equals("used")) { trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb"); } if (bk.equals("available")) { trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb"); } }); instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get()); return; } instance.sendMessage(sender, ak .replace("onlinePlayers", "online players") .replace("cps", "connections/s") + ": " + analytics.get(ak)); }); } private void firewall(String[] args) { if (args.length == 1) { instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----"); instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall -> instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")"))); } else if (args.length == 3) { String ip = args[2]; String action = args[1]; String mode = args[0].toUpperCase(); int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode); if (response == -1) { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); return; } if (response == 0) { instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode)); return; } if (response == 400) { instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip)); return; } if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")"); } else { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); } } @SuppressWarnings("ResultOfMethodCallIgnored") private void debugTool(String[] args) { if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) { instance.sendMessage(sender, localization.get(locale, "debug.spigot")); return; } if (args.length == 2) { if (args[1].equals("cancel")) { debugTimer.cancel(); instance.getCore().setDebugRunning(false); instance.sendMessage(sender, localization.get(locale, "debug.cancelled")); return; } if (!isInteger(args[1])) { instance.sendMessage(sender, localization.get(locale, "usage.debug")); return; } } if (instance.getCore().isDebugRunning()) { instance.sendMessage(sender, localization.get(locale, "debug.running")); return; } instance.getCore().setDebugRunning(true); instance.sendMessage(sender, localization.get(locale, "debug.starting")); int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5; debugTimer = new Timer(); debugTimer.schedule(new TimerTask() { int counter = 0; @Override public void run() { counter++; instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis())); instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")"); if (counter >= amount) this.cancel(); } }, 500, 2000); debugTimer.schedule(new TimerTask() { @Override public void run() { API.getExecutorService().submit(() -> { try { long startTime = System.currentTimeMillis(); Stats stats = instance.getStats(); File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml"); YamlConfiguration configuration = new YamlConfiguration(); if (!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } configuration.load(file); configuration.set("general.osName", System.getProperty("os.name")); configuration.set("general.javaVersion", System.getProperty("java.version")); configuration.set("general.pluginVersion", stats.getPluginVersion()); configuration.set("general.ProxyName", stats.getServerName()); configuration.set("general.ProxyVersion", stats.getServerVersion()); configuration.set("general.ProxyPlugins", instance.getPlugins()); instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> { List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName); long maxPlayerToProxyLatenz = 0; long maxNeoToProxyLatenz = 0; long maxProxyToBackendLatenz = 0; long maxPlayerToNeoLatenz = 0; long avgPlayerToProxyLatenz = 0; long avgNeoToProxyLatenz = 0; long avgProxyToBackendLatenz = 0; long avgPlayerToNeoLatenz = 0; long minPlayerToProxyLatenz = Long.MAX_VALUE; long minNeoToProxyLatenz = Long.MAX_VALUE; long minProxyToBackendLatenz = Long.MAX_VALUE; long minPlayerToNeoLatenz = Long.MAX_VALUE; configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress()); configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress()); for (DebugPingResponse response : list) { if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz()) maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz()) maxNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz()) maxProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz()) maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz(); avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz(); avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz(); avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz(); if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz()) minPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (minNeoToProxyLatenz > response.getNeoToProxyLatenz()) minNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (minProxyToBackendLatenz > response.getProxyToBackendLatenz()) minProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz()) minPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); } configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz); configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size()); configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz); })); configuration.save(file); final String content = new String(Files.readAllBytes(file.toPath())); final String pasteKey = instance.getCore().getRestAPI().paste(content); instance.getCore().getDebugPingResponses().clear(); instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)"); if(pasteKey != null) { final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml"; instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null); } else { instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null); } instance.getCore().setDebugRunning(false); } catch (Exception ex) { instance.getCore().severe(ex.getMessage(), ex); } }); } }, 2000L * amount + 500); } private void gameshieldSelector() { instance.sendMessage(sender, localization.get(locale, "select.gameshield")); List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields(); for (Gameshield gameshield : gameshieldList) { instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgameshield " + gameshield.getId(), "SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId())); } } private void setGameshield(String[] args) { if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1])); return; } Config.setGameShieldID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1])); javaBackendSelector(); } private void javaBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); instance.sendMessage(sender, localization.get(locale, "select.backend", "java")); for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setJavaBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1])); return; } Config.setBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1])); instance.getCore().getRestAPI().testCredentials(); bedrockBackendSelector(); } private void bedrockBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); if(backendList.stream().noneMatch(Backend::isGeyser))return; instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser")); for (Backend backend : backendList) { if(!backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgeyserbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setBedrockBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1])); return; } Config.setGeyserBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1])); if (instance.getCore().getPlayerInSetup().remove(sender)) { instance.sendMessage(sender, localization.get(locale, "setup.finished")); } } private void showHelp() { instance.sendMessage(sender, localization.get(locale, "available.commands")); instance.sendMessage(sender, " - /np setup"); instance.sendMessage(sender, " - /np ipanic"); instance.sendMessage(sender, " - /np analytics"); instance.sendMessage(sender, " - /np toggle (option)"); instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)"); instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)"); instance.sendMessage(sender, " - /np debugTool (cancel / amount)"); instance.sendMessage(sender, " - /np directConnectWhitelist (ip)"); instance.sendMessage(sender, " - /np setgameshield [id]"); instance.sendMessage(sender, " - /np setbackend [id]"); instance.sendMessage(sender, " - /np setgeyserbackend [id]"); } public static class ExecutorBuilder { private NeoProtectPlugin instance; private Object sender; private String[] args; private Locale local; private String msg; private boolean viaConsole; public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) { this.instance = instance; return this; } public ExecutorBuilder sender(Object sender) { this.sender = sender; return this; } public ExecutorBuilder args(String[] args) { this.args = args; return this; } public ExecutorBuilder local(Locale local) { this.local = local; return this; } public ExecutorBuilder msg(String msg) { this.msg = msg; return this; } public ExecutorBuilder viaConsole(boolean viaConsole) { this.viaConsole = viaConsole; return this; } public void executeChatEvent() { API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this)); } public void executeCommand() { API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this)); } public NeoProtectPlugin getInstance() { return instance; } public Object getSender() { return sender; } public String[] getArgs() { return args; } public Locale getLocal() { return local; } public String getMsg() { return msg; } public boolean isViaConsole() { return viaConsole; } } public static boolean isInteger(String input) { try { Integer.parseInt(input); return true; } catch (NumberFormatException e) { return false; } } }
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
NeoProtect-NeoPlugin-a71f673
[ { "filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java", "retrieved_chunk": " core.severe(\"Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield\");\n setup = false;\n return;\n } else if (isBackendInvalid(Config.getBackendID())) {\n core.severe(\"Backend is not valid! Please run /neoprotect setbackend to set the backend\");\n setup = false;\n return;\n }\n this.setup = true;\n setProxyProtocol(Config.isProxyProtocol());", "score": 0.8546241521835327 }, { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java", "retrieved_chunk": " }\n }\n if (args.length <= 1) {\n list.add(\"setup\");\n if (instance.getCore().isSetup()) {\n list.add(\"directConnectWhitelist\");\n list.add(\"setgameshield\");\n list.add(\"setbackend\");\n list.add(\"analytics\");\n list.add(\"debugTool\");", "score": 0.8461856245994568 }, { "filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java", "retrieved_chunk": " debugMode = config.getBoolean(\"DebugMode\", false);\n geyserServerIP = config.getString(\"geyserServerIP\", \"127.0.0.1\");\n if (APIKey.length() != 64) {\n core.severe(\"Failed to load API-Key. Key is null or not valid\");\n return;\n }\n if (gameShieldID.isEmpty()) {\n core.severe(\"Failed to load GameshieldID. ID is null\");\n return;\n }", "score": 0.8403074145317078 }, { "filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java", "retrieved_chunk": " private static boolean proxyProtocol;\n private static String gameShieldID;\n private static String backendID;\n private static String geyserBackendID;\n private static boolean updateIP;\n private static boolean debugMode;\n private static String geyserServerIP;\n private static String updateSetting;\n private static Core core;\n private static FileUtils fileUtils;", "score": 0.8307032585144043 }, { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/command/NeoProtectTabCompleter.java", "retrieved_chunk": " completorList.add(\"remove\");\n }\n if (args.length != 1) {\n return completorList;\n }\n list.add(\"setup\");\n if (instance.getCore().isSetup()) {\n list.add(\"directConnectWhitelist\");\n list.add(\"setgameshield\");\n list.add(\"setbackend\");", "score": 0.8250045776367188 } ]
java
if(backend.isGeyser())continue;
package de.cubeattack.neoprotect.core.executor; import de.cubeattack.api.API; import de.cubeattack.api.language.Localization; import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration; import de.cubeattack.api.libraries.org.json.JSONObject; import de.cubeattack.neoprotect.core.Config; import de.cubeattack.neoprotect.core.NeoProtectPlugin; import de.cubeattack.neoprotect.core.model.Backend; import de.cubeattack.neoprotect.core.model.Gameshield; import de.cubeattack.neoprotect.core.model.Stats; import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse; import java.io.File; import java.nio.file.Files; import java.sql.Timestamp; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.atomic.AtomicReference; public class NeoProtectExecutor { private static Timer debugTimer = new Timer(); private NeoProtectPlugin instance; private Localization localization; private Object sender; private Locale locale; private String msg; private String[] args; private boolean isViaConsole; private void initials(ExecutorBuilder executeBuilder) { this.instance = executeBuilder.getInstance(); this.localization = instance.getCore().getLocalization(); this.sender = executeBuilder.getSender(); this.locale = executeBuilder.getLocal(); this.args = executeBuilder.getArgs(); this.msg = executeBuilder.getMsg(); this.isViaConsole = executeBuilder.isViaConsole(); } private void chatEvent(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (instance.getCore().getRestAPI().isAPIInvalid(msg)) { instance.sendMessage(sender, localization.get(locale, "apikey.invalid")); return; } Config.setAPIKey(msg); instance.sendMessage(sender, localization.get(locale, "apikey.valid")); gameshieldSelector(); } private void command(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (args.length == 0) { showHelp(); return; } if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) { instance.sendMessage(sender, localization.get(locale, "setup.command.required")); return; } switch (args[0].toLowerCase()) { case "setup": { if (isViaConsole) { instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command")); } else { setup(); } break; } case "ipanic": { iPanic(args); break; } case "directconnectwhitelist": { directConnectWhitelist(args); break; } case "toggle": { toggle(args); break; } case "analytics": { analytics(); break; } case "whitelist": case "blacklist": { firewall(args); break; } case "debugtool": { debugTool(args); break; } case "setgameshield": { if (args.length == 1 && !isViaConsole) { gameshieldSelector(); } else if (args.length == 2) { setGameshield(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgameshield")); } break; } case "setbackend": { if (args.length == 1 && !isViaConsole) { javaBackendSelector(); } else if (args.length == 2) { setJavaBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setbackend")); } break; } case "setgeyserbackend": { if (args.length == 1 && !isViaConsole) { bedrockBackendSelector(); } else if (args.length == 2) { setBedrockBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend")); } break; } default: { showHelp(); } } } private void setup() { instance.getCore().getPlayerInSetup().add(sender); instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"), "OPEN_URL", "https://panel.neoprotect.net/profile", "SHOW_TEXT", localization.get(locale, "apikey.find")); } private void iPanic(String[] args) { if (args.length != 1) { instance.sendMessage(sender, localization.get(locale, "usage.ipanic")); } else { instance.sendMessage(sender, localization.get(locale, "command.ipanic", localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated"))); } } private void directConnectWhitelist(String[] args) { if (args.length == 2) { instance.getCore().getDirectConnectWhitelist().add(args[1]); instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1])); } else { instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist")); } } private void toggle(String[] args) { if (args.length != 2) { instance.sendMessage(sender, localization.get(locale, "usage.toggle")); } else { int response = instance.getCore().getRestAPI().toggle(args[1]); if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } if (response == -1) { instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'"); return; } instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1], localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated"))); } } private void analytics() { instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------"); JSONObject analytics = instance.getCore().getRestAPI().getAnalytics(); instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> { if (ak.equals("bandwidth")) { return; } if (ak.equals("traffic")) { instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " + new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s"); JSONObject traffic = instance.getCore().getRestAPI().getTraffic(); AtomicReference<String> trafficUsed = new AtomicReference<>(); AtomicReference<String> trafficAvailable = new AtomicReference<>(); traffic.keySet().forEach(bk -> { if (bk.equals("used")) { trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb"); } if (bk.equals("available")) { trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb"); } }); instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get()); return; } instance.sendMessage(sender, ak .replace("onlinePlayers", "online players") .replace("cps", "connections/s") + ": " + analytics.get(ak)); }); } private void firewall(String[] args) { if (args.length == 1) { instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----"); instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall -> instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")"))); } else if (args.length == 3) { String ip = args[2]; String action = args[1]; String mode = args[0].toUpperCase(); int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode); if (response == -1) { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); return; } if (response == 0) { instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode)); return; } if (response == 400) { instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip)); return; } if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")"); } else { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); } } @SuppressWarnings("ResultOfMethodCallIgnored") private void debugTool(String[] args) { if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) { instance.sendMessage(sender, localization.get(locale, "debug.spigot")); return; } if (args.length == 2) { if (args[1].equals("cancel")) { debugTimer.cancel(); instance.getCore().setDebugRunning(false); instance.sendMessage(sender, localization.get(locale, "debug.cancelled")); return; } if (!isInteger(args[1])) { instance.sendMessage(sender, localization.get(locale, "usage.debug")); return; } } if (instance.getCore().isDebugRunning()) { instance.sendMessage(sender, localization.get(locale, "debug.running")); return; } instance.getCore().setDebugRunning(true); instance.sendMessage(sender, localization.get(locale, "debug.starting")); int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5; debugTimer = new Timer(); debugTimer.schedule(new TimerTask() { int counter = 0; @Override public void run() { counter++; instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis())); instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")"); if (counter >= amount) this.cancel(); } }, 500, 2000); debugTimer.schedule(new TimerTask() { @Override public void run() { API.getExecutorService().submit(() -> { try { long startTime = System.currentTimeMillis(); Stats stats = instance.getStats(); File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml"); YamlConfiguration configuration = new YamlConfiguration(); if (!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } configuration.load(file); configuration.set("general.osName", System.getProperty("os.name")); configuration.set("general.javaVersion", System.getProperty("java.version")); configuration.set("general.pluginVersion", stats.getPluginVersion()); configuration.set("general.ProxyName", stats.getServerName()); configuration.set("general.ProxyVersion", stats.getServerVersion()); configuration.set("general.ProxyPlugins", instance.getPlugins()); instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> { List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName); long maxPlayerToProxyLatenz = 0; long maxNeoToProxyLatenz = 0; long maxProxyToBackendLatenz = 0; long maxPlayerToNeoLatenz = 0; long avgPlayerToProxyLatenz = 0; long avgNeoToProxyLatenz = 0; long avgProxyToBackendLatenz = 0; long avgPlayerToNeoLatenz = 0; long minPlayerToProxyLatenz = Long.MAX_VALUE; long minNeoToProxyLatenz = Long.MAX_VALUE; long minProxyToBackendLatenz = Long.MAX_VALUE; long minPlayerToNeoLatenz = Long.MAX_VALUE; configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress()); configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress()); for (DebugPingResponse response : list) { if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz()) maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz()) maxNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz()) maxProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz()) maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz(); avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz(); avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz(); avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz(); if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz()) minPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (minNeoToProxyLatenz > response.getNeoToProxyLatenz()) minNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (minProxyToBackendLatenz > response.getProxyToBackendLatenz()) minProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz()) minPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); } configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz); configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size()); configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz); })); configuration.save(file); final String content = new String(Files.readAllBytes(file.toPath())); final String pasteKey = instance.getCore().getRestAPI().paste(content); instance.getCore().getDebugPingResponses().clear(); instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)"); if(pasteKey != null) { final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml"; instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null); } else { instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null); } instance.getCore().setDebugRunning(false); } catch (Exception ex) { instance.getCore().severe(ex.getMessage(), ex); } }); } }, 2000L * amount + 500); } private void gameshieldSelector() { instance.sendMessage(sender, localization.get(locale, "select.gameshield")); List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields(); for (Gameshield gameshield : gameshieldList) { instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgameshield " + gameshield.getId(), "SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId())); } } private void setGameshield(String[] args) { if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1])); return; } Config.setGameShieldID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1])); javaBackendSelector(); } private void javaBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); instance.sendMessage(sender, localization.get(locale, "select.backend", "java")); for (Backend backend : backendList) { if(backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setbackend " + backend.getId(), "SHOW_TEXT", localization
.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
} } private void setJavaBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1])); return; } Config.setBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1])); instance.getCore().getRestAPI().testCredentials(); bedrockBackendSelector(); } private void bedrockBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); if(backendList.stream().noneMatch(Backend::isGeyser))return; instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser")); for (Backend backend : backendList) { if(!backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgeyserbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setBedrockBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1])); return; } Config.setGeyserBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1])); if (instance.getCore().getPlayerInSetup().remove(sender)) { instance.sendMessage(sender, localization.get(locale, "setup.finished")); } } private void showHelp() { instance.sendMessage(sender, localization.get(locale, "available.commands")); instance.sendMessage(sender, " - /np setup"); instance.sendMessage(sender, " - /np ipanic"); instance.sendMessage(sender, " - /np analytics"); instance.sendMessage(sender, " - /np toggle (option)"); instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)"); instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)"); instance.sendMessage(sender, " - /np debugTool (cancel / amount)"); instance.sendMessage(sender, " - /np directConnectWhitelist (ip)"); instance.sendMessage(sender, " - /np setgameshield [id]"); instance.sendMessage(sender, " - /np setbackend [id]"); instance.sendMessage(sender, " - /np setgeyserbackend [id]"); } public static class ExecutorBuilder { private NeoProtectPlugin instance; private Object sender; private String[] args; private Locale local; private String msg; private boolean viaConsole; public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) { this.instance = instance; return this; } public ExecutorBuilder sender(Object sender) { this.sender = sender; return this; } public ExecutorBuilder args(String[] args) { this.args = args; return this; } public ExecutorBuilder local(Locale local) { this.local = local; return this; } public ExecutorBuilder msg(String msg) { this.msg = msg; return this; } public ExecutorBuilder viaConsole(boolean viaConsole) { this.viaConsole = viaConsole; return this; } public void executeChatEvent() { API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this)); } public void executeCommand() { API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this)); } public NeoProtectPlugin getInstance() { return instance; } public Object getSender() { return sender; } public String[] getArgs() { return args; } public Locale getLocal() { return local; } public String getMsg() { return msg; } public boolean isViaConsole() { return viaConsole; } } public static boolean isInteger(String input) { try { Integer.parseInt(input); return true; } catch (NumberFormatException e) { return false; } } }
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
NeoProtect-NeoPlugin-a71f673
[ { "filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java", "retrieved_chunk": " private void backendServerIPUpdater() {\n core.info(\"BackendServerIPUpdate scheduler started\");\n new Timer().schedule(new TimerTask() {\n @Override\n public void run() {\n if (!setup) return;\n Backend javaBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getBackendID())).findAny().orElse(null);\n Backend geyserBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getGeyserBackendID())).findAny().orElse(null);\n String ip = getIpv4();\n if (ip == null) return;", "score": 0.8315305709838867 }, { "filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java", "retrieved_chunk": " }\n if (geyserBackend != null) {\n if (!ip.equals(geyserBackend.getIp())) {\n RequestBody requestBody = RequestBody.create(MediaType.parse(\"application/json\"), new JsonBuilder().appendField(\"ipv4\", ip).build().toString());\n if (!updateBackend(requestBody, Config.getGeyserBackendID())) {\n core.warn(\"Update geyser backendserver ID '\" + Config.getGeyserBackendID() + \"' to IP '\" + ip + \"' failed\");\n } else {\n core.info(\"Update geyser backendserver ID '\" + Config.getGeyserBackendID() + \"' to IP '\" + ip + \"' success\");\n geyserBackend.setIp(ip);\n }", "score": 0.8240005970001221 }, { "filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java", "retrieved_chunk": " if (javaBackend != null) {\n if (!ip.equals(javaBackend.getIp())) {\n RequestBody requestBody = RequestBody.create(MediaType.parse(\"application/json\"), new JsonBuilder().appendField(\"ipv4\", ip).build().toString());\n if (!updateBackend(requestBody, Config.getBackendID())) {\n core.warn(\"Update java backendserver ID '\" + Config.getBackendID() + \"' to IP '\" + ip + \"' failed\");\n } else {\n core.info(\"Update java backendserver ID '\" + Config.getBackendID() + \"' to IP '\" + ip + \"' success\");\n javaBackend.setIp(ip);\n }\n }", "score": 0.8150277137756348 }, { "filename": "src/main/java/de/cubeattack/neoprotect/core/model/Backend.java", "retrieved_chunk": "package de.cubeattack.neoprotect.core.model;\npublic class Backend {\n private final String id;\n private String ip;\n private final String port;\n private final boolean geyser;\n public Backend(String id, String ip, String port, boolean geyser) {\n this.id = id;\n this.ip = ip;\n this.port = port;", "score": 0.8143039345741272 }, { "filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java", "retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +", "score": 0.8029499053955078 } ]
java
.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
package de.cubeattack.neoprotect.core.executor; import de.cubeattack.api.API; import de.cubeattack.api.language.Localization; import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration; import de.cubeattack.api.libraries.org.json.JSONObject; import de.cubeattack.neoprotect.core.Config; import de.cubeattack.neoprotect.core.NeoProtectPlugin; import de.cubeattack.neoprotect.core.model.Backend; import de.cubeattack.neoprotect.core.model.Gameshield; import de.cubeattack.neoprotect.core.model.Stats; import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse; import java.io.File; import java.nio.file.Files; import java.sql.Timestamp; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.atomic.AtomicReference; public class NeoProtectExecutor { private static Timer debugTimer = new Timer(); private NeoProtectPlugin instance; private Localization localization; private Object sender; private Locale locale; private String msg; private String[] args; private boolean isViaConsole; private void initials(ExecutorBuilder executeBuilder) { this.instance = executeBuilder.getInstance(); this.localization = instance.getCore().getLocalization(); this.sender = executeBuilder.getSender(); this.locale = executeBuilder.getLocal(); this.args = executeBuilder.getArgs(); this.msg = executeBuilder.getMsg(); this.isViaConsole = executeBuilder.isViaConsole(); } private void chatEvent(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (instance.getCore().getRestAPI().isAPIInvalid(msg)) { instance.sendMessage(sender, localization.get(locale, "apikey.invalid")); return; } Config.setAPIKey(msg); instance.sendMessage(sender, localization.get(locale, "apikey.valid")); gameshieldSelector(); } private void command(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (args.length == 0) { showHelp(); return; } if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) { instance.sendMessage(sender, localization.get(locale, "setup.command.required")); return; } switch (args[0].toLowerCase()) { case "setup": { if (isViaConsole) { instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command")); } else { setup(); } break; } case "ipanic": { iPanic(args); break; } case "directconnectwhitelist": { directConnectWhitelist(args); break; } case "toggle": { toggle(args); break; } case "analytics": { analytics(); break; } case "whitelist": case "blacklist": { firewall(args); break; } case "debugtool": { debugTool(args); break; } case "setgameshield": { if (args.length == 1 && !isViaConsole) { gameshieldSelector(); } else if (args.length == 2) { setGameshield(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgameshield")); } break; } case "setbackend": { if (args.length == 1 && !isViaConsole) { javaBackendSelector(); } else if (args.length == 2) { setJavaBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setbackend")); } break; } case "setgeyserbackend": { if (args.length == 1 && !isViaConsole) { bedrockBackendSelector(); } else if (args.length == 2) { setBedrockBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend")); } break; } default: { showHelp(); } } } private void setup() { instance.getCore().getPlayerInSetup().add(sender); instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"), "OPEN_URL", "https://panel.neoprotect.net/profile", "SHOW_TEXT", localization.get(locale, "apikey.find")); } private void iPanic(String[] args) { if (args.length != 1) { instance.sendMessage(sender, localization.get(locale, "usage.ipanic")); } else { instance.sendMessage(sender, localization.get(locale, "command.ipanic", localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated"))); } } private void directConnectWhitelist(String[] args) { if (args.length == 2) { instance.getCore().getDirectConnectWhitelist().add(args[1]); instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1])); } else { instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist")); } } private void toggle(String[] args) { if (args.length != 2) { instance.sendMessage(sender, localization.get(locale, "usage.toggle")); } else { int response = instance.getCore().getRestAPI().toggle(args[1]); if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } if (response == -1) { instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'"); return; } instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1], localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated"))); } } private void analytics() { instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------"); JSONObject analytics = instance.getCore().getRestAPI().getAnalytics(); instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> { if (ak.equals("bandwidth")) { return; } if (ak.equals("traffic")) { instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " + new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s"); JSONObject traffic = instance.getCore().getRestAPI().getTraffic(); AtomicReference<String> trafficUsed = new AtomicReference<>(); AtomicReference<String> trafficAvailable = new AtomicReference<>(); traffic.keySet().forEach(bk -> { if (bk.equals("used")) { trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb"); } if (bk.equals("available")) { trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb"); } }); instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get()); return; } instance.sendMessage(sender, ak .replace("onlinePlayers", "online players") .replace("cps", "connections/s") + ": " + analytics.get(ak)); }); } private void firewall(String[] args) { if (args.length == 1) { instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----"); instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall -> instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")"))); } else if (args.length == 3) { String ip = args[2]; String action = args[1]; String mode = args[0].toUpperCase(); int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode); if (response == -1) { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); return; } if (response == 0) { instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode)); return; } if (response == 400) { instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip)); return; } if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")"); } else { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); } } @SuppressWarnings("ResultOfMethodCallIgnored") private void debugTool(String[] args) { if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) { instance.sendMessage(sender, localization.get(locale, "debug.spigot")); return; } if (args.length == 2) { if (args[1].equals("cancel")) { debugTimer.cancel(); instance.getCore().setDebugRunning(false); instance.sendMessage(sender, localization.get(locale, "debug.cancelled")); return; } if (!isInteger(args[1])) { instance.sendMessage(sender, localization.get(locale, "usage.debug")); return; } } if (instance.getCore().isDebugRunning()) { instance.sendMessage(sender, localization.get(locale, "debug.running")); return; } instance.getCore().setDebugRunning(true); instance.sendMessage(sender, localization.get(locale, "debug.starting")); int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5; debugTimer = new Timer(); debugTimer.schedule(new TimerTask() { int counter = 0; @Override public void run() { counter++; instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis())); instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")"); if (counter >= amount) this.cancel(); } }, 500, 2000); debugTimer.schedule(new TimerTask() { @Override public void run() { API.getExecutorService().submit(() -> { try { long startTime = System.currentTimeMillis(); Stats stats = instance.getStats(); File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml"); YamlConfiguration configuration = new YamlConfiguration(); if (!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } configuration.load(file); configuration.set("general.osName", System.getProperty("os.name")); configuration.set("general.javaVersion", System.getProperty("java.version")); configuration.set("general.pluginVersion", stats.getPluginVersion()); configuration.set("general.ProxyName", stats.getServerName()); configuration.set("general.ProxyVersion", stats.getServerVersion()); configuration.set("general.ProxyPlugins", instance.getPlugins()); instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> { List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName); long maxPlayerToProxyLatenz = 0; long maxNeoToProxyLatenz = 0; long maxProxyToBackendLatenz = 0; long maxPlayerToNeoLatenz = 0; long avgPlayerToProxyLatenz = 0; long avgNeoToProxyLatenz = 0; long avgProxyToBackendLatenz = 0; long avgPlayerToNeoLatenz = 0; long minPlayerToProxyLatenz = Long.MAX_VALUE; long minNeoToProxyLatenz = Long.MAX_VALUE; long minProxyToBackendLatenz = Long.MAX_VALUE; long minPlayerToNeoLatenz = Long.MAX_VALUE; configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress()); configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress()); for (DebugPingResponse response : list) { if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz()) maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz()) maxNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz()) maxProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz()) maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz(); avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz(); avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz(); avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz(); if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz()) minPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (minNeoToProxyLatenz > response.getNeoToProxyLatenz()) minNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (minProxyToBackendLatenz > response.getProxyToBackendLatenz()) minProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz()) minPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); } configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz); configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size()); configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz); })); configuration.save(file); final String content = new String(Files.readAllBytes(file.toPath())); final String pasteKey = instance.getCore().getRestAPI().paste(content); instance.getCore().getDebugPingResponses().clear(); instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)"); if(pasteKey != null) { final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml"; instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null); } else { instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null); } instance.getCore().setDebugRunning(false); } catch (Exception ex) { instance.getCore().severe(ex.getMessage(), ex); } }); } }, 2000L * amount + 500); } private void gameshieldSelector() { instance.sendMessage(sender, localization.get(locale, "select.gameshield")); List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields(); for (Gameshield gameshield : gameshieldList) { instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgameshield " + gameshield.getId(), "SHOW_TEXT", localization.get(locale, "hover.gameshield",
gameshield.getName(), gameshield.getId()));
} } private void setGameshield(String[] args) { if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1])); return; } Config.setGameShieldID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1])); javaBackendSelector(); } private void javaBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); instance.sendMessage(sender, localization.get(locale, "select.backend", "java")); for (Backend backend : backendList) { if(backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setJavaBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1])); return; } Config.setBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1])); instance.getCore().getRestAPI().testCredentials(); bedrockBackendSelector(); } private void bedrockBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); if(backendList.stream().noneMatch(Backend::isGeyser))return; instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser")); for (Backend backend : backendList) { if(!backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgeyserbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setBedrockBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1])); return; } Config.setGeyserBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1])); if (instance.getCore().getPlayerInSetup().remove(sender)) { instance.sendMessage(sender, localization.get(locale, "setup.finished")); } } private void showHelp() { instance.sendMessage(sender, localization.get(locale, "available.commands")); instance.sendMessage(sender, " - /np setup"); instance.sendMessage(sender, " - /np ipanic"); instance.sendMessage(sender, " - /np analytics"); instance.sendMessage(sender, " - /np toggle (option)"); instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)"); instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)"); instance.sendMessage(sender, " - /np debugTool (cancel / amount)"); instance.sendMessage(sender, " - /np directConnectWhitelist (ip)"); instance.sendMessage(sender, " - /np setgameshield [id]"); instance.sendMessage(sender, " - /np setbackend [id]"); instance.sendMessage(sender, " - /np setgeyserbackend [id]"); } public static class ExecutorBuilder { private NeoProtectPlugin instance; private Object sender; private String[] args; private Locale local; private String msg; private boolean viaConsole; public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) { this.instance = instance; return this; } public ExecutorBuilder sender(Object sender) { this.sender = sender; return this; } public ExecutorBuilder args(String[] args) { this.args = args; return this; } public ExecutorBuilder local(Locale local) { this.local = local; return this; } public ExecutorBuilder msg(String msg) { this.msg = msg; return this; } public ExecutorBuilder viaConsole(boolean viaConsole) { this.viaConsole = viaConsole; return this; } public void executeChatEvent() { API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this)); } public void executeCommand() { API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this)); } public NeoProtectPlugin getInstance() { return instance; } public Object getSender() { return sender; } public String[] getArgs() { return args; } public Locale getLocal() { return local; } public String getMsg() { return msg; } public boolean isViaConsole() { return viaConsole; } } public static boolean isInteger(String input) { try { Integer.parseInt(input); return true; } catch (NumberFormatException e) { return false; } } }
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
NeoProtect-NeoPlugin-a71f673
[ { "filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java", "retrieved_chunk": " return;\n }\n if (!attackRunning[0]) {\n core.warn(\"Gameshield ID '\" + Config.getGameShieldID() + \"' is under attack\");\n core.getPlugin().sendAdminMessage(Permission.NOTIFY, \"Gameshield ID '\" + Config.getGameShieldID() + \"' is under attack\", null, null, null, null);\n attackRunning[0] = true;\n }\n }\n }, 1000 * 5, 1000 * 10);\n }", "score": 0.8437252044677734 }, { "filename": "src/main/java/de/cubeattack/neoprotect/core/model/Gameshield.java", "retrieved_chunk": "package de.cubeattack.neoprotect.core.model;\npublic class Gameshield {\n private final String id;\n private final String name;\n public Gameshield(String id, String name) {\n this.id = id;\n this.name = name;\n }\n public String getId() {\n return id;", "score": 0.8067853450775146 }, { "filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java", "retrieved_chunk": " }\n }\n }, 500);\n }\n}", "score": 0.7905603051185608 }, { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java", "retrieved_chunk": " }\n }\n }, 500);\n }\n}", "score": 0.7905603051185608 }, { "filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java", "retrieved_chunk": " JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject(\"gameShieldSettings\");\n String mitigationSensitivity = settings.getString(\"mitigationSensitivity\");\n if (mitigationSensitivity.equals(\"UNDER_ATTACK\")) {\n rest.request(RequestType.POST_GAMESHIELD_UPDATE,\n RequestBody.create(MediaType.parse(\"application/json\"), settings.put(\"mitigationSensitivity\", \"MEDIUM\").toString()),\n Config.getGameShieldID());\n return false;\n } else {\n rest.request(RequestType.POST_GAMESHIELD_UPDATE,\n RequestBody.create(MediaType.parse(\"application/json\"), settings.put(\"mitigationSensitivity\", \"UNDER_ATTACK\").toString()),", "score": 0.784733235836029 } ]
java
gameshield.getName(), gameshield.getId()));
package de.cubeattack.neoprotect.velocity; import com.google.inject.Inject; import com.velocitypowered.api.command.CommandSource; import com.velocitypowered.api.event.Subscribe; import com.velocitypowered.api.event.proxy.ProxyInitializeEvent; import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.ProxyServer; import com.velocitypowered.proxy.connection.client.ConnectedPlayer; import com.velocitypowered.proxy.protocol.packet.KeepAlive; import de.cubeattack.neoprotect.core.Config; import de.cubeattack.neoprotect.core.Core; import de.cubeattack.neoprotect.core.NeoProtectPlugin; import de.cubeattack.neoprotect.core.Permission; import de.cubeattack.neoprotect.core.model.Stats; import de.cubeattack.neoprotect.core.model.debugtool.KeepAliveResponseKey; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TextComponent; import net.kyori.adventure.text.event.ClickEvent; import net.kyori.adventure.text.event.HoverEvent; import org.bstats.charts.SimplePie; import org.bstats.velocity.Metrics; import java.util.ArrayList; import java.util.Arrays; import java.util.Objects; import java.util.logging.Logger; public class NeoProtectVelocity implements NeoProtectPlugin { private final Metrics.Factory metricsFactory; private final Logger logger; private final ProxyServer proxy; private Core core; @Inject public NeoProtectVelocity(ProxyServer proxy, Logger logger, Metrics.Factory metricsFactory) { this.proxy = proxy; this.logger = logger; this.metricsFactory = metricsFactory; } @Subscribe public void onProxyInitialize(ProxyInitializeEvent event) { Metrics metrics = metricsFactory.make(this, 18727); metrics.addCustomChart(new SimplePie("language", Config::getLanguage)); core = new Core(this); new Startup(this); } public Core getCore() { return core; } @Override public Stats getStats() { return new Stats( getPluginType(), getProxy().getVersion().getVersion(), getProxy().getVersion().getName(), System.getProperty("java.version"), System.getProperty("os.name"), System.getProperty("os.arch"), System.getProperty("os.version"), getPluginVersion(), getCore().getVersionResult().getVersionStatus().toString(), Config.getAutoUpdaterSettings().toString(), getCore().isSetup() ? getCore().getRestAPI().getPlan() : "§cNOT CONNECTED", Arrays.toString(getPlugins().stream().filter(p -> !p.startsWith("cmd_") && !p.equals("reconnect_yaml")).toArray()), getProxy().getPlayerCount(), getProxy().getAllServers().size(), Runtime.getRuntime().availableProcessors(), getProxy().getConfiguration().isOnlineMode(), Config.isProxyProtocol() ); } public ProxyServer getProxy() { return proxy; } @Override public void sendMessage(Object receiver, String text) { sendMessage(receiver, text, null, null, null, null); } @Override @SuppressWarnings("unchecked") public void sendMessage(Object receiver, String text, String clickAction, String clickMsg, String hoverAction, String hoverMsg) { TextComponent msg =
Component.text(core.getPrefix() + text);
if (clickAction != null) msg = msg.clickEvent(ClickEvent.clickEvent(ClickEvent.Action.valueOf(clickAction), clickMsg)); if (hoverAction != null) msg = msg.hoverEvent(HoverEvent.hoverEvent((HoverEvent.Action<Object>) Objects.requireNonNull(HoverEvent.Action.NAMES.value(hoverAction.toLowerCase())), Component.text(hoverMsg))); if (receiver instanceof CommandSource) ((CommandSource) receiver).sendMessage(msg); } @Override public void sendAdminMessage(Permission permission, String text, String clickAction, String clickMsg, String hoverAction, String hoverMsg) { getProxy().getAllPlayers().forEach(receiver -> { if (receiver.hasPermission("neoprotect.admin") || receiver.hasPermission(permission.value)) sendMessage(receiver, text, clickAction, clickMsg, hoverAction, hoverMsg); }); } @Override public void sendKeepAliveMessage(Object receiver, long id) { if (receiver instanceof Player) { KeepAlive keepAlive = new KeepAlive(); keepAlive.setRandomId(id); ((ConnectedPlayer) receiver).getConnection().getChannel().writeAndFlush(keepAlive); getCore().getPingMap().put(new KeepAliveResponseKey(((Player) receiver).getRemoteAddress(), id), System.currentTimeMillis()); } } @Override public long sendKeepAliveMessage(long id) { for (Player player : this.proxy.getAllPlayers()) { sendKeepAliveMessage(player, id); } return id; } @Override public Logger getLogger() { return logger; } @Override public ArrayList<String> getPlugins() { ArrayList<String> plugins = new ArrayList<>(); getProxy().getPluginManager().getPlugins().forEach(p -> plugins.add(p.getDescription().getName().orElseThrow(null))); return plugins; } @Override public PluginType getPluginType() { return PluginType.VELOCITY; } @Override public String getPluginVersion() { return proxy.getPluginManager().ensurePluginContainer(this).getDescription().getVersion().orElse(""); } }
src/main/java/de/cubeattack/neoprotect/velocity/NeoProtectVelocity.java
NeoProtect-NeoPlugin-a71f673
[ { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/NeoProtectBungee.java", "retrieved_chunk": " }\n @Override\n public void sendMessage(Object receiver, String text, String clickAction, String clickMsg, String hoverAction, String hoverMsg) {\n TextComponent msg = new TextComponent(core.getPrefix() + text);\n if (clickAction != null)\n msg.setClickEvent(new ClickEvent(ClickEvent.Action.valueOf(clickAction), clickMsg));\n if (hoverAction != null)\n msg.setHoverEvent(new HoverEvent(HoverEvent.Action.valueOf(hoverAction), Collections.singletonList(new Text(hoverMsg))));\n if (receiver instanceof CommandSender) ((CommandSender) receiver).sendMessage(msg);\n }", "score": 0.9749853610992432 }, { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/NeoProtectSpigot.java", "retrieved_chunk": " public void sendMessage(Object receiver, String text, String clickAction, String clickMsg, String hoverAction, String hoverMsg) {\n TextComponent msg = new TextComponent(core.getPrefix() + text);\n if (clickAction != null)\n msg.setClickEvent(new ClickEvent(ClickEvent.Action.valueOf(clickAction), clickMsg));\n if (hoverAction != null)\n msg.setHoverEvent(new HoverEvent(HoverEvent.Action.valueOf(hoverAction), new ComponentBuilder(hoverMsg).create()));\n if (receiver instanceof ConsoleCommandSender) ((ConsoleCommandSender) receiver).sendMessage(msg.toLegacyText());\n if (receiver instanceof Player) ((Player) receiver).spigot().sendMessage(msg);\n }\n @Override", "score": 0.9639136791229248 }, { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/NeoProtectBungee.java", "retrieved_chunk": " getProxy().getOnlineCount(),\n getProxy().getServers().size(),\n Runtime.getRuntime().availableProcessors(),\n getProxy().getConfig().isOnlineMode(),\n Config.isProxyProtocol()\n );\n }\n @Override\n public void sendMessage(Object receiver, String text) {\n sendMessage(receiver, text, null, null, null, null);", "score": 0.8960211277008057 }, { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/NeoProtectSpigot.java", "retrieved_chunk": " getServer().getOnlineMode(),\n Config.isProxyProtocol()\n );\n }\n @Override\n public void sendMessage(Object receiver, String text) {\n sendMessage(receiver, text, null, null, null, null);\n }\n @Override\n @SuppressWarnings(\"deprecation\")", "score": 0.8933016061782837 }, { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/NeoProtectBungee.java", "retrieved_chunk": " @Override\n public void sendAdminMessage(Permission permission, String text, String clickAction, String clickMsg, String hoverAction, String hoverMsg) {\n getProxy().getPlayers().forEach(receiver -> {\n if (receiver.hasPermission(\"neoprotect.admin\") || receiver.hasPermission(permission.value))\n sendMessage(receiver, text, clickAction, clickMsg, hoverAction, hoverMsg);\n });\n }\n @Override\n public void sendKeepAliveMessage(Object receiver, long id) {\n if (receiver instanceof ProxiedPlayer) {", "score": 0.8748667240142822 } ]
java
Component.text(core.getPrefix() + text);
package de.cubeattack.neoprotect.core.executor; import de.cubeattack.api.API; import de.cubeattack.api.language.Localization; import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration; import de.cubeattack.api.libraries.org.json.JSONObject; import de.cubeattack.neoprotect.core.Config; import de.cubeattack.neoprotect.core.NeoProtectPlugin; import de.cubeattack.neoprotect.core.model.Backend; import de.cubeattack.neoprotect.core.model.Gameshield; import de.cubeattack.neoprotect.core.model.Stats; import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse; import java.io.File; import java.nio.file.Files; import java.sql.Timestamp; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.atomic.AtomicReference; public class NeoProtectExecutor { private static Timer debugTimer = new Timer(); private NeoProtectPlugin instance; private Localization localization; private Object sender; private Locale locale; private String msg; private String[] args; private boolean isViaConsole; private void initials(ExecutorBuilder executeBuilder) { this.instance = executeBuilder.getInstance(); this.localization = instance.getCore().getLocalization(); this.sender = executeBuilder.getSender(); this.locale = executeBuilder.getLocal(); this.args = executeBuilder.getArgs(); this.msg = executeBuilder.getMsg(); this.isViaConsole = executeBuilder.isViaConsole(); } private void chatEvent(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (instance.getCore().getRestAPI().isAPIInvalid(msg)) { instance.sendMessage(sender, localization.get(locale, "apikey.invalid")); return; } Config.setAPIKey(msg); instance.sendMessage(sender, localization.get(locale, "apikey.valid")); gameshieldSelector(); } private void command(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (args.length == 0) { showHelp(); return; } if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) { instance.sendMessage(sender, localization.get(locale, "setup.command.required")); return; } switch (args[0].toLowerCase()) { case "setup": { if (isViaConsole) { instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command")); } else { setup(); } break; } case "ipanic": { iPanic(args); break; } case "directconnectwhitelist": { directConnectWhitelist(args); break; } case "toggle": { toggle(args); break; } case "analytics": { analytics(); break; } case "whitelist": case "blacklist": { firewall(args); break; } case "debugtool": { debugTool(args); break; } case "setgameshield": { if (args.length == 1 && !isViaConsole) { gameshieldSelector(); } else if (args.length == 2) { setGameshield(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgameshield")); } break; } case "setbackend": { if (args.length == 1 && !isViaConsole) { javaBackendSelector(); } else if (args.length == 2) { setJavaBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setbackend")); } break; } case "setgeyserbackend": { if (args.length == 1 && !isViaConsole) { bedrockBackendSelector(); } else if (args.length == 2) { setBedrockBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend")); } break; } default: { showHelp(); } } } private void setup() { instance.getCore().getPlayerInSetup().add(sender); instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"), "OPEN_URL", "https://panel.neoprotect.net/profile", "SHOW_TEXT", localization.get(locale, "apikey.find")); } private void iPanic(String[] args) { if (args.length != 1) { instance.sendMessage(sender, localization.get(locale, "usage.ipanic")); } else { instance.sendMessage(sender, localization.get(locale, "command.ipanic", localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated"))); } } private void directConnectWhitelist(String[] args) { if (args.length == 2) { instance.getCore().getDirectConnectWhitelist().add(args[1]); instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1])); } else { instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist")); } } private void toggle(String[] args) { if (args.length != 2) { instance.sendMessage(sender, localization.get(locale, "usage.toggle")); } else { int response = instance.getCore().getRestAPI().toggle(args[1]); if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } if (response == -1) { instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'"); return; } instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1], localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated"))); } } private void analytics() { instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------"); JSONObject analytics = instance.getCore().getRestAPI().getAnalytics(); instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> { if (ak.equals("bandwidth")) { return; } if (ak.equals("traffic")) { instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " + new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s"); JSONObject traffic = instance.getCore().getRestAPI().getTraffic(); AtomicReference<String> trafficUsed = new AtomicReference<>(); AtomicReference<String> trafficAvailable = new AtomicReference<>(); traffic.keySet().forEach(bk -> { if (bk.equals("used")) { trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb"); } if (bk.equals("available")) { trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb"); } }); instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get()); return; } instance.sendMessage(sender, ak .replace("onlinePlayers", "online players") .replace("cps", "connections/s") + ": " + analytics.get(ak)); }); } private void firewall(String[] args) { if (args.length == 1) { instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----"); instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall -> instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")"))); } else if (args.length == 3) { String ip = args[2]; String action = args[1]; String mode = args[0].toUpperCase(); int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode); if (response == -1) { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); return; } if (response == 0) { instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode)); return; } if (response == 400) { instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip)); return; } if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")"); } else { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); } } @SuppressWarnings("ResultOfMethodCallIgnored") private void debugTool(String[] args) { if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) { instance.sendMessage(sender, localization.get(locale, "debug.spigot")); return; } if (args.length == 2) { if (args[1].equals("cancel")) { debugTimer.cancel(); instance.getCore().setDebugRunning(false); instance.sendMessage(sender, localization.get(locale, "debug.cancelled")); return; } if (!isInteger(args[1])) { instance.sendMessage(sender, localization.get(locale, "usage.debug")); return; } } if (instance.getCore().isDebugRunning()) { instance.sendMessage(sender, localization.get(locale, "debug.running")); return; } instance.getCore().setDebugRunning(true); instance.sendMessage(sender, localization.get(locale, "debug.starting")); int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5; debugTimer = new Timer(); debugTimer.schedule(new TimerTask() { int counter = 0; @Override public void run() { counter++; instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis())); instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")"); if (counter >= amount) this.cancel(); } }, 500, 2000); debugTimer.schedule(new TimerTask() { @Override public void run() { API.getExecutorService().submit(() -> { try { long startTime = System.currentTimeMillis(); Stats stats = instance.getStats(); File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml"); YamlConfiguration configuration = new YamlConfiguration(); if (!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } configuration.load(file); configuration.set("general.osName", System.getProperty("os.name")); configuration.set("general.javaVersion", System.getProperty("java.version")); configuration.
set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName()); configuration.set("general.ProxyVersion", stats.getServerVersion()); configuration.set("general.ProxyPlugins", instance.getPlugins()); instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> { List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName); long maxPlayerToProxyLatenz = 0; long maxNeoToProxyLatenz = 0; long maxProxyToBackendLatenz = 0; long maxPlayerToNeoLatenz = 0; long avgPlayerToProxyLatenz = 0; long avgNeoToProxyLatenz = 0; long avgProxyToBackendLatenz = 0; long avgPlayerToNeoLatenz = 0; long minPlayerToProxyLatenz = Long.MAX_VALUE; long minNeoToProxyLatenz = Long.MAX_VALUE; long minProxyToBackendLatenz = Long.MAX_VALUE; long minPlayerToNeoLatenz = Long.MAX_VALUE; configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress()); configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress()); for (DebugPingResponse response : list) { if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz()) maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz()) maxNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz()) maxProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz()) maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz(); avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz(); avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz(); avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz(); if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz()) minPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (minNeoToProxyLatenz > response.getNeoToProxyLatenz()) minNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (minProxyToBackendLatenz > response.getProxyToBackendLatenz()) minProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz()) minPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); } configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz); configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size()); configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz); })); configuration.save(file); final String content = new String(Files.readAllBytes(file.toPath())); final String pasteKey = instance.getCore().getRestAPI().paste(content); instance.getCore().getDebugPingResponses().clear(); instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)"); if(pasteKey != null) { final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml"; instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null); } else { instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null); } instance.getCore().setDebugRunning(false); } catch (Exception ex) { instance.getCore().severe(ex.getMessage(), ex); } }); } }, 2000L * amount + 500); } private void gameshieldSelector() { instance.sendMessage(sender, localization.get(locale, "select.gameshield")); List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields(); for (Gameshield gameshield : gameshieldList) { instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgameshield " + gameshield.getId(), "SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId())); } } private void setGameshield(String[] args) { if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1])); return; } Config.setGameShieldID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1])); javaBackendSelector(); } private void javaBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); instance.sendMessage(sender, localization.get(locale, "select.backend", "java")); for (Backend backend : backendList) { if(backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setJavaBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1])); return; } Config.setBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1])); instance.getCore().getRestAPI().testCredentials(); bedrockBackendSelector(); } private void bedrockBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); if(backendList.stream().noneMatch(Backend::isGeyser))return; instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser")); for (Backend backend : backendList) { if(!backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgeyserbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setBedrockBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1])); return; } Config.setGeyserBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1])); if (instance.getCore().getPlayerInSetup().remove(sender)) { instance.sendMessage(sender, localization.get(locale, "setup.finished")); } } private void showHelp() { instance.sendMessage(sender, localization.get(locale, "available.commands")); instance.sendMessage(sender, " - /np setup"); instance.sendMessage(sender, " - /np ipanic"); instance.sendMessage(sender, " - /np analytics"); instance.sendMessage(sender, " - /np toggle (option)"); instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)"); instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)"); instance.sendMessage(sender, " - /np debugTool (cancel / amount)"); instance.sendMessage(sender, " - /np directConnectWhitelist (ip)"); instance.sendMessage(sender, " - /np setgameshield [id]"); instance.sendMessage(sender, " - /np setbackend [id]"); instance.sendMessage(sender, " - /np setgeyserbackend [id]"); } public static class ExecutorBuilder { private NeoProtectPlugin instance; private Object sender; private String[] args; private Locale local; private String msg; private boolean viaConsole; public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) { this.instance = instance; return this; } public ExecutorBuilder sender(Object sender) { this.sender = sender; return this; } public ExecutorBuilder args(String[] args) { this.args = args; return this; } public ExecutorBuilder local(Locale local) { this.local = local; return this; } public ExecutorBuilder msg(String msg) { this.msg = msg; return this; } public ExecutorBuilder viaConsole(boolean viaConsole) { this.viaConsole = viaConsole; return this; } public void executeChatEvent() { API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this)); } public void executeCommand() { API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this)); } public NeoProtectPlugin getInstance() { return instance; } public Object getSender() { return sender; } public String[] getArgs() { return args; } public Locale getLocal() { return local; } public String getMsg() { return msg; } public boolean isViaConsole() { return viaConsole; } } public static boolean isInteger(String input) { try { Integer.parseInt(input); return true; } catch (NumberFormatException e) { return false; } } }
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
NeoProtect-NeoPlugin-a71f673
[ { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/NeoProtectSpigot.java", "retrieved_chunk": " System.getProperty(\"os.arch\"),\n System.getProperty(\"os.version\"),\n getPluginVersion(),\n getCore().getVersionResult().getVersionStatus().toString(),\n Config.getAutoUpdaterSettings().toString(),\n getCore().isSetup() ? getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\",\n Arrays.toString(getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray()),\n getServer().getOnlinePlayers().size(),\n 0,\n Runtime.getRuntime().availableProcessors(),", "score": 0.8228055834770203 }, { "filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java", "retrieved_chunk": " \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +\n \"§bProxyProtocol§7: \" + Config.isProxyProtocol() + \" \\n\" +\n \"§bNeoProtectPlan§7: \" + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\") + \" \\n\" +\n \"§bVelocityName§7: \" + stats.getServerName() + \" \\n\" +\n \"§bVelocityVersion§7: \" + stats.getServerVersion() + \" \\n\" +\n \"§bVelocityPlugins§7: \" + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray());\n instance.sendMessage(player, \"§bHello \" + player.getUsername() + \" ;)\", null, null, \"SHOW_TEXT\", infos);\n instance.sendMessage(player, \"§bThis server uses your NeoPlugin\", null, null, \"SHOW_TEXT\", infos);", "score": 0.8171842098236084 }, { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java", "retrieved_chunk": " \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +\n \"§bProxyProtocol§7: \" + Config.isProxyProtocol() + \" \\n\" +\n \"§bNeoProtectPlan§7: \" + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\") + \" \\n\" +\n \"§bBungeecordName§7: \" + stats.getServerName() + \" \\n\" +\n \"§bBungeecordVersion§7: \" + stats.getServerVersion()+ \" \\n\" +\n \"§bBungeecordPlugins§7: \" + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray());\n instance.sendMessage(player, \"§bHello \" + player.getName() + \" ;)\", null, null, \"SHOW_TEXT\", infos);\n instance.sendMessage(player, \"§bThis server uses your NeoPlugin\", null, null, \"SHOW_TEXT\", infos);", "score": 0.8161888122558594 }, { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/NeoProtectSpigot.java", "retrieved_chunk": " return core;\n }\n @Override\n public Stats getStats() {\n return new Stats(\n getPluginType(),\n getServer().getVersion(),\n getServer().getName(),\n System.getProperty(\"java.version\"),\n System.getProperty(\"os.name\"),", "score": 0.8096742033958435 }, { "filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java", "retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +", "score": 0.8023276329040527 } ]
java
set("general.pluginVersion", stats.getPluginVersion());
package com.cursework.WebArtSell.Controllers; import com.cursework.WebArtSell.Models.Product; import com.cursework.WebArtSell.Models.User; import com.cursework.WebArtSell.Services.ProductService; import com.cursework.WebArtSell.Services.TransactionService; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import java.util.List; @Controller public class HomeController { private final ProductService productService; private final TransactionService transactionService; public HomeController(ProductService productService, TransactionService transactionService) { this.productService = productService; this.transactionService = transactionService; } @GetMapping("/main-user") public String getMainUserPage(Model model, HttpServletRequest request) { HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); List<Product> products = productService.findAll(); Long currentUserId = user.getId(); for (Product product : products) { if (transactionService.isProductInTransactions(product)) { product.setDescription("Этот товар уже продан!"); product.setDisableButton(true); } if (product.getCreatedBy().getId().equals(currentUserId)) {
product.setDescription("Это ваше объявление!");
product.setDisableButton(true); } } model.addAttribute("products", products); return "main-user"; } @GetMapping("/") public String home(Model model) { List<Product> products = productService.findAll(); model.addAttribute("products", products); return "main"; } @GetMapping("/main-user/category/{category}") public String getMainUserPageByCategory(@PathVariable String category, Model model, HttpServletRequest request) { HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); if (user == null) { return "redirect:/authorisation"; } List<Product> products = productService.findAllByCategory(category); Long currentUserId = user.getId(); for (Product product : products) { if (transactionService.isProductInTransactions(product)) { product.setDescription("Этот товар уже продан!"); product.setDisableButton(true); } if (product.getCreatedBy().getId().equals(currentUserId)) { product.setDescription("Это ваше объявление!"); product.setDisableButton(true); } } model.addAttribute("products", products); return "main-user"; } }
src/main/java/com/cursework/WebArtSell/Controllers/HomeController.java
Neural-Enigma-Art-sales-Spring-Boot-57a8036
[ { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java", "retrieved_chunk": " } catch (Exception e) {\n model.addAttribute(\"error\", \"Ошибка\");\n model.addAttribute(\"transaction\", new Transaction());\n Optional<Product> product = productRepository.findById(productId);\n if (product.isPresent()) {\n model.addAttribute(\"product\", product.get());\n HttpSession session = request.getSession();\n User buyer = (User) session.getAttribute(\"user\");\n transaction.setBuyerId(buyer.getId());\n transaction.setSellerId(product.get().getCreatedBy().getId());", "score": 0.8917446136474609 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java", "retrieved_chunk": " model.addAttribute(\"product\", product.get());\n Transaction transaction = new Transaction();\n HttpSession session = request.getSession();\n User buyer = (User) session.getAttribute(\"user\");\n transaction.setBuyerId(buyer.getId());\n transaction.setSellerId(product.get().getCreatedBy().getId());\n transaction.setPurchaseDate(LocalDateTime.now());\n transaction.setSum(product.get().getPrice().doubleValue());\n transaction.setProductId(product.get().getId());\n model.addAttribute(\"transaction\", transaction);", "score": 0.8733078241348267 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java", "retrieved_chunk": " System.out.println(transaction.getSellerId());\n System.out.println(transaction.getPurchaseDate());\n System.out.println(transaction.getSum());\n transactionRepository.save(transaction);\n Optional<Product> product = productRepository.findById(productId);\n if (product.isPresent()) {\n model.addAttribute(\"product\", product.get());\n } else {\n return \"redirect:/main-user\";\n }", "score": 0.8694263696670532 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java", "retrieved_chunk": " transaction.setPurchaseDate(LocalDateTime.now());\n transaction.setSum(product.get().getPrice().doubleValue());\n transaction.setProductId(product.get().getId());\n }\n return \"billing\";\n }\n return \"redirect:/main-user\";\n }\n @GetMapping(\"/api/transactions\")\n public List<Transaction> getTransactions() {", "score": 0.8500389456748962 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java", "retrieved_chunk": "package com.cursework.WebArtSell.Controllers;\nimport com.cursework.WebArtSell.Models.Product;\nimport com.cursework.WebArtSell.Models.Transaction;\nimport com.cursework.WebArtSell.Models.TransactionChartData;\nimport com.cursework.WebArtSell.Models.User;\nimport com.cursework.WebArtSell.Repositories.ProductRepository;\nimport com.cursework.WebArtSell.Repositories.TransactionRepository;\nimport com.cursework.WebArtSell.Services.TransactionService;\nimport jakarta.servlet.http.HttpServletRequest;\nimport jakarta.servlet.http.HttpSession;", "score": 0.8469341397285461 } ]
java
product.setDescription("Это ваше объявление!");
package com.cursework.WebArtSell.Controllers; import com.cursework.WebArtSell.Models.User; import com.cursework.WebArtSell.Repositories.UserRepository; import jakarta.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.Optional; @Controller @RequestMapping("/table-users") public class UserController { @Autowired private UserRepository userRepository; @GetMapping public String getAllUsers(Model model, HttpSession session) { Iterable<User> users = userRepository.findAll(); User currentUser = (User) session.getAttribute("user"); model.addAttribute("users", users); model.addAttribute("currentUser", currentUser); model.addAttribute("statuses", new String[]{"Проверенный", "Непроверенный"}); model.addAttribute("roles", new String[]{"ADMIN", "USER"}); return "table-users"; } @PostMapping("/edit/{id}") public String editUser(@PathVariable("id") Long id, @ModelAttribute User user, HttpSession session) { User currentUser = (User) session.getAttribute("user"); if (!currentUser.getId().equals(id)) { Optional<User> optUser = userRepository.findById(id); if (optUser.isPresent()) { User existUser = optUser.get(); existUser.setLogin(user.getLogin()); existUser.
setEmail(user.getEmail());
existUser.setStatus(user.getStatus()); existUser.setRole(user.getRole()); userRepository.save(existUser); } } return "redirect:/table-users"; } @PostMapping("/delete/{id}") public String deleteUser(@PathVariable("id") Long id, HttpSession session) { User currentUser = (User) session.getAttribute("user"); if (!currentUser.getId().equals(id)) { userRepository.deleteById(id); } return "redirect:/table-users"; } }
src/main/java/com/cursework/WebArtSell/Controllers/UserController.java
Neural-Enigma-Art-sales-Spring-Boot-57a8036
[ { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/ProductController.java", "retrieved_chunk": " }\n @PostMapping(\"/{id}/edit\")\n public String updateProduct(@PathVariable long id, @ModelAttribute Product updatedProduct) {\n Product product = productRepository.findById(id).orElseThrow();\n product.setName(updatedProduct.getName());\n product.setDescription(updatedProduct.getDescription());\n product.setImageUrl(updatedProduct.getImageUrl());\n product.setPrice(updatedProduct.getPrice());\n product.setArtist(updatedProduct.getArtist());\n product.setDimensions(updatedProduct.getDimensions());", "score": 0.8612722158432007 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/AuthorisationController.java", "retrieved_chunk": " model.addAttribute(\"users\", userRepository.findAll());\n return \"authorisation\";\n }\n @PostMapping\n public String userLogin(@RequestParam String email,\n @RequestParam String password,\n Model model,\n HttpServletRequest request) {\n Optional<User> optionalUser = userRepository.findByEmailAndPassword(email, password);\n if (optionalUser.isPresent()) {", "score": 0.8592646718025208 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/AuthorisationController.java", "retrieved_chunk": " User user = optionalUser.get();\n HttpSession session = request.getSession();\n session.setAttribute(\"user\", user);\n if (user.getRole().equals(\"ADMIN\")) {\n return \"redirect:/table-users\";\n } else {\n return \"redirect:/main-user\";\n }\n } else {\n model.addAttribute(\"error\", \"Неверный email или пароль\");", "score": 0.8425941467285156 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/RegistrationController.java", "retrieved_chunk": " user.setEmail(email);\n user.setPassword(password);\n user.setRole(\"USER\");\n user.setCreationDate(LocalDateTime.now());\n user.setStatus(\"Активный\");\n userRepository.save(user);\n return \"redirect:/authorisation\";\n }\n}", "score": 0.8423203229904175 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/RegistrationController.java", "retrieved_chunk": " }\n @PostMapping\n public String registerUser(@RequestParam String name, @RequestParam String email, @RequestParam String password,\n @RequestParam String confirm_password, Model model) {\n if (!password.equals(confirm_password)) {\n model.addAttribute(\"error\", \"Пароли не совпадают!\");\n return \"registration\";\n }\n User user = new User();\n user.setLogin(name);", "score": 0.8355991244316101 } ]
java
setEmail(user.getEmail());
package com.cursework.WebArtSell.Controllers; import com.cursework.WebArtSell.Models.User; import com.cursework.WebArtSell.Repositories.UserRepository; import jakarta.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.Optional; @Controller @RequestMapping("/table-users") public class UserController { @Autowired private UserRepository userRepository; @GetMapping public String getAllUsers(Model model, HttpSession session) { Iterable<User> users = userRepository.findAll(); User currentUser = (User) session.getAttribute("user"); model.addAttribute("users", users); model.addAttribute("currentUser", currentUser); model.addAttribute("statuses", new String[]{"Проверенный", "Непроверенный"}); model.addAttribute("roles", new String[]{"ADMIN", "USER"}); return "table-users"; } @PostMapping("/edit/{id}") public String editUser(@PathVariable("id") Long id, @ModelAttribute User user, HttpSession session) { User currentUser = (User) session.getAttribute("user"); if (!currentUser.getId().equals(id)) { Optional<User> optUser = userRepository.findById(id); if (optUser.isPresent()) { User existUser = optUser.get(); existUser.setLogin(user.getLogin()); existUser.setEmail(user.getEmail()); existUser.setStatus(user.getStatus());
existUser.setRole(user.getRole());
userRepository.save(existUser); } } return "redirect:/table-users"; } @PostMapping("/delete/{id}") public String deleteUser(@PathVariable("id") Long id, HttpSession session) { User currentUser = (User) session.getAttribute("user"); if (!currentUser.getId().equals(id)) { userRepository.deleteById(id); } return "redirect:/table-users"; } }
src/main/java/com/cursework/WebArtSell/Controllers/UserController.java
Neural-Enigma-Art-sales-Spring-Boot-57a8036
[ { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/AuthorisationController.java", "retrieved_chunk": " model.addAttribute(\"users\", userRepository.findAll());\n return \"authorisation\";\n }\n @PostMapping\n public String userLogin(@RequestParam String email,\n @RequestParam String password,\n Model model,\n HttpServletRequest request) {\n Optional<User> optionalUser = userRepository.findByEmailAndPassword(email, password);\n if (optionalUser.isPresent()) {", "score": 0.8446330428123474 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/ProductController.java", "retrieved_chunk": " }\n @PostMapping(\"/{id}/edit\")\n public String updateProduct(@PathVariable long id, @ModelAttribute Product updatedProduct) {\n Product product = productRepository.findById(id).orElseThrow();\n product.setName(updatedProduct.getName());\n product.setDescription(updatedProduct.getDescription());\n product.setImageUrl(updatedProduct.getImageUrl());\n product.setPrice(updatedProduct.getPrice());\n product.setArtist(updatedProduct.getArtist());\n product.setDimensions(updatedProduct.getDimensions());", "score": 0.8442022800445557 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/AuthorisationController.java", "retrieved_chunk": " User user = optionalUser.get();\n HttpSession session = request.getSession();\n session.setAttribute(\"user\", user);\n if (user.getRole().equals(\"ADMIN\")) {\n return \"redirect:/table-users\";\n } else {\n return \"redirect:/main-user\";\n }\n } else {\n model.addAttribute(\"error\", \"Неверный email или пароль\");", "score": 0.8303776979446411 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/RegistrationController.java", "retrieved_chunk": " user.setEmail(email);\n user.setPassword(password);\n user.setRole(\"USER\");\n user.setCreationDate(LocalDateTime.now());\n user.setStatus(\"Активный\");\n userRepository.save(user);\n return \"redirect:/authorisation\";\n }\n}", "score": 0.8289880156517029 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/AuthorisationController.java", "retrieved_chunk": "package com.cursework.WebArtSell.Controllers;\nimport com.cursework.WebArtSell.Models.User;\nimport com.cursework.WebArtSell.Repositories.UserRepository;\nimport jakarta.servlet.http.HttpServletRequest;\nimport jakarta.servlet.http.HttpSession;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PostMapping;", "score": 0.8213077783584595 } ]
java
existUser.setRole(user.getRole());
package com.cursework.WebArtSell.Controllers; import com.cursework.WebArtSell.Models.User; import com.cursework.WebArtSell.Repositories.UserRepository; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.Optional; @Controller @RequestMapping("/authorisation") public class AuthorisationController { @Autowired private UserRepository userRepository; @GetMapping public String getAllUsers(Model model) { model.addAttribute("users", userRepository.findAll()); return "authorisation"; } @PostMapping public String userLogin(@RequestParam String email, @RequestParam String password, Model model, HttpServletRequest request) { Optional<User> optionalUser = userRepository.findByEmailAndPassword(email, password); if (optionalUser.isPresent()) { User user = optionalUser.get(); HttpSession session = request.getSession(); session.setAttribute("user", user); if
(user.getRole().equals("ADMIN")) {
return "redirect:/table-users"; } else { return "redirect:/main-user"; } } else { model.addAttribute("error", "Неверный email или пароль"); return "authorisation"; } } }
src/main/java/com/cursework/WebArtSell/Controllers/AuthorisationController.java
Neural-Enigma-Art-sales-Spring-Boot-57a8036
[ { "filename": "src/main/java/com/cursework/WebArtSell/Secure/RoleCheckInterceptor.java", "retrieved_chunk": " HttpSession session = request.getSession();\n User user = (User) session.getAttribute(\"user\");\n if (user == null || !user.getRole().equals(\"ADMIN\")) {\n response.sendRedirect(\"/authorisation\");\n return false;\n }\n return true;\n }\n}", "score": 0.8797621130943298 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/RegistrationController.java", "retrieved_chunk": " user.setEmail(email);\n user.setPassword(password);\n user.setRole(\"USER\");\n user.setCreationDate(LocalDateTime.now());\n user.setStatus(\"Активный\");\n userRepository.save(user);\n return \"redirect:/authorisation\";\n }\n}", "score": 0.8725824356079102 }, { "filename": "src/main/java/com/cursework/WebArtSell/Secure/UserCheckInterceptor.java", "retrieved_chunk": " HttpSession session = request.getSession();\n User user = (User) session.getAttribute(\"user\");\n if (user == null || !user.getRole().equals(\"USER\")) {\n response.sendRedirect(\"/authorisation\");\n return false;\n }\n return true;\n }\n}", "score": 0.8707961440086365 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/RegistrationController.java", "retrieved_chunk": " }\n @PostMapping\n public String registerUser(@RequestParam String name, @RequestParam String email, @RequestParam String password,\n @RequestParam String confirm_password, Model model) {\n if (!password.equals(confirm_password)) {\n model.addAttribute(\"error\", \"Пароли не совпадают!\");\n return \"registration\";\n }\n User user = new User();\n user.setLogin(name);", "score": 0.8670368194580078 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/UserController.java", "retrieved_chunk": " model.addAttribute(\"statuses\", new String[]{\"Проверенный\", \"Непроверенный\"});\n model.addAttribute(\"roles\", new String[]{\"ADMIN\", \"USER\"});\n return \"table-users\";\n }\n @PostMapping(\"/edit/{id}\")\n public String editUser(@PathVariable(\"id\") Long id, @ModelAttribute User user, HttpSession session) {\n User currentUser = (User) session.getAttribute(\"user\");\n if (!currentUser.getId().equals(id)) {\n Optional<User> optUser = userRepository.findById(id);\n if (optUser.isPresent()) {", "score": 0.8544015288352966 } ]
java
(user.getRole().equals("ADMIN")) {
package com.cursework.WebArtSell.Controllers; import com.cursework.WebArtSell.Models.Product; import com.cursework.WebArtSell.Models.User; import com.cursework.WebArtSell.Services.ProductService; import com.cursework.WebArtSell.Services.TransactionService; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import java.util.List; @Controller public class HomeController { private final ProductService productService; private final TransactionService transactionService; public HomeController(ProductService productService, TransactionService transactionService) { this.productService = productService; this.transactionService = transactionService; } @GetMapping("/main-user") public String getMainUserPage(Model model, HttpServletRequest request) { HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); List<Product> products = productService.findAll(); Long currentUserId = user.getId(); for (Product product : products) { if (transactionService.isProductInTransactions(product)) { product.setDescription("Этот товар уже продан!"); product.setDisableButton(true); }
if (product.getCreatedBy().getId().equals(currentUserId)) {
product.setDescription("Это ваше объявление!"); product.setDisableButton(true); } } model.addAttribute("products", products); return "main-user"; } @GetMapping("/") public String home(Model model) { List<Product> products = productService.findAll(); model.addAttribute("products", products); return "main"; } @GetMapping("/main-user/category/{category}") public String getMainUserPageByCategory(@PathVariable String category, Model model, HttpServletRequest request) { HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); if (user == null) { return "redirect:/authorisation"; } List<Product> products = productService.findAllByCategory(category); Long currentUserId = user.getId(); for (Product product : products) { if (transactionService.isProductInTransactions(product)) { product.setDescription("Этот товар уже продан!"); product.setDisableButton(true); } if (product.getCreatedBy().getId().equals(currentUserId)) { product.setDescription("Это ваше объявление!"); product.setDisableButton(true); } } model.addAttribute("products", products); return "main-user"; } }
src/main/java/com/cursework/WebArtSell/Controllers/HomeController.java
Neural-Enigma-Art-sales-Spring-Boot-57a8036
[ { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java", "retrieved_chunk": " } catch (Exception e) {\n model.addAttribute(\"error\", \"Ошибка\");\n model.addAttribute(\"transaction\", new Transaction());\n Optional<Product> product = productRepository.findById(productId);\n if (product.isPresent()) {\n model.addAttribute(\"product\", product.get());\n HttpSession session = request.getSession();\n User buyer = (User) session.getAttribute(\"user\");\n transaction.setBuyerId(buyer.getId());\n transaction.setSellerId(product.get().getCreatedBy().getId());", "score": 0.8973174095153809 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java", "retrieved_chunk": " model.addAttribute(\"product\", product.get());\n Transaction transaction = new Transaction();\n HttpSession session = request.getSession();\n User buyer = (User) session.getAttribute(\"user\");\n transaction.setBuyerId(buyer.getId());\n transaction.setSellerId(product.get().getCreatedBy().getId());\n transaction.setPurchaseDate(LocalDateTime.now());\n transaction.setSum(product.get().getPrice().doubleValue());\n transaction.setProductId(product.get().getId());\n model.addAttribute(\"transaction\", transaction);", "score": 0.8844337463378906 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java", "retrieved_chunk": " System.out.println(transaction.getSellerId());\n System.out.println(transaction.getPurchaseDate());\n System.out.println(transaction.getSum());\n transactionRepository.save(transaction);\n Optional<Product> product = productRepository.findById(productId);\n if (product.isPresent()) {\n model.addAttribute(\"product\", product.get());\n } else {\n return \"redirect:/main-user\";\n }", "score": 0.8679473996162415 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java", "retrieved_chunk": "package com.cursework.WebArtSell.Controllers;\nimport com.cursework.WebArtSell.Models.Product;\nimport com.cursework.WebArtSell.Models.Transaction;\nimport com.cursework.WebArtSell.Models.TransactionChartData;\nimport com.cursework.WebArtSell.Models.User;\nimport com.cursework.WebArtSell.Repositories.ProductRepository;\nimport com.cursework.WebArtSell.Repositories.TransactionRepository;\nimport com.cursework.WebArtSell.Services.TransactionService;\nimport jakarta.servlet.http.HttpServletRequest;\nimport jakarta.servlet.http.HttpSession;", "score": 0.8511738181114197 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java", "retrieved_chunk": " transaction.setPurchaseDate(LocalDateTime.now());\n transaction.setSum(product.get().getPrice().doubleValue());\n transaction.setProductId(product.get().getId());\n }\n return \"billing\";\n }\n return \"redirect:/main-user\";\n }\n @GetMapping(\"/api/transactions\")\n public List<Transaction> getTransactions() {", "score": 0.8510932922363281 } ]
java
if (product.getCreatedBy().getId().equals(currentUserId)) {
package de.cubeattack.neoprotect.core.executor; import de.cubeattack.api.API; import de.cubeattack.api.language.Localization; import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration; import de.cubeattack.api.libraries.org.json.JSONObject; import de.cubeattack.neoprotect.core.Config; import de.cubeattack.neoprotect.core.NeoProtectPlugin; import de.cubeattack.neoprotect.core.model.Backend; import de.cubeattack.neoprotect.core.model.Gameshield; import de.cubeattack.neoprotect.core.model.Stats; import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse; import java.io.File; import java.nio.file.Files; import java.sql.Timestamp; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.atomic.AtomicReference; public class NeoProtectExecutor { private static Timer debugTimer = new Timer(); private NeoProtectPlugin instance; private Localization localization; private Object sender; private Locale locale; private String msg; private String[] args; private boolean isViaConsole; private void initials(ExecutorBuilder executeBuilder) { this.instance = executeBuilder.getInstance(); this.localization = instance.getCore().getLocalization(); this.sender = executeBuilder.getSender(); this.locale = executeBuilder.getLocal(); this.args = executeBuilder.getArgs(); this.msg = executeBuilder.getMsg(); this.isViaConsole = executeBuilder.isViaConsole(); } private void chatEvent(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (instance.getCore().getRestAPI().isAPIInvalid(msg)) { instance.sendMessage(sender, localization.get(locale, "apikey.invalid")); return; } Config.setAPIKey(msg); instance.sendMessage(sender, localization.get(locale, "apikey.valid")); gameshieldSelector(); } private void command(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (args.length == 0) { showHelp(); return; } if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) { instance.sendMessage(sender, localization.get(locale, "setup.command.required")); return; } switch (args[0].toLowerCase()) { case "setup": { if (isViaConsole) { instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command")); } else { setup(); } break; } case "ipanic": { iPanic(args); break; } case "directconnectwhitelist": { directConnectWhitelist(args); break; } case "toggle": { toggle(args); break; } case "analytics": { analytics(); break; } case "whitelist": case "blacklist": { firewall(args); break; } case "debugtool": { debugTool(args); break; } case "setgameshield": { if (args.length == 1 && !isViaConsole) { gameshieldSelector(); } else if (args.length == 2) { setGameshield(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgameshield")); } break; } case "setbackend": { if (args.length == 1 && !isViaConsole) { javaBackendSelector(); } else if (args.length == 2) { setJavaBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setbackend")); } break; } case "setgeyserbackend": { if (args.length == 1 && !isViaConsole) { bedrockBackendSelector(); } else if (args.length == 2) { setBedrockBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend")); } break; } default: { showHelp(); } } } private void setup() { instance.getCore().getPlayerInSetup().add(sender); instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"), "OPEN_URL", "https://panel.neoprotect.net/profile", "SHOW_TEXT", localization.get(locale, "apikey.find")); } private void iPanic(String[] args) { if (args.length != 1) { instance.sendMessage(sender, localization.get(locale, "usage.ipanic")); } else { instance.sendMessage(sender, localization.get(locale, "command.ipanic", localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated"))); } } private void directConnectWhitelist(String[] args) { if (args.length == 2) { instance.getCore().getDirectConnectWhitelist().add(args[1]); instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1])); } else { instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist")); } } private void toggle(String[] args) { if (args.length != 2) { instance.sendMessage(sender, localization.get(locale, "usage.toggle")); } else { int response = instance.getCore().getRestAPI().toggle(args[1]); if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } if (response == -1) { instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'"); return; } instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1], localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated"))); } } private void analytics() { instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------"); JSONObject analytics = instance.getCore().getRestAPI().getAnalytics(); instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> { if (ak.equals("bandwidth")) { return; } if (ak.equals("traffic")) { instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " + new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s"); JSONObject traffic = instance.getCore().getRestAPI().getTraffic(); AtomicReference<String> trafficUsed = new AtomicReference<>(); AtomicReference<String> trafficAvailable = new AtomicReference<>(); traffic.keySet().forEach(bk -> { if (bk.equals("used")) { trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb"); } if (bk.equals("available")) { trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb"); } }); instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get()); return; } instance.sendMessage(sender, ak .replace("onlinePlayers", "online players") .replace("cps", "connections/s") + ": " + analytics.get(ak)); }); } private void firewall(String[] args) { if (args.length == 1) { instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----"); instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall -> instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")"))); } else if (args.length == 3) { String ip = args[2]; String action = args[1]; String mode = args[0].toUpperCase(); int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode); if (response == -1) { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); return; } if (response == 0) { instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode)); return; } if (response == 400) { instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip)); return; } if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")"); } else { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); } } @SuppressWarnings("ResultOfMethodCallIgnored") private void debugTool(String[] args) { if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) { instance.sendMessage(sender, localization.get(locale, "debug.spigot")); return; } if (args.length == 2) { if (args[1].equals("cancel")) { debugTimer.cancel(); instance.getCore().setDebugRunning(false); instance.sendMessage(sender, localization.get(locale, "debug.cancelled")); return; } if (!isInteger(args[1])) { instance.sendMessage(sender, localization.get(locale, "usage.debug")); return; } } if (instance.getCore().isDebugRunning()) { instance.sendMessage(sender, localization.get(locale, "debug.running")); return; } instance.getCore().setDebugRunning(true); instance.sendMessage(sender, localization.get(locale, "debug.starting")); int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5; debugTimer = new Timer(); debugTimer.schedule(new TimerTask() { int counter = 0; @Override public void run() { counter++; instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis())); instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")"); if (counter >= amount) this.cancel(); } }, 500, 2000); debugTimer.schedule(new TimerTask() { @Override public void run() { API.getExecutorService().submit(() -> { try { long startTime = System.currentTimeMillis(); Stats stats = instance.getStats(); File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml"); YamlConfiguration configuration = new YamlConfiguration(); if (!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } configuration.load(file); configuration.set("general.osName", System.getProperty("os.name")); configuration.set("general.javaVersion", System.getProperty("java.version")); configuration.set("general.pluginVersion", stats.getPluginVersion()); configuration.set("general.ProxyName", stats.getServerName()); configuration.set(
"general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins()); instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> { List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName); long maxPlayerToProxyLatenz = 0; long maxNeoToProxyLatenz = 0; long maxProxyToBackendLatenz = 0; long maxPlayerToNeoLatenz = 0; long avgPlayerToProxyLatenz = 0; long avgNeoToProxyLatenz = 0; long avgProxyToBackendLatenz = 0; long avgPlayerToNeoLatenz = 0; long minPlayerToProxyLatenz = Long.MAX_VALUE; long minNeoToProxyLatenz = Long.MAX_VALUE; long minProxyToBackendLatenz = Long.MAX_VALUE; long minPlayerToNeoLatenz = Long.MAX_VALUE; configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress()); configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress()); for (DebugPingResponse response : list) { if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz()) maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz()) maxNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz()) maxProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz()) maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz(); avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz(); avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz(); avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz(); if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz()) minPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (minNeoToProxyLatenz > response.getNeoToProxyLatenz()) minNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (minProxyToBackendLatenz > response.getProxyToBackendLatenz()) minProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz()) minPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); } configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz); configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size()); configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz); })); configuration.save(file); final String content = new String(Files.readAllBytes(file.toPath())); final String pasteKey = instance.getCore().getRestAPI().paste(content); instance.getCore().getDebugPingResponses().clear(); instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)"); if(pasteKey != null) { final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml"; instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null); } else { instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null); } instance.getCore().setDebugRunning(false); } catch (Exception ex) { instance.getCore().severe(ex.getMessage(), ex); } }); } }, 2000L * amount + 500); } private void gameshieldSelector() { instance.sendMessage(sender, localization.get(locale, "select.gameshield")); List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields(); for (Gameshield gameshield : gameshieldList) { instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgameshield " + gameshield.getId(), "SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId())); } } private void setGameshield(String[] args) { if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1])); return; } Config.setGameShieldID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1])); javaBackendSelector(); } private void javaBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); instance.sendMessage(sender, localization.get(locale, "select.backend", "java")); for (Backend backend : backendList) { if(backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setJavaBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1])); return; } Config.setBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1])); instance.getCore().getRestAPI().testCredentials(); bedrockBackendSelector(); } private void bedrockBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); if(backendList.stream().noneMatch(Backend::isGeyser))return; instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser")); for (Backend backend : backendList) { if(!backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgeyserbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setBedrockBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1])); return; } Config.setGeyserBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1])); if (instance.getCore().getPlayerInSetup().remove(sender)) { instance.sendMessage(sender, localization.get(locale, "setup.finished")); } } private void showHelp() { instance.sendMessage(sender, localization.get(locale, "available.commands")); instance.sendMessage(sender, " - /np setup"); instance.sendMessage(sender, " - /np ipanic"); instance.sendMessage(sender, " - /np analytics"); instance.sendMessage(sender, " - /np toggle (option)"); instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)"); instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)"); instance.sendMessage(sender, " - /np debugTool (cancel / amount)"); instance.sendMessage(sender, " - /np directConnectWhitelist (ip)"); instance.sendMessage(sender, " - /np setgameshield [id]"); instance.sendMessage(sender, " - /np setbackend [id]"); instance.sendMessage(sender, " - /np setgeyserbackend [id]"); } public static class ExecutorBuilder { private NeoProtectPlugin instance; private Object sender; private String[] args; private Locale local; private String msg; private boolean viaConsole; public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) { this.instance = instance; return this; } public ExecutorBuilder sender(Object sender) { this.sender = sender; return this; } public ExecutorBuilder args(String[] args) { this.args = args; return this; } public ExecutorBuilder local(Locale local) { this.local = local; return this; } public ExecutorBuilder msg(String msg) { this.msg = msg; return this; } public ExecutorBuilder viaConsole(boolean viaConsole) { this.viaConsole = viaConsole; return this; } public void executeChatEvent() { API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this)); } public void executeCommand() { API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this)); } public NeoProtectPlugin getInstance() { return instance; } public Object getSender() { return sender; } public String[] getArgs() { return args; } public Locale getLocal() { return local; } public String getMsg() { return msg; } public boolean isViaConsole() { return viaConsole; } } public static boolean isInteger(String input) { try { Integer.parseInt(input); return true; } catch (NumberFormatException e) { return false; } } }
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
NeoProtect-NeoPlugin-a71f673
[ { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/NeoProtectSpigot.java", "retrieved_chunk": " System.getProperty(\"os.arch\"),\n System.getProperty(\"os.version\"),\n getPluginVersion(),\n getCore().getVersionResult().getVersionStatus().toString(),\n Config.getAutoUpdaterSettings().toString(),\n getCore().isSetup() ? getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\",\n Arrays.toString(getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray()),\n getServer().getOnlinePlayers().size(),\n 0,\n Runtime.getRuntime().availableProcessors(),", "score": 0.8135497570037842 }, { "filename": "src/main/java/de/cubeattack/neoprotect/velocity/NeoProtectVelocity.java", "retrieved_chunk": " getProxy().getVersion().getVersion(),\n getProxy().getVersion().getName(),\n System.getProperty(\"java.version\"),\n System.getProperty(\"os.name\"),\n System.getProperty(\"os.arch\"),\n System.getProperty(\"os.version\"),\n getPluginVersion(),\n getCore().getVersionResult().getVersionStatus().toString(),\n Config.getAutoUpdaterSettings().toString(),\n getCore().isSetup() ? getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\",", "score": 0.8110814094543457 }, { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/NeoProtectBungee.java", "retrieved_chunk": " getProxy().getName(),\n System.getProperty(\"java.version\"),\n System.getProperty(\"os.name\"),\n System.getProperty(\"os.arch\"),\n System.getProperty(\"os.version\"),\n getDescription().getVersion(),\n getCore().getVersionResult().getVersionStatus().toString(),\n Config.getAutoUpdaterSettings().toString(),\n getCore().isSetup() ? getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\",\n Arrays.toString(getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray()),", "score": 0.809369683265686 }, { "filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java", "retrieved_chunk": " public static void loadConfig(Core core, FileUtils config) {\n Config.core = core;\n fileUtils = config;\n APIKey = config.getString(\"APIKey\", \"\");\n language = config.getString(\"defaultLanguage\", Locale.ENGLISH.toLanguageTag());\n proxyProtocol = config.getBoolean(\"ProxyProtocol\", true);\n gameShieldID = config.getString(\"gameshield.serverId\", \"\");\n backendID = config.getString(\"gameshield.backendId\", \"\");\n geyserBackendID = config.getString(\"gameshield.geyserBackendId\", \"\");\n updateIP = config.getBoolean(\"gameshield.autoUpdateIP\", false);", "score": 0.8083746433258057 }, { "filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java", "retrieved_chunk": " fileUtils.remove(\"AutoUpdater\");\n } else if (!fileUtils.getConfig().isSet(\"AutoUpdater\")) {\n fileUtils.getConfig().set(\"AutoUpdater\", \"ENABLED\");\n }\n List<String> description = new ArrayList<>();\n description.add(\"This setting is only for paid costumer and allow you to disable the AutoUpdater\");\n description.add(\"'ENABLED' (Recommended/Default) Update/Downgrade plugin to the current version \");\n description.add(\"'DISABLED' AutoUpdater just disabled\");\n description.add(\"'DEV' Only update to the latest version (Please never use this)\");\n fileUtils.getConfig().setComments(\"AutoUpdater\", description);", "score": 0.8056094646453857 } ]
java
"general.ProxyVersion", stats.getServerVersion());
package com.cursework.WebArtSell.Controllers; import com.cursework.WebArtSell.Models.User; import com.cursework.WebArtSell.Repositories.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import java.time.LocalDateTime; @Controller @RequestMapping("/registration") public class RegistrationController { @Autowired private UserRepository userRepository; @GetMapping public String getAllUsers(Model model) { model.addAttribute("users", userRepository.findAll()); return "registration"; } @PostMapping public String registerUser(@RequestParam String name, @RequestParam String email, @RequestParam String password, @RequestParam String confirm_password, Model model) { if (!password.equals(confirm_password)) { model.addAttribute("error", "Пароли не совпадают!"); return "registration"; } User user = new User(); user.setLogin(name); user.setEmail(email); user.setPassword(password); user.setRole("USER"); user.setCreationDate(LocalDateTime.now());
user.setStatus("Активный");
userRepository.save(user); return "redirect:/authorisation"; } }
src/main/java/com/cursework/WebArtSell/Controllers/RegistrationController.java
Neural-Enigma-Art-sales-Spring-Boot-57a8036
[ { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/AuthorisationController.java", "retrieved_chunk": " User user = optionalUser.get();\n HttpSession session = request.getSession();\n session.setAttribute(\"user\", user);\n if (user.getRole().equals(\"ADMIN\")) {\n return \"redirect:/table-users\";\n } else {\n return \"redirect:/main-user\";\n }\n } else {\n model.addAttribute(\"error\", \"Неверный email или пароль\");", "score": 0.8786124587059021 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/AuthorisationController.java", "retrieved_chunk": " model.addAttribute(\"users\", userRepository.findAll());\n return \"authorisation\";\n }\n @PostMapping\n public String userLogin(@RequestParam String email,\n @RequestParam String password,\n Model model,\n HttpServletRequest request) {\n Optional<User> optionalUser = userRepository.findByEmailAndPassword(email, password);\n if (optionalUser.isPresent()) {", "score": 0.8703610897064209 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/UserController.java", "retrieved_chunk": " model.addAttribute(\"statuses\", new String[]{\"Проверенный\", \"Непроверенный\"});\n model.addAttribute(\"roles\", new String[]{\"ADMIN\", \"USER\"});\n return \"table-users\";\n }\n @PostMapping(\"/edit/{id}\")\n public String editUser(@PathVariable(\"id\") Long id, @ModelAttribute User user, HttpSession session) {\n User currentUser = (User) session.getAttribute(\"user\");\n if (!currentUser.getId().equals(id)) {\n Optional<User> optUser = userRepository.findById(id);\n if (optUser.isPresent()) {", "score": 0.8498550653457642 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/UserController.java", "retrieved_chunk": " User existUser = optUser.get();\n existUser.setLogin(user.getLogin());\n existUser.setEmail(user.getEmail());\n existUser.setStatus(user.getStatus());\n existUser.setRole(user.getRole());\n userRepository.save(existUser);\n }\n }\n return \"redirect:/table-users\";\n }", "score": 0.8350686430931091 }, { "filename": "src/main/java/com/cursework/WebArtSell/Models/User.java", "retrieved_chunk": " private String email;\n @Column(unique = true, nullable = false)\n private String login;\n @Column(nullable = false)\n private String password;\n @Column(nullable = false)\n private String role;\n @Column(nullable = false)\n private LocalDateTime creationDate;\n @Column(nullable = false)", "score": 0.8272198438644409 } ]
java
user.setStatus("Активный");
package com.cursework.WebArtSell.Controllers; import com.cursework.WebArtSell.Models.User; import com.cursework.WebArtSell.Repositories.UserRepository; import jakarta.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.Optional; @Controller @RequestMapping("/table-users") public class UserController { @Autowired private UserRepository userRepository; @GetMapping public String getAllUsers(Model model, HttpSession session) { Iterable<User> users = userRepository.findAll(); User currentUser = (User) session.getAttribute("user"); model.addAttribute("users", users); model.addAttribute("currentUser", currentUser); model.addAttribute("statuses", new String[]{"Проверенный", "Непроверенный"}); model.addAttribute("roles", new String[]{"ADMIN", "USER"}); return "table-users"; } @PostMapping("/edit/{id}") public String editUser(@PathVariable("id") Long id, @ModelAttribute User user, HttpSession session) { User currentUser = (User) session.getAttribute("user"); if
(!currentUser.getId().equals(id)) {
Optional<User> optUser = userRepository.findById(id); if (optUser.isPresent()) { User existUser = optUser.get(); existUser.setLogin(user.getLogin()); existUser.setEmail(user.getEmail()); existUser.setStatus(user.getStatus()); existUser.setRole(user.getRole()); userRepository.save(existUser); } } return "redirect:/table-users"; } @PostMapping("/delete/{id}") public String deleteUser(@PathVariable("id") Long id, HttpSession session) { User currentUser = (User) session.getAttribute("user"); if (!currentUser.getId().equals(id)) { userRepository.deleteById(id); } return "redirect:/table-users"; } }
src/main/java/com/cursework/WebArtSell/Controllers/UserController.java
Neural-Enigma-Art-sales-Spring-Boot-57a8036
[ { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/AuthorisationController.java", "retrieved_chunk": " User user = optionalUser.get();\n HttpSession session = request.getSession();\n session.setAttribute(\"user\", user);\n if (user.getRole().equals(\"ADMIN\")) {\n return \"redirect:/table-users\";\n } else {\n return \"redirect:/main-user\";\n }\n } else {\n model.addAttribute(\"error\", \"Неверный email или пароль\");", "score": 0.8858745098114014 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/HomeController.java", "retrieved_chunk": " @GetMapping(\"/main-user\")\n public String getMainUserPage(Model model, HttpServletRequest request) {\n HttpSession session = request.getSession();\n User user = (User) session.getAttribute(\"user\");\n List<Product> products = productService.findAll();\n Long currentUserId = user.getId();\n for (Product product : products) {\n if (transactionService.isProductInTransactions(product)) {\n product.setDescription(\"Этот товар уже продан!\");\n product.setDisableButton(true);", "score": 0.8669787049293518 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/AuthorisationController.java", "retrieved_chunk": " model.addAttribute(\"users\", userRepository.findAll());\n return \"authorisation\";\n }\n @PostMapping\n public String userLogin(@RequestParam String email,\n @RequestParam String password,\n Model model,\n HttpServletRequest request) {\n Optional<User> optionalUser = userRepository.findByEmailAndPassword(email, password);\n if (optionalUser.isPresent()) {", "score": 0.8636394143104553 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/HomeController.java", "retrieved_chunk": " }\n if (product.getCreatedBy().getId().equals(currentUserId)) {\n product.setDescription(\"Это ваше объявление!\");\n product.setDisableButton(true);\n }\n }\n model.addAttribute(\"products\", products);\n return \"main-user\";\n }\n @GetMapping(\"/\")", "score": 0.8532736897468567 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/RegistrationController.java", "retrieved_chunk": " }\n @PostMapping\n public String registerUser(@RequestParam String name, @RequestParam String email, @RequestParam String password,\n @RequestParam String confirm_password, Model model) {\n if (!password.equals(confirm_password)) {\n model.addAttribute(\"error\", \"Пароли не совпадают!\");\n return \"registration\";\n }\n User user = new User();\n user.setLogin(name);", "score": 0.8517469167709351 } ]
java
(!currentUser.getId().equals(id)) {
package com.cursework.WebArtSell.Controllers; import com.cursework.WebArtSell.Models.Comment; import com.cursework.WebArtSell.Models.Product; import com.cursework.WebArtSell.Models.User; import com.cursework.WebArtSell.Repositories.CommentRepository; import com.cursework.WebArtSell.Repositories.ProductRepository; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; @Controller @RequestMapping("/table-products") public class ProductController { @Autowired private ProductRepository productRepository; @Autowired private CommentRepository commentRepository; @GetMapping public String getAllProducts(Model model) { List<Product> products = productRepository.findAll(); model.addAttribute("products", products); return "table-products"; } @GetMapping("/add") public String addAnnouncement() { return "product-add"; } @PostMapping("/add") public String createProduct(@ModelAttribute Product product, HttpServletRequest request) { HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); product.setCreatedBy(user); product.setCreationDate(LocalDateTime.now()); productRepository.save(product); return "redirect:/main-user"; } @GetMapping("/{id}") public String getProductById(@PathVariable long id, Model model) { Optional<Product> product = productRepository.findById(id); if (product.isPresent()) { List<Comment> comments = commentRepository.findByProductId(id); model.addAttribute("product", product.get()); model.addAttribute("comments", comments); return "product-details"; } return "redirect:/table-products"; } @GetMapping("/{id}/edit") public String editProduct(@PathVariable long id, Model model) { Optional<Product> product = productRepository.findById(id); if (product.isPresent()) { model.addAttribute("product", product.get()); return "product-edit"; } return "redirect:/table-products"; } @PostMapping("/{id}/edit") public String updateProduct(@PathVariable long id, @ModelAttribute Product updatedProduct) { Product product = productRepository.findById(id).orElseThrow(); product.setName(updatedProduct.getName()); product.setDescription(updatedProduct.getDescription()); product.setImageUrl(updatedProduct.getImageUrl()); product.setPrice(updatedProduct.getPrice());
product.setArtist(updatedProduct.getArtist());
product.setDimensions(updatedProduct.getDimensions()); productRepository.save(product); return "redirect:/table-products"; } @PostMapping("/{id}/remove") public String deleteProduct(@PathVariable long id) { productRepository.deleteById(id); return "redirect:/table-products"; } }
src/main/java/com/cursework/WebArtSell/Controllers/ProductController.java
Neural-Enigma-Art-sales-Spring-Boot-57a8036
[ { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java", "retrieved_chunk": " System.out.println(transaction.getSellerId());\n System.out.println(transaction.getPurchaseDate());\n System.out.println(transaction.getSum());\n transactionRepository.save(transaction);\n Optional<Product> product = productRepository.findById(productId);\n if (product.isPresent()) {\n model.addAttribute(\"product\", product.get());\n } else {\n return \"redirect:/main-user\";\n }", "score": 0.8742265701293945 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/CommentController.java", "retrieved_chunk": " public String addComment(@PathVariable long productId, @ModelAttribute Comment comment, HttpServletRequest request) {\n HttpSession session = request.getSession();\n User user = (User) session.getAttribute(\"user\");\n Product product = productRepository.findById(productId).orElseThrow();\n comment.setUser(user);\n comment.setProduct(product);\n comment.setCreationDate(LocalDateTime.now());\n commentRepository.save(comment);\n return \"redirect:/table-products/\" + productId;\n }", "score": 0.8624504208564758 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/CommentController.java", "retrieved_chunk": "import org.springframework.web.bind.annotation.*;\nimport java.time.LocalDateTime;\n@Controller\n@RequestMapping(\"/table-products/{productId}/comments\")\npublic class CommentController {\n @Autowired\n private CommentRepository commentRepository;\n @Autowired\n private ProductRepository productRepository;\n @PostMapping(\"/add\")", "score": 0.8597310185432434 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java", "retrieved_chunk": " model.addAttribute(\"product\", product.get());\n Transaction transaction = new Transaction();\n HttpSession session = request.getSession();\n User buyer = (User) session.getAttribute(\"user\");\n transaction.setBuyerId(buyer.getId());\n transaction.setSellerId(product.get().getCreatedBy().getId());\n transaction.setPurchaseDate(LocalDateTime.now());\n transaction.setSum(product.get().getPrice().doubleValue());\n transaction.setProductId(product.get().getId());\n model.addAttribute(\"transaction\", transaction);", "score": 0.8560115098953247 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java", "retrieved_chunk": " model.addAttribute(\"productId\", product.get().getId());\n } else {\n return \"redirect:/billing\";\n }\n return \"billing\";\n }\n @PostMapping(\"/billing-buy\")\n public String processTransaction(@ModelAttribute Transaction transaction, @RequestParam(\"productId\") Long productId, Model model, HttpServletRequest request) {\n try {\n System.out.println(transaction.getBuyerId());", "score": 0.8539908528327942 } ]
java
product.setArtist(updatedProduct.getArtist());
package com.cursework.WebArtSell.Controllers; import com.cursework.WebArtSell.Models.User; import com.cursework.WebArtSell.Repositories.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import java.time.LocalDateTime; @Controller @RequestMapping("/registration") public class RegistrationController { @Autowired private UserRepository userRepository; @GetMapping public String getAllUsers(Model model) { model.addAttribute("users", userRepository.findAll()); return "registration"; } @PostMapping public String registerUser(@RequestParam String name, @RequestParam String email, @RequestParam String password, @RequestParam String confirm_password, Model model) { if (!password.equals(confirm_password)) { model.addAttribute("error", "Пароли не совпадают!"); return "registration"; } User user = new User(); user.setLogin(name); user.setEmail(email); user.setPassword(password); user.setRole("USER");
user.setCreationDate(LocalDateTime.now());
user.setStatus("Активный"); userRepository.save(user); return "redirect:/authorisation"; } }
src/main/java/com/cursework/WebArtSell/Controllers/RegistrationController.java
Neural-Enigma-Art-sales-Spring-Boot-57a8036
[ { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/AuthorisationController.java", "retrieved_chunk": " User user = optionalUser.get();\n HttpSession session = request.getSession();\n session.setAttribute(\"user\", user);\n if (user.getRole().equals(\"ADMIN\")) {\n return \"redirect:/table-users\";\n } else {\n return \"redirect:/main-user\";\n }\n } else {\n model.addAttribute(\"error\", \"Неверный email или пароль\");", "score": 0.8581743836402893 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/AuthorisationController.java", "retrieved_chunk": " model.addAttribute(\"users\", userRepository.findAll());\n return \"authorisation\";\n }\n @PostMapping\n public String userLogin(@RequestParam String email,\n @RequestParam String password,\n Model model,\n HttpServletRequest request) {\n Optional<User> optionalUser = userRepository.findByEmailAndPassword(email, password);\n if (optionalUser.isPresent()) {", "score": 0.8538540601730347 }, { "filename": "src/main/java/com/cursework/WebArtSell/Models/User.java", "retrieved_chunk": " private String email;\n @Column(unique = true, nullable = false)\n private String login;\n @Column(nullable = false)\n private String password;\n @Column(nullable = false)\n private String role;\n @Column(nullable = false)\n private LocalDateTime creationDate;\n @Column(nullable = false)", "score": 0.8341982364654541 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/UserController.java", "retrieved_chunk": " model.addAttribute(\"statuses\", new String[]{\"Проверенный\", \"Непроверенный\"});\n model.addAttribute(\"roles\", new String[]{\"ADMIN\", \"USER\"});\n return \"table-users\";\n }\n @PostMapping(\"/edit/{id}\")\n public String editUser(@PathVariable(\"id\") Long id, @ModelAttribute User user, HttpSession session) {\n User currentUser = (User) session.getAttribute(\"user\");\n if (!currentUser.getId().equals(id)) {\n Optional<User> optUser = userRepository.findById(id);\n if (optUser.isPresent()) {", "score": 0.8240793347358704 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/UserController.java", "retrieved_chunk": " User existUser = optUser.get();\n existUser.setLogin(user.getLogin());\n existUser.setEmail(user.getEmail());\n existUser.setStatus(user.getStatus());\n existUser.setRole(user.getRole());\n userRepository.save(existUser);\n }\n }\n return \"redirect:/table-users\";\n }", "score": 0.8226650953292847 } ]
java
user.setCreationDate(LocalDateTime.now());
package com.cursework.WebArtSell.Controllers; import com.cursework.WebArtSell.Models.Product; import com.cursework.WebArtSell.Models.Transaction; import com.cursework.WebArtSell.Models.TransactionChartData; import com.cursework.WebArtSell.Models.User; import com.cursework.WebArtSell.Repositories.ProductRepository; import com.cursework.WebArtSell.Repositories.TransactionRepository; import com.cursework.WebArtSell.Services.TransactionService; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.time.LocalDateTime; import java.util.List; import java.util.Map; import java.util.Optional; @Controller public class TransactionController { @Autowired private TransactionService transactionService; @Autowired private TransactionRepository transactionRepository; @Autowired private ProductRepository productRepository; @GetMapping("/billing/{id}") public String authorisationModel(@PathVariable Long id, Model model, HttpServletRequest request) { Optional<Product> product = productRepository.findById(id); if (product.isPresent()) { model.addAttribute("product", product.get()); Transaction transaction = new Transaction(); HttpSession session = request.getSession(); User buyer = (User) session.getAttribute("user"); transaction.setBuyerId(buyer.getId()); transaction.setSellerId(product.get().getCreatedBy().getId()); transaction.setPurchaseDate(LocalDateTime.now()); transaction.setSum(product.get().getPrice().doubleValue()); transaction.setProductId(product.get().getId()); model.addAttribute("transaction", transaction); model.addAttribute(
"productId", product.get().getId());
} else { return "redirect:/billing"; } return "billing"; } @PostMapping("/billing-buy") public String processTransaction(@ModelAttribute Transaction transaction, @RequestParam("productId") Long productId, Model model, HttpServletRequest request) { try { System.out.println(transaction.getBuyerId()); System.out.println(transaction.getSellerId()); System.out.println(transaction.getPurchaseDate()); System.out.println(transaction.getSum()); transactionRepository.save(transaction); Optional<Product> product = productRepository.findById(productId); if (product.isPresent()) { model.addAttribute("product", product.get()); } else { return "redirect:/main-user"; } } catch (Exception e) { model.addAttribute("error", "Ошибка"); model.addAttribute("transaction", new Transaction()); Optional<Product> product = productRepository.findById(productId); if (product.isPresent()) { model.addAttribute("product", product.get()); HttpSession session = request.getSession(); User buyer = (User) session.getAttribute("user"); transaction.setBuyerId(buyer.getId()); transaction.setSellerId(product.get().getCreatedBy().getId()); transaction.setPurchaseDate(LocalDateTime.now()); transaction.setSum(product.get().getPrice().doubleValue()); transaction.setProductId(product.get().getId()); } return "billing"; } return "redirect:/main-user"; } @GetMapping("/api/transactions") public List<Transaction> getTransactions() { return transactionRepository.findAll(); } @GetMapping("/api/transactionChartData") public List<TransactionChartData> getTransactionChartData() { List<TransactionChartData> chartData = transactionRepository.findTransactionChartData(); System.out.println(chartData); return chartData; } @GetMapping("/table-transactions") public String transactions(Model model) { List<Transaction> transactions = transactionService.findAll(); Map<String, Double> chartData = transactionService.getMonthlySalesData(); model.addAttribute("transactions", transactions); model.addAttribute("chartData", chartData); return "table-transactions"; } }
src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java
Neural-Enigma-Art-sales-Spring-Boot-57a8036
[ { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/ProductController.java", "retrieved_chunk": " return \"product-add\";\n }\n @PostMapping(\"/add\")\n public String createProduct(@ModelAttribute Product product, HttpServletRequest request) {\n HttpSession session = request.getSession();\n User user = (User) session.getAttribute(\"user\");\n product.setCreatedBy(user);\n product.setCreationDate(LocalDateTime.now());\n productRepository.save(product);\n return \"redirect:/main-user\";", "score": 0.8856133818626404 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/HomeController.java", "retrieved_chunk": "package com.cursework.WebArtSell.Controllers;\nimport com.cursework.WebArtSell.Models.Product;\nimport com.cursework.WebArtSell.Models.User;\nimport com.cursework.WebArtSell.Services.ProductService;\nimport com.cursework.WebArtSell.Services.TransactionService;\nimport jakarta.servlet.http.HttpServletRequest;\nimport jakarta.servlet.http.HttpSession;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.web.bind.annotation.GetMapping;", "score": 0.870560348033905 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/HomeController.java", "retrieved_chunk": " @GetMapping(\"/main-user\")\n public String getMainUserPage(Model model, HttpServletRequest request) {\n HttpSession session = request.getSession();\n User user = (User) session.getAttribute(\"user\");\n List<Product> products = productService.findAll();\n Long currentUserId = user.getId();\n for (Product product : products) {\n if (transactionService.isProductInTransactions(product)) {\n product.setDescription(\"Этот товар уже продан!\");\n product.setDisableButton(true);", "score": 0.8574087619781494 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/HomeController.java", "retrieved_chunk": " return \"redirect:/authorisation\";\n }\n List<Product> products = productService.findAllByCategory(category);\n Long currentUserId = user.getId();\n for (Product product : products) {\n if (transactionService.isProductInTransactions(product)) {\n product.setDescription(\"Этот товар уже продан!\");\n product.setDisableButton(true);\n }\n if (product.getCreatedBy().getId().equals(currentUserId)) {", "score": 0.8567313551902771 }, { "filename": "src/main/java/com/cursework/WebArtSell/Models/Transaction.java", "retrieved_chunk": "package com.cursework.WebArtSell.Models;\nimport jakarta.persistence.*;\nimport org.springframework.data.annotation.Id;\nimport java.time.LocalDateTime;\n@Entity\n@Table(name = \"transaction\")\npublic class Transaction {\n @jakarta.persistence.Id\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)", "score": 0.8565388321876526 } ]
java
"productId", product.get().getId());
package de.cubeattack.neoprotect.core.executor; import de.cubeattack.api.API; import de.cubeattack.api.language.Localization; import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration; import de.cubeattack.api.libraries.org.json.JSONObject; import de.cubeattack.neoprotect.core.Config; import de.cubeattack.neoprotect.core.NeoProtectPlugin; import de.cubeattack.neoprotect.core.model.Backend; import de.cubeattack.neoprotect.core.model.Gameshield; import de.cubeattack.neoprotect.core.model.Stats; import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse; import java.io.File; import java.nio.file.Files; import java.sql.Timestamp; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.atomic.AtomicReference; public class NeoProtectExecutor { private static Timer debugTimer = new Timer(); private NeoProtectPlugin instance; private Localization localization; private Object sender; private Locale locale; private String msg; private String[] args; private boolean isViaConsole; private void initials(ExecutorBuilder executeBuilder) { this.instance = executeBuilder.getInstance(); this.localization = instance.getCore().getLocalization(); this.sender = executeBuilder.getSender(); this.locale = executeBuilder.getLocal(); this.args = executeBuilder.getArgs(); this.msg = executeBuilder.getMsg(); this.isViaConsole = executeBuilder.isViaConsole(); } private void chatEvent(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (instance.getCore().getRestAPI().isAPIInvalid(msg)) { instance.sendMessage(sender, localization.get(locale, "apikey.invalid")); return; } Config.setAPIKey(msg); instance.sendMessage(sender, localization.get(locale, "apikey.valid")); gameshieldSelector(); } private void command(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (args.length == 0) { showHelp(); return; } if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) { instance.sendMessage(sender, localization.get(locale, "setup.command.required")); return; } switch (args[0].toLowerCase()) { case "setup": { if (isViaConsole) { instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command")); } else { setup(); } break; } case "ipanic": { iPanic(args); break; } case "directconnectwhitelist": { directConnectWhitelist(args); break; } case "toggle": { toggle(args); break; } case "analytics": { analytics(); break; } case "whitelist": case "blacklist": { firewall(args); break; } case "debugtool": { debugTool(args); break; } case "setgameshield": { if (args.length == 1 && !isViaConsole) { gameshieldSelector(); } else if (args.length == 2) { setGameshield(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgameshield")); } break; } case "setbackend": { if (args.length == 1 && !isViaConsole) { javaBackendSelector(); } else if (args.length == 2) { setJavaBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setbackend")); } break; } case "setgeyserbackend": { if (args.length == 1 && !isViaConsole) { bedrockBackendSelector(); } else if (args.length == 2) { setBedrockBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend")); } break; } default: { showHelp(); } } } private void setup() { instance.getCore().getPlayerInSetup().add(sender); instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"), "OPEN_URL", "https://panel.neoprotect.net/profile", "SHOW_TEXT", localization.get(locale, "apikey.find")); } private void iPanic(String[] args) { if (args.length != 1) { instance.sendMessage(sender, localization.get(locale, "usage.ipanic")); } else { instance.sendMessage(sender, localization.get(locale, "command.ipanic", localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated"))); } } private void directConnectWhitelist(String[] args) { if (args.length == 2) { instance.getCore().getDirectConnectWhitelist().add(args[1]); instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1])); } else { instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist")); } } private void toggle(String[] args) { if (args.length != 2) { instance.sendMessage(sender, localization.get(locale, "usage.toggle")); } else { int response = instance.getCore().getRestAPI().toggle(args[1]); if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } if (response == -1) { instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'"); return; } instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1], localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated"))); } } private void analytics() { instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------"); JSONObject analytics = instance.getCore().getRestAPI().getAnalytics(); instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> { if (ak.equals("bandwidth")) { return; } if (ak.equals("traffic")) { instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " + new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s"); JSONObject traffic = instance.getCore().getRestAPI().getTraffic(); AtomicReference<String> trafficUsed = new AtomicReference<>(); AtomicReference<String> trafficAvailable = new AtomicReference<>(); traffic.keySet().forEach(bk -> { if (bk.equals("used")) { trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb"); } if (bk.equals("available")) { trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb"); } }); instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get()); return; } instance.sendMessage(sender, ak .replace("onlinePlayers", "online players") .replace("cps", "connections/s") + ": " + analytics.get(ak)); }); } private void firewall(String[] args) { if (args.length == 1) { instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----"); instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall -> instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")"))); } else if (args.length == 3) { String ip = args[2]; String action = args[1]; String mode = args[0].toUpperCase(); int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode); if (response == -1) { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); return; } if (response == 0) { instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode)); return; } if (response == 400) { instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip)); return; } if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")"); } else { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); } } @SuppressWarnings("ResultOfMethodCallIgnored") private void debugTool(String[] args) { if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) { instance.sendMessage(sender, localization.get(locale, "debug.spigot")); return; } if (args.length == 2) { if (args[1].equals("cancel")) { debugTimer.cancel(); instance.getCore().setDebugRunning(false); instance.sendMessage(sender, localization.get(locale, "debug.cancelled")); return; } if (!isInteger(args[1])) { instance.sendMessage(sender, localization.get(locale, "usage.debug")); return; } } if (instance.getCore().isDebugRunning()) { instance.sendMessage(sender, localization.get(locale, "debug.running")); return; } instance.getCore().setDebugRunning(true); instance.sendMessage(sender, localization.get(locale, "debug.starting")); int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5; debugTimer = new Timer(); debugTimer.schedule(new TimerTask() { int counter = 0; @Override public void run() { counter++; instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis())); instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")"); if (counter >= amount) this.cancel(); } }, 500, 2000); debugTimer.schedule(new TimerTask() { @Override public void run() { API.getExecutorService().submit(() -> { try { long startTime = System.currentTimeMillis(); Stats stats = instance.getStats(); File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml"); YamlConfiguration configuration = new YamlConfiguration(); if (!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } configuration.load(file); configuration.set("general.osName", System.getProperty("os.name")); configuration.set("general.javaVersion", System.getProperty("java.version")); configuration.set("general.pluginVersion", stats.getPluginVersion()); configuration.set("general.ProxyName"
, stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion()); configuration.set("general.ProxyPlugins", instance.getPlugins()); instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> { List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName); long maxPlayerToProxyLatenz = 0; long maxNeoToProxyLatenz = 0; long maxProxyToBackendLatenz = 0; long maxPlayerToNeoLatenz = 0; long avgPlayerToProxyLatenz = 0; long avgNeoToProxyLatenz = 0; long avgProxyToBackendLatenz = 0; long avgPlayerToNeoLatenz = 0; long minPlayerToProxyLatenz = Long.MAX_VALUE; long minNeoToProxyLatenz = Long.MAX_VALUE; long minProxyToBackendLatenz = Long.MAX_VALUE; long minPlayerToNeoLatenz = Long.MAX_VALUE; configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress()); configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress()); for (DebugPingResponse response : list) { if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz()) maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz()) maxNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz()) maxProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz()) maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz(); avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz(); avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz(); avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz(); if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz()) minPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (minNeoToProxyLatenz > response.getNeoToProxyLatenz()) minNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (minProxyToBackendLatenz > response.getProxyToBackendLatenz()) minProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz()) minPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); } configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz); configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size()); configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz); })); configuration.save(file); final String content = new String(Files.readAllBytes(file.toPath())); final String pasteKey = instance.getCore().getRestAPI().paste(content); instance.getCore().getDebugPingResponses().clear(); instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)"); if(pasteKey != null) { final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml"; instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null); } else { instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null); } instance.getCore().setDebugRunning(false); } catch (Exception ex) { instance.getCore().severe(ex.getMessage(), ex); } }); } }, 2000L * amount + 500); } private void gameshieldSelector() { instance.sendMessage(sender, localization.get(locale, "select.gameshield")); List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields(); for (Gameshield gameshield : gameshieldList) { instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgameshield " + gameshield.getId(), "SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId())); } } private void setGameshield(String[] args) { if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1])); return; } Config.setGameShieldID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1])); javaBackendSelector(); } private void javaBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); instance.sendMessage(sender, localization.get(locale, "select.backend", "java")); for (Backend backend : backendList) { if(backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setJavaBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1])); return; } Config.setBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1])); instance.getCore().getRestAPI().testCredentials(); bedrockBackendSelector(); } private void bedrockBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); if(backendList.stream().noneMatch(Backend::isGeyser))return; instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser")); for (Backend backend : backendList) { if(!backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgeyserbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setBedrockBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1])); return; } Config.setGeyserBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1])); if (instance.getCore().getPlayerInSetup().remove(sender)) { instance.sendMessage(sender, localization.get(locale, "setup.finished")); } } private void showHelp() { instance.sendMessage(sender, localization.get(locale, "available.commands")); instance.sendMessage(sender, " - /np setup"); instance.sendMessage(sender, " - /np ipanic"); instance.sendMessage(sender, " - /np analytics"); instance.sendMessage(sender, " - /np toggle (option)"); instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)"); instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)"); instance.sendMessage(sender, " - /np debugTool (cancel / amount)"); instance.sendMessage(sender, " - /np directConnectWhitelist (ip)"); instance.sendMessage(sender, " - /np setgameshield [id]"); instance.sendMessage(sender, " - /np setbackend [id]"); instance.sendMessage(sender, " - /np setgeyserbackend [id]"); } public static class ExecutorBuilder { private NeoProtectPlugin instance; private Object sender; private String[] args; private Locale local; private String msg; private boolean viaConsole; public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) { this.instance = instance; return this; } public ExecutorBuilder sender(Object sender) { this.sender = sender; return this; } public ExecutorBuilder args(String[] args) { this.args = args; return this; } public ExecutorBuilder local(Locale local) { this.local = local; return this; } public ExecutorBuilder msg(String msg) { this.msg = msg; return this; } public ExecutorBuilder viaConsole(boolean viaConsole) { this.viaConsole = viaConsole; return this; } public void executeChatEvent() { API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this)); } public void executeCommand() { API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this)); } public NeoProtectPlugin getInstance() { return instance; } public Object getSender() { return sender; } public String[] getArgs() { return args; } public Locale getLocal() { return local; } public String getMsg() { return msg; } public boolean isViaConsole() { return viaConsole; } } public static boolean isInteger(String input) { try { Integer.parseInt(input); return true; } catch (NumberFormatException e) { return false; } } }
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
NeoProtect-NeoPlugin-a71f673
[ { "filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java", "retrieved_chunk": " public static void loadConfig(Core core, FileUtils config) {\n Config.core = core;\n fileUtils = config;\n APIKey = config.getString(\"APIKey\", \"\");\n language = config.getString(\"defaultLanguage\", Locale.ENGLISH.toLanguageTag());\n proxyProtocol = config.getBoolean(\"ProxyProtocol\", true);\n gameShieldID = config.getString(\"gameshield.serverId\", \"\");\n backendID = config.getString(\"gameshield.backendId\", \"\");\n geyserBackendID = config.getString(\"gameshield.geyserBackendId\", \"\");\n updateIP = config.getBoolean(\"gameshield.autoUpdateIP\", false);", "score": 0.8170478343963623 }, { "filename": "src/main/java/de/cubeattack/neoprotect/spigot/NeoProtectSpigot.java", "retrieved_chunk": " System.getProperty(\"os.arch\"),\n System.getProperty(\"os.version\"),\n getPluginVersion(),\n getCore().getVersionResult().getVersionStatus().toString(),\n Config.getAutoUpdaterSettings().toString(),\n getCore().isSetup() ? getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\",\n Arrays.toString(getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray()),\n getServer().getOnlinePlayers().size(),\n 0,\n Runtime.getRuntime().availableProcessors(),", "score": 0.8080800771713257 }, { "filename": "src/main/java/de/cubeattack/neoprotect/velocity/NeoProtectVelocity.java", "retrieved_chunk": " getProxy().getVersion().getVersion(),\n getProxy().getVersion().getName(),\n System.getProperty(\"java.version\"),\n System.getProperty(\"os.name\"),\n System.getProperty(\"os.arch\"),\n System.getProperty(\"os.version\"),\n getPluginVersion(),\n getCore().getVersionResult().getVersionStatus().toString(),\n Config.getAutoUpdaterSettings().toString(),\n getCore().isSetup() ? getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\",", "score": 0.8067960739135742 }, { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/NeoProtectBungee.java", "retrieved_chunk": " getProxy().getName(),\n System.getProperty(\"java.version\"),\n System.getProperty(\"os.name\"),\n System.getProperty(\"os.arch\"),\n System.getProperty(\"os.version\"),\n getDescription().getVersion(),\n getCore().getVersionResult().getVersionStatus().toString(),\n Config.getAutoUpdaterSettings().toString(),\n getCore().isSetup() ? getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\",\n Arrays.toString(getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray()),", "score": 0.8050071597099304 }, { "filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java", "retrieved_chunk": " debugMode = config.getBoolean(\"DebugMode\", false);\n geyserServerIP = config.getString(\"geyserServerIP\", \"127.0.0.1\");\n if (APIKey.length() != 64) {\n core.severe(\"Failed to load API-Key. Key is null or not valid\");\n return;\n }\n if (gameShieldID.isEmpty()) {\n core.severe(\"Failed to load GameshieldID. ID is null\");\n return;\n }", "score": 0.8038177490234375 } ]
java
, stats.getServerName());
package com.cursework.WebArtSell.Controllers; import com.cursework.WebArtSell.Models.Comment; import com.cursework.WebArtSell.Models.Product; import com.cursework.WebArtSell.Models.User; import com.cursework.WebArtSell.Repositories.CommentRepository; import com.cursework.WebArtSell.Repositories.ProductRepository; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; @Controller @RequestMapping("/table-products") public class ProductController { @Autowired private ProductRepository productRepository; @Autowired private CommentRepository commentRepository; @GetMapping public String getAllProducts(Model model) { List<Product> products = productRepository.findAll(); model.addAttribute("products", products); return "table-products"; } @GetMapping("/add") public String addAnnouncement() { return "product-add"; } @PostMapping("/add") public String createProduct(@ModelAttribute Product product, HttpServletRequest request) { HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); product.setCreatedBy(user); product.setCreationDate(LocalDateTime.now()); productRepository.save(product); return "redirect:/main-user"; } @GetMapping("/{id}") public String getProductById(@PathVariable long id, Model model) { Optional<Product> product = productRepository.findById(id); if (product.isPresent()) { List<Comment> comments = commentRepository.findByProductId(id); model.addAttribute("product", product.get()); model.addAttribute("comments", comments); return "product-details"; } return "redirect:/table-products"; } @GetMapping("/{id}/edit") public String editProduct(@PathVariable long id, Model model) { Optional<Product> product = productRepository.findById(id); if (product.isPresent()) { model.addAttribute("product", product.get()); return "product-edit"; } return "redirect:/table-products"; } @PostMapping("/{id}/edit") public String updateProduct(@PathVariable long id, @ModelAttribute Product updatedProduct) { Product product = productRepository.findById(id).orElseThrow(); product.setName(updatedProduct.getName()); product.setDescription(updatedProduct.getDescription()); product.
setImageUrl(updatedProduct.getImageUrl());
product.setPrice(updatedProduct.getPrice()); product.setArtist(updatedProduct.getArtist()); product.setDimensions(updatedProduct.getDimensions()); productRepository.save(product); return "redirect:/table-products"; } @PostMapping("/{id}/remove") public String deleteProduct(@PathVariable long id) { productRepository.deleteById(id); return "redirect:/table-products"; } }
src/main/java/com/cursework/WebArtSell/Controllers/ProductController.java
Neural-Enigma-Art-sales-Spring-Boot-57a8036
[ { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java", "retrieved_chunk": " System.out.println(transaction.getSellerId());\n System.out.println(transaction.getPurchaseDate());\n System.out.println(transaction.getSum());\n transactionRepository.save(transaction);\n Optional<Product> product = productRepository.findById(productId);\n if (product.isPresent()) {\n model.addAttribute(\"product\", product.get());\n } else {\n return \"redirect:/main-user\";\n }", "score": 0.8723671436309814 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/CommentController.java", "retrieved_chunk": " public String addComment(@PathVariable long productId, @ModelAttribute Comment comment, HttpServletRequest request) {\n HttpSession session = request.getSession();\n User user = (User) session.getAttribute(\"user\");\n Product product = productRepository.findById(productId).orElseThrow();\n comment.setUser(user);\n comment.setProduct(product);\n comment.setCreationDate(LocalDateTime.now());\n commentRepository.save(comment);\n return \"redirect:/table-products/\" + productId;\n }", "score": 0.8611082434654236 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/CommentController.java", "retrieved_chunk": "import org.springframework.web.bind.annotation.*;\nimport java.time.LocalDateTime;\n@Controller\n@RequestMapping(\"/table-products/{productId}/comments\")\npublic class CommentController {\n @Autowired\n private CommentRepository commentRepository;\n @Autowired\n private ProductRepository productRepository;\n @PostMapping(\"/add\")", "score": 0.85956871509552 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java", "retrieved_chunk": " } catch (Exception e) {\n model.addAttribute(\"error\", \"Ошибка\");\n model.addAttribute(\"transaction\", new Transaction());\n Optional<Product> product = productRepository.findById(productId);\n if (product.isPresent()) {\n model.addAttribute(\"product\", product.get());\n HttpSession session = request.getSession();\n User buyer = (User) session.getAttribute(\"user\");\n transaction.setBuyerId(buyer.getId());\n transaction.setSellerId(product.get().getCreatedBy().getId());", "score": 0.8538027405738831 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java", "retrieved_chunk": " model.addAttribute(\"product\", product.get());\n Transaction transaction = new Transaction();\n HttpSession session = request.getSession();\n User buyer = (User) session.getAttribute(\"user\");\n transaction.setBuyerId(buyer.getId());\n transaction.setSellerId(product.get().getCreatedBy().getId());\n transaction.setPurchaseDate(LocalDateTime.now());\n transaction.setSum(product.get().getPrice().doubleValue());\n transaction.setProductId(product.get().getId());\n model.addAttribute(\"transaction\", transaction);", "score": 0.8534720540046692 } ]
java
setImageUrl(updatedProduct.getImageUrl());
package com.cursework.WebArtSell.Controllers; import com.cursework.WebArtSell.Models.Comment; import com.cursework.WebArtSell.Models.Product; import com.cursework.WebArtSell.Models.User; import com.cursework.WebArtSell.Repositories.CommentRepository; import com.cursework.WebArtSell.Repositories.ProductRepository; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; @Controller @RequestMapping("/table-products") public class ProductController { @Autowired private ProductRepository productRepository; @Autowired private CommentRepository commentRepository; @GetMapping public String getAllProducts(Model model) { List<Product> products = productRepository.findAll(); model.addAttribute("products", products); return "table-products"; } @GetMapping("/add") public String addAnnouncement() { return "product-add"; } @PostMapping("/add") public String createProduct(@ModelAttribute Product product, HttpServletRequest request) { HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); product.setCreatedBy(user); product.setCreationDate(LocalDateTime.now()); productRepository.save(product); return "redirect:/main-user"; } @GetMapping("/{id}") public String getProductById(@PathVariable long id, Model model) { Optional<Product> product = productRepository.findById(id); if (product.isPresent()) {
List<Comment> comments = commentRepository.findByProductId(id);
model.addAttribute("product", product.get()); model.addAttribute("comments", comments); return "product-details"; } return "redirect:/table-products"; } @GetMapping("/{id}/edit") public String editProduct(@PathVariable long id, Model model) { Optional<Product> product = productRepository.findById(id); if (product.isPresent()) { model.addAttribute("product", product.get()); return "product-edit"; } return "redirect:/table-products"; } @PostMapping("/{id}/edit") public String updateProduct(@PathVariable long id, @ModelAttribute Product updatedProduct) { Product product = productRepository.findById(id).orElseThrow(); product.setName(updatedProduct.getName()); product.setDescription(updatedProduct.getDescription()); product.setImageUrl(updatedProduct.getImageUrl()); product.setPrice(updatedProduct.getPrice()); product.setArtist(updatedProduct.getArtist()); product.setDimensions(updatedProduct.getDimensions()); productRepository.save(product); return "redirect:/table-products"; } @PostMapping("/{id}/remove") public String deleteProduct(@PathVariable long id) { productRepository.deleteById(id); return "redirect:/table-products"; } }
src/main/java/com/cursework/WebArtSell/Controllers/ProductController.java
Neural-Enigma-Art-sales-Spring-Boot-57a8036
[ { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/CommentController.java", "retrieved_chunk": " public String addComment(@PathVariable long productId, @ModelAttribute Comment comment, HttpServletRequest request) {\n HttpSession session = request.getSession();\n User user = (User) session.getAttribute(\"user\");\n Product product = productRepository.findById(productId).orElseThrow();\n comment.setUser(user);\n comment.setProduct(product);\n comment.setCreationDate(LocalDateTime.now());\n commentRepository.save(comment);\n return \"redirect:/table-products/\" + productId;\n }", "score": 0.8863608837127686 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java", "retrieved_chunk": " model.addAttribute(\"product\", product.get());\n Transaction transaction = new Transaction();\n HttpSession session = request.getSession();\n User buyer = (User) session.getAttribute(\"user\");\n transaction.setBuyerId(buyer.getId());\n transaction.setSellerId(product.get().getCreatedBy().getId());\n transaction.setPurchaseDate(LocalDateTime.now());\n transaction.setSum(product.get().getPrice().doubleValue());\n transaction.setProductId(product.get().getId());\n model.addAttribute(\"transaction\", transaction);", "score": 0.8861926794052124 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/CommentController.java", "retrieved_chunk": "import org.springframework.web.bind.annotation.*;\nimport java.time.LocalDateTime;\n@Controller\n@RequestMapping(\"/table-products/{productId}/comments\")\npublic class CommentController {\n @Autowired\n private CommentRepository commentRepository;\n @Autowired\n private ProductRepository productRepository;\n @PostMapping(\"/add\")", "score": 0.8798239231109619 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java", "retrieved_chunk": " @Autowired\n private TransactionService transactionService;\n @Autowired\n private TransactionRepository transactionRepository;\n @Autowired\n private ProductRepository productRepository;\n @GetMapping(\"/billing/{id}\")\n public String authorisationModel(@PathVariable Long id, Model model, HttpServletRequest request) {\n Optional<Product> product = productRepository.findById(id);\n if (product.isPresent()) {", "score": 0.8794588446617126 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java", "retrieved_chunk": " System.out.println(transaction.getSellerId());\n System.out.println(transaction.getPurchaseDate());\n System.out.println(transaction.getSum());\n transactionRepository.save(transaction);\n Optional<Product> product = productRepository.findById(productId);\n if (product.isPresent()) {\n model.addAttribute(\"product\", product.get());\n } else {\n return \"redirect:/main-user\";\n }", "score": 0.8760628700256348 } ]
java
List<Comment> comments = commentRepository.findByProductId(id);
package com.cursework.WebArtSell.Controllers; import com.cursework.WebArtSell.Models.Comment; import com.cursework.WebArtSell.Models.Product; import com.cursework.WebArtSell.Models.User; import com.cursework.WebArtSell.Repositories.CommentRepository; import com.cursework.WebArtSell.Repositories.ProductRepository; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; @Controller @RequestMapping("/table-products") public class ProductController { @Autowired private ProductRepository productRepository; @Autowired private CommentRepository commentRepository; @GetMapping public String getAllProducts(Model model) { List<Product> products = productRepository.findAll(); model.addAttribute("products", products); return "table-products"; } @GetMapping("/add") public String addAnnouncement() { return "product-add"; } @PostMapping("/add") public String createProduct(@ModelAttribute Product product, HttpServletRequest request) { HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); product.setCreatedBy(user);
product.setCreationDate(LocalDateTime.now());
productRepository.save(product); return "redirect:/main-user"; } @GetMapping("/{id}") public String getProductById(@PathVariable long id, Model model) { Optional<Product> product = productRepository.findById(id); if (product.isPresent()) { List<Comment> comments = commentRepository.findByProductId(id); model.addAttribute("product", product.get()); model.addAttribute("comments", comments); return "product-details"; } return "redirect:/table-products"; } @GetMapping("/{id}/edit") public String editProduct(@PathVariable long id, Model model) { Optional<Product> product = productRepository.findById(id); if (product.isPresent()) { model.addAttribute("product", product.get()); return "product-edit"; } return "redirect:/table-products"; } @PostMapping("/{id}/edit") public String updateProduct(@PathVariable long id, @ModelAttribute Product updatedProduct) { Product product = productRepository.findById(id).orElseThrow(); product.setName(updatedProduct.getName()); product.setDescription(updatedProduct.getDescription()); product.setImageUrl(updatedProduct.getImageUrl()); product.setPrice(updatedProduct.getPrice()); product.setArtist(updatedProduct.getArtist()); product.setDimensions(updatedProduct.getDimensions()); productRepository.save(product); return "redirect:/table-products"; } @PostMapping("/{id}/remove") public String deleteProduct(@PathVariable long id) { productRepository.deleteById(id); return "redirect:/table-products"; } }
src/main/java/com/cursework/WebArtSell/Controllers/ProductController.java
Neural-Enigma-Art-sales-Spring-Boot-57a8036
[ { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/CommentController.java", "retrieved_chunk": " public String addComment(@PathVariable long productId, @ModelAttribute Comment comment, HttpServletRequest request) {\n HttpSession session = request.getSession();\n User user = (User) session.getAttribute(\"user\");\n Product product = productRepository.findById(productId).orElseThrow();\n comment.setUser(user);\n comment.setProduct(product);\n comment.setCreationDate(LocalDateTime.now());\n commentRepository.save(comment);\n return \"redirect:/table-products/\" + productId;\n }", "score": 0.8852087259292603 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java", "retrieved_chunk": " model.addAttribute(\"product\", product.get());\n Transaction transaction = new Transaction();\n HttpSession session = request.getSession();\n User buyer = (User) session.getAttribute(\"user\");\n transaction.setBuyerId(buyer.getId());\n transaction.setSellerId(product.get().getCreatedBy().getId());\n transaction.setPurchaseDate(LocalDateTime.now());\n transaction.setSum(product.get().getPrice().doubleValue());\n transaction.setProductId(product.get().getId());\n model.addAttribute(\"transaction\", transaction);", "score": 0.8801553845405579 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/HomeController.java", "retrieved_chunk": " product.setDescription(\"Это ваше объявление!\");\n product.setDisableButton(true);\n }\n }\n model.addAttribute(\"products\", products);\n return \"main-user\";\n }\n}", "score": 0.8724651336669922 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/CommentController.java", "retrieved_chunk": "import org.springframework.web.bind.annotation.*;\nimport java.time.LocalDateTime;\n@Controller\n@RequestMapping(\"/table-products/{productId}/comments\")\npublic class CommentController {\n @Autowired\n private CommentRepository commentRepository;\n @Autowired\n private ProductRepository productRepository;\n @PostMapping(\"/add\")", "score": 0.8717761039733887 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/HomeController.java", "retrieved_chunk": " }\n if (product.getCreatedBy().getId().equals(currentUserId)) {\n product.setDescription(\"Это ваше объявление!\");\n product.setDisableButton(true);\n }\n }\n model.addAttribute(\"products\", products);\n return \"main-user\";\n }\n @GetMapping(\"/\")", "score": 0.8708240985870361 } ]
java
product.setCreationDate(LocalDateTime.now());
package com.cursework.WebArtSell.Controllers; import com.cursework.WebArtSell.Models.User; import com.cursework.WebArtSell.Repositories.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import java.time.LocalDateTime; @Controller @RequestMapping("/registration") public class RegistrationController { @Autowired private UserRepository userRepository; @GetMapping public String getAllUsers(Model model) { model.addAttribute("users", userRepository.findAll()); return "registration"; } @PostMapping public String registerUser(@RequestParam String name, @RequestParam String email, @RequestParam String password, @RequestParam String confirm_password, Model model) { if (!password.equals(confirm_password)) { model.addAttribute("error", "Пароли не совпадают!"); return "registration"; } User user = new User(); user.setLogin(name); user.setEmail(email); user.setPassword(password);
user.setRole("USER");
user.setCreationDate(LocalDateTime.now()); user.setStatus("Активный"); userRepository.save(user); return "redirect:/authorisation"; } }
src/main/java/com/cursework/WebArtSell/Controllers/RegistrationController.java
Neural-Enigma-Art-sales-Spring-Boot-57a8036
[ { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/AuthorisationController.java", "retrieved_chunk": " model.addAttribute(\"users\", userRepository.findAll());\n return \"authorisation\";\n }\n @PostMapping\n public String userLogin(@RequestParam String email,\n @RequestParam String password,\n Model model,\n HttpServletRequest request) {\n Optional<User> optionalUser = userRepository.findByEmailAndPassword(email, password);\n if (optionalUser.isPresent()) {", "score": 0.8480586409568787 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/AuthorisationController.java", "retrieved_chunk": " User user = optionalUser.get();\n HttpSession session = request.getSession();\n session.setAttribute(\"user\", user);\n if (user.getRole().equals(\"ADMIN\")) {\n return \"redirect:/table-users\";\n } else {\n return \"redirect:/main-user\";\n }\n } else {\n model.addAttribute(\"error\", \"Неверный email или пароль\");", "score": 0.8431957960128784 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/UserController.java", "retrieved_chunk": " model.addAttribute(\"statuses\", new String[]{\"Проверенный\", \"Непроверенный\"});\n model.addAttribute(\"roles\", new String[]{\"ADMIN\", \"USER\"});\n return \"table-users\";\n }\n @PostMapping(\"/edit/{id}\")\n public String editUser(@PathVariable(\"id\") Long id, @ModelAttribute User user, HttpSession session) {\n User currentUser = (User) session.getAttribute(\"user\");\n if (!currentUser.getId().equals(id)) {\n Optional<User> optUser = userRepository.findById(id);\n if (optUser.isPresent()) {", "score": 0.8197588920593262 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/UserController.java", "retrieved_chunk": " User existUser = optUser.get();\n existUser.setLogin(user.getLogin());\n existUser.setEmail(user.getEmail());\n existUser.setStatus(user.getStatus());\n existUser.setRole(user.getRole());\n userRepository.save(existUser);\n }\n }\n return \"redirect:/table-users\";\n }", "score": 0.7999150156974792 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java", "retrieved_chunk": " } catch (Exception e) {\n model.addAttribute(\"error\", \"Ошибка\");\n model.addAttribute(\"transaction\", new Transaction());\n Optional<Product> product = productRepository.findById(productId);\n if (product.isPresent()) {\n model.addAttribute(\"product\", product.get());\n HttpSession session = request.getSession();\n User buyer = (User) session.getAttribute(\"user\");\n transaction.setBuyerId(buyer.getId());\n transaction.setSellerId(product.get().getCreatedBy().getId());", "score": 0.7902277112007141 } ]
java
user.setRole("USER");
package com.cursework.WebArtSell.Controllers; import com.cursework.WebArtSell.Models.Product; import com.cursework.WebArtSell.Models.Transaction; import com.cursework.WebArtSell.Models.TransactionChartData; import com.cursework.WebArtSell.Models.User; import com.cursework.WebArtSell.Repositories.ProductRepository; import com.cursework.WebArtSell.Repositories.TransactionRepository; import com.cursework.WebArtSell.Services.TransactionService; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.time.LocalDateTime; import java.util.List; import java.util.Map; import java.util.Optional; @Controller public class TransactionController { @Autowired private TransactionService transactionService; @Autowired private TransactionRepository transactionRepository; @Autowired private ProductRepository productRepository; @GetMapping("/billing/{id}") public String authorisationModel(@PathVariable Long id, Model model, HttpServletRequest request) { Optional<Product> product = productRepository.findById(id); if (product.isPresent()) { model.addAttribute("product", product.get()); Transaction transaction = new Transaction(); HttpSession session = request.getSession(); User buyer = (User) session.getAttribute("user"); transaction.setBuyerId(buyer.getId()); transaction.setSellerId(product.get().getCreatedBy().getId()); transaction.setPurchaseDate(LocalDateTime.now()); transaction.setSum(
product.get().getPrice().doubleValue());
transaction.setProductId(product.get().getId()); model.addAttribute("transaction", transaction); model.addAttribute("productId", product.get().getId()); } else { return "redirect:/billing"; } return "billing"; } @PostMapping("/billing-buy") public String processTransaction(@ModelAttribute Transaction transaction, @RequestParam("productId") Long productId, Model model, HttpServletRequest request) { try { System.out.println(transaction.getBuyerId()); System.out.println(transaction.getSellerId()); System.out.println(transaction.getPurchaseDate()); System.out.println(transaction.getSum()); transactionRepository.save(transaction); Optional<Product> product = productRepository.findById(productId); if (product.isPresent()) { model.addAttribute("product", product.get()); } else { return "redirect:/main-user"; } } catch (Exception e) { model.addAttribute("error", "Ошибка"); model.addAttribute("transaction", new Transaction()); Optional<Product> product = productRepository.findById(productId); if (product.isPresent()) { model.addAttribute("product", product.get()); HttpSession session = request.getSession(); User buyer = (User) session.getAttribute("user"); transaction.setBuyerId(buyer.getId()); transaction.setSellerId(product.get().getCreatedBy().getId()); transaction.setPurchaseDate(LocalDateTime.now()); transaction.setSum(product.get().getPrice().doubleValue()); transaction.setProductId(product.get().getId()); } return "billing"; } return "redirect:/main-user"; } @GetMapping("/api/transactions") public List<Transaction> getTransactions() { return transactionRepository.findAll(); } @GetMapping("/api/transactionChartData") public List<TransactionChartData> getTransactionChartData() { List<TransactionChartData> chartData = transactionRepository.findTransactionChartData(); System.out.println(chartData); return chartData; } @GetMapping("/table-transactions") public String transactions(Model model) { List<Transaction> transactions = transactionService.findAll(); Map<String, Double> chartData = transactionService.getMonthlySalesData(); model.addAttribute("transactions", transactions); model.addAttribute("chartData", chartData); return "table-transactions"; } }
src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java
Neural-Enigma-Art-sales-Spring-Boot-57a8036
[ { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/ProductController.java", "retrieved_chunk": " return \"product-add\";\n }\n @PostMapping(\"/add\")\n public String createProduct(@ModelAttribute Product product, HttpServletRequest request) {\n HttpSession session = request.getSession();\n User user = (User) session.getAttribute(\"user\");\n product.setCreatedBy(user);\n product.setCreationDate(LocalDateTime.now());\n productRepository.save(product);\n return \"redirect:/main-user\";", "score": 0.8944915533065796 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/HomeController.java", "retrieved_chunk": "package com.cursework.WebArtSell.Controllers;\nimport com.cursework.WebArtSell.Models.Product;\nimport com.cursework.WebArtSell.Models.User;\nimport com.cursework.WebArtSell.Services.ProductService;\nimport com.cursework.WebArtSell.Services.TransactionService;\nimport jakarta.servlet.http.HttpServletRequest;\nimport jakarta.servlet.http.HttpSession;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.web.bind.annotation.GetMapping;", "score": 0.8776760101318359 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/ProductController.java", "retrieved_chunk": " productRepository.save(product);\n return \"redirect:/table-products\";\n }\n @PostMapping(\"/{id}/remove\")\n public String deleteProduct(@PathVariable long id) {\n productRepository.deleteById(id);\n return \"redirect:/table-products\";\n }\n}", "score": 0.8696106672286987 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/HomeController.java", "retrieved_chunk": " return \"redirect:/authorisation\";\n }\n List<Product> products = productService.findAllByCategory(category);\n Long currentUserId = user.getId();\n for (Product product : products) {\n if (transactionService.isProductInTransactions(product)) {\n product.setDescription(\"Этот товар уже продан!\");\n product.setDisableButton(true);\n }\n if (product.getCreatedBy().getId().equals(currentUserId)) {", "score": 0.8668693900108337 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/HomeController.java", "retrieved_chunk": " @GetMapping(\"/main-user\")\n public String getMainUserPage(Model model, HttpServletRequest request) {\n HttpSession session = request.getSession();\n User user = (User) session.getAttribute(\"user\");\n List<Product> products = productService.findAll();\n Long currentUserId = user.getId();\n for (Product product : products) {\n if (transactionService.isProductInTransactions(product)) {\n product.setDescription(\"Этот товар уже продан!\");\n product.setDisableButton(true);", "score": 0.8665501475334167 } ]
java
product.get().getPrice().doubleValue());
package com.cursework.WebArtSell.Controllers; import com.cursework.WebArtSell.Models.Product; import com.cursework.WebArtSell.Models.Transaction; import com.cursework.WebArtSell.Models.TransactionChartData; import com.cursework.WebArtSell.Models.User; import com.cursework.WebArtSell.Repositories.ProductRepository; import com.cursework.WebArtSell.Repositories.TransactionRepository; import com.cursework.WebArtSell.Services.TransactionService; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.time.LocalDateTime; import java.util.List; import java.util.Map; import java.util.Optional; @Controller public class TransactionController { @Autowired private TransactionService transactionService; @Autowired private TransactionRepository transactionRepository; @Autowired private ProductRepository productRepository; @GetMapping("/billing/{id}") public String authorisationModel(@PathVariable Long id, Model model, HttpServletRequest request) { Optional<Product> product = productRepository.findById(id); if (product.isPresent()) { model.addAttribute("product", product.get()); Transaction transaction = new Transaction(); HttpSession session = request.getSession(); User buyer = (User) session.getAttribute("user"); transaction.setBuyerId(buyer.getId()); transaction.setSellerId(product.get().getCreatedBy().getId()); transaction.setPurchaseDate(LocalDateTime.now()); transaction.setSum(product.get().getPrice().doubleValue()); transaction.setProductId(product.get().getId()); model.addAttribute("transaction", transaction); model.addAttribute("productId", product.get().getId()); } else { return "redirect:/billing"; } return "billing"; } @PostMapping("/billing-buy") public String processTransaction(@ModelAttribute Transaction transaction, @RequestParam("productId") Long productId, Model model, HttpServletRequest request) { try {
System.out.println(transaction.getBuyerId());
System.out.println(transaction.getSellerId()); System.out.println(transaction.getPurchaseDate()); System.out.println(transaction.getSum()); transactionRepository.save(transaction); Optional<Product> product = productRepository.findById(productId); if (product.isPresent()) { model.addAttribute("product", product.get()); } else { return "redirect:/main-user"; } } catch (Exception e) { model.addAttribute("error", "Ошибка"); model.addAttribute("transaction", new Transaction()); Optional<Product> product = productRepository.findById(productId); if (product.isPresent()) { model.addAttribute("product", product.get()); HttpSession session = request.getSession(); User buyer = (User) session.getAttribute("user"); transaction.setBuyerId(buyer.getId()); transaction.setSellerId(product.get().getCreatedBy().getId()); transaction.setPurchaseDate(LocalDateTime.now()); transaction.setSum(product.get().getPrice().doubleValue()); transaction.setProductId(product.get().getId()); } return "billing"; } return "redirect:/main-user"; } @GetMapping("/api/transactions") public List<Transaction> getTransactions() { return transactionRepository.findAll(); } @GetMapping("/api/transactionChartData") public List<TransactionChartData> getTransactionChartData() { List<TransactionChartData> chartData = transactionRepository.findTransactionChartData(); System.out.println(chartData); return chartData; } @GetMapping("/table-transactions") public String transactions(Model model) { List<Transaction> transactions = transactionService.findAll(); Map<String, Double> chartData = transactionService.getMonthlySalesData(); model.addAttribute("transactions", transactions); model.addAttribute("chartData", chartData); return "table-transactions"; } }
src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java
Neural-Enigma-Art-sales-Spring-Boot-57a8036
[ { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/ProductController.java", "retrieved_chunk": " return \"product-add\";\n }\n @PostMapping(\"/add\")\n public String createProduct(@ModelAttribute Product product, HttpServletRequest request) {\n HttpSession session = request.getSession();\n User user = (User) session.getAttribute(\"user\");\n product.setCreatedBy(user);\n product.setCreationDate(LocalDateTime.now());\n productRepository.save(product);\n return \"redirect:/main-user\";", "score": 0.871383547782898 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/HomeController.java", "retrieved_chunk": "package com.cursework.WebArtSell.Controllers;\nimport com.cursework.WebArtSell.Models.Product;\nimport com.cursework.WebArtSell.Models.User;\nimport com.cursework.WebArtSell.Services.ProductService;\nimport com.cursework.WebArtSell.Services.TransactionService;\nimport jakarta.servlet.http.HttpServletRequest;\nimport jakarta.servlet.http.HttpSession;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.web.bind.annotation.GetMapping;", "score": 0.8607673645019531 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/ProductController.java", "retrieved_chunk": " return \"redirect:/table-products\";\n }\n @GetMapping(\"/{id}/edit\")\n public String editProduct(@PathVariable long id, Model model) {\n Optional<Product> product = productRepository.findById(id);\n if (product.isPresent()) {\n model.addAttribute(\"product\", product.get());\n return \"product-edit\";\n }\n return \"redirect:/table-products\";", "score": 0.858039379119873 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/ProductController.java", "retrieved_chunk": " productRepository.save(product);\n return \"redirect:/table-products\";\n }\n @PostMapping(\"/{id}/remove\")\n public String deleteProduct(@PathVariable long id) {\n productRepository.deleteById(id);\n return \"redirect:/table-products\";\n }\n}", "score": 0.854795515537262 }, { "filename": "src/main/java/com/cursework/WebArtSell/Controllers/HomeController.java", "retrieved_chunk": " return \"redirect:/authorisation\";\n }\n List<Product> products = productService.findAllByCategory(category);\n Long currentUserId = user.getId();\n for (Product product : products) {\n if (transactionService.isProductInTransactions(product)) {\n product.setDescription(\"Этот товар уже продан!\");\n product.setDisableButton(true);\n }\n if (product.getCreatedBy().getId().equals(currentUserId)) {", "score": 0.8521757125854492 } ]
java
System.out.println(transaction.getBuyerId());
package de.cubeattack.neoprotect.core.executor; import de.cubeattack.api.API; import de.cubeattack.api.language.Localization; import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration; import de.cubeattack.api.libraries.org.json.JSONObject; import de.cubeattack.neoprotect.core.Config; import de.cubeattack.neoprotect.core.NeoProtectPlugin; import de.cubeattack.neoprotect.core.model.Backend; import de.cubeattack.neoprotect.core.model.Gameshield; import de.cubeattack.neoprotect.core.model.Stats; import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse; import java.io.File; import java.nio.file.Files; import java.sql.Timestamp; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.atomic.AtomicReference; public class NeoProtectExecutor { private static Timer debugTimer = new Timer(); private NeoProtectPlugin instance; private Localization localization; private Object sender; private Locale locale; private String msg; private String[] args; private boolean isViaConsole; private void initials(ExecutorBuilder executeBuilder) { this.instance = executeBuilder.getInstance(); this.localization = instance.getCore().getLocalization(); this.sender = executeBuilder.getSender(); this.locale = executeBuilder.getLocal(); this.args = executeBuilder.getArgs(); this.msg = executeBuilder.getMsg(); this.isViaConsole = executeBuilder.isViaConsole(); } private void chatEvent(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (instance.getCore().getRestAPI().isAPIInvalid(msg)) { instance.sendMessage(sender, localization.get(locale, "apikey.invalid")); return; } Config.setAPIKey(msg); instance.sendMessage(sender, localization.get(locale, "apikey.valid")); gameshieldSelector(); } private void command(ExecutorBuilder executorBuilder) { initials(executorBuilder); if (args.length == 0) { showHelp(); return; } if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) { instance.sendMessage(sender, localization.get(locale, "setup.command.required")); return; } switch (args[0].toLowerCase()) { case "setup": { if (isViaConsole) { instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command")); } else { setup(); } break; } case "ipanic": { iPanic(args); break; } case "directconnectwhitelist": { directConnectWhitelist(args); break; } case "toggle": { toggle(args); break; } case "analytics": { analytics(); break; } case "whitelist": case "blacklist": { firewall(args); break; } case "debugtool": { debugTool(args); break; } case "setgameshield": { if (args.length == 1 && !isViaConsole) { gameshieldSelector(); } else if (args.length == 2) { setGameshield(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgameshield")); } break; } case "setbackend": { if (args.length == 1 && !isViaConsole) { javaBackendSelector(); } else if (args.length == 2) { setJavaBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setbackend")); } break; } case "setgeyserbackend": { if (args.length == 1 && !isViaConsole) { bedrockBackendSelector(); } else if (args.length == 2) { setBedrockBackend(args); } else { instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend")); } break; } default: { showHelp(); } } } private void setup() { instance.getCore().getPlayerInSetup().add(sender); instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"), "OPEN_URL", "https://panel.neoprotect.net/profile", "SHOW_TEXT", localization.get(locale, "apikey.find")); } private void iPanic(String[] args) { if (args.length != 1) { instance.sendMessage(sender, localization.get(locale, "usage.ipanic")); } else { instance.sendMessage(sender, localization.get(locale, "command.ipanic", localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated"))); } } private void directConnectWhitelist(String[] args) { if (args.length == 2) { instance.getCore().getDirectConnectWhitelist().add(args[1]); instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1])); } else { instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist")); } } private void toggle(String[] args) { if (args.length != 2) { instance.sendMessage(sender, localization.get(locale, "usage.toggle")); } else { int response = instance.getCore().getRestAPI().toggle(args[1]); if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } if (response == -1) { instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'"); return; } instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1], localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated"))); } } private void analytics() { instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------"); JSONObject analytics = instance.getCore().getRestAPI().getAnalytics(); instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> { if (ak.equals("bandwidth")) { return; } if (ak.equals("traffic")) { instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " + new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s"); JSONObject traffic = instance.getCore().getRestAPI().getTraffic(); AtomicReference<String> trafficUsed = new AtomicReference<>(); AtomicReference<String> trafficAvailable = new AtomicReference<>(); traffic.keySet().forEach(bk -> { if (bk.equals("used")) { trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb"); } if (bk.equals("available")) { trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb"); } }); instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get()); return; } instance.sendMessage(sender, ak .replace("onlinePlayers", "online players") .replace("cps", "connections/s") + ": " + analytics.get(ak)); }); } private void firewall(String[] args) { if (args.length == 1) { instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----"); instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall -> instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")"))); } else if (args.length == 3) { String ip = args[2]; String action = args[1]; String mode = args[0].toUpperCase(); int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode); if (response == -1) { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); return; } if (response == 0) { instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode)); return; } if (response == 400) { instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip)); return; } if (response == 403) { instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan")); return; } if (response == 429) { instance.sendMessage(sender, localization.get(locale, "err.rate-limit")); return; } instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")"); } else { instance.sendMessage(sender, localization.get(locale, "usage.firewall")); } } @SuppressWarnings("ResultOfMethodCallIgnored") private void debugTool(String[] args) { if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) { instance.sendMessage(sender, localization.get(locale, "debug.spigot")); return; } if (args.length == 2) { if (args[1].equals("cancel")) { debugTimer.cancel(); instance.getCore().setDebugRunning(false); instance.sendMessage(sender, localization.get(locale, "debug.cancelled")); return; } if (!isInteger(args[1])) { instance.sendMessage(sender, localization.get(locale, "usage.debug")); return; } } if (instance.getCore().isDebugRunning()) { instance.sendMessage(sender, localization.get(locale, "debug.running")); return; } instance.getCore().setDebugRunning(true); instance.sendMessage(sender, localization.get(locale, "debug.starting")); int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5; debugTimer = new Timer(); debugTimer.schedule(new TimerTask() { int counter = 0; @Override public void run() { counter++; instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis())); instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")"); if (counter >= amount) this.cancel(); } }, 500, 2000); debugTimer.schedule(new TimerTask() { @Override public void run() { API.getExecutorService().submit(() -> { try { long startTime = System.currentTimeMillis(); Stats stats = instance.getStats(); File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml"); YamlConfiguration configuration = new YamlConfiguration(); if (!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } configuration.load(file); configuration.set("general.osName", System.getProperty("os.name")); configuration.set("general.javaVersion", System.getProperty("java.version")); configuration.set("general.pluginVersion", stats.getPluginVersion()); configuration.set("general.ProxyName", stats.getServerName()); configuration.set("general.ProxyVersion", stats.getServerVersion()); configuration.set("general.ProxyPlugins", instance.getPlugins()); instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> { List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName); long maxPlayerToProxyLatenz = 0; long maxNeoToProxyLatenz = 0; long maxProxyToBackendLatenz = 0; long maxPlayerToNeoLatenz = 0; long avgPlayerToProxyLatenz = 0; long avgNeoToProxyLatenz = 0; long avgProxyToBackendLatenz = 0; long avgPlayerToNeoLatenz = 0; long minPlayerToProxyLatenz = Long.MAX_VALUE; long minNeoToProxyLatenz = Long.MAX_VALUE; long minProxyToBackendLatenz = Long.MAX_VALUE; long minPlayerToNeoLatenz = Long.MAX_VALUE; configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress()); configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress()); for (DebugPingResponse response : list) { if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz()) maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz()) maxNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz()) maxProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz()) maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz(); avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz(); avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz(); avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz(); if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz()) minPlayerToProxyLatenz = response.getPlayerToProxyLatenz(); if (minNeoToProxyLatenz > response.getNeoToProxyLatenz()) minNeoToProxyLatenz = response.getNeoToProxyLatenz(); if (minProxyToBackendLatenz > response.getProxyToBackendLatenz()) minProxyToBackendLatenz = response.getProxyToBackendLatenz(); if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz()) minPlayerToNeoLatenz = response.getPlayerToNeoLatenz(); } configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz); configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size()); configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size()); configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz); configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz); configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz); configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz); })); configuration.save(file); final String content = new String(Files.readAllBytes(file.toPath())); final String pasteKey = instance.getCore().getRestAPI().paste(content); instance.getCore().getDebugPingResponses().clear(); instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)"); if(pasteKey != null) { final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml"; instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null); } else { instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null); } instance.getCore().setDebugRunning(false); } catch (Exception ex) { instance.getCore().severe(ex.getMessage(), ex); } }); } }, 2000L * amount + 500); } private void gameshieldSelector() { instance.sendMessage(sender, localization.get(locale, "select.gameshield")); List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields(); for (Gameshield gameshield : gameshieldList) { instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgameshield " + gameshield.getId(), "SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(
), gameshield.getId()));
} } private void setGameshield(String[] args) { if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1])); return; } Config.setGameShieldID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1])); javaBackendSelector(); } private void javaBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); instance.sendMessage(sender, localization.get(locale, "select.backend", "java")); for (Backend backend : backendList) { if(backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setJavaBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1])); return; } Config.setBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1])); instance.getCore().getRestAPI().testCredentials(); bedrockBackendSelector(); } private void bedrockBackendSelector() { List<Backend> backendList = instance.getCore().getRestAPI().getBackends(); if(backendList.stream().noneMatch(Backend::isGeyser))return; instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser")); for (Backend backend : backendList) { if(!backend.isGeyser())continue; instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"), "RUN_COMMAND", "/np setgeyserbackend " + backend.getId(), "SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); } } private void setBedrockBackend(String[] args) { if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) { instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1])); return; } Config.setGeyserBackendID(args[1]); instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1])); if (instance.getCore().getPlayerInSetup().remove(sender)) { instance.sendMessage(sender, localization.get(locale, "setup.finished")); } } private void showHelp() { instance.sendMessage(sender, localization.get(locale, "available.commands")); instance.sendMessage(sender, " - /np setup"); instance.sendMessage(sender, " - /np ipanic"); instance.sendMessage(sender, " - /np analytics"); instance.sendMessage(sender, " - /np toggle (option)"); instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)"); instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)"); instance.sendMessage(sender, " - /np debugTool (cancel / amount)"); instance.sendMessage(sender, " - /np directConnectWhitelist (ip)"); instance.sendMessage(sender, " - /np setgameshield [id]"); instance.sendMessage(sender, " - /np setbackend [id]"); instance.sendMessage(sender, " - /np setgeyserbackend [id]"); } public static class ExecutorBuilder { private NeoProtectPlugin instance; private Object sender; private String[] args; private Locale local; private String msg; private boolean viaConsole; public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) { this.instance = instance; return this; } public ExecutorBuilder sender(Object sender) { this.sender = sender; return this; } public ExecutorBuilder args(String[] args) { this.args = args; return this; } public ExecutorBuilder local(Locale local) { this.local = local; return this; } public ExecutorBuilder msg(String msg) { this.msg = msg; return this; } public ExecutorBuilder viaConsole(boolean viaConsole) { this.viaConsole = viaConsole; return this; } public void executeChatEvent() { API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this)); } public void executeCommand() { API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this)); } public NeoProtectPlugin getInstance() { return instance; } public Object getSender() { return sender; } public String[] getArgs() { return args; } public Locale getLocal() { return local; } public String getMsg() { return msg; } public boolean isViaConsole() { return viaConsole; } } public static boolean isInteger(String input) { try { Integer.parseInt(input); return true; } catch (NumberFormatException e) { return false; } } }
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
NeoProtect-NeoPlugin-a71f673
[ { "filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java", "retrieved_chunk": " return;\n }\n if (!attackRunning[0]) {\n core.warn(\"Gameshield ID '\" + Config.getGameShieldID() + \"' is under attack\");\n core.getPlugin().sendAdminMessage(Permission.NOTIFY, \"Gameshield ID '\" + Config.getGameShieldID() + \"' is under attack\", null, null, null, null);\n attackRunning[0] = true;\n }\n }\n }, 1000 * 5, 1000 * 10);\n }", "score": 0.8435848951339722 }, { "filename": "src/main/java/de/cubeattack/neoprotect/core/model/Gameshield.java", "retrieved_chunk": "package de.cubeattack.neoprotect.core.model;\npublic class Gameshield {\n private final String id;\n private final String name;\n public Gameshield(String id, String name) {\n this.id = id;\n this.name = name;\n }\n public String getId() {\n return id;", "score": 0.8036932945251465 }, { "filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java", "retrieved_chunk": " }\n }\n }, 500);\n }\n}", "score": 0.7917078733444214 }, { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java", "retrieved_chunk": " }\n }\n }, 500);\n }\n}", "score": 0.7917078733444214 }, { "filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java", "retrieved_chunk": " JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject(\"gameShieldSettings\");\n String mitigationSensitivity = settings.getString(\"mitigationSensitivity\");\n if (mitigationSensitivity.equals(\"UNDER_ATTACK\")) {\n rest.request(RequestType.POST_GAMESHIELD_UPDATE,\n RequestBody.create(MediaType.parse(\"application/json\"), settings.put(\"mitigationSensitivity\", \"MEDIUM\").toString()),\n Config.getGameShieldID());\n return false;\n } else {\n rest.request(RequestType.POST_GAMESHIELD_UPDATE,\n RequestBody.create(MediaType.parse(\"application/json\"), settings.put(\"mitigationSensitivity\", \"UNDER_ATTACK\").toString()),", "score": 0.7827821373939514 } ]
java
), gameshield.getId()));
package com.example.MonitoringInternetShop.Controllers; import com.example.MonitoringInternetShop.Models.Category; import com.example.MonitoringInternetShop.Models.OrderItem; import com.example.MonitoringInternetShop.Models.Product; import com.example.MonitoringInternetShop.Services.CategoryService; import com.example.MonitoringInternetShop.Services.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.util.List; @Controller @RequestMapping("/products") public class ProductController { @Autowired private ProductService productService; @Autowired private CategoryService categoryService; @GetMapping public String products(Model model, @RequestParam(name = "category", required = false) String category, @RequestParam(name = "sortBy", required = false) String sortBy) { List<Product> products = productService.getFilteredAndSortedProducts(category, sortBy); List<Category> categories = categoryService.getAllCategories(); model.addAttribute("products", products); model.addAttribute("product", new Product()); model.addAttribute("categories", categories); model.addAttribute("category", new Category()); return "products"; } @PostMapping public String createProduct(@ModelAttribute Product product) { productService.saveProduct(product); return "redirect:/products"; } @PostMapping("/{id}/edit") public String editProduct(@PathVariable Long id, Product product) { Product existingProduct = productService.getProductById(id); if (existingProduct != null) { existingProduct.setName(product.getName()); existingProduct.setPrice(product.getPrice()); existingProduct.setSales(product.getSales()); existingProduct.setDescription(product.getDescription()); existingProduct.setCategory(product.getCategory()); existingProduct.setStock(product.getStock()); productService.updateProduct(existingProduct); } return "redirect:/products"; } @PostMapping("/{id}/delete") public String deleteProduct(@PathVariable Long id, RedirectAttributes redirectAttributes) { List
<OrderItem> orderItems = productService.findOrderItemsByProduct(id);
if (!orderItems.isEmpty()) { redirectAttributes.addFlashAttribute("alert", "Нельзя удалить товар, пока у него есть заказы. Разберитесь с заказами перед удалением."); return "redirect:/products"; } productService.deleteProduct(id); return "redirect:/products"; } @PostMapping("/{id}/incrementStock") public String incrementProductStock(@PathVariable("id") Long id, @RequestParam("incrementAmount") Integer incrementAmount) { productService.incrementProductStock(id, incrementAmount); return "redirect:/products"; } @PostMapping("/{id}/decrementStock") public String decrementProductStock(@PathVariable("id") Long id, @RequestParam("decrementAmount") Integer decrementAmount, Model model) { try { productService.decrementProductStock(id, decrementAmount); } catch (RuntimeException ex) { model.addAttribute("alert", ex.getMessage()); return "products"; } return "redirect:/products"; } @PostMapping("/categories") public String createCategory(@ModelAttribute Category category) { categoryService.saveCategory(category); return "redirect:/products"; } }
MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Controllers/ProductController.java
Neural-Enigma-Ecommerce-Sales-Dashboard-Spring-0130f60
[ { "filename": "MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Services/ProductService.java", "retrieved_chunk": " }\n }\n public void deleteProduct(Long id) {\n productRepository.deleteById(id);\n }\n public List<OrderItem> findOrderItemsByProduct(Long productId) {\n return orderItemRepository.findAllByProduct_Id(productId);\n }\n}", "score": 0.8953695297241211 }, { "filename": "MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Controllers/OrderController.java", "retrieved_chunk": " Product product = productService.findById(productId);\n OrderItem orderItem = new OrderItem();\n orderItem.setProduct(product);\n orderItem.setQuantity(quantity);\n orderItems.add(orderItem);\n }\n newOrder.setOrderItems(orderItems);\n orderService.saveOrder(newOrder);\n return \"redirect:/orders\";\n }", "score": 0.881115734577179 }, { "filename": "MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Controllers/OrderController.java", "retrieved_chunk": " orderService.updateOrderStatus(id, status);\n return \"redirect:/orders\";\n }\n @PostMapping(\"/orders/new\")\n public String createOrder(@RequestParam String user, @RequestParam List<Long> products, @RequestParam int quantity) {\n Order newOrder = new Order();\n newOrder.setUser(userService.findByName(user).orElseThrow());\n newOrder.setOrderDate(LocalDate.now());\n List<OrderItem> orderItems = new ArrayList<>();\n for (Long productId : products) {", "score": 0.8795941472053528 }, { "filename": "MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Controllers/OrderController.java", "retrieved_chunk": " }\n @PostMapping(\"/orders/delete/{id}\")\n public String deleteOrder(@PathVariable Long id) {\n orderService.deleteOrder(id);\n return \"redirect:/orders\";\n }\n}", "score": 0.8713741898536682 }, { "filename": "MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Controllers/OrderController.java", "retrieved_chunk": " for (int i = 0; i < productIds.size(); i++) {\n Long productId = productIds.get(i);\n Product product = productService.getProductById(productId);\n int quantity = quantities.get(i);\n if (product.getStock() < quantity) {\n redirectAttrs.addFlashAttribute(\"error\", \"Недостаточное количество товара на складе для товара \" + product.getName());\n return \"redirect:/create-order\";\n }\n product.setStock(product.getStock() - quantity);\n product.setSales(product.getSales() + quantity);", "score": 0.8706051707267761 } ]
java
<OrderItem> orderItems = productService.findOrderItemsByProduct(id);
package com.example.MonitoringInternetShop.Controllers; import com.example.MonitoringInternetShop.Models.User; import com.example.MonitoringInternetShop.Repositories.UserRepository; import com.example.MonitoringInternetShop.Services.UserService; import jakarta.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.Optional; @Controller public class LoginController { private static final String INVALID_USER = "Неверный логин или пароль"; private static final String UNKNOWN_ROLE = "Неизвестная роль пользователя"; private static final String INACTIVE_ACCOUNT = "Ваш аккаунт не активирован, обратитесь к администратору для активации"; private static final String LOGIN_EXISTS = "Пользователь с таким логином уже существует!"; private static final String EMAIL_EXISTS = "Пользователь с таким email уже существует!"; private static final String PASSWORD_MISMATCH = "Пароли не совпадают!"; private static final String REGISTRATION_SUCCESS = "Регистрация успешна. Ваш аккаунт ожидает активации."; @Autowired private UserService userService; @Autowired private UserRepository userRepository; @GetMapping("/login") public String showLoginPage() { return "login"; } @GetMapping("/register") public String registerForm(Model model) { model.addAttribute("user", new User()); return "registration"; } @PostMapping("/login") public String handleLogin(@RequestParam String username, @RequestParam String password, HttpSession session, Model model) {
Optional<User> userOptional = userService.validateUser(username, password);
if (userOptional.isPresent()) { User user = userOptional.get(); if (User.Status.ACTIVE.equals(user.getStatus())) { session.setAttribute("user", user); if (User.Role.ADMIN.equals(user.getRole())) { return "redirect:/dashboard"; } else if (User.Role.USER.equals(user.getRole())) { return "redirect:/create-order"; } else { model.addAttribute("error", UNKNOWN_ROLE); return "login"; } } else { model.addAttribute("error", INACTIVE_ACCOUNT); return "login"; } } else { model.addAttribute("error", INVALID_USER); return "login"; } } @PostMapping("/register") public String addUser(@ModelAttribute User user, @RequestParam String passwordConfirm, Model model) { Optional<User> userFromDbOptional = userRepository.findByLogin(user.getLogin()); Optional<User> emailFromDbOptional = userRepository.findByMail(user.getMail()); if (userFromDbOptional.isPresent()) { model.addAttribute("message", LOGIN_EXISTS); return "registration"; } if (emailFromDbOptional.isPresent()) { model.addAttribute("message", EMAIL_EXISTS); return "registration"; } if (!user.getPassword().equals(passwordConfirm)) { model.addAttribute("message", PASSWORD_MISMATCH); return "registration"; } user.setStatus(User.Status.INACTIVE); user.setRole(User.Role.USER); userRepository.save(user); model.addAttribute("message", REGISTRATION_SUCCESS); return "login"; } }
MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Controllers/LoginController.java
Neural-Enigma-Ecommerce-Sales-Dashboard-Spring-0130f60
[ { "filename": "MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Controllers/UserManagementController.java", "retrieved_chunk": " return \"user-management\";\n }\n @GetMapping(\"/edit/{id}\")\n public String showEditForm(@PathVariable(\"id\") Long id, Model model) {\n User user = userService.getUserById(id).orElseThrow();\n model.addAttribute(\"user\", user);\n return \"edit-user\";\n }\n @PostMapping(\"/edit/{id}\")\n public String updateUser(@PathVariable(\"id\") Long id, @ModelAttribute User user) {", "score": 0.8706268072128296 }, { "filename": "MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Controllers/UserManagementController.java", "retrieved_chunk": "@RequestMapping(\"user-management\")\npublic class UserManagementController {\n @Autowired\n private UserService userService;\n @GetMapping(\"\")\n public String showUsers(Model model, HttpSession session) {\n User loggedInUser = userService.getLoggedInUser(session).orElseThrow();\n List<User> users = userService.getAllUsers();\n users.remove(loggedInUser);\n model.addAttribute(\"users\", users);", "score": 0.8690263032913208 }, { "filename": "MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Controllers/SettingsController.java", "retrieved_chunk": "package com.example.MonitoringInternetShop.Controllers;\nimport com.example.MonitoringInternetShop.Models.User;\nimport com.example.MonitoringInternetShop.Repositories.UserRepository;\nimport jakarta.servlet.http.HttpSession;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.ModelAttribute;", "score": 0.8609867095947266 }, { "filename": "MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Controllers/SettingsController.java", "retrieved_chunk": "@Controller\npublic class SettingsController {\n @Autowired\n private UserRepository userRepository;\n @GetMapping(\"/settings\")\n public String settingsForm(Model model, HttpSession session) {\n User user = (User) session.getAttribute(\"user\");\n if (user != null) {\n model.addAttribute(\"user\", user);\n return \"settings\";", "score": 0.857219398021698 }, { "filename": "MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Controllers/SettingsController.java", "retrieved_chunk": " } else {\n return \"redirect:/login\";\n }\n }\n @PostMapping(\"/settings\")\n public String updateUser(@ModelAttribute User updatedUser, HttpSession session) {\n User currentUser = (User) session.getAttribute(\"user\");\n if (currentUser != null) {\n currentUser.setName(updatedUser.getName());\n currentUser.setMail(updatedUser.getMail());", "score": 0.8528357744216919 } ]
java
Optional<User> userOptional = userService.validateUser(username, password);
package com.example.MonitoringInternetShop.Services; import com.example.MonitoringInternetShop.Models.OrderItem; import com.example.MonitoringInternetShop.Models.Product; import com.example.MonitoringInternetShop.Repositories.OrderItemRepository; import com.example.MonitoringInternetShop.Repositories.ProductRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @Service public class ProductService { @Autowired private ProductRepository productRepository; @Autowired private OrderItemRepository orderItemRepository; public List<Product> getFilteredAndSortedProducts(String category, String sortBy) { List<Product> products; if (category != null && !category.isEmpty()) { products = productRepository.findByCategory(category); } else { products = productRepository.findAll(); } if (sortBy != null && !sortBy.isEmpty()) { if ("price".equalsIgnoreCase(sortBy)) { products.sort(Comparator.comparing(Product::getPrice)); } else if ("popularity".equalsIgnoreCase(sortBy)) { products.sort(Comparator.comparing(Product::getSales).reversed()); } } return products; } public void saveProduct(Product product) { productRepository.save(product); } public List<Product> getTopProducts() { return productRepository.findAll().stream() .sorted((p1, p2) -> p2.getSales() - p1.getSales()) .limit(10) .collect(Collectors.toList()); } public List<Product> getAllProducts() { return productRepository.findAll(); } public Product findById(Long id) { Optional<Product> productOptional = productRepository.findById(id); return productOptional.orElse(null); } public Product getProductById(Long id) { return productRepository.findById(id).orElse(null); } public void incrementProductStock(Long id, Integer incrementAmount) { Optional<Product> optionalProduct = productRepository.findById(id); if (optionalProduct.isPresent()) { Product product = optionalProduct.get(); product.setStock(product.getStock() + incrementAmount); productRepository.save(product); } else { throw new RuntimeException("Продукт не найден с id: " + id); } } public void decrementProductStock(Long id, Integer decrementAmount) throws RuntimeException { Optional<Product> optionalProduct = productRepository.findById(id); if (optionalProduct.isPresent()) { Product product = optionalProduct.get(); if (product.getStock() >= decrementAmount) { product.setStock(product.getStock() - decrementAmount); } else { throw new RuntimeException("Товара на складе недостаточно с id: " + id); } productRepository.save(product); } else { throw new RuntimeException("Продукт не найден с id: " + id); } } public void updateProduct(Product product) { Optional<Product> existingProduct = productRepository.findById(product.getId()); if (existingProduct.isPresent()) { productRepository.save(product); } } public void deleteProduct(Long id) { productRepository.deleteById(id); } public List<OrderItem> findOrderItemsByProduct(Long productId) {
return orderItemRepository.findAllByProduct_Id(productId);
} }
MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Services/ProductService.java
Neural-Enigma-Ecommerce-Sales-Dashboard-Spring-0130f60
[ { "filename": "MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Controllers/ProductController.java", "retrieved_chunk": " }\n @PostMapping\n public String createProduct(@ModelAttribute Product product) {\n productService.saveProduct(product);\n return \"redirect:/products\";\n }\n @PostMapping(\"/{id}/edit\")\n public String editProduct(@PathVariable Long id, Product product) {\n Product existingProduct = productService.getProductById(id);\n if (existingProduct != null) {", "score": 0.8814457654953003 }, { "filename": "MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Repositories/OrderItemRepository.java", "retrieved_chunk": "package com.example.MonitoringInternetShop.Repositories;\nimport com.example.MonitoringInternetShop.Models.OrderItem;\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.stereotype.Repository;\nimport java.util.List;\nimport java.util.Optional;\n@Repository\npublic interface OrderItemRepository extends JpaRepository<OrderItem, Long> {\n List<OrderItem> findAllByProduct_Id(Long productId);\n}", "score": 0.8782480955123901 }, { "filename": "MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Controllers/ProductController.java", "retrieved_chunk": " @PostMapping(\"/{id}/delete\")\n public String deleteProduct(@PathVariable Long id, RedirectAttributes redirectAttributes) {\n List<OrderItem> orderItems = productService.findOrderItemsByProduct(id);\n if (!orderItems.isEmpty()) {\n redirectAttributes.addFlashAttribute(\"alert\", \"Нельзя удалить товар, пока у него есть заказы. Разберитесь с заказами перед удалением.\");\n return \"redirect:/products\";\n }\n productService.deleteProduct(id);\n return \"redirect:/products\";\n }", "score": 0.8693566918373108 }, { "filename": "MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Controllers/ProductController.java", "retrieved_chunk": " existingProduct.setName(product.getName());\n existingProduct.setPrice(product.getPrice());\n existingProduct.setSales(product.getSales());\n existingProduct.setDescription(product.getDescription());\n existingProduct.setCategory(product.getCategory());\n existingProduct.setStock(product.getStock());\n productService.updateProduct(existingProduct);\n }\n return \"redirect:/products\";\n }", "score": 0.8666832447052002 }, { "filename": "MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Services/OrderService.java", "retrieved_chunk": " }\n public List<Order> findOrdersByUser(User user) {\n return orderRepository.findByUser(user);\n }\n public List<Order> getOrdersByStatus(String status) {\n return orderRepository.findByStatus(status);\n }\n @Transactional\n public void deleteOrder(Long id) {\n Order order = orderRepository.findById(id)", "score": 0.8652225732803345 } ]
java
return orderItemRepository.findAllByProduct_Id(productId);
package io.github.newhoo.restkit.ext.solon.helper; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiEnumConstant; import com.intellij.psi.PsiField; import com.intellij.psi.PsiModifier; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.PsiShortNamesCache; import io.github.newhoo.restkit.ext.solon.util.TypeUtils; import io.github.newhoo.restkit.util.JsonUtils; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; /** * PsiClassHelper in Java * * @author newhoo * @since 1.0.0 */ public class PsiClassHelper { private static final int MAX_CORRELATION_COUNT = 6; public static String convertClassToJSON(String className, Project project) { Object o = assemblePsiClass(className, project, 0, false); return JsonUtils.toJson(o); } public static Object assemblePsiClass(String typeCanonicalText, Project project, int autoCorrelationCount, boolean putClass) { boolean containsGeneric = typeCanonicalText.contains("<"); // 数组|集合 if (TypeUtils.isArray(typeCanonicalText) || TypeUtils.isList(typeCanonicalText)) { String elementType = TypeUtils.isArray(typeCanonicalText) ? typeCanonicalText.replace("[]", "") : containsGeneric ? typeCanonicalText.substring(typeCanonicalText.indexOf("<") + 1, typeCanonicalText.lastIndexOf(">")) : Object.class.getCanonicalName(); return Collections.singletonList(assemblePsiClass(elementType, project, autoCorrelationCount, putClass)); } PsiClass psiClass = PsiClassHelper.findPsiClass(typeCanonicalText, project); if (psiClass == null) { //简单常用类型 if (
TypeUtils.isPrimitiveOrSimpleType(typeCanonicalText)) {
return TypeUtils.getExampleValue(typeCanonicalText, false); } return Collections.emptyMap(); } //简单常用类型 if (TypeUtils.isPrimitiveOrSimpleType(typeCanonicalText)) { return TypeUtils.getExampleValue(typeCanonicalText, false); } // 枚举 if (psiClass.isEnum()) { PsiField[] enumFields = psiClass.getFields(); for (PsiField enumField : enumFields) { if (enumField instanceof PsiEnumConstant) { return enumField.getName(); } } return ""; } // Map if (TypeUtils.isMap(typeCanonicalText)) { return Collections.emptyMap(); } if (autoCorrelationCount > MAX_CORRELATION_COUNT) { return Collections.emptyMap(); } autoCorrelationCount++; Map<String, Object> map = new LinkedHashMap<>(); if (putClass) { if (containsGeneric) { map.put("class", typeCanonicalText.substring(0, typeCanonicalText.indexOf("<"))); } else { map.put("class", typeCanonicalText); } } for (PsiField field : psiClass.getAllFields()) { if (field.hasModifierProperty(PsiModifier.STATIC) || field.hasModifierProperty(PsiModifier.FINAL) || field.hasModifierProperty(PsiModifier.TRANSIENT)) { continue; } String fieldType = field.getType().getCanonicalText(); // 不存在泛型 if (!containsGeneric) { map.put(field.getName(), assemblePsiClass(fieldType, project, autoCorrelationCount, putClass)); continue; } // 存在泛型 if (TypeUtils.isPrimitiveOrSimpleType(fieldType.replaceAll("\\[]", ""))) { map.put(field.getName(), assemblePsiClass(fieldType, project, autoCorrelationCount, putClass)); } else if (PsiClassHelper.findPsiClass(fieldType, project) == null) { map.put(field.getName(), assemblePsiClass(typeCanonicalText.substring(typeCanonicalText.indexOf("<") + 1, typeCanonicalText.lastIndexOf(">")), project, autoCorrelationCount, putClass)); } else { map.put(field.getName(), assemblePsiClass(fieldType, project, autoCorrelationCount, putClass)); } } return map; } /** * 查找类 * * @param typeCanonicalText 参数类型全限定名称 * @param project 当前project * @return 查找到的类 */ public static PsiClass findPsiClass(String typeCanonicalText, Project project) { // 基本类型转化为对应包装类型 typeCanonicalText = TypeUtils.primitiveToBox(typeCanonicalText); String className = typeCanonicalText; if (className.contains("[]")) { className = className.replaceAll("\\[]", ""); } if (className.contains("<")) { className = className.substring(0, className.indexOf("<")); } if (className.lastIndexOf(".") > 0) { className = className.substring(className.lastIndexOf(".") + 1); } PsiClass[] classesByName = PsiShortNamesCache.getInstance(project).getClassesByName(className, GlobalSearchScope.allScope(project)); for (PsiClass psiClass : classesByName) { if (typeCanonicalText.startsWith(psiClass.getQualifiedName())) { return psiClass; } } return null; } }
src/main/java/io/github/newhoo/restkit/ext/solon/helper/PsiClassHelper.java
newhoo-RestfulBox-Solon-8533971
[ { "filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/BaseLanguageResolver.java", "retrieved_chunk": " // 数组|集合\n if (TypeUtils.isArray(paramType) || TypeUtils.isList(paramType)) {\n paramType = TypeUtils.isArray(paramType)\n ? paramType.replace(\"[]\", \"\")\n : paramType.contains(\"<\")\n ? paramType.substring(paramType.indexOf(\"<\") + 1, paramType.lastIndexOf(\">\"))\n : Object.class.getCanonicalName();\n }\n // 简单常用类型\n if (TypeUtils.isPrimitiveOrSimpleType(paramType)) {", "score": 0.8180517554283142 }, { "filename": "src/main/java/io/github/newhoo/restkit/ext/solon/util/TypeUtils.java", "retrieved_chunk": " if (parameterType.isEmpty()) {\n return \"\";\n }\n if (parameterType.lastIndexOf(\".\") > 0) {\n parameterType = parameterType.substring(parameterType.lastIndexOf(\".\") + 1);\n }\n String type = parameterType.replace(\"PsiType:\", \"\");\n switch (type) {\n case \"byte\":\n case \"Byte\":", "score": 0.7966632843017578 }, { "filename": "src/main/java/io/github/newhoo/restkit/ext/solon/util/TypeUtils.java", "retrieved_chunk": " public static boolean isPrimitiveOrSimpleType(String parameterType) {\n if (parameterType == null) {\n return false;\n }\n String type = parameterType.replace(\"PsiType:\", \"\");\n switch (type) {\n case \"byte\":\n case \"java.lang.Byte\":\n case \"char\":\n case \"java.lang.String\":", "score": 0.7966066598892212 }, { "filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/BaseLanguageResolver.java", "retrieved_chunk": " ));\n PsiClass fieldClass = PsiClassHelper.findPsiClass(psiParameter.getType().getCanonicalText(), psiMethod.getProject());\n if (fieldClass != null && fieldClass.isEnum()) {\n PsiField[] enumFields = fieldClass.getAllFields();\n list.add(new KV(headerName, enumFields.length > 1 ? enumFields[0].getName() : \"\"));\n } else {\n Object fieldDefaultValue = TypeUtils.getExampleValue(psiParameter.getType().getPresentableText(), true);\n list.add(new KV(headerName, String.valueOf(fieldDefaultValue)));\n }\n }", "score": 0.7863988280296326 }, { "filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/BaseLanguageResolver.java", "retrieved_chunk": " Set<String> paramFilterTypes = getParamFilterTypes(psiMethod.getProject());\n PsiParameter[] psiParameters = psiMethod.getParameterList().getParameters();\n for (PsiParameter psiParameter : psiParameters) {\n String paramTypeName = psiParameter.getType().getCanonicalText();\n if (paramFilterTypes.contains(paramTypeName)\n || CollectionUtils.containsAny(paramFilterTypes, Arrays.stream(psiParameter.getAnnotations()).map(PsiAnnotation::getQualifiedName).collect(Collectors.toSet()))) {\n continue;\n }\n // @PathVariable\n PsiAnnotation pathVariableAnno = psiParameter.getAnnotation(PATH_VARIABLE.getQualifiedName());", "score": 0.78522789478302 } ]
java
TypeUtils.isPrimitiveOrSimpleType(typeCanonicalText)) {
package io.github.newhoo.restkit.ext.solon.helper; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiEnumConstant; import com.intellij.psi.PsiField; import com.intellij.psi.PsiModifier; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.PsiShortNamesCache; import io.github.newhoo.restkit.ext.solon.util.TypeUtils; import io.github.newhoo.restkit.util.JsonUtils; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; /** * PsiClassHelper in Java * * @author newhoo * @since 1.0.0 */ public class PsiClassHelper { private static final int MAX_CORRELATION_COUNT = 6; public static String convertClassToJSON(String className, Project project) { Object o = assemblePsiClass(className, project, 0, false); return JsonUtils.toJson(o); } public static Object assemblePsiClass(String typeCanonicalText, Project project, int autoCorrelationCount, boolean putClass) { boolean containsGeneric = typeCanonicalText.contains("<"); // 数组|集合 if (TypeUtils.isArray(typeCanonicalText) || TypeUtils.isList(typeCanonicalText)) { String elementType = TypeUtils.isArray(typeCanonicalText) ? typeCanonicalText.replace("[]", "") : containsGeneric ? typeCanonicalText.substring(typeCanonicalText.indexOf("<") + 1, typeCanonicalText.lastIndexOf(">")) : Object.class.getCanonicalName(); return Collections.singletonList(assemblePsiClass(elementType, project, autoCorrelationCount, putClass)); } PsiClass psiClass = PsiClassHelper.findPsiClass(typeCanonicalText, project); if (psiClass == null) { //简单常用类型 if (TypeUtils.isPrimitiveOrSimpleType(typeCanonicalText)) { return TypeUtils.getExampleValue(typeCanonicalText, false); } return Collections.emptyMap(); } //简单常用类型 if (TypeUtils.isPrimitiveOrSimpleType(typeCanonicalText)) { return TypeUtils.getExampleValue(typeCanonicalText, false); } // 枚举 if (psiClass.isEnum()) { PsiField[] enumFields = psiClass.getFields(); for (PsiField enumField : enumFields) { if (enumField instanceof PsiEnumConstant) { return enumField.getName(); } } return ""; } // Map if
(TypeUtils.isMap(typeCanonicalText)) {
return Collections.emptyMap(); } if (autoCorrelationCount > MAX_CORRELATION_COUNT) { return Collections.emptyMap(); } autoCorrelationCount++; Map<String, Object> map = new LinkedHashMap<>(); if (putClass) { if (containsGeneric) { map.put("class", typeCanonicalText.substring(0, typeCanonicalText.indexOf("<"))); } else { map.put("class", typeCanonicalText); } } for (PsiField field : psiClass.getAllFields()) { if (field.hasModifierProperty(PsiModifier.STATIC) || field.hasModifierProperty(PsiModifier.FINAL) || field.hasModifierProperty(PsiModifier.TRANSIENT)) { continue; } String fieldType = field.getType().getCanonicalText(); // 不存在泛型 if (!containsGeneric) { map.put(field.getName(), assemblePsiClass(fieldType, project, autoCorrelationCount, putClass)); continue; } // 存在泛型 if (TypeUtils.isPrimitiveOrSimpleType(fieldType.replaceAll("\\[]", ""))) { map.put(field.getName(), assemblePsiClass(fieldType, project, autoCorrelationCount, putClass)); } else if (PsiClassHelper.findPsiClass(fieldType, project) == null) { map.put(field.getName(), assemblePsiClass(typeCanonicalText.substring(typeCanonicalText.indexOf("<") + 1, typeCanonicalText.lastIndexOf(">")), project, autoCorrelationCount, putClass)); } else { map.put(field.getName(), assemblePsiClass(fieldType, project, autoCorrelationCount, putClass)); } } return map; } /** * 查找类 * * @param typeCanonicalText 参数类型全限定名称 * @param project 当前project * @return 查找到的类 */ public static PsiClass findPsiClass(String typeCanonicalText, Project project) { // 基本类型转化为对应包装类型 typeCanonicalText = TypeUtils.primitiveToBox(typeCanonicalText); String className = typeCanonicalText; if (className.contains("[]")) { className = className.replaceAll("\\[]", ""); } if (className.contains("<")) { className = className.substring(0, className.indexOf("<")); } if (className.lastIndexOf(".") > 0) { className = className.substring(className.lastIndexOf(".") + 1); } PsiClass[] classesByName = PsiShortNamesCache.getInstance(project).getClassesByName(className, GlobalSearchScope.allScope(project)); for (PsiClass psiClass : classesByName) { if (typeCanonicalText.startsWith(psiClass.getQualifiedName())) { return psiClass; } } return null; } }
src/main/java/io/github/newhoo/restkit/ext/solon/helper/PsiClassHelper.java
newhoo-RestfulBox-Solon-8533971
[ { "filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/BaseLanguageResolver.java", "retrieved_chunk": " PsiClass fieldClass = PsiClassHelper.findPsiClass(field.getType().getCanonicalText(), psiMethod.getProject());\n if (fieldClass != null && fieldClass.isEnum()) {\n PsiField[] enumFields = fieldClass.getAllFields();\n list.add(new KV(field.getName(), enumFields.length > 1 ? enumFields[0].getName() : \"\"));\n } else {\n Object fieldDefaultValue = TypeUtils.getExampleValue(field.getType().getPresentableText(), true);\n list.add(new KV(field.getName(), String.valueOf(fieldDefaultValue)));\n }\n }\n }", "score": 0.8502516746520996 }, { "filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/BaseLanguageResolver.java", "retrieved_chunk": " ));\n PsiClass fieldClass = PsiClassHelper.findPsiClass(psiParameter.getType().getCanonicalText(), psiMethod.getProject());\n if (fieldClass != null && fieldClass.isEnum()) {\n PsiField[] enumFields = fieldClass.getAllFields();\n list.add(new KV(headerName, enumFields.length > 1 ? enumFields[0].getName() : \"\"));\n } else {\n Object fieldDefaultValue = TypeUtils.getExampleValue(psiParameter.getType().getPresentableText(), true);\n list.add(new KV(headerName, String.valueOf(fieldDefaultValue)));\n }\n }", "score": 0.8403070569038391 }, { "filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/BaseLanguageResolver.java", "retrieved_chunk": " if (psiClass != null) {\n PsiField[] fields = psiClass.getAllFields();\n if (psiClass.isEnum()) {\n list.add(new KV(parameter.getParamName(), fields.length > 1 ? fields[0].getName() : \"\"));\n continue;\n }\n for (PsiField field : fields) {\n if (field.hasModifierProperty(PsiModifier.STATIC) || field.hasModifierProperty(PsiModifier.TRANSIENT)) {\n continue;\n }", "score": 0.8393005132675171 }, { "filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/JavaLanguageResolver.java", "retrieved_chunk": " return \"\";\n }\n PsiMethod psiMethod = (PsiMethod) psiElement;\n String restName = null;\n String location;\n if (psiMethod.getDocComment() != null) {\n restName = Arrays.stream(psiMethod.getDocComment().getDescriptionElements())\n .filter(e -> e instanceof PsiDocToken)\n .filter(e -> StringUtils.isNotBlank(e.getText()))\n .findFirst()", "score": 0.8171513676643372 }, { "filename": "src/main/java/io/github/newhoo/restkit/ext/solon/util/TypeUtils.java", "retrieved_chunk": " if (parameterType.isEmpty()) {\n return \"\";\n }\n if (parameterType.lastIndexOf(\".\") > 0) {\n parameterType = parameterType.substring(parameterType.lastIndexOf(\".\") + 1);\n }\n String type = parameterType.replace(\"PsiType:\", \"\");\n switch (type) {\n case \"byte\":\n case \"Byte\":", "score": 0.8053189516067505 } ]
java
(TypeUtils.isMap(typeCanonicalText)) {
package io.github.newhoo.restkit.ext.solon.helper; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiEnumConstant; import com.intellij.psi.PsiField; import com.intellij.psi.PsiModifier; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.PsiShortNamesCache; import io.github.newhoo.restkit.ext.solon.util.TypeUtils; import io.github.newhoo.restkit.util.JsonUtils; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; /** * PsiClassHelper in Java * * @author newhoo * @since 1.0.0 */ public class PsiClassHelper { private static final int MAX_CORRELATION_COUNT = 6; public static String convertClassToJSON(String className, Project project) { Object o = assemblePsiClass(className, project, 0, false); return JsonUtils.toJson(o); } public static Object assemblePsiClass(String typeCanonicalText, Project project, int autoCorrelationCount, boolean putClass) { boolean containsGeneric = typeCanonicalText.contains("<"); // 数组|集合 if (TypeUtils.isArray(typeCanonicalText) || TypeUtils.isList(typeCanonicalText)) { String elementType = TypeUtils.isArray(typeCanonicalText) ? typeCanonicalText.replace("[]", "") : containsGeneric ? typeCanonicalText.substring(typeCanonicalText.indexOf("<") + 1, typeCanonicalText.lastIndexOf(">")) : Object.class.getCanonicalName(); return Collections.singletonList(assemblePsiClass(elementType, project, autoCorrelationCount, putClass)); } PsiClass psiClass = PsiClassHelper.findPsiClass(typeCanonicalText, project); if (psiClass == null) { //简单常用类型 if (TypeUtils.isPrimitiveOrSimpleType(typeCanonicalText)) { return TypeUtils.getExampleValue(typeCanonicalText, false); } return Collections.emptyMap(); } //简单常用类型 if (TypeUtils.isPrimitiveOrSimpleType(typeCanonicalText)) { return TypeUtils.getExampleValue(typeCanonicalText, false); } // 枚举 if (psiClass.isEnum()) { PsiField[] enumFields = psiClass.getFields(); for (PsiField enumField : enumFields) { if (enumField instanceof PsiEnumConstant) { return enumField.getName(); } } return ""; } // Map if (TypeUtils.isMap(typeCanonicalText)) { return Collections.emptyMap(); } if (autoCorrelationCount > MAX_CORRELATION_COUNT) { return Collections.emptyMap(); } autoCorrelationCount++; Map<String, Object> map = new LinkedHashMap<>(); if (putClass) { if (containsGeneric) { map.put("class", typeCanonicalText.substring(0, typeCanonicalText.indexOf("<"))); } else { map.put("class", typeCanonicalText); } } for (PsiField field : psiClass.getAllFields()) { if (field.hasModifierProperty(PsiModifier.STATIC) || field.hasModifierProperty(PsiModifier.FINAL) || field.hasModifierProperty(PsiModifier.TRANSIENT)) { continue; } String fieldType = field.getType().getCanonicalText(); // 不存在泛型 if (!containsGeneric) { map.put(field.getName(), assemblePsiClass(fieldType, project, autoCorrelationCount, putClass)); continue; } // 存在泛型 if (TypeUtils.isPrimitiveOrSimpleType(fieldType.replaceAll("\\[]", ""))) { map.put(field.getName(), assemblePsiClass(fieldType, project, autoCorrelationCount, putClass)); } else if (PsiClassHelper.findPsiClass(fieldType, project) == null) { map.put(field.getName(), assemblePsiClass(typeCanonicalText.substring(typeCanonicalText.indexOf("<") + 1, typeCanonicalText.lastIndexOf(">")), project, autoCorrelationCount, putClass)); } else { map.put(field.getName(), assemblePsiClass(fieldType, project, autoCorrelationCount, putClass)); } } return map; } /** * 查找类 * * @param typeCanonicalText 参数类型全限定名称 * @param project 当前project * @return 查找到的类 */ public static PsiClass findPsiClass(String typeCanonicalText, Project project) { // 基本类型转化为对应包装类型 typeCanonicalText
= TypeUtils.primitiveToBox(typeCanonicalText);
String className = typeCanonicalText; if (className.contains("[]")) { className = className.replaceAll("\\[]", ""); } if (className.contains("<")) { className = className.substring(0, className.indexOf("<")); } if (className.lastIndexOf(".") > 0) { className = className.substring(className.lastIndexOf(".") + 1); } PsiClass[] classesByName = PsiShortNamesCache.getInstance(project).getClassesByName(className, GlobalSearchScope.allScope(project)); for (PsiClass psiClass : classesByName) { if (typeCanonicalText.startsWith(psiClass.getQualifiedName())) { return psiClass; } } return null; } }
src/main/java/io/github/newhoo/restkit/ext/solon/helper/PsiClassHelper.java
newhoo-RestfulBox-Solon-8533971
[ { "filename": "src/main/java/io/github/newhoo/restkit/ext/solon/util/TypeUtils.java", "retrieved_chunk": " return false;\n }\n }\n /**\n * 基本类型转化为包装类型\n *\n * @param classType 基本类型\n */\n public static String primitiveToBox(String classType) {\n switch (classType) {", "score": 0.7864692211151123 }, { "filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/BaseLanguageResolver.java", "retrieved_chunk": " PsiClass fieldClass = PsiClassHelper.findPsiClass(field.getType().getCanonicalText(), psiMethod.getProject());\n if (fieldClass != null && fieldClass.isEnum()) {\n PsiField[] enumFields = fieldClass.getAllFields();\n list.add(new KV(field.getName(), enumFields.length > 1 ? enumFields[0].getName() : \"\"));\n } else {\n Object fieldDefaultValue = TypeUtils.getExampleValue(field.getType().getPresentableText(), true);\n list.add(new KV(field.getName(), String.valueOf(fieldDefaultValue)));\n }\n }\n }", "score": 0.7591532468795776 }, { "filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/BaseLanguageResolver.java", "retrieved_chunk": " // 数组|集合\n if (TypeUtils.isArray(paramType) || TypeUtils.isList(paramType)) {\n paramType = TypeUtils.isArray(paramType)\n ? paramType.replace(\"[]\", \"\")\n : paramType.contains(\"<\")\n ? paramType.substring(paramType.indexOf(\"<\") + 1, paramType.lastIndexOf(\">\"))\n : Object.class.getCanonicalName();\n }\n // 简单常用类型\n if (TypeUtils.isPrimitiveOrSimpleType(paramType)) {", "score": 0.7582427859306335 }, { "filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/BaseLanguageResolver.java", "retrieved_chunk": " parameterList.add(parameter);\n }\n return parameterList;\n }\n @NotNull\n @Override\n public Set<String> getParamFilterTypes(@NotNull Project project) {\n return Stream.of(\n \"java.util.Locale\",\n \"org.noear.solon.core.handle.Context\",", "score": 0.7544851303100586 }, { "filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/BaseLanguageResolver.java", "retrieved_chunk": " Set<String> paramFilterTypes = getParamFilterTypes(psiMethod.getProject());\n PsiParameter[] psiParameters = psiMethod.getParameterList().getParameters();\n for (PsiParameter psiParameter : psiParameters) {\n String paramTypeName = psiParameter.getType().getCanonicalText();\n if (paramFilterTypes.contains(paramTypeName)\n || CollectionUtils.containsAny(paramFilterTypes, Arrays.stream(psiParameter.getAnnotations()).map(PsiAnnotation::getQualifiedName).collect(Collectors.toSet()))) {\n continue;\n }\n // @PathVariable\n PsiAnnotation pathVariableAnno = psiParameter.getAnnotation(PATH_VARIABLE.getQualifiedName());", "score": 0.7529183626174927 } ]
java
= TypeUtils.primitiveToBox(typeCanonicalText);
package io.github.newhoo.restkit.ext.solon.helper; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiEnumConstant; import com.intellij.psi.PsiField; import com.intellij.psi.PsiModifier; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.PsiShortNamesCache; import io.github.newhoo.restkit.ext.solon.util.TypeUtils; import io.github.newhoo.restkit.util.JsonUtils; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; /** * PsiClassHelper in Java * * @author newhoo * @since 1.0.0 */ public class PsiClassHelper { private static final int MAX_CORRELATION_COUNT = 6; public static String convertClassToJSON(String className, Project project) { Object o = assemblePsiClass(className, project, 0, false); return JsonUtils.toJson(o); } public static Object assemblePsiClass(String typeCanonicalText, Project project, int autoCorrelationCount, boolean putClass) { boolean containsGeneric = typeCanonicalText.contains("<"); // 数组|集合 if (TypeUtils.isArray(typeCanonicalText) || TypeUtils.isList(typeCanonicalText)) { String elementType = TypeUtils.isArray(typeCanonicalText) ? typeCanonicalText.replace("[]", "") : containsGeneric ? typeCanonicalText.substring(typeCanonicalText.indexOf("<") + 1, typeCanonicalText.lastIndexOf(">")) : Object.class.getCanonicalName(); return Collections.singletonList(assemblePsiClass(elementType, project, autoCorrelationCount, putClass)); } PsiClass psiClass = PsiClassHelper.findPsiClass(typeCanonicalText, project); if (psiClass == null) { //简单常用类型 if (TypeUtils.isPrimitiveOrSimpleType(typeCanonicalText)) { return TypeUtils.getExampleValue(typeCanonicalText, false); } return Collections.emptyMap(); } //简单常用类型 if (TypeUtils.isPrimitiveOrSimpleType(typeCanonicalText)) { return TypeUtils.getExampleValue(typeCanonicalText, false); } // 枚举 if (psiClass.isEnum()) { PsiField[] enumFields = psiClass.getFields(); for (PsiField enumField : enumFields) { if (enumField instanceof PsiEnumConstant) { return enumField.getName(); } } return ""; } // Map if (TypeUtils.isMap(typeCanonicalText)) { return Collections.emptyMap(); } if (autoCorrelationCount > MAX_CORRELATION_COUNT) { return Collections.emptyMap(); } autoCorrelationCount++; Map<String, Object> map = new LinkedHashMap<>(); if (putClass) { if (containsGeneric) { map.put("class", typeCanonicalText.substring(0, typeCanonicalText.indexOf("<"))); } else { map.put("class", typeCanonicalText); } } for (PsiField field : psiClass.getAllFields()) { if (field.hasModifierProperty(PsiModifier.STATIC) || field.hasModifierProperty(PsiModifier.FINAL) || field.hasModifierProperty(PsiModifier.TRANSIENT)) { continue; } String fieldType = field.getType().getCanonicalText(); // 不存在泛型 if (!containsGeneric) { map.put(field.getName(), assemblePsiClass(fieldType, project, autoCorrelationCount, putClass)); continue; } // 存在泛型
if (TypeUtils.isPrimitiveOrSimpleType(fieldType.replaceAll("\\[]", ""))) {
map.put(field.getName(), assemblePsiClass(fieldType, project, autoCorrelationCount, putClass)); } else if (PsiClassHelper.findPsiClass(fieldType, project) == null) { map.put(field.getName(), assemblePsiClass(typeCanonicalText.substring(typeCanonicalText.indexOf("<") + 1, typeCanonicalText.lastIndexOf(">")), project, autoCorrelationCount, putClass)); } else { map.put(field.getName(), assemblePsiClass(fieldType, project, autoCorrelationCount, putClass)); } } return map; } /** * 查找类 * * @param typeCanonicalText 参数类型全限定名称 * @param project 当前project * @return 查找到的类 */ public static PsiClass findPsiClass(String typeCanonicalText, Project project) { // 基本类型转化为对应包装类型 typeCanonicalText = TypeUtils.primitiveToBox(typeCanonicalText); String className = typeCanonicalText; if (className.contains("[]")) { className = className.replaceAll("\\[]", ""); } if (className.contains("<")) { className = className.substring(0, className.indexOf("<")); } if (className.lastIndexOf(".") > 0) { className = className.substring(className.lastIndexOf(".") + 1); } PsiClass[] classesByName = PsiShortNamesCache.getInstance(project).getClassesByName(className, GlobalSearchScope.allScope(project)); for (PsiClass psiClass : classesByName) { if (typeCanonicalText.startsWith(psiClass.getQualifiedName())) { return psiClass; } } return null; } }
src/main/java/io/github/newhoo/restkit/ext/solon/helper/PsiClassHelper.java
newhoo-RestfulBox-Solon-8533971
[ { "filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/BaseLanguageResolver.java", "retrieved_chunk": " PsiClass fieldClass = PsiClassHelper.findPsiClass(field.getType().getCanonicalText(), psiMethod.getProject());\n if (fieldClass != null && fieldClass.isEnum()) {\n PsiField[] enumFields = fieldClass.getAllFields();\n list.add(new KV(field.getName(), enumFields.length > 1 ? enumFields[0].getName() : \"\"));\n } else {\n Object fieldDefaultValue = TypeUtils.getExampleValue(field.getType().getPresentableText(), true);\n list.add(new KV(field.getName(), String.valueOf(fieldDefaultValue)));\n }\n }\n }", "score": 0.8209899663925171 }, { "filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/BaseLanguageResolver.java", "retrieved_chunk": " // 数组|集合\n if (TypeUtils.isArray(paramType) || TypeUtils.isList(paramType)) {\n paramType = TypeUtils.isArray(paramType)\n ? paramType.replace(\"[]\", \"\")\n : paramType.contains(\"<\")\n ? paramType.substring(paramType.indexOf(\"<\") + 1, paramType.lastIndexOf(\">\"))\n : Object.class.getCanonicalName();\n }\n // 简单常用类型\n if (TypeUtils.isPrimitiveOrSimpleType(paramType)) {", "score": 0.8167381286621094 }, { "filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/BaseLanguageResolver.java", "retrieved_chunk": " list.add(new KV(parameter.getParamName(), String.valueOf(TypeUtils.getExampleValue(paramType, true))));\n continue;\n }\n // 文件类型\n Set<String> fileParameterTypeSet = Stream.of(\"org.noear.solon.core.handle.UploadedFile\").collect(Collectors.toSet());\n if (fileParameterTypeSet.contains(paramType)) {\n list.add(new KV(parameter.getParamName(), \"file@[filepath]\"));\n continue;\n }\n PsiClass psiClass = PsiClassHelper.findPsiClass(paramType, psiMethod.getProject());", "score": 0.8122954368591309 }, { "filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/BaseLanguageResolver.java", "retrieved_chunk": " if (psiClass != null) {\n PsiField[] fields = psiClass.getAllFields();\n if (psiClass.isEnum()) {\n list.add(new KV(parameter.getParamName(), fields.length > 1 ? fields[0].getName() : \"\"));\n continue;\n }\n for (PsiField field : fields) {\n if (field.hasModifierProperty(PsiModifier.STATIC) || field.hasModifierProperty(PsiModifier.TRANSIENT)) {\n continue;\n }", "score": 0.8117697238922119 }, { "filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/BaseLanguageResolver.java", "retrieved_chunk": " if (requestParamAnno != null) {\n String paramName = ObjectUtils.defaultIfNull(PsiAnnotationHelper.getAnnotationValue(requestParamAnno, \"value\"),\n ObjectUtils.defaultIfNull(PsiAnnotationHelper.getAnnotationValue(requestParamAnno, \"name\"), psiParameter.getName()\n ));\n Parameter parameter = new Parameter(paramTypeName, paramName);\n parameterList.add(parameter);\n continue;\n }\n // 其他未包含指定注解\n Parameter parameter = new Parameter(paramTypeName, psiParameter.getName());", "score": 0.8077612519264221 } ]
java
if (TypeUtils.isPrimitiveOrSimpleType(fieldType.replaceAll("\\[]", ""))) {
package io.github.newhoo.restkit.ext.solon.helper; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiEnumConstant; import com.intellij.psi.PsiField; import com.intellij.psi.PsiModifier; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.PsiShortNamesCache; import io.github.newhoo.restkit.ext.solon.util.TypeUtils; import io.github.newhoo.restkit.util.JsonUtils; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; /** * PsiClassHelper in Java * * @author newhoo * @since 1.0.0 */ public class PsiClassHelper { private static final int MAX_CORRELATION_COUNT = 6; public static String convertClassToJSON(String className, Project project) { Object o = assemblePsiClass(className, project, 0, false); return JsonUtils.toJson(o); } public static Object assemblePsiClass(String typeCanonicalText, Project project, int autoCorrelationCount, boolean putClass) { boolean containsGeneric = typeCanonicalText.contains("<"); // 数组|集合 if (TypeUtils.isArray(typeCanonicalText) || TypeUtils.isList(typeCanonicalText)) { String elementType = TypeUtils.isArray(typeCanonicalText) ? typeCanonicalText.replace("[]", "") : containsGeneric ? typeCanonicalText.substring(typeCanonicalText.indexOf("<") + 1, typeCanonicalText.lastIndexOf(">")) : Object.class.getCanonicalName(); return Collections.singletonList(assemblePsiClass(elementType, project, autoCorrelationCount, putClass)); } PsiClass psiClass = PsiClassHelper.findPsiClass(typeCanonicalText, project); if (psiClass == null) { //简单常用类型 if (TypeUtils.isPrimitiveOrSimpleType(typeCanonicalText)) { return
TypeUtils.getExampleValue(typeCanonicalText, false);
} return Collections.emptyMap(); } //简单常用类型 if (TypeUtils.isPrimitiveOrSimpleType(typeCanonicalText)) { return TypeUtils.getExampleValue(typeCanonicalText, false); } // 枚举 if (psiClass.isEnum()) { PsiField[] enumFields = psiClass.getFields(); for (PsiField enumField : enumFields) { if (enumField instanceof PsiEnumConstant) { return enumField.getName(); } } return ""; } // Map if (TypeUtils.isMap(typeCanonicalText)) { return Collections.emptyMap(); } if (autoCorrelationCount > MAX_CORRELATION_COUNT) { return Collections.emptyMap(); } autoCorrelationCount++; Map<String, Object> map = new LinkedHashMap<>(); if (putClass) { if (containsGeneric) { map.put("class", typeCanonicalText.substring(0, typeCanonicalText.indexOf("<"))); } else { map.put("class", typeCanonicalText); } } for (PsiField field : psiClass.getAllFields()) { if (field.hasModifierProperty(PsiModifier.STATIC) || field.hasModifierProperty(PsiModifier.FINAL) || field.hasModifierProperty(PsiModifier.TRANSIENT)) { continue; } String fieldType = field.getType().getCanonicalText(); // 不存在泛型 if (!containsGeneric) { map.put(field.getName(), assemblePsiClass(fieldType, project, autoCorrelationCount, putClass)); continue; } // 存在泛型 if (TypeUtils.isPrimitiveOrSimpleType(fieldType.replaceAll("\\[]", ""))) { map.put(field.getName(), assemblePsiClass(fieldType, project, autoCorrelationCount, putClass)); } else if (PsiClassHelper.findPsiClass(fieldType, project) == null) { map.put(field.getName(), assemblePsiClass(typeCanonicalText.substring(typeCanonicalText.indexOf("<") + 1, typeCanonicalText.lastIndexOf(">")), project, autoCorrelationCount, putClass)); } else { map.put(field.getName(), assemblePsiClass(fieldType, project, autoCorrelationCount, putClass)); } } return map; } /** * 查找类 * * @param typeCanonicalText 参数类型全限定名称 * @param project 当前project * @return 查找到的类 */ public static PsiClass findPsiClass(String typeCanonicalText, Project project) { // 基本类型转化为对应包装类型 typeCanonicalText = TypeUtils.primitiveToBox(typeCanonicalText); String className = typeCanonicalText; if (className.contains("[]")) { className = className.replaceAll("\\[]", ""); } if (className.contains("<")) { className = className.substring(0, className.indexOf("<")); } if (className.lastIndexOf(".") > 0) { className = className.substring(className.lastIndexOf(".") + 1); } PsiClass[] classesByName = PsiShortNamesCache.getInstance(project).getClassesByName(className, GlobalSearchScope.allScope(project)); for (PsiClass psiClass : classesByName) { if (typeCanonicalText.startsWith(psiClass.getQualifiedName())) { return psiClass; } } return null; } }
src/main/java/io/github/newhoo/restkit/ext/solon/helper/PsiClassHelper.java
newhoo-RestfulBox-Solon-8533971
[ { "filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/BaseLanguageResolver.java", "retrieved_chunk": " // 数组|集合\n if (TypeUtils.isArray(paramType) || TypeUtils.isList(paramType)) {\n paramType = TypeUtils.isArray(paramType)\n ? paramType.replace(\"[]\", \"\")\n : paramType.contains(\"<\")\n ? paramType.substring(paramType.indexOf(\"<\") + 1, paramType.lastIndexOf(\">\"))\n : Object.class.getCanonicalName();\n }\n // 简单常用类型\n if (TypeUtils.isPrimitiveOrSimpleType(paramType)) {", "score": 0.8087471723556519 }, { "filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/BaseLanguageResolver.java", "retrieved_chunk": " ));\n PsiClass fieldClass = PsiClassHelper.findPsiClass(psiParameter.getType().getCanonicalText(), psiMethod.getProject());\n if (fieldClass != null && fieldClass.isEnum()) {\n PsiField[] enumFields = fieldClass.getAllFields();\n list.add(new KV(headerName, enumFields.length > 1 ? enumFields[0].getName() : \"\"));\n } else {\n Object fieldDefaultValue = TypeUtils.getExampleValue(psiParameter.getType().getPresentableText(), true);\n list.add(new KV(headerName, String.valueOf(fieldDefaultValue)));\n }\n }", "score": 0.8022958040237427 }, { "filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/BaseLanguageResolver.java", "retrieved_chunk": " list.add(new KV(parameter.getParamName(), String.valueOf(TypeUtils.getExampleValue(paramType, true))));\n continue;\n }\n // 文件类型\n Set<String> fileParameterTypeSet = Stream.of(\"org.noear.solon.core.handle.UploadedFile\").collect(Collectors.toSet());\n if (fileParameterTypeSet.contains(paramType)) {\n list.add(new KV(parameter.getParamName(), \"file@[filepath]\"));\n continue;\n }\n PsiClass psiClass = PsiClassHelper.findPsiClass(paramType, psiMethod.getProject());", "score": 0.8021062612533569 }, { "filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/BaseLanguageResolver.java", "retrieved_chunk": " PsiClass fieldClass = PsiClassHelper.findPsiClass(field.getType().getCanonicalText(), psiMethod.getProject());\n if (fieldClass != null && fieldClass.isEnum()) {\n PsiField[] enumFields = fieldClass.getAllFields();\n list.add(new KV(field.getName(), enumFields.length > 1 ? enumFields[0].getName() : \"\"));\n } else {\n Object fieldDefaultValue = TypeUtils.getExampleValue(field.getType().getPresentableText(), true);\n list.add(new KV(field.getName(), String.valueOf(fieldDefaultValue)));\n }\n }\n }", "score": 0.8021009564399719 }, { "filename": "src/main/java/io/github/newhoo/restkit/ext/solon/util/TypeUtils.java", "retrieved_chunk": " case \"double\":\n return \"java.lang.Double\";\n case \"boolean\":\n return \"java.lang.Boolean\";\n default:\n }\n return classType;\n }\n @NotNull\n public static Object getExampleValue(String parameterType, boolean isRandom) {", "score": 0.8008323907852173 } ]
java
TypeUtils.getExampleValue(typeCanonicalText, false);
package com.example.RestaurantManagement.Services; import com.example.RestaurantManagement.Models.TableBooking; import com.example.RestaurantManagement.Models.Tables; import com.example.RestaurantManagement.Repositories.TableBookingRepository; import com.example.RestaurantManagement.Repositories.TablesRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.sql.Date; import java.sql.Time; import java.util.List; @Service public class TableBookingService { private final TableBookingRepository tableBookingRepository; private final TablesRepository tablesRepository; @Autowired public TableBookingService(TableBookingRepository tableBookingRepository, TablesRepository tablesRepository) { this.tableBookingRepository = tableBookingRepository; this.tablesRepository = tablesRepository; } public List<Tables> getAllTables() { return tablesRepository.findAll(); } public List<TableBooking> getAllBookings() { return tableBookingRepository.findAll(); } public String bookTable(int tableId, Date date, Time time, String info) { Tables table = tablesRepository.findById(tableId).orElse(null); if (table == null) { return "Столик не найден"; } TableBooking booking = new TableBooking(); booking.setTable(table); booking.setDate(date); booking.setTime(time); booking.setInfo(info); tableBookingRepository.save(booking); return "Столик успешно забронирован"; } public boolean isTableBooked(int tableId, Date date, Time time) { List<TableBooking> bookings = this.getAllBookings(); for (TableBooking booking : bookings) { if (booking.getTable().getId() == tableId && booking.getDate()
.equals(date) && booking.getTime().equals(time)) {
return true; } } return false; } public void deleteBooking(int id) { tableBookingRepository.deleteById(id); } }
RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/TableBookingService.java
Neural-Enigma-RestaurantManagement-Spring-Boot-Java-086881a
[ { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/TableBookingController.java", "retrieved_chunk": " DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"HH:mm\");\n LocalTime localTime = LocalTime.parse(time, formatter);\n Time sqlTime = Time.valueOf(localTime);\n String message = tableBookingService.bookTable(tableId, date, sqlTime, info);\n model.addAttribute(\"message\", message);\n List<Tables> allTables = tableBookingService.getAllTables();\n model.addAttribute(\"tables\", allTables);\n Date currentDate = Date.valueOf(LocalDate.now());\n Date maxDate = Date.valueOf(LocalDate.now().plusDays(3));\n model.addAttribute(\"currentDate\", currentDate);", "score": 0.9050989151000977 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/TableBookingController.java", "retrieved_chunk": " }\n model.addAttribute(\"times\", times);\n return \"book-table\";\n }\n @PostMapping(\"/book-table\")\n public String bookTable(@RequestParam(\"table_id\") int tableId,\n @RequestParam(\"date\") Date date,\n @RequestParam(\"time\") String time,\n @RequestParam(\"info\") String info,\n Model model) {", "score": 0.8651515245437622 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Models/TableBooking.java", "retrieved_chunk": "package com.example.RestaurantManagement.Models;\nimport jakarta.persistence.*;\nimport java.sql.Date;\nimport java.sql.Time;\n@Entity\n@Table(name = \"tables_booking\")\npublic class TableBooking {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private int id;", "score": 0.8466697335243225 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Repositories/TableBookingRepository.java", "retrieved_chunk": "package com.example.RestaurantManagement.Repositories;\nimport com.example.RestaurantManagement.Models.TableBooking;\nimport com.example.RestaurantManagement.Models.Tables;\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.stereotype.Repository;\nimport java.sql.Time;\nimport java.util.Date;\nimport java.util.List;\n@Repository\npublic interface TableBookingRepository extends JpaRepository<TableBooking, Integer> {", "score": 0.8463506698608398 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/TableBookingController.java", "retrieved_chunk": " return \"book-table\";\n }\n @PostMapping(\"/book-table/{id}/delete\")\n public String deleteBooking(@PathVariable(\"id\") int id, Model model) {\n tableBookingService.deleteBooking(id);\n return \"redirect:/book-table\";\n }\n}", "score": 0.8345664143562317 } ]
java
.equals(date) && booking.getTime().equals(time)) {
package com.example.RestaurantManagement.Services; import com.example.RestaurantManagement.Models.TableBooking; import com.example.RestaurantManagement.Models.Tables; import com.example.RestaurantManagement.Repositories.TableBookingRepository; import com.example.RestaurantManagement.Repositories.TablesRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.sql.Date; import java.sql.Time; import java.util.List; @Service public class TableBookingService { private final TableBookingRepository tableBookingRepository; private final TablesRepository tablesRepository; @Autowired public TableBookingService(TableBookingRepository tableBookingRepository, TablesRepository tablesRepository) { this.tableBookingRepository = tableBookingRepository; this.tablesRepository = tablesRepository; } public List<Tables> getAllTables() { return tablesRepository.findAll(); } public List<TableBooking> getAllBookings() { return tableBookingRepository.findAll(); } public String bookTable(int tableId, Date date, Time time, String info) { Tables table = tablesRepository.findById(tableId).orElse(null); if (table == null) { return "Столик не найден"; } TableBooking booking = new TableBooking(); booking.setTable(table); booking.setDate(date); booking.setTime(time); booking.setInfo(info); tableBookingRepository.save(booking); return "Столик успешно забронирован"; } public boolean isTableBooked(int tableId, Date date, Time time) { List<TableBooking> bookings = this.getAllBookings(); for (TableBooking booking : bookings) { if (booking.getTable()
.getId() == tableId && booking.getDate().equals(date) && booking.getTime().equals(time)) {
return true; } } return false; } public void deleteBooking(int id) { tableBookingRepository.deleteById(id); } }
RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/TableBookingService.java
Neural-Enigma-RestaurantManagement-Spring-Boot-Java-086881a
[ { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/TableBookingController.java", "retrieved_chunk": " DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"HH:mm\");\n LocalTime localTime = LocalTime.parse(time, formatter);\n Time sqlTime = Time.valueOf(localTime);\n String message = tableBookingService.bookTable(tableId, date, sqlTime, info);\n model.addAttribute(\"message\", message);\n List<Tables> allTables = tableBookingService.getAllTables();\n model.addAttribute(\"tables\", allTables);\n Date currentDate = Date.valueOf(LocalDate.now());\n Date maxDate = Date.valueOf(LocalDate.now().plusDays(3));\n model.addAttribute(\"currentDate\", currentDate);", "score": 0.9053166508674622 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/TableBookingController.java", "retrieved_chunk": " }\n model.addAttribute(\"times\", times);\n return \"book-table\";\n }\n @PostMapping(\"/book-table\")\n public String bookTable(@RequestParam(\"table_id\") int tableId,\n @RequestParam(\"date\") Date date,\n @RequestParam(\"time\") String time,\n @RequestParam(\"info\") String info,\n Model model) {", "score": 0.8650528788566589 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Repositories/TableBookingRepository.java", "retrieved_chunk": "package com.example.RestaurantManagement.Repositories;\nimport com.example.RestaurantManagement.Models.TableBooking;\nimport com.example.RestaurantManagement.Models.Tables;\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.stereotype.Repository;\nimport java.sql.Time;\nimport java.util.Date;\nimport java.util.List;\n@Repository\npublic interface TableBookingRepository extends JpaRepository<TableBooking, Integer> {", "score": 0.8472809791564941 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Models/TableBooking.java", "retrieved_chunk": "package com.example.RestaurantManagement.Models;\nimport jakarta.persistence.*;\nimport java.sql.Date;\nimport java.sql.Time;\n@Entity\n@Table(name = \"tables_booking\")\npublic class TableBooking {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private int id;", "score": 0.8464301824569702 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/TableBookingController.java", "retrieved_chunk": " return \"book-table\";\n }\n @PostMapping(\"/book-table/{id}/delete\")\n public String deleteBooking(@PathVariable(\"id\") int id, Model model) {\n tableBookingService.deleteBooking(id);\n return \"redirect:/book-table\";\n }\n}", "score": 0.835138738155365 } ]
java
.getId() == tableId && booking.getDate().equals(date) && booking.getTime().equals(time)) {
package de.cubeattack.neoprotect.velocity.proxyprotocol; import com.velocitypowered.api.proxy.Player; import com.velocitypowered.proxy.VelocityServer; import com.velocitypowered.proxy.connection.MinecraftConnection; import com.velocitypowered.proxy.connection.client.ConnectedPlayer; import com.velocitypowered.proxy.network.ConnectionManager; import com.velocitypowered.proxy.network.Connections; import com.velocitypowered.proxy.network.ServerChannelInitializerHolder; import com.velocitypowered.proxy.protocol.packet.KeepAlive; import de.cubeattack.neoprotect.core.Config; import de.cubeattack.neoprotect.core.NeoProtectPlugin; import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse; import de.cubeattack.neoprotect.core.model.debugtool.KeepAliveResponseKey; import de.cubeattack.neoprotect.velocity.NeoProtectVelocity; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelInitializer; import io.netty.channel.epoll.EpollSocketChannel; import io.netty.channel.epoll.EpollTcpInfo; import io.netty.handler.codec.haproxy.HAProxyMessage; import io.netty.handler.codec.haproxy.HAProxyMessageDecoder; import java.lang.reflect.Field; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.ArrayList; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; public class ProxyProtocol { private final Reflection.MethodInvoker initChannelMethod = Reflection.getMethod(ChannelInitializer.class, "initChannel", Channel.class); public ProxyProtocol(NeoProtectVelocity instance) { instance.getLogger().info("Proceeding with the server channel injection..."); try { VelocityServer velocityServer = (VelocityServer) instance.getProxy(); Reflection.FieldAccessor<ConnectionManager> connectionManagerFieldAccessor = Reflection.getField(VelocityServer.class, ConnectionManager.class, 0); ConnectionManager connectionManager = connectionManagerFieldAccessor.get(velocityServer); ChannelInitializer<?> oldInitializer = connectionManager.getServerChannelInitializer().get(); ChannelInitializer<Channel> channelInitializer = new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel channel) { try { instance.getCore().debug("Open channel (" + channel.remoteAddress().toString() + ")"); initChannelMethod.getMethod().setAccessible(true); initChannelMethod.invoke(oldInitializer, channel); AtomicReference<InetSocketAddress> playerAddress = new AtomicReference<>(); String sourceAddress = ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress(); if (channel.localAddress().toString().startsWith("local:") || sourceAddress.equals(Config.getGeyserServerIP())) { instance.getCore().debug("Detected bedrock player (return)"); return; } if (!instance.getCore().getDirectConnectWhitelist().contains(sourceAddress)) { if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null || instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, sourceAddress)))) { channel.close(); instance.getCore().debug("Close connection IP (" + channel.remoteAddress() + ") doesn't match to Neo-IPs (close / return)"); return; } instance.getCore().debug("Adding handler..."); if (instance.getCore().isSetup() && Config.isProxyProtocol()) { addProxyProtocolHandler(channel, playerAddress); instance.getCore().debug("Plugin is setup & ProxyProtocol is on (Added proxyProtocolHandler)"); } addKeepAlivePacketHandler(channel, playerAddress, velocityServer, instance); instance.getCore().debug("Added KeepAlivePacketHandler"); } instance.getCore().debug("Connecting finished"); } catch (Exception ex) { instance.getLogger().log(Level.SEVERE, "Cannot inject incoming channel " + channel, ex); } } }; ServerChannelInitializerHolder newChannelHolder = (ServerChannelInitializerHolder) Reflection.getConstructor(ServerChannelInitializerHolder.class, ChannelInitializer.class).invoke(channelInitializer); Reflection.FieldAccessor<ServerChannelInitializerHolder> serverChannelInitializerHolderFieldAccessor = Reflection.getField(ConnectionManager.class, ServerChannelInitializerHolder.class, 0); Field channelInitializerHolderField = serverChannelInitializerHolderFieldAccessor.getField(); channelInitializerHolderField.setAccessible(true); channelInitializerHolderField.set(connectionManager, newChannelHolder); instance.getLogger().info("Found the server channel and added the handler. Injection successfully!"); } catch (Exception ex) { instance.getLogger().log(Level.SEVERE, "An unknown error has occurred", ex); } } public void addProxyProtocolHandler(Channel channel, AtomicReference<InetSocketAddress> inetAddress) { channel.pipeline().names().forEach((n) -> { if (n.equals("HAProxyMessageDecoder#0")) channel.pipeline().remove("HAProxyMessageDecoder#0"); if (n.equals("ProxyProtocol$1#0")) channel.pipeline().remove("ProxyProtocol$1#0"); }); channel.pipeline().addFirst("haproxy-decoder", new HAProxyMessageDecoder()); channel.pipeline().addAfter("haproxy-decoder", "haproxy-handler", new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HAProxyMessage) { HAProxyMessage message = (HAProxyMessage) msg; Reflection.FieldAccessor<SocketAddress> fieldAccessor = Reflection.getField(MinecraftConnection.class, SocketAddress.class, 0); inetAddress.set(new InetSocketAddress(message.sourceAddress(), message.sourcePort())); fieldAccessor.set(channel.pipeline().get(Connections.HANDLER), inetAddress.get()); } else { super.channelRead(ctx, msg); } } }); } public void addKeepAlivePacketHandler(Channel channel, AtomicReference<InetSocketAddress> inetAddress, VelocityServer velocityServer, NeoProtectPlugin instance) { channel.pipeline().addAfter("minecraft-decoder", "neo-keep-alive-handler", new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { super.channelRead(ctx, msg); if (!(msg instanceof KeepAlive)) { return; } KeepAlive keepAlive = (KeepAlive) msg; ConcurrentHashMap<KeepAliveResponseKey, Long> pingMap = instance.getCore().getPingMap(); instance.getCore().debug("Received KeepAlivePackets (" + keepAlive.getRandomId() + ")"); for (KeepAliveResponseKey keepAliveResponseKey : pingMap.keySet()) { if (!keepAliveResponseKey.getAddress().equals(inetAddress.get()) || !(keepAliveResponseKey.getId() == keepAlive.getRandomId())) { continue; } instance.getCore().debug("KeepAlivePackets matched to DebugKeepAlivePacket"); for (Player player : velocityServer.getAllPlayers()) { if (!(player).getRemoteAddress().equals(inetAddress.get())) { continue; } instance.getCore().debug("Player matched to DebugKeepAlivePacket (loading data...)"); EpollTcpInfo tcpInfo = ((EpollSocketChannel) channel).tcpInfo(); EpollTcpInfo tcpInfoBackend = ((EpollSocketChannel) ((ConnectedPlayer) player).getConnection().getChannel()).tcpInfo(); long ping = System.currentTimeMillis() - pingMap.get(keepAliveResponseKey); long neoRTT = 0; long backendRTT = 0; if (tcpInfo != null) { neoRTT = tcpInfo.rtt() / 1000; } if (tcpInfoBackend != null) { backendRTT = tcpInfoBackend.rtt() / 1000; } ConcurrentHashMap<String, ArrayList<DebugPingResponse>> map = instance.getCore().getDebugPingResponses(); if (!map.containsKey(player.getUsername())) {
instance.getCore().getDebugPingResponses().put(player.getUsername(), new ArrayList<>());
} map.get(player.getUsername()).add(new DebugPingResponse(ping, neoRTT, backendRTT, inetAddress.get(), channel.remoteAddress())); instance.getCore().debug("Loading completed"); instance.getCore().debug(" "); } pingMap.remove(keepAliveResponseKey); } } }); } public static boolean isIPInRange(String ipRange, String ipAddress) { if (!ipRange.contains("/")) { ipRange = ipRange + "/32"; } long targetIntAddress = ipToDecimal(ipAddress); int range = Integer.parseInt(ipRange.split("/")[1]); String startIP = ipRange.split("/")[0]; long startIntAddress = ipToDecimal(startIP); return targetIntAddress <= (startIntAddress + (long) Math.pow(2, (32 - range))) && targetIntAddress >= startIntAddress; } public static long ipToDecimal(String ipAddress) throws IllegalArgumentException { String[] parts = ipAddress.split("\\."); if (parts.length != 4) { return -1; } long decimal = 0; for (int i = 0; i < 4; i++) { int octet = Integer.parseInt(parts[i]); if (octet < 0 || octet > 255) { return -1; } decimal += (long) (octet * Math.pow(256, 3 - i)); } return decimal; } }
src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java
NeoProtect-NeoPlugin-a71f673
[ { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java", "retrieved_chunk": " if (tcpInfoBackend != null) {\n backendRTT = tcpInfoBackend.rtt() / 1000;\n }\n ConcurrentHashMap<String, ArrayList<DebugPingResponse>> map = instance.getCore().getDebugPingResponses();\n if (!map.containsKey(player.getName())) {\n instance.getCore().getDebugPingResponses().put(player.getName(), new ArrayList<>());\n }\n map.get(player.getName()).add(new DebugPingResponse(ping, neoRTT, backendRTT, inetAddress.get(), channel.remoteAddress()));\n instance.getCore().debug(\"Loading completed\");\n instance.getCore().debug(\" \");", "score": 0.9490031003952026 }, { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java", "retrieved_chunk": " }\n instance.getCore().debug(\"Player matched to DebugKeepAlivePacket (loading data...)\");\n EpollTcpInfo tcpInfo = ((EpollSocketChannel) channel).tcpInfo();\n EpollTcpInfo tcpInfoBackend = ((EpollSocketChannel) ((UserConnection) player).getServer().getCh().getHandle()).tcpInfo();\n long ping = System.currentTimeMillis() - pingMap.get(keepAliveResponseKey);\n long neoRTT = 0;\n long backendRTT = 0;\n if (tcpInfo != null) {\n neoRTT = tcpInfo.rtt() / 1000;\n }", "score": 0.9196408987045288 }, { "filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java", "retrieved_chunk": " ConcurrentHashMap<KeepAliveResponseKey, Long> pingMap = instance.getCore().getPingMap();\n instance.getCore().debug(\"Received KeepAlivePackets (\" + keepAlive.getRandomId() + \")\");\n for (KeepAliveResponseKey keepAliveResponseKey : pingMap.keySet()) {\n if (!keepAliveResponseKey.getAddress().equals(inetAddress.get()) || !(keepAliveResponseKey.getId() == keepAlive.getRandomId())) {\n continue;\n }\n instance.getCore().debug(\"KeepAlivePackets matched to DebugKeepAlivePacket\");\n for (ProxiedPlayer player : BungeeCord.getInstance().getPlayers()) {\n if (!(player).getPendingConnection().getSocketAddress().equals(inetAddress.get())) {\n continue;", "score": 0.866680920124054 }, { "filename": "src/main/java/de/cubeattack/neoprotect/core/model/debugtool/DebugPingResponse.java", "retrieved_chunk": "package de.cubeattack.neoprotect.core.model.debugtool;\nimport java.net.SocketAddress;\n@SuppressWarnings(\"unused\")\npublic class DebugPingResponse {\n private final long proxyToBackendLatenz;\n private final long playerToProxyLatenz;\n private final long neoToProxyLatenz;\n private final SocketAddress playerAddress;\n private final SocketAddress neoAddress;\n public DebugPingResponse(long playerToProxyLatenz, long neoToProxyLatenz, long proxyToBackendLatenz, SocketAddress playerAddress, SocketAddress neoAddress) {", "score": 0.8446968197822571 }, { "filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java", "retrieved_chunk": " long minPlayerToNeoLatenz = Long.MAX_VALUE;\n configuration.set(\"players.\" + playerName + \".playerAddress\", list.get(0).getPlayerAddress());\n configuration.set(\"players.\" + playerName + \".neoAddress\", list.get(0).getNeoAddress());\n for (DebugPingResponse response : list) {\n if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())\n maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();\n if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())\n maxNeoToProxyLatenz = response.getNeoToProxyLatenz();\n if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())\n maxProxyToBackendLatenz = response.getProxyToBackendLatenz();", "score": 0.8441576957702637 } ]
java
instance.getCore().getDebugPingResponses().put(player.getUsername(), new ArrayList<>());
package com.example.RestaurantManagement.Services; import com.example.RestaurantManagement.Models.Staff; import com.example.RestaurantManagement.Repositories.StaffRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class StaffService { private final StaffRepository staffRepository; @Autowired public StaffService(StaffRepository staffRepository) { this.staffRepository = staffRepository; } public List<Staff> getAllStaff() { return staffRepository.findAll(); } public void saveStaff(Staff staff) { staffRepository.save(staff); } public void updateStaff(Staff staff) { staffRepository.save(staff); } public void deleteStaff(Staff staff) { staffRepository.delete(staff); } public Staff getStaffById(int id) { Optional<Staff> staff = staffRepository.findById(id); if (staff.isPresent()) { return staff.get(); } else { throw new RuntimeException("Staff not found for id: " + id); } } public boolean loginExists(String login) { return
staffRepository.findByLogin(login) != null;
} }
RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/StaffService.java
Neural-Enigma-RestaurantManagement-Spring-Boot-Java-086881a
[ { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Repositories/StaffRepository.java", "retrieved_chunk": "package com.example.RestaurantManagement.Repositories;\nimport com.example.RestaurantManagement.Models.Staff;\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.stereotype.Repository;\nimport java.util.Optional;\n@Repository\npublic interface StaffRepository extends JpaRepository<Staff, Integer> {\n Optional<Staff> findStaffByLogin(String login);\n Staff findByLogin(String login);\n}", "score": 0.8952351212501526 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/AuthorisationController.java", "retrieved_chunk": " public String login() {\n return \"login\";\n }\n @PostMapping(\"/login\")\n public String postLogin(@RequestParam String login, @RequestParam String password, Model model, HttpSession session) {\n Optional<Staff> optionalStaff = staffRepository.findStaffByLogin(login);\n if (optionalStaff.isPresent()) {\n Staff staff = optionalStaff.get();\n if (staff.getPassword().equals(password) && staff.getDismissalFromWork() == null) {\n session.setAttribute(\"staff\", staff);", "score": 0.8587014675140381 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/StaffController.java", "retrieved_chunk": " @GetMapping(\"/staff\")\n public String getStaff(Model model) {\n model.addAttribute(\"staff\", staffService.getAllStaff());\n model.addAttribute(\"newStaff\", new Staff());\n model.addAttribute(\"currentUser\", getCurrentUser());\n return \"staff\";\n }\n @PostMapping(\"/staff/add\")\n public String addStaff(@ModelAttribute Staff staff, Model model) {\n if (staffService.loginExists(staff.getLogin())) {", "score": 0.8508742451667786 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/AuthorisationController.java", "retrieved_chunk": "package com.example.RestaurantManagement.Controllers;\nimport com.example.RestaurantManagement.Models.Staff;\nimport com.example.RestaurantManagement.Repositories.StaffRepository;\nimport jakarta.servlet.http.HttpSession;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestParam;", "score": 0.8458101749420166 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/StaffController.java", "retrieved_chunk": " staffService.deleteStaff(staff);\n return \"redirect:/staff\";\n }\n public Staff getCurrentUser() {\n return (Staff) session.getAttribute(\"staff\");\n }\n}", "score": 0.8429611921310425 } ]
java
staffRepository.findByLogin(login) != null;
package com.example.RestaurantManagement.Controllers; import com.example.RestaurantManagement.Models.Staff; import com.example.RestaurantManagement.Services.StaffService; import jakarta.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class StaffController { @Autowired private HttpSession session; private final StaffService staffService; @Autowired public StaffController(StaffService staffService) { this.staffService = staffService; } @GetMapping("/staff") public String getStaff(Model model) { model.addAttribute("staff", staffService.getAllStaff()); model.addAttribute("newStaff", new Staff()); model.addAttribute("currentUser", getCurrentUser()); return "staff"; } @PostMapping("/staff/add") public String addStaff(@ModelAttribute Staff staff, Model model) { if (staffService.loginExists(staff.getLogin())) { model.addAttribute("error", "Логин уже существует!"); model.addAttribute("staff", staffService.getAllStaff()); model.addAttribute("newStaff", staff); return "redirect:/staff"; } java.util.Date currentDate = new java.util.Date();
staff.setApparatusEmployed(new java.sql.Date(currentDate.getTime()));
staffService.saveStaff(staff); return "redirect:/staff"; } @PostMapping("/staff/update") public String updateStaff(@RequestParam("id") int id, @RequestParam("role") String role) { Staff staff = staffService.getStaffById(id); staff.setRole(role); staffService.updateStaff(staff); return "redirect:/staff"; } @PostMapping("/staff/delete") public String deleteStaff(@RequestParam("id") int id) { Staff staff = staffService.getStaffById(id); staffService.deleteStaff(staff); return "redirect:/staff"; } public Staff getCurrentUser() { return (Staff) session.getAttribute("staff"); } }
RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/StaffController.java
Neural-Enigma-RestaurantManagement-Spring-Boot-Java-086881a
[ { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/AuthorisationController.java", "retrieved_chunk": "package com.example.RestaurantManagement.Controllers;\nimport com.example.RestaurantManagement.Models.Staff;\nimport com.example.RestaurantManagement.Repositories.StaffRepository;\nimport jakarta.servlet.http.HttpSession;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestParam;", "score": 0.8631578683853149 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/AuthorisationController.java", "retrieved_chunk": " public String login() {\n return \"login\";\n }\n @PostMapping(\"/login\")\n public String postLogin(@RequestParam String login, @RequestParam String password, Model model, HttpSession session) {\n Optional<Staff> optionalStaff = staffRepository.findStaffByLogin(login);\n if (optionalStaff.isPresent()) {\n Staff staff = optionalStaff.get();\n if (staff.getPassword().equals(password) && staff.getDismissalFromWork() == null) {\n session.setAttribute(\"staff\", staff);", "score": 0.8565647006034851 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/AuthorisationController.java", "retrieved_chunk": " model.addAttribute(\"errorMessage\", \"Неверный логин или пароль\");\n return \"login\";\n }\n @GetMapping(\"/logout\")\n public String logout(HttpSession request) {\n request.setAttribute(\"staff\", null);\n return \"redirect:/login\";\n }\n}", "score": 0.8534220457077026 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/ShiftController.java", "retrieved_chunk": " }\n @GetMapping(\"/assign-shifts\")\n public String assignShifts(Model model) {\n model.addAttribute(\"staffs\", staffRepository.findAll());\n return \"assign-shifts\";\n }\n @PostMapping(\"/assign-shift\")\n public String assignShift(int staff_id, Date date) {\n Staff staff = staffRepository.findById(staff_id).orElseThrow();\n WorkHour workHour = new WorkHour();", "score": 0.8524291515350342 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/ShiftController.java", "retrieved_chunk": "package com.example.RestaurantManagement.Controllers;\nimport com.example.RestaurantManagement.Models.Staff;\nimport com.example.RestaurantManagement.Models.WorkHour;\nimport com.example.RestaurantManagement.Repositories.StaffRepository;\nimport com.example.RestaurantManagement.Repositories.WorkHourRepository;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.PathVariable;", "score": 0.8483271598815918 } ]
java
staff.setApparatusEmployed(new java.sql.Date(currentDate.getTime()));
package com.example.RestaurantManagement.Controllers; import com.example.RestaurantManagement.Models.Dish; import com.example.RestaurantManagement.Models.DishType; import com.example.RestaurantManagement.Repositories.DishTypeRepository; import com.example.RestaurantManagement.Services.DishService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.List; @Controller public class MenuController { private final DishService dishService; private final DishTypeRepository dishTypeRepository; public MenuController(DishService dishService, DishTypeRepository dishTypeRepository) { this.dishService = dishService; this.dishTypeRepository = dishTypeRepository; } @GetMapping("/menu") public String showMenu(Model model) { List<Dish> dishes = dishService.getAllDishes(); List<DishType> dishTypes = dishTypeRepository.findAll(); model.addAttribute("dishes", dishes); model.addAttribute("dishTypes", dishTypes); return "menu"; } @PostMapping("/menu/edit") public String editDish(@RequestParam("id") int id, @RequestParam("name") String name, @RequestParam("cost") double cost, @RequestParam("type") String typeName) { if (dishService.checkIfDishIsOrdered(id)) { } else { dishService.editDish(id, name, cost, typeName); } return "redirect:/menu"; } @PostMapping("/menu/delete") public String deleteDish(@RequestParam("id") int id) { if (dishService.checkIfDishIsOrdered(id)) { } else { dishService.deleteDish(id); } return "redirect:/menu"; } @PostMapping("/menu/add") public String addDish(@RequestParam("name") String name, @RequestParam("cost") double cost, @RequestParam("type") String typeName) { dishService.addDish(name, cost, typeName); return "redirect:/menu"; } @GetMapping("/menu/{id}/details") public String showDishDetails(@PathVariable("id") int id, Model model) { Dish dish = dishService.getDishById(id); model.addAttribute("dish", dish); return "dishDetails"; } @PostMapping("/menu/{id}/edit") public String editDishDetails(@PathVariable("id") int id, @RequestParam("name") String name, @RequestParam("description") String description, @RequestParam("recipe") String recipe){ // @RequestParam("image") MultipartFile image) throws IOException {
dishService.editDishDetails(id, name, description, recipe);
//, image.getBytes()); return "redirect:/menu/{id}/details"; } @GetMapping("kitchen/{id}/recipe") public String showRecipe(@PathVariable("id") int id, Model model) { Dish dish = dishService.getDishById(id); model.addAttribute("dish", dish); return "recipe"; } }
RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/MenuController.java
Neural-Enigma-RestaurantManagement-Spring-Boot-Java-086881a
[ { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/DishService.java", "retrieved_chunk": " dish.setCost(cost);\n dish.setType(dishType);\n dishRepository.save(dish);\n }\n }\n public Dish getDishById(int id) {\n return dishRepository.findById(id).orElse(null);\n }\n public void editDishDetails(int id, String name, String description, String recipe){//}, byte[] image) {\n Dish dish = getDishById(id);", "score": 0.9255983829498291 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java", "retrieved_chunk": " }\n return \"redirect:/manage-orders\";\n }\n @PostMapping(\"/update-dish-status-manager/{id}\")\n public String updateDishStatus(@PathVariable int id, @RequestParam String status) {\n Optional<OrderedDish> optionalDish = orderedDishRepository.findById(id);\n if (optionalDish.isPresent()) {\n OrderedDish dish = optionalDish.get();\n dish.setStatus(status);\n orderedDishRepository.save(dish);", "score": 0.8979599475860596 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/DishService.java", "retrieved_chunk": " this.dishTypeRepository = dishTypeRepository;\n }\n public List<Dish> getAllDishes() {\n return dishRepository.findAll();\n }\n public boolean checkIfDishIsOrdered(int id) {\n List<OrderedDish> orderedDishes = orderedDishRepository.findAllByDish_Id(id);\n return !orderedDishes.isEmpty();\n }\n public void editDish(int id, String name, double cost, String typeName) {", "score": 0.8909988403320312 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/DishService.java", "retrieved_chunk": " Optional<Dish> optionalDish = dishRepository.findById(id);\n if (optionalDish.isPresent()) {\n Dish dish = optionalDish.get();\n dish.setName(name);\n dish.setCost(cost);\n DishType dishType = dishTypeRepository.findByName(typeName);\n if (dishType != null) {\n dish.setType(dishType);\n }\n dishRepository.save(dish);", "score": 0.887109100818634 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/KitchenController.java", "retrieved_chunk": " @PostMapping(\"/update-dish-status/{id}\")\n public String updateDishStatus(@PathVariable(\"id\") int id, @RequestParam(\"status\") String status) {\n Optional<OrderedDish> optionalOrderedDish = orderedDishRepository.findById(id);\n if (optionalOrderedDish.isPresent()) {\n OrderedDish orderedDish = optionalOrderedDish.get();\n orderedDish.setStatus(status);\n orderedDishRepository.save(orderedDish);\n List<OrderedDish> dishesInOrder = orderedDishRepository.findAllByOrder(orderedDish.getOrder());\n boolean allMatch = dishesInOrder.stream()\n .allMatch(dish -> dish.getStatus().equals(status));", "score": 0.8816598057746887 } ]
java
dishService.editDishDetails(id, name, description, recipe);
package com.example.RestaurantManagement.Services; import com.example.RestaurantManagement.Models.Dish; import com.example.RestaurantManagement.Models.DishType; import com.example.RestaurantManagement.Models.OrderedDish; import com.example.RestaurantManagement.Repositories.DishRepository; import com.example.RestaurantManagement.Repositories.DishTypeRepository; import com.example.RestaurantManagement.Repositories.OrderedDishRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class DishService { private final DishRepository dishRepository; private final OrderedDishRepository orderedDishRepository; private final DishTypeRepository dishTypeRepository; @Autowired public DishService(DishRepository dishRepository, OrderedDishRepository orderedDishRepository, DishTypeRepository dishTypeRepository) { this.dishRepository = dishRepository; this.orderedDishRepository = orderedDishRepository; this.dishTypeRepository = dishTypeRepository; } public List<Dish> getAllDishes() { return dishRepository.findAll(); } public boolean checkIfDishIsOrdered(int id) { List<OrderedDish> orderedDishes = orderedDishRepository.findAllByDish_Id(id); return !orderedDishes.isEmpty(); } public void editDish(int id, String name, double cost, String typeName) { Optional<Dish> optionalDish = dishRepository.findById(id); if (optionalDish.isPresent()) { Dish dish = optionalDish.get(); dish.setName(name); dish.setCost(cost); DishType dishType = dishTypeRepository.findByName(typeName); if (dishType != null) { dish.setType(dishType); } dishRepository.save(dish); } } public void deleteDish(int id) { dishRepository.deleteById(id); } public void addDish(String name, double cost, String typeName) {
DishType dishType = dishTypeRepository.findByName(typeName);
if (dishType != null) { Dish dish = new Dish(); dish.setName(name); dish.setCost(cost); dish.setType(dishType); dishRepository.save(dish); } } public Dish getDishById(int id) { return dishRepository.findById(id).orElse(null); } public void editDishDetails(int id, String name, String description, String recipe){//}, byte[] image) { Dish dish = getDishById(id); if (dish != null) { dish.setName(name); dish.setDescription(description); dish.setRecipe(recipe); // dish.setImage(image); dishRepository.save(dish); } } }
RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/DishService.java
Neural-Enigma-RestaurantManagement-Spring-Boot-Java-086881a
[ { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/MenuController.java", "retrieved_chunk": " public String deleteDish(@RequestParam(\"id\") int id) {\n if (dishService.checkIfDishIsOrdered(id)) {\n } else {\n dishService.deleteDish(id);\n }\n return \"redirect:/menu\";\n }\n @PostMapping(\"/menu/add\")\n public String addDish(@RequestParam(\"name\") String name, @RequestParam(\"cost\") double cost,\n @RequestParam(\"type\") String typeName) {", "score": 0.9076449871063232 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/MenuController.java", "retrieved_chunk": " @PostMapping(\"/menu/edit\")\n public String editDish(@RequestParam(\"id\") int id, @RequestParam(\"name\") String name,\n @RequestParam(\"cost\") double cost, @RequestParam(\"type\") String typeName) {\n if (dishService.checkIfDishIsOrdered(id)) {\n } else {\n dishService.editDish(id, name, cost, typeName);\n }\n return \"redirect:/menu\";\n }\n @PostMapping(\"/menu/delete\")", "score": 0.8878300786018372 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/MenuController.java", "retrieved_chunk": " dishService.addDish(name, cost, typeName);\n return \"redirect:/menu\";\n }\n @GetMapping(\"/menu/{id}/details\")\n public String showDishDetails(@PathVariable(\"id\") int id, Model model) {\n Dish dish = dishService.getDishById(id);\n model.addAttribute(\"dish\", dish);\n return \"dishDetails\";\n }\n @PostMapping(\"/menu/{id}/edit\")", "score": 0.8811770677566528 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Repositories/DishTypeRepository.java", "retrieved_chunk": "package com.example.RestaurantManagement.Repositories;\nimport com.example.RestaurantManagement.Models.DishType;\nimport org.springframework.data.jpa.repository.JpaRepository;\npublic interface DishTypeRepository extends JpaRepository<DishType, Integer> {\n DishType findByName(String name);\n}", "score": 0.8738414645195007 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Models/DishType.java", "retrieved_chunk": "package com.example.RestaurantManagement.Models;\nimport jakarta.persistence.*;\n@Entity\n@Table(name = \"dish_types\")\npublic class DishType {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private int id;\n @Column(name = \"name\")\n private String name;", "score": 0.8609672784805298 } ]
java
DishType dishType = dishTypeRepository.findByName(typeName);
package com.example.RestaurantManagement.Controllers; import com.example.RestaurantManagement.Models.Dish; import com.example.RestaurantManagement.Models.DishType; import com.example.RestaurantManagement.Repositories.DishTypeRepository; import com.example.RestaurantManagement.Services.DishService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.List; @Controller public class MenuController { private final DishService dishService; private final DishTypeRepository dishTypeRepository; public MenuController(DishService dishService, DishTypeRepository dishTypeRepository) { this.dishService = dishService; this.dishTypeRepository = dishTypeRepository; } @GetMapping("/menu") public String showMenu(Model model) { List<Dish> dishes = dishService.getAllDishes(); List<DishType> dishTypes = dishTypeRepository.findAll(); model.addAttribute("dishes", dishes); model.addAttribute("dishTypes", dishTypes); return "menu"; } @PostMapping("/menu/edit") public String editDish(@RequestParam("id") int id, @RequestParam("name") String name, @RequestParam("cost") double cost, @RequestParam("type") String typeName) { if
(dishService.checkIfDishIsOrdered(id)) {
} else { dishService.editDish(id, name, cost, typeName); } return "redirect:/menu"; } @PostMapping("/menu/delete") public String deleteDish(@RequestParam("id") int id) { if (dishService.checkIfDishIsOrdered(id)) { } else { dishService.deleteDish(id); } return "redirect:/menu"; } @PostMapping("/menu/add") public String addDish(@RequestParam("name") String name, @RequestParam("cost") double cost, @RequestParam("type") String typeName) { dishService.addDish(name, cost, typeName); return "redirect:/menu"; } @GetMapping("/menu/{id}/details") public String showDishDetails(@PathVariable("id") int id, Model model) { Dish dish = dishService.getDishById(id); model.addAttribute("dish", dish); return "dishDetails"; } @PostMapping("/menu/{id}/edit") public String editDishDetails(@PathVariable("id") int id, @RequestParam("name") String name, @RequestParam("description") String description, @RequestParam("recipe") String recipe){ // @RequestParam("image") MultipartFile image) throws IOException { dishService.editDishDetails(id, name, description, recipe);//, image.getBytes()); return "redirect:/menu/{id}/details"; } @GetMapping("kitchen/{id}/recipe") public String showRecipe(@PathVariable("id") int id, Model model) { Dish dish = dishService.getDishById(id); model.addAttribute("dish", dish); return "recipe"; } }
RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/MenuController.java
Neural-Enigma-RestaurantManagement-Spring-Boot-Java-086881a
[ { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/DishService.java", "retrieved_chunk": " this.dishTypeRepository = dishTypeRepository;\n }\n public List<Dish> getAllDishes() {\n return dishRepository.findAll();\n }\n public boolean checkIfDishIsOrdered(int id) {\n List<OrderedDish> orderedDishes = orderedDishRepository.findAllByDish_Id(id);\n return !orderedDishes.isEmpty();\n }\n public void editDish(int id, String name, double cost, String typeName) {", "score": 0.9337239265441895 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/DishService.java", "retrieved_chunk": " dish.setCost(cost);\n dish.setType(dishType);\n dishRepository.save(dish);\n }\n }\n public Dish getDishById(int id) {\n return dishRepository.findById(id).orElse(null);\n }\n public void editDishDetails(int id, String name, String description, String recipe){//}, byte[] image) {\n Dish dish = getDishById(id);", "score": 0.9160805344581604 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/DishService.java", "retrieved_chunk": " }\n }\n public void deleteDish(int id) {\n dishRepository.deleteById(id);\n }\n public void addDish(String name, double cost, String typeName) {\n DishType dishType = dishTypeRepository.findByName(typeName);\n if (dishType != null) {\n Dish dish = new Dish();\n dish.setName(name);", "score": 0.912566065788269 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/DishService.java", "retrieved_chunk": " Optional<Dish> optionalDish = dishRepository.findById(id);\n if (optionalDish.isPresent()) {\n Dish dish = optionalDish.get();\n dish.setName(name);\n dish.setCost(cost);\n DishType dishType = dishTypeRepository.findByName(typeName);\n if (dishType != null) {\n dish.setType(dishType);\n }\n dishRepository.save(dish);", "score": 0.900101900100708 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java", "retrieved_chunk": " }\n return \"redirect:/manage-orders\";\n }\n @PostMapping(\"/update-dish-status-manager/{id}\")\n public String updateDishStatus(@PathVariable int id, @RequestParam String status) {\n Optional<OrderedDish> optionalDish = orderedDishRepository.findById(id);\n if (optionalDish.isPresent()) {\n OrderedDish dish = optionalDish.get();\n dish.setStatus(status);\n orderedDishRepository.save(dish);", "score": 0.8916890621185303 } ]
java
(dishService.checkIfDishIsOrdered(id)) {
package com.example.RestaurantManagement.Controllers; import com.example.RestaurantManagement.Models.Order; import com.example.RestaurantManagement.Models.OrderedDish; import com.example.RestaurantManagement.Repositories.OrderRepository; import com.example.RestaurantManagement.Repositories.OrderedDishRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @Controller public class KitchenController { @Autowired private OrderedDishRepository orderedDishRepository; @Autowired private OrderRepository orderRepository; @GetMapping("/kitchen") public String getKitchen(Model model) { List<OrderedDish> orderedDishes = orderedDishRepository.findAll(); List<OrderedDish> acceptedDishes = orderedDishes.stream() .filter(dish -> dish.getStatus().equals("Принят")) .collect(Collectors.toList()); model.addAttribute("orderedDishes", acceptedDishes); return "kitchen"; } @PostMapping("/update-dish-status/{id}") public String updateDishStatus(@PathVariable("id") int id, @RequestParam("status") String status) { Optional<OrderedDish> optionalOrderedDish = orderedDishRepository.findById(id); if (optionalOrderedDish.isPresent()) { OrderedDish orderedDish = optionalOrderedDish.get();
orderedDish.setStatus(status);
orderedDishRepository.save(orderedDish); List<OrderedDish> dishesInOrder = orderedDishRepository.findAllByOrder(orderedDish.getOrder()); boolean allMatch = dishesInOrder.stream() .allMatch(dish -> dish.getStatus().equals(status)); if (allMatch) { Order order = orderedDish.getOrder(); order.setStatus(status); orderRepository.save(order); } } return "redirect:/kitchen"; } }
RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/KitchenController.java
Neural-Enigma-RestaurantManagement-Spring-Boot-Java-086881a
[ { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java", "retrieved_chunk": " }\n return \"redirect:/manage-orders\";\n }\n @PostMapping(\"/update-dish-status-manager/{id}\")\n public String updateDishStatus(@PathVariable int id, @RequestParam String status) {\n Optional<OrderedDish> optionalDish = orderedDishRepository.findById(id);\n if (optionalDish.isPresent()) {\n OrderedDish dish = optionalDish.get();\n dish.setStatus(status);\n orderedDishRepository.save(dish);", "score": 0.95216965675354 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java", "retrieved_chunk": " public String updateStatusManager(@PathVariable int id, @RequestParam String status) {\n Optional<Order> optionalOrder = orderRepository.findById(id);\n if (optionalOrder.isPresent()) {\n Order order = optionalOrder.get();\n order.setStatus(status);\n order.getOrderedDishes().forEach(dish -> dish.setStatus(status));\n if (status.equals(\"Закрыт\")) {\n order.setEndTime(Timestamp.valueOf(LocalDateTime.now()));\n }\n orderRepository.save(order);", "score": 0.9076394438743591 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java", "retrieved_chunk": " orders = orders.stream()\n .filter(order -> order.getStartTime().toLocalDateTime().toLocalDate().equals(date))\n .collect(Collectors.toList());\n }\n model.addAttribute(\"orders\", orders);\n return \"view-orders\";\n }\n @PostMapping(\"/update-status/{id}\")\n public String updateStatus(@PathVariable int id, @RequestParam String status) {\n Optional<Order> optionalOrder = orderRepository.findById(id);", "score": 0.906749427318573 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java", "retrieved_chunk": " if (optionalOrder.isPresent()) {\n Order order = optionalOrder.get();\n order.setStatus(status);\n order.getOrderedDishes().forEach(dish -> dish.setStatus(status));\n if (status.equals(\"Закрыт\")) {\n order.setEndTime(Timestamp.valueOf(LocalDateTime.now()));\n }\n orderRepository.save(order);\n }\n return \"redirect:/view-orders\";", "score": 0.8926820158958435 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/MenuController.java", "retrieved_chunk": " public String editDishDetails(@PathVariable(\"id\") int id, @RequestParam(\"name\") String name,\n @RequestParam(\"description\") String description,\n @RequestParam(\"recipe\") String recipe){\n// @RequestParam(\"image\") MultipartFile image) throws IOException {\n dishService.editDishDetails(id, name, description, recipe);//, image.getBytes());\n return \"redirect:/menu/{id}/details\";\n }\n @GetMapping(\"kitchen/{id}/recipe\")\n public String showRecipe(@PathVariable(\"id\") int id, Model model) {\n Dish dish = dishService.getDishById(id);", "score": 0.8852725625038147 } ]
java
orderedDish.setStatus(status);
package com.example.RestaurantManagement.Controllers; import com.example.RestaurantManagement.Models.Order; import com.example.RestaurantManagement.Models.OrderedDish; import com.example.RestaurantManagement.Repositories.OrderRepository; import com.example.RestaurantManagement.Repositories.OrderedDishRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @Controller public class KitchenController { @Autowired private OrderedDishRepository orderedDishRepository; @Autowired private OrderRepository orderRepository; @GetMapping("/kitchen") public String getKitchen(Model model) { List<OrderedDish> orderedDishes = orderedDishRepository.findAll(); List<OrderedDish> acceptedDishes = orderedDishes.stream() .filter(dish -> dish.getStatus().equals("Принят")) .collect(Collectors.toList()); model.addAttribute("orderedDishes", acceptedDishes); return "kitchen"; } @PostMapping("/update-dish-status/{id}") public String updateDishStatus(@PathVariable("id") int id, @RequestParam("status") String status) { Optional<OrderedDish> optionalOrderedDish = orderedDishRepository.findById(id); if (optionalOrderedDish.isPresent()) { OrderedDish orderedDish = optionalOrderedDish.get(); orderedDish.setStatus(status); orderedDishRepository.save(orderedDish); List
<OrderedDish> dishesInOrder = orderedDishRepository.findAllByOrder(orderedDish.getOrder());
boolean allMatch = dishesInOrder.stream() .allMatch(dish -> dish.getStatus().equals(status)); if (allMatch) { Order order = orderedDish.getOrder(); order.setStatus(status); orderRepository.save(order); } } return "redirect:/kitchen"; } }
RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/KitchenController.java
Neural-Enigma-RestaurantManagement-Spring-Boot-Java-086881a
[ { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java", "retrieved_chunk": " }\n return \"redirect:/manage-orders\";\n }\n @PostMapping(\"/update-dish-status-manager/{id}\")\n public String updateDishStatus(@PathVariable int id, @RequestParam String status) {\n Optional<OrderedDish> optionalDish = orderedDishRepository.findById(id);\n if (optionalDish.isPresent()) {\n OrderedDish dish = optionalDish.get();\n dish.setStatus(status);\n orderedDishRepository.save(dish);", "score": 0.9643198847770691 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java", "retrieved_chunk": " public String updateStatusManager(@PathVariable int id, @RequestParam String status) {\n Optional<Order> optionalOrder = orderRepository.findById(id);\n if (optionalOrder.isPresent()) {\n Order order = optionalOrder.get();\n order.setStatus(status);\n order.getOrderedDishes().forEach(dish -> dish.setStatus(status));\n if (status.equals(\"Закрыт\")) {\n order.setEndTime(Timestamp.valueOf(LocalDateTime.now()));\n }\n orderRepository.save(order);", "score": 0.9314843416213989 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java", "retrieved_chunk": " orders = orders.stream()\n .filter(order -> order.getStartTime().toLocalDateTime().toLocalDate().equals(date))\n .collect(Collectors.toList());\n }\n model.addAttribute(\"orders\", orders);\n return \"view-orders\";\n }\n @PostMapping(\"/update-status/{id}\")\n public String updateStatus(@PathVariable int id, @RequestParam String status) {\n Optional<Order> optionalOrder = orderRepository.findById(id);", "score": 0.8987002372741699 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java", "retrieved_chunk": " Order order = dish.getOrder();\n boolean allSameStatus = order.getOrderedDishes().stream()\n .allMatch(d -> d.getStatus().equals(status));\n if (allSameStatus) {\n order.setStatus(status);\n if (status.equals(\"Закрыт\")) {\n order.setEndTime(Timestamp.valueOf(LocalDateTime.now()));\n }\n orderRepository.save(order);\n }", "score": 0.8901852369308472 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java", "retrieved_chunk": " if (optionalOrder.isPresent()) {\n Order order = optionalOrder.get();\n order.setStatus(status);\n order.getOrderedDishes().forEach(dish -> dish.setStatus(status));\n if (status.equals(\"Закрыт\")) {\n order.setEndTime(Timestamp.valueOf(LocalDateTime.now()));\n }\n orderRepository.save(order);\n }\n return \"redirect:/view-orders\";", "score": 0.8865393400192261 } ]
java
<OrderedDish> dishesInOrder = orderedDishRepository.findAllByOrder(orderedDish.getOrder());
package com.example.RestaurantManagement.Controllers; import com.example.RestaurantManagement.Models.Dish; import com.example.RestaurantManagement.Models.DishType; import com.example.RestaurantManagement.Repositories.DishTypeRepository; import com.example.RestaurantManagement.Services.DishService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.List; @Controller public class MenuController { private final DishService dishService; private final DishTypeRepository dishTypeRepository; public MenuController(DishService dishService, DishTypeRepository dishTypeRepository) { this.dishService = dishService; this.dishTypeRepository = dishTypeRepository; } @GetMapping("/menu") public String showMenu(Model model) { List<Dish> dishes = dishService.getAllDishes(); List<DishType> dishTypes = dishTypeRepository.findAll(); model.addAttribute("dishes", dishes); model.addAttribute("dishTypes", dishTypes); return "menu"; } @PostMapping("/menu/edit") public String editDish(@RequestParam("id") int id, @RequestParam("name") String name, @RequestParam("cost") double cost, @RequestParam("type") String typeName) { if (dishService.checkIfDishIsOrdered(id)) { } else { dishService.editDish(id, name, cost, typeName); } return "redirect:/menu"; } @PostMapping("/menu/delete") public String deleteDish(@RequestParam("id") int id) {
if (dishService.checkIfDishIsOrdered(id)) {
} else { dishService.deleteDish(id); } return "redirect:/menu"; } @PostMapping("/menu/add") public String addDish(@RequestParam("name") String name, @RequestParam("cost") double cost, @RequestParam("type") String typeName) { dishService.addDish(name, cost, typeName); return "redirect:/menu"; } @GetMapping("/menu/{id}/details") public String showDishDetails(@PathVariable("id") int id, Model model) { Dish dish = dishService.getDishById(id); model.addAttribute("dish", dish); return "dishDetails"; } @PostMapping("/menu/{id}/edit") public String editDishDetails(@PathVariable("id") int id, @RequestParam("name") String name, @RequestParam("description") String description, @RequestParam("recipe") String recipe){ // @RequestParam("image") MultipartFile image) throws IOException { dishService.editDishDetails(id, name, description, recipe);//, image.getBytes()); return "redirect:/menu/{id}/details"; } @GetMapping("kitchen/{id}/recipe") public String showRecipe(@PathVariable("id") int id, Model model) { Dish dish = dishService.getDishById(id); model.addAttribute("dish", dish); return "recipe"; } }
RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/MenuController.java
Neural-Enigma-RestaurantManagement-Spring-Boot-Java-086881a
[ { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/DishService.java", "retrieved_chunk": " }\n }\n public void deleteDish(int id) {\n dishRepository.deleteById(id);\n }\n public void addDish(String name, double cost, String typeName) {\n DishType dishType = dishTypeRepository.findByName(typeName);\n if (dishType != null) {\n Dish dish = new Dish();\n dish.setName(name);", "score": 0.9178433418273926 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/DishService.java", "retrieved_chunk": " this.dishTypeRepository = dishTypeRepository;\n }\n public List<Dish> getAllDishes() {\n return dishRepository.findAll();\n }\n public boolean checkIfDishIsOrdered(int id) {\n List<OrderedDish> orderedDishes = orderedDishRepository.findAllByDish_Id(id);\n return !orderedDishes.isEmpty();\n }\n public void editDish(int id, String name, double cost, String typeName) {", "score": 0.9030685424804688 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/DishService.java", "retrieved_chunk": " dish.setCost(cost);\n dish.setType(dishType);\n dishRepository.save(dish);\n }\n }\n public Dish getDishById(int id) {\n return dishRepository.findById(id).orElse(null);\n }\n public void editDishDetails(int id, String name, String description, String recipe){//}, byte[] image) {\n Dish dish = getDishById(id);", "score": 0.8896834254264832 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java", "retrieved_chunk": " }\n return \"redirect:/manage-orders\";\n }\n @PostMapping(\"/update-dish-status-manager/{id}\")\n public String updateDishStatus(@PathVariable int id, @RequestParam String status) {\n Optional<OrderedDish> optionalDish = orderedDishRepository.findById(id);\n if (optionalDish.isPresent()) {\n OrderedDish dish = optionalDish.get();\n dish.setStatus(status);\n orderedDishRepository.save(dish);", "score": 0.8818796277046204 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/DishService.java", "retrieved_chunk": " Optional<Dish> optionalDish = dishRepository.findById(id);\n if (optionalDish.isPresent()) {\n Dish dish = optionalDish.get();\n dish.setName(name);\n dish.setCost(cost);\n DishType dishType = dishTypeRepository.findByName(typeName);\n if (dishType != null) {\n dish.setType(dishType);\n }\n dishRepository.save(dish);", "score": 0.879456639289856 } ]
java
if (dishService.checkIfDishIsOrdered(id)) {
package com.example.RestaurantManagement.Controllers; import com.example.RestaurantManagement.Models.Staff; import com.example.RestaurantManagement.Services.StaffService; import jakarta.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class StaffController { @Autowired private HttpSession session; private final StaffService staffService; @Autowired public StaffController(StaffService staffService) { this.staffService = staffService; } @GetMapping("/staff") public String getStaff(Model model) { model.addAttribute("staff", staffService.getAllStaff()); model.addAttribute("newStaff", new Staff()); model.addAttribute("currentUser", getCurrentUser()); return "staff"; } @PostMapping("/staff/add") public String addStaff(@ModelAttribute Staff staff, Model model) { if (staffService.loginExists(staff.getLogin())) { model.addAttribute("error", "Логин уже существует!");
model.addAttribute("staff", staffService.getAllStaff());
model.addAttribute("newStaff", staff); return "redirect:/staff"; } java.util.Date currentDate = new java.util.Date(); staff.setApparatusEmployed(new java.sql.Date(currentDate.getTime())); staffService.saveStaff(staff); return "redirect:/staff"; } @PostMapping("/staff/update") public String updateStaff(@RequestParam("id") int id, @RequestParam("role") String role) { Staff staff = staffService.getStaffById(id); staff.setRole(role); staffService.updateStaff(staff); return "redirect:/staff"; } @PostMapping("/staff/delete") public String deleteStaff(@RequestParam("id") int id) { Staff staff = staffService.getStaffById(id); staffService.deleteStaff(staff); return "redirect:/staff"; } public Staff getCurrentUser() { return (Staff) session.getAttribute("staff"); } }
RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/StaffController.java
Neural-Enigma-RestaurantManagement-Spring-Boot-Java-086881a
[ { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/AuthorisationController.java", "retrieved_chunk": " public String login() {\n return \"login\";\n }\n @PostMapping(\"/login\")\n public String postLogin(@RequestParam String login, @RequestParam String password, Model model, HttpSession session) {\n Optional<Staff> optionalStaff = staffRepository.findStaffByLogin(login);\n if (optionalStaff.isPresent()) {\n Staff staff = optionalStaff.get();\n if (staff.getPassword().equals(password) && staff.getDismissalFromWork() == null) {\n session.setAttribute(\"staff\", staff);", "score": 0.8824008107185364 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/AuthorisationController.java", "retrieved_chunk": " model.addAttribute(\"errorMessage\", \"Неверный логин или пароль\");\n return \"login\";\n }\n @GetMapping(\"/logout\")\n public String logout(HttpSession request) {\n request.setAttribute(\"staff\", null);\n return \"redirect:/login\";\n }\n}", "score": 0.8764612674713135 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/AuthorisationController.java", "retrieved_chunk": "package com.example.RestaurantManagement.Controllers;\nimport com.example.RestaurantManagement.Models.Staff;\nimport com.example.RestaurantManagement.Repositories.StaffRepository;\nimport jakarta.servlet.http.HttpSession;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestParam;", "score": 0.8754294514656067 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/AuthorisationController.java", "retrieved_chunk": " switch (staff.getRole()) {\n case \"ОФИЦИАНТ\" -> {\n return \"redirect:/create-order\";\n }\n case \"АДМИНИСТРАТОР\" -> {\n return \"redirect:/staff\";\n }\n case \"МЕНЕДЖЕР\" -> {\n return \"redirect:/view-schedule\";\n }", "score": 0.8579826951026917 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/AuthorisationController.java", "retrieved_chunk": "import java.util.Optional;\n@Controller\npublic class AuthorisationController {\n @Autowired\n StaffRepository staffRepository;\n @GetMapping(\"/\")\n public String defaultPageRedirect() {\n return \"redirect:/login\";\n }\n @GetMapping(\"/login\")", "score": 0.8549008369445801 } ]
java
model.addAttribute("staff", staffService.getAllStaff());
package com.example.RestaurantManagement.Controllers; import com.example.RestaurantManagement.Models.TableBooking; import com.example.RestaurantManagement.Models.Tables; import com.example.RestaurantManagement.Services.TableBookingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import java.sql.Date; import java.sql.Time; import java.time.LocalDate; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; @Controller public class TableBookingController { private final TableBookingService tableBookingService; @Autowired public TableBookingController(TableBookingService tableBookingService) { this.tableBookingService = tableBookingService; } @GetMapping("/book-table") public String bookingForm(Model model) { List<TableBooking> bookings = tableBookingService.getAllBookings(); model.addAttribute("bookings", bookings); List<Tables> allTables = tableBookingService.getAllTables(); model.addAttribute("tables", allTables); Date currentDate = Date.valueOf(LocalDate.now()); Date maxDate = Date.valueOf(LocalDate.now().plusDays(3)); model.addAttribute("currentDate", currentDate); model.addAttribute("maxDate", maxDate); List<LocalTime> times = new ArrayList<>(); for (LocalTime timeOption = LocalTime.of(12, 0); timeOption.isBefore(LocalTime.of(20, 30)); timeOption = timeOption.plusMinutes(30)) { times.add(timeOption); } model.addAttribute("times", times); return "book-table"; } @PostMapping("/book-table") public String bookTable(@RequestParam("table_id") int tableId, @RequestParam("date") Date date, @RequestParam("time") String time, @RequestParam("info") String info, Model model) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm"); LocalTime localTime = LocalTime.parse(time, formatter); Time sqlTime = Time.valueOf(localTime); String message = tableBookingService.bookTable(tableId, date, sqlTime, info); model.addAttribute("message", message); List
<Tables> allTables = tableBookingService.getAllTables();
model.addAttribute("tables", allTables); Date currentDate = Date.valueOf(LocalDate.now()); Date maxDate = Date.valueOf(LocalDate.now().plusDays(3)); model.addAttribute("currentDate", currentDate); model.addAttribute("maxDate", maxDate); List<LocalTime> times = new ArrayList<>(); for (LocalTime timeOption = LocalTime.of(12, 0); timeOption.isBefore(LocalTime.of(20, 30)); timeOption = timeOption.plusMinutes(30)) { times.add(timeOption); } model.addAttribute("times", times); List<TableBooking> bookings = tableBookingService.getAllBookings(); model.addAttribute("bookings", bookings); return "book-table"; } @PostMapping("/book-table/{id}/delete") public String deleteBooking(@PathVariable("id") int id, Model model) { tableBookingService.deleteBooking(id); return "redirect:/book-table"; } }
RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/TableBookingController.java
Neural-Enigma-RestaurantManagement-Spring-Boot-Java-086881a
[ { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/TableBookingService.java", "retrieved_chunk": " }\n TableBooking booking = new TableBooking();\n booking.setTable(table);\n booking.setDate(date);\n booking.setTime(time);\n booking.setInfo(info);\n tableBookingRepository.save(booking);\n return \"Столик успешно забронирован\";\n }\n public boolean isTableBooked(int tableId, Date date, Time time) {", "score": 0.9033370018005371 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/TableBookingService.java", "retrieved_chunk": " public List<Tables> getAllTables() {\n return tablesRepository.findAll();\n }\n public List<TableBooking> getAllBookings() {\n return tableBookingRepository.findAll();\n }\n public String bookTable(int tableId, Date date, Time time, String info) {\n Tables table = tablesRepository.findById(tableId).orElse(null);\n if (table == null) {\n return \"Столик не найден\";", "score": 0.8883979320526123 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/TableBookingService.java", "retrieved_chunk": "package com.example.RestaurantManagement.Services;\nimport com.example.RestaurantManagement.Models.TableBooking;\nimport com.example.RestaurantManagement.Models.Tables;\nimport com.example.RestaurantManagement.Repositories.TableBookingRepository;\nimport com.example.RestaurantManagement.Repositories.TablesRepository;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport java.sql.Date;\nimport java.sql.Time;\nimport java.util.List;", "score": 0.8559905886650085 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Models/TableBooking.java", "retrieved_chunk": "package com.example.RestaurantManagement.Models;\nimport jakarta.persistence.*;\nimport java.sql.Date;\nimport java.sql.Time;\n@Entity\n@Table(name = \"tables_booking\")\npublic class TableBooking {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private int id;", "score": 0.855221152305603 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/TableBookingService.java", "retrieved_chunk": " List<TableBooking> bookings = this.getAllBookings();\n for (TableBooking booking : bookings) {\n if (booking.getTable().getId() == tableId && booking.getDate().equals(date) && booking.getTime().equals(time)) {\n return true;\n }\n }\n return false;\n }\n public void deleteBooking(int id) {\n tableBookingRepository.deleteById(id);", "score": 0.8509081602096558 } ]
java
<Tables> allTables = tableBookingService.getAllTables();
package com.example.RestaurantManagement.Controllers; import com.example.RestaurantManagement.Models.Order; import com.example.RestaurantManagement.Models.OrderedDish; import com.example.RestaurantManagement.Repositories.OrderRepository; import com.example.RestaurantManagement.Repositories.OrderedDishRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @Controller public class KitchenController { @Autowired private OrderedDishRepository orderedDishRepository; @Autowired private OrderRepository orderRepository; @GetMapping("/kitchen") public String getKitchen(Model model) { List<OrderedDish> orderedDishes = orderedDishRepository.findAll(); List<OrderedDish> acceptedDishes = orderedDishes.stream() .filter(dish -> dish.getStatus().equals("Принят")) .collect(Collectors.toList()); model.addAttribute("orderedDishes", acceptedDishes); return "kitchen"; } @PostMapping("/update-dish-status/{id}") public String updateDishStatus(@PathVariable("id") int id, @RequestParam("status") String status) { Optional<OrderedDish> optionalOrderedDish = orderedDishRepository.findById(id); if (optionalOrderedDish.isPresent()) { OrderedDish orderedDish = optionalOrderedDish.get(); orderedDish.setStatus(status); orderedDishRepository.save(orderedDish); List<OrderedDish> dishesInOrder = orderedDishRepository.findAllByOrder(orderedDish.getOrder()); boolean allMatch = dishesInOrder.stream() .allMatch(dish -> dish.getStatus().equals(status)); if (allMatch) { Order order
= orderedDish.getOrder();
order.setStatus(status); orderRepository.save(order); } } return "redirect:/kitchen"; } }
RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/KitchenController.java
Neural-Enigma-RestaurantManagement-Spring-Boot-Java-086881a
[ { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java", "retrieved_chunk": " Order order = dish.getOrder();\n boolean allSameStatus = order.getOrderedDishes().stream()\n .allMatch(d -> d.getStatus().equals(status));\n if (allSameStatus) {\n order.setStatus(status);\n if (status.equals(\"Закрыт\")) {\n order.setEndTime(Timestamp.valueOf(LocalDateTime.now()));\n }\n orderRepository.save(order);\n }", "score": 0.9122111797332764 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java", "retrieved_chunk": " if (optionalOrder.isPresent()) {\n Order order = optionalOrder.get();\n order.setStatus(status);\n order.getOrderedDishes().forEach(dish -> dish.setStatus(status));\n if (status.equals(\"Закрыт\")) {\n order.setEndTime(Timestamp.valueOf(LocalDateTime.now()));\n }\n orderRepository.save(order);\n }\n return \"redirect:/view-orders\";", "score": 0.9105392694473267 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java", "retrieved_chunk": " }\n return \"redirect:/manage-orders\";\n }\n @PostMapping(\"/update-dish-status-manager/{id}\")\n public String updateDishStatus(@PathVariable int id, @RequestParam String status) {\n Optional<OrderedDish> optionalDish = orderedDishRepository.findById(id);\n if (optionalDish.isPresent()) {\n OrderedDish dish = optionalDish.get();\n dish.setStatus(status);\n orderedDishRepository.save(dish);", "score": 0.8754128217697144 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/DishService.java", "retrieved_chunk": " Optional<Dish> optionalDish = dishRepository.findById(id);\n if (optionalDish.isPresent()) {\n Dish dish = optionalDish.get();\n dish.setName(name);\n dish.setCost(cost);\n DishType dishType = dishTypeRepository.findByName(typeName);\n if (dishType != null) {\n dish.setType(dishType);\n }\n dishRepository.save(dish);", "score": 0.8722423315048218 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java", "retrieved_chunk": " public String updateStatusManager(@PathVariable int id, @RequestParam String status) {\n Optional<Order> optionalOrder = orderRepository.findById(id);\n if (optionalOrder.isPresent()) {\n Order order = optionalOrder.get();\n order.setStatus(status);\n order.getOrderedDishes().forEach(dish -> dish.setStatus(status));\n if (status.equals(\"Закрыт\")) {\n order.setEndTime(Timestamp.valueOf(LocalDateTime.now()));\n }\n orderRepository.save(order);", "score": 0.8654523491859436 } ]
java
= orderedDish.getOrder();
package com.example.RestaurantManagement.Controllers; import com.example.RestaurantManagement.Models.Staff; import com.example.RestaurantManagement.Services.StaffService; import jakarta.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class StaffController { @Autowired private HttpSession session; private final StaffService staffService; @Autowired public StaffController(StaffService staffService) { this.staffService = staffService; } @GetMapping("/staff") public String getStaff(Model model) { model.addAttribute("staff", staffService.getAllStaff()); model.addAttribute("newStaff", new Staff()); model.addAttribute("currentUser", getCurrentUser()); return "staff"; } @PostMapping("/staff/add") public String addStaff(@ModelAttribute Staff staff, Model model) { if (staffService.
loginExists(staff.getLogin())) {
model.addAttribute("error", "Логин уже существует!"); model.addAttribute("staff", staffService.getAllStaff()); model.addAttribute("newStaff", staff); return "redirect:/staff"; } java.util.Date currentDate = new java.util.Date(); staff.setApparatusEmployed(new java.sql.Date(currentDate.getTime())); staffService.saveStaff(staff); return "redirect:/staff"; } @PostMapping("/staff/update") public String updateStaff(@RequestParam("id") int id, @RequestParam("role") String role) { Staff staff = staffService.getStaffById(id); staff.setRole(role); staffService.updateStaff(staff); return "redirect:/staff"; } @PostMapping("/staff/delete") public String deleteStaff(@RequestParam("id") int id) { Staff staff = staffService.getStaffById(id); staffService.deleteStaff(staff); return "redirect:/staff"; } public Staff getCurrentUser() { return (Staff) session.getAttribute("staff"); } }
RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/StaffController.java
Neural-Enigma-RestaurantManagement-Spring-Boot-Java-086881a
[ { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/AuthorisationController.java", "retrieved_chunk": " public String login() {\n return \"login\";\n }\n @PostMapping(\"/login\")\n public String postLogin(@RequestParam String login, @RequestParam String password, Model model, HttpSession session) {\n Optional<Staff> optionalStaff = staffRepository.findStaffByLogin(login);\n if (optionalStaff.isPresent()) {\n Staff staff = optionalStaff.get();\n if (staff.getPassword().equals(password) && staff.getDismissalFromWork() == null) {\n session.setAttribute(\"staff\", staff);", "score": 0.8981574177742004 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/AuthorisationController.java", "retrieved_chunk": "package com.example.RestaurantManagement.Controllers;\nimport com.example.RestaurantManagement.Models.Staff;\nimport com.example.RestaurantManagement.Repositories.StaffRepository;\nimport jakarta.servlet.http.HttpSession;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestParam;", "score": 0.8744256496429443 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/AuthorisationController.java", "retrieved_chunk": " model.addAttribute(\"errorMessage\", \"Неверный логин или пароль\");\n return \"login\";\n }\n @GetMapping(\"/logout\")\n public String logout(HttpSession request) {\n request.setAttribute(\"staff\", null);\n return \"redirect:/login\";\n }\n}", "score": 0.8599923849105835 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/ShiftController.java", "retrieved_chunk": "package com.example.RestaurantManagement.Controllers;\nimport com.example.RestaurantManagement.Models.Staff;\nimport com.example.RestaurantManagement.Models.WorkHour;\nimport com.example.RestaurantManagement.Repositories.StaffRepository;\nimport com.example.RestaurantManagement.Repositories.WorkHourRepository;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.PathVariable;", "score": 0.8523116111755371 }, { "filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/AuthorisationController.java", "retrieved_chunk": "import java.util.Optional;\n@Controller\npublic class AuthorisationController {\n @Autowired\n StaffRepository staffRepository;\n @GetMapping(\"/\")\n public String defaultPageRedirect() {\n return \"redirect:/login\";\n }\n @GetMapping(\"/login\")", "score": 0.8492156267166138 } ]
java
loginExists(staff.getLogin())) {
/* * Conventional Commits Version Policy * Copyright (C) 2022-2023 Niels Basjes * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nl.basjes.maven.release.version.conventionalcommits; import org.apache.maven.scm.ChangeSet; import org.semver.Version; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * The set of rules that determine from the commit history what the next version should be. */ public class VersionRules { private final Pattern tagPattern; private final List<Pattern> majorUpdatePatterns = new ArrayList<>(); private final List<Pattern> minorUpdatePatterns = new ArrayList<>(); public VersionRules(ConventionalCommitsVersionConfig config) { int patternFlags = Pattern.MULTILINE | Pattern.DOTALL | Pattern.UNIX_LINES; // The default assumes then entire tag is what we need String tagRegex = "^(\\d+\\.\\d+\\.\\d+)$"; // The default rules following https://www.conventionalcommits.org/en/v1.0.0/ majorUpdatePatterns.add(Pattern.compile("^[a-zA-Z]+(?:\\([a-zA-Z\\d_-]+\\))?!: .*$", patternFlags)); majorUpdatePatterns.add(Pattern.compile("^BREAKING CHANGE:.*$", patternFlags)); minorUpdatePatterns.add(Pattern.compile("^feat(?:\\([a-zA-Z\\d_-]+\\))?: .*$", patternFlags)); if (config != null) { String semverConfigVersionTag = config.getVersionTag(); if (semverConfigVersionTag != null && !semverConfigVersionTag.trim().isEmpty()) { tagRegex = semverConfigVersionTag; } if (
!config.getMajorRules().isEmpty() || !config.getMinorRules().isEmpty()) {
majorUpdatePatterns.clear(); for (String majorRule : config.getMajorRules()) { majorUpdatePatterns.add(Pattern.compile(majorRule, patternFlags)); } minorUpdatePatterns.clear(); for (String minorRule : config.getMinorRules()) { minorUpdatePatterns.add(Pattern.compile(minorRule, patternFlags)); } } } tagPattern = Pattern.compile(tagRegex, Pattern.MULTILINE); } public Version.Element getMaxElementSinceLastVersionTag(CommitHistory commitHistory) { Version.Element maxElement = Version.Element.PATCH; for (ChangeSet change : commitHistory.getChanges()) { if (isMajorUpdate(change.getComment())) { // This is the highest possible: Immediately done return Version.Element.MAJOR; } else if (isMinorUpdate(change.getComment())) { // Have to wait, there may be another MAJOR one. maxElement = Version.Element.MINOR; } } return maxElement; } public boolean isMajorUpdate(String input) { return matchesAny(majorUpdatePatterns, input); } public boolean isMinorUpdate(String input) { return matchesAny(minorUpdatePatterns, input); } private boolean matchesAny(List<Pattern> patterns, String input) { for (Pattern pattern : patterns) { Matcher matcher = pattern.matcher(input); if (matcher.find()) { return true; } } return false; } public Pattern getTagPattern() { return tagPattern; } public List<Pattern> getMajorUpdatePatterns() { return majorUpdatePatterns; } public List<Pattern> getMinorUpdatePatterns() { return minorUpdatePatterns; } @Override public String toString() { StringBuilder result = new StringBuilder(); result.append("Conventional Commits config:\n"); result.append(" VersionTag:\n"); result.append(" >>>").append(tagPattern).append("<<<\n"); result.append(" Major Rules:\n"); for (Pattern majorUpdatePattern : majorUpdatePatterns) { result.append(" >>>").append(majorUpdatePattern).append("<<<\n"); } result.append(" Minor Rules:\n"); for (Pattern minorUpdatePattern : minorUpdatePatterns) { result.append(" >>>").append(minorUpdatePattern).append("<<<\n"); } return result.toString(); } }
src/main/java/nl/basjes/maven/release/version/conventionalcommits/VersionRules.java
nielsbasjes-conventional-commits-maven-release-151e36d
[ { "filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/ConfigParsingTest.java", "retrieved_chunk": " private final String customVersionTagRegex = \"^The awesome ([0-9]+\\\\.[0-9]+\\\\.[0-9]+) release$\";\n private final String customMajorRulesRegex = \"^.*Big Change.*$\";\n private final String customMinorRulesRegex = \"^.*Nice Change.*$\";\n private final String customVersionTagXML = \"<versionTag>\"+ customVersionTagRegex +\"</versionTag>\";\n private final String customMajorRulesXML = \"<majorRules><majorRule>\"+ customMajorRulesRegex +\"</majorRule></majorRules>\";\n private final String customMinorRulesXML = \"<minorRules><minorRule>\"+ customMinorRulesRegex +\"</minorRule></minorRules>\";\n private final int patternFlags = Pattern.MULTILINE | Pattern.DOTALL | Pattern.UNIX_LINES;\n private final Pattern customVersionTagPattern =\n Pattern.compile(customVersionTagRegex, patternFlags);\n private final List<Pattern> customMajorRulesPatterns =", "score": 0.9072434902191162 }, { "filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/ConfigParsingTest.java", "retrieved_chunk": " Collections.singletonList(Pattern.compile(customMajorRulesRegex, patternFlags));\n private final List<Pattern> customMinorRulesPatterns =\n Collections.singletonList(Pattern.compile(customMinorRulesRegex, patternFlags));\n private void assertTagPatternIsDefault(VersionRules versionRules) {\n assertEquals(defaultVersionRules.getTagPattern().toString(), versionRules.getTagPattern().toString());\n }\n private void assertTagPatternIsCustom(VersionRules versionRules) {\n assertEquals(customVersionTagPattern.toString(), versionRules.getTagPattern().toString());\n }\n private void assertMajorIsDefault(VersionRules versionRules) {", "score": 0.8787969946861267 }, { "filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/ConventionalCommitsVersionPolicyTest.java", "retrieved_chunk": " String major = \"This is a Big Change commit.\";\n String versionRulesConfig = \"\"\n + \"<projectVersionPolicyConfig>\"\n + \" <versionTag>^The awesome ([0-9]+\\\\.[0-9]+\\\\.[0-9]+) release$</versionTag>\"\n + \" <majorRules>\"\n + \" <majorRule>^.*Big Change.*$</majorRule>\"\n + \" </majorRules>\"\n + \" <minorRules>\"\n + \" <minorRule>^.*Nice Change.*$</minorRule>\"\n + \" </minorRules>\"", "score": 0.8741086721420288 }, { "filename": "src/main/java/nl/basjes/maven/release/version/conventionalcommits/ConventionalCommitsVersionConfig.java", "retrieved_chunk": " /*\n * The list of regexes that must be classified as \"minor\" version changes.\n */\n private final List<String> minorRules = new ArrayList<>();\n /*\n * The list of regexes that must be classified as \"major\" version changes.\n */\n private final List<String> majorRules = new ArrayList<>();\n public String getVersionTag() {\n return versionTag;", "score": 0.8704041242599487 }, { "filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/ConfigParsingTest.java", "retrieved_chunk": " LOG.info(\"Tested config: {}\", config);\n assertNull(config.getVersionTag());\n assertEquals(1, config.getMajorRules().size());\n assertEquals(customMajorRulesRegex, config.getMajorRules().get(0));\n assertEquals(1, config.getMinorRules().size());\n assertEquals(customMinorRulesRegex, config.getMinorRules().get(0));\n VersionRules versionRules = new VersionRules(config);\n assertTagPatternIsDefault(versionRules);\n assertMajorIsCustom(versionRules);\n assertMinorIsCustom(versionRules);", "score": 0.859991192817688 } ]
java
!config.getMajorRules().isEmpty() || !config.getMinorRules().isEmpty()) {
/* * Conventional Commits Version Policy * Copyright (C) 2022-2023 Niels Basjes * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nl.basjes.maven.release.version.conventionalcommits; import org.apache.maven.scm.ChangeSet; import org.semver.Version; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * The set of rules that determine from the commit history what the next version should be. */ public class VersionRules { private final Pattern tagPattern; private final List<Pattern> majorUpdatePatterns = new ArrayList<>(); private final List<Pattern> minorUpdatePatterns = new ArrayList<>(); public VersionRules(ConventionalCommitsVersionConfig config) { int patternFlags = Pattern.MULTILINE | Pattern.DOTALL | Pattern.UNIX_LINES; // The default assumes then entire tag is what we need String tagRegex = "^(\\d+\\.\\d+\\.\\d+)$"; // The default rules following https://www.conventionalcommits.org/en/v1.0.0/ majorUpdatePatterns.add(Pattern.compile("^[a-zA-Z]+(?:\\([a-zA-Z\\d_-]+\\))?!: .*$", patternFlags)); majorUpdatePatterns.add(Pattern.compile("^BREAKING CHANGE:.*$", patternFlags)); minorUpdatePatterns.add(Pattern.compile("^feat(?:\\([a-zA-Z\\d_-]+\\))?: .*$", patternFlags)); if (config != null) { String semverConfigVersionTag = config.getVersionTag(); if (semverConfigVersionTag != null && !semverConfigVersionTag.trim().isEmpty()) { tagRegex = semverConfigVersionTag; } if (!config.getMajorRules(
).isEmpty() || !config.getMinorRules().isEmpty()) {
majorUpdatePatterns.clear(); for (String majorRule : config.getMajorRules()) { majorUpdatePatterns.add(Pattern.compile(majorRule, patternFlags)); } minorUpdatePatterns.clear(); for (String minorRule : config.getMinorRules()) { minorUpdatePatterns.add(Pattern.compile(minorRule, patternFlags)); } } } tagPattern = Pattern.compile(tagRegex, Pattern.MULTILINE); } public Version.Element getMaxElementSinceLastVersionTag(CommitHistory commitHistory) { Version.Element maxElement = Version.Element.PATCH; for (ChangeSet change : commitHistory.getChanges()) { if (isMajorUpdate(change.getComment())) { // This is the highest possible: Immediately done return Version.Element.MAJOR; } else if (isMinorUpdate(change.getComment())) { // Have to wait, there may be another MAJOR one. maxElement = Version.Element.MINOR; } } return maxElement; } public boolean isMajorUpdate(String input) { return matchesAny(majorUpdatePatterns, input); } public boolean isMinorUpdate(String input) { return matchesAny(minorUpdatePatterns, input); } private boolean matchesAny(List<Pattern> patterns, String input) { for (Pattern pattern : patterns) { Matcher matcher = pattern.matcher(input); if (matcher.find()) { return true; } } return false; } public Pattern getTagPattern() { return tagPattern; } public List<Pattern> getMajorUpdatePatterns() { return majorUpdatePatterns; } public List<Pattern> getMinorUpdatePatterns() { return minorUpdatePatterns; } @Override public String toString() { StringBuilder result = new StringBuilder(); result.append("Conventional Commits config:\n"); result.append(" VersionTag:\n"); result.append(" >>>").append(tagPattern).append("<<<\n"); result.append(" Major Rules:\n"); for (Pattern majorUpdatePattern : majorUpdatePatterns) { result.append(" >>>").append(majorUpdatePattern).append("<<<\n"); } result.append(" Minor Rules:\n"); for (Pattern minorUpdatePattern : minorUpdatePatterns) { result.append(" >>>").append(minorUpdatePattern).append("<<<\n"); } return result.toString(); } }
src/main/java/nl/basjes/maven/release/version/conventionalcommits/VersionRules.java
nielsbasjes-conventional-commits-maven-release-151e36d
[ { "filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/ConfigParsingTest.java", "retrieved_chunk": " private final String customVersionTagRegex = \"^The awesome ([0-9]+\\\\.[0-9]+\\\\.[0-9]+) release$\";\n private final String customMajorRulesRegex = \"^.*Big Change.*$\";\n private final String customMinorRulesRegex = \"^.*Nice Change.*$\";\n private final String customVersionTagXML = \"<versionTag>\"+ customVersionTagRegex +\"</versionTag>\";\n private final String customMajorRulesXML = \"<majorRules><majorRule>\"+ customMajorRulesRegex +\"</majorRule></majorRules>\";\n private final String customMinorRulesXML = \"<minorRules><minorRule>\"+ customMinorRulesRegex +\"</minorRule></minorRules>\";\n private final int patternFlags = Pattern.MULTILINE | Pattern.DOTALL | Pattern.UNIX_LINES;\n private final Pattern customVersionTagPattern =\n Pattern.compile(customVersionTagRegex, patternFlags);\n private final List<Pattern> customMajorRulesPatterns =", "score": 0.9076575040817261 }, { "filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/ConfigParsingTest.java", "retrieved_chunk": " Collections.singletonList(Pattern.compile(customMajorRulesRegex, patternFlags));\n private final List<Pattern> customMinorRulesPatterns =\n Collections.singletonList(Pattern.compile(customMinorRulesRegex, patternFlags));\n private void assertTagPatternIsDefault(VersionRules versionRules) {\n assertEquals(defaultVersionRules.getTagPattern().toString(), versionRules.getTagPattern().toString());\n }\n private void assertTagPatternIsCustom(VersionRules versionRules) {\n assertEquals(customVersionTagPattern.toString(), versionRules.getTagPattern().toString());\n }\n private void assertMajorIsDefault(VersionRules versionRules) {", "score": 0.8788536190986633 }, { "filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/ConventionalCommitsVersionPolicyTest.java", "retrieved_chunk": " String major = \"This is a Big Change commit.\";\n String versionRulesConfig = \"\"\n + \"<projectVersionPolicyConfig>\"\n + \" <versionTag>^The awesome ([0-9]+\\\\.[0-9]+\\\\.[0-9]+) release$</versionTag>\"\n + \" <majorRules>\"\n + \" <majorRule>^.*Big Change.*$</majorRule>\"\n + \" </majorRules>\"\n + \" <minorRules>\"\n + \" <minorRule>^.*Nice Change.*$</minorRule>\"\n + \" </minorRules>\"", "score": 0.8730534315109253 }, { "filename": "src/main/java/nl/basjes/maven/release/version/conventionalcommits/ConventionalCommitsVersionConfig.java", "retrieved_chunk": " /*\n * The list of regexes that must be classified as \"minor\" version changes.\n */\n private final List<String> minorRules = new ArrayList<>();\n /*\n * The list of regexes that must be classified as \"major\" version changes.\n */\n private final List<String> majorRules = new ArrayList<>();\n public String getVersionTag() {\n return versionTag;", "score": 0.8713904023170471 }, { "filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/ConfigParsingTest.java", "retrieved_chunk": " LOG.info(\"Tested config: {}\", config);\n assertNull(config.getVersionTag());\n assertEquals(1, config.getMajorRules().size());\n assertEquals(customMajorRulesRegex, config.getMajorRules().get(0));\n assertEquals(1, config.getMinorRules().size());\n assertEquals(customMinorRulesRegex, config.getMinorRules().get(0));\n VersionRules versionRules = new VersionRules(config);\n assertTagPatternIsDefault(versionRules);\n assertMajorIsCustom(versionRules);\n assertMinorIsCustom(versionRules);", "score": 0.8608199954032898 } ]
java
).isEmpty() || !config.getMinorRules().isEmpty()) {
/* * Conventional Commits Version Policy * Copyright (C) 2022-2023 Niels Basjes * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nl.basjes.maven.release.version.conventionalcommits; import org.apache.maven.scm.ChangeSet; import org.semver.Version; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * The set of rules that determine from the commit history what the next version should be. */ public class VersionRules { private final Pattern tagPattern; private final List<Pattern> majorUpdatePatterns = new ArrayList<>(); private final List<Pattern> minorUpdatePatterns = new ArrayList<>(); public VersionRules(ConventionalCommitsVersionConfig config) { int patternFlags = Pattern.MULTILINE | Pattern.DOTALL | Pattern.UNIX_LINES; // The default assumes then entire tag is what we need String tagRegex = "^(\\d+\\.\\d+\\.\\d+)$"; // The default rules following https://www.conventionalcommits.org/en/v1.0.0/ majorUpdatePatterns.add(Pattern.compile("^[a-zA-Z]+(?:\\([a-zA-Z\\d_-]+\\))?!: .*$", patternFlags)); majorUpdatePatterns.add(Pattern.compile("^BREAKING CHANGE:.*$", patternFlags)); minorUpdatePatterns.add(Pattern.compile("^feat(?:\\([a-zA-Z\\d_-]+\\))?: .*$", patternFlags)); if (config != null) { String
semverConfigVersionTag = config.getVersionTag();
if (semverConfigVersionTag != null && !semverConfigVersionTag.trim().isEmpty()) { tagRegex = semverConfigVersionTag; } if (!config.getMajorRules().isEmpty() || !config.getMinorRules().isEmpty()) { majorUpdatePatterns.clear(); for (String majorRule : config.getMajorRules()) { majorUpdatePatterns.add(Pattern.compile(majorRule, patternFlags)); } minorUpdatePatterns.clear(); for (String minorRule : config.getMinorRules()) { minorUpdatePatterns.add(Pattern.compile(minorRule, patternFlags)); } } } tagPattern = Pattern.compile(tagRegex, Pattern.MULTILINE); } public Version.Element getMaxElementSinceLastVersionTag(CommitHistory commitHistory) { Version.Element maxElement = Version.Element.PATCH; for (ChangeSet change : commitHistory.getChanges()) { if (isMajorUpdate(change.getComment())) { // This is the highest possible: Immediately done return Version.Element.MAJOR; } else if (isMinorUpdate(change.getComment())) { // Have to wait, there may be another MAJOR one. maxElement = Version.Element.MINOR; } } return maxElement; } public boolean isMajorUpdate(String input) { return matchesAny(majorUpdatePatterns, input); } public boolean isMinorUpdate(String input) { return matchesAny(minorUpdatePatterns, input); } private boolean matchesAny(List<Pattern> patterns, String input) { for (Pattern pattern : patterns) { Matcher matcher = pattern.matcher(input); if (matcher.find()) { return true; } } return false; } public Pattern getTagPattern() { return tagPattern; } public List<Pattern> getMajorUpdatePatterns() { return majorUpdatePatterns; } public List<Pattern> getMinorUpdatePatterns() { return minorUpdatePatterns; } @Override public String toString() { StringBuilder result = new StringBuilder(); result.append("Conventional Commits config:\n"); result.append(" VersionTag:\n"); result.append(" >>>").append(tagPattern).append("<<<\n"); result.append(" Major Rules:\n"); for (Pattern majorUpdatePattern : majorUpdatePatterns) { result.append(" >>>").append(majorUpdatePattern).append("<<<\n"); } result.append(" Minor Rules:\n"); for (Pattern minorUpdatePattern : minorUpdatePatterns) { result.append(" >>>").append(minorUpdatePattern).append("<<<\n"); } return result.toString(); } }
src/main/java/nl/basjes/maven/release/version/conventionalcommits/VersionRules.java
nielsbasjes-conventional-commits-maven-release-151e36d
[ { "filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/ConfigParsingTest.java", "retrieved_chunk": " private final String customVersionTagRegex = \"^The awesome ([0-9]+\\\\.[0-9]+\\\\.[0-9]+) release$\";\n private final String customMajorRulesRegex = \"^.*Big Change.*$\";\n private final String customMinorRulesRegex = \"^.*Nice Change.*$\";\n private final String customVersionTagXML = \"<versionTag>\"+ customVersionTagRegex +\"</versionTag>\";\n private final String customMajorRulesXML = \"<majorRules><majorRule>\"+ customMajorRulesRegex +\"</majorRule></majorRules>\";\n private final String customMinorRulesXML = \"<minorRules><minorRule>\"+ customMinorRulesRegex +\"</minorRule></minorRules>\";\n private final int patternFlags = Pattern.MULTILINE | Pattern.DOTALL | Pattern.UNIX_LINES;\n private final Pattern customVersionTagPattern =\n Pattern.compile(customVersionTagRegex, patternFlags);\n private final List<Pattern> customMajorRulesPatterns =", "score": 0.9143956899642944 }, { "filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/ConfigParsingTest.java", "retrieved_chunk": " Collections.singletonList(Pattern.compile(customMajorRulesRegex, patternFlags));\n private final List<Pattern> customMinorRulesPatterns =\n Collections.singletonList(Pattern.compile(customMinorRulesRegex, patternFlags));\n private void assertTagPatternIsDefault(VersionRules versionRules) {\n assertEquals(defaultVersionRules.getTagPattern().toString(), versionRules.getTagPattern().toString());\n }\n private void assertTagPatternIsCustom(VersionRules versionRules) {\n assertEquals(customVersionTagPattern.toString(), versionRules.getTagPattern().toString());\n }\n private void assertMajorIsDefault(VersionRules versionRules) {", "score": 0.8682407140731812 }, { "filename": "src/main/java/nl/basjes/maven/release/version/conventionalcommits/ConventionalCommitsVersionConfig.java", "retrieved_chunk": " /*\n * The list of regexes that must be classified as \"minor\" version changes.\n */\n private final List<String> minorRules = new ArrayList<>();\n /*\n * The list of regexes that must be classified as \"major\" version changes.\n */\n private final List<String> majorRules = new ArrayList<>();\n public String getVersionTag() {\n return versionTag;", "score": 0.867233395576477 }, { "filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/ConventionalCommitsVersionPolicyTest.java", "retrieved_chunk": " String major = \"This is a Big Change commit.\";\n String versionRulesConfig = \"\"\n + \"<projectVersionPolicyConfig>\"\n + \" <versionTag>^The awesome ([0-9]+\\\\.[0-9]+\\\\.[0-9]+) release$</versionTag>\"\n + \" <majorRules>\"\n + \" <majorRule>^.*Big Change.*$</majorRule>\"\n + \" </majorRules>\"\n + \" <minorRules>\"\n + \" <minorRule>^.*Nice Change.*$</minorRule>\"\n + \" </minorRules>\"", "score": 0.8668292164802551 }, { "filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/ConfigParsingTest.java", "retrieved_chunk": " ConventionalCommitsVersionConfig config = ConventionalCommitsVersionConfig.fromXml(versionRulesConfig);\n LOG.info(\"Tested config: {}\", config);\n assertNull(config.getVersionTag());\n assertEquals(1, config.getMajorRules().size());\n assertEquals(customMajorRulesRegex, config.getMajorRules().get(0));\n assertEquals(0, config.getMinorRules().size());\n VersionRules versionRules = new VersionRules(config);\n assertTagPatternIsDefault(versionRules);\n assertMajorIsCustom(versionRules);\n assertMinorIsEmpty(versionRules);", "score": 0.8575958609580994 } ]
java
semverConfigVersionTag = config.getVersionTag();
/* * Conventional Commits Version Policy * Copyright (C) 2022-2023 Niels Basjes * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nl.basjes.maven.release.version.conventionalcommits; import org.apache.maven.scm.ChangeSet; import org.semver.Version; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * The set of rules that determine from the commit history what the next version should be. */ public class VersionRules { private final Pattern tagPattern; private final List<Pattern> majorUpdatePatterns = new ArrayList<>(); private final List<Pattern> minorUpdatePatterns = new ArrayList<>(); public VersionRules(ConventionalCommitsVersionConfig config) { int patternFlags = Pattern.MULTILINE | Pattern.DOTALL | Pattern.UNIX_LINES; // The default assumes then entire tag is what we need String tagRegex = "^(\\d+\\.\\d+\\.\\d+)$"; // The default rules following https://www.conventionalcommits.org/en/v1.0.0/ majorUpdatePatterns.add(Pattern.compile("^[a-zA-Z]+(?:\\([a-zA-Z\\d_-]+\\))?!: .*$", patternFlags)); majorUpdatePatterns.add(Pattern.compile("^BREAKING CHANGE:.*$", patternFlags)); minorUpdatePatterns.add(Pattern.compile("^feat(?:\\([a-zA-Z\\d_-]+\\))?: .*$", patternFlags)); if (config != null) { String semverConfigVersionTag = config.getVersionTag(); if (semverConfigVersionTag != null && !semverConfigVersionTag.trim().isEmpty()) { tagRegex = semverConfigVersionTag; } if (!config.getMajorRules().isEmpty() || !config.getMinorRules().isEmpty()) { majorUpdatePatterns.clear(); for (String majorRule : config.getMajorRules()) { majorUpdatePatterns.add(Pattern.compile(majorRule, patternFlags)); } minorUpdatePatterns.clear(); for (String minorRule : config.getMinorRules()) { minorUpdatePatterns.add(Pattern.compile(minorRule, patternFlags)); } } } tagPattern = Pattern.compile(tagRegex, Pattern.MULTILINE); } public Version.Element getMaxElementSinceLastVersionTag(CommitHistory commitHistory) { Version.Element maxElement = Version.Element.PATCH; for (ChangeSet change :
commitHistory.getChanges()) {
if (isMajorUpdate(change.getComment())) { // This is the highest possible: Immediately done return Version.Element.MAJOR; } else if (isMinorUpdate(change.getComment())) { // Have to wait, there may be another MAJOR one. maxElement = Version.Element.MINOR; } } return maxElement; } public boolean isMajorUpdate(String input) { return matchesAny(majorUpdatePatterns, input); } public boolean isMinorUpdate(String input) { return matchesAny(minorUpdatePatterns, input); } private boolean matchesAny(List<Pattern> patterns, String input) { for (Pattern pattern : patterns) { Matcher matcher = pattern.matcher(input); if (matcher.find()) { return true; } } return false; } public Pattern getTagPattern() { return tagPattern; } public List<Pattern> getMajorUpdatePatterns() { return majorUpdatePatterns; } public List<Pattern> getMinorUpdatePatterns() { return minorUpdatePatterns; } @Override public String toString() { StringBuilder result = new StringBuilder(); result.append("Conventional Commits config:\n"); result.append(" VersionTag:\n"); result.append(" >>>").append(tagPattern).append("<<<\n"); result.append(" Major Rules:\n"); for (Pattern majorUpdatePattern : majorUpdatePatterns) { result.append(" >>>").append(majorUpdatePattern).append("<<<\n"); } result.append(" Minor Rules:\n"); for (Pattern minorUpdatePattern : minorUpdatePatterns) { result.append(" >>>").append(minorUpdatePattern).append("<<<\n"); } return result.toString(); } }
src/main/java/nl/basjes/maven/release/version/conventionalcommits/VersionRules.java
nielsbasjes-conventional-commits-maven-release-151e36d
[ { "filename": "src/main/java/nl/basjes/maven/release/version/conventionalcommits/ConventionalCommitsVersionPolicy.java", "retrieved_chunk": " String versionString = request.getVersion(); // The current version in the pom\n Version version;\n LOG.debug(\"--------------------------------------------------------\");\n LOG.debug(\"Determining next ReleaseVersion\");\n LOG.debug(\"VersionRules: \\n{}\", versionRules);\n LOG.debug(\"Pom version : {}\", versionString);\n LOG.debug(\"Commit History : \\n{}\", commitHistory);\n Element maxElementSinceLastVersionTag = versionRules.getMaxElementSinceLastVersionTag(commitHistory);\n String latestVersionTag = commitHistory.getLastVersionTag();\n if (latestVersionTag != null) {", "score": 0.8452620506286621 }, { "filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/ConfigParsingTest.java", "retrieved_chunk": " private final String customVersionTagRegex = \"^The awesome ([0-9]+\\\\.[0-9]+\\\\.[0-9]+) release$\";\n private final String customMajorRulesRegex = \"^.*Big Change.*$\";\n private final String customMinorRulesRegex = \"^.*Nice Change.*$\";\n private final String customVersionTagXML = \"<versionTag>\"+ customVersionTagRegex +\"</versionTag>\";\n private final String customMajorRulesXML = \"<majorRules><majorRule>\"+ customMajorRulesRegex +\"</majorRule></majorRules>\";\n private final String customMinorRulesXML = \"<minorRules><minorRule>\"+ customMinorRulesRegex +\"</minorRule></minorRules>\";\n private final int patternFlags = Pattern.MULTILINE | Pattern.DOTALL | Pattern.UNIX_LINES;\n private final Pattern customVersionTagPattern =\n Pattern.compile(customVersionTagRegex, patternFlags);\n private final List<Pattern> customMajorRulesPatterns =", "score": 0.8311905860900879 }, { "filename": "src/main/java/nl/basjes/maven/release/version/conventionalcommits/CommitHistory.java", "retrieved_chunk": " public List<ChangeSet> getChanges() {\n return changes;\n }\n public void addChanges(ChangeSet change) {\n this.changes.add(change);\n }\n public String getLastVersionTag() {\n return latestVersionTag;\n }\n public CommitHistory(VersionPolicyRequest request, VersionRules versionRules)", "score": 0.8267495632171631 }, { "filename": "src/main/java/nl/basjes/maven/release/version/conventionalcommits/CommitHistory.java", "retrieved_chunk": " new ScmFileSet(new File(workingDirectory))\n );\n Logger logger = LoggerFactory.getLogger(CommitHistory.class);\n int limit = 0;\n while (latestVersionTag == null) {\n limit += 100; // Read the repository in incremental steps of 100\n changeLogRequest.setLimit(null);\n changeLogRequest.setLimit(limit);\n changes.clear();\n logger.debug(\"Checking the last {} commits.\", limit);", "score": 0.8239942789077759 }, { "filename": "src/main/java/nl/basjes/maven/release/version/conventionalcommits/CommitHistory.java", "retrieved_chunk": " }\n if (latestVersionTag == null &&\n changeSets.size() < limit) {\n // Apparently there are simply no more commits.\n logger.debug(\"Did not find any tag\");\n break;\n }\n }\n }\n @Override", "score": 0.8228906393051147 } ]
java
commitHistory.getChanges()) {
package com.noq.backend.services; import com.noq.backend.models.User; import com.noq.backend.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.UUID; @Service public class UserService { private UserRepository userRepository; @Autowired public UserService(UserRepository userRepository) { this.userRepository = userRepository; } public List<User> getAllUsers() { return userRepository.getAllUsers(); } public List<User> createUsers() { User user1 = new User( "1", "Person Personsson", false ); User user2 = new User( "2", "Individ Individson", true ); userRepository.save(user1); userRepository.save(user2); return new ArrayList<>(userRepository.getAllUsers()); } public User getUserById(String userId) { User existingUser = userRepository.getUserByUserId(userId); if (existingUser != null) { return existingUser; } else { return
userRepository.getUserByUserId(userId);
} } }
noq-backend/src/main/java/com/noq/backend/services/UserService.java
noQ-sweden-noq-7f5b8d1
[ { "filename": "noq-backend/src/main/java/com/noq/backend/controllers/UserController.java", "retrieved_chunk": " .stream()\n .map(UserController::userDTO)\n .collect(Collectors.toList());\n }\n @GetMapping(\"/{userId}\")\n public UserDTO getUserById(@PathVariable String userId) {\n User user = userService.getUserById(userId);\n return userDTO(user);\n }\n private static UserDTO userDTO(User user) {", "score": 0.8862998485565186 }, { "filename": "noq-backend/src/main/java/com/noq/backend/repository/UserRepositoryImp.java", "retrieved_chunk": " @Override\n public User save(User user) {\n users.put(user.getId(), user);\n return user;\n }\n @Override\n public User getUserByUserId(String userId) {\n return users.get(userId);\n }\n @Override", "score": 0.8732103705406189 }, { "filename": "noq-backend/src/main/java/com/noq/backend/services/ReservationService.java", "retrieved_chunk": " this.hostRepository = hostRepository;\n this.userRepository = userRepository;\n this.reservationRepository = reservationRepository;\n }\n public Reservation getReservationByUserId(String userId) {\n List<Reservation> reservations = reservationRepository.getAllReservations();\n Reservation reservation = reservations.stream()\n .filter(res -> res.getUser().getId().equals(userId))\n .findFirst()\n .orElse(null);", "score": 0.8588107824325562 }, { "filename": "noq-backend/src/main/java/com/noq/backend/controllers/UserController.java", "retrieved_chunk": "@CrossOrigin(origins = \"*\", allowedHeaders = \"*\")\npublic class UserController {\n private final UserService userService;\n @Autowired\n public UserController(UserService userService) {\n this.userService = userService;\n }\n @GetMapping(\"/get-all\")\n public List<UserDTO> getAllUsers() {\n return userService.getAllUsers()", "score": 0.848333477973938 }, { "filename": "noq-backend/src/main/java/com/noq/backend/repository/UserRepository.java", "retrieved_chunk": "package com.noq.backend.repository;\nimport com.noq.backend.models.User;\nimport java.util.List;\npublic interface UserRepository {\n User save(User user);\n User getUserByUserId(String userId);\n List<User> getAllUsers();\n}", "score": 0.8437936305999756 } ]
java
userRepository.getUserByUserId(userId);
package com.noq.backend.services; import com.noq.backend.DTO.ReservationDTO; import com.noq.backend.models.*; import com.noq.backend.repository.HostRepository; import com.noq.backend.repository.ReservationRepository; import com.noq.backend.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; @Service public class ReservationService { private HostRepository hostRepository; private UserRepository userRepository; private ReservationRepository reservationRepository; @Autowired public ReservationService(ReservationRepository reservationRepository, HostRepository hostRepository, UserRepository userRepository) { this.hostRepository = hostRepository; this.userRepository = userRepository; this.reservationRepository = reservationRepository; } public Reservation getReservationByUserId(String userId) { List<Reservation> reservations = reservationRepository.getAllReservations(); Reservation reservation = reservations.stream() .filter(res -> res.getUser().getId().equals(userId)) .findFirst() .orElse(null); return reservation; } public Reservation createReservation(CreateReservation createReservation) { User user = userRepository.getUserByUserId(createReservation.getUserId()); user.setReservation(true); userRepository.save(user); Host host = hostRepository.getHostByHostId(createReservation.getHostId()); Reservation reservation = new Reservation(host, user, Status.PENDING); reservationRepository.save(reservation); return reservation; } // returns empty array...?? public List<Reservation> getReservationsByHostIdStatusPending(String hostId) { System.out.print(hostId); List<Reservation> reservations = reservationRepository.getAllReservations().stream() .filter(res -> res.getHost().getHostId().equals(hostId) && res.getStatus().equals(Status.PENDING)) .collect(Collectors.toList()); System.out.print(reservations); return reservations; } public List<Reservation> approveReservations(List<String> reservationsId) {
List<Reservation> reservations = reservationRepository.getAllReservations().stream() .filter(res -> {
if (reservationsId.contains(res.getReservationId())) { res.setStatus(Status.RESERVED); return true; } return false; }) .collect(Collectors.toList()); reservationRepository.saveAll(reservations); return reservations; } public List<Reservation> getReservationsByHostIdStatusReserved(String hostId) { System.out.print(hostId); List<Reservation> reservations = reservationRepository.getAllReservations().stream() .filter(res -> res.getHost().getHostId().equals(hostId) && res.getStatus().equals(Status.RESERVED)) .collect(Collectors.toList()); System.out.print(reservations); return reservations; } }
noq-backend/src/main/java/com/noq/backend/services/ReservationService.java
noQ-sweden-noq-7f5b8d1
[ { "filename": "noq-backend/src/main/java/com/noq/backend/controllers/ReservationController.java", "retrieved_chunk": " .map(ReservationController::toReservationDTO)\n .collect(Collectors.toList());\n }\n @PutMapping(\"/approve-reservations/{hostId}\")\n public List<ReservationDTO> approveReservations(@RequestBody List<String> reservationsId) {\n return reservationService.approveReservations(reservationsId)\n .stream()\n .map(ReservationController::toReservationDTO)\n .collect(Collectors.toList());\n }", "score": 0.922700822353363 }, { "filename": "noq-backend/src/main/java/com/noq/backend/controllers/ReservationController.java", "retrieved_chunk": " @GetMapping(\"/get-approved/{hostId}\")\n public List<ReservationDTO> getApprovedByHostId(@PathVariable String hostId) {\n return reservationService.getReservationsByHostIdStatusReserved(hostId)\n .stream()\n .map(ReservationController::toReservationDTO)\n .collect(Collectors.toList());\n }\n private static ReservationDTO toReservationDTO(Reservation reservation) {\n return new ReservationDTO(\n reservation.getReservationId(),", "score": 0.9120134711265564 }, { "filename": "noq-backend/src/main/java/com/noq/backend/controllers/ReservationController.java", "retrieved_chunk": " return toReservationDTO(reservationService.getReservationByUserId(userId));\n }\n @PostMapping(\"/create\")\n public ReservationDTO createReservation(@RequestBody CreateReservation createReservation) {\n return toReservationDTO(reservationService.createReservation(createReservation));\n }\n @GetMapping(\"/get-reservations/{hostId}\")\n public List<ReservationDTO> getReservationsByHostId(@PathVariable String hostId) {\n return reservationService.getReservationsByHostIdStatusPending(hostId)\n .stream()", "score": 0.8517759442329407 }, { "filename": "noq-backend/src/main/java/com/noq/backend/repository/ReservationRepositoryImpl.java", "retrieved_chunk": "package com.noq.backend.repository;\nimport com.noq.backend.models.Host;\nimport com.noq.backend.models.Reservation;\nimport org.springframework.stereotype.Repository;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n@Repository\npublic class ReservationRepositoryImpl implements ReservationRepository {", "score": 0.8419764041900635 }, { "filename": "noq-backend/src/main/java/com/noq/backend/repository/ReservationRepositoryImpl.java", "retrieved_chunk": " };\n @Override\n public Reservation getReservationByReservationId(String reservationId) {\n return reservations.get(reservationId);\n }\n @Override\n public List<Reservation> getAllReservations() {\n return new ArrayList<>(reservations.values());\n }\n}", "score": 0.8411985039710999 } ]
java
List<Reservation> reservations = reservationRepository.getAllReservations().stream() .filter(res -> {
package com.noq.backend.services; import com.noq.backend.models.User; import com.noq.backend.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.UUID; @Service public class UserService { private UserRepository userRepository; @Autowired public UserService(UserRepository userRepository) { this.userRepository = userRepository; } public List<User> getAllUsers() { return userRepository.getAllUsers(); } public List<User> createUsers() { User user1 = new User( "1", "Person Personsson", false ); User user2 = new User( "2", "Individ Individson", true ); userRepository.save(user1); userRepository.save(user2); return new ArrayList<>(userRepository.getAllUsers()); } public User getUserById(String userId) {
User existingUser = userRepository.getUserByUserId(userId);
if (existingUser != null) { return existingUser; } else { return userRepository.getUserByUserId(userId); } } }
noq-backend/src/main/java/com/noq/backend/services/UserService.java
noQ-sweden-noq-7f5b8d1
[ { "filename": "noq-backend/src/main/java/com/noq/backend/controllers/UserController.java", "retrieved_chunk": " .stream()\n .map(UserController::userDTO)\n .collect(Collectors.toList());\n }\n @GetMapping(\"/{userId}\")\n public UserDTO getUserById(@PathVariable String userId) {\n User user = userService.getUserById(userId);\n return userDTO(user);\n }\n private static UserDTO userDTO(User user) {", "score": 0.8535590767860413 }, { "filename": "noq-backend/src/main/java/com/noq/backend/repository/UserRepositoryImp.java", "retrieved_chunk": " @Override\n public User save(User user) {\n users.put(user.getId(), user);\n return user;\n }\n @Override\n public User getUserByUserId(String userId) {\n return users.get(userId);\n }\n @Override", "score": 0.8431548476219177 }, { "filename": "noq-backend/src/main/java/com/noq/backend/services/ReservationService.java", "retrieved_chunk": " this.hostRepository = hostRepository;\n this.userRepository = userRepository;\n this.reservationRepository = reservationRepository;\n }\n public Reservation getReservationByUserId(String userId) {\n List<Reservation> reservations = reservationRepository.getAllReservations();\n Reservation reservation = reservations.stream()\n .filter(res -> res.getUser().getId().equals(userId))\n .findFirst()\n .orElse(null);", "score": 0.8366096615791321 }, { "filename": "noq-backend/src/main/java/com/noq/backend/services/HostService.java", "retrieved_chunk": " Host host2 = new Host(\"4\", \"Test-Härberget 2\", new Address(UUID.randomUUID().toString(), \"Vägvägen\", \"21\", \"23546\", \"Lund\"), \"url/till/bild/pa/Harberget2.png\", 20L);\n hostRepository.save(host1);\n hostRepository.save(host2);\n return new ArrayList<>(hostRepository.getAllHosts());\n }\n}", "score": 0.8362115025520325 }, { "filename": "noq-backend/src/main/java/com/noq/backend/repository/UserRepositoryImp.java", "retrieved_chunk": "package com.noq.backend.repository;\nimport com.noq.backend.models.User;\nimport org.springframework.stereotype.Repository;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n@Repository\npublic class UserRepositoryImp implements UserRepository{\n private final Map<String, User> users = new HashMap<>();", "score": 0.8316664099693298 } ]
java
User existingUser = userRepository.getUserByUserId(userId);
/* * Conventional Commits Version Policy * Copyright (C) 2022-2023 Niels Basjes * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nl.basjes.maven.release.version.conventionalcommits; import org.apache.maven.scm.ChangeSet; import org.apache.maven.scm.ScmException; import org.apache.maven.scm.ScmFileSet; import org.apache.maven.scm.command.changelog.ChangeLogScmRequest; import org.apache.maven.scm.command.changelog.ChangeLogSet; import org.apache.maven.scm.provider.ScmProvider; import org.apache.maven.scm.repository.ScmRepository; import org.apache.maven.shared.release.policy.version.VersionPolicyRequest; import org.apache.maven.shared.release.versions.VersionParseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.regex.Matcher; import java.util.stream.Collectors; /** * Helper class to manage the commit history of the SCM repository. */ public class CommitHistory { private final List<ChangeSet> changes = new ArrayList<>(); private String latestVersionTag = null; public List<ChangeSet> getChanges() { return changes; } public void addChanges(ChangeSet change) { this.changes.add(change); } public String getLastVersionTag() { return latestVersionTag; } public CommitHistory(VersionPolicyRequest request, VersionRules versionRules) throws ScmException, VersionParseException { ScmRepository scmRepository = request.getScmRepository(); ScmProvider scmProvider = request.getScmProvider(); String workingDirectory = request.getWorkingDirectory(); if (scmRepository == null || scmProvider == null || workingDirectory == null) { // We do not have a commit history so the changes and tags will remain empty return; } ChangeLogScmRequest changeLogRequest = new ChangeLogScmRequest( scmRepository, new ScmFileSet(new File(workingDirectory)) ); Logger logger = LoggerFactory.getLogger(CommitHistory.class); int limit = 0; while (latestVersionTag == null) { limit += 100; // Read the repository in incremental steps of 100 changeLogRequest.setLimit(null); changeLogRequest.setLimit(limit); changes.clear(); logger.debug("Checking the last {} commits.", limit); ChangeLogSet changeLogSet = scmProvider.changeLog(changeLogRequest).getChangeLog(); if (changeLogSet == null) { return; } List<ChangeSet> changeSets = changeLogSet.getChangeSets(); for (ChangeSet changeSet : changeSets) { addChanges(changeSet); List<String> changeSetTags = changeSet.getTags(); List<String> versionTags = changeSetTags .stream() .map(tag -> { Matcher matcher
= versionRules.getTagPattern().matcher(tag);
if (matcher.find()) { return matcher.group(1); } return null; } ) .filter(Objects::nonNull) .collect(Collectors.toList()); if (!versionTags.isEmpty()) { // Found the previous release tag if (versionTags.size() > 1) { throw new VersionParseException("Most recent commit with tags has multiple version tags: " + versionTags); } latestVersionTag = versionTags.get(0); logger.debug("Found tag"); break; // We have the last version tag } } if (latestVersionTag == null && changeSets.size() < limit) { // Apparently there are simply no more commits. logger.debug("Did not find any tag"); break; } } } @Override public String toString() { List<String> logLines = new ArrayList<>(); logLines.add("Filtered commit history:"); for (ChangeSet changeSet : changes) { logLines.add("-- Comment: \"" + changeSet.getComment() + "\""); logLines.add(" Tags : " + changeSet.getTags()); } StringBuilder sb = new StringBuilder(); for (String logLine : logLines) { sb.append(logLine).append('\n'); } return sb.toString(); } }
src/main/java/nl/basjes/maven/release/version/conventionalcommits/CommitHistory.java
nielsbasjes-conventional-commits-maven-release-151e36d
[ { "filename": "src/it/setup/maven-scm-provider-dummy/src/main/java/org/apache/maven/scm/provider/dummy/DummyTagsScmProvider.java", "retrieved_chunk": " ChangeLogSet changeLogSet = new ChangeLogSet(\n Arrays.asList(\n changeSet( \"Commit 19\" ),\n changeSet( \"Commit 18\" ),\n changeSet( \"Commit 17\" ),\n changeSet( \"Commit 16\" ),\n changeSet( \"Commit 15\", \"tag 1\", \"tag 2\" ),\n changeSet( \"feat(it): This is a new feature.\" ), // For Conventional Commits.\n changeSet( \"Commit 13\" ),\n changeSet( \"Commit 12\", \"tag 3\" ),", "score": 0.8575915098190308 }, { "filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/mockscm/MockScmProvider.java", "retrieved_chunk": " fullChangeSetList.add(changeSet(\"Dummy Commit without tags\"));\n if (fullChangeSetList.size() >= request.getLimit()) {\n break;\n }\n fullChangeSetList.add(configuredChangeSet);\n if (fullChangeSetList.size() >= request.getLimit()) {\n break;\n }\n fullChangeSetList.add(changeSet(\"Dummy Commit with tags\", \"Dummy tag \"+ tagId++, \"Dummy tag \"+ tagId++));\n }", "score": 0.857270359992981 }, { "filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/mockscm/MockScmProvider.java", "retrieved_chunk": " fullChangeSetList.add(changeSet(\"Dummy Commit without tags\"));\n if (fullChangeSetList.size() >= request.getLimit()) {\n break;\n }\n fullChangeSetList.add(changeSet(\"Dummy Commit with tags\", \"Dummy tag \" + tagId++, \"Dummy tag \" + tagId++));\n }\n for (ChangeSet configuredChangeSet : configuredChangeSets) {\n if (fullChangeSetList.size() >= request.getLimit()) {\n break;\n }", "score": 0.8556578159332275 }, { "filename": "src/main/java/nl/basjes/maven/release/version/conventionalcommits/VersionRules.java", "retrieved_chunk": "import java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n/**\n * The set of rules that determine from the commit history what the next version should be.\n */\npublic class VersionRules {\n private final Pattern tagPattern;\n private final List<Pattern> majorUpdatePatterns = new ArrayList<>();\n private final List<Pattern> minorUpdatePatterns = new ArrayList<>();", "score": 0.8466861248016357 }, { "filename": "src/main/java/nl/basjes/maven/release/version/conventionalcommits/VersionRules.java", "retrieved_chunk": " minorUpdatePatterns.add(Pattern.compile(minorRule, patternFlags));\n }\n }\n }\n tagPattern = Pattern.compile(tagRegex, Pattern.MULTILINE);\n }\n public Version.Element getMaxElementSinceLastVersionTag(CommitHistory commitHistory) {\n Version.Element maxElement = Version.Element.PATCH;\n for (ChangeSet change : commitHistory.getChanges()) {\n if (isMajorUpdate(change.getComment())) {", "score": 0.8457390666007996 } ]
java
= versionRules.getTagPattern().matcher(tag);
package com.noq.backend.services; import com.noq.backend.models.User; import com.noq.backend.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.UUID; @Service public class UserService { private UserRepository userRepository; @Autowired public UserService(UserRepository userRepository) { this.userRepository = userRepository; } public List<User> getAllUsers() { return userRepository.getAllUsers(); } public List<User> createUsers() { User user1 = new User( "1", "Person Personsson", false ); User user2 = new User( "2", "Individ Individson", true ); userRepository.save(user1); userRepository.save(user2); return new
ArrayList<>(userRepository.getAllUsers());
} public User getUserById(String userId) { User existingUser = userRepository.getUserByUserId(userId); if (existingUser != null) { return existingUser; } else { return userRepository.getUserByUserId(userId); } } }
noq-backend/src/main/java/com/noq/backend/services/UserService.java
noQ-sweden-noq-7f5b8d1
[ { "filename": "noq-backend/src/main/java/com/noq/backend/services/HostService.java", "retrieved_chunk": " Host host2 = new Host(\"4\", \"Test-Härberget 2\", new Address(UUID.randomUUID().toString(), \"Vägvägen\", \"21\", \"23546\", \"Lund\"), \"url/till/bild/pa/Harberget2.png\", 20L);\n hostRepository.save(host1);\n hostRepository.save(host2);\n return new ArrayList<>(hostRepository.getAllHosts());\n }\n}", "score": 0.8569482564926147 }, { "filename": "noq-backend/src/main/java/com/noq/backend/repository/UserRepositoryImp.java", "retrieved_chunk": "package com.noq.backend.repository;\nimport com.noq.backend.models.User;\nimport org.springframework.stereotype.Repository;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n@Repository\npublic class UserRepositoryImp implements UserRepository{\n private final Map<String, User> users = new HashMap<>();", "score": 0.8458845019340515 }, { "filename": "noq-backend/src/main/java/com/noq/backend/repository/UserRepositoryImp.java", "retrieved_chunk": " public List<User> getAllUsers() {\n return new ArrayList<>(users.values());\n }\n}", "score": 0.8398635983467102 }, { "filename": "noq-backend/src/main/java/com/noq/backend/controllers/UserController.java", "retrieved_chunk": "@CrossOrigin(origins = \"*\", allowedHeaders = \"*\")\npublic class UserController {\n private final UserService userService;\n @Autowired\n public UserController(UserService userService) {\n this.userService = userService;\n }\n @GetMapping(\"/get-all\")\n public List<UserDTO> getAllUsers() {\n return userService.getAllUsers()", "score": 0.8341155052185059 }, { "filename": "noq-backend/src/main/java/com/noq/backend/repository/UserRepository.java", "retrieved_chunk": "package com.noq.backend.repository;\nimport com.noq.backend.models.User;\nimport java.util.List;\npublic interface UserRepository {\n User save(User user);\n User getUserByUserId(String userId);\n List<User> getAllUsers();\n}", "score": 0.8291856050491333 } ]
java
ArrayList<>(userRepository.getAllUsers());
/* * Conventional Commits Version Policy * Copyright (C) 2022-2023 Niels Basjes * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nl.basjes.maven.release.version.conventionalcommits; import org.apache.maven.scm.ScmException; import org.apache.maven.shared.release.policy.PolicyException; import org.apache.maven.shared.release.policy.version.VersionPolicy; import org.apache.maven.shared.release.policy.version.VersionPolicyRequest; import org.apache.maven.shared.release.policy.version.VersionPolicyResult; import org.apache.maven.shared.release.versions.VersionParseException; import org.eclipse.sisu.Description; import org.semver.Version; import org.semver.Version.Element; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Named; import javax.inject.Singleton; /** * Uses SemVer combined with the tags and commit messages to increase the version. */ @Singleton @Named("ConventionalCommitsVersionPolicy") @Description("A VersionPolicy following the SemVer rules and looks at " + "the commit messages following the Conventional Commits convention.") public class ConventionalCommitsVersionPolicy implements VersionPolicy { private static final Logger LOG = LoggerFactory.getLogger(ConventionalCommitsVersionPolicy.class); @Override public VersionPolicyResult getReleaseVersion(VersionPolicyRequest request) throws VersionParseException, PolicyException { ConventionalCommitsVersionConfig versionConfig = ConventionalCommitsVersionConfig.fromXml(request.getConfig()); VersionRules versionRules = new VersionRules(versionConfig); CommitHistory commitHistory; try { commitHistory = new CommitHistory(request, versionRules); } catch (ScmException e) { throw new PolicyException("Something went wrong fetching the commit history", e); } boolean usingTag = false; String versionString = request.getVersion(); // The current version in the pom Version version; LOG.debug("--------------------------------------------------------"); LOG.debug("Determining next ReleaseVersion"); LOG.debug("VersionRules: \n{}", versionRules); LOG.debug("Pom version : {}", versionString); LOG.debug("Commit History : \n{}", commitHistory); Element maxElementSinceLastVersionTag = versionRules.getMaxElementSinceLastVersionTag(commitHistory); String latestVersionTag
= commitHistory.getLastVersionTag();
if (latestVersionTag != null) { // Use the latest tag we have versionString = latestVersionTag; usingTag = true; LOG.debug("Version from tags : {}", versionString); } else { LOG.debug("Version from tags : NOT FOUND"); } LOG.debug("Step from commits : {}", maxElementSinceLastVersionTag.name()); try { version = Version.parse(versionString); } catch (IllegalArgumentException e) { throw new VersionParseException(e.getMessage(), e); } LOG.debug("Current version : {}", version); // If we have a version from the tag we use that + the calculated update. // If only have the version from the current pom version with -SNAPSHOT removed IF it is only a PATCH. if (!(latestVersionTag == null && maxElementSinceLastVersionTag == Element.PATCH)) { version = version.next(maxElementSinceLastVersionTag); } Version releaseVersion = version.toReleaseVersion(); LOG.debug("Next version : {}", releaseVersion); LOG.debug("--------------------------------------------------------"); LOG.info("Version and SCM analysis result:"); if (usingTag) { LOG.info("- Starting from SCM tag with version {}", versionString); } else { LOG.info("- Starting from project.version {} (because we did not find any valid SCM tags)", versionString); } LOG.info("- Doing a {} version increase{}.", maxElementSinceLastVersionTag, maxElementSinceLastVersionTag == Element.PATCH ? " (because we did not find any minor/major commit messages)" : ""); LOG.info("- Next release version : {}", releaseVersion); VersionPolicyResult result = new VersionPolicyResult(); result.setVersion(releaseVersion.toString()); return result; } @Override public VersionPolicyResult getDevelopmentVersion(VersionPolicyRequest request) throws VersionParseException { Version version; try { version = Version.parse(request.getVersion()); } catch (IllegalArgumentException e) { throw new VersionParseException(e.getMessage()); } version = version.next(Element.PATCH); VersionPolicyResult result = new VersionPolicyResult(); result.setVersion(version + "-SNAPSHOT"); return result; } }
src/main/java/nl/basjes/maven/release/version/conventionalcommits/ConventionalCommitsVersionPolicy.java
nielsbasjes-conventional-commits-maven-release-151e36d
[ { "filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/AbstractNextVersionTest.java", "retrieved_chunk": " request.setConfig(configXml);\n VersionPolicy versionPolicy = new ConventionalCommitsVersionPolicy();\n String suggestedVersion = versionPolicy.getReleaseVersion(request).getVersion();\n assertEquals(expectedReleaseVersion, suggestedVersion);\n if (expectedDevelopmentVersion != null) {\n request.setVersion(suggestedVersion);\n String suggestedDevelopmentVersion = versionPolicy.getDevelopmentVersion(request).getVersion();\n assertEquals(expectedDevelopmentVersion, suggestedDevelopmentVersion);\n }\n }", "score": 0.8530415296554565 }, { "filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/ConventionalCommitsVersionPolicyTest.java", "retrieved_chunk": " String major = \"This is a Big Change commit.\";\n String versionRulesConfig = \"\"\n + \"<projectVersionPolicyConfig>\"\n + \" <versionTag>^The awesome ([0-9]+\\\\.[0-9]+\\\\.[0-9]+) release$</versionTag>\"\n + \" <majorRules>\"\n + \" <majorRule>^.*Big Change.*$</majorRule>\"\n + \" </majorRules>\"\n + \" <minorRules>\"\n + \" <minorRule>^.*Nice Change.*$</minorRule>\"\n + \" </minorRules>\"", "score": 0.8510795831680298 }, { "filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/ConfigParsingTest.java", "retrieved_chunk": " + \"</projectVersionPolicyConfig>\" +\n \"\";\n ConventionalCommitsVersionConfig config = ConventionalCommitsVersionConfig.fromXml(versionRulesConfig);\n LOG.info(\"Tested config: {}\", config);\n assertNull(config.getVersionTag());\n assertEquals(0, config.getMajorRules().size());\n assertEquals(1, config.getMinorRules().size());\n assertEquals(customMinorRulesRegex, config.getMinorRules().get(0));\n VersionRules versionRules = new VersionRules(config);\n assertTagPatternIsDefault(versionRules);", "score": 0.8500927686691284 }, { "filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/ConfigParsingTest.java", "retrieved_chunk": " + customMajorRulesXML\n + \"</projectVersionPolicyConfig>\" +\n \"\";\n ConventionalCommitsVersionConfig config = ConventionalCommitsVersionConfig.fromXml(versionRulesConfig);\n LOG.info(\"Tested config: {}\", config);\n assertEquals(customVersionTagRegex, config.getVersionTag());\n assertEquals(1, config.getMajorRules().size());\n assertEquals(customMajorRulesRegex, config.getMajorRules().get(0));\n assertEquals(0, config.getMinorRules().size());\n VersionRules versionRules = new VersionRules(config);", "score": 0.8496004343032837 }, { "filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/ConfigParsingTest.java", "retrieved_chunk": " + customVersionTagXML\n + customMinorRulesXML\n + \"</projectVersionPolicyConfig>\" +\n \"\";\n ConventionalCommitsVersionConfig config = ConventionalCommitsVersionConfig.fromXml(versionRulesConfig);\n LOG.info(\"Tested config: {}\", config);\n assertEquals(customVersionTagRegex, config.getVersionTag());\n assertEquals(0, config.getMajorRules().size());\n assertEquals(1, config.getMinorRules().size());\n assertEquals(customMinorRulesRegex, config.getMinorRules().get(0));", "score": 0.8492343425750732 } ]
java
= commitHistory.getLastVersionTag();
package org.example.service; import com.alibaba.fastjson.JSONObject; import com.aliyun.dingtalkrobot_1_0.Client; import com.aliyun.dingtalkrobot_1_0.models.OrgGroupSendHeaders; import com.aliyun.dingtalkrobot_1_0.models.OrgGroupSendRequest; import com.aliyun.dingtalkrobot_1_0.models.OrgGroupSendResponse; import com.aliyun.tea.TeaException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import java.util.Objects; /** * @author zeymo */ @Slf4j @Service public class RobotGroupMessagesService { private Client robotClient; private final AccessTokenService accessTokenService; @Value("${robot.code}") private String robotCode; @Autowired public RobotGroupMessagesService(AccessTokenService accessTokenService) { this.accessTokenService = accessTokenService; } @PostConstruct public void init() throws Exception { com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config(); config.protocol = "https"; config.regionId = "central"; robotClient = new Client(config); } /** * send message to group with openConversationId * * @param openConversationId conversationId * @return messageId * @throws Exception e */ public String send(String openConversationId, String text) throws Exception { OrgGroupSendHeaders orgGroupSendHeaders = new OrgGroupSendHeaders();
orgGroupSendHeaders.setXAcsDingtalkAccessToken(accessTokenService.getAccessToken());
OrgGroupSendRequest orgGroupSendRequest = new OrgGroupSendRequest(); orgGroupSendRequest.setMsgKey("sampleText"); orgGroupSendRequest.setRobotCode(robotCode); orgGroupSendRequest.setOpenConversationId(openConversationId); JSONObject msgParam = new JSONObject(); msgParam.put("content", "java-getting-start say : " + text); orgGroupSendRequest.setMsgParam(msgParam.toJSONString()); try { OrgGroupSendResponse orgGroupSendResponse = robotClient.orgGroupSendWithOptions(orgGroupSendRequest, orgGroupSendHeaders, new com.aliyun.teautil.models.RuntimeOptions()); if (Objects.isNull(orgGroupSendResponse) || Objects.isNull(orgGroupSendResponse.getBody())) { log.error("RobotGroupMessagesService_send orgGroupSendWithOptions return error, response={}", orgGroupSendResponse); return null; } return orgGroupSendResponse.getBody().getProcessQueryKey(); } catch (TeaException e) { log.error("RobotGroupMessagesService_send orgGroupSendWithOptions throw TeaException, errCode={}, " + "errorMessage={}", e.getCode(), e.getMessage(), e); throw e; } catch (Exception e) { log.error("RobotGroupMessagesService_send orgGroupSendWithOptions throw Exception", e); throw e; } } }
src/main/java/org/example/service/RobotGroupMessagesService.java
open-dingtalk-dingtalk-stream-sdk-java-quick-start-bb889b2
[ { "filename": "src/main/java/org/example/callback/robot/RobotMsgCallbackConsumer.java", "retrieved_chunk": " if (text != null) {\n String msg = text.getContent();\n log.info(\"receive bot message from user={}, msg={}\", message.getSenderId(), msg);\n String openConversationId = message.getConversationId();\n try {\n //发送机器人消息\n robotGroupMessagesService.send(openConversationId, \"hello\");\n } catch (Exception e) {\n log.error(\"send group message by robot error:\" + e.getMessage(), e);\n }", "score": 0.8232237100601196 }, { "filename": "src/main/java/org/example/callback/robot/RobotMsgCallbackConsumer.java", "retrieved_chunk": " /**\n * https://open.dingtalk.com/document/orgapp/the-application-robot-in-the-enterprise-sends-group-chat-messages\n *\n * @param message\n * @return\n */\n @Override\n public JSONObject execute(DingTalkBotMessage message) {\n try {\n Text text = message.getText();", "score": 0.8058483004570007 }, { "filename": "src/main/java/org/example/callback/robot/RobotMsgCallbackConsumer.java", "retrieved_chunk": "package org.example.callback.robot;\nimport com.alibaba.fastjson.JSONObject;\nimport org.example.model.DingTalkBotMessage;\nimport org.example.model.Text;\nimport org.example.service.RobotGroupMessagesService;\nimport com.dingtalk.open.app.api.callback.OpenDingTalkCallbackListener;\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\n/**", "score": 0.773087739944458 }, { "filename": "src/main/java/org/example/model/DingTalkBotMessage.java", "retrieved_chunk": " private String senderCorpId;\n private String conversationType;\n private String senderId;\n private String conversationTitle;\n private Boolean isInAtList;\n private Text text;\n private String msgtype;\n}", "score": 0.765576958656311 }, { "filename": "src/main/java/org/example/callback/robot/RobotMsgCallbackConsumer.java", "retrieved_chunk": " }\n } catch (Exception e) {\n log.error(\"receive group message by robot error:\" + e.getMessage(), e);\n }\n return new JSONObject();\n }\n}", "score": 0.7615185379981995 } ]
java
orgGroupSendHeaders.setXAcsDingtalkAccessToken(accessTokenService.getAccessToken());
/* * The MIT License (MIT) * * Copyright (c) 2023 Objectionary.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.objectionary; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import org.objectionary.entities.Entity; import org.objectionary.entities.FlatObject; import org.objectionary.entities.Locator; import org.objectionary.entities.NestedObject; /** * This class realizes the flattening of the objects. * @since 0.1.0 */ public final class Flatter { /** * The counter of created objects. */ private static int counter; /** * The objects box. */ private final ObjectsBox box; /** * Constructor. * @param box The objects box. */ public Flatter(final ObjectsBox box) { this.box = box; } /** * Flattens the objects. * @return The flattened objects box. */ public ObjectsBox flat() { Flatter.counter = this.findMaxIndex() + 1; boolean found = true; while (found) { found = false; for ( final Map.Entry<String, Map<String, Entity>> entry : this.box.content().entrySet() ) { for (final Map.Entry<String, Entity> binding : entry.getValue().entrySet()) { if (binding.getValue() instanceof NestedObject) { this.flatOne( binding.getKey(), (NestedObject) binding.getValue(), entry.getValue() ); found = true; break; } } if (found) { break; } } } this.removeUnusedObjects(); this.resuspendLocalBinds(); this.renameObjects(); return this.box; } /** * Flattens one object. * @param key The name of binding to this non-flat object. * @param object The non-flat object itself. * @param user The object which contains the non-flat object. */ private void flatOne( final String key, final NestedObject object, final Map<String, Entity> user ) { final Map<String, Entity> bindings = deepCopy(this.box.get(object.getName())); final Map<String, Entity> application
= deepCopy(object.getApplication());
final Map<String, Entity> reframed = deepReframe(application); for (final Map.Entry<String, Entity> entry : reframed.entrySet()) { if (bindings.containsKey(entry.getKey())) { bindings.put(entry.getKey(), entry.getValue()); } } final String name = String.format("ν%d", Flatter.counter); Flatter.counter += 1; this.box.put(name, bindings); user.put(key, new FlatObject(name, "ξ")); } /** * Removes unused objects from the box. */ private void removeUnusedObjects() { final Set<String> uses = new HashSet<>(); final Queue<String> queue = new LinkedList<>(); queue.add("ν0"); while (!queue.isEmpty()) { final String name = queue.poll(); uses.add(name); for (final Map.Entry<String, Entity> binding : this.box.get(name).entrySet()) { if (binding.getValue() instanceof FlatObject) { final String value = ((FlatObject) binding.getValue()).getName(); if (!uses.contains(value)) { queue.add(value); } } } } this.box.content().entrySet().removeIf(entry -> !uses.contains(entry.getKey())); } /** * Takes all locators to local variables and clearly sets them up. */ private void resuspendLocalBinds() { for (final Map<String, Entity> bindings : this.box.content().values()) { boolean found = true; while (found) { found = false; for (final Map.Entry<String, Entity> binding : bindings.entrySet()) { if (binding.getValue() instanceof Locator) { final List<String> locator = ((Locator) binding.getValue()).getPath(); if (!locator.get(0).equals("ξ")) { continue; } final String name = locator.get(1); final Entity entity = bindings.get(name); bindings.remove(name); bindings.put(binding.getKey(), entity); found = true; break; } } } } } /** * Renames the objects to use smaller indexes. */ private void renameObjects() { final List<Integer> list = new ArrayList<>(0); for (final String name : this.box.content().keySet()) { list.add(Integer.parseInt(name.substring(1))); } Collections.sort(list); final int size = this.box.content().size(); for (int idx = 0; idx < size; ++idx) { final String end = String.valueOf(idx); final String start = String.valueOf(list.get(idx)); if (end.equals(start)) { continue; } this.changeName(String.format("ν%s", start), String.format("ν%s", end)); } } /** * Changes the name of the object. * @param start The old name. * @param end The new name. */ private void changeName(final String start, final String end) { for ( final Map.Entry<String, Map<String, Entity>> bindings : this.box.content().entrySet() ) { for (final Map.Entry<String, Entity> binding : bindings.getValue().entrySet()) { if ( binding.getValue() instanceof FlatObject && ((FlatObject) binding.getValue()).getName().equals(start) ) { binding.setValue( new FlatObject(end, ((FlatObject) binding.getValue()).getLocator()) ); } } } this.box.put(end, this.box.get(start)); this.box.content().remove(start); } /** * Finds the maximum index of the objects. * @return The maximum index of the objects. */ private int findMaxIndex() { return this.box.content().keySet().stream() .map(key -> Integer.parseInt(key.substring(1))) .max(Integer::compareTo).orElse(0); } /** * Returns the deep copy of the bindings. * @param bindings The bindings. * @return The deep copy of the bindings. */ private static Map<String, Entity> deepCopy(final Map<String, Entity> bindings) { final Map<String, Entity> result = new HashMap<>(bindings.size()); for (final Map.Entry<String, Entity> entry : bindings.entrySet()) { result.put(entry.getKey(), entry.getValue().copy()); } return result; } /** * Returns the deep reframe of the bindings. * @param bindings The bindings. * @return The deep reframe of the bindings. */ private static Map<String, Entity> deepReframe(final Map<String, Entity> bindings) { final Map<String, Entity> result = new HashMap<>(bindings.size()); for (final Map.Entry<String, Entity> entry : bindings.entrySet()) { result.put(entry.getKey(), entry.getValue().reframe()); } return result; } }
src/main/java/org/objectionary/Flatter.java
objectionary-flatty-688a3da
[ { "filename": "src/test/java/org/objectionary/FlatterTest.java", "retrieved_chunk": " final Map<String, Entity> bindings = new HashMap<>();\n bindings.put(\"y\", new NestedObject(\"v\", application));\n box.put(FlatterTest.INIT_OBJECT, bindings);\n final Flatter flatter = new Flatter(box);\n MatcherAssert.assertThat(\n flatter.flat().toString(),\n Matchers.equalTo(\"ν0(𝜋) ↦ ⟦ y ↦ v( x ↦ 𝜋.𝜋.z ) ⟧\")\n );\n }\n @Test", "score": 0.8659995198249817 }, { "filename": "src/test/java/org/objectionary/FlatterTest.java", "retrieved_chunk": " /**\n * Flatter can flatten empty object.\n */\n @Test\n void testFlatter() {\n final ObjectsBox box = new ObjectsBox();\n final Map<String, Entity> bindings = new HashMap<>();\n bindings.put(\"x\", new Empty());\n box.put(FlatterTest.INIT_OBJECT, bindings);\n final Flatter flatter = new Flatter(box);", "score": 0.8332880735397339 }, { "filename": "src/test/java/org/objectionary/FlatterTest.java", "retrieved_chunk": " final Map<String, Entity> bindings = new HashMap<>();\n bindings.put(\"x\", new Locator(\"𝜋.𝜋.y\"));\n box.put(FlatterTest.INIT_OBJECT, bindings);\n final Flatter flatter = new Flatter(box);\n MatcherAssert.assertThat(\n flatter.flat().toString(),\n Matchers.equalTo(\"ν0(𝜋) ↦ ⟦ x ↦ 𝜋.𝜋.y ⟧\")\n );\n }\n @Test", "score": 0.8236252069473267 }, { "filename": "src/test/java/org/objectionary/ObjectsBoxTest.java", "retrieved_chunk": " void boxWithFlatObjectToStringTest() {\n final ObjectsBox box = new ObjectsBox();\n final Map<String, Entity> bindings = new HashMap<>();\n bindings.put(\"y\", new FlatObject(\"bar\", \"ξ\"));\n box.put(ObjectsBoxTest.INIT_OBJECT, bindings);\n MatcherAssert.assertThat(\n box.toString(),\n Matchers.equalTo(\"ν0(𝜋) ↦ ⟦ y ↦ bar(ξ) ⟧\")\n );\n }", "score": 0.8193370699882507 }, { "filename": "src/test/java/org/objectionary/ObjectsBoxTest.java", "retrieved_chunk": " }\n @Test\n void boxWithNestedObjectToStringTest() {\n final ObjectsBox box = new ObjectsBox();\n final Map<String, Entity> application = new HashMap<>();\n application.put(\"x\", new Locator(\"𝜋.𝜋.z\"));\n final Map<String, Entity> bindings = new HashMap<>();\n bindings.put(\"y\", new NestedObject(\"v\", application));\n box.put(ObjectsBoxTest.INIT_OBJECT, bindings);\n MatcherAssert.assertThat(", "score": 0.8178971409797668 } ]
java
= deepCopy(object.getApplication());
/* * The MIT License (MIT) * * Copyright (c) 2023 Objectionary.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.objectionary; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import org.objectionary.entities.Entity; import org.objectionary.entities.FlatObject; import org.objectionary.entities.Locator; import org.objectionary.entities.NestedObject; /** * This class realizes the flattening of the objects. * @since 0.1.0 */ public final class Flatter { /** * The counter of created objects. */ private static int counter; /** * The objects box. */ private final ObjectsBox box; /** * Constructor. * @param box The objects box. */ public Flatter(final ObjectsBox box) { this.box = box; } /** * Flattens the objects. * @return The flattened objects box. */ public ObjectsBox flat() { Flatter.counter = this.findMaxIndex() + 1; boolean found = true; while (found) { found = false; for ( final Map.Entry<String, Map<String, Entity>> entry : this.box.content().entrySet() ) { for (final Map.Entry<String, Entity> binding : entry.getValue().entrySet()) { if (binding.getValue() instanceof NestedObject) { this.flatOne( binding.getKey(), (NestedObject) binding.getValue(), entry.getValue() ); found = true; break; } } if (found) { break; } } } this.removeUnusedObjects(); this.resuspendLocalBinds(); this.renameObjects(); return this.box; } /** * Flattens one object. * @param key The name of binding to this non-flat object. * @param object The non-flat object itself. * @param user The object which contains the non-flat object. */ private void flatOne( final String key, final NestedObject object, final Map<String, Entity> user ) { final Map<String, Entity> bindings = deepCopy(this.box.get(object.getName())); final Map<String, Entity> application = deepCopy(object.getApplication()); final Map<String, Entity> reframed = deepReframe(application); for (final Map.Entry<String, Entity> entry : reframed.entrySet()) { if (bindings.containsKey(entry.getKey())) { bindings.put(entry.getKey(), entry.getValue()); } } final String name = String.format("ν%d", Flatter.counter); Flatter.counter += 1; this.box.put(name, bindings); user.put(key, new FlatObject(name, "ξ")); } /** * Removes unused objects from the box. */ private void removeUnusedObjects() { final Set<String> uses = new HashSet<>(); final Queue<String> queue = new LinkedList<>(); queue.add("ν0"); while (!queue.isEmpty()) { final String name = queue.poll(); uses.add(name); for (final Map.Entry<String, Entity> binding : this.box.get(name).entrySet()) { if (binding.getValue() instanceof FlatObject) { final String value = ((FlatObject) binding.getValue()).getName(); if (!uses.contains(value)) { queue.add(value); } } } } this.box.content().entrySet().removeIf(entry -> !uses.contains(entry.getKey())); } /** * Takes all locators to local variables and clearly sets them up. */ private void resuspendLocalBinds() { for (final Map<String, Entity> bindings : this.box.content().values()) { boolean found = true; while (found) { found = false; for (final Map.Entry<String, Entity> binding : bindings.entrySet()) { if (binding.getValue() instanceof Locator) { final List<String>
locator = ((Locator) binding.getValue()).getPath();
if (!locator.get(0).equals("ξ")) { continue; } final String name = locator.get(1); final Entity entity = bindings.get(name); bindings.remove(name); bindings.put(binding.getKey(), entity); found = true; break; } } } } } /** * Renames the objects to use smaller indexes. */ private void renameObjects() { final List<Integer> list = new ArrayList<>(0); for (final String name : this.box.content().keySet()) { list.add(Integer.parseInt(name.substring(1))); } Collections.sort(list); final int size = this.box.content().size(); for (int idx = 0; idx < size; ++idx) { final String end = String.valueOf(idx); final String start = String.valueOf(list.get(idx)); if (end.equals(start)) { continue; } this.changeName(String.format("ν%s", start), String.format("ν%s", end)); } } /** * Changes the name of the object. * @param start The old name. * @param end The new name. */ private void changeName(final String start, final String end) { for ( final Map.Entry<String, Map<String, Entity>> bindings : this.box.content().entrySet() ) { for (final Map.Entry<String, Entity> binding : bindings.getValue().entrySet()) { if ( binding.getValue() instanceof FlatObject && ((FlatObject) binding.getValue()).getName().equals(start) ) { binding.setValue( new FlatObject(end, ((FlatObject) binding.getValue()).getLocator()) ); } } } this.box.put(end, this.box.get(start)); this.box.content().remove(start); } /** * Finds the maximum index of the objects. * @return The maximum index of the objects. */ private int findMaxIndex() { return this.box.content().keySet().stream() .map(key -> Integer.parseInt(key.substring(1))) .max(Integer::compareTo).orElse(0); } /** * Returns the deep copy of the bindings. * @param bindings The bindings. * @return The deep copy of the bindings. */ private static Map<String, Entity> deepCopy(final Map<String, Entity> bindings) { final Map<String, Entity> result = new HashMap<>(bindings.size()); for (final Map.Entry<String, Entity> entry : bindings.entrySet()) { result.put(entry.getKey(), entry.getValue().copy()); } return result; } /** * Returns the deep reframe of the bindings. * @param bindings The bindings. * @return The deep reframe of the bindings. */ private static Map<String, Entity> deepReframe(final Map<String, Entity> bindings) { final Map<String, Entity> result = new HashMap<>(bindings.size()); for (final Map.Entry<String, Entity> entry : bindings.entrySet()) { result.put(entry.getKey(), entry.getValue().reframe()); } return result; } }
src/main/java/org/objectionary/Flatter.java
objectionary-flatty-688a3da
[ { "filename": "src/test/java/org/objectionary/ObjectsBoxTest.java", "retrieved_chunk": " final ObjectsBox box = new ObjectsBox();\n final Map<String, Entity> bindings = new HashMap<>();\n bindings.put(\"x\", new Locator(\"𝜋.𝜋.y\"));\n box.put(ObjectsBoxTest.INIT_OBJECT, bindings);\n MatcherAssert.assertThat(\n box.toString(),\n Matchers.equalTo(\"ν0(𝜋) ↦ ⟦ x ↦ 𝜋.𝜋.y ⟧\")\n );\n }\n @Test", "score": 0.8141411542892456 }, { "filename": "src/test/java/org/objectionary/ObjectsBoxTest.java", "retrieved_chunk": " final Map<String, Entity> bindings = new HashMap<>();\n bindings.put(\"Δ\", new Data(Integer.parseInt(\"000A\", 16)));\n box.put(ObjectsBoxTest.INIT_OBJECT, bindings);\n MatcherAssert.assertThat(\n box.toString(),\n Matchers.equalTo(\"ν0(𝜋) ↦ ⟦ Δ ↦ 0x000A ⟧\")\n );\n }\n @Test\n void boxWithLocatorToStringTest() {", "score": 0.8068346977233887 }, { "filename": "src/main/java/org/objectionary/ObjectsBox.java", "retrieved_chunk": " for (final String binding : dataizations) {\n if (bindings.containsKey(binding)) {\n result.add(\n String.format(\"%s ↦ %s\", binding, bindings.get(binding))\n );\n }\n }\n for (final Map.Entry<String, Entity> binding : bindings.entrySet()) {\n if (dataizations.contains(binding.getKey())) {\n continue;", "score": 0.8038527965545654 }, { "filename": "src/test/java/org/objectionary/FlatterTest.java", "retrieved_chunk": " final Map<String, Entity> bindings = new HashMap<>();\n bindings.put(\"x\", new Locator(\"𝜋.𝜋.y\"));\n box.put(FlatterTest.INIT_OBJECT, bindings);\n final Flatter flatter = new Flatter(box);\n MatcherAssert.assertThat(\n flatter.flat().toString(),\n Matchers.equalTo(\"ν0(𝜋) ↦ ⟦ x ↦ 𝜋.𝜋.y ⟧\")\n );\n }\n @Test", "score": 0.8013010621070862 }, { "filename": "src/main/java/org/objectionary/ObjectsBox.java", "retrieved_chunk": " public void put(final String name, final Map<String, Entity> bindings) {\n this.box.put(name, bindings);\n }\n /**\n * Gets an object by name.\n * @param name The name of the object.\n * @return The object.\n */\n public Map<String, Entity> get(final String name) {\n return this.box.get(name);", "score": 0.7927573919296265 } ]
java
locator = ((Locator) binding.getValue()).getPath();
/* * The MIT License (MIT) * * Copyright (c) 2023 Objectionary.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.objectionary; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import org.objectionary.entities.Entity; import org.objectionary.entities.FlatObject; import org.objectionary.entities.Locator; import org.objectionary.entities.NestedObject; /** * This class realizes the flattening of the objects. * @since 0.1.0 */ public final class Flatter { /** * The counter of created objects. */ private static int counter; /** * The objects box. */ private final ObjectsBox box; /** * Constructor. * @param box The objects box. */ public Flatter(final ObjectsBox box) { this.box = box; } /** * Flattens the objects. * @return The flattened objects box. */ public ObjectsBox flat() { Flatter.counter = this.findMaxIndex() + 1; boolean found = true; while (found) { found = false; for ( final Map.Entry<String, Map<String, Entity>> entry : this.box.content().entrySet() ) { for (final Map.Entry<String, Entity> binding : entry.getValue().entrySet()) { if (binding.getValue() instanceof NestedObject) { this.flatOne( binding.getKey(), (NestedObject) binding.getValue(), entry.getValue() ); found = true; break; } } if (found) { break; } } } this.removeUnusedObjects(); this.resuspendLocalBinds(); this.renameObjects(); return this.box; } /** * Flattens one object. * @param key The name of binding to this non-flat object. * @param object The non-flat object itself. * @param user The object which contains the non-flat object. */ private void flatOne( final String key, final NestedObject object, final Map<String, Entity> user ) { final Map<String, Entity> bindings = deepCopy(this.
box.get(object.getName()));
final Map<String, Entity> application = deepCopy(object.getApplication()); final Map<String, Entity> reframed = deepReframe(application); for (final Map.Entry<String, Entity> entry : reframed.entrySet()) { if (bindings.containsKey(entry.getKey())) { bindings.put(entry.getKey(), entry.getValue()); } } final String name = String.format("ν%d", Flatter.counter); Flatter.counter += 1; this.box.put(name, bindings); user.put(key, new FlatObject(name, "ξ")); } /** * Removes unused objects from the box. */ private void removeUnusedObjects() { final Set<String> uses = new HashSet<>(); final Queue<String> queue = new LinkedList<>(); queue.add("ν0"); while (!queue.isEmpty()) { final String name = queue.poll(); uses.add(name); for (final Map.Entry<String, Entity> binding : this.box.get(name).entrySet()) { if (binding.getValue() instanceof FlatObject) { final String value = ((FlatObject) binding.getValue()).getName(); if (!uses.contains(value)) { queue.add(value); } } } } this.box.content().entrySet().removeIf(entry -> !uses.contains(entry.getKey())); } /** * Takes all locators to local variables and clearly sets them up. */ private void resuspendLocalBinds() { for (final Map<String, Entity> bindings : this.box.content().values()) { boolean found = true; while (found) { found = false; for (final Map.Entry<String, Entity> binding : bindings.entrySet()) { if (binding.getValue() instanceof Locator) { final List<String> locator = ((Locator) binding.getValue()).getPath(); if (!locator.get(0).equals("ξ")) { continue; } final String name = locator.get(1); final Entity entity = bindings.get(name); bindings.remove(name); bindings.put(binding.getKey(), entity); found = true; break; } } } } } /** * Renames the objects to use smaller indexes. */ private void renameObjects() { final List<Integer> list = new ArrayList<>(0); for (final String name : this.box.content().keySet()) { list.add(Integer.parseInt(name.substring(1))); } Collections.sort(list); final int size = this.box.content().size(); for (int idx = 0; idx < size; ++idx) { final String end = String.valueOf(idx); final String start = String.valueOf(list.get(idx)); if (end.equals(start)) { continue; } this.changeName(String.format("ν%s", start), String.format("ν%s", end)); } } /** * Changes the name of the object. * @param start The old name. * @param end The new name. */ private void changeName(final String start, final String end) { for ( final Map.Entry<String, Map<String, Entity>> bindings : this.box.content().entrySet() ) { for (final Map.Entry<String, Entity> binding : bindings.getValue().entrySet()) { if ( binding.getValue() instanceof FlatObject && ((FlatObject) binding.getValue()).getName().equals(start) ) { binding.setValue( new FlatObject(end, ((FlatObject) binding.getValue()).getLocator()) ); } } } this.box.put(end, this.box.get(start)); this.box.content().remove(start); } /** * Finds the maximum index of the objects. * @return The maximum index of the objects. */ private int findMaxIndex() { return this.box.content().keySet().stream() .map(key -> Integer.parseInt(key.substring(1))) .max(Integer::compareTo).orElse(0); } /** * Returns the deep copy of the bindings. * @param bindings The bindings. * @return The deep copy of the bindings. */ private static Map<String, Entity> deepCopy(final Map<String, Entity> bindings) { final Map<String, Entity> result = new HashMap<>(bindings.size()); for (final Map.Entry<String, Entity> entry : bindings.entrySet()) { result.put(entry.getKey(), entry.getValue().copy()); } return result; } /** * Returns the deep reframe of the bindings. * @param bindings The bindings. * @return The deep reframe of the bindings. */ private static Map<String, Entity> deepReframe(final Map<String, Entity> bindings) { final Map<String, Entity> result = new HashMap<>(bindings.size()); for (final Map.Entry<String, Entity> entry : bindings.entrySet()) { result.put(entry.getKey(), entry.getValue().reframe()); } return result; } }
src/main/java/org/objectionary/Flatter.java
objectionary-flatty-688a3da
[ { "filename": "src/test/java/org/objectionary/FlatterTest.java", "retrieved_chunk": " final Map<String, Entity> bindings = new HashMap<>();\n bindings.put(\"y\", new NestedObject(\"v\", application));\n box.put(FlatterTest.INIT_OBJECT, bindings);\n final Flatter flatter = new Flatter(box);\n MatcherAssert.assertThat(\n flatter.flat().toString(),\n Matchers.equalTo(\"ν0(𝜋) ↦ ⟦ y ↦ v( x ↦ 𝜋.𝜋.z ) ⟧\")\n );\n }\n @Test", "score": 0.8478830456733704 }, { "filename": "src/test/java/org/objectionary/FlatterTest.java", "retrieved_chunk": " /**\n * Flatter can flatten empty object.\n */\n @Test\n void testFlatter() {\n final ObjectsBox box = new ObjectsBox();\n final Map<String, Entity> bindings = new HashMap<>();\n bindings.put(\"x\", new Empty());\n box.put(FlatterTest.INIT_OBJECT, bindings);\n final Flatter flatter = new Flatter(box);", "score": 0.8446340560913086 }, { "filename": "src/test/java/org/objectionary/FlatterTest.java", "retrieved_chunk": " final Map<String, Entity> bindings = new HashMap<>();\n bindings.put(\"x\", new Locator(\"𝜋.𝜋.y\"));\n box.put(FlatterTest.INIT_OBJECT, bindings);\n final Flatter flatter = new Flatter(box);\n MatcherAssert.assertThat(\n flatter.flat().toString(),\n Matchers.equalTo(\"ν0(𝜋) ↦ ⟦ x ↦ 𝜋.𝜋.y ⟧\")\n );\n }\n @Test", "score": 0.8376227021217346 }, { "filename": "src/test/java/org/objectionary/ObjectsBoxTest.java", "retrieved_chunk": " void boxWithFlatObjectToStringTest() {\n final ObjectsBox box = new ObjectsBox();\n final Map<String, Entity> bindings = new HashMap<>();\n bindings.put(\"y\", new FlatObject(\"bar\", \"ξ\"));\n box.put(ObjectsBoxTest.INIT_OBJECT, bindings);\n MatcherAssert.assertThat(\n box.toString(),\n Matchers.equalTo(\"ν0(𝜋) ↦ ⟦ y ↦ bar(ξ) ⟧\")\n );\n }", "score": 0.8343947529792786 }, { "filename": "src/test/java/org/objectionary/FlatterTest.java", "retrieved_chunk": " @Disabled\n void boxWithFlatObjectToStringTest() {\n final ObjectsBox box = new ObjectsBox();\n final Map<String, Entity> bindings = new HashMap<>();\n bindings.put(\"y\", new FlatObject(\"bar\", \"ξ\"));\n box.put(FlatterTest.INIT_OBJECT, bindings);\n final Flatter flatter = new Flatter(box);\n MatcherAssert.assertThat(\n flatter.flat().toString(),\n Matchers.equalTo(\"ν0(𝜋) ↦ ⟦ y ↦ bar(ξ) ⟧\")", "score": 0.8327605724334717 } ]
java
box.get(object.getName()));
package org.example.callback.robot; import com.alibaba.fastjson.JSONObject; import org.example.model.DingTalkBotMessage; import org.example.model.Text; import org.example.service.RobotGroupMessagesService; import com.dingtalk.open.app.api.callback.OpenDingTalkCallbackListener; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * @author zeymo */ @Slf4j @Component public class RobotMsgCallbackConsumer implements OpenDingTalkCallbackListener<DingTalkBotMessage, JSONObject> { private RobotGroupMessagesService robotGroupMessagesService; @Autowired public RobotMsgCallbackConsumer(RobotGroupMessagesService robotGroupMessagesService) { this.robotGroupMessagesService = robotGroupMessagesService; } /** * https://open.dingtalk.com/document/orgapp/the-application-robot-in-the-enterprise-sends-group-chat-messages * * @param message * @return */ @Override public JSONObject execute(DingTalkBotMessage message) { try { Text text = message.getText(); if (text != null) { String msg = text.getContent(); log.info("receive bot message from user={}, msg={}", message.getSenderId(), msg); String openConversationId = message.getConversationId(); try { //发送机器人消息
robotGroupMessagesService.send(openConversationId, "hello");
} catch (Exception e) { log.error("send group message by robot error:" + e.getMessage(), e); } } } catch (Exception e) { log.error("receive group message by robot error:" + e.getMessage(), e); } return new JSONObject(); } }
src/main/java/org/example/callback/robot/RobotMsgCallbackConsumer.java
open-dingtalk-dingtalk-stream-sdk-java-quick-start-bb889b2
[ { "filename": "src/main/java/org/example/service/RobotGroupMessagesService.java", "retrieved_chunk": " */\n public String send(String openConversationId, String text) throws Exception {\n OrgGroupSendHeaders orgGroupSendHeaders = new OrgGroupSendHeaders();\n orgGroupSendHeaders.setXAcsDingtalkAccessToken(accessTokenService.getAccessToken());\n OrgGroupSendRequest orgGroupSendRequest = new OrgGroupSendRequest();\n orgGroupSendRequest.setMsgKey(\"sampleText\");\n orgGroupSendRequest.setRobotCode(robotCode);\n orgGroupSendRequest.setOpenConversationId(openConversationId);\n JSONObject msgParam = new JSONObject();\n msgParam.put(\"content\", \"java-getting-start say : \" + text);", "score": 0.8759583234786987 }, { "filename": "src/main/java/org/example/service/RobotGroupMessagesService.java", "retrieved_chunk": "package org.example.service;\nimport com.alibaba.fastjson.JSONObject;\nimport com.aliyun.dingtalkrobot_1_0.Client;\nimport com.aliyun.dingtalkrobot_1_0.models.OrgGroupSendHeaders;\nimport com.aliyun.dingtalkrobot_1_0.models.OrgGroupSendRequest;\nimport com.aliyun.dingtalkrobot_1_0.models.OrgGroupSendResponse;\nimport com.aliyun.tea.TeaException;\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.beans.factory.annotation.Value;", "score": 0.8282274007797241 }, { "filename": "src/main/java/org/example/model/DingTalkBotMessage.java", "retrieved_chunk": "package org.example.model;\nimport lombok.Data;\nimport java.util.List;\n/**\n * @author feiyin\n * @date 2023/6/30\n * 参考钉钉机器人官方说明 @see <a href=https://open.dingtalk.com/document/orgapp/the-application-robot-in-the-enterprise-sends-group-chat-messages/>\n */\n@Data\npublic class DingTalkBotMessage {", "score": 0.8231195211410522 }, { "filename": "src/main/java/org/example/service/RobotGroupMessagesService.java", "retrieved_chunk": " private final AccessTokenService accessTokenService;\n @Value(\"${robot.code}\")\n private String robotCode;\n @Autowired\n public RobotGroupMessagesService(AccessTokenService accessTokenService) {\n this.accessTokenService = accessTokenService;\n }\n @PostConstruct\n public void init() throws Exception {\n com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();", "score": 0.8159738779067993 }, { "filename": "src/main/java/org/example/StreamCallbackListener.java", "retrieved_chunk": "package org.example;\nimport org.example.callback.robot.RobotMsgCallbackConsumer;\nimport com.dingtalk.open.app.api.OpenDingTalkClient;\nimport com.dingtalk.open.app.api.OpenDingTalkStreamClientBuilder;\nimport com.dingtalk.open.app.api.security.AuthClientCredential;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.stereotype.Component;\nimport javax.annotation.PostConstruct;\n/**", "score": 0.8114454746246338 } ]
java
robotGroupMessagesService.send(openConversationId, "hello");
/* * The MIT License (MIT) * * Copyright (c) 2023 Objectionary.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.objectionary.parsing; import java.util.HashMap; import java.util.Map; import org.objectionary.Tokenizer; import org.objectionary.entities.Data; import org.objectionary.entities.Empty; import org.objectionary.entities.Entity; import org.objectionary.entities.FlatObject; import org.objectionary.entities.Lambda; import org.objectionary.entities.Locator; import org.objectionary.entities.NestedObject; import org.objectionary.tokens.BracketToken; import org.objectionary.tokens.StringToken; import org.objectionary.tokens.Token; /** * Entities reader. * @since 0.1.0 * @checkstyle NonStaticMethodCheck (100 lines) */ public final class Entities { /** * The tokenizer. */ @SuppressWarnings({"PMD.UnusedPrivateField", "PMD.SingularField"}) private final Tokenizer tokenizer; /** * Constructor. * @param tokenizer The tokenizer. */ public Entities(final Tokenizer tokenizer) { this.tokenizer = tokenizer; } /** * Reads one entity. * @return The parsed entity. */ public Entity one() { final Token token = this.
tokenizer.getToken();
if (!(token instanceof StringToken)) { throw new IllegalArgumentException("Expected string token"); } final String value = ((StringToken) token).getValue(); final Entity result; final TypeChecker type = new TypeChecker(value); if (type.isEmpty()) { result = new Empty(); } else if (type.isLocator()) { result = new Locator(value); } else if (type.isData()) { result = new Data(Integer.parseInt(value.substring(2), 16)); } else if (type.isLambda()) { result = new Lambda(value); } else if (type.isObject()) { result = this.createObject(value); } else { throw new IllegalArgumentException("Unknown token"); } return result; } /** * Reads nested entity. * @return The parsed nested entity. */ public Map<String, Entity> nested() { final Map<String, Entity> result = new HashMap<>(); while (true) { final Token token = this.tokenizer.getToken(); if (token instanceof BracketToken) { final BracketToken bracket = (BracketToken) token; if (bracket.getState() == BracketToken.BracketType.CLOSE) { break; } } final String name = ((StringToken) token).getValue(); this.tokenizer.next(); this.tokenizer.next(); final Entity entity = this.one(); result.put(name, entity); this.tokenizer.next(); } return result; } /** * Creates an object. * @param value The value to parse. * @return The parsed entity. */ private Entity createObject(final String value) { final Entity result; if (value.contains(")")) { result = new FlatObject( value.substring(0, value.indexOf('(')), value.substring(value.indexOf('(') + 1, value.indexOf(')')) ); } else if (value.contains("(")) { this.tokenizer.next(); final Map<String, Entity> application = this.nested(); result = new NestedObject( value.substring(0, value.indexOf('(')), application ); } else { result = new FlatObject(value, ""); } return result; } }
src/main/java/org/objectionary/parsing/Entities.java
objectionary-flatty-688a3da
[ { "filename": "src/test/java/org/objectionary/EntitiesTest.java", "retrieved_chunk": " }\n @Test\n void readOneObjectTest() {\n final String input = \"ν(𝜋)\";\n final Entities reader = new Entities(new Tokenizer(input));\n MatcherAssert.assertThat(\n reader.one(),\n Matchers.instanceOf(FlatObject.class)\n );\n }", "score": 0.8499477505683899 }, { "filename": "src/test/java/org/objectionary/EntitiesTest.java", "retrieved_chunk": " @Test\n void readOneNestedObject() {\n final String input = \"ν1( ρ ↦ ξ.ρ )\";\n final Entities reader = new Entities(new Tokenizer(input));\n MatcherAssert.assertThat(\n reader.one(),\n Matchers.instanceOf(NestedObject.class)\n );\n }\n @Test", "score": 0.8355424404144287 }, { "filename": "src/test/java/org/objectionary/EntitiesTest.java", "retrieved_chunk": " );\n }\n @Test\n void readOneDataTest() {\n final String input = \"0x0042\";\n final Entities reader = new Entities(new Tokenizer(input));\n MatcherAssert.assertThat(\n reader.one(),\n Matchers.instanceOf(Data.class)\n );", "score": 0.8345432281494141 }, { "filename": "src/test/java/org/objectionary/EntitiesTest.java", "retrieved_chunk": " @Disabled\n @Test\n void readOneFailedTest() {\n final String input = \"...\";\n final Entities reader = new Entities(new Tokenizer(input));\n MatcherAssert.assertThat(\n reader.one(),\n Matchers.instanceOf(IllegalArgumentException.class)\n );\n }", "score": 0.8337191939353943 }, { "filename": "src/test/java/org/objectionary/EntitiesTest.java", "retrieved_chunk": " reader.one(),\n Matchers.instanceOf(Empty.class)\n );\n }\n @Test\n void readOneLocatorTest() {\n final String input = \"𝜋.𝜋.𝜋.x\";\n final Entities reader = new Entities(new Tokenizer(input));\n MatcherAssert.assertThat(\n reader.one(),", "score": 0.8335680365562439 } ]
java
tokenizer.getToken();
package onebeastchris.event; import com.mojang.authlib.GameProfile; import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.text.Text; import net.minecraft.world.GameMode; import onebeastchris.util.PlayerDataUtil; import onebeastchris.util.PlayerInfoStorage; import onebeastchris.visitors; public class ServerLeaveEvent { public static void register() { ServerPlayConnectionEvents.DISCONNECT.register((handler, server) -> { ServerPlayerEntity player = handler.getPlayer().networkHandler.player; GameProfile profile = player.getGameProfile(); if (PlayerDataUtil.isVisitor(profile)) { onLeave(player, profile); } }); } public static void onLeave(ServerPlayerEntity player, GameProfile profile){ PlayerDataUtil.removeVisitor(profile); PlayerInfoStorage storage = ServerJoinEvent.tempStorage.get(player); int x = storage.getPosition()[0]; int y = storage.getPosition()[1]; int z = storage.getPosition()[2]; player.teleport(storage.getWorld(), x, y, z, 0, 0); player.changeGameMode(GameMode.DEFAULT); player.sendMessage(Text.of(visitors.config.getWelcomeMemberMessage()), true); player.setCustomName
(storage.getName());
PlayerDataUtil.removeVisitor(profile); ServerJoinEvent.tempStorage.remove(player); } }
src/main/java/onebeastchris/event/ServerLeaveEvent.java
onebeastchris-visitors-abf022e
[ { "filename": "src/main/java/onebeastchris/event/ServerJoinEvent.java", "retrieved_chunk": " player.getCustomName(),\n player.getWorld(),\n new int[]{player.getBlockPos().getX(), player.getBlockPos().getY(), player.getBlockPos().getZ()})\n );\n if (visitors.config.getUseAdventure()) {\n player.changeGameMode(GameMode.ADVENTURE);\n } else {\n player.changeGameMode(GameMode.SPECTATOR);\n }\n player.setCustomName(Text.of(\"Visitor: \" + player.getGameProfile().getName()));", "score": 0.8980459570884705 }, { "filename": "src/main/java/onebeastchris/event/ServerJoinEvent.java", "retrieved_chunk": " player.setCustomNameVisible(true);\n //calling this once to ensure players see... something.\n player.sendMessage(Text.of(visitors.config.getWelcomeVisitorMessage1()), true);\n }\n }\n });\n }\n}", "score": 0.8731159567832947 }, { "filename": "src/main/java/onebeastchris/event/ServerJoinEvent.java", "retrieved_chunk": "public class ServerJoinEvent {\n public static final HashMap<ServerPlayerEntity, PlayerInfoStorage> tempStorage = new HashMap<>();\n public static void register() {\n ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> {\n ServerPlayerEntity player = handler.getPlayer().networkHandler.player;\n GameProfile profile = player.getGameProfile();\n if (PlayerDataUtil.isVisitor(profile)) {\n if (PlayerDataUtil.isVisitor(profile)) {\n PlayerDataUtil.addPlayer(profile, player);\n tempStorage.put(player, new PlayerInfoStorage(", "score": 0.8631574511528015 }, { "filename": "src/main/java/onebeastchris/util/PlayerDataUtil.java", "retrieved_chunk": "package onebeastchris.util;\nimport com.mojang.authlib.GameProfile;\nimport net.minecraft.server.network.ServerPlayerEntity;\nimport onebeastchris.event.ServerLeaveEvent;\nimport java.util.HashMap;\npublic class PlayerDataUtil {\n public static HashMap<GameProfile, ServerPlayerEntity> visitorMap = new HashMap<>();\n public static void addVisitor(GameProfile gameProfile, ServerPlayerEntity player){\n visitorMap.put(gameProfile, player);\n }", "score": 0.8563041687011719 }, { "filename": "src/main/java/onebeastchris/util/PlayerDataUtil.java", "retrieved_chunk": " public static void addPlayer(GameProfile gameProfile, ServerPlayerEntity player){\n visitorMap.remove(gameProfile, null);\n visitorMap.put(gameProfile, player);\n }\n public static void changeStatus(GameProfile gameProfile){\n if (visitorMap.containsKey(gameProfile)) {\n ServerLeaveEvent.onLeave(visitorMap.get(gameProfile), gameProfile);\n visitorMap.remove(gameProfile);\n }\n }", "score": 0.8552626967430115 } ]
java
(storage.getName());
/* * The MIT License (MIT) * * Copyright (c) 2023 Objectionary.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.objectionary; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import org.objectionary.entities.Entity; import org.objectionary.entities.FlatObject; import org.objectionary.entities.Locator; import org.objectionary.entities.NestedObject; /** * This class realizes the flattening of the objects. * @since 0.1.0 */ public final class Flatter { /** * The counter of created objects. */ private static int counter; /** * The objects box. */ private final ObjectsBox box; /** * Constructor. * @param box The objects box. */ public Flatter(final ObjectsBox box) { this.box = box; } /** * Flattens the objects. * @return The flattened objects box. */ public ObjectsBox flat() { Flatter.counter = this.findMaxIndex() + 1; boolean found = true; while (found) { found = false; for ( final Map.Entry<String, Map<String, Entity>> entry : this.box.content().entrySet() ) { for (final Map.Entry<String, Entity> binding : entry.getValue().entrySet()) { if (binding.getValue() instanceof NestedObject) { this.flatOne( binding.getKey(), (NestedObject) binding.getValue(), entry.getValue() ); found = true; break; } } if (found) { break; } } } this.removeUnusedObjects(); this.resuspendLocalBinds(); this.renameObjects(); return this.box; } /** * Flattens one object. * @param key The name of binding to this non-flat object. * @param object The non-flat object itself. * @param user The object which contains the non-flat object. */ private void flatOne( final String key, final NestedObject object, final Map<String, Entity> user ) { final Map<String, Entity> bindings = deepCopy(this.box.get(object.getName())); final Map<String, Entity> application = deepCopy(object.getApplication()); final Map<String, Entity> reframed = deepReframe(application); for (final Map.Entry<String, Entity> entry : reframed.entrySet()) { if (bindings.containsKey(entry.getKey())) { bindings.put(entry.getKey(), entry.getValue()); } } final String name = String.format("ν%d", Flatter.counter); Flatter.counter += 1; this.box.put(name, bindings); user.put(key, new FlatObject(name, "ξ")); } /** * Removes unused objects from the box. */ private void removeUnusedObjects() { final Set<String> uses = new HashSet<>(); final Queue<String> queue = new LinkedList<>(); queue.add("ν0"); while (!queue.isEmpty()) { final String name = queue.poll(); uses.add(name); for (final Map.Entry<String, Entity> binding : this.box.get(name).entrySet()) { if (binding.getValue() instanceof FlatObject) { final String value = ((FlatObject) binding.getValue()
).getName();
if (!uses.contains(value)) { queue.add(value); } } } } this.box.content().entrySet().removeIf(entry -> !uses.contains(entry.getKey())); } /** * Takes all locators to local variables and clearly sets them up. */ private void resuspendLocalBinds() { for (final Map<String, Entity> bindings : this.box.content().values()) { boolean found = true; while (found) { found = false; for (final Map.Entry<String, Entity> binding : bindings.entrySet()) { if (binding.getValue() instanceof Locator) { final List<String> locator = ((Locator) binding.getValue()).getPath(); if (!locator.get(0).equals("ξ")) { continue; } final String name = locator.get(1); final Entity entity = bindings.get(name); bindings.remove(name); bindings.put(binding.getKey(), entity); found = true; break; } } } } } /** * Renames the objects to use smaller indexes. */ private void renameObjects() { final List<Integer> list = new ArrayList<>(0); for (final String name : this.box.content().keySet()) { list.add(Integer.parseInt(name.substring(1))); } Collections.sort(list); final int size = this.box.content().size(); for (int idx = 0; idx < size; ++idx) { final String end = String.valueOf(idx); final String start = String.valueOf(list.get(idx)); if (end.equals(start)) { continue; } this.changeName(String.format("ν%s", start), String.format("ν%s", end)); } } /** * Changes the name of the object. * @param start The old name. * @param end The new name. */ private void changeName(final String start, final String end) { for ( final Map.Entry<String, Map<String, Entity>> bindings : this.box.content().entrySet() ) { for (final Map.Entry<String, Entity> binding : bindings.getValue().entrySet()) { if ( binding.getValue() instanceof FlatObject && ((FlatObject) binding.getValue()).getName().equals(start) ) { binding.setValue( new FlatObject(end, ((FlatObject) binding.getValue()).getLocator()) ); } } } this.box.put(end, this.box.get(start)); this.box.content().remove(start); } /** * Finds the maximum index of the objects. * @return The maximum index of the objects. */ private int findMaxIndex() { return this.box.content().keySet().stream() .map(key -> Integer.parseInt(key.substring(1))) .max(Integer::compareTo).orElse(0); } /** * Returns the deep copy of the bindings. * @param bindings The bindings. * @return The deep copy of the bindings. */ private static Map<String, Entity> deepCopy(final Map<String, Entity> bindings) { final Map<String, Entity> result = new HashMap<>(bindings.size()); for (final Map.Entry<String, Entity> entry : bindings.entrySet()) { result.put(entry.getKey(), entry.getValue().copy()); } return result; } /** * Returns the deep reframe of the bindings. * @param bindings The bindings. * @return The deep reframe of the bindings. */ private static Map<String, Entity> deepReframe(final Map<String, Entity> bindings) { final Map<String, Entity> result = new HashMap<>(bindings.size()); for (final Map.Entry<String, Entity> entry : bindings.entrySet()) { result.put(entry.getKey(), entry.getValue().reframe()); } return result; } }
src/main/java/org/objectionary/Flatter.java
objectionary-flatty-688a3da
[ { "filename": "src/test/java/org/objectionary/ObjectsBoxTest.java", "retrieved_chunk": " final Map<String, Entity> bindings = new HashMap<>();\n bindings.put(\"λ\", new Data(Integer.parseInt(\"000A\", 16)));\n bindings.put(\"a1\", new Empty());\n bindings.put(\"a2\", new FlatObject(\"bar\", \"𝜋\"));\n bindings.put(\"a3\", new Lambda(\"Atom\"));\n box.put(ObjectsBoxTest.INIT_OBJECT, bindings);\n final String result = box.toString();\n MatcherAssert.assertThat(\n result.split(\" \")[3],\n Matchers.equalTo(\"λ\")", "score": 0.8656157851219177 }, { "filename": "src/test/java/org/objectionary/FlatterTest.java", "retrieved_chunk": " final Map<String, Entity> bindings = new HashMap<>();\n bindings.put(\"x\", new Locator(\"𝜋.𝜋.y\"));\n box.put(FlatterTest.INIT_OBJECT, bindings);\n final Flatter flatter = new Flatter(box);\n MatcherAssert.assertThat(\n flatter.flat().toString(),\n Matchers.equalTo(\"ν0(𝜋) ↦ ⟦ x ↦ 𝜋.𝜋.y ⟧\")\n );\n }\n @Test", "score": 0.8619367480278015 }, { "filename": "src/test/java/org/objectionary/FlatterTest.java", "retrieved_chunk": " final Map<String, Entity> bindings = new HashMap<>();\n bindings.put(\"y\", new NestedObject(\"v\", application));\n box.put(FlatterTest.INIT_OBJECT, bindings);\n final Flatter flatter = new Flatter(box);\n MatcherAssert.assertThat(\n flatter.flat().toString(),\n Matchers.equalTo(\"ν0(𝜋) ↦ ⟦ y ↦ v( x ↦ 𝜋.𝜋.z ) ⟧\")\n );\n }\n @Test", "score": 0.8508760929107666 }, { "filename": "src/test/java/org/objectionary/ObjectsBoxTest.java", "retrieved_chunk": " void boxWithFlatObjectToStringTest() {\n final ObjectsBox box = new ObjectsBox();\n final Map<String, Entity> bindings = new HashMap<>();\n bindings.put(\"y\", new FlatObject(\"bar\", \"ξ\"));\n box.put(ObjectsBoxTest.INIT_OBJECT, bindings);\n MatcherAssert.assertThat(\n box.toString(),\n Matchers.equalTo(\"ν0(𝜋) ↦ ⟦ y ↦ bar(ξ) ⟧\")\n );\n }", "score": 0.8504301309585571 }, { "filename": "src/test/java/org/objectionary/ObjectsBoxTest.java", "retrieved_chunk": " final ObjectsBox box = new ObjectsBox();\n final Map<String, Entity> bindings = new HashMap<>();\n bindings.put(\"x\", new Locator(\"𝜋.𝜋.y\"));\n box.put(ObjectsBoxTest.INIT_OBJECT, bindings);\n MatcherAssert.assertThat(\n box.toString(),\n Matchers.equalTo(\"ν0(𝜋) ↦ ⟦ x ↦ 𝜋.𝜋.y ⟧\")\n );\n }\n @Test", "score": 0.8493692874908447 } ]
java
).getName();
/* * The MIT License (MIT) * * Copyright (c) 2023 Objectionary.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.objectionary; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import org.objectionary.entities.Entity; import org.objectionary.entities.FlatObject; import org.objectionary.entities.Locator; import org.objectionary.entities.NestedObject; /** * This class realizes the flattening of the objects. * @since 0.1.0 */ public final class Flatter { /** * The counter of created objects. */ private static int counter; /** * The objects box. */ private final ObjectsBox box; /** * Constructor. * @param box The objects box. */ public Flatter(final ObjectsBox box) { this.box = box; } /** * Flattens the objects. * @return The flattened objects box. */ public ObjectsBox flat() { Flatter.counter = this.findMaxIndex() + 1; boolean found = true; while (found) { found = false; for ( final Map.Entry<String, Map<String, Entity>> entry : this.box.content().entrySet() ) { for (final Map.Entry<String, Entity> binding : entry.getValue().entrySet()) { if (binding.getValue() instanceof NestedObject) { this.flatOne( binding.getKey(), (NestedObject) binding.getValue(), entry.getValue() ); found = true; break; } } if (found) { break; } } } this.removeUnusedObjects(); this.resuspendLocalBinds(); this.renameObjects(); return this.box; } /** * Flattens one object. * @param key The name of binding to this non-flat object. * @param object The non-flat object itself. * @param user The object which contains the non-flat object. */ private void flatOne( final String key, final NestedObject object, final Map<String, Entity> user ) { final Map<String, Entity> bindings = deepCopy(this.box.get(object.getName())); final Map<String, Entity> application = deepCopy(object.getApplication()); final Map<String, Entity> reframed = deepReframe(application); for (final Map.Entry<String, Entity> entry : reframed.entrySet()) { if (bindings.containsKey(entry.getKey())) { bindings.put(entry.getKey(), entry.getValue()); } } final String name = String.format("ν%d", Flatter.counter); Flatter.counter += 1; this.box.put(name, bindings); user.put(key, new FlatObject(name, "ξ")); } /** * Removes unused objects from the box. */ private void removeUnusedObjects() { final Set<String> uses = new HashSet<>(); final Queue<String> queue = new LinkedList<>(); queue.add("ν0"); while (!queue.isEmpty()) { final String name = queue.poll(); uses.add(name); for (final Map.Entry<String, Entity> binding : this.box.get(name).entrySet()) { if (binding.getValue() instanceof FlatObject) { final String value = ((FlatObject) binding.getValue()).getName(); if (!uses.contains(value)) { queue.add(value); } } } } this.box.content().entrySet().removeIf(entry -> !uses.contains(entry.getKey())); } /** * Takes all locators to local variables and clearly sets them up. */ private void resuspendLocalBinds() { for (final Map<String, Entity> bindings : this.box.content().values()) { boolean found = true; while (found) { found = false; for (final Map.Entry<String, Entity> binding : bindings.entrySet()) { if (binding.getValue() instanceof Locator) { final List<String> locator = ((Locator) binding.getValue()).getPath(); if (!locator.get(0).equals("ξ")) { continue; } final String name = locator.get(1); final Entity entity = bindings.get(name); bindings.remove(name); bindings.put(binding.getKey(), entity); found = true; break; } } } } } /** * Renames the objects to use smaller indexes. */ private void renameObjects() { final List<Integer> list = new ArrayList<>(0); for (final String name : this.box.content().keySet()) { list.add(Integer.parseInt(name.substring(1))); } Collections.sort(list); final int size = this.box.content().size(); for (int idx = 0; idx < size; ++idx) { final String end = String.valueOf(idx); final String start = String.valueOf(list.get(idx)); if (end.equals(start)) { continue; } this.changeName(String.format("ν%s", start), String.format("ν%s", end)); } } /** * Changes the name of the object. * @param start The old name. * @param end The new name. */ private void changeName(final String start, final String end) { for ( final Map.Entry<String, Map<String, Entity>> bindings : this.box.content().entrySet() ) { for (final Map.Entry<String, Entity> binding : bindings.getValue().entrySet()) { if ( binding.getValue() instanceof FlatObject && ((FlatObject) binding.getValue()).getName().equals(start) ) { binding.setValue( new FlatObject(end,
((FlatObject) binding.getValue()).getLocator()) );
} } } this.box.put(end, this.box.get(start)); this.box.content().remove(start); } /** * Finds the maximum index of the objects. * @return The maximum index of the objects. */ private int findMaxIndex() { return this.box.content().keySet().stream() .map(key -> Integer.parseInt(key.substring(1))) .max(Integer::compareTo).orElse(0); } /** * Returns the deep copy of the bindings. * @param bindings The bindings. * @return The deep copy of the bindings. */ private static Map<String, Entity> deepCopy(final Map<String, Entity> bindings) { final Map<String, Entity> result = new HashMap<>(bindings.size()); for (final Map.Entry<String, Entity> entry : bindings.entrySet()) { result.put(entry.getKey(), entry.getValue().copy()); } return result; } /** * Returns the deep reframe of the bindings. * @param bindings The bindings. * @return The deep reframe of the bindings. */ private static Map<String, Entity> deepReframe(final Map<String, Entity> bindings) { final Map<String, Entity> result = new HashMap<>(bindings.size()); for (final Map.Entry<String, Entity> entry : bindings.entrySet()) { result.put(entry.getKey(), entry.getValue().reframe()); } return result; } }
src/main/java/org/objectionary/Flatter.java
objectionary-flatty-688a3da
[ { "filename": "src/test/java/org/objectionary/FlatterTest.java", "retrieved_chunk": " final Map<String, Entity> bindings = new HashMap<>();\n bindings.put(\"x\", new Locator(\"𝜋.𝜋.y\"));\n box.put(FlatterTest.INIT_OBJECT, bindings);\n final Flatter flatter = new Flatter(box);\n MatcherAssert.assertThat(\n flatter.flat().toString(),\n Matchers.equalTo(\"ν0(𝜋) ↦ ⟦ x ↦ 𝜋.𝜋.y ⟧\")\n );\n }\n @Test", "score": 0.8305255174636841 }, { "filename": "src/main/java/org/objectionary/ObjectsBox.java", "retrieved_chunk": " for (final String binding : dataizations) {\n if (bindings.containsKey(binding)) {\n result.add(\n String.format(\"%s ↦ %s\", binding, bindings.get(binding))\n );\n }\n }\n for (final Map.Entry<String, Entity> binding : bindings.entrySet()) {\n if (dataizations.contains(binding.getKey())) {\n continue;", "score": 0.8097875118255615 }, { "filename": "src/test/java/org/objectionary/ObjectsBoxTest.java", "retrieved_chunk": " final ObjectsBox box = new ObjectsBox();\n final Map<String, Entity> bindings = new HashMap<>();\n bindings.put(\"x\", new Locator(\"𝜋.𝜋.y\"));\n box.put(ObjectsBoxTest.INIT_OBJECT, bindings);\n MatcherAssert.assertThat(\n box.toString(),\n Matchers.equalTo(\"ν0(𝜋) ↦ ⟦ x ↦ 𝜋.𝜋.y ⟧\")\n );\n }\n @Test", "score": 0.8074133396148682 }, { "filename": "src/test/java/org/objectionary/FlatterTest.java", "retrieved_chunk": " final Map<String, Entity> bindings = new HashMap<>();\n bindings.put(\"y\", new NestedObject(\"v\", application));\n box.put(FlatterTest.INIT_OBJECT, bindings);\n final Flatter flatter = new Flatter(box);\n MatcherAssert.assertThat(\n flatter.flat().toString(),\n Matchers.equalTo(\"ν0(𝜋) ↦ ⟦ y ↦ v( x ↦ 𝜋.𝜋.z ) ⟧\")\n );\n }\n @Test", "score": 0.8061834573745728 }, { "filename": "src/test/java/org/objectionary/ObjectsBoxTest.java", "retrieved_chunk": " final Map<String, Entity> bindings = new HashMap<>();\n bindings.put(\"Δ\", new Data(Integer.parseInt(\"000A\", 16)));\n box.put(ObjectsBoxTest.INIT_OBJECT, bindings);\n MatcherAssert.assertThat(\n box.toString(),\n Matchers.equalTo(\"ν0(𝜋) ↦ ⟦ Δ ↦ 0x000A ⟧\")\n );\n }\n @Test\n void boxWithLocatorToStringTest() {", "score": 0.8014427423477173 } ]
java
((FlatObject) binding.getValue()).getLocator()) );
/* * The MIT License (MIT) * * Copyright (c) 2023 Objectionary.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.objectionary.parsing; import java.util.HashMap; import java.util.Map; import org.objectionary.Tokenizer; import org.objectionary.entities.Data; import org.objectionary.entities.Empty; import org.objectionary.entities.Entity; import org.objectionary.entities.FlatObject; import org.objectionary.entities.Lambda; import org.objectionary.entities.Locator; import org.objectionary.entities.NestedObject; import org.objectionary.tokens.BracketToken; import org.objectionary.tokens.StringToken; import org.objectionary.tokens.Token; /** * Entities reader. * @since 0.1.0 * @checkstyle NonStaticMethodCheck (100 lines) */ public final class Entities { /** * The tokenizer. */ @SuppressWarnings({"PMD.UnusedPrivateField", "PMD.SingularField"}) private final Tokenizer tokenizer; /** * Constructor. * @param tokenizer The tokenizer. */ public Entities(final Tokenizer tokenizer) { this.tokenizer = tokenizer; } /** * Reads one entity. * @return The parsed entity. */ public Entity one() { final Token token = this.tokenizer.getToken(); if (!(token instanceof StringToken)) { throw new IllegalArgumentException("Expected string token"); } final String value = ((StringToken) token).getValue(); final Entity result; final TypeChecker type = new TypeChecker(value); if (type.isEmpty()) { result = new Empty(); } else if (type.isLocator()) { result = new Locator(value); } else if (type.isData()) { result = new Data(Integer.parseInt(value.substring(2), 16)); } else if (type.isLambda()) { result = new Lambda(value); } else if (type.isObject()) { result = this.createObject(value); } else { throw new IllegalArgumentException("Unknown token"); } return result; } /** * Reads nested entity. * @return The parsed nested entity. */ public Map<String, Entity> nested() { final Map<String, Entity> result = new HashMap<>(); while (true) { final Token token = this.tokenizer.getToken(); if (token instanceof BracketToken) { final BracketToken bracket = (BracketToken) token; if (bracket.getState() == BracketToken.BracketType.CLOSE) { break; } } final String name = ((StringToken) token).getValue();
this.tokenizer.next();
this.tokenizer.next(); final Entity entity = this.one(); result.put(name, entity); this.tokenizer.next(); } return result; } /** * Creates an object. * @param value The value to parse. * @return The parsed entity. */ private Entity createObject(final String value) { final Entity result; if (value.contains(")")) { result = new FlatObject( value.substring(0, value.indexOf('(')), value.substring(value.indexOf('(') + 1, value.indexOf(')')) ); } else if (value.contains("(")) { this.tokenizer.next(); final Map<String, Entity> application = this.nested(); result = new NestedObject( value.substring(0, value.indexOf('(')), application ); } else { result = new FlatObject(value, ""); } return result; } }
src/main/java/org/objectionary/parsing/Entities.java
objectionary-flatty-688a3da
[ { "filename": "src/test/java/org/objectionary/TokenizerTest.java", "retrieved_chunk": " );\n if (expected instanceof BracketToken) {\n MatcherAssert.assertThat(\n ((BracketToken) expected).getState(),\n Matchers.equalTo(((BracketToken) tokenizer.getToken()).getState())\n );\n }\n tokenizer.next();\n }\n }", "score": 0.8624306917190552 }, { "filename": "src/main/java/org/objectionary/Tokenizer.java", "retrieved_chunk": " result = new BracketToken(BracketToken.BracketType.OPEN);\n break;\n case \")\":\n case \"⟧\":\n result = new BracketToken(BracketToken.BracketType.CLOSE);\n break;\n default:\n result = new StringToken(token);\n break;\n }", "score": 0.8616233468055725 }, { "filename": "src/test/java/org/objectionary/TokenizerTest.java", "retrieved_chunk": " new ArrowToken(),\n new StringToken(\"\"),\n new BracketToken(BracketToken.BracketType.CLOSE),\n new BracketToken(BracketToken.BracketType.CLOSE),\n };\n while (tokenizer.hasNext()) {\n final Token expected = expectations[index];\n index += 1;\n MatcherAssert.assertThat(\n tokenizer.getToken(), Matchers.instanceOf(expected.getClass())", "score": 0.8367326855659485 }, { "filename": "src/main/java/org/objectionary/Tokenizer.java", "retrieved_chunk": " */\n public Token getToken() {\n final String token = this.tokens[this.position];\n final Token result;\n switch (token) {\n case \"↦\":\n result = new ArrowToken();\n break;\n case \"(\":\n case \"⟦\":", "score": 0.8363272547721863 }, { "filename": "src/test/java/org/objectionary/TokenizerTest.java", "retrieved_chunk": " final Tokenizer tokenizer = new Tokenizer(input);\n int index = 0;\n final Token[] expectations = {\n new StringToken(\"\"),\n new ArrowToken(),\n new BracketToken(BracketToken.BracketType.OPEN),\n new StringToken(\"\"),\n new ArrowToken(),\n new StringToken(\"\"),\n new StringToken(\"\"),", "score": 0.8306755423545837 } ]
java
this.tokenizer.next();
package committee.nova.flotage.datagen; import committee.nova.flotage.init.BlockRegistry; import committee.nova.flotage.util.BlockMember; import committee.nova.flotage.util.WorkingMode; import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput; import net.fabricmc.fabric.api.datagen.v1.provider.FabricLanguageProvider; public class FloLangProvider { public static class English extends FabricLanguageProvider { public English(FabricDataOutput dataOutput) { super(dataOutput); } @Override public void generateTranslations(TranslationBuilder builder) { builder.add("itemGroup.flotage.tab", "Flotage"); builder.add("modmenu.descriptionTranslation.flotage", "Survive on the sea!"); builder.add("tip.flotage.rack.processtime", "%s second(s) processing"); builder.add("tip.flotage.rack.mode", "Current Condition: "); builder.add("block.flotage.rack", "Rack Processing"); builder.add("config.jade.plugin_flotage.rack_blockentity", "Rack Working Mode"); builder.add("emi.category.flotage.rack", "Rack Processing"); for (WorkingMode mode : WorkingMode.values()) { builder.add("tip.flotage.rack.mode." + mode.toString(), beautifyName(mode.toString())); } for (BlockMember member : BlockMember.values()) { builder.add(BlockRegistry.get(member.raft()), beautifyName(member.raft())); builder
.add(BlockRegistry.get(member.brokenRaft()), beautifyName(member.brokenRaft()));
builder.add(BlockRegistry.get(member.fence()), beautifyName(member.fence())); builder.add(BlockRegistry.get(member.crossedFence()), beautifyName(member.crossedFence())); builder.add(BlockRegistry.get(member.rack()), beautifyName(member.rack())); } } } public static class Chinese extends FabricLanguageProvider { public Chinese(FabricDataOutput dataOutput) { super(dataOutput, "zh_cn"); } @Override public void generateTranslations(TranslationBuilder builder) { builder.add("itemGroup.flotage.tab", "漂浮物"); builder.add("modmenu.descriptionTranslation.flotage", "生存于大海之上!"); builder.add("tip.flotage.rack.processtime", "需要处理 %s 秒。"); builder.add("tip.flotage.rack.mode", "当前处理条件:"); builder.add("block.flotage.rack", "置物架"); builder.add("config.jade.plugin_flotage.rack_blockentity", "置物架模式"); builder.add("emi.category.flotage.rack", "置物架"); builder.add("tip.flotage.rack.mode.unconditional", "无条件"); builder.add("tip.flotage.rack.mode.sun", "白天"); builder.add("tip.flotage.rack.mode.night", "夜晚"); builder.add("tip.flotage.rack.mode.rain", "雨天"); builder.add("tip.flotage.rack.mode.snow", "雪天"); builder.add("tip.flotage.rack.mode.rain_at", "淋雨"); builder.add("tip.flotage.rack.mode.snow_at", "淋雪"); builder.add("tip.flotage.rack.mode.smoke", "烟熏"); for (BlockMember member : BlockMember.values()) { builder.add(BlockRegistry.get(member.raft()), member.chinese + "筏"); builder.add(BlockRegistry.get(member.brokenRaft()), "损坏的" + member.chinese + "筏"); builder.add(BlockRegistry.get(member.fence()), "简易" + member.chinese + "栅栏"); builder.add(BlockRegistry.get(member.crossedFence()), member.chinese + "十字栅栏"); builder.add(BlockRegistry.get(member.rack()), member.chinese + "置物架"); } } } public static String beautifyName(String name) { String[] str1 = name.split("_"); StringBuilder str2 = new StringBuilder(); for(int i = 0 ; i < str1.length; i++) { str1[i] = str1[i].substring(0,1).toUpperCase() + str1[i].substring(1); if(i == str1.length-1) str2.append(str1[i]); else str2.append(str1[i]).append(" "); } return str2.toString(); } }
src/main/java/committee/nova/flotage/datagen/FloLangProvider.java
Nova-Committee-Flotage-Fabric-6478e2a
[ { "filename": "src/main/java/committee/nova/flotage/datagen/FloBlockTagProvider.java", "retrieved_chunk": " FabricTagProvider<Block>.FabricTagBuilder rack = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"rack\")));\n FabricTagProvider<Block>.FabricTagBuilder fence = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"fence\")));\n FabricTagProvider<Block>.FabricTagBuilder crossedFence = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"crossed_fence\")));\n FabricTagProvider<Block>.FabricTagBuilder raft = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"raft\")));\n FabricTagProvider<Block>.FabricTagBuilder brokenRaft = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"broken_raft\")));\n for (BlockMember member : BlockMember.values()){\n rack.add(BlockRegistry.get(member.rack()));\n fence.add(BlockRegistry.get(member.fence()));\n crossedFence.add(BlockRegistry.get(member.crossedFence()));\n raft.add(BlockRegistry.get(member.raft()));", "score": 0.8843300938606262 }, { "filename": "src/main/java/committee/nova/flotage/datagen/FloModelProvider.java", "retrieved_chunk": " Block rack = BlockRegistry.get(member.rack());\n itemGenerator.register(raft.asItem(), itemModel(raft));\n itemGenerator.register(brokenRaft.asItem(), itemModel(brokenRaft));\n itemGenerator.register(rack.asItem(), itemModel(rack));\n }\n private static void member(BlockMember member) {\n Block raft = BlockRegistry.get(member.raft());\n Block brokenRaft = BlockRegistry.get(member.brokenRaft());\n Block rack = BlockRegistry.get(member.rack());\n blockGenerator.registerSingleton(raft, memberTexture(member), model(\"raft\"));", "score": 0.8703460693359375 }, { "filename": "src/main/java/committee/nova/flotage/datagen/FloModelProvider.java", "retrieved_chunk": " blockGenerator.registerSingleton(brokenRaft, memberTexture(member), model(\"broken_raft\"));\n blockGenerator.registerSingleton(rack, memberTexture(member), model(\"rack\"));\n }\n @Override\n public void generateBlockStateModels(BlockStateModelGenerator generator) {\n blockGenerator = generator;\n for (BlockMember member : BlockMember.values()) {\n member(member);\n }\n }", "score": 0.8594422936439514 }, { "filename": "src/main/java/committee/nova/flotage/init/TileRegistry.java", "retrieved_chunk": "package committee.nova.flotage.init;\nimport committee.nova.flotage.Flotage;\nimport committee.nova.flotage.impl.tile.RackBlockEntity;\nimport net.fabricmc.fabric.api.object.builder.v1.block.entity.FabricBlockEntityTypeBuilder;\nimport net.minecraft.block.entity.BlockEntityType;\nimport net.minecraft.registry.Registries;\nimport net.minecraft.registry.Registry;\npublic class TileRegistry {\n public static final BlockEntityType<RackBlockEntity> RACK_BLOCK_ENTITY =\n FabricBlockEntityTypeBuilder.create(RackBlockEntity::new, BlockRegistry.getRacks()).build();", "score": 0.8575403690338135 }, { "filename": "src/main/java/committee/nova/flotage/datagen/FloBlockTagProvider.java", "retrieved_chunk": " brokenRaft.add(BlockRegistry.get(member.brokenRaft()));\n }\n for (BlockMember member : BlockMember.values()) {\n axe.add(BlockRegistry.get(member.crossedFence()));\n axe.add(BlockRegistry.get(member.fence()));\n axe.add(BlockRegistry.get(member.raft()));\n axe.add(BlockRegistry.get(member.brokenRaft()));\n axe.add(BlockRegistry.get(member.rack()));\n }\n }", "score": 0.8556635975837708 } ]
java
.add(BlockRegistry.get(member.brokenRaft()), beautifyName(member.brokenRaft()));
package committee.nova.flotage.datagen; import committee.nova.flotage.init.BlockRegistry; import committee.nova.flotage.util.BlockMember; import committee.nova.flotage.util.WorkingMode; import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput; import net.fabricmc.fabric.api.datagen.v1.provider.FabricLanguageProvider; public class FloLangProvider { public static class English extends FabricLanguageProvider { public English(FabricDataOutput dataOutput) { super(dataOutput); } @Override public void generateTranslations(TranslationBuilder builder) { builder.add("itemGroup.flotage.tab", "Flotage"); builder.add("modmenu.descriptionTranslation.flotage", "Survive on the sea!"); builder.add("tip.flotage.rack.processtime", "%s second(s) processing"); builder.add("tip.flotage.rack.mode", "Current Condition: "); builder.add("block.flotage.rack", "Rack Processing"); builder.add("config.jade.plugin_flotage.rack_blockentity", "Rack Working Mode"); builder.add("emi.category.flotage.rack", "Rack Processing"); for (WorkingMode mode : WorkingMode.values()) { builder.add("tip.flotage.rack.mode." + mode.toString(), beautifyName(mode.toString())); } for (BlockMember member : BlockMember.values()) { builder.add(BlockRegistry.get(member.raft()), beautifyName(member.raft())); builder.add(BlockRegistry.get(member.brokenRaft()), beautifyName(member.brokenRaft())); builder.add(BlockRegistry.get(member.fence()), beautifyName(member.fence())); builder.add(BlockRegistry.get(member.crossedFence()), beautifyName(member.crossedFence())); builder.add(BlockRegistry.get(member.rack()), beautifyName(member.rack())); } } } public static class Chinese extends FabricLanguageProvider { public Chinese(FabricDataOutput dataOutput) { super(dataOutput, "zh_cn"); } @Override public void generateTranslations(TranslationBuilder builder) { builder.add("itemGroup.flotage.tab", "漂浮物"); builder.add("modmenu.descriptionTranslation.flotage", "生存于大海之上!"); builder.add("tip.flotage.rack.processtime", "需要处理 %s 秒。"); builder.add("tip.flotage.rack.mode", "当前处理条件:"); builder.add("block.flotage.rack", "置物架"); builder.add("config.jade.plugin_flotage.rack_blockentity", "置物架模式"); builder.add("emi.category.flotage.rack", "置物架"); builder.add("tip.flotage.rack.mode.unconditional", "无条件"); builder.add("tip.flotage.rack.mode.sun", "白天"); builder.add("tip.flotage.rack.mode.night", "夜晚"); builder.add("tip.flotage.rack.mode.rain", "雨天"); builder.add("tip.flotage.rack.mode.snow", "雪天"); builder.add("tip.flotage.rack.mode.rain_at", "淋雨"); builder.add("tip.flotage.rack.mode.snow_at", "淋雪"); builder.add("tip.flotage.rack.mode.smoke", "烟熏"); for (BlockMember member : BlockMember.values()) { builder
.add(BlockRegistry.get(member.raft()), member.chinese + "筏");
builder.add(BlockRegistry.get(member.brokenRaft()), "损坏的" + member.chinese + "筏"); builder.add(BlockRegistry.get(member.fence()), "简易" + member.chinese + "栅栏"); builder.add(BlockRegistry.get(member.crossedFence()), member.chinese + "十字栅栏"); builder.add(BlockRegistry.get(member.rack()), member.chinese + "置物架"); } } } public static String beautifyName(String name) { String[] str1 = name.split("_"); StringBuilder str2 = new StringBuilder(); for(int i = 0 ; i < str1.length; i++) { str1[i] = str1[i].substring(0,1).toUpperCase() + str1[i].substring(1); if(i == str1.length-1) str2.append(str1[i]); else str2.append(str1[i]).append(" "); } return str2.toString(); } }
src/main/java/committee/nova/flotage/datagen/FloLangProvider.java
Nova-Committee-Flotage-Fabric-6478e2a
[ { "filename": "src/main/java/committee/nova/flotage/datagen/FloBlockTagProvider.java", "retrieved_chunk": " FabricTagProvider<Block>.FabricTagBuilder rack = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"rack\")));\n FabricTagProvider<Block>.FabricTagBuilder fence = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"fence\")));\n FabricTagProvider<Block>.FabricTagBuilder crossedFence = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"crossed_fence\")));\n FabricTagProvider<Block>.FabricTagBuilder raft = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"raft\")));\n FabricTagProvider<Block>.FabricTagBuilder brokenRaft = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"broken_raft\")));\n for (BlockMember member : BlockMember.values()){\n rack.add(BlockRegistry.get(member.rack()));\n fence.add(BlockRegistry.get(member.fence()));\n crossedFence.add(BlockRegistry.get(member.crossedFence()));\n raft.add(BlockRegistry.get(member.raft()));", "score": 0.8572400808334351 }, { "filename": "src/main/java/committee/nova/flotage/datagen/FloModelProvider.java", "retrieved_chunk": " Block rack = BlockRegistry.get(member.rack());\n itemGenerator.register(raft.asItem(), itemModel(raft));\n itemGenerator.register(brokenRaft.asItem(), itemModel(brokenRaft));\n itemGenerator.register(rack.asItem(), itemModel(rack));\n }\n private static void member(BlockMember member) {\n Block raft = BlockRegistry.get(member.raft());\n Block brokenRaft = BlockRegistry.get(member.brokenRaft());\n Block rack = BlockRegistry.get(member.rack());\n blockGenerator.registerSingleton(raft, memberTexture(member), model(\"raft\"));", "score": 0.8488343954086304 }, { "filename": "src/main/java/committee/nova/flotage/init/ItemRegistry.java", "retrieved_chunk": " public static void register() {\n for (BlockMember member : BlockMember.values()) {\n raftItem(member.raft(), settings());\n raftItem(member.brokenRaft(), settings());\n blockItem(member.fence(), settings());\n blockItem(member.crossedFence(), settings());\n blockItem(member.rack(), settings());\n }\n }\n private static void blockItem(String id, Item.Settings settings) {", "score": 0.8447356224060059 }, { "filename": "src/main/java/committee/nova/flotage/datagen/FloBlockLootProvider.java", "retrieved_chunk": " }\n @Override\n public void generate() {\n for (BlockMember member : BlockMember.values()) {\n addDrop(BlockRegistry.get(member.raft()));\n addDrop(BlockRegistry.get(member.brokenRaft()), member.repairBlock.asItem());\n addDrop(BlockRegistry.get(member.fence()));\n addDrop(BlockRegistry.get(member.crossedFence()), drops(ItemRegistry.get(member.fence()), ConstantLootNumberProvider.create(2f)));\n addDrop(BlockRegistry.get(member.rack()));\n }", "score": 0.8394100069999695 }, { "filename": "src/main/java/committee/nova/flotage/init/BlockRegistry.java", "retrieved_chunk": "public class BlockRegistry {\n public static void register() {\n for (BlockMember member : BlockMember.values()) {\n woodenRaft(member);\n brokenRaft(member);\n fence(member);\n crossedFence(member);\n rack(member);\n }\n }", "score": 0.8381909132003784 } ]
java
.add(BlockRegistry.get(member.raft()), member.chinese + "筏");
package committee.nova.flotage.datagen; import committee.nova.flotage.init.BlockRegistry; import committee.nova.flotage.util.BlockMember; import committee.nova.flotage.util.WorkingMode; import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput; import net.fabricmc.fabric.api.datagen.v1.provider.FabricLanguageProvider; public class FloLangProvider { public static class English extends FabricLanguageProvider { public English(FabricDataOutput dataOutput) { super(dataOutput); } @Override public void generateTranslations(TranslationBuilder builder) { builder.add("itemGroup.flotage.tab", "Flotage"); builder.add("modmenu.descriptionTranslation.flotage", "Survive on the sea!"); builder.add("tip.flotage.rack.processtime", "%s second(s) processing"); builder.add("tip.flotage.rack.mode", "Current Condition: "); builder.add("block.flotage.rack", "Rack Processing"); builder.add("config.jade.plugin_flotage.rack_blockentity", "Rack Working Mode"); builder.add("emi.category.flotage.rack", "Rack Processing"); for (WorkingMode mode : WorkingMode.values()) { builder.add("tip.flotage.rack.mode." + mode.toString(), beautifyName(mode.toString())); } for (BlockMember member : BlockMember.values()) { builder.add(BlockRegistry.get(member.raft()), beautifyName(member.raft())); builder.add(BlockRegistry.get(member.brokenRaft()), beautifyName(member.brokenRaft())); builder
.add(BlockRegistry.get(member.fence()), beautifyName(member.fence()));
builder.add(BlockRegistry.get(member.crossedFence()), beautifyName(member.crossedFence())); builder.add(BlockRegistry.get(member.rack()), beautifyName(member.rack())); } } } public static class Chinese extends FabricLanguageProvider { public Chinese(FabricDataOutput dataOutput) { super(dataOutput, "zh_cn"); } @Override public void generateTranslations(TranslationBuilder builder) { builder.add("itemGroup.flotage.tab", "漂浮物"); builder.add("modmenu.descriptionTranslation.flotage", "生存于大海之上!"); builder.add("tip.flotage.rack.processtime", "需要处理 %s 秒。"); builder.add("tip.flotage.rack.mode", "当前处理条件:"); builder.add("block.flotage.rack", "置物架"); builder.add("config.jade.plugin_flotage.rack_blockentity", "置物架模式"); builder.add("emi.category.flotage.rack", "置物架"); builder.add("tip.flotage.rack.mode.unconditional", "无条件"); builder.add("tip.flotage.rack.mode.sun", "白天"); builder.add("tip.flotage.rack.mode.night", "夜晚"); builder.add("tip.flotage.rack.mode.rain", "雨天"); builder.add("tip.flotage.rack.mode.snow", "雪天"); builder.add("tip.flotage.rack.mode.rain_at", "淋雨"); builder.add("tip.flotage.rack.mode.snow_at", "淋雪"); builder.add("tip.flotage.rack.mode.smoke", "烟熏"); for (BlockMember member : BlockMember.values()) { builder.add(BlockRegistry.get(member.raft()), member.chinese + "筏"); builder.add(BlockRegistry.get(member.brokenRaft()), "损坏的" + member.chinese + "筏"); builder.add(BlockRegistry.get(member.fence()), "简易" + member.chinese + "栅栏"); builder.add(BlockRegistry.get(member.crossedFence()), member.chinese + "十字栅栏"); builder.add(BlockRegistry.get(member.rack()), member.chinese + "置物架"); } } } public static String beautifyName(String name) { String[] str1 = name.split("_"); StringBuilder str2 = new StringBuilder(); for(int i = 0 ; i < str1.length; i++) { str1[i] = str1[i].substring(0,1).toUpperCase() + str1[i].substring(1); if(i == str1.length-1) str2.append(str1[i]); else str2.append(str1[i]).append(" "); } return str2.toString(); } }
src/main/java/committee/nova/flotage/datagen/FloLangProvider.java
Nova-Committee-Flotage-Fabric-6478e2a
[ { "filename": "src/main/java/committee/nova/flotage/datagen/FloBlockTagProvider.java", "retrieved_chunk": " FabricTagProvider<Block>.FabricTagBuilder rack = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"rack\")));\n FabricTagProvider<Block>.FabricTagBuilder fence = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"fence\")));\n FabricTagProvider<Block>.FabricTagBuilder crossedFence = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"crossed_fence\")));\n FabricTagProvider<Block>.FabricTagBuilder raft = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"raft\")));\n FabricTagProvider<Block>.FabricTagBuilder brokenRaft = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"broken_raft\")));\n for (BlockMember member : BlockMember.values()){\n rack.add(BlockRegistry.get(member.rack()));\n fence.add(BlockRegistry.get(member.fence()));\n crossedFence.add(BlockRegistry.get(member.crossedFence()));\n raft.add(BlockRegistry.get(member.raft()));", "score": 0.8776246905326843 }, { "filename": "src/main/java/committee/nova/flotage/datagen/FloModelProvider.java", "retrieved_chunk": " Block rack = BlockRegistry.get(member.rack());\n itemGenerator.register(raft.asItem(), itemModel(raft));\n itemGenerator.register(brokenRaft.asItem(), itemModel(brokenRaft));\n itemGenerator.register(rack.asItem(), itemModel(rack));\n }\n private static void member(BlockMember member) {\n Block raft = BlockRegistry.get(member.raft());\n Block brokenRaft = BlockRegistry.get(member.brokenRaft());\n Block rack = BlockRegistry.get(member.rack());\n blockGenerator.registerSingleton(raft, memberTexture(member), model(\"raft\"));", "score": 0.8610047101974487 }, { "filename": "src/main/java/committee/nova/flotage/compat/jade/FlotageJadePlugin.java", "retrieved_chunk": "package committee.nova.flotage.compat.jade;\nimport committee.nova.flotage.compat.jade.provider.RackBlockTipProvider;\nimport committee.nova.flotage.impl.block.RackBlock;\nimport committee.nova.flotage.impl.tile.RackBlockEntity;\nimport snownee.jade.api.IWailaClientRegistration;\nimport snownee.jade.api.IWailaCommonRegistration;\nimport snownee.jade.api.IWailaPlugin;\nimport snownee.jade.api.WailaPlugin;\n@WailaPlugin\npublic class FlotageJadePlugin implements IWailaPlugin {", "score": 0.8600077629089355 }, { "filename": "src/main/java/committee/nova/flotage/init/TileRegistry.java", "retrieved_chunk": "package committee.nova.flotage.init;\nimport committee.nova.flotage.Flotage;\nimport committee.nova.flotage.impl.tile.RackBlockEntity;\nimport net.fabricmc.fabric.api.object.builder.v1.block.entity.FabricBlockEntityTypeBuilder;\nimport net.minecraft.block.entity.BlockEntityType;\nimport net.minecraft.registry.Registries;\nimport net.minecraft.registry.Registry;\npublic class TileRegistry {\n public static final BlockEntityType<RackBlockEntity> RACK_BLOCK_ENTITY =\n FabricBlockEntityTypeBuilder.create(RackBlockEntity::new, BlockRegistry.getRacks()).build();", "score": 0.8536144495010376 }, { "filename": "src/main/java/committee/nova/flotage/datagen/FloModelProvider.java", "retrieved_chunk": " blockGenerator.registerSingleton(brokenRaft, memberTexture(member), model(\"broken_raft\"));\n blockGenerator.registerSingleton(rack, memberTexture(member), model(\"rack\"));\n }\n @Override\n public void generateBlockStateModels(BlockStateModelGenerator generator) {\n blockGenerator = generator;\n for (BlockMember member : BlockMember.values()) {\n member(member);\n }\n }", "score": 0.8526541590690613 } ]
java
.add(BlockRegistry.get(member.fence()), beautifyName(member.fence()));
package committee.nova.flotage.datagen; import committee.nova.flotage.init.BlockRegistry; import committee.nova.flotage.util.BlockMember; import committee.nova.flotage.util.WorkingMode; import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput; import net.fabricmc.fabric.api.datagen.v1.provider.FabricLanguageProvider; public class FloLangProvider { public static class English extends FabricLanguageProvider { public English(FabricDataOutput dataOutput) { super(dataOutput); } @Override public void generateTranslations(TranslationBuilder builder) { builder.add("itemGroup.flotage.tab", "Flotage"); builder.add("modmenu.descriptionTranslation.flotage", "Survive on the sea!"); builder.add("tip.flotage.rack.processtime", "%s second(s) processing"); builder.add("tip.flotage.rack.mode", "Current Condition: "); builder.add("block.flotage.rack", "Rack Processing"); builder.add("config.jade.plugin_flotage.rack_blockentity", "Rack Working Mode"); builder.add("emi.category.flotage.rack", "Rack Processing"); for (WorkingMode mode : WorkingMode.values()) { builder.add("tip.flotage.rack.mode." + mode.toString(), beautifyName(mode.toString())); } for (BlockMember member : BlockMember.values()) { builder.add(BlockRegistry.get(member.raft()), beautifyName(member.raft())); builder.add(BlockRegistry.get(member.brokenRaft()), beautifyName(member.brokenRaft())); builder.add(BlockRegistry.get(member.fence()), beautifyName(member.fence())); builder.add(BlockRegistry.get(member.crossedFence()), beautifyName(member.crossedFence())); builder.add
(BlockRegistry.get(member.rack()), beautifyName(member.rack()));
} } } public static class Chinese extends FabricLanguageProvider { public Chinese(FabricDataOutput dataOutput) { super(dataOutput, "zh_cn"); } @Override public void generateTranslations(TranslationBuilder builder) { builder.add("itemGroup.flotage.tab", "漂浮物"); builder.add("modmenu.descriptionTranslation.flotage", "生存于大海之上!"); builder.add("tip.flotage.rack.processtime", "需要处理 %s 秒。"); builder.add("tip.flotage.rack.mode", "当前处理条件:"); builder.add("block.flotage.rack", "置物架"); builder.add("config.jade.plugin_flotage.rack_blockentity", "置物架模式"); builder.add("emi.category.flotage.rack", "置物架"); builder.add("tip.flotage.rack.mode.unconditional", "无条件"); builder.add("tip.flotage.rack.mode.sun", "白天"); builder.add("tip.flotage.rack.mode.night", "夜晚"); builder.add("tip.flotage.rack.mode.rain", "雨天"); builder.add("tip.flotage.rack.mode.snow", "雪天"); builder.add("tip.flotage.rack.mode.rain_at", "淋雨"); builder.add("tip.flotage.rack.mode.snow_at", "淋雪"); builder.add("tip.flotage.rack.mode.smoke", "烟熏"); for (BlockMember member : BlockMember.values()) { builder.add(BlockRegistry.get(member.raft()), member.chinese + "筏"); builder.add(BlockRegistry.get(member.brokenRaft()), "损坏的" + member.chinese + "筏"); builder.add(BlockRegistry.get(member.fence()), "简易" + member.chinese + "栅栏"); builder.add(BlockRegistry.get(member.crossedFence()), member.chinese + "十字栅栏"); builder.add(BlockRegistry.get(member.rack()), member.chinese + "置物架"); } } } public static String beautifyName(String name) { String[] str1 = name.split("_"); StringBuilder str2 = new StringBuilder(); for(int i = 0 ; i < str1.length; i++) { str1[i] = str1[i].substring(0,1).toUpperCase() + str1[i].substring(1); if(i == str1.length-1) str2.append(str1[i]); else str2.append(str1[i]).append(" "); } return str2.toString(); } }
src/main/java/committee/nova/flotage/datagen/FloLangProvider.java
Nova-Committee-Flotage-Fabric-6478e2a
[ { "filename": "src/main/java/committee/nova/flotage/datagen/FloBlockTagProvider.java", "retrieved_chunk": " brokenRaft.add(BlockRegistry.get(member.brokenRaft()));\n }\n for (BlockMember member : BlockMember.values()) {\n axe.add(BlockRegistry.get(member.crossedFence()));\n axe.add(BlockRegistry.get(member.fence()));\n axe.add(BlockRegistry.get(member.raft()));\n axe.add(BlockRegistry.get(member.brokenRaft()));\n axe.add(BlockRegistry.get(member.rack()));\n }\n }", "score": 0.8833319544792175 }, { "filename": "src/main/java/committee/nova/flotage/datagen/FloBlockTagProvider.java", "retrieved_chunk": " FabricTagProvider<Block>.FabricTagBuilder rack = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"rack\")));\n FabricTagProvider<Block>.FabricTagBuilder fence = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"fence\")));\n FabricTagProvider<Block>.FabricTagBuilder crossedFence = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"crossed_fence\")));\n FabricTagProvider<Block>.FabricTagBuilder raft = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"raft\")));\n FabricTagProvider<Block>.FabricTagBuilder brokenRaft = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"broken_raft\")));\n for (BlockMember member : BlockMember.values()){\n rack.add(BlockRegistry.get(member.rack()));\n fence.add(BlockRegistry.get(member.fence()));\n crossedFence.add(BlockRegistry.get(member.crossedFence()));\n raft.add(BlockRegistry.get(member.raft()));", "score": 0.8825158476829529 }, { "filename": "src/main/java/committee/nova/flotage/datagen/FloModelProvider.java", "retrieved_chunk": " Block rack = BlockRegistry.get(member.rack());\n itemGenerator.register(raft.asItem(), itemModel(raft));\n itemGenerator.register(brokenRaft.asItem(), itemModel(brokenRaft));\n itemGenerator.register(rack.asItem(), itemModel(rack));\n }\n private static void member(BlockMember member) {\n Block raft = BlockRegistry.get(member.raft());\n Block brokenRaft = BlockRegistry.get(member.brokenRaft());\n Block rack = BlockRegistry.get(member.rack());\n blockGenerator.registerSingleton(raft, memberTexture(member), model(\"raft\"));", "score": 0.8743960857391357 }, { "filename": "src/main/java/committee/nova/flotage/datagen/FloBlockLootProvider.java", "retrieved_chunk": " }\n @Override\n public void generate() {\n for (BlockMember member : BlockMember.values()) {\n addDrop(BlockRegistry.get(member.raft()));\n addDrop(BlockRegistry.get(member.brokenRaft()), member.repairBlock.asItem());\n addDrop(BlockRegistry.get(member.fence()));\n addDrop(BlockRegistry.get(member.crossedFence()), drops(ItemRegistry.get(member.fence()), ConstantLootNumberProvider.create(2f)));\n addDrop(BlockRegistry.get(member.rack()));\n }", "score": 0.8668290972709656 }, { "filename": "src/main/java/committee/nova/flotage/init/BlockRegistry.java", "retrieved_chunk": "public class BlockRegistry {\n public static void register() {\n for (BlockMember member : BlockMember.values()) {\n woodenRaft(member);\n brokenRaft(member);\n fence(member);\n crossedFence(member);\n rack(member);\n }\n }", "score": 0.8667463660240173 } ]
java
(BlockRegistry.get(member.rack()), beautifyName(member.rack()));
package committee.nova.flotage.datagen; import committee.nova.flotage.init.BlockRegistry; import committee.nova.flotage.util.BlockMember; import committee.nova.flotage.util.WorkingMode; import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput; import net.fabricmc.fabric.api.datagen.v1.provider.FabricLanguageProvider; public class FloLangProvider { public static class English extends FabricLanguageProvider { public English(FabricDataOutput dataOutput) { super(dataOutput); } @Override public void generateTranslations(TranslationBuilder builder) { builder.add("itemGroup.flotage.tab", "Flotage"); builder.add("modmenu.descriptionTranslation.flotage", "Survive on the sea!"); builder.add("tip.flotage.rack.processtime", "%s second(s) processing"); builder.add("tip.flotage.rack.mode", "Current Condition: "); builder.add("block.flotage.rack", "Rack Processing"); builder.add("config.jade.plugin_flotage.rack_blockentity", "Rack Working Mode"); builder.add("emi.category.flotage.rack", "Rack Processing"); for (WorkingMode mode : WorkingMode.values()) { builder.add("tip.flotage.rack.mode." + mode.toString(), beautifyName(mode.toString())); } for (BlockMember member : BlockMember.values()) { builder.add(BlockRegistry.get(member.raft()),
beautifyName(member.raft()));
builder.add(BlockRegistry.get(member.brokenRaft()), beautifyName(member.brokenRaft())); builder.add(BlockRegistry.get(member.fence()), beautifyName(member.fence())); builder.add(BlockRegistry.get(member.crossedFence()), beautifyName(member.crossedFence())); builder.add(BlockRegistry.get(member.rack()), beautifyName(member.rack())); } } } public static class Chinese extends FabricLanguageProvider { public Chinese(FabricDataOutput dataOutput) { super(dataOutput, "zh_cn"); } @Override public void generateTranslations(TranslationBuilder builder) { builder.add("itemGroup.flotage.tab", "漂浮物"); builder.add("modmenu.descriptionTranslation.flotage", "生存于大海之上!"); builder.add("tip.flotage.rack.processtime", "需要处理 %s 秒。"); builder.add("tip.flotage.rack.mode", "当前处理条件:"); builder.add("block.flotage.rack", "置物架"); builder.add("config.jade.plugin_flotage.rack_blockentity", "置物架模式"); builder.add("emi.category.flotage.rack", "置物架"); builder.add("tip.flotage.rack.mode.unconditional", "无条件"); builder.add("tip.flotage.rack.mode.sun", "白天"); builder.add("tip.flotage.rack.mode.night", "夜晚"); builder.add("tip.flotage.rack.mode.rain", "雨天"); builder.add("tip.flotage.rack.mode.snow", "雪天"); builder.add("tip.flotage.rack.mode.rain_at", "淋雨"); builder.add("tip.flotage.rack.mode.snow_at", "淋雪"); builder.add("tip.flotage.rack.mode.smoke", "烟熏"); for (BlockMember member : BlockMember.values()) { builder.add(BlockRegistry.get(member.raft()), member.chinese + "筏"); builder.add(BlockRegistry.get(member.brokenRaft()), "损坏的" + member.chinese + "筏"); builder.add(BlockRegistry.get(member.fence()), "简易" + member.chinese + "栅栏"); builder.add(BlockRegistry.get(member.crossedFence()), member.chinese + "十字栅栏"); builder.add(BlockRegistry.get(member.rack()), member.chinese + "置物架"); } } } public static String beautifyName(String name) { String[] str1 = name.split("_"); StringBuilder str2 = new StringBuilder(); for(int i = 0 ; i < str1.length; i++) { str1[i] = str1[i].substring(0,1).toUpperCase() + str1[i].substring(1); if(i == str1.length-1) str2.append(str1[i]); else str2.append(str1[i]).append(" "); } return str2.toString(); } }
src/main/java/committee/nova/flotage/datagen/FloLangProvider.java
Nova-Committee-Flotage-Fabric-6478e2a
[ { "filename": "src/main/java/committee/nova/flotage/datagen/FloBlockTagProvider.java", "retrieved_chunk": " FabricTagProvider<Block>.FabricTagBuilder rack = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"rack\")));\n FabricTagProvider<Block>.FabricTagBuilder fence = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"fence\")));\n FabricTagProvider<Block>.FabricTagBuilder crossedFence = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"crossed_fence\")));\n FabricTagProvider<Block>.FabricTagBuilder raft = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"raft\")));\n FabricTagProvider<Block>.FabricTagBuilder brokenRaft = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"broken_raft\")));\n for (BlockMember member : BlockMember.values()){\n rack.add(BlockRegistry.get(member.rack()));\n fence.add(BlockRegistry.get(member.fence()));\n crossedFence.add(BlockRegistry.get(member.crossedFence()));\n raft.add(BlockRegistry.get(member.raft()));", "score": 0.8765081167221069 }, { "filename": "src/main/java/committee/nova/flotage/datagen/FloModelProvider.java", "retrieved_chunk": " Block rack = BlockRegistry.get(member.rack());\n itemGenerator.register(raft.asItem(), itemModel(raft));\n itemGenerator.register(brokenRaft.asItem(), itemModel(brokenRaft));\n itemGenerator.register(rack.asItem(), itemModel(rack));\n }\n private static void member(BlockMember member) {\n Block raft = BlockRegistry.get(member.raft());\n Block brokenRaft = BlockRegistry.get(member.brokenRaft());\n Block rack = BlockRegistry.get(member.rack());\n blockGenerator.registerSingleton(raft, memberTexture(member), model(\"raft\"));", "score": 0.8567283749580383 }, { "filename": "src/main/java/committee/nova/flotage/compat/jade/provider/RackBlockTipProvider.java", "retrieved_chunk": " tooltip.add(text);\n }\n }\n @Override\n public Identifier getUid() {\n return Flotage.id(\"rack_blockentity\");\n }\n @Override\n public void appendServerData(NbtCompound nbt, BlockAccessor blockAccessor) {\n nbt.putString(\"WorkingMode\", WorkingMode.judge(blockAccessor.getLevel(), blockAccessor.getPosition()).toString());", "score": 0.8502514362335205 }, { "filename": "src/main/java/committee/nova/flotage/init/TileRegistry.java", "retrieved_chunk": "package committee.nova.flotage.init;\nimport committee.nova.flotage.Flotage;\nimport committee.nova.flotage.impl.tile.RackBlockEntity;\nimport net.fabricmc.fabric.api.object.builder.v1.block.entity.FabricBlockEntityTypeBuilder;\nimport net.minecraft.block.entity.BlockEntityType;\nimport net.minecraft.registry.Registries;\nimport net.minecraft.registry.Registry;\npublic class TileRegistry {\n public static final BlockEntityType<RackBlockEntity> RACK_BLOCK_ENTITY =\n FabricBlockEntityTypeBuilder.create(RackBlockEntity::new, BlockRegistry.getRacks()).build();", "score": 0.8479973077774048 }, { "filename": "src/main/java/committee/nova/flotage/datagen/FloModelProvider.java", "retrieved_chunk": " blockGenerator.registerSingleton(brokenRaft, memberTexture(member), model(\"broken_raft\"));\n blockGenerator.registerSingleton(rack, memberTexture(member), model(\"rack\"));\n }\n @Override\n public void generateBlockStateModels(BlockStateModelGenerator generator) {\n blockGenerator = generator;\n for (BlockMember member : BlockMember.values()) {\n member(member);\n }\n }", "score": 0.8464629054069519 } ]
java
beautifyName(member.raft()));
package committee.nova.flotage.datagen; import committee.nova.flotage.init.BlockRegistry; import committee.nova.flotage.util.BlockMember; import committee.nova.flotage.util.WorkingMode; import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput; import net.fabricmc.fabric.api.datagen.v1.provider.FabricLanguageProvider; public class FloLangProvider { public static class English extends FabricLanguageProvider { public English(FabricDataOutput dataOutput) { super(dataOutput); } @Override public void generateTranslations(TranslationBuilder builder) { builder.add("itemGroup.flotage.tab", "Flotage"); builder.add("modmenu.descriptionTranslation.flotage", "Survive on the sea!"); builder.add("tip.flotage.rack.processtime", "%s second(s) processing"); builder.add("tip.flotage.rack.mode", "Current Condition: "); builder.add("block.flotage.rack", "Rack Processing"); builder.add("config.jade.plugin_flotage.rack_blockentity", "Rack Working Mode"); builder.add("emi.category.flotage.rack", "Rack Processing"); for (WorkingMode mode : WorkingMode.values()) { builder.add("tip.flotage.rack.mode." + mode.toString(), beautifyName(mode.toString())); } for (BlockMember member : BlockMember.values()) { builder.add(BlockRegistry.get(member.raft()), beautifyName(member.raft())); builder.add(BlockRegistry.get(member.brokenRaft()), beautifyName(member.brokenRaft())); builder.add(BlockRegistry.get(member.
fence()), beautifyName(member.fence()));
builder.add(BlockRegistry.get(member.crossedFence()), beautifyName(member.crossedFence())); builder.add(BlockRegistry.get(member.rack()), beautifyName(member.rack())); } } } public static class Chinese extends FabricLanguageProvider { public Chinese(FabricDataOutput dataOutput) { super(dataOutput, "zh_cn"); } @Override public void generateTranslations(TranslationBuilder builder) { builder.add("itemGroup.flotage.tab", "漂浮物"); builder.add("modmenu.descriptionTranslation.flotage", "生存于大海之上!"); builder.add("tip.flotage.rack.processtime", "需要处理 %s 秒。"); builder.add("tip.flotage.rack.mode", "当前处理条件:"); builder.add("block.flotage.rack", "置物架"); builder.add("config.jade.plugin_flotage.rack_blockentity", "置物架模式"); builder.add("emi.category.flotage.rack", "置物架"); builder.add("tip.flotage.rack.mode.unconditional", "无条件"); builder.add("tip.flotage.rack.mode.sun", "白天"); builder.add("tip.flotage.rack.mode.night", "夜晚"); builder.add("tip.flotage.rack.mode.rain", "雨天"); builder.add("tip.flotage.rack.mode.snow", "雪天"); builder.add("tip.flotage.rack.mode.rain_at", "淋雨"); builder.add("tip.flotage.rack.mode.snow_at", "淋雪"); builder.add("tip.flotage.rack.mode.smoke", "烟熏"); for (BlockMember member : BlockMember.values()) { builder.add(BlockRegistry.get(member.raft()), member.chinese + "筏"); builder.add(BlockRegistry.get(member.brokenRaft()), "损坏的" + member.chinese + "筏"); builder.add(BlockRegistry.get(member.fence()), "简易" + member.chinese + "栅栏"); builder.add(BlockRegistry.get(member.crossedFence()), member.chinese + "十字栅栏"); builder.add(BlockRegistry.get(member.rack()), member.chinese + "置物架"); } } } public static String beautifyName(String name) { String[] str1 = name.split("_"); StringBuilder str2 = new StringBuilder(); for(int i = 0 ; i < str1.length; i++) { str1[i] = str1[i].substring(0,1).toUpperCase() + str1[i].substring(1); if(i == str1.length-1) str2.append(str1[i]); else str2.append(str1[i]).append(" "); } return str2.toString(); } }
src/main/java/committee/nova/flotage/datagen/FloLangProvider.java
Nova-Committee-Flotage-Fabric-6478e2a
[ { "filename": "src/main/java/committee/nova/flotage/datagen/FloBlockTagProvider.java", "retrieved_chunk": " FabricTagProvider<Block>.FabricTagBuilder rack = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"rack\")));\n FabricTagProvider<Block>.FabricTagBuilder fence = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"fence\")));\n FabricTagProvider<Block>.FabricTagBuilder crossedFence = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"crossed_fence\")));\n FabricTagProvider<Block>.FabricTagBuilder raft = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"raft\")));\n FabricTagProvider<Block>.FabricTagBuilder brokenRaft = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"broken_raft\")));\n for (BlockMember member : BlockMember.values()){\n rack.add(BlockRegistry.get(member.rack()));\n fence.add(BlockRegistry.get(member.fence()));\n crossedFence.add(BlockRegistry.get(member.crossedFence()));\n raft.add(BlockRegistry.get(member.raft()));", "score": 0.8789729475975037 }, { "filename": "src/main/java/committee/nova/flotage/datagen/FloModelProvider.java", "retrieved_chunk": " Block rack = BlockRegistry.get(member.rack());\n itemGenerator.register(raft.asItem(), itemModel(raft));\n itemGenerator.register(brokenRaft.asItem(), itemModel(brokenRaft));\n itemGenerator.register(rack.asItem(), itemModel(rack));\n }\n private static void member(BlockMember member) {\n Block raft = BlockRegistry.get(member.raft());\n Block brokenRaft = BlockRegistry.get(member.brokenRaft());\n Block rack = BlockRegistry.get(member.rack());\n blockGenerator.registerSingleton(raft, memberTexture(member), model(\"raft\"));", "score": 0.8619847297668457 }, { "filename": "src/main/java/committee/nova/flotage/compat/jade/FlotageJadePlugin.java", "retrieved_chunk": "package committee.nova.flotage.compat.jade;\nimport committee.nova.flotage.compat.jade.provider.RackBlockTipProvider;\nimport committee.nova.flotage.impl.block.RackBlock;\nimport committee.nova.flotage.impl.tile.RackBlockEntity;\nimport snownee.jade.api.IWailaClientRegistration;\nimport snownee.jade.api.IWailaCommonRegistration;\nimport snownee.jade.api.IWailaPlugin;\nimport snownee.jade.api.WailaPlugin;\n@WailaPlugin\npublic class FlotageJadePlugin implements IWailaPlugin {", "score": 0.8604450225830078 }, { "filename": "src/main/java/committee/nova/flotage/init/TileRegistry.java", "retrieved_chunk": "package committee.nova.flotage.init;\nimport committee.nova.flotage.Flotage;\nimport committee.nova.flotage.impl.tile.RackBlockEntity;\nimport net.fabricmc.fabric.api.object.builder.v1.block.entity.FabricBlockEntityTypeBuilder;\nimport net.minecraft.block.entity.BlockEntityType;\nimport net.minecraft.registry.Registries;\nimport net.minecraft.registry.Registry;\npublic class TileRegistry {\n public static final BlockEntityType<RackBlockEntity> RACK_BLOCK_ENTITY =\n FabricBlockEntityTypeBuilder.create(RackBlockEntity::new, BlockRegistry.getRacks()).build();", "score": 0.8541207909584045 }, { "filename": "src/main/java/committee/nova/flotage/datagen/FloModelProvider.java", "retrieved_chunk": " blockGenerator.registerSingleton(brokenRaft, memberTexture(member), model(\"broken_raft\"));\n blockGenerator.registerSingleton(rack, memberTexture(member), model(\"rack\"));\n }\n @Override\n public void generateBlockStateModels(BlockStateModelGenerator generator) {\n blockGenerator = generator;\n for (BlockMember member : BlockMember.values()) {\n member(member);\n }\n }", "score": 0.8535457253456116 } ]
java
fence()), beautifyName(member.fence()));
package committee.nova.flotage.datagen; import committee.nova.flotage.init.BlockRegistry; import committee.nova.flotage.util.BlockMember; import committee.nova.flotage.util.WorkingMode; import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput; import net.fabricmc.fabric.api.datagen.v1.provider.FabricLanguageProvider; public class FloLangProvider { public static class English extends FabricLanguageProvider { public English(FabricDataOutput dataOutput) { super(dataOutput); } @Override public void generateTranslations(TranslationBuilder builder) { builder.add("itemGroup.flotage.tab", "Flotage"); builder.add("modmenu.descriptionTranslation.flotage", "Survive on the sea!"); builder.add("tip.flotage.rack.processtime", "%s second(s) processing"); builder.add("tip.flotage.rack.mode", "Current Condition: "); builder.add("block.flotage.rack", "Rack Processing"); builder.add("config.jade.plugin_flotage.rack_blockentity", "Rack Working Mode"); builder.add("emi.category.flotage.rack", "Rack Processing"); for (WorkingMode mode : WorkingMode.values()) { builder.add("tip.flotage.rack.mode." + mode.toString(), beautifyName(mode.toString())); } for (BlockMember member : BlockMember.values()) { builder.add(BlockRegistry.get(member.raft()), beautifyName(member.raft())); builder.add(BlockRegistry.get(member.brokenRaft()), beautifyName(member.brokenRaft())); builder.add(BlockRegistry.get(member.fence()), beautifyName(member.fence())); builder.add(BlockRegistry.get(member.crossedFence()), beautifyName(member.crossedFence())); builder.add(BlockRegistry.get(
member.rack()), beautifyName(member.rack()));
} } } public static class Chinese extends FabricLanguageProvider { public Chinese(FabricDataOutput dataOutput) { super(dataOutput, "zh_cn"); } @Override public void generateTranslations(TranslationBuilder builder) { builder.add("itemGroup.flotage.tab", "漂浮物"); builder.add("modmenu.descriptionTranslation.flotage", "生存于大海之上!"); builder.add("tip.flotage.rack.processtime", "需要处理 %s 秒。"); builder.add("tip.flotage.rack.mode", "当前处理条件:"); builder.add("block.flotage.rack", "置物架"); builder.add("config.jade.plugin_flotage.rack_blockentity", "置物架模式"); builder.add("emi.category.flotage.rack", "置物架"); builder.add("tip.flotage.rack.mode.unconditional", "无条件"); builder.add("tip.flotage.rack.mode.sun", "白天"); builder.add("tip.flotage.rack.mode.night", "夜晚"); builder.add("tip.flotage.rack.mode.rain", "雨天"); builder.add("tip.flotage.rack.mode.snow", "雪天"); builder.add("tip.flotage.rack.mode.rain_at", "淋雨"); builder.add("tip.flotage.rack.mode.snow_at", "淋雪"); builder.add("tip.flotage.rack.mode.smoke", "烟熏"); for (BlockMember member : BlockMember.values()) { builder.add(BlockRegistry.get(member.raft()), member.chinese + "筏"); builder.add(BlockRegistry.get(member.brokenRaft()), "损坏的" + member.chinese + "筏"); builder.add(BlockRegistry.get(member.fence()), "简易" + member.chinese + "栅栏"); builder.add(BlockRegistry.get(member.crossedFence()), member.chinese + "十字栅栏"); builder.add(BlockRegistry.get(member.rack()), member.chinese + "置物架"); } } } public static String beautifyName(String name) { String[] str1 = name.split("_"); StringBuilder str2 = new StringBuilder(); for(int i = 0 ; i < str1.length; i++) { str1[i] = str1[i].substring(0,1).toUpperCase() + str1[i].substring(1); if(i == str1.length-1) str2.append(str1[i]); else str2.append(str1[i]).append(" "); } return str2.toString(); } }
src/main/java/committee/nova/flotage/datagen/FloLangProvider.java
Nova-Committee-Flotage-Fabric-6478e2a
[ { "filename": "src/main/java/committee/nova/flotage/datagen/FloBlockTagProvider.java", "retrieved_chunk": " brokenRaft.add(BlockRegistry.get(member.brokenRaft()));\n }\n for (BlockMember member : BlockMember.values()) {\n axe.add(BlockRegistry.get(member.crossedFence()));\n axe.add(BlockRegistry.get(member.fence()));\n axe.add(BlockRegistry.get(member.raft()));\n axe.add(BlockRegistry.get(member.brokenRaft()));\n axe.add(BlockRegistry.get(member.rack()));\n }\n }", "score": 0.8838450908660889 }, { "filename": "src/main/java/committee/nova/flotage/datagen/FloBlockTagProvider.java", "retrieved_chunk": " FabricTagProvider<Block>.FabricTagBuilder rack = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"rack\")));\n FabricTagProvider<Block>.FabricTagBuilder fence = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"fence\")));\n FabricTagProvider<Block>.FabricTagBuilder crossedFence = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"crossed_fence\")));\n FabricTagProvider<Block>.FabricTagBuilder raft = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"raft\")));\n FabricTagProvider<Block>.FabricTagBuilder brokenRaft = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"broken_raft\")));\n for (BlockMember member : BlockMember.values()){\n rack.add(BlockRegistry.get(member.rack()));\n fence.add(BlockRegistry.get(member.fence()));\n crossedFence.add(BlockRegistry.get(member.crossedFence()));\n raft.add(BlockRegistry.get(member.raft()));", "score": 0.8830913305282593 }, { "filename": "src/main/java/committee/nova/flotage/datagen/FloModelProvider.java", "retrieved_chunk": " Block rack = BlockRegistry.get(member.rack());\n itemGenerator.register(raft.asItem(), itemModel(raft));\n itemGenerator.register(brokenRaft.asItem(), itemModel(brokenRaft));\n itemGenerator.register(rack.asItem(), itemModel(rack));\n }\n private static void member(BlockMember member) {\n Block raft = BlockRegistry.get(member.raft());\n Block brokenRaft = BlockRegistry.get(member.brokenRaft());\n Block rack = BlockRegistry.get(member.rack());\n blockGenerator.registerSingleton(raft, memberTexture(member), model(\"raft\"));", "score": 0.8748962879180908 }, { "filename": "src/main/java/committee/nova/flotage/datagen/FloBlockLootProvider.java", "retrieved_chunk": " }\n @Override\n public void generate() {\n for (BlockMember member : BlockMember.values()) {\n addDrop(BlockRegistry.get(member.raft()));\n addDrop(BlockRegistry.get(member.brokenRaft()), member.repairBlock.asItem());\n addDrop(BlockRegistry.get(member.fence()));\n addDrop(BlockRegistry.get(member.crossedFence()), drops(ItemRegistry.get(member.fence()), ConstantLootNumberProvider.create(2f)));\n addDrop(BlockRegistry.get(member.rack()));\n }", "score": 0.8673979043960571 }, { "filename": "src/main/java/committee/nova/flotage/init/BlockRegistry.java", "retrieved_chunk": "public class BlockRegistry {\n public static void register() {\n for (BlockMember member : BlockMember.values()) {\n woodenRaft(member);\n brokenRaft(member);\n fence(member);\n crossedFence(member);\n rack(member);\n }\n }", "score": 0.8663226366043091 } ]
java
member.rack()), beautifyName(member.rack()));
package committee.nova.flotage.datagen; import committee.nova.flotage.init.BlockRegistry; import committee.nova.flotage.util.BlockMember; import committee.nova.flotage.util.WorkingMode; import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput; import net.fabricmc.fabric.api.datagen.v1.provider.FabricLanguageProvider; public class FloLangProvider { public static class English extends FabricLanguageProvider { public English(FabricDataOutput dataOutput) { super(dataOutput); } @Override public void generateTranslations(TranslationBuilder builder) { builder.add("itemGroup.flotage.tab", "Flotage"); builder.add("modmenu.descriptionTranslation.flotage", "Survive on the sea!"); builder.add("tip.flotage.rack.processtime", "%s second(s) processing"); builder.add("tip.flotage.rack.mode", "Current Condition: "); builder.add("block.flotage.rack", "Rack Processing"); builder.add("config.jade.plugin_flotage.rack_blockentity", "Rack Working Mode"); builder.add("emi.category.flotage.rack", "Rack Processing"); for (WorkingMode mode : WorkingMode.values()) { builder.add("tip.flotage.rack.mode." + mode.toString(), beautifyName(mode.toString())); } for (BlockMember member : BlockMember.values()) { builder.add(BlockRegistry.get(member.raft()), beautifyName(member.raft())); builder.add(BlockRegistry.get(member.brokenRaft()), beautifyName(member.brokenRaft())); builder.add(BlockRegistry.get(member.fence()), beautifyName(member.fence())); builder.add(BlockRegistry
.get(member.crossedFence()), beautifyName(member.crossedFence()));
builder.add(BlockRegistry.get(member.rack()), beautifyName(member.rack())); } } } public static class Chinese extends FabricLanguageProvider { public Chinese(FabricDataOutput dataOutput) { super(dataOutput, "zh_cn"); } @Override public void generateTranslations(TranslationBuilder builder) { builder.add("itemGroup.flotage.tab", "漂浮物"); builder.add("modmenu.descriptionTranslation.flotage", "生存于大海之上!"); builder.add("tip.flotage.rack.processtime", "需要处理 %s 秒。"); builder.add("tip.flotage.rack.mode", "当前处理条件:"); builder.add("block.flotage.rack", "置物架"); builder.add("config.jade.plugin_flotage.rack_blockentity", "置物架模式"); builder.add("emi.category.flotage.rack", "置物架"); builder.add("tip.flotage.rack.mode.unconditional", "无条件"); builder.add("tip.flotage.rack.mode.sun", "白天"); builder.add("tip.flotage.rack.mode.night", "夜晚"); builder.add("tip.flotage.rack.mode.rain", "雨天"); builder.add("tip.flotage.rack.mode.snow", "雪天"); builder.add("tip.flotage.rack.mode.rain_at", "淋雨"); builder.add("tip.flotage.rack.mode.snow_at", "淋雪"); builder.add("tip.flotage.rack.mode.smoke", "烟熏"); for (BlockMember member : BlockMember.values()) { builder.add(BlockRegistry.get(member.raft()), member.chinese + "筏"); builder.add(BlockRegistry.get(member.brokenRaft()), "损坏的" + member.chinese + "筏"); builder.add(BlockRegistry.get(member.fence()), "简易" + member.chinese + "栅栏"); builder.add(BlockRegistry.get(member.crossedFence()), member.chinese + "十字栅栏"); builder.add(BlockRegistry.get(member.rack()), member.chinese + "置物架"); } } } public static String beautifyName(String name) { String[] str1 = name.split("_"); StringBuilder str2 = new StringBuilder(); for(int i = 0 ; i < str1.length; i++) { str1[i] = str1[i].substring(0,1).toUpperCase() + str1[i].substring(1); if(i == str1.length-1) str2.append(str1[i]); else str2.append(str1[i]).append(" "); } return str2.toString(); } }
src/main/java/committee/nova/flotage/datagen/FloLangProvider.java
Nova-Committee-Flotage-Fabric-6478e2a
[ { "filename": "src/main/java/committee/nova/flotage/datagen/FloBlockTagProvider.java", "retrieved_chunk": " FabricTagProvider<Block>.FabricTagBuilder rack = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"rack\")));\n FabricTagProvider<Block>.FabricTagBuilder fence = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"fence\")));\n FabricTagProvider<Block>.FabricTagBuilder crossedFence = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"crossed_fence\")));\n FabricTagProvider<Block>.FabricTagBuilder raft = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"raft\")));\n FabricTagProvider<Block>.FabricTagBuilder brokenRaft = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"broken_raft\")));\n for (BlockMember member : BlockMember.values()){\n rack.add(BlockRegistry.get(member.rack()));\n fence.add(BlockRegistry.get(member.fence()));\n crossedFence.add(BlockRegistry.get(member.crossedFence()));\n raft.add(BlockRegistry.get(member.raft()));", "score": 0.8855600357055664 }, { "filename": "src/main/java/committee/nova/flotage/datagen/FloBlockTagProvider.java", "retrieved_chunk": " brokenRaft.add(BlockRegistry.get(member.brokenRaft()));\n }\n for (BlockMember member : BlockMember.values()) {\n axe.add(BlockRegistry.get(member.crossedFence()));\n axe.add(BlockRegistry.get(member.fence()));\n axe.add(BlockRegistry.get(member.raft()));\n axe.add(BlockRegistry.get(member.brokenRaft()));\n axe.add(BlockRegistry.get(member.rack()));\n }\n }", "score": 0.8712472915649414 }, { "filename": "src/main/java/committee/nova/flotage/datagen/FloModelProvider.java", "retrieved_chunk": " Block rack = BlockRegistry.get(member.rack());\n itemGenerator.register(raft.asItem(), itemModel(raft));\n itemGenerator.register(brokenRaft.asItem(), itemModel(brokenRaft));\n itemGenerator.register(rack.asItem(), itemModel(rack));\n }\n private static void member(BlockMember member) {\n Block raft = BlockRegistry.get(member.raft());\n Block brokenRaft = BlockRegistry.get(member.brokenRaft());\n Block rack = BlockRegistry.get(member.rack());\n blockGenerator.registerSingleton(raft, memberTexture(member), model(\"raft\"));", "score": 0.8712467551231384 }, { "filename": "src/main/java/committee/nova/flotage/datagen/FloBlockLootProvider.java", "retrieved_chunk": " }\n @Override\n public void generate() {\n for (BlockMember member : BlockMember.values()) {\n addDrop(BlockRegistry.get(member.raft()));\n addDrop(BlockRegistry.get(member.brokenRaft()), member.repairBlock.asItem());\n addDrop(BlockRegistry.get(member.fence()));\n addDrop(BlockRegistry.get(member.crossedFence()), drops(ItemRegistry.get(member.fence()), ConstantLootNumberProvider.create(2f)));\n addDrop(BlockRegistry.get(member.rack()));\n }", "score": 0.8633854985237122 }, { "filename": "src/main/java/committee/nova/flotage/datagen/FloModelProvider.java", "retrieved_chunk": " blockGenerator.registerSingleton(brokenRaft, memberTexture(member), model(\"broken_raft\"));\n blockGenerator.registerSingleton(rack, memberTexture(member), model(\"rack\"));\n }\n @Override\n public void generateBlockStateModels(BlockStateModelGenerator generator) {\n blockGenerator = generator;\n for (BlockMember member : BlockMember.values()) {\n member(member);\n }\n }", "score": 0.8575217723846436 } ]
java
.get(member.crossedFence()), beautifyName(member.crossedFence()));
package committee.nova.flotage.datagen; import committee.nova.flotage.init.BlockRegistry; import committee.nova.flotage.util.BlockMember; import committee.nova.flotage.util.WorkingMode; import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput; import net.fabricmc.fabric.api.datagen.v1.provider.FabricLanguageProvider; public class FloLangProvider { public static class English extends FabricLanguageProvider { public English(FabricDataOutput dataOutput) { super(dataOutput); } @Override public void generateTranslations(TranslationBuilder builder) { builder.add("itemGroup.flotage.tab", "Flotage"); builder.add("modmenu.descriptionTranslation.flotage", "Survive on the sea!"); builder.add("tip.flotage.rack.processtime", "%s second(s) processing"); builder.add("tip.flotage.rack.mode", "Current Condition: "); builder.add("block.flotage.rack", "Rack Processing"); builder.add("config.jade.plugin_flotage.rack_blockentity", "Rack Working Mode"); builder.add("emi.category.flotage.rack", "Rack Processing"); for (WorkingMode mode : WorkingMode.values()) { builder.add("tip.flotage.rack.mode." + mode.toString(), beautifyName(mode.toString())); } for (BlockMember member : BlockMember.values()) { builder.add(BlockRegistry.get(member.raft()), beautifyName(member.raft())); builder.add(BlockRegistry.get(member.brokenRaft())
, beautifyName(member.brokenRaft()));
builder.add(BlockRegistry.get(member.fence()), beautifyName(member.fence())); builder.add(BlockRegistry.get(member.crossedFence()), beautifyName(member.crossedFence())); builder.add(BlockRegistry.get(member.rack()), beautifyName(member.rack())); } } } public static class Chinese extends FabricLanguageProvider { public Chinese(FabricDataOutput dataOutput) { super(dataOutput, "zh_cn"); } @Override public void generateTranslations(TranslationBuilder builder) { builder.add("itemGroup.flotage.tab", "漂浮物"); builder.add("modmenu.descriptionTranslation.flotage", "生存于大海之上!"); builder.add("tip.flotage.rack.processtime", "需要处理 %s 秒。"); builder.add("tip.flotage.rack.mode", "当前处理条件:"); builder.add("block.flotage.rack", "置物架"); builder.add("config.jade.plugin_flotage.rack_blockentity", "置物架模式"); builder.add("emi.category.flotage.rack", "置物架"); builder.add("tip.flotage.rack.mode.unconditional", "无条件"); builder.add("tip.flotage.rack.mode.sun", "白天"); builder.add("tip.flotage.rack.mode.night", "夜晚"); builder.add("tip.flotage.rack.mode.rain", "雨天"); builder.add("tip.flotage.rack.mode.snow", "雪天"); builder.add("tip.flotage.rack.mode.rain_at", "淋雨"); builder.add("tip.flotage.rack.mode.snow_at", "淋雪"); builder.add("tip.flotage.rack.mode.smoke", "烟熏"); for (BlockMember member : BlockMember.values()) { builder.add(BlockRegistry.get(member.raft()), member.chinese + "筏"); builder.add(BlockRegistry.get(member.brokenRaft()), "损坏的" + member.chinese + "筏"); builder.add(BlockRegistry.get(member.fence()), "简易" + member.chinese + "栅栏"); builder.add(BlockRegistry.get(member.crossedFence()), member.chinese + "十字栅栏"); builder.add(BlockRegistry.get(member.rack()), member.chinese + "置物架"); } } } public static String beautifyName(String name) { String[] str1 = name.split("_"); StringBuilder str2 = new StringBuilder(); for(int i = 0 ; i < str1.length; i++) { str1[i] = str1[i].substring(0,1).toUpperCase() + str1[i].substring(1); if(i == str1.length-1) str2.append(str1[i]); else str2.append(str1[i]).append(" "); } return str2.toString(); } }
src/main/java/committee/nova/flotage/datagen/FloLangProvider.java
Nova-Committee-Flotage-Fabric-6478e2a
[ { "filename": "src/main/java/committee/nova/flotage/datagen/FloBlockTagProvider.java", "retrieved_chunk": " FabricTagProvider<Block>.FabricTagBuilder rack = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"rack\")));\n FabricTagProvider<Block>.FabricTagBuilder fence = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"fence\")));\n FabricTagProvider<Block>.FabricTagBuilder crossedFence = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"crossed_fence\")));\n FabricTagProvider<Block>.FabricTagBuilder raft = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"raft\")));\n FabricTagProvider<Block>.FabricTagBuilder brokenRaft = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"broken_raft\")));\n for (BlockMember member : BlockMember.values()){\n rack.add(BlockRegistry.get(member.rack()));\n fence.add(BlockRegistry.get(member.fence()));\n crossedFence.add(BlockRegistry.get(member.crossedFence()));\n raft.add(BlockRegistry.get(member.raft()));", "score": 0.8852574825286865 }, { "filename": "src/main/java/committee/nova/flotage/datagen/FloModelProvider.java", "retrieved_chunk": " Block rack = BlockRegistry.get(member.rack());\n itemGenerator.register(raft.asItem(), itemModel(raft));\n itemGenerator.register(brokenRaft.asItem(), itemModel(brokenRaft));\n itemGenerator.register(rack.asItem(), itemModel(rack));\n }\n private static void member(BlockMember member) {\n Block raft = BlockRegistry.get(member.raft());\n Block brokenRaft = BlockRegistry.get(member.brokenRaft());\n Block rack = BlockRegistry.get(member.rack());\n blockGenerator.registerSingleton(raft, memberTexture(member), model(\"raft\"));", "score": 0.8713029026985168 }, { "filename": "src/main/java/committee/nova/flotage/datagen/FloModelProvider.java", "retrieved_chunk": " blockGenerator.registerSingleton(brokenRaft, memberTexture(member), model(\"broken_raft\"));\n blockGenerator.registerSingleton(rack, memberTexture(member), model(\"rack\"));\n }\n @Override\n public void generateBlockStateModels(BlockStateModelGenerator generator) {\n blockGenerator = generator;\n for (BlockMember member : BlockMember.values()) {\n member(member);\n }\n }", "score": 0.8599346876144409 }, { "filename": "src/main/java/committee/nova/flotage/init/TileRegistry.java", "retrieved_chunk": "package committee.nova.flotage.init;\nimport committee.nova.flotage.Flotage;\nimport committee.nova.flotage.impl.tile.RackBlockEntity;\nimport net.fabricmc.fabric.api.object.builder.v1.block.entity.FabricBlockEntityTypeBuilder;\nimport net.minecraft.block.entity.BlockEntityType;\nimport net.minecraft.registry.Registries;\nimport net.minecraft.registry.Registry;\npublic class TileRegistry {\n public static final BlockEntityType<RackBlockEntity> RACK_BLOCK_ENTITY =\n FabricBlockEntityTypeBuilder.create(RackBlockEntity::new, BlockRegistry.getRacks()).build();", "score": 0.8580968379974365 }, { "filename": "src/main/java/committee/nova/flotage/datagen/FloBlockTagProvider.java", "retrieved_chunk": " brokenRaft.add(BlockRegistry.get(member.brokenRaft()));\n }\n for (BlockMember member : BlockMember.values()) {\n axe.add(BlockRegistry.get(member.crossedFence()));\n axe.add(BlockRegistry.get(member.fence()));\n axe.add(BlockRegistry.get(member.raft()));\n axe.add(BlockRegistry.get(member.brokenRaft()));\n axe.add(BlockRegistry.get(member.rack()));\n }\n }", "score": 0.8560384511947632 } ]
java
, beautifyName(member.brokenRaft()));
package com.orangomango.chess.multiplayer; import java.io.*; import java.net.*; import javafx.scene.paint.Color; import com.orangomango.chess.Logger; public class Client{ private String ip; private int port; private Socket socket; private BufferedWriter writer; private BufferedReader reader; private Color color; public Client(String ip, int port, Color color){ this.ip = ip; this.port = port; try { this.socket = new Socket(ip, port); this.writer = new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream())); this.reader = new BufferedReader(new InputStreamReader(this.socket.getInputStream())); sendMessage(color == Color.WHITE ? "WHITE" : "BLACK"); String response = getMessage(); if (response != null){ if (response.equals("FULL")){ Logger.writeInfo("Server is full"); System.exit(0); } else { this.color = response.equals("WHITE") ? Color.WHITE : Color.BLACK; } } else {
Logger.writeError("Invalid server response");
System.exit(0); } } catch (IOException ex){ close(); } } public Color getColor(){ return this.color; } public boolean isConnected(){ return this.socket != null && this.socket.isConnected(); } public void sendMessage(String message){ try { this.writer.write(message); this.writer.newLine(); this.writer.flush(); } catch (IOException ex){ close(); } } public String getMessage(){ try { String message = this.reader.readLine(); return message; } catch (IOException ex){ close(); return null; } } private void close(){ try { if (this.socket != null) this.socket.close(); if (this.reader != null) this.reader.close(); if (this.writer != null) this.writer.close(); } catch (IOException ex){ ex.printStackTrace(); } } }
src/main/java/com/orangomango/chess/multiplayer/Client.java
OrangoMango-Chess-c4bd8f5
[ { "filename": "src/main/java/com/orangomango/chess/multiplayer/ClientManager.java", "retrieved_chunk": "\t\tif (Server.clients.size() > 2){\n\t\t\tmessage = \"FULL\";\n\t\t\tServer.clients.remove(this);\n\t\t} else {\n\t\t\tmessage = this.color == Color.WHITE ? \"WHITE\" : \"BLACK\";\n\t\t}\n\t\ttry {\n\t\t\tthis.writer.write(message);\n\t\t\tthis.writer.newLine();\n\t\t\tthis.writer.flush();", "score": 0.8783027529716492 }, { "filename": "src/main/java/com/orangomango/chess/multiplayer/ClientManager.java", "retrieved_chunk": "\t\tLogger.writeInfo(\"Client connected\");\n\t\tlisten();\n\t}\n\tpublic void reply(){\n\t\tString message = null;\n\t\tfor (ClientManager c : Server.clients){\n\t\t\tif (c != this && c.getColor() == this.color){\n\t\t\t\tthis.color = this.color == Color.WHITE ? Color.BLACK : Color.WHITE;\n\t\t\t}\n\t\t}", "score": 0.847998857498169 }, { "filename": "src/main/java/com/orangomango/chess/multiplayer/ClientManager.java", "retrieved_chunk": "\tpublic ClientManager(Socket socket){\n\t\tthis.socket = socket;\n\t\ttry {\n\t\t\tthis.writer = new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream()));\n\t\t\tthis.reader = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));\n\t\t\tString message = this.reader.readLine();\n\t\t\tthis.color = message.equals(\"WHITE\") ? Color.WHITE : Color.BLACK;\n\t\t} catch (IOException ex){\n\t\t\tclose();\n\t\t}", "score": 0.8089758157730103 }, { "filename": "src/main/java/com/orangomango/chess/Engine.java", "retrieved_chunk": "\t\t\twhile (true){\n\t\t\t\tString line = this.reader.readLine();\n\t\t\t\tif (line == null || line.equals(\"readyok\")){\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\tbuilder.append(line+\"\\n\");\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception ex){\n\t\t\tex.printStackTrace();", "score": 0.8069552183151245 }, { "filename": "src/main/java/com/orangomango/chess/multiplayer/ClientManager.java", "retrieved_chunk": "package com.orangomango.chess.multiplayer;\nimport java.io.*;\nimport java.net.*;\nimport javafx.scene.paint.Color;\nimport com.orangomango.chess.Logger;\npublic class ClientManager{\n\tprivate Socket socket;\n\tprivate BufferedWriter writer;\n\tprivate BufferedReader reader;\n\tprivate Color color;", "score": 0.8047518730163574 } ]
java
Logger.writeError("Invalid server response");
package com.orangomango.chess; import java.io.*; import javafx.scene.paint.Color; public class Engine{ private static String COMMAND = "stockfish"; private OutputStreamWriter writer; private BufferedReader reader; private boolean running = true; static { File dir = new File(System.getProperty("user.home"), ".omchess"); String found = null; if (dir.exists()){ for (File file : dir.listFiles()){ // Custom stockfish file if (file.getName().startsWith("stockfish")){ found = file.getAbsolutePath(); break; } } } if (found != null) COMMAND = found; } public Engine(){ try { Process process = Runtime.getRuntime().exec(COMMAND); this.writer = new OutputStreamWriter(process.getOutputStream()); this.reader = new BufferedReader(new InputStreamReader(process.getInputStream())); getOutput(20); } catch (IOException ex){ ex.printStackTrace(); Logger.writeError(ex.getMessage()); this.running = false; } } public boolean isRunning(){ return this.running; } public void writeCommand(String command){ try { this.writer.write(command+"\n"); this.writer.flush(); } catch (IOException ex){ ex.printStackTrace(); } } public String getOutput(int time){ StringBuilder builder = new StringBuilder(); try { Thread.sleep(time); writeCommand("isready"); while (true){ String line = this.reader.readLine(); if (line == null || line.equals("readyok")){ break; } else { builder.append(line+"\n"); } } } catch (Exception ex){ ex.printStackTrace(); System.exit(0); } return builder.toString(); } public String getBestMove(Board b){ writeCommand
("position fen "+b.getFEN());
writeCommand(String.format("go wtime %s btime %s winc %s binc %s", b.getTime(Color.WHITE), b.getTime(Color.BLACK), b.getIncrementTime(), b.getIncrementTime())); String output = ""; while (true) { try { String line = this.reader.readLine(); if (line != null && line.contains("bestmove")){ output = line.split("bestmove ")[1].split(" ")[0]; break; } } catch (IOException ex){ ex.printStackTrace(); } } if (output.trim().equals("(none)")) return null; char[] c = output.toCharArray(); return String.valueOf(c[0])+String.valueOf(c[1])+" "+String.valueOf(c[2])+String.valueOf(c[3])+(c.length == 5 ? " "+String.valueOf(c[4]) : ""); } public String getEval(String fen){ writeCommand("position fen "+fen); writeCommand("eval"); String output = getOutput(50).split("Final evaluation")[1].split("\\(")[0].trim(); if (output.startsWith(":")) output = output.substring(1).trim(); return output; } }
src/main/java/com/orangomango/chess/Engine.java
OrangoMango-Chess-c4bd8f5
[ { "filename": "src/main/java/com/orangomango/chess/Board.java", "retrieved_chunk": "\t\t\tresult = \"0-1\";\n\t\t} else if (isCheckMate(Color.BLACK)){\n\t\t\tresult = \"1-0\";\n\t\t}\n\t\tbuilder.append(\"[Result \\\"\"+result+\"\\\"]\\n\\n\");\n\t\tfor (int i = 0; i < this.moves.size(); i++){\n\t\t\tif (i % 2 == 0) builder.append((i/2+1)+\". \");\n\t\t\tbuilder.append(this.moves.get(i)+\" \");\n\t\t}\n\t\tbuilder.append(result);", "score": 0.8300759792327881 }, { "filename": "src/main/java/com/orangomango/chess/Board.java", "retrieved_chunk": "\t\treturn builder.toString();\n\t}\n\tpublic String getFEN(){\n\t\tStringBuilder builder = new StringBuilder();\n\t\tfor (int i = 0; i < 8; i++){\n\t\t\tint empty = 0;\n\t\t\tfor (int j = 0; j < 8; j++){\n\t\t\t\tPiece piece = this.board[j][i];\n\t\t\t\tif (piece == null){\n\t\t\t\t\tempty++;", "score": 0.8293214440345764 }, { "filename": "src/main/java/com/orangomango/chess/MainApplication.java", "retrieved_chunk": "\t\tif (this.gameFinished) return;\n\t\tnew Thread(() -> {\n\t\t\tString output = this.engine.getBestMove(this.board);\n\t\t\tif (output != null){\n\t\t\t\tthis.animation = new PieceAnimation(output.split(\" \")[0], output.split(\" \")[1], () -> {\n\t\t\t\t\tString prom = output.split(\" \").length == 3 ? output.split(\" \")[2] : null;\n\t\t\t\t\tthis.board.move(output.split(\" \")[0], output.split(\" \")[1], prom);\n\t\t\t\t\tif (this.client != null) this.client.sendMessage(output.split(\" \")[0]+\" \"+output.split(\" \")[1]);\n\t\t\t\t\tthis.hold.clear();\n\t\t\t\t\tthis.currentSelection = null;", "score": 0.8094668984413147 }, { "filename": "src/main/java/com/orangomango/chess/Board.java", "retrieved_chunk": "\t\tbuilder.append(\"[Event \\\"\"+String.format(\"%s vs %s\", this.playerA, this.playerB)+\"\\\"]\\n\");\n\t\tbuilder.append(\"[Site \\\"com.orangomango.chess\\\"]\\n\");\n\t\tbuilder.append(\"[Date \\\"\"+format.format(date)+\"\\\"]\\n\");\n\t\tbuilder.append(\"[Round \\\"1\\\"]\\n\");\n\t\tbuilder.append(\"[White \\\"\"+this.playerA+\"\\\"]\\n\");\n\t\tbuilder.append(\"[Black \\\"\"+this.playerB+\"\\\"]\\n\");\n\t\tString result = \"*\";\n\t\tif (isDraw()){\n\t\t\tresult = \"½-½\";\n\t\t} else if (isCheckMate(Color.WHITE)){", "score": 0.8088572025299072 }, { "filename": "src/main/java/com/orangomango/chess/Board.java", "retrieved_chunk": "\tprivate List<String> moves = new ArrayList<>();\n\tpublic String playerA = System.getProperty(\"user.name\"), playerB = \"BLACK\";\n\tprivate volatile long whiteTime, blackTime;\n\tprivate long lastTime, gameTime;\n\tprivate int increment;\n\tpublic Board(String fen, long time, int increment){\n\t\tthis.board = new Piece[8][8];\n\t\tsetupBoard(fen);\n\t\tthis.gameTime = time;\n\t\tthis.increment = increment;", "score": 0.8047089576721191 } ]
java
("position fen "+b.getFEN());
package org.swmaestro.kauth.authentication.jwt; import java.io.IOException; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.web.filter.OncePerRequestFilter; import org.swmaestro.kauth.exceptions.RefreshTokenMismatchException; import org.swmaestro.kauth.exceptions.RefreshTokenMissingException; import org.swmaestro.kauth.exceptions.RefreshTokenServiceUnavailableException; import org.swmaestro.kauth.util.HttpServletResponseUtil; import org.swmaestro.kauth.util.JwtUtil; import com.auth0.jwt.exceptions.JWTVerificationException; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * 토큰 재발급 필터 * @author ChangEn Yea */ public class JwtReissueFilter extends OncePerRequestFilter { private final AntPathRequestMatcher requestMatcher; private final JwtUtil jwtUtil; private final RefreshTokenManager refreshTokenManager; private final HttpServletResponseUtil responseUtil; /** * 인스턴스를 생성한다. * @param requestMatcher {@link AntPathRequestMatcher} * @param jwtUtil {@link JwtUtil} * @param refreshTokenManager {@link RefreshTokenManager} * @param responseUtil {@link HttpServletResponseUtil} */ public JwtReissueFilter(AntPathRequestMatcher requestMatcher, JwtUtil jwtUtil, RefreshTokenManager refreshTokenManager, HttpServletResponseUtil responseUtil) { this.requestMatcher = requestMatcher; this.jwtUtil = jwtUtil; this.refreshTokenManager = refreshTokenManager; this.responseUtil = responseUtil; } /** * 요청이 {@link #requestMatcher}와 일치하면 요청 Refresh-Token 헤더의 토큰을 검증한다. * 헤더와 서버 내의 두 refreshToken을 비교하고, * 같은 토큰이라면 새로운 토큰을 발급하고 저장하고 응답 헤더에 토큰을 설정한다. * @param request {@link HttpServletRequest} * @param response {@link HttpServletResponse} * @param filterChain {@link FilterChain} * @throws ServletException * @throws IOException */ @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (requestMatcher.matches(request)) { try { String token = request.getHeader("Refresh-Token"); if (token == null) { throw new RefreshTokenMissingException(); } String
username = jwtUtil.verifyToken(token);
if (!refreshTokenManager.getRefreshToken(username).equals(token)) { responseUtil.setUnauthorizedResponse(response, new RefreshTokenMismatchException("RefreshTokens are not match.")); } String accessToken = jwtUtil.createAccessToken(username); String refreshToken = jwtUtil.createRefreshToken(username); refreshTokenManager.setRefreshToken(refreshToken, username); responseUtil.setHeader(response, "Authorization", accessToken); responseUtil.setHeader(response, "Refresh-Token", refreshToken); } catch (RefreshTokenMissingException | RefreshTokenServiceUnavailableException | RefreshTokenMismatchException | JWTVerificationException e) { responseUtil.setUnauthorizedResponse(response, e); } } else { filterChain.doFilter(request, response); } } }
src/main/java/org/swmaestro/kauth/authentication/jwt/JwtReissueFilter.java
nsce9806q-k-spring-security-8e88d3d
[ { "filename": "src/main/java/org/swmaestro/kauth/authentication/AbstractAuthenticationFilter.java", "retrieved_chunk": "\t@Override\n\tpublic void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)\n\t\tthrows IOException, ServletException {\n\t\tif (requestMatcher.matches(request)) {\n\t\t\ttry {\n\t\t\t\tAuthentication authenticationResult = attemptAuthentication(request, response);\n\t\t\t\tsuccessfulAuthentication(request, response, chain, authenticationResult);\n\t\t\t} catch (InternalAuthenticationServiceException failed) {\n\t\t\t\tsuper.logger.error(\"An internal error occurred while trying to authenticate the user.\", failed);\n\t\t\t} catch (AuthenticationException ex) {", "score": 0.886495053768158 }, { "filename": "src/main/java/org/swmaestro/kauth/authentication/jwt/JwtUsernamePasswordAuthenticationFilter.java", "retrieved_chunk": "package org.swmaestro.kauth.authentication.jwt;\nimport jakarta.servlet.FilterChain;\nimport jakarta.servlet.ServletException;\nimport jakarta.servlet.http.HttpServletRequest;\nimport jakarta.servlet.http.HttpServletResponse;\nimport java.io.IOException;\nimport org.springframework.security.authentication.AuthenticationManager;\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.web.util.matcher.AntPathRequestMatcher;\nimport org.swmaestro.kauth.authentication.AbstractUsernamePasswordAuthenticationFilter;", "score": 0.8588670492172241 }, { "filename": "src/main/java/org/swmaestro/kauth/authentication/jwt/JwtUsernamePasswordAuthenticationFilter.java", "retrieved_chunk": "\t\tString username = (String) authResult.getPrincipal();\n\t\tString accessToken = jwtUtil.createAccessToken(username);\n\t\tString refreshToken = jwtUtil.createRefreshToken(username);\n\t\trefreshTokenManager.setRefreshToken(refreshToken, username);\n\t\tsuper.responseUtil.setHeader(response, \"Authorization\", accessToken);\n\t\tsuper.responseUtil.setHeader(response, \"Refresh-Token\", refreshToken);\n\t}\n}", "score": 0.8515331745147705 }, { "filename": "src/main/java/org/swmaestro/kauth/core/jwt/JwtFilterChain.java", "retrieved_chunk": "\t * @throws Exception\n\t */\n\tprotected JwtFilterChain(HttpSecurity http, JwtUtil jwtUtil,\n\t\tAuthenticationManager authenticationManager, RefreshTokenManager refreshTokenManager,\n\t\tObjectMapper objectMapper, HttpServletResponseUtil responseUtil) throws Exception {\n\t\tsuper(http, responseUtil);\n\t\tthis.jwtUtil = jwtUtil;\n\t\tthis.authenticationManager = authenticationManager;\n\t\tthis.refreshTokenManager = refreshTokenManager;\n\t\tthis.objectMapper = objectMapper;", "score": 0.8394735455513 }, { "filename": "src/main/java/org/swmaestro/kauth/authentication/AbstractAuthenticationFilter.java", "retrieved_chunk": "package org.swmaestro.kauth.authentication;\nimport jakarta.servlet.FilterChain;\nimport jakarta.servlet.ServletException;\nimport jakarta.servlet.http.HttpServletRequest;\nimport jakarta.servlet.http.HttpServletResponse;\nimport java.io.IOException;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.springframework.security.authentication.InternalAuthenticationServiceException;\nimport org.springframework.security.core.Authentication;", "score": 0.836553692817688 } ]
java
username = jwtUtil.verifyToken(token);
package com.orangomango.chess; import java.io.*; import javafx.scene.paint.Color; public class Engine{ private static String COMMAND = "stockfish"; private OutputStreamWriter writer; private BufferedReader reader; private boolean running = true; static { File dir = new File(System.getProperty("user.home"), ".omchess"); String found = null; if (dir.exists()){ for (File file : dir.listFiles()){ // Custom stockfish file if (file.getName().startsWith("stockfish")){ found = file.getAbsolutePath(); break; } } } if (found != null) COMMAND = found; } public Engine(){ try { Process process = Runtime.getRuntime().exec(COMMAND); this.writer = new OutputStreamWriter(process.getOutputStream()); this.reader = new BufferedReader(new InputStreamReader(process.getInputStream())); getOutput(20); } catch (IOException ex){ ex.printStackTrace(); Logger.writeError(ex.getMessage()); this.running = false; } } public boolean isRunning(){ return this.running; } public void writeCommand(String command){ try { this.writer.write(command+"\n"); this.writer.flush(); } catch (IOException ex){ ex.printStackTrace(); } } public String getOutput(int time){ StringBuilder builder = new StringBuilder(); try { Thread.sleep(time); writeCommand("isready"); while (true){ String line = this.reader.readLine(); if (line == null || line.equals("readyok")){ break; } else { builder.append(line+"\n"); } } } catch (Exception ex){ ex.printStackTrace(); System.exit(0); } return builder.toString(); } public String getBestMove(Board b){ writeCommand("position fen "+b.getFEN()); writeCommand(String.format("go wtime %s btime %s winc %s binc %s", b.getTime(Color.WHITE), b.getTime(Color.BLACK), b.
getIncrementTime(), b.getIncrementTime()));
String output = ""; while (true) { try { String line = this.reader.readLine(); if (line != null && line.contains("bestmove")){ output = line.split("bestmove ")[1].split(" ")[0]; break; } } catch (IOException ex){ ex.printStackTrace(); } } if (output.trim().equals("(none)")) return null; char[] c = output.toCharArray(); return String.valueOf(c[0])+String.valueOf(c[1])+" "+String.valueOf(c[2])+String.valueOf(c[3])+(c.length == 5 ? " "+String.valueOf(c[4]) : ""); } public String getEval(String fen){ writeCommand("position fen "+fen); writeCommand("eval"); String output = getOutput(50).split("Final evaluation")[1].split("\\(")[0].trim(); if (output.startsWith(":")) output = output.substring(1).trim(); return output; } }
src/main/java/com/orangomango/chess/Engine.java
OrangoMango-Chess-c4bd8f5
[ { "filename": "src/main/java/com/orangomango/chess/Board.java", "retrieved_chunk": "\t\t\tresult = \"0-1\";\n\t\t} else if (isCheckMate(Color.BLACK)){\n\t\t\tresult = \"1-0\";\n\t\t}\n\t\tbuilder.append(\"[Result \\\"\"+result+\"\\\"]\\n\\n\");\n\t\tfor (int i = 0; i < this.moves.size(); i++){\n\t\t\tif (i % 2 == 0) builder.append((i/2+1)+\". \");\n\t\t\tbuilder.append(this.moves.get(i)+\" \");\n\t\t}\n\t\tbuilder.append(result);", "score": 0.8582912683486938 }, { "filename": "src/main/java/com/orangomango/chess/Board.java", "retrieved_chunk": "\t\tbuilder.append(\"[Event \\\"\"+String.format(\"%s vs %s\", this.playerA, this.playerB)+\"\\\"]\\n\");\n\t\tbuilder.append(\"[Site \\\"com.orangomango.chess\\\"]\\n\");\n\t\tbuilder.append(\"[Date \\\"\"+format.format(date)+\"\\\"]\\n\");\n\t\tbuilder.append(\"[Round \\\"1\\\"]\\n\");\n\t\tbuilder.append(\"[White \\\"\"+this.playerA+\"\\\"]\\n\");\n\t\tbuilder.append(\"[Black \\\"\"+this.playerB+\"\\\"]\\n\");\n\t\tString result = \"*\";\n\t\tif (isDraw()){\n\t\t\tresult = \"½-½\";\n\t\t} else if (isCheckMate(Color.WHITE)){", "score": 0.8369029760360718 }, { "filename": "src/main/java/com/orangomango/chess/Board.java", "retrieved_chunk": "\tprivate List<String> moves = new ArrayList<>();\n\tpublic String playerA = System.getProperty(\"user.name\"), playerB = \"BLACK\";\n\tprivate volatile long whiteTime, blackTime;\n\tprivate long lastTime, gameTime;\n\tprivate int increment;\n\tpublic Board(String fen, long time, int increment){\n\t\tthis.board = new Piece[8][8];\n\t\tsetupBoard(fen);\n\t\tthis.gameTime = time;\n\t\tthis.increment = increment;", "score": 0.8366673588752747 }, { "filename": "src/main/java/com/orangomango/chess/Board.java", "retrieved_chunk": "\t\treturn builder.toString();\n\t}\n\tpublic String getFEN(){\n\t\tStringBuilder builder = new StringBuilder();\n\t\tfor (int i = 0; i < 8; i++){\n\t\t\tint empty = 0;\n\t\t\tfor (int j = 0; j < 8; j++){\n\t\t\t\tPiece piece = this.board[j][i];\n\t\t\t\tif (piece == null){\n\t\t\t\t\tempty++;", "score": 0.8366189002990723 }, { "filename": "src/main/java/com/orangomango/chess/Board.java", "retrieved_chunk": "\t\t\treturn this.blackChecks;\n\t\t}\n\t}\n\tpublic Piece[][] getBoard(){\n\t\treturn this.board;\n\t}\n\tpublic String getPGN(){\n\t\tStringBuilder builder = new StringBuilder();\n\t\tSimpleDateFormat format = new SimpleDateFormat(\"YYYY/MM/dd\");\n\t\tDate date = new Date();", "score": 0.8271892070770264 } ]
java
getIncrementTime(), b.getIncrementTime()));
package com.orangomango.chess; import java.io.*; import javafx.scene.paint.Color; public class Engine{ private static String COMMAND = "stockfish"; private OutputStreamWriter writer; private BufferedReader reader; private boolean running = true; static { File dir = new File(System.getProperty("user.home"), ".omchess"); String found = null; if (dir.exists()){ for (File file : dir.listFiles()){ // Custom stockfish file if (file.getName().startsWith("stockfish")){ found = file.getAbsolutePath(); break; } } } if (found != null) COMMAND = found; } public Engine(){ try { Process process = Runtime.getRuntime().exec(COMMAND); this.writer = new OutputStreamWriter(process.getOutputStream()); this.reader = new BufferedReader(new InputStreamReader(process.getInputStream())); getOutput(20); } catch (IOException ex){ ex.printStackTrace(); Logger.writeError(ex.getMessage()); this.running = false; } } public boolean isRunning(){ return this.running; } public void writeCommand(String command){ try { this.writer.write(command+"\n"); this.writer.flush(); } catch (IOException ex){ ex.printStackTrace(); } } public String getOutput(int time){ StringBuilder builder = new StringBuilder(); try { Thread.sleep(time); writeCommand("isready"); while (true){ String line = this.reader.readLine(); if (line == null || line.equals("readyok")){ break; } else { builder.append(line+"\n"); } } } catch (Exception ex){ ex.printStackTrace(); System.exit(0); } return builder.toString(); } public String getBestMove(Board b){ writeCommand("position fen "+b.getFEN()); writeCommand(String.format("go wtime %s btime %s winc %s binc %s", b.getTime(
Color.WHITE), b.getTime(Color.BLACK), b.getIncrementTime(), b.getIncrementTime()));
String output = ""; while (true) { try { String line = this.reader.readLine(); if (line != null && line.contains("bestmove")){ output = line.split("bestmove ")[1].split(" ")[0]; break; } } catch (IOException ex){ ex.printStackTrace(); } } if (output.trim().equals("(none)")) return null; char[] c = output.toCharArray(); return String.valueOf(c[0])+String.valueOf(c[1])+" "+String.valueOf(c[2])+String.valueOf(c[3])+(c.length == 5 ? " "+String.valueOf(c[4]) : ""); } public String getEval(String fen){ writeCommand("position fen "+fen); writeCommand("eval"); String output = getOutput(50).split("Final evaluation")[1].split("\\(")[0].trim(); if (output.startsWith(":")) output = output.substring(1).trim(); return output; } }
src/main/java/com/orangomango/chess/Engine.java
OrangoMango-Chess-c4bd8f5
[ { "filename": "src/main/java/com/orangomango/chess/Board.java", "retrieved_chunk": "\t\t\tresult = \"0-1\";\n\t\t} else if (isCheckMate(Color.BLACK)){\n\t\t\tresult = \"1-0\";\n\t\t}\n\t\tbuilder.append(\"[Result \\\"\"+result+\"\\\"]\\n\\n\");\n\t\tfor (int i = 0; i < this.moves.size(); i++){\n\t\t\tif (i % 2 == 0) builder.append((i/2+1)+\". \");\n\t\t\tbuilder.append(this.moves.get(i)+\" \");\n\t\t}\n\t\tbuilder.append(result);", "score": 0.8569191098213196 }, { "filename": "src/main/java/com/orangomango/chess/Board.java", "retrieved_chunk": "\tprivate List<String> moves = new ArrayList<>();\n\tpublic String playerA = System.getProperty(\"user.name\"), playerB = \"BLACK\";\n\tprivate volatile long whiteTime, blackTime;\n\tprivate long lastTime, gameTime;\n\tprivate int increment;\n\tpublic Board(String fen, long time, int increment){\n\t\tthis.board = new Piece[8][8];\n\t\tsetupBoard(fen);\n\t\tthis.gameTime = time;\n\t\tthis.increment = increment;", "score": 0.8378024697303772 }, { "filename": "src/main/java/com/orangomango/chess/Board.java", "retrieved_chunk": "\t\treturn builder.toString();\n\t}\n\tpublic String getFEN(){\n\t\tStringBuilder builder = new StringBuilder();\n\t\tfor (int i = 0; i < 8; i++){\n\t\t\tint empty = 0;\n\t\t\tfor (int j = 0; j < 8; j++){\n\t\t\t\tPiece piece = this.board[j][i];\n\t\t\t\tif (piece == null){\n\t\t\t\t\tempty++;", "score": 0.8373656272888184 }, { "filename": "src/main/java/com/orangomango/chess/Board.java", "retrieved_chunk": "\t\tbuilder.append(\"[Event \\\"\"+String.format(\"%s vs %s\", this.playerA, this.playerB)+\"\\\"]\\n\");\n\t\tbuilder.append(\"[Site \\\"com.orangomango.chess\\\"]\\n\");\n\t\tbuilder.append(\"[Date \\\"\"+format.format(date)+\"\\\"]\\n\");\n\t\tbuilder.append(\"[Round \\\"1\\\"]\\n\");\n\t\tbuilder.append(\"[White \\\"\"+this.playerA+\"\\\"]\\n\");\n\t\tbuilder.append(\"[Black \\\"\"+this.playerB+\"\\\"]\\n\");\n\t\tString result = \"*\";\n\t\tif (isDraw()){\n\t\t\tresult = \"½-½\";\n\t\t} else if (isCheckMate(Color.WHITE)){", "score": 0.8361999988555908 }, { "filename": "src/main/java/com/orangomango/chess/Board.java", "retrieved_chunk": "\t\t\treturn this.blackChecks;\n\t\t}\n\t}\n\tpublic Piece[][] getBoard(){\n\t\treturn this.board;\n\t}\n\tpublic String getPGN(){\n\t\tStringBuilder builder = new StringBuilder();\n\t\tSimpleDateFormat format = new SimpleDateFormat(\"YYYY/MM/dd\");\n\t\tDate date = new Date();", "score": 0.8265161514282227 } ]
java
Color.WHITE), b.getTime(Color.BLACK), b.getIncrementTime(), b.getIncrementTime()));
package com.orangomango.chess.multiplayer; import java.io.*; import java.net.*; import java.util.*; import com.orangomango.chess.Logger; public class Server{ private String ip; private int port; private ServerSocket server; public static List<ClientManager> clients = new ArrayList<>(); public Server(String ip, int port){ this.ip = ip; this.port = port; try { this.server = new ServerSocket(port, 10, InetAddress.getByName(ip)); } catch (IOException ex){ close(); } listen(); Logger.writeInfo("Server started"); } private void listen(){ Thread listener = new Thread(() -> { while (!this.server.isClosed()){ try { Socket socket = this.server.accept(); ClientManager cm = new ClientManager(socket); clients.add(cm);
cm.reply();
} catch (IOException ex){ ex.printStackTrace(); } } }); listener.setDaemon(true); listener.start(); } private void close(){ try { if (this.server != null) this.server.close(); } catch (IOException ex){ ex.printStackTrace(); } } }
src/main/java/com/orangomango/chess/multiplayer/Server.java
OrangoMango-Chess-c4bd8f5
[ { "filename": "src/main/java/com/orangomango/chess/multiplayer/ClientManager.java", "retrieved_chunk": "\t\tLogger.writeInfo(\"Client connected\");\n\t\tlisten();\n\t}\n\tpublic void reply(){\n\t\tString message = null;\n\t\tfor (ClientManager c : Server.clients){\n\t\t\tif (c != this && c.getColor() == this.color){\n\t\t\t\tthis.color = this.color == Color.WHITE ? Color.BLACK : Color.WHITE;\n\t\t\t}\n\t\t}", "score": 0.8757883310317993 }, { "filename": "src/main/java/com/orangomango/chess/multiplayer/ClientManager.java", "retrieved_chunk": "\tpublic ClientManager(Socket socket){\n\t\tthis.socket = socket;\n\t\ttry {\n\t\t\tthis.writer = new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream()));\n\t\t\tthis.reader = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));\n\t\t\tString message = this.reader.readLine();\n\t\t\tthis.color = message.equals(\"WHITE\") ? Color.WHITE : Color.BLACK;\n\t\t} catch (IOException ex){\n\t\t\tclose();\n\t\t}", "score": 0.8441592454910278 }, { "filename": "src/main/java/com/orangomango/chess/multiplayer/ClientManager.java", "retrieved_chunk": "\t\t} catch (IOException ex){\n\t\t\tclose();\n\t\t}\n\t}\n\tpublic Color getColor(){\n\t\treturn this.color;\n\t}\n\tprivate void listen(){\n\t\tThread listener = new Thread(() -> {\n\t\t\twhile (this.socket.isConnected()){", "score": 0.8438711166381836 }, { "filename": "src/main/java/com/orangomango/chess/multiplayer/ClientManager.java", "retrieved_chunk": "\t\tlistener.setDaemon(true);\n\t\tlistener.start();\n\t}\n\tprivate void broadcast(String message){\n\t\tfor (ClientManager cm : Server.clients){\n\t\t\tif (cm == this) continue;\n\t\t\ttry {\n\t\t\t\tcm.writer.write(message);\n\t\t\t\tcm.writer.newLine();\n\t\t\t\tcm.writer.flush();", "score": 0.8363489508628845 }, { "filename": "src/main/java/com/orangomango/chess/multiplayer/ClientManager.java", "retrieved_chunk": "package com.orangomango.chess.multiplayer;\nimport java.io.*;\nimport java.net.*;\nimport javafx.scene.paint.Color;\nimport com.orangomango.chess.Logger;\npublic class ClientManager{\n\tprivate Socket socket;\n\tprivate BufferedWriter writer;\n\tprivate BufferedReader reader;\n\tprivate Color color;", "score": 0.82166588306427 } ]
java
cm.reply();
package org.swmaestro.kauth.authentication; import org.springframework.context.annotation.Lazy; import org.springframework.security.authentication.AccountStatusUserDetailsChecker; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsChecker; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; import org.swmaestro.kauth.core.user.PostAuthenticationService; import org.swmaestro.kauth.core.user.KauthUserDetailsService; /** * Username + Password를 사용하는 {@link AuthenticationManager} * @author ChangEn Yea */ @Lazy @Component public class UsernamePasswordAuthenticationManager implements AuthenticationManager { private final KauthUserDetailsService userDetailsService; private final PasswordEncoder passwordEncoder; private final UserDetailsChecker userDetailsChecker = new AccountStatusUserDetailsChecker(); /** * 인스턴스를 생성한다. * @param userDetailsService {@link KauthUserDetailsService} * @param passwordEncoder {@link PasswordEncoder} */ public UsernamePasswordAuthenticationManager(KauthUserDetailsService userDetailsService, PasswordEncoder passwordEncoder) { this.userDetailsService = userDetailsService; this.passwordEncoder = passwordEncoder; } /** * <pre> * {@link UserDetailsService#loadUserByUsername}를 호출해서 * {@link Authentication}의 credentials과 {@link UserDetails}의 password를 {@link PasswordEncoder#matches}를 통해 * 일치 여부를 확인한다. * 일치 한다면 {@link Authentication} 인스턴스를 인증 처리하고, credential를 삭제하고, 권한을 설정한다. * </pre> * @param authentication {@link Authentication} * @return 인증 처리 된 {@link Authentication} * @throws AuthenticationException */ @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { AuthenticationProvider auth = (AuthenticationProvider)authentication; UserDetails
user = userDetailsService.loadUserByUsername((String)auth.getPrincipal());
if (user == null) { throw new UsernameNotFoundException("userDetailsService.loadUserByUsername returns null"); } // AccountStatusException 체크 userDetailsChecker.check(user); if (passwordEncoder.matches((String)auth.getCredentials(), user.getPassword())) { auth.setAuthenticated(true); auth.eraseCredentials(); auth.setAuthorities(user.getAuthorities()); userDetailsService.handleSuccessfulAuthentication(user); return auth; } else { throw new BadCredentialsException("Password does not matches."); } } /** * {@link BadCredentialsException}을 처리하도록 * {@link PostAuthenticationService#handleBadCredentialsException}을 호출한다. * @param username * @return 비밀번호 틀린 횟수. (-1 이면 틀린 횟수를 알려주지 않는다) */ public Integer handleBadCredentialsException(String username) { return userDetailsService.handleBadCredentialsException(username); } }
src/main/java/org/swmaestro/kauth/authentication/UsernamePasswordAuthenticationManager.java
nsce9806q-k-spring-security-8e88d3d
[ { "filename": "src/main/java/org/swmaestro/kauth/authentication/AbstractUsernamePasswordAuthenticationFilter.java", "retrieved_chunk": "\t * @throws AuthenticationException 로그인 오류(아이디, 비밀번호 오류 등), 계정 잠김 등 인증 실패 시\n\t */\n\t@Override\n\tpublic Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)\n\t\tthrows AuthenticationException {\n\t\ttry {\n\t\t\tUsernamePasswordLoginRequest loginRequest = objectMapper\n\t\t\t\t.readValue(request.getInputStream(), UsernamePasswordLoginRequest.class);\n\t\t\treturn this.authenticationManager.authenticate(new AuthenticationProvider(\n\t\t\t\tloginRequest.getUsername(), loginRequest.getPassword()));", "score": 0.8192489147186279 }, { "filename": "src/main/java/org/swmaestro/kauth/authentication/AuthenticationProvider.java", "retrieved_chunk": "package org.swmaestro.kauth.authentication;\nimport java.util.Collection;\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.core.CredentialsContainer;\nimport org.springframework.security.core.GrantedAuthority;\n/**\n * Kauth에서 사용하는 {@link Authentication} 구현 클래스\n * @author ChangEn Yea\n */\npublic class AuthenticationProvider implements Authentication, CredentialsContainer {", "score": 0.8041428327560425 }, { "filename": "src/main/java/org/swmaestro/kauth/authentication/AuthenticationProvider.java", "retrieved_chunk": "\t */\n\tpublic AuthenticationProvider(Object principal, Object details,\n\t\tCollection<? extends GrantedAuthority> authorities) {\n\t\tthis.principal = principal;\n\t\tthis.details = details;\n\t\tthis.authorities = authorities;\n\t}\n\t/**\n\t * principal과 credential로 인스턴스를 생성한다.\n\t * @param principal {@link Object}", "score": 0.8005567789077759 }, { "filename": "src/main/java/org/swmaestro/kauth/authentication/AuthenticationProvider.java", "retrieved_chunk": "\t * @return {@link Authentication}의 {@link #principal}\n\t */\n\t@Override\n\tpublic Object getPrincipal() {\n\t\treturn this.principal;\n\t}\n\t/**\n\t * 인증 여부를 반환한다.\n\t * @return {@link Authentication}의 인증 여부\n\t */", "score": 0.796026885509491 }, { "filename": "src/main/java/org/swmaestro/kauth/core/user/PostAuthenticationService.java", "retrieved_chunk": "\t * @return 비밀번호 틀린 횟수. (-1 이면 틀린 횟수를 알려주지 않는다)\n\t */\n\tdefault Integer handleBadCredentialsException(String username) {\n\t\treturn -1;\n\t}\n\t/**\n\t * 인증 성공 후 호출되는 추가적인 처리를 위한 메서드\n\t * @param userDetails {@link UserDetails}\n\t */\n\tdefault void handleSuccessfulAuthentication(UserDetails userDetails) {", "score": 0.792757511138916 } ]
java
user = userDetailsService.loadUserByUsername((String)auth.getPrincipal());
package com.upCycle.service; import com.upCycle.dto.request.DtoEcoproveedor; import com.upCycle.dto.response.DtoEcoproveedorResponse; import com.upCycle.entity.Ecoproveedor; import com.upCycle.entity.Producto; import com.upCycle.entity.Usuario; import com.upCycle.exception.UserAlreadyExistException; import com.upCycle.exception.UserNotExistException; import com.upCycle.mapper.EcoproveedorMapper; import com.upCycle.repository.UsuarioRepository; import jakarta.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Optional; @Service public class EcoproveedorService { private final UsuarioRepository repository; private final EcoproveedorMapper ecoproveedorMapper; @Autowired public EcoproveedorService(UsuarioRepository repository, EcoproveedorMapper ecoproveedorMapper) { this.repository = repository; this.ecoproveedorMapper = ecoproveedorMapper; } public DtoEcoproveedorResponse registrarEcoproveedor(DtoEcoproveedor dtoEcoproveedor, HttpSession session) throws UserAlreadyExistException { Optional<Usuario> usuario = repository.findByEmail(dtoEcoproveedor.getEmail()); if(usuario.isPresent()){ throw new UserAlreadyExistException("El usuario ya existe"); } Ecoproveedor user = repository.save(ecoproveedorMapper.dtoEcoproveedorAEntidad(dtoEcoproveedor)); session.setAttribute("usuarioLogueado", user); return ecoproveedorMapper.entidadADtoEcoproveedor(user); } public void guardarProducto(Ecoproveedor ecoproveedor, Producto producto){ ecoproveedor.getListaProductos().add(producto); int puntos =
ecoproveedor.calcularPuntosTotales();
ecoproveedor.setPuntos(puntos); //repository.save(ecoproveedor); } public Integer getEcopuntos(HttpSession session) throws UserNotExistException { Usuario usuario = (Usuario) session.getAttribute("usuarioLogueado"); Ecoproveedor ecoproveedor = repository.buscarEcoproveedorPorId(usuario.getId()).orElseThrow(() -> new UserNotExistException("El usuario no existe")); return ecoproveedor.getPuntos(); } }
backend/src/main/java/com/upCycle/service/EcoproveedorService.java
No-Country-c11-19-m-javareact-cf62efa
[ { "filename": "backend/src/main/java/com/upCycle/service/ProductoService.java", "retrieved_chunk": " this.usuarioRepository = usuarioRepository;\n this.ubicacionService = ubicacionService;\n this.ecoproveedorService = ecoproveedorService;\n }\n public DtoProductoResponse crearProducto(DtoProducto dtoProducto, HttpSession session) throws UserUnauthorizedException, UserNotExistException {\n Optional<Usuario> oUser = usuarioRepository.findById(dtoProducto.getIdEcoproveedor());\n if(oUser.isEmpty()){\n return null;\n }\n Usuario user = oUser.get();", "score": 0.917282223701477 }, { "filename": "backend/src/main/java/com/upCycle/service/ProductoService.java", "retrieved_chunk": " Ubicacion ubicacion = ubicacionService.buscarPorNombre(dtoProducto.getLocation());\n producto.setEcoproveedor(ecoproveedor);\n producto.setUbicacion(ubicacion);\n ecoproveedorService.guardarProducto(ecoproveedor, producto);\n mapper.entidadADtoProducto(repository.save(producto));\n return mapper.entidadADtoProducto(producto);\n }\n public void eliminarProducto(Long id, HttpSession session) throws UserUnauthorizedException, UserNotExistException {\n Usuario logueado = (Usuario) session.getAttribute(\"usuarioLogueado\");\n if(Objects.isNull(logueado)){", "score": 0.9153642654418945 }, { "filename": "backend/src/main/java/com/upCycle/service/ProductoService.java", "retrieved_chunk": " //Ecoproveedor ecoproveedor = usuarioRepository.buscarEcoproveedorPorId(dtoProducto.getIdEcoproveedor()).orElseThrow(() -> new UserNotExistException(\"El usuario no existe\"));\n Optional<Ecoproveedor> oEcoproveedor = usuarioRepository.buscarEcoproveedorPorId(user.getId());\n if(oEcoproveedor.isEmpty()){\n return null;\n }\n Ecoproveedor ecoproveedor = oEcoproveedor.get();\n if(!ecoproveedor.getRol().equals(Rol.ECOPROVEEDOR)){\n throw new UserUnauthorizedException(\"Usuario no autorizado\");\n }\n Producto producto = mapper.DtoAentidadProducto(dtoProducto);", "score": 0.915217936038971 }, { "filename": "backend/src/main/java/com/upCycle/service/EcocreadorService.java", "retrieved_chunk": " }\n public DtoEcocreadorResponse registrarEcocreador(DtoEcocreador dtoEcocreador, HttpSession session) throws UserAlreadyExistException {\n Optional<Usuario> usuario = repository.findByEmail(dtoEcocreador.getEmail());\n if(usuario.isPresent()){\n throw new UserAlreadyExistException(\"El usuario ya existe\");\n }\n Ecocreador user = repository.save(ecocreadorMapper.dtoEcocreadorAEntidad(dtoEcocreador));\n session.setAttribute(\"usuarioLogueado\", user);\n return ecocreadorMapper.entidadADtoEcocreador(user);\n }", "score": 0.9077149629592896 }, { "filename": "backend/src/main/java/com/upCycle/mapper/EcoproveedorMapper.java", "retrieved_chunk": " ecoproveedor.setNombre(dtoEcoproveedor.getFirstName());\n ecoproveedor.setApellido(dtoEcoproveedor.getLastName());\n ecoproveedor.setCuit(dtoEcoproveedor.getCuit());\n ecoproveedor.setLogo(dtoEcoproveedor.getLogoImage());\n ecoproveedor.setEmail(dtoEcoproveedor.getEmail());\n ecoproveedor.setRol(Rol.ECOPROVEEDOR);\n ecoproveedor.setRazonSocial(dtoEcoproveedor.getCompanyName());\n ecoproveedor.setPassword(dtoEcoproveedor.getPassword());\n List<Producto> productos = new ArrayList<>();\n ecoproveedor.setListaProductos(productos);", "score": 0.9049765467643738 } ]
java
ecoproveedor.calcularPuntosTotales();
package org.swmaestro.kauth.authentication; import org.springframework.context.annotation.Lazy; import org.springframework.security.authentication.AccountStatusUserDetailsChecker; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsChecker; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; import org.swmaestro.kauth.core.user.PostAuthenticationService; import org.swmaestro.kauth.core.user.KauthUserDetailsService; /** * Username + Password를 사용하는 {@link AuthenticationManager} * @author ChangEn Yea */ @Lazy @Component public class UsernamePasswordAuthenticationManager implements AuthenticationManager { private final KauthUserDetailsService userDetailsService; private final PasswordEncoder passwordEncoder; private final UserDetailsChecker userDetailsChecker = new AccountStatusUserDetailsChecker(); /** * 인스턴스를 생성한다. * @param userDetailsService {@link KauthUserDetailsService} * @param passwordEncoder {@link PasswordEncoder} */ public UsernamePasswordAuthenticationManager(KauthUserDetailsService userDetailsService, PasswordEncoder passwordEncoder) { this.userDetailsService = userDetailsService; this.passwordEncoder = passwordEncoder; } /** * <pre> * {@link UserDetailsService#loadUserByUsername}를 호출해서 * {@link Authentication}의 credentials과 {@link UserDetails}의 password를 {@link PasswordEncoder#matches}를 통해 * 일치 여부를 확인한다. * 일치 한다면 {@link Authentication} 인스턴스를 인증 처리하고, credential를 삭제하고, 권한을 설정한다. * </pre> * @param authentication {@link Authentication} * @return 인증 처리 된 {@link Authentication} * @throws AuthenticationException */ @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { AuthenticationProvider auth = (AuthenticationProvider)authentication; UserDetails user = userDetailsService.loadUserByUsername((String)auth.getPrincipal()); if (user == null) { throw new UsernameNotFoundException("userDetailsService.loadUserByUsername returns null"); } // AccountStatusException 체크 userDetailsChecker.check(user); if (passwordEncoder.matches((String)auth.getCredentials(), user.getPassword())) { auth.setAuthenticated(true);
auth.eraseCredentials();
auth.setAuthorities(user.getAuthorities()); userDetailsService.handleSuccessfulAuthentication(user); return auth; } else { throw new BadCredentialsException("Password does not matches."); } } /** * {@link BadCredentialsException}을 처리하도록 * {@link PostAuthenticationService#handleBadCredentialsException}을 호출한다. * @param username * @return 비밀번호 틀린 횟수. (-1 이면 틀린 횟수를 알려주지 않는다) */ public Integer handleBadCredentialsException(String username) { return userDetailsService.handleBadCredentialsException(username); } }
src/main/java/org/swmaestro/kauth/authentication/UsernamePasswordAuthenticationManager.java
nsce9806q-k-spring-security-8e88d3d
[ { "filename": "src/main/java/org/swmaestro/kauth/authentication/AbstractUsernamePasswordAuthenticationFilter.java", "retrieved_chunk": "import org.springframework.security.core.userdetails.UsernameNotFoundException;\nimport org.springframework.security.web.util.matcher.AntPathRequestMatcher;\nimport org.swmaestro.kauth.dto.UsernamePasswordLoginRequest;\nimport org.swmaestro.kauth.util.HttpServletResponseUtil;\n/**\n * Kauth username + password 인증 추상 클래스 필터\n * @author ChangEn Yea\n */\npublic abstract class AbstractUsernamePasswordAuthenticationFilter extends AbstractAuthenticationFilter {\n\tprivate final UsernamePasswordAuthenticationManager authenticationManager;", "score": 0.8282550573348999 }, { "filename": "src/main/java/org/swmaestro/kauth/authentication/AbstractUsernamePasswordAuthenticationFilter.java", "retrieved_chunk": "\t\t\t// UserDetailsService에서 UserDetails를 찾을 수 없는 경우, 아이디+비밀번호 오류 메세지\n\t\t\tsuper.responseUtil.setUnauthorizedResponse(response, failed);\n\t\t} else if (failed.getClass().equals(BadCredentialsException.class)) {\n\t\t\tInteger passwordFailureCount = authenticationManager.handleBadCredentialsException(\n\t\t\t\tobjectMapper.readTree(request.getInputStream()).get(\"username\").asText());\n\t\t\tif (passwordFailureCount == -1) {\n\t\t\t\t// 비밀번호 오류 횟수 비공개, 아이디+비밀번호 오류 메세지\n\t\t\t\tsuper.responseUtil.setUnauthorizedResponse(response, failed);\n\t\t\t} else {\n\t\t\t\t// 비밀번호 틀린 횟수 + 비밀번호 오류 메세지", "score": 0.8242006301879883 }, { "filename": "src/main/java/org/swmaestro/kauth/core/user/PostAuthenticationService.java", "retrieved_chunk": "\t * @return 비밀번호 틀린 횟수. (-1 이면 틀린 횟수를 알려주지 않는다)\n\t */\n\tdefault Integer handleBadCredentialsException(String username) {\n\t\treturn -1;\n\t}\n\t/**\n\t * 인증 성공 후 호출되는 추가적인 처리를 위한 메서드\n\t * @param userDetails {@link UserDetails}\n\t */\n\tdefault void handleSuccessfulAuthentication(UserDetails userDetails) {", "score": 0.8223644495010376 }, { "filename": "src/main/java/org/swmaestro/kauth/authentication/AbstractUsernamePasswordAuthenticationFilter.java", "retrieved_chunk": "\t * @throws AuthenticationException 로그인 오류(아이디, 비밀번호 오류 등), 계정 잠김 등 인증 실패 시\n\t */\n\t@Override\n\tpublic Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)\n\t\tthrows AuthenticationException {\n\t\ttry {\n\t\t\tUsernamePasswordLoginRequest loginRequest = objectMapper\n\t\t\t\t.readValue(request.getInputStream(), UsernamePasswordLoginRequest.class);\n\t\t\treturn this.authenticationManager.authenticate(new AuthenticationProvider(\n\t\t\t\tloginRequest.getUsername(), loginRequest.getPassword()));", "score": 0.8205564618110657 }, { "filename": "src/test/java/org/swmaestro/kauth/showcase/UserLoginWithJwtTests.java", "retrieved_chunk": "import org.springframework.security.core.userdetails.User;\nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.security.core.userdetails.UserDetailsService;\nimport org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;\nimport org.springframework.security.provisioning.InMemoryUserDetailsManager;\nimport org.springframework.security.web.SecurityFilterChain;\nimport org.springframework.test.context.ContextConfiguration;\nimport org.springframework.test.context.junit.jupiter.SpringExtension;\nimport org.springframework.test.context.web.WebAppConfiguration;\nimport org.springframework.test.web.servlet.MockMvc;", "score": 0.8202309012413025 } ]
java
auth.eraseCredentials();
package committee.nova.flotage.datagen; import committee.nova.flotage.init.BlockRegistry; import committee.nova.flotage.util.BlockMember; import committee.nova.flotage.util.WorkingMode; import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput; import net.fabricmc.fabric.api.datagen.v1.provider.FabricLanguageProvider; public class FloLangProvider { public static class English extends FabricLanguageProvider { public English(FabricDataOutput dataOutput) { super(dataOutput); } @Override public void generateTranslations(TranslationBuilder builder) { builder.add("itemGroup.flotage.tab", "Flotage"); builder.add("modmenu.descriptionTranslation.flotage", "Survive on the sea!"); builder.add("tip.flotage.rack.processtime", "%s second(s) processing"); builder.add("tip.flotage.rack.mode", "Current Condition: "); builder.add("block.flotage.rack", "Rack Processing"); builder.add("config.jade.plugin_flotage.rack_blockentity", "Rack Working Mode"); builder.add("emi.category.flotage.rack", "Rack Processing"); for (WorkingMode mode : WorkingMode.values()) { builder.add("tip.flotage.rack.mode." + mode.toString(), beautifyName(mode.toString())); } for (BlockMember member : BlockMember.values()) { builder.add(BlockRegistry.get(member.raft()), beautifyName(member.raft())); builder.add(BlockRegistry.get(member.brokenRaft()), beautifyName(member.brokenRaft())); builder.add(BlockRegistry.get(member.fence()), beautifyName(member.fence())); builder.add(BlockRegistry.get(member.crossedFence()), beautifyName(member.crossedFence())); builder.add(BlockRegistry.get(member.rack()), beautifyName(member.rack())); } } } public static class Chinese extends FabricLanguageProvider { public Chinese(FabricDataOutput dataOutput) { super(dataOutput, "zh_cn"); } @Override public void generateTranslations(TranslationBuilder builder) { builder.add("itemGroup.flotage.tab", "漂浮物"); builder.add("modmenu.descriptionTranslation.flotage", "生存于大海之上!"); builder.add("tip.flotage.rack.processtime", "需要处理 %s 秒。"); builder.add("tip.flotage.rack.mode", "当前处理条件:"); builder.add("block.flotage.rack", "置物架"); builder.add("config.jade.plugin_flotage.rack_blockentity", "置物架模式"); builder.add("emi.category.flotage.rack", "置物架"); builder.add("tip.flotage.rack.mode.unconditional", "无条件"); builder.add("tip.flotage.rack.mode.sun", "白天"); builder.add("tip.flotage.rack.mode.night", "夜晚"); builder.add("tip.flotage.rack.mode.rain", "雨天"); builder.add("tip.flotage.rack.mode.snow", "雪天"); builder.add("tip.flotage.rack.mode.rain_at", "淋雨"); builder.add("tip.flotage.rack.mode.snow_at", "淋雪"); builder.add("tip.flotage.rack.mode.smoke", "烟熏"); for (BlockMember member : BlockMember.values()) { builder.add(BlockRegistry.get(member.raft()), member.chinese + "筏");
builder.add(BlockRegistry.get(member.brokenRaft()), "损坏的" + member.chinese + "筏");
builder.add(BlockRegistry.get(member.fence()), "简易" + member.chinese + "栅栏"); builder.add(BlockRegistry.get(member.crossedFence()), member.chinese + "十字栅栏"); builder.add(BlockRegistry.get(member.rack()), member.chinese + "置物架"); } } } public static String beautifyName(String name) { String[] str1 = name.split("_"); StringBuilder str2 = new StringBuilder(); for(int i = 0 ; i < str1.length; i++) { str1[i] = str1[i].substring(0,1).toUpperCase() + str1[i].substring(1); if(i == str1.length-1) str2.append(str1[i]); else str2.append(str1[i]).append(" "); } return str2.toString(); } }
src/main/java/committee/nova/flotage/datagen/FloLangProvider.java
Nova-Committee-Flotage-Fabric-6478e2a
[ { "filename": "src/main/java/committee/nova/flotage/datagen/FloBlockTagProvider.java", "retrieved_chunk": " FabricTagProvider<Block>.FabricTagBuilder rack = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"rack\")));\n FabricTagProvider<Block>.FabricTagBuilder fence = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"fence\")));\n FabricTagProvider<Block>.FabricTagBuilder crossedFence = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"crossed_fence\")));\n FabricTagProvider<Block>.FabricTagBuilder raft = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"raft\")));\n FabricTagProvider<Block>.FabricTagBuilder brokenRaft = this.getOrCreateTagBuilder(TagKey.of(Registries.BLOCK.getKey(), Flotage.id(\"broken_raft\")));\n for (BlockMember member : BlockMember.values()){\n rack.add(BlockRegistry.get(member.rack()));\n fence.add(BlockRegistry.get(member.fence()));\n crossedFence.add(BlockRegistry.get(member.crossedFence()));\n raft.add(BlockRegistry.get(member.raft()));", "score": 0.860447108745575 }, { "filename": "src/main/java/committee/nova/flotage/datagen/FloModelProvider.java", "retrieved_chunk": " Block rack = BlockRegistry.get(member.rack());\n itemGenerator.register(raft.asItem(), itemModel(raft));\n itemGenerator.register(brokenRaft.asItem(), itemModel(brokenRaft));\n itemGenerator.register(rack.asItem(), itemModel(rack));\n }\n private static void member(BlockMember member) {\n Block raft = BlockRegistry.get(member.raft());\n Block brokenRaft = BlockRegistry.get(member.brokenRaft());\n Block rack = BlockRegistry.get(member.rack());\n blockGenerator.registerSingleton(raft, memberTexture(member), model(\"raft\"));", "score": 0.8532102108001709 }, { "filename": "src/main/java/committee/nova/flotage/datagen/FloBlockTagProvider.java", "retrieved_chunk": " brokenRaft.add(BlockRegistry.get(member.brokenRaft()));\n }\n for (BlockMember member : BlockMember.values()) {\n axe.add(BlockRegistry.get(member.crossedFence()));\n axe.add(BlockRegistry.get(member.fence()));\n axe.add(BlockRegistry.get(member.raft()));\n axe.add(BlockRegistry.get(member.brokenRaft()));\n axe.add(BlockRegistry.get(member.rack()));\n }\n }", "score": 0.8464258909225464 }, { "filename": "src/main/java/committee/nova/flotage/init/ItemRegistry.java", "retrieved_chunk": " public static void register() {\n for (BlockMember member : BlockMember.values()) {\n raftItem(member.raft(), settings());\n raftItem(member.brokenRaft(), settings());\n blockItem(member.fence(), settings());\n blockItem(member.crossedFence(), settings());\n blockItem(member.rack(), settings());\n }\n }\n private static void blockItem(String id, Item.Settings settings) {", "score": 0.8460540771484375 }, { "filename": "src/main/java/committee/nova/flotage/datagen/FloBlockLootProvider.java", "retrieved_chunk": " }\n @Override\n public void generate() {\n for (BlockMember member : BlockMember.values()) {\n addDrop(BlockRegistry.get(member.raft()));\n addDrop(BlockRegistry.get(member.brokenRaft()), member.repairBlock.asItem());\n addDrop(BlockRegistry.get(member.fence()));\n addDrop(BlockRegistry.get(member.crossedFence()), drops(ItemRegistry.get(member.fence()), ConstantLootNumberProvider.create(2f)));\n addDrop(BlockRegistry.get(member.rack()));\n }", "score": 0.8431735634803772 } ]
java
builder.add(BlockRegistry.get(member.brokenRaft()), "损坏的" + member.chinese + "筏");
package com.orangomango.chess; import javafx.scene.paint.Color; import java.util.*; import java.text.SimpleDateFormat; import java.util.stream.Collectors; public class Board{ private Piece[][] board; private boolean blackRightCastleAllowed = true, whiteRightCastleAllowed = true; private boolean blackLeftCastleAllowed = true, whiteLeftCastleAllowed = true; private List<Piece> blackCaptured = new ArrayList<>(); private List<Piece> whiteCaptured = new ArrayList<>(); private int whiteExtraMaterial, blackExtraMaterial; private List<Piece> whiteChecks = new ArrayList<>(); private List<Piece> blackChecks = new ArrayList<>(); private Piece whiteKing, blackKing; private Color player = Color.WHITE; private int fifty = 0, movesN = 1; private String enPassant = null; private boolean[] canCastle = new boolean[4]; private Map<String, Integer> states = new HashMap<>(); private List<String> moves = new ArrayList<>(); public String playerA = System.getProperty("user.name"), playerB = "BLACK"; private volatile long whiteTime, blackTime; private long lastTime, gameTime; private int increment; public Board(String fen, long time, int increment){ this.board = new Piece[8][8]; setupBoard(fen); this.gameTime = time; this.increment = increment; this.whiteTime = time; this.blackTime = time; this.lastTime = System.currentTimeMillis(); } public void tick(){ if (this.movesN == 1){ this.lastTime = System.currentTimeMillis(); return; } long time = System.currentTimeMillis()-this.lastTime; if (this.player == Color.WHITE){ this.whiteTime -= time; } else { this.blackTime -= time; } this.whiteTime = Math.max(this.whiteTime, 0); this.blackTime = Math.max(this.blackTime, 0); this.lastTime = System.currentTimeMillis(); } public long getGameTime(){ return this.gameTime; } public int getIncrementTime(){ return this.increment; } private void setupBoard(String fen){ String[] data = fen.split(" "); this.whiteKing = null; this.blackKing = null; int r = 0; for (String row : data[0].split("/")){ char[] p = row.toCharArray(); int pos = 0; for (int i = 0; i < 8; i++){ try { int n = Integer.parseInt(Character.toString(p[pos])); i += n-1; } catch (NumberFormatException ex){ Piece piece = new Piece(Piece.getType(String.valueOf(p[pos])), Character.isUpperCase(p[pos]) ? Color.WHITE : Color.BLACK, i, r); this.board[i][r] = piece; if (piece.getType().getName() == Piece.PIECE_KING){ if (piece.getColor() == Color.WHITE){ this.whiteKing = piece; } else { this.blackKing = piece; } } } pos++; } r++; } this.player = data[1].equals("w") ? Color.WHITE : Color.BLACK; char[] c = data[2].toCharArray(); for (int i = 0; i < c.length; i++){ if (i == 0 && String.valueOf(c[i]).equals("-")){ this.whiteLeftCastleAllowed = false; this.whiteRightCastleAllowed = false; if (c.length == 1){ this.blackLeftCastleAllowed = false; this.blackRightCastleAllowed = false; } } else if (String.valueOf(c[i]).equals("-")){ this.blackLeftCastleAllowed = false; this.blackRightCastleAllowed = false; } else { String d = String.valueOf(c[i]); if (d.equals("Q")) this.whiteLeftCastleAllowed = true; if (d.equals("K")) this.whiteRightCastleAllowed = true; if (d.equals("q")) this.blackLeftCastleAllowed = true; if (d.equals("k")) this.blackRightCastleAllowed = true; } } this.canCastle[0] = canCastleLeft(Color.WHITE); this.canCastle[1] = canCastleRight(Color.WHITE); this.canCastle[2] = canCastleLeft(Color.BLACK); this.canCastle[3] = canCastleRight(Color.BLACK); String ep = String.valueOf(data[3]); if (!ep.equals("-")) this.enPassant = ep; this.fifty = Integer.parseInt(String.valueOf(data[4])); this.movesN = Integer.parseInt(String.valueOf(data[5])); this.states.clear(); this.states.put(getFEN().split(" ")[0], 1); setupCaptures(Color.WHITE); setupCaptures(Color.BLACK); this.blackChecks.clear(); this.whiteChecks.clear(); for (Piece boardPiece : getPiecesOnBoard()){ List<String> newLegalMoves = getLegalMoves(boardPiece); if (boardPiece.getColor() == Color.WHITE && newLegalMoves.contains(convertPosition(this.blackKing.getX(), this.blackKing.getY()))){ this.blackChecks.add(boardPiece); } else if (boardPiece.getColor() == Color.BLACK && newLegalMoves.contains(convertPosition(this.whiteKing.getX(), this.whiteKing.getY()))){ this.whiteChecks.add(boardPiece); } } if (this.whiteKing == null || this.blackKing == null) throw new IllegalStateException("Missing king"); if (getAttackers(this.player == Color.WHITE ? this.blackKing : this.whiteKing) != null) throw new IllegalStateException("King is in check"); } private void setupCaptures(Color color){ List<Piece> pieces = getPiecesOnBoard().stream().filter(piece -> piece.getColor() == color).toList(); List<Piece> captures = color == Color.WHITE ? this.blackCaptured : this.whiteCaptured; int pawns = (int)pieces
.stream().filter(piece -> piece.getType().getName() == Piece.PIECE_PAWN).count();
int rooks = (int)pieces.stream().filter(piece -> piece.getType().getName() == Piece.PIECE_ROOK).count(); int knights = (int)pieces.stream().filter(piece -> piece.getType().getName() == Piece.PIECE_KNIGHT).count(); int bishops = (int)pieces.stream().filter(piece -> piece.getType().getName() == Piece.PIECE_BISHOP).count(); int queens = (int)pieces.stream().filter(piece -> piece.getType().getName() == Piece.PIECE_QUEEN).count(); for (int i = 0; i < 8-pawns; i++){ captures.add(new Piece(Piece.Pieces.PAWN, color, -1, -1)); } for (int i = 0; i < 2-rooks; i++){ captures.add(new Piece(Piece.Pieces.ROOK, color, -1, -1)); } for (int i = 0; i < 2-knights; i++){ captures.add(new Piece(Piece.Pieces.KNIGHT, color, -1, -1)); } for (int i = 0; i < 2-bishops; i++){ captures.add(new Piece(Piece.Pieces.BISHOP, color, -1, -1)); } if (queens == 0){ captures.add(new Piece(Piece.Pieces.QUEEN, color, -1, -1)); } for (int i = 0; i < -(2-rooks); i++){ capture(new Piece(Piece.Pieces.PAWN, color, -1, -1)); promote(color, Piece.Pieces.ROOK); } for (int i = 0; i < -(2-knights); i++){ capture(new Piece(Piece.Pieces.PAWN, color, -1, -1)); promote(color, Piece.Pieces.KNIGHT); } for (int i = 0; i < -(2-bishops); i++){ capture(new Piece(Piece.Pieces.PAWN, color, -1, -1)); promote(color, Piece.Pieces.BISHOP); } for (int i = 0; i < -(1-queens); i++){ capture(new Piece(Piece.Pieces.PAWN, color, -1, -1)); promote(color, Piece.Pieces.QUEEN); } } public int getMovesN(){ return this.movesN; } public List<String> getMoves(){ return this.moves; } public boolean move(String pos1, String pos, String prom){ if (pos1 == null || pos == null) return false; int[] p1 = convertNotation(pos1); Piece piece = this.board[p1[0]][p1[1]]; if (piece == null || piece.getColor() != this.player) return false; List<String> legalMoves = getLegalMoves(piece); if (legalMoves.contains(pos)){ int[] p2 = convertNotation(pos); Piece[][] backup = createBackup(); List<Piece> identical = new ArrayList<>(); for (Piece p : getPiecesOnBoard()){ if (p != piece && p.getType() == piece.getType() && p.getColor() == piece.getColor()){ if (getValidMoves(p).contains(pos)) identical.add(p); } } Piece capture = this.board[p2[0]][p2[1]]; if (this.enPassant != null && pos.equals(this.enPassant)){ capture = this.board[p2[0]][p1[1]]; this.board[capture.getX()][capture.getY()] = null; } this.board[p1[0]][p1[1]] = null; setPiece(piece, p2[0], p2[1]); if (getAttackers(piece.getColor() == Color.WHITE ? this.whiteKing : this.blackKing) != null){ restoreBackup(backup); return false; } if (capture != null) capture(capture); boolean castle = false; if (piece.getType().getName() == Piece.PIECE_KING){ if (Math.abs(p2[0]-p1[0]) == 2){ if (p2[0] == 6){ castleRight(piece.getColor()); castle = true; } else if (p2[0] == 2){ castleLeft(piece.getColor()); castle = true; } } if (piece.getColor() == Color.WHITE){ this.whiteRightCastleAllowed = false; this.whiteLeftCastleAllowed = false; } else { this.blackRightCastleAllowed = false; this.blackLeftCastleAllowed = false; } } if (piece.getType().getName() == Piece.PIECE_ROOK){ if (piece.getColor() == Color.WHITE){ if (this.whiteRightCastleAllowed && p1[0] == 7){ this.whiteRightCastleAllowed = false; } else if (this.whiteLeftCastleAllowed && p1[0] == 0){ this.whiteLeftCastleAllowed = false; } } else { if (this.blackRightCastleAllowed && p1[0] == 7){ this.blackRightCastleAllowed = false; } else if (this.blackLeftCastleAllowed && p1[0] == 0){ this.blackLeftCastleAllowed = false; } } } if (piece.getType().getName() == Piece.PIECE_PAWN){ this.fifty = 0; if ((piece.getColor() == Color.WHITE && piece.getY() == 0) || (piece.getColor() == Color.BLACK && piece.getY() == 7)){ Piece.Pieces promotion = Piece.getType(prom); this.board[piece.getX()][piece.getY()] = new Piece(promotion, piece.getColor(), piece.getX(), piece.getY()); capture(piece); promote(piece.getColor(), promotion); } if (Math.abs(p2[1]-p1[1]) == 2){ this.enPassant = convertPosition(piece.getX(), piece.getColor() == Color.WHITE ? piece.getY()+1 : piece.getY()-1); } else { this.enPassant = null; } } else { this.fifty++; this.enPassant = null; } this.canCastle[0] = canCastleLeft(Color.WHITE); this.canCastle[1] = canCastleRight(Color.WHITE); this.canCastle[2] = canCastleLeft(Color.BLACK); this.canCastle[3] = canCastleRight(Color.BLACK); this.blackChecks.clear(); this.whiteChecks.clear(); boolean check = false; for (Piece boardPiece : getPiecesOnBoard()){ List<String> newLegalMoves = getLegalMoves(boardPiece); if (boardPiece.getColor() == Color.WHITE && newLegalMoves.contains(convertPosition(this.blackKing.getX(), this.blackKing.getY()))){ this.blackChecks.add(boardPiece); check = true; } else if (boardPiece.getColor() == Color.BLACK && newLegalMoves.contains(convertPosition(this.whiteKing.getX(), this.whiteKing.getY()))){ this.whiteChecks.add(boardPiece); check = true; } } if (check){ MainApplication.playSound(MainApplication.CHECK_SOUND); } if (this.movesN > 1){ if (this.player == Color.WHITE){ this.whiteTime += this.increment*1000; } else { this.blackTime += this.increment*1000; } } if (this.player == Color.BLACK) this.movesN++; this.player = this.player == Color.WHITE ? Color.BLACK : Color.WHITE; String fen = getFEN().split(" ")[0]; this.states.put(fen, this.states.getOrDefault(fen, 0)+1); this.moves.add(moveToString(piece, pos1, pos, check, capture != null, prom, castle, identical)); if (capture != null){ MainApplication.playSound(MainApplication.CAPTURE_SOUND); } else if (castle){ MainApplication.playSound(MainApplication.CASTLE_SOUND); } else { MainApplication.playSound(MainApplication.MOVE_SOUND); } return true; } return false; } private String moveToString(Piece piece, String start, String pos, boolean check, boolean capture, String prom, boolean castle, List<Piece> identical){ int[] coord = convertNotation(start); String output = ""; if (piece.getType().getName() == Piece.PIECE_PAWN){ if (capture){ output = String.valueOf(start.charAt(0))+"x"+pos; } else { output = pos; } if (prom != null) output += "="+prom.toUpperCase(); } else if (castle){ output = piece.getX() == 2 ? "O-O-O" : "O-O"; } else { String extra = ""; if (identical.size() >= 2){ extra = start; } else if (identical.size() == 1){ Piece other = identical.get(0); if (coord[0] != other.getX()){ extra = String.valueOf(start.charAt(0)); } else if (coord[1] != other.getY()){ extra = String.valueOf(start.charAt(1)); } } output = piece.getType().getName().toUpperCase()+extra+(capture ? "x" : "")+pos; } if (isCheckMate(piece.getColor() == Color.WHITE ? Color.BLACK : Color.WHITE)){ output += "#"; } else if (check){ output += "+"; } return output; } public int getTime(Color color){ return color == Color.WHITE ? (int)this.whiteTime : (int)this.blackTime; } public void castleRight(Color color){ int ypos = color == Color.WHITE ? 7 : 0; Piece king = color == Color.WHITE ? this.whiteKing : this.blackKing; Piece rook = this.board[7][ypos]; if (canCastleRight(color)){ this.board[rook.getX()][rook.getY()] = null; setPiece(rook, king.getX()-1, king.getY()); } } public void castleLeft(Color color){ int ypos = color == Color.WHITE ? 7 : 0; Piece king = color == Color.WHITE ? this.whiteKing : this.blackKing; Piece rook = this.board[0][ypos]; if (canCastleLeft(color)){ this.board[rook.getX()][rook.getY()] = null; setPiece(rook, king.getX()+1, king.getY()); } } private boolean canCastleRight(Color color){ boolean moved = color == Color.WHITE ? this.whiteRightCastleAllowed : this.blackRightCastleAllowed; return moved && getAttackers(color == Color.WHITE ? this.whiteKing : this.blackKing) == null && canCastle(new int[]{5, 6}, new int[]{5, 6}, color); } private boolean canCastleLeft(Color color){ boolean moved = color == Color.WHITE ? this.whiteLeftCastleAllowed : this.blackLeftCastleAllowed; return moved && getAttackers(color == Color.WHITE ? this.whiteKing : this.blackKing) == null && canCastle(new int[]{2, 3}, new int[]{1, 2, 3}, color); } private boolean canCastle(int[] xpos, int[] checkXpos, Color color){ int ypos = color == Color.WHITE ? 7 : 0; Piece king = color == Color.WHITE ? this.whiteKing : this.blackKing; for (int i = 0; i < xpos.length; i++){ if (this.board[xpos[i]][ypos] != null && this.board[xpos[i]][ypos].getType().getName() != Piece.PIECE_KING) return false; } Piece[][] backup = createBackup(); for (int i = 0; i < checkXpos.length; i++){ this.board[king.getX()][king.getY()] = null; setPiece(king, checkXpos[i], ypos); if (getAttackers(king) != null){ restoreBackup(backup); return false; } restoreBackup(backup); } return true; } public List<String> getValidMoves(Piece piece){ List<String> legalMoves = getLegalMoves(piece); List<String> validMoves = new ArrayList<>(); if (piece.getColor() != this.player) return validMoves; Piece[][] backup = createBackup(); for (String move : legalMoves){ int[] pos = convertNotation(move); int oldY = piece.getY(); this.board[piece.getX()][oldY] = null; setPiece(piece, pos[0], pos[1]); if (move.equals(this.enPassant)){ int x = convertNotation(this.enPassant)[0]; this.board[x][oldY] = null; } if (getAttackers(piece.getColor() == Color.WHITE ? this.whiteKing : this.blackKing) == null){ restoreBackup(backup); validMoves.add(move); } else { restoreBackup(backup); } } return validMoves; } private List<String> getLegalMoves(Piece piece){ List<String> result = new ArrayList<>(); int extraMove = 0; if (piece.getType().getName() == Piece.PIECE_PAWN){ if ((piece.getColor() == Color.WHITE && piece.getY() == 6) || (piece.getColor() == Color.BLACK && piece.getY() == 1)){ extraMove = 1; } int factor = piece.getColor() == Color.WHITE ? -1 : 1; String not1 = convertPosition(piece.getX()-1, piece.getY()+factor); String not2 = convertPosition(piece.getX()+1, piece.getY()+factor); if (not1 != null && this.board[piece.getX()-1][piece.getY()+factor] != null && this.board[piece.getX()-1][piece.getY()+factor].getColor() != piece.getColor()) result.add(not1); if (not2 != null && this.board[piece.getX()+1][piece.getY()+factor] != null && this.board[piece.getX()+1][piece.getY()+factor].getColor() != piece.getColor()) result.add(not2); // En passant if (this.enPassant != null && piece.getY() == convertNotation(this.enPassant)[1]+(piece.getColor() == Color.WHITE ? 1 : -1) && Math.abs(piece.getX()-convertNotation(this.enPassant)[0]) == 1){ result.add(this.enPassant); } } if (piece.getType().getName() == Piece.PIECE_KING){ if ((piece.getColor() == Color.WHITE && this.canCastle[0]) || (piece.getColor() == Color.BLACK && this.canCastle[2])){ result.add(convertPosition(piece.getX()-2, piece.getY())); } if ((piece.getColor() == Color.WHITE && this.canCastle[1]) || (piece.getColor() == Color.BLACK && this.canCastle[3])){ result.add(convertPosition(piece.getX()+2, piece.getY())); } } int[] dir = piece.getType().getDirections(); for (int i = 0; i < dir.length; i++){ int[][] comb = null; if (dir[i] == Piece.MOVE_DIAGONAL){ comb = new int[][]{{1, -1}, {1, 1}, {-1, 1}, {-1, -1}}; } else if (dir[i] == Piece.MOVE_HORIZONTAL){ comb = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; } else if (dir[i] == Piece.MOVE_KNIGHT){ comb = new int[][]{{-2, -1}, {-1, -2}, {2, -1}, {1, -2}, {1, 2}, {2, 1}, {-1, 2}, {-2, 1}}; } if (comb != null){ for (int c = 0; c < comb.length; c++){ for (int j = 1; j <= piece.getType().getAmount()+extraMove; j++){ int x = piece.getX()+comb[c][0]*j; int y = piece.getY()+comb[c][1]*j; if (piece.getType().getName() == Piece.PIECE_PAWN){ if (x != piece.getX() || (piece.getColor() == Color.WHITE && y > piece.getY()) || (piece.getColor() == Color.BLACK && y < piece.getY())){ continue; } } Piece captured = getPieceAt(x, y); String not = convertPosition(x, y); if (not != null && (captured == null || captured.getColor() != piece.getColor())){ if (captured == null || piece.getType().getName() != Piece.PIECE_PAWN || captured.getX() != piece.getX()){ result.add(not); } } if (captured != null){ break; } } } } } return result; } private Piece getPieceAt(int x, int y){ if (x >= 0 && y >= 0 && x < 8 && y < 8){ return this.board[x][y]; } else { return null; } } private void capture(Piece piece){ if (piece.getColor() == Color.WHITE){ this.blackCaptured.add(piece); } else { this.whiteCaptured.add(piece); } this.fifty = 0; } private void promote(Color color, Piece.Pieces type){ List<Piece> list = color == Color.BLACK ? this.whiteCaptured : this.blackCaptured; Iterator<Piece> iterator = list.iterator(); boolean removed = false; while (iterator.hasNext()){ Piece piece = iterator.next(); if (piece.getType() == type){ iterator.remove(); removed = true; break; } } if (!removed){ if (color == Color.WHITE){ this.whiteExtraMaterial += type.getValue(); } else { this.blackExtraMaterial += type.getValue(); } } } private List<Piece> getAttackers(Piece piece){ List<Piece> pieces = getPiecesOnBoard(); List<Piece> result = new ArrayList<>(); String pos = convertPosition(piece.getX(), piece.getY()); for (Piece boardPiece : pieces){ if (boardPiece.getColor() != piece.getColor() && getLegalMoves(boardPiece).contains(pos)){ result.add(boardPiece); } } return result.size() == 0 ? null : result; } private boolean canKingMove(Color color){ Piece king = color == Color.WHITE ? this.whiteKing : this.blackKing; Piece[][] backup = createBackup(); // Check if king has any legal moves for (int x = king.getX()-1; x < king.getX()+2; x++){ for (int y = king.getY()-1; y < king.getY()+2; y++){ if (x >= 0 && y >= 0 && x < 8 && y < 8){ Piece piece = this.board[x][y]; if (piece == null || piece.getColor() != king.getColor()){ this.board[king.getX()][king.getY()] = null; setPiece(king, x, y); if (getAttackers(king) == null){ restoreBackup(backup); return true; } else { restoreBackup(backup); } } } } } // If there is a single check, check if the piece can be captured or the ckeck can be blocked List<Piece> checks = king.getColor() == Color.WHITE ? this.whiteChecks : this.blackChecks; if (checks.size() == 1){ List<Piece> canCapture = getAttackers(checks.get(0)); if (canCapture != null){ for (Piece piece : canCapture){ this.board[piece.getX()][piece.getY()] = null; setPiece(piece, checks.get(0).getX(), checks.get(0).getY()); if (getAttackers(king) == null){ restoreBackup(backup); return true; } else { restoreBackup(backup); } } } else { List<String> legalMoves = getLegalMoves(checks.get(0)); List<Piece> pieces = getPiecesOnBoard(); for (Piece piece : pieces){ if (piece.getColor() == checks.get(0).getColor()) continue; Set<String> intersection = getLegalMoves(piece).stream().distinct().filter(legalMoves::contains).collect(Collectors.toSet()); List<String> allowed = new ArrayList<>(); for (String move : intersection){ int[] pos = convertNotation(move); this.board[piece.getX()][piece.getY()] = null; setPiece(piece, pos[0], pos[1]); if (getAttackers(piece.getColor() == Color.WHITE ? this.whiteKing : this.blackKing) == null){ restoreBackup(backup); allowed.add(move); } else { restoreBackup(backup); } } if (allowed.size() > 0){ return true; } } } } return false; } private Piece[][] createBackup(){ Piece[][] backup = new Piece[8][8]; for (int i = 0; i < 8; i++){ for (int j = 0; j < 8; j++){ backup[i][j] = this.board[i][j]; } } return backup; } private void restoreBackup(Piece[][] backup){ for (int i = 0; i < 8; i++){ for (int j = 0; j < 8; j++){ Piece piece = backup[i][j]; if (piece == null){ this.board[i][j] = null; } else { setPiece(piece, i, j); } } } } private List<Piece> getPiecesOnBoard(){ List<Piece> pieces = new ArrayList<>(); for (int i = 0; i < 8; i++){ for (int j = 0; j < 8; j++){ if (this.board[i][j] != null) pieces.add(this.board[i][j]); } } return pieces; } private void setPiece(Piece piece, int x, int y){ this.board[x][y] = piece; piece.setPos(x, y); } public static int[] convertNotation(String pos){ char[] c = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}; char[] data = pos.toCharArray(); int x = -1; for (int i = 0; i < 8; i++){ if (c[i] == data[0]){ x = i; break; } } int y = 8-Integer.parseInt(String.valueOf(data[1])); if (x < 0 || y < 0 || y > 7){ return null; } else { return new int[]{x, y}; } } public static String convertPosition(int x, int y){ char[] c = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}; if (x < 0 || y < 0 || x > 7 || y > 7){ return null; } else { return c[x]+Integer.toString(8-y); } } public List<Piece> getCheckingPieces(Color color){ if (color == Color.WHITE){ return this.whiteChecks; } else { return this.blackChecks; } } public Piece[][] getBoard(){ return this.board; } public String getPGN(){ StringBuilder builder = new StringBuilder(); SimpleDateFormat format = new SimpleDateFormat("YYYY/MM/dd"); Date date = new Date(); builder.append("[Event \""+String.format("%s vs %s", this.playerA, this.playerB)+"\"]\n"); builder.append("[Site \"com.orangomango.chess\"]\n"); builder.append("[Date \""+format.format(date)+"\"]\n"); builder.append("[Round \"1\"]\n"); builder.append("[White \""+this.playerA+"\"]\n"); builder.append("[Black \""+this.playerB+"\"]\n"); String result = "*"; if (isDraw()){ result = "½-½"; } else if (isCheckMate(Color.WHITE)){ result = "0-1"; } else if (isCheckMate(Color.BLACK)){ result = "1-0"; } builder.append("[Result \""+result+"\"]\n\n"); for (int i = 0; i < this.moves.size(); i++){ if (i % 2 == 0) builder.append((i/2+1)+". "); builder.append(this.moves.get(i)+" "); } builder.append(result); return builder.toString(); } public String getFEN(){ StringBuilder builder = new StringBuilder(); for (int i = 0; i < 8; i++){ int empty = 0; for (int j = 0; j < 8; j++){ Piece piece = this.board[j][i]; if (piece == null){ empty++; } else { if (empty > 0){ builder.append(empty); empty = 0; } builder.append(piece.getColor() == Color.WHITE ? piece.getType().getName().toUpperCase() : piece.getType().getName().toLowerCase()); } } if (empty > 0) builder.append(empty); if (i < 7) builder.append("/"); } builder.append(this.player == Color.WHITE ? " w " : " b "); boolean no = false; if (!this.whiteLeftCastleAllowed && !this.whiteRightCastleAllowed){ builder.append("-"); no = true; } else { if (this.whiteRightCastleAllowed) builder.append("K"); if (this.whiteLeftCastleAllowed) builder.append("Q"); } if (!this.blackLeftCastleAllowed && !this.blackRightCastleAllowed){ if (!no) builder.append("-"); } else { if (this.blackRightCastleAllowed) builder.append("k"); if (this.blackLeftCastleAllowed) builder.append("q"); } builder.append(" "); builder.append(String.format("%s %d %d", this.enPassant == null ? "-" : this.enPassant, this.fifty, this.movesN)); return builder.toString(); } private boolean isCheckMate(Color color){ Piece king = color == Color.WHITE ? this.whiteKing : this.blackKing; return getAttackers(king) != null && !canKingMove(color); } private boolean isDraw(){ if (this.fifty >= 50) return true; List<Piece> pieces = getPiecesOnBoard(); int whitePieces = pieces.stream().filter(piece -> piece.getColor() == Color.WHITE).mapToInt(p -> p.getType().getValue()).sum(); int blackPieces = pieces.stream().filter(piece -> piece.getColor() == Color.BLACK).mapToInt(p -> p.getType().getValue()).sum(); List<String> whiteLegalMoves = new ArrayList<>(); List<String> blackLegalMoves = new ArrayList<>(); for (Piece piece : pieces){ if (piece.getColor() == Color.WHITE){ whiteLegalMoves.addAll(getValidMoves(piece)); } else { blackLegalMoves.addAll(getValidMoves(piece)); } } boolean whiteDraw = whitePieces == 0 || (whitePieces == 3 && pieces.stream().filter(piece -> piece.getColor() == Color.WHITE).count() == 2); boolean blackDraw = blackPieces == 0 || (blackPieces == 3 && pieces.stream().filter(piece -> piece.getColor() == Color.BLACK).count() == 2); if (whiteDraw && blackDraw) return true; if ((getAttackers(this.blackKing) == null && !canKingMove(Color.BLACK) && blackLegalMoves.size() == 0 && this.player == Color.BLACK) || (getAttackers(this.whiteKing) == null && !canKingMove(Color.WHITE)) && whiteLegalMoves.size() == 0 && this.player == Color.WHITE){ return true; } if (this.states.values().contains(3)) return true; return false; } public String getBoardInfo(){ int whiteSum = getMaterial(Color.WHITE); int blackSum = getMaterial(Color.BLACK); return String.format("B:%d W:%d - BK:%s WK:%s - BCK:%s WCK:%s\nChecks: %s %s\n", blackSum, whiteSum, getAttackers(this.blackKing) != null, getAttackers(this.whiteKing) != null, isCheckMate(Color.BLACK), isCheckMate(Color.WHITE), this.blackChecks, this.whiteChecks); } public List<Piece> getMaterialList(Color color){ List<Piece> list = new ArrayList<>(color == Color.WHITE ? this.whiteCaptured : this.blackCaptured); list.sort((p1, p2) -> Integer.compare(p1.getType().getValue(), p2.getType().getValue())); return list; } public int getMaterial(Color color){ return getMaterialList(color).stream().mapToInt(p -> p.getType().getValue()).sum()+(color == Color.WHITE ? this.whiteExtraMaterial : this.blackExtraMaterial); } public Color getPlayer(){ return this.player; } public boolean isGameFinished(){ return isCheckMate(Color.WHITE) || isCheckMate(Color.BLACK) || isDraw() || this.whiteTime <= 0 || this.blackTime <= 0; } @Override public String toString(){ StringBuilder builder = new StringBuilder(); for (int i = 0; i < 8; i++){ // y for (int j = 0; j < 8; j++){ // x builder.append(this.board[j][i]+" "); } builder.append("\n"); } builder.append(getBoardInfo()); return builder.toString(); } }
src/main/java/com/orangomango/chess/Board.java
OrangoMango-Chess-c4bd8f5
[ { "filename": "src/main/java/com/orangomango/chess/MainApplication.java", "retrieved_chunk": "\t\t\t\t}\n\t\t\t\tif (piece != null){\n\t\t\t\t\tif (piece.getType().getName() == Piece.PIECE_KING){\n\t\t\t\t\t\tif ((piece.getColor() == Color.WHITE && this.board.getCheckingPieces(Color.WHITE).size() > 0) || (piece.getColor() == Color.BLACK && this.board.getCheckingPieces(Color.BLACK).size() > 0)){\n\t\t\t\t\t\t\tgc.setFill(Color.BLUE);\n\t\t\t\t\t\t\tgc.fillOval(pos.getX()*SQUARE_SIZE, pos.getY()*SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (piece != this.draggingPiece) gc.drawImage(piece.getImage(), pos.getX()*SQUARE_SIZE, pos.getY()*SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE);\n\t\t\t\t}", "score": 0.8017778992652893 }, { "filename": "src/main/java/com/orangomango/chess/MainApplication.java", "retrieved_chunk": "\t\tgc.save();\n\t\tfor (int i = 0; i < white.size(); i++){\n\t\t\tPiece piece = white.get(i);\n\t\t\tPiece prev = i == 0 ? null : white.get(i-1);\n\t\t\tif (i > 0) gc.translate(prev != null && prev.getType().getValue() == piece.getType().getValue() ? SQUARE_SIZE/4.0 : SQUARE_SIZE/2.0+SQUARE_SIZE/10.0, 0);\n\t\t\tgc.drawImage(piece.getImage(), WIDTH*0.05, this.viewPoint == Color.WHITE ? bd : wd, SQUARE_SIZE/2.0, SQUARE_SIZE/2.0);\n\t\t}\n\t\tgc.restore();\n\t\tfor (Map.Entry<String, List<String>> entry : this.hold.entrySet()){\n\t\t\tif (entry.getKey() == null || entry.getValue() == null) continue;", "score": 0.7962380051612854 }, { "filename": "src/main/java/com/orangomango/chess/MainApplication.java", "retrieved_chunk": "\t\t}\n\t\tif (this.currentMoves != null){\n\t\t\tfor (String move : this.currentMoves){\n\t\t\t\tint[] pos = Board.convertNotation(move);\n\t\t\t\tgc.setFill(this.board.getBoard()[pos[0]][pos[1]] == null ? Color.YELLOW : Color.BLUE);\n\t\t\t\tgc.fillOval((this.viewPoint == Color.BLACK ? 7-pos[0] : pos[0])*SQUARE_SIZE+SQUARE_SIZE/3.0, (this.viewPoint == Color.BLACK ? 7-pos[1] : pos[1])*SQUARE_SIZE+SQUARE_SIZE/3.0, SQUARE_SIZE/3.0, SQUARE_SIZE/3.0);\n\t\t\t}\n\t\t}\n\t\tif (this.draggingPiece != null){\n\t\t\tgc.drawImage(this.promotionPiece == null ? this.draggingPiece.getImage() : this.promotionPiece.getImage(), this.dragX-SQUARE_SIZE/2.0, this.dragY-SPACE-SQUARE_SIZE/2.0, SQUARE_SIZE, SQUARE_SIZE);", "score": 0.7901272773742676 }, { "filename": "src/main/java/com/orangomango/chess/MainApplication.java", "retrieved_chunk": "\t\tList<Piece> black = this.board.getMaterialList(Color.BLACK);\n\t\tList<Piece> white = this.board.getMaterialList(Color.WHITE);\n\t\tgc.save();\n\t\tfor (int i = 0; i < black.size(); i++){\n\t\t\tPiece piece = black.get(i);\n\t\t\tPiece prev = i == 0 ? null : black.get(i-1);\n\t\t\tif (i > 0) gc.translate(prev != null && prev.getType().getValue() == piece.getType().getValue() ? SQUARE_SIZE/4.0 : SQUARE_SIZE/2.0+SQUARE_SIZE/10.0, 0);\n\t\t\tgc.drawImage(piece.getImage(), WIDTH*0.05, this.viewPoint == Color.WHITE ? wd : bd, SQUARE_SIZE/2.0, SQUARE_SIZE/2.0);\n\t\t}\n\t\tgc.restore();", "score": 0.7855721712112427 }, { "filename": "src/main/java/com/orangomango/chess/MainApplication.java", "retrieved_chunk": "\tprivate static final String STARTPOS = \"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1\";\n\tprivate Board board;\n\tprivate Engine engine;\n\tprivate String currentSelection;\n\tprivate List<String> currentMoves;\n\tprivate volatile boolean gameFinished = false;\n\tprivate volatile String eval;\n\tprivate volatile PieceAnimation animation;\n\tprivate Color viewPoint;\n\tprivate boolean overTheBoard = true;", "score": 0.78440922498703 } ]
java
.stream().filter(piece -> piece.getType().getName() == Piece.PIECE_PAWN).count();