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": " }\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.8072570562362671
},
{
"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.8037907481193542
},
{
"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.7950769662857056
},
{
"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.7823620438575745
},
{
"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.7622138261795044
}
] | 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/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.7607153654098511
},
{
"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.7467052936553955
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " private boolean isAttack() {\n return rest.request(RequestType.GET_GAMESHIELD_ISUNDERATTACK, null, Config.getGameShieldID()).getResponseBody().equals(\"true\");\n }\n public String getPlan() {\n try {\n return rest.request(RequestType.GET_GAMESHIELD_PLAN, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject(\"gameShieldPlan\").getJSONObject(\"options\").getString(\"name\");\n }catch (Exception ignore){}\n return null;\n }\n private boolean updateStats(RequestBody requestBody, String gameshieldID, String backendID) {",
"score": 0.7418805956840515
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " Config.getGameShieldID());\n return true;\n }\n }\n public int toggle(String mode) {\n JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject(\"gameShieldSettings\");\n if(!settings.has(mode)) return -1;\n boolean mitigationSensitivity = settings.getBoolean(mode);\n if (mitigationSensitivity) {\n int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,",
"score": 0.7355552911758423
},
{
"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.7303177714347839
}
] | 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": " }\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.8157714605331421
},
{
"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.8132332563400269
},
{
"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.7902783155441284
},
{
"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.7731198668479919
},
{
"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.7708627581596375
}
] | 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, \"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.7645251750946045
},
{
"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.748596727848053
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java",
"retrieved_chunk": " return;\n VersionUtils.Result result = instance.getCore().getVersionResult();\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.OUTDATED)) {\n instance.sendMessage(player, localization.get(locale, 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()));",
"score": 0.7473065853118896
},
{
"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.746792197227478
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java",
"retrieved_chunk": " return;\n VersionUtils.Result result = instance.getCore().getVersionResult();\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.OUTDATED)) {\n 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()));",
"score": 0.7433537244796753
}
] | 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/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.7590124011039734
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " fileUtils.save();\n APIKey = key;\n }\n public static void setGameShieldID(String id) {\n fileUtils.set(\"gameshield.serverId\", id);\n fileUtils.save();\n gameShieldID = id;\n }\n public static void setBackendID(String id) {\n fileUtils.set(\"gameshield.backendId\", id);",
"score": 0.7571285963058472
},
{
"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.7289989590644836
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " private boolean isAttack() {\n return rest.request(RequestType.GET_GAMESHIELD_ISUNDERATTACK, null, Config.getGameShieldID()).getResponseBody().equals(\"true\");\n }\n public String getPlan() {\n try {\n return rest.request(RequestType.GET_GAMESHIELD_PLAN, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject(\"gameShieldPlan\").getJSONObject(\"options\").getString(\"name\");\n }catch (Exception ignore){}\n return null;\n }\n private boolean updateStats(RequestBody requestBody, String gameshieldID, String backendID) {",
"score": 0.7279752492904663
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " RequestBody.create(MediaType.parse(\"application/json\"), settings.put(mode, false).toString()),\n Config.getGameShieldID()).getCode();\n return code == 200 ? 0 : code;\n } else {\n int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,\n RequestBody.create(MediaType.parse(\"application/json\"), settings.put(mode, true).toString()),\n Config.getGameShieldID()).getCode();\n return code == 200 ? 1 : code;\n }\n }",
"score": 0.7226272821426392
}
] | 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/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.7406403422355652
},
{
"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.740021824836731
},
{
"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.7170578241348267
},
{
"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.711227536201477
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/Startup.java",
"retrieved_chunk": " register(instance);\n new ProxyProtocol(instance);\n }\n private void register(NeoProtectBungee instance) {\n PluginManager pm = ProxyServer.getInstance().getPluginManager();\n pm.registerCommand(instance, new NeoProtectCommand(instance, \"neoprotect\", \"neoprotect.admin\", \"np\"));\n pm.registerListener(instance, new ChatListener(instance));\n pm.registerListener(instance, new LoginListener(instance));\n pm.registerListener(instance, new DisconnectListener(instance));\n }",
"score": 0.7091012001037598
}
] | 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/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.68904709815979
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " if (args.length == 2) {\n if (args[0].equalsIgnoreCase(\"debugtool\")) {\n for (int i = 10; i <= 100; i = i + 10) {\n list.add(String.valueOf(i));\n }\n list.add(\"cancel\");\n }\n if ((args[0].equalsIgnoreCase(\"whitelist\") || args[0].equalsIgnoreCase(\"blacklist\"))) {\n list.add(\"add\");\n list.add(\"remove\");",
"score": 0.6813802123069763
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/Startup.java",
"retrieved_chunk": " register(instance);\n new ProxyProtocol(instance);\n }\n private void register(NeoProtectBungee instance) {\n PluginManager pm = ProxyServer.getInstance().getPluginManager();\n pm.registerCommand(instance, new NeoProtectCommand(instance, \"neoprotect\", \"neoprotect.admin\", \"np\"));\n pm.registerListener(instance, new ChatListener(instance));\n pm.registerListener(instance, new LoginListener(instance));\n pm.registerListener(instance, new DisconnectListener(instance));\n }",
"score": 0.6766347885131836
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " }\n if (args[0].equalsIgnoreCase(\"toggle\")) {\n list.add(\"antiVPN\");\n list.add(\"anycast\");\n list.add(\"motdCache\");\n list.add(\"blockForge\");\n list.add(\"ipWhitelist\");\n list.add(\"ipBlacklist\");\n list.add(\"secureProfiles\");\n list.add(\"advancedAntiBot\");",
"score": 0.6764100790023804
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/command/NeoProtectCommand.java",
"retrieved_chunk": " list.add(\"setgameshield\");\n list.add(\"setbackend\");\n list.add(\"analytics\");\n list.add(\"debugTool\");\n list.add(\"whitelist\");\n list.add(\"blacklist\");\n list.add(\"ipanic\");\n list.add(\"toggle\");\n }\n }",
"score": 0.6592296361923218
}
] | 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, \"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.7688428163528442
},
{
"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.7503480911254883
},
{
"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.7503441572189331
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java",
"retrieved_chunk": " return;\n VersionUtils.Result result = instance.getCore().getVersionResult();\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.OUTDATED)) {\n 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()));",
"score": 0.7068376541137695
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java",
"retrieved_chunk": " return;\n VersionUtils.Result result = instance.getCore().getVersionResult();\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.OUTDATED)) {\n instance.sendMessage(player, localization.get(locale, 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()));",
"score": 0.6980372667312622
}
] | 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/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.7389788031578064
},
{
"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.7177413702011108
},
{
"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.7172098159790039
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java",
"retrieved_chunk": " return;\n VersionUtils.Result result = instance.getCore().getVersionResult();\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.OUTDATED)) {\n 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()));",
"score": 0.7003433704376221
},
{
"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.6992747783660889
}
] | 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.7159937620162964
},
{
"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.7080853581428528
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java",
"retrieved_chunk": " return;\n VersionUtils.Result result = instance.getCore().getVersionResult();\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.OUTDATED)) {\n 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()));",
"score": 0.7070646286010742
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java",
"retrieved_chunk": " return;\n VersionUtils.Result result = instance.getCore().getVersionResult();\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.OUTDATED)) {\n instance.sendMessage(player, localization.get(locale, 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()));",
"score": 0.7060871720314026
},
{
"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.6915410161018372
}
] | 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/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.7005776166915894
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/Startup.java",
"retrieved_chunk": " register(instance);\n new ProxyProtocol(instance);\n }\n private void register(NeoProtectBungee instance) {\n PluginManager pm = ProxyServer.getInstance().getPluginManager();\n pm.registerCommand(instance, new NeoProtectCommand(instance, \"neoprotect\", \"neoprotect.admin\", \"np\"));\n pm.registerListener(instance, new ChatListener(instance));\n pm.registerListener(instance, new LoginListener(instance));\n pm.registerListener(instance, new DisconnectListener(instance));\n }",
"score": 0.6943949460983276
},
{
"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.6757833957672119
},
{
"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.6746631264686584
},
{
"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.6739672422409058
}
] | 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/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.7044434547424316
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " }\n if (args[0].equalsIgnoreCase(\"toggle\")) {\n list.add(\"antiVPN\");\n list.add(\"anycast\");\n list.add(\"motdCache\");\n list.add(\"blockForge\");\n list.add(\"ipWhitelist\");\n list.add(\"ipBlacklist\");\n list.add(\"secureProfiles\");\n list.add(\"advancedAntiBot\");",
"score": 0.678563117980957
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/Startup.java",
"retrieved_chunk": " register(instance);\n new ProxyProtocol(instance);\n }\n private void register(NeoProtectBungee instance) {\n PluginManager pm = ProxyServer.getInstance().getPluginManager();\n pm.registerCommand(instance, new NeoProtectCommand(instance, \"neoprotect\", \"neoprotect.admin\", \"np\"));\n pm.registerListener(instance, new ChatListener(instance));\n pm.registerListener(instance, new LoginListener(instance));\n pm.registerListener(instance, new DisconnectListener(instance));\n }",
"score": 0.6717357039451599
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/command/NeoProtectCommand.java",
"retrieved_chunk": " list.add(\"setgameshield\");\n list.add(\"setbackend\");\n list.add(\"analytics\");\n list.add(\"debugTool\");\n list.add(\"whitelist\");\n list.add(\"blacklist\");\n list.add(\"ipanic\");\n list.add(\"toggle\");\n }\n }",
"score": 0.6672204732894897
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " if (args.length == 2) {\n if (args[0].equalsIgnoreCase(\"debugtool\")) {\n for (int i = 10; i <= 100; i = i + 10) {\n list.add(String.valueOf(i));\n }\n list.add(\"cancel\");\n }\n if ((args[0].equalsIgnoreCase(\"whitelist\") || args[0].equalsIgnoreCase(\"blacklist\"))) {\n list.add(\"add\");\n list.add(\"remove\");",
"score": 0.6664562225341797
}
] | 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/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.7717268466949463
},
{
"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.7647759914398193
},
{
"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.7593850493431091
},
{
"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.7590694427490234
},
{
"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.7531917095184326
}
] | 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 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.7548500299453735
},
{
"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.7469960451126099
},
{
"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.7403625845909119
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " List<Backend> list = new ArrayList<>();\n JSONArray backends = rest.request(RequestType.GET_GAMESHIELD_BACKENDS, null, Config.getGameShieldID()).getResponseBodyArray();\n for (Object object : backends) {\n JSONObject jsonObject = (JSONObject) object;\n list.add(new Backend(jsonObject.getString(\"id\"), jsonObject.getString(\"ipv4\"), String.valueOf(jsonObject.getInt(\"port\")), jsonObject.getBoolean(\"geyser\")));\n }\n return list;\n }\n public List<Firewall> getFirewall(String mode) {\n List<Firewall> list = new ArrayList<>();",
"score": 0.7382698655128479
},
{
"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.7272740602493286
}
] | 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/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.6942003965377808
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/command/NeoProtectCommand.java",
"retrieved_chunk": " list.add(\"setgameshield\");\n list.add(\"setbackend\");\n list.add(\"analytics\");\n list.add(\"debugTool\");\n list.add(\"whitelist\");\n list.add(\"blacklist\");\n list.add(\"ipanic\");\n list.add(\"toggle\");\n }\n }",
"score": 0.693164587020874
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " }\n if (args[0].equalsIgnoreCase(\"toggle\")) {\n list.add(\"antiVPN\");\n list.add(\"anycast\");\n list.add(\"motdCache\");\n list.add(\"blockForge\");\n list.add(\"ipWhitelist\");\n list.add(\"ipBlacklist\");\n list.add(\"secureProfiles\");\n list.add(\"advancedAntiBot\");",
"score": 0.668933093547821
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/command/NeoProtectCommand.java",
"retrieved_chunk": " }\n if ((args[0].equalsIgnoreCase(\"whitelist\") || args[0].equalsIgnoreCase(\"blacklist\"))) {\n list.add(\"add\");\n list.add(\"remove\");\n }\n if (args[0].equalsIgnoreCase(\"toggle\")) {\n list.add(\"antiVPN\");\n list.add(\"anycast\");\n list.add(\"motdCache\");\n list.add(\"blockForge\");",
"score": 0.6473991870880127
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/Startup.java",
"retrieved_chunk": " register(instance);\n new ProxyProtocol(instance);\n }\n private void register(NeoProtectBungee instance) {\n PluginManager pm = ProxyServer.getInstance().getPluginManager();\n pm.registerCommand(instance, new NeoProtectCommand(instance, \"neoprotect\", \"neoprotect.admin\", \"np\"));\n pm.registerListener(instance, new ChatListener(instance));\n pm.registerListener(instance, new LoginListener(instance));\n pm.registerListener(instance, new DisconnectListener(instance));\n }",
"score": 0.645959734916687
}
] | java | instance.sendMessage(sender, " - /np setgameshield [id]"); |
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/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.9187847375869751
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/NeoProtectSpigot.java",
"retrieved_chunk": " public void sendAdminMessage(Permission permission, String text, String clickAction, String clickMsg, String hoverAction, String hoverMsg) {\n getServer().getOnlinePlayers().forEach(pp -> {\n if (pp.hasPermission(\"neoprotect.admin\") || pp.hasPermission(permission.value))\n sendMessage(pp, text, clickAction, clickMsg, hoverAction, hoverMsg);\n });\n }\n @Override\n public void sendKeepAliveMessage(Object sender, long id) {}\n @Override\n public long sendKeepAliveMessage(long id) {",
"score": 0.8617888689041138
},
{
"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.8558260202407837
},
{
"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.8233004808425903
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " }\n public Object getSender() {\n return sender;\n }\n public String[] getArgs() {\n return args;\n }\n public Locale getLocal() {\n return local;\n }",
"score": 0.8138603568077087
}
] | 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/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.754878580570221
},
{
"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.726500928401947
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " private boolean isAttack() {\n return rest.request(RequestType.GET_GAMESHIELD_ISUNDERATTACK, null, Config.getGameShieldID()).getResponseBody().equals(\"true\");\n }\n public String getPlan() {\n try {\n return rest.request(RequestType.GET_GAMESHIELD_PLAN, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject(\"gameShieldPlan\").getJSONObject(\"options\").getString(\"name\");\n }catch (Exception ignore){}\n return null;\n }\n private boolean updateStats(RequestBody requestBody, String gameshieldID, String backendID) {",
"score": 0.724846363067627
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " Config.getGameShieldID());\n return true;\n }\n }\n public int toggle(String mode) {\n JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject(\"gameShieldSettings\");\n if(!settings.has(mode)) return -1;\n boolean mitigationSensitivity = settings.getBoolean(mode);\n if (mitigationSensitivity) {\n int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,",
"score": 0.7184473276138306
},
{
"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.7166082262992859
}
] | java | gameshield.getName(), gameshield.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/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.7762032747268677
},
{
"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.7528789043426514
},
{
"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.7404998540878296
},
{
"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.7373591065406799
},
{
"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.687294065952301
}
] | java | set("general.pluginVersion", stats.getPluginVersion()); |
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/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.8175606727600098
},
{
"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.8169074058532715
},
{
"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.777235746383667
},
{
"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.7737108469009399
},
{
"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.7373478412628174
}
] | java | "general.ProxyVersion", stats.getServerVersion()); |
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/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.8024217486381531
},
{
"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.7956883907318115
},
{
"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.775279700756073
},
{
"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.7714955806732178
},
{
"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.7222991585731506
}
] | java | , stats.getServerName()); |
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.84842449426651
},
{
"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.8017559051513672
},
{
"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.7921069860458374
},
{
"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.7914711236953735
},
{
"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.7735897302627563
}
] | 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/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.8374982476234436
},
{
"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.8264445066452026
},
{
"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.8101320266723633
},
{
"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.7961621284484863
},
{
"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.7923951148986816
}
] | 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/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.8221855759620667
},
{
"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.8093019723892212
},
{
"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.7975813150405884
},
{
"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.7947416305541992
},
{
"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.7674312591552734
}
] | 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/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.8745836615562439
},
{
"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.8396995067596436
},
{
"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.8393877744674683
},
{
"filename": "src/main/java/com/cursework/WebArtSell/Controllers/UserController.java",
"retrieved_chunk": "@RequestMapping(\"/table-users\")\npublic class UserController {\n @Autowired\n private UserRepository userRepository;\n @GetMapping\n public String getAllUsers(Model model, HttpSession session) {\n Iterable<User> users = userRepository.findAll();\n User currentUser = (User) session.getAttribute(\"user\");\n model.addAttribute(\"users\", users);\n model.addAttribute(\"currentUser\", currentUser);",
"score": 0.8390892744064331
},
{
"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.8388513326644897
}
] | java | (user.getRole().equals("ADMIN")) { |
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/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.7952560782432556
},
{
"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.7788398265838623
},
{
"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.743567705154419
},
{
"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.7397066354751587
},
{
"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.7393964529037476
}
] | java | user.setStatus("Активный"); |
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.8775547742843628
},
{
"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.8388255834579468
},
{
"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.8381152153015137
},
{
"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.8223209381103516
},
{
"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.8202762603759766
}
] | 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/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.7592065334320068
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " private boolean isAttack() {\n return rest.request(RequestType.GET_GAMESHIELD_ISUNDERATTACK, null, Config.getGameShieldID()).getResponseBody().equals(\"true\");\n }\n public String getPlan() {\n try {\n return rest.request(RequestType.GET_GAMESHIELD_PLAN, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject(\"gameShieldPlan\").getJSONObject(\"options\").getString(\"name\");\n }catch (Exception ignore){}\n return null;\n }\n private boolean updateStats(RequestBody requestBody, String gameshieldID, String backendID) {",
"score": 0.7276573181152344
},
{
"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.7269518375396729
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " Config.getGameShieldID());\n return true;\n }\n }\n public int toggle(String mode) {\n JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject(\"gameShieldSettings\");\n if(!settings.has(mode)) return -1;\n boolean mitigationSensitivity = settings.getBoolean(mode);\n if (mitigationSensitivity) {\n int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,",
"score": 0.7200812697410583
},
{
"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.715467095375061
}
] | java | ), gameshield.getId())); |
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.8265622854232788
},
{
"filename": "src/main/java/com/cursework/WebArtSell/Controllers/HomeController.java",
"retrieved_chunk": " public String home(Model model) {\n List<Product> products = productService.findAll();\n model.addAttribute(\"products\", products);\n return \"main\";\n }\n @GetMapping(\"/main-user/category/{category}\")\n public String getMainUserPageByCategory(@PathVariable String category, Model model, HttpServletRequest request) {\n HttpSession session = request.getSession();\n User user = (User) session.getAttribute(\"user\");\n if (user == null) {",
"score": 0.8169848918914795
},
{
"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.8160194754600525
},
{
"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.815340518951416
},
{
"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.8094141483306885
}
] | java | (!currentUser.getId().equals(id)) { |
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.793677806854248
},
{
"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.7913475632667542
},
{
"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.7463810443878174
},
{
"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.7439372539520264
},
{
"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.7426474094390869
}
] | java | user.setCreationDate(LocalDateTime.now()); |
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.8201369047164917
},
{
"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.8002934455871582
},
{
"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.7882521748542786
},
{
"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.7876964807510376
},
{
"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.7794708013534546
}
] | java | product.setArtist(updatedProduct.getArtist()); |
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": " }\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.7610613703727722
},
{
"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.757360577583313
},
{
"filename": "src/main/java/com/cursework/WebArtSell/Services/TransactionService.java",
"retrieved_chunk": " for (Transaction transaction : transactions) {\n String monthYear = transaction.getPurchaseDate().format(DateTimeFormatter.ofPattern(\"MM-yyyy\"));\n salesData.put(monthYear, salesData.getOrDefault(monthYear, 0.0) + transaction.getSum());\n }\n return salesData;\n }\n public boolean isProductInTransactions(Product product) {\n return transactionRepository.findAll().stream()\n .anyMatch(transaction -> transaction.getProductId().equals(product.getId()));\n }",
"score": 0.7559876441955566
},
{
"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.7554953694343567
},
{
"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.7429378032684326
}
] | java | "productId", product.get().getId()); |
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.8528231978416443
},
{
"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.7905709743499756
},
{
"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.7845359444618225
},
{
"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.7772210836410522
},
{
"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.7732285261154175
}
] | 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.895982563495636
},
{
"filename": "src/main/java/com/cursework/WebArtSell/Controllers/HomeController.java",
"retrieved_chunk": " public String home(Model model) {\n List<Product> products = productService.findAll();\n model.addAttribute(\"products\", products);\n return \"main\";\n }\n @GetMapping(\"/main-user/category/{category}\")\n public String getMainUserPageByCategory(@PathVariable String category, Model model, HttpServletRequest request) {\n HttpSession session = request.getSession();\n User user = (User) session.getAttribute(\"user\");\n if (user == null) {",
"score": 0.8546810150146484
},
{
"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.8350605964660645
},
{
"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.8188184499740601
},
{
"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.8174899816513062
}
] | java | List<Comment> comments = commentRepository.findByProductId(id); |
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.811490535736084
},
{
"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.7647026777267456
},
{
"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.7646797895431519
},
{
"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.743022620677948
},
{
"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.7430151700973511
}
] | 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/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.7920181751251221
},
{
"filename": "src/main/java/com/cursework/WebArtSell/Services/TransactionService.java",
"retrieved_chunk": " for (Transaction transaction : transactions) {\n String monthYear = transaction.getPurchaseDate().format(DateTimeFormatter.ofPattern(\"MM-yyyy\"));\n salesData.put(monthYear, salesData.getOrDefault(monthYear, 0.0) + transaction.getSum());\n }\n return salesData;\n }\n public boolean isProductInTransactions(Product product) {\n return transactionRepository.findAll().stream()\n .anyMatch(transaction -> transaction.getProductId().equals(product.getId()));\n }",
"score": 0.7919365167617798
},
{
"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.7909373044967651
},
{
"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.7865390181541443
},
{
"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.7698730230331421
}
] | 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 \"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.8558005094528198
},
{
"filename": "src/main/java/com/cursework/WebArtSell/Controllers/HomeController.java",
"retrieved_chunk": " public String home(Model model) {\n List<Product> products = productService.findAll();\n model.addAttribute(\"products\", products);\n return \"main\";\n }\n @GetMapping(\"/main-user/category/{category}\")\n public String getMainUserPageByCategory(@PathVariable String category, Model model, HttpServletRequest request) {\n HttpSession session = request.getSession();\n User user = (User) session.getAttribute(\"user\");\n if (user == null) {",
"score": 0.8508453369140625
},
{
"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.8257073163986206
},
{
"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.8184918165206909
},
{
"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.801422655582428
}
] | java | System.out.println(transaction.getBuyerId()); |
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/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.8511320352554321
},
{
"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.8374468088150024
},
{
"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.8226690888404846
},
{
"filename": "MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Controllers/PromotionController.java",
"retrieved_chunk": " @GetMapping(\"/promotions/delete/{id}\")\n public String deletePromotion(@PathVariable(\"id\") Long id) {\n promotionService.deletePromotion(id);\n return \"redirect:/promotions\";\n }\n}",
"score": 0.7984941601753235
},
{
"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.7974340915679932
}
] | java | <OrderItem> orderItems = productService.findOrderItemsByProduct(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.8789085149765015
},
{
"filename": "src/main/java/com/cursework/WebArtSell/Controllers/HomeController.java",
"retrieved_chunk": " public String home(Model model) {\n List<Product> products = productService.findAll();\n model.addAttribute(\"products\", products);\n return \"main\";\n }\n @GetMapping(\"/main-user/category/{category}\")\n public String getMainUserPageByCategory(@PathVariable String category, Model model, HttpServletRequest request) {\n HttpSession session = request.getSession();\n User user = (User) session.getAttribute(\"user\");\n if (user == null) {",
"score": 0.8687335252761841
},
{
"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.8506191968917847
},
{
"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.8181438446044922
},
{
"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.8159061670303345
}
] | java | product.setCreationDate(LocalDateTime.now()); |
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/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.8969436883926392
},
{
"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.8909483551979065
},
{
"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.858083963394165
},
{
"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.8371270298957825
},
{
"filename": "MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Controllers/OrderController.java",
"retrieved_chunk": " @GetMapping(\"/create-order\")\n public String showCreateOrderPage(Model model, HttpSession session) {\n User user = (User) session.getAttribute(\"user\");\n if (user == null) {\n return \"redirect:/login\";\n }\n List<Product> products = productService.getAllProducts();\n model.addAttribute(\"products\", products);\n return \"create-order\";\n }",
"score": 0.8340088129043579
}
] | java | Optional<User> userOptional = userService.validateUser(username, password); |
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.9201642274856567
},
{
"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.8740189075469971
},
{
"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.7776666879653931
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " if (!instance.getCore().getDirectConnectWhitelist().contains(sourceAddress)) {\n if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||\n instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, sourceAddress)))) {\n channel.close();\n instance.getCore().debug(\"Close connection IP (\" + channel.remoteAddress() + \") doesn't match to Neo-IPs (close / return)\");\n return;\n }\n instance.getCore().debug(\"Adding handler...\");\n if (instance.getCore().isSetup() && Config.isProxyProtocol()) {\n addProxyProtocolHandler(channel, playerAddress);",
"score": 0.7433266639709473
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " @Override\n protected void initChannel(Channel channel) {\n if (!Config.isProxyProtocol() | !instance.getCore().isSetup() | instance.getCore().getDirectConnectWhitelist().contains(((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())) {\n instance.getCore().debug(\"Plugin is not setup / ProxyProtocol is off / Player is on DirectConnectWhitelist (return)\");\n return;\n }\n if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||\n instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())))) {\n channel.close();\n instance.getCore().debug(\"Player connected over IP (\" + channel.remoteAddress() + \") doesn't match to Neo-IPs (warning)\");",
"score": 0.7396386861801147
}
] | java | instance.getCore().getDebugPingResponses().put(player.getUsername(), new ArrayList<>()); |
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/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.8716517686843872
},
{
"filename": "MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Services/OrderService.java",
"retrieved_chunk": " Order order = orderRepository.findById(id).orElseThrow();\n order.setStatus(status);\n orderRepository.save(order);\n }\n public Order saveOrder(Order order) {\n return orderRepository.save(order);\n }\n @Autowired\n public OrderService(OrderRepository orderRepository) {\n this.orderRepository = orderRepository;",
"score": 0.8689315915107727
},
{
"filename": "MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Services/OrderService.java",
"retrieved_chunk": " .orElseThrow(() -> new IllegalArgumentException(\"Invalid order Id:\" + id));\n List<OrderItem> orderItems = order.getOrderItems();\n orderItemRepository.deleteAll(orderItems);\n orderRepository.delete(order);\n }\n}",
"score": 0.8435757160186768
},
{
"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.8194993734359741
},
{
"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.8190622329711914
}
] | 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.8233179450035095
},
{
"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.8223353624343872
},
{
"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.8193836212158203
},
{
"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.8108363151550293
},
{
"filename": "src/main/java/io/github/newhoo/restkit/ext/solon/helper/PsiAnnotationHelper.java",
"retrieved_chunk": " return annotation;\n }\n for (PsiClass aSuper : psiClass.getSupers()) {\n if (!\"java.lang.Object\".equals(aSuper.getQualifiedName())) {\n PsiAnnotation superClassAnno = getInheritedAnnotation(aSuper, fqn);\n if (superClassAnno != null) {\n return superClassAnno;\n }\n }\n }",
"score": 0.8080538511276245
}
] | 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.8591211438179016
},
{
"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.848038911819458
},
{
"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.8422602415084839
},
{
"filename": "src/main/java/io/github/newhoo/restkit/ext/solon/helper/PsiAnnotationHelper.java",
"retrieved_chunk": " values.add(initializer.getText().replaceAll(\"\\\"\", \"\"));\n }\n }\n return values;\n }\n public static String getAnnotationValue(PsiAnnotation annotation, String attributeName) {\n String paramName = null;\n PsiAnnotationMemberValue attributeValue = annotation.findDeclaredAttributeValue(attributeName);\n if (attributeValue instanceof PsiLiteralExpression) {\n paramName = (String) ((PsiLiteralExpression) attributeValue).getValue();",
"score": 0.8178396821022034
},
{
"filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/BaseLanguageResolver.java",
"retrieved_chunk": " if (headers instanceof PsiArrayInitializerMemberValue) {\n for (PsiAnnotationMemberValue initializer : ((PsiArrayInitializerMemberValue) headers).getInitializers()) {\n list.addAll(getHeaderItem(initializer));\n }\n }\n return list;\n }\n @NotNull\n private List<Parameter> getParameterList(PsiMethod psiMethod) {\n List<Parameter> parameterList = new ArrayList<>();",
"score": 0.8098012804985046
}
] | 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.872861385345459
},
{
"filename": "src/main/java/io/github/newhoo/restkit/ext/solon/helper/PsiAnnotationHelper.java",
"retrieved_chunk": " return null;\n }\n /**\n * 获取method注解\n *\n * @param psiMethod\n * @param fqn\n */\n public static PsiAnnotation getInheritedAnnotation(PsiMethod psiMethod, String fqn) {\n PsiAnnotation annotation = psiMethod.getAnnotation(fqn);",
"score": 0.82973313331604
},
{
"filename": "src/main/java/io/github/newhoo/restkit/ext/solon/helper/PsiAnnotationHelper.java",
"retrieved_chunk": "import java.util.List;\n/**\n * PsiAnnotationHelper in Java\n *\n * @author newhoo\n * @since 1.0.0\n */\npublic class PsiAnnotationHelper {\n /**\n * 获取class注解",
"score": 0.7860959768295288
},
{
"filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/BaseLanguageResolver.java",
"retrieved_chunk": " }\n }\n return list;\n }\n public List<KV> buildParamString(PsiMethod psiMethod) {\n List<KV> list = new ArrayList<>();\n List<Parameter> parameterList = getParameterList(psiMethod);\n // 拼接参数\n for (Parameter parameter : parameterList) {\n String paramType = parameter.getParamType();",
"score": 0.7497625350952148
},
{
"filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/BaseLanguageResolver.java",
"retrieved_chunk": " }\n return list;\n }\n /**\n * 构建RequestBody json 参数\n */\n public String buildRequestBodyJson(PsiMethod psiMethod) {\n return Arrays.stream(psiMethod.getParameterList().getParameters())\n .filter(psiParameter -> psiParameter.hasAnnotation(REQUEST_BODY.getQualifiedName()))\n .findFirst()",
"score": 0.7495370507240295
}
] | 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": " ));\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.846642017364502
},
{
"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.8461192846298218
},
{
"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.810371994972229
},
{
"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.8073549270629883
},
{
"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.8056831359863281
}
] | java | TypeUtils.getExampleValue(typeCanonicalText, false); |
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.822553277015686
},
{
"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.8122532367706299
},
{
"filename": "src/main/java/io/github/newhoo/restkit/ext/solon/helper/PsiAnnotationHelper.java",
"retrieved_chunk": " return annotation;\n }\n for (PsiClass aSuper : psiClass.getSupers()) {\n if (!\"java.lang.Object\".equals(aSuper.getQualifiedName())) {\n PsiAnnotation superClassAnno = getInheritedAnnotation(aSuper, fqn);\n if (superClassAnno != null) {\n return superClassAnno;\n }\n }\n }",
"score": 0.7992997169494629
},
{
"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.7981552481651306
},
{
"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.7960034608840942
}
] | java | if (TypeUtils.isPrimitiveOrSimpleType(fieldType.replaceAll("\\[]", ""))) { |
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": " private final TableBookingService tableBookingService;\n @Autowired\n public TableBookingController(TableBookingService tableBookingService) {\n this.tableBookingService = tableBookingService;\n }\n @GetMapping(\"/book-table\")\n public String bookingForm(Model model) {\n List<TableBooking> bookings = tableBookingService.getAllBookings();\n model.addAttribute(\"bookings\", bookings);\n List<Tables> allTables = tableBookingService.getAllTables();",
"score": 0.7913935780525208
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/TableBookingController.java",
"retrieved_chunk": " model.addAttribute(\"maxDate\", maxDate);\n List<LocalTime> times = new ArrayList<>();\n for (LocalTime timeOption = LocalTime.of(12, 0);\n timeOption.isBefore(LocalTime.of(20, 30));\n timeOption = timeOption.plusMinutes(30)) {\n times.add(timeOption);\n }\n model.addAttribute(\"times\", times);\n List<TableBooking> bookings = tableBookingService.getAllBookings();\n model.addAttribute(\"bookings\", bookings);",
"score": 0.7703204154968262
},
{
"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.7643172740936279
},
{
"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.7388689517974854
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java",
"retrieved_chunk": " newOrder.setStartTime(new Timestamp(System.currentTimeMillis()));\n newOrder.setStatus(\"Принят\");\n newOrder.setInformation(\"Информация о блюдах формируется...\");\n newOrder = orderRepository.save(newOrder);\n Map<String, Pair<Integer, Double>> dishInfo = new HashMap<>();\n double totalCost = 0.0;\n if (orderRequest.getDish_ids() != null) {\n for (Integer dishId : orderRequest.getDish_ids()) {\n Dish dish = dishRepository.findById(dishId)\n .orElseThrow(() -> new RuntimeException(\"Блюдо не найдено: \" + dishId));",
"score": 0.7375824451446533
}
] | 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": " private final TableBookingService tableBookingService;\n @Autowired\n public TableBookingController(TableBookingService tableBookingService) {\n this.tableBookingService = tableBookingService;\n }\n @GetMapping(\"/book-table\")\n public String bookingForm(Model model) {\n List<TableBooking> bookings = tableBookingService.getAllBookings();\n model.addAttribute(\"bookings\", bookings);\n List<Tables> allTables = tableBookingService.getAllTables();",
"score": 0.7932144403457642
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/TableBookingController.java",
"retrieved_chunk": " model.addAttribute(\"maxDate\", maxDate);\n List<LocalTime> times = new ArrayList<>();\n for (LocalTime timeOption = LocalTime.of(12, 0);\n timeOption.isBefore(LocalTime.of(20, 30));\n timeOption = timeOption.plusMinutes(30)) {\n times.add(timeOption);\n }\n model.addAttribute(\"times\", times);\n List<TableBooking> bookings = tableBookingService.getAllBookings();\n model.addAttribute(\"bookings\", bookings);",
"score": 0.7688230872154236
},
{
"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.7626817226409912
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java",
"retrieved_chunk": " newOrder.setStartTime(new Timestamp(System.currentTimeMillis()));\n newOrder.setStatus(\"Принят\");\n newOrder.setInformation(\"Информация о блюдах формируется...\");\n newOrder = orderRepository.save(newOrder);\n Map<String, Pair<Integer, Double>> dishInfo = new HashMap<>();\n double totalCost = 0.0;\n if (orderRequest.getDish_ids() != null) {\n for (Integer dishId : orderRequest.getDish_ids()) {\n Dish dish = dishRepository.findById(dishId)\n .orElseThrow(() -> new RuntimeException(\"Блюдо не найдено: \" + dishId));",
"score": 0.7380646467208862
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java",
"retrieved_chunk": " model.addAttribute(\"tables\", tablesRepository.findAll());\n return \"create-order\";\n }\n @PostMapping(\"/create-order\")\n public String createOrder(@RequestBody OrderRequest orderRequest) {\n System.out.println(orderRequest);\n Order newOrder = new Order();\n Tables table = tablesRepository.findById(orderRequest.getTable_id())\n .orElseThrow(() -> new RuntimeException(\"Стол не найден: \" + orderRequest.getTable_id()));\n newOrder.setTable(table);",
"score": 0.7377294301986694
}
] | java | .getId() == tableId && booking.getDate().equals(date) && booking.getTime().equals(time)) { |
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/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.8442827463150024
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Models/WorkHour.java",
"retrieved_chunk": " public Staff getStaff() {\n return staff;\n }\n public void setStaff(Staff staff) {\n this.staff = staff;\n }\n public Date getDate() {\n return date;\n }\n public void setDate(Date date) {",
"score": 0.8101772665977478
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Models/WorkHour.java",
"retrieved_chunk": " @JoinColumn(name = \"staff_id\")\n private Staff staff;\n @Column(name = \"date\")\n private Date date;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }",
"score": 0.8037309050559998
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Models/Staff.java",
"retrieved_chunk": " public void setName(String name) {\n this.name = name;\n }\n public String getLogin() {\n return login;\n }\n public void setLogin(String login) {\n this.login = login;\n }\n public String getPassword() {",
"score": 0.8008931279182434
},
{
"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.7925909161567688
}
] | java | staffRepository.findByLogin(login) != null; |
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.8075329661369324
},
{
"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.7744585871696472
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/DishService.java",
"retrieved_chunk": " if (dish != null) {\n dish.setName(name);\n dish.setDescription(description);\n dish.setRecipe(recipe);\n // dish.setImage(image);\n dishRepository.save(dish);\n }\n }\n}",
"score": 0.7427737712860107
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java",
"retrieved_chunk": " @Autowired\n private OrderedDishRepository orderedDishRepository;\n @Autowired\n private TablesRepository tablesRepository;\n @Autowired\n private DishTypeRepository dishTypeRepository;\n @GetMapping(\"/create-order\")\n public String createOrderForm(Model model) {\n model.addAttribute(\"dishes\", dishRepository.findAll());\n model.addAttribute(\"types\", dishTypeRepository.findAll());",
"score": 0.737205982208252
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrdersController.java",
"retrieved_chunk": " orders = new ArrayList<>();\n }\n model.addAttribute(\"orders\", orders);\n return \"orders\";\n }\n @PostMapping(\"/orders/delete\")\n public String deleteOrder(@RequestParam(\"id\") int id) {\n orderService.deleteOrder(id);\n return \"redirect:/orders\";\n }",
"score": 0.7336536645889282
}
] | java | dishService.editDishDetails(id, name, description, recipe); |
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.8323732018470764
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Secure/WaiterCheckInterceptor.java",
"retrieved_chunk": " HttpSession session = request.getSession();\n Staff user = (Staff) session.getAttribute(\"staff\");\n if (user == null || !user.getRole().equals(\"ОФИЦИАНТ\")) {\n response.sendRedirect(\"/login\");\n return false;\n }\n return true;\n }\n}",
"score": 0.8053760528564453
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Secure/ManagerCheckInterceptor.java",
"retrieved_chunk": " HttpSession session = request.getSession();\n Staff user = (Staff) session.getAttribute(\"staff\");\n if (user == null || !user.getRole().equals(\"МЕНЕДЖЕР\")) {\n response.sendRedirect(\"/login\");\n return false;\n }\n return true;\n }\n}",
"score": 0.8030040264129639
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Secure/KitchenCheckInterceptor.java",
"retrieved_chunk": " HttpSession session = request.getSession();\n Staff user = (Staff) session.getAttribute(\"staff\");\n if (user == null || !user.getRole().equals(\"ПОВАР\")) {\n response.sendRedirect(\"/login\");\n return false;\n }\n return true;\n }\n}",
"score": 0.8021010160446167
},
{
"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.7984452247619629
}
] | java | staff.setApparatusEmployed(new java.sql.Date(currentDate.getTime())); |
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/Models/OrderedDish.java",
"retrieved_chunk": " this.id = id;\n }\n public Dish getDish() {\n return dish;\n }\n public void setDish(Dish dish) {\n this.dish = dish;\n }\n public Order getOrder() {\n return order;",
"score": 0.8795109391212463
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/MenuController.java",
"retrieved_chunk": " this.dishTypeRepository = dishTypeRepository;\n }\n @GetMapping(\"/menu\")\n public String showMenu(Model model) {\n List<Dish> dishes = dishService.getAllDishes();\n List<DishType> dishTypes = dishTypeRepository.findAll();\n model.addAttribute(\"dishes\", dishes);\n model.addAttribute(\"dishTypes\", dishTypes);\n return \"menu\";\n }",
"score": 0.8397611975669861
},
{
"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.8187797665596008
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/OrderService.java",
"retrieved_chunk": " @Transactional\n public void deleteOrder(int id) {\n Order order = orderRepository.findById(id).orElseThrow(() -> new IllegalArgumentException(\"Order not found\"));\n List<OrderedDish> orderedDishes = orderedDishRepository.findByOrder(order);\n orderedDishRepository.deleteInBatch(orderedDishes);\n orderRepository.delete(order);\n }\n}",
"score": 0.8042675256729126
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java",
"retrieved_chunk": " @Autowired\n private OrderedDishRepository orderedDishRepository;\n @Autowired\n private TablesRepository tablesRepository;\n @Autowired\n private DishTypeRepository dishTypeRepository;\n @GetMapping(\"/create-order\")\n public String createOrderForm(Model model) {\n model.addAttribute(\"dishes\", dishRepository.findAll());\n model.addAttribute(\"types\", dishTypeRepository.findAll());",
"score": 0.8022283315658569
}
] | 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/Controllers/OrderController.java",
"retrieved_chunk": " @Autowired\n private OrderedDishRepository orderedDishRepository;\n @Autowired\n private TablesRepository tablesRepository;\n @Autowired\n private DishTypeRepository dishTypeRepository;\n @GetMapping(\"/create-order\")\n public String createOrderForm(Model model) {\n model.addAttribute(\"dishes\", dishRepository.findAll());\n model.addAttribute(\"types\", dishTypeRepository.findAll());",
"score": 0.8524618744850159
},
{
"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.846603274345398
},
{
"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.8282914161682129
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/KitchenController.java",
"retrieved_chunk": " private OrderRepository orderRepository;\n @GetMapping(\"/kitchen\")\n public String getKitchen(Model model) {\n List<OrderedDish> orderedDishes = orderedDishRepository.findAll();\n List<OrderedDish> acceptedDishes = orderedDishes.stream()\n .filter(dish -> dish.getStatus().equals(\"Принят\"))\n .collect(Collectors.toList());\n model.addAttribute(\"orderedDishes\", acceptedDishes);\n return \"kitchen\";\n }",
"score": 0.8257580995559692
},
{
"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.8254603147506714
}
] | 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.9627880454063416
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Models/Order.java",
"retrieved_chunk": " private Timestamp endTime;\n @Column(name = \"status\")\n private String status;\n @OneToMany(mappedBy = \"order\", fetch = FetchType.EAGER)\n private List<OrderedDish> orderedDishes;\n public List<OrderedDish> getOrderedDishes() {\n return orderedDishes;\n }\n public void setOrderedDishes(List<OrderedDish> orderedDishes) {\n this.orderedDishes = orderedDishes;",
"score": 0.8432509899139404
},
{
"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.8353886008262634
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/MenuController.java",
"retrieved_chunk": " this.dishTypeRepository = dishTypeRepository;\n }\n @GetMapping(\"/menu\")\n public String showMenu(Model model) {\n List<Dish> dishes = dishService.getAllDishes();\n List<DishType> dishTypes = dishTypeRepository.findAll();\n model.addAttribute(\"dishes\", dishes);\n model.addAttribute(\"dishTypes\", dishTypes);\n return \"menu\";\n }",
"score": 0.832912802696228
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/OrderService.java",
"retrieved_chunk": " @Transactional\n public void deleteOrder(int id) {\n Order order = orderRepository.findById(id).orElseThrow(() -> new IllegalArgumentException(\"Order not found\"));\n List<OrderedDish> orderedDishes = orderedDishRepository.findByOrder(order);\n orderedDishRepository.deleteInBatch(orderedDishes);\n orderRepository.delete(order);\n }\n}",
"score": 0.8304131031036377
}
] | 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.9620423316955566
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/OrderService.java",
"retrieved_chunk": " @Transactional\n public void deleteOrder(int id) {\n Order order = orderRepository.findById(id).orElseThrow(() -> new IllegalArgumentException(\"Order not found\"));\n List<OrderedDish> orderedDishes = orderedDishRepository.findByOrder(order);\n orderedDishRepository.deleteInBatch(orderedDishes);\n orderRepository.delete(order);\n }\n}",
"score": 0.8637425899505615
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java",
"retrieved_chunk": " int count = orderRequest.getDish_counts().getOrDefault(dishId, 0);\n for (int i = 0; i < count; i++) {\n OrderedDish orderedDish = new OrderedDish();\n orderedDish.setDish(dish);\n orderedDish.setOrder(newOrder);\n orderedDish.setStatus(\"Принят\");\n orderedDishRepository.save(orderedDish);\n totalCost += dish.getCost();\n }\n String dishName = dish.getName();",
"score": 0.8443036079406738
},
{
"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.8351122140884399
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Models/Order.java",
"retrieved_chunk": " private Timestamp endTime;\n @Column(name = \"status\")\n private String status;\n @OneToMany(mappedBy = \"order\", fetch = FetchType.EAGER)\n private List<OrderedDish> orderedDishes;\n public List<OrderedDish> getOrderedDishes() {\n return orderedDishes;\n }\n public void setOrderedDishes(List<OrderedDish> orderedDishes) {\n this.orderedDishes = orderedDishes;",
"score": 0.8331496715545654
}
] | 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/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.8706915378570557
},
{
"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.8487768173217773
},
{
"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.8408286571502686
},
{
"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.8386654853820801
},
{
"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.8207736015319824
}
] | 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.8581625819206238
},
{
"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.8315624594688416
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Secure/ManagerCheckInterceptor.java",
"retrieved_chunk": " HttpSession session = request.getSession();\n Staff user = (Staff) session.getAttribute(\"staff\");\n if (user == null || !user.getRole().equals(\"МЕНЕДЖЕР\")) {\n response.sendRedirect(\"/login\");\n return false;\n }\n return true;\n }\n}",
"score": 0.799444854259491
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Secure/WaiterCheckInterceptor.java",
"retrieved_chunk": " HttpSession session = request.getSession();\n Staff user = (Staff) session.getAttribute(\"staff\");\n if (user == null || !user.getRole().equals(\"ОФИЦИАНТ\")) {\n response.sendRedirect(\"/login\");\n return false;\n }\n return true;\n }\n}",
"score": 0.7969706058502197
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Secure/KitchenCheckInterceptor.java",
"retrieved_chunk": " HttpSession session = request.getSession();\n Staff user = (Staff) session.getAttribute(\"staff\");\n if (user == null || !user.getRole().equals(\"ПОВАР\")) {\n response.sendRedirect(\"/login\");\n return false;\n }\n return true;\n }\n}",
"score": 0.7969332933425903
}
] | 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.7948110699653625
},
{
"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.7801942825317383
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java",
"retrieved_chunk": " }\n @GetMapping(\"/manage-orders\")\n public String viewOrdersManager(@RequestParam(required = false) String status,\n @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date,\n Model model) {\n List<Order> orders = orderRepository.findAll();\n if (status != null && !status.isEmpty()) {\n orders = orders.stream()\n .filter(order -> order.getStatus().equals(status))\n .collect(Collectors.toList());",
"score": 0.7634285688400269
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java",
"retrieved_chunk": " public String viewOrders(@RequestParam(required = false) String status,\n @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date,\n Model model) {\n List<Order> orders = orderRepository.findAll();\n if (status != null && !status.isEmpty()) {\n orders = orders.stream()\n .filter(order -> order.getStatus().equals(status))\n .collect(Collectors.toList());\n }\n if (date != null) {",
"score": 0.762360692024231
},
{
"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.7589769959449768
}
] | java | <Tables> allTables = tableBookingService.getAllTables(); |
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/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.8718671798706055
},
{
"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.8685146570205688
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/StaffService.java",
"retrieved_chunk": " public void updateStaff(Staff staff) {\n staffRepository.save(staff);\n }\n public void deleteStaff(Staff staff) {\n staffRepository.delete(staff);\n }\n public Staff getStaffById(int id) {\n Optional<Staff> staff = staffRepository.findById(id);\n if (staff.isPresent()) {\n return staff.get();",
"score": 0.7996730804443359
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/StaffService.java",
"retrieved_chunk": " @Autowired\n public StaffService(StaffRepository staffRepository) {\n this.staffRepository = staffRepository;\n }\n public List<Staff> getAllStaff() {\n return staffRepository.findAll();\n }\n public void saveStaff(Staff staff) {\n staffRepository.save(staff);\n }",
"score": 0.793104887008667
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/ShiftController.java",
"retrieved_chunk": " workHour.setStaff(staff);\n workHour.setDate(date);\n workHourRepository.save(workHour);\n return \"redirect:/assign-shifts\";\n }\n @GetMapping(\"/view-schedule\")\n public String viewSchedule(Model model) {\n Map<Staff, Long> shiftStats = workHourRepository.findAll().stream()\n .collect(Collectors.groupingBy(WorkHour::getStaff, Collectors.counting()));\n model.addAttribute(\"workHours\", workHourRepository.findAll());",
"score": 0.7897488474845886
}
] | java | loginExists(staff.getLogin())) { |
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.8872685432434082
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java",
"retrieved_chunk": " int count = orderRequest.getDish_counts().getOrDefault(dishId, 0);\n for (int i = 0; i < count; i++) {\n OrderedDish orderedDish = new OrderedDish();\n orderedDish.setDish(dish);\n orderedDish.setOrder(newOrder);\n orderedDish.setStatus(\"Принят\");\n orderedDishRepository.save(orderedDish);\n totalCost += dish.getCost();\n }\n String dishName = dish.getName();",
"score": 0.8787752389907837
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/OrderService.java",
"retrieved_chunk": " @Transactional\n public void deleteOrder(int id) {\n Order order = orderRepository.findById(id).orElseThrow(() -> new IllegalArgumentException(\"Order not found\"));\n List<OrderedDish> orderedDishes = orderedDishRepository.findByOrder(order);\n orderedDishRepository.deleteInBatch(orderedDishes);\n orderRepository.delete(order);\n }\n}",
"score": 0.8675276637077332
},
{
"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.8633970022201538
},
{
"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.8421792387962341
}
] | java | = orderedDish.getOrder(); |
/*
* 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.7703698873519897
},
{
"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.7688627243041992
},
{
"filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/ConfigParsingTest.java",
"retrieved_chunk": " + customMinorRulesXML\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(1, config.getMinorRules().size());\n assertEquals(customMinorRulesRegex, config.getMinorRules().get(0));",
"score": 0.7667004466056824
},
{
"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.7609555125236511
},
{
"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.7598507404327393
}
] | 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.7727382183074951
},
{
"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.7693221569061279
},
{
"filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/ConfigParsingTest.java",
"retrieved_chunk": " + customMinorRulesXML\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(1, config.getMinorRules().size());\n assertEquals(customMinorRulesRegex, config.getMinorRules().get(0));",
"score": 0.7666308283805847
},
{
"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.7613410949707031
},
{
"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.7603225708007812
}
] | 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.7910991311073303
},
{
"filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/ConventionalCommitsVersionPolicyTest.java",
"retrieved_chunk": " + \"<versionTag>^v([0-9]+\\\\.[0-9]+\\\\.[0-9]+)$</versionTag>\"\n + \"</projectVersionPolicyConfig>\" +\n \"\";\n verifyNextVersion(versionRulesConfig, \"1.1.1-SNAPSHOT\", \"1.1.1\", \"1.1.2-SNAPSHOT\", normal); // No Tag - No CC Comments\n verifyNextVersion(versionRulesConfig, \"1.1.1-SNAPSHOT\", \"1.1.1\", \"1.1.2-SNAPSHOT\", patch); // No Tag - Patch Comments\n verifyNextVersion(versionRulesConfig, \"1.1.1-SNAPSHOT\", \"1.2.0\", \"1.2.1-SNAPSHOT\", minor); // No Tag - Minor Comments\n verifyNextVersion(versionRulesConfig, \"1.1.1-SNAPSHOT\", \"2.0.0\", \"2.0.1-SNAPSHOT\", major); // No Tag - Major Comments\n // The custom tag pattern will look at the \"v3.4.5\" tag\n verifyNextVersion(versionRulesConfig, \"0.0.1-SNAPSHOT\", \"3.4.6\", \"3.4.7-SNAPSHOT\", normal, \"2.3.4\", \"v3.4.5\"); // Tag - No CC Comments\n verifyNextVersion(versionRulesConfig, \"0.0.1-SNAPSHOT\", \"3.4.6\", \"3.4.7-SNAPSHOT\", patch, \"2.3.4\", \"v3.4.5\"); // Tag - Patch Comments",
"score": 0.7779133915901184
},
{
"filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/ConventionalCommitsVersionPolicyTest.java",
"retrieved_chunk": " verifyNextVersion(versionRulesConfig, \"1.1.1-SNAPSHOT\", \"1.1.1\", \"1.1.2-SNAPSHOT\", normal); // No Tag - No CC Comments\n verifyNextVersion(versionRulesConfig, \"1.1.1-SNAPSHOT\", \"1.1.1\", \"1.1.2-SNAPSHOT\", patch); // No Tag - Patch Comments\n verifyNextVersion(versionRulesConfig, \"1.1.1-SNAPSHOT\", \"1.2.0\", \"1.2.1-SNAPSHOT\", minor); // No Tag - Minor Comments\n verifyNextVersion(versionRulesConfig, \"1.1.1-SNAPSHOT\", \"2.0.0\", \"2.0.1-SNAPSHOT\", major); // No Tag - Major Comments\n // The default tag pattern will look at the \"2.3.4\" tag\n verifyNextVersion(versionRulesConfig, \"0.0.1-SNAPSHOT\", \"2.3.5\", \"2.3.6-SNAPSHOT\", normal, \"2.3.4\", \"v3.4.5\"); // Tag - No CC Comments\n verifyNextVersion(versionRulesConfig, \"0.0.1-SNAPSHOT\", \"2.3.5\", \"2.3.6-SNAPSHOT\", patch, \"2.3.4\", \"v3.4.5\"); // Tag - Patch Comments\n verifyNextVersion(versionRulesConfig, \"0.0.1-SNAPSHOT\", \"2.4.0\", \"2.4.1-SNAPSHOT\", minor, \"2.3.4\", \"v3.4.5\"); // Tag - Minor Comments\n verifyNextVersion(versionRulesConfig, \"0.0.1-SNAPSHOT\", \"3.0.0\", \"3.0.1-SNAPSHOT\", major, \"2.3.4\", \"v3.4.5\"); // Tag - Major Comments\n // Too many valid version tags on one commit",
"score": 0.7263690233230591
},
{
"filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/ConventionalCommitsVersionPolicyTest.java",
"retrieved_chunk": " verifyNextVersion(versionRulesConfig, \"0.0.1-SNAPSHOT\", \"3.5.0\", \"3.5.1-SNAPSHOT\", minor, \"2.3.4\", \"v3.4.5\"); // Tag - Minor Comments\n verifyNextVersion(versionRulesConfig, \"0.0.1-SNAPSHOT\", \"4.0.0\", \"4.0.1-SNAPSHOT\", major, \"2.3.4\", \"v3.4.5\"); // Tag - Major Comments\n // Too many valid version tags on one commit\n verifyNextVersionMustFail(versionRulesConfig, \"1.1.1-SNAPSHOT\", minor, \"v1.1.1\", \"v2.2.2\");\n }\n @Test\n void testCustomVersionRules() throws VersionParseException, PolicyException, IOException, ScmRepositoryException {\n String normal = \"This is a different commit.\";\n String patch = \"This is a No Change commit.\";\n String minor = \"This is a Nice Change commit.\";",
"score": 0.7235289216041565
},
{
"filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/ConventionalCommitsVersionPolicyTest.java",
"retrieved_chunk": " + \"</projectVersionPolicyConfig>\" +\n \"\";\n verifyNextVersion(versionRulesConfig, \"1.1.1-SNAPSHOT\", \"1.1.1\", \"1.1.2-SNAPSHOT\", normal); // No Tag - No CC Comments\n verifyNextVersion(versionRulesConfig, \"1.1.1-SNAPSHOT\", \"1.1.1\", \"1.1.2-SNAPSHOT\", patch); // No Tag - Patch Comments\n verifyNextVersion(versionRulesConfig, \"1.1.1-SNAPSHOT\", \"1.2.0\", \"1.2.1-SNAPSHOT\", minor); // No Tag - Minor Comments\n verifyNextVersion(versionRulesConfig, \"1.1.1-SNAPSHOT\", \"2.0.0\", \"2.0.1-SNAPSHOT\", major); // No Tag - Major Comments\n verifyNextVersion(versionRulesConfig, \"1.1.1-SNAPSHOT\", \"3.4.6\", \"3.4.7-SNAPSHOT\", normal, \"2.3.4\", \"The awesome 3.4.5 release\"); // Tag - No CC Comments\n verifyNextVersion(versionRulesConfig, \"1.1.1-SNAPSHOT\", \"3.4.6\", \"3.4.7-SNAPSHOT\", patch, \"2.3.4\", \"The awesome 3.4.5 release\"); // Tag - Patch Comments\n verifyNextVersion(versionRulesConfig, \"1.1.1-SNAPSHOT\", \"3.5.0\", \"3.5.1-SNAPSHOT\", minor, \"2.3.4\", \"The awesome 3.4.5 release\"); // Tag - Minor Comments\n verifyNextVersion(versionRulesConfig, \"1.1.1-SNAPSHOT\", \"4.0.0\", \"4.0.1-SNAPSHOT\", major, \"2.3.4\", \"The awesome 3.4.5 release\"); // Tag - Major Comments",
"score": 0.7183222770690918
}
] | 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.8118495941162109
},
{
"filename": "src/main/java/nl/basjes/maven/release/version/conventionalcommits/ConventionalCommitsVersionPolicy.java",
"retrieved_chunk": " maxElementSinceLastVersionTag == Element.PATCH\n ? \" (because we did not find any minor/major commit messages)\"\n : \"\");\n LOG.info(\"- Next release version : {}\", releaseVersion);\n VersionPolicyResult result = new VersionPolicyResult();\n result.setVersion(releaseVersion.toString());\n return result;\n }\n @Override\n public VersionPolicyResult getDevelopmentVersion(VersionPolicyRequest request)",
"score": 0.7999725341796875
},
{
"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.7862921953201294
},
{
"filename": "src/main/java/nl/basjes/maven/release/version/conventionalcommits/ConventionalCommitsVersionPolicy.java",
"retrieved_chunk": " } catch (IllegalArgumentException e) {\n throw new VersionParseException(e.getMessage(), e);\n }\n LOG.debug(\"Current version : {}\", version);\n // If we have a version from the tag we use that + the calculated update.\n // If only have the version from the current pom version with -SNAPSHOT removed IF it is only a PATCH.\n if (!(latestVersionTag == null && maxElementSinceLastVersionTag == Element.PATCH)) {\n version = version.next(maxElementSinceLastVersionTag);\n }\n Version releaseVersion = version.toReleaseVersion();",
"score": 0.7825343608856201
},
{
"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.7783137559890747
}
] | java | commitHistory.getChanges()) { |
/*
* 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/test/java/nl/basjes/maven/release/version/conventionalcommits/mockscm/MockScmProvider.java",
"retrieved_chunk": " private ChangeSet changeSet(String newComment, String... newTags) {\n return changeSet(newComment, Arrays.asList(newTags));\n }\n private ChangeSet changeSet(String newComment, List<String> newTags) {\n ChangeSet changeSet = new ChangeSet();\n changeSet.setComment(newComment);\n changeSet.setAuthor(\"Niels Basjes <[email protected]>\");\n if (!newTags.isEmpty()) {\n List<String> tags = new ArrayList<>();\n for (String newTag : newTags) {",
"score": 0.8384273052215576
},
{
"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.8112360239028931
},
{
"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.7727855443954468
},
{
"filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/mockscm/MockScmProvider.java",
"retrieved_chunk": "public class MockScmProvider\n extends AbstractScmProvider {\n List<ChangeSet> configuredChangeSets;\n public MockScmProvider(List<String> comments, List<String> tags) {\n configuredChangeSets = comments.stream().map(this::changeSet).collect(Collectors.toList());\n configuredChangeSets.add(changeSet(\"Commit for tags\", tags));\n }\n @Override\n public String getScmType() {\n return \"dummy\";",
"score": 0.7702746987342834
},
{
"filename": "src/main/java/nl/basjes/maven/release/version/conventionalcommits/VersionRules.java",
"retrieved_chunk": " if (semverConfigVersionTag != null && !semverConfigVersionTag.trim().isEmpty()) {\n tagRegex = semverConfigVersionTag;\n }\n if (!config.getMajorRules().isEmpty() || !config.getMinorRules().isEmpty()) {\n majorUpdatePatterns.clear();\n for (String majorRule : config.getMajorRules()) {\n majorUpdatePatterns.add(Pattern.compile(majorRule, patternFlags));\n }\n minorUpdatePatterns.clear();\n for (String minorRule : config.getMinorRules()) {",
"score": 0.7639873623847961
}
] | java | = versionRules.getTagPattern().matcher(tag); |
/*
* 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/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.7940988540649414
},
{
"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.7803517580032349
},
{
"filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/ConfigParsingTest.java",
"retrieved_chunk": " void testParseValidTag() {\n String versionRulesConfig = \"\"\n + \"<projectVersionPolicyConfig>\"\n + customVersionTagXML\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());",
"score": 0.7779032588005066
},
{
"filename": "src/main/java/nl/basjes/maven/release/version/conventionalcommits/CommitHistory.java",
"retrieved_chunk": " if (!versionTags.isEmpty()) {\n // Found the previous release tag\n if (versionTags.size() > 1) {\n throw new VersionParseException(\"Most recent commit with tags has multiple version tags: \"\n + versionTags);\n }\n latestVersionTag = versionTags.get(0);\n logger.debug(\"Found tag\");\n break; // We have the last version tag\n }",
"score": 0.769503116607666
},
{
"filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/CommitHistoryTests.java",
"retrieved_chunk": " assertTrue(commitHistoryString.contains(\"Comment: \\\"Two\\\"\"));\n assertTrue(commitHistoryString.contains(\"Tags : [My Tag 1]\"));\n LOG.info(\"Commit history: {}\", commitHistoryString);\n }\n @Test\n void badRequestNoWorkingDirectory() throws ScmException, VersionParseException {\n VersionPolicyRequest request = new VersionPolicyRequest();\n request.setVersion(\"1.2.3\");\n// request.setWorkingDirectory(\"/tmp\");\n ScmProvider scmProvider = createScmProvider();",
"score": 0.7676076889038086
}
] | java | = commitHistory.getLastVersionTag(); |
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/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.9041982293128967
},
{
"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.8279141783714294
},
{
"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.8170064091682434
},
{
"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.7776807546615601
},
{
"filename": "noq-backend/src/main/java/com/noq/backend/repository/HostRepositoryImpl.java",
"retrieved_chunk": " private final Map<String, Host> hosts = new HashMap<>();\n @Override\n public Host save(Host host) {\n hosts.put(host.getHostId(), host);\n return host;\n }\n @Override\n public Host getHostByHostId(String hostId) {\n return hosts.get(hostId);\n }",
"score": 0.7729485034942627
}
] | 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.8538156747817993
},
{
"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.8532519936561584
},
{
"filename": "noq-backend/src/main/java/com/noq/backend/repository/ReservationRepositoryImpl.java",
"retrieved_chunk": " private final Map<String, Reservation> reservations = new HashMap<>();\n @Override\n public Reservation save(Reservation reservation) {\n return reservations.put(reservation.getReservationId(), reservation);\n }\n @Override\n public void saveAll(List<Reservation> reservations){\n for (Reservation reservation : reservations) {\n this.reservations.put(reservation.getReservationId(), reservation);\n }",
"score": 0.8097988367080688
},
{
"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.8086221218109131
},
{
"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.773141622543335
}
] | 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/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.7013330459594727
},
{
"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.7003523707389832
},
{
"filename": "noq-backend/src/main/java/com/noq/backend/services/ReservationService.java",
"retrieved_chunk": " return reservation;\n }\n public Reservation createReservation(CreateReservation createReservation) {\n User user = userRepository.getUserByUserId(createReservation.getUserId());\n user.setReservation(true);\n userRepository.save(user);\n Host host = hostRepository.getHostByHostId(createReservation.getHostId());\n Reservation reservation = new Reservation(host, user, Status.PENDING);\n reservationRepository.save(reservation);\n return reservation;",
"score": 0.6721698045730591
},
{
"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.6692395210266113
},
{
"filename": "noq-backend/src/main/java/com/noq/backend/services/HostService.java",
"retrieved_chunk": " private HostRepository hostRepository;\n @Autowired\n public HostService(HostRepository hostRepository) {\n this.hostRepository = hostRepository;\n }\n public List<Host> getAllHosts() {\n return hostRepository.getAllHosts();\n }\n public List<Host> createHosts() {\n Host host1 = new Host(\"3\", \"Test-Härberget 1\", new Address(UUID.randomUUID().toString(), \"Gatgatan\", \"12\", \"12345\", \"Stockholm\"), \"url/till/bild/pa/Harberget1.png\", 15L);",
"score": 0.6684936285018921
}
] | java | ArrayList<>(userRepository.getAllUsers()); |
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/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.8299983739852905
},
{
"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.819987416267395
},
{
"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.7836623191833496
},
{
"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.7816094160079956
},
{
"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.7605022192001343
}
] | java | User existingUser = userRepository.getUserByUserId(userId); |
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.774341344833374
},
{
"filename": "src/main/java/org/example/service/AccessTokenService.java",
"retrieved_chunk": " private Long expireTimestamp;\n }\n /**\n * init for first accessToken\n */\n @PostConstruct\n public void init() throws Exception {\n if (Objects.isNull(appKey)) {\n throw new RuntimeException(\"please set application.properties app.appKey=xxx\");\n }",
"score": 0.7355724573135376
},
{
"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.7306370735168457
},
{
"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.7132511734962463
},
{
"filename": "src/main/java/org/example/model/DingTalkBotMessage.java",
"retrieved_chunk": " private String conversationId;\n private List<AtUser> atUsers;\n private String chatbotCorpId;\n private String chatbotUserId;\n private String msgId;\n private String senderNick;\n private String isAdmin;\n private String senderStaffId;\n private Long sessionWebhookExpiredTime;\n private Long createAt;",
"score": 0.7128174304962158
}
] | 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/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.8556612133979797
},
{
"filename": "src/main/java/org/objectionary/ObjectsBox.java",
"retrieved_chunk": " * Converts an object to a string.\n * @param name The name of the object.\n * @param bindings The bindings of the object.\n * @return The string representation of the object.\n */\n private static String serialize(\n final String name, final Map<String, Entity> bindings\n ) {\n final List<String> dataizations = Arrays.asList(\"Δ\", \"𝜑\", \"λ\");\n final List<String> result = new ArrayList<>(bindings.size());",
"score": 0.8310940265655518
},
{
"filename": "src/main/java/org/objectionary/entities/NestedObject.java",
"retrieved_chunk": " if (count < size) {\n buffer.append(\", \");\n }\n }\n return String.format(\"%s( %s )\", this.getName(), buffer);\n }\n @Override\n public Entity copy() {\n final Map<String, Entity> copy = new HashMap<>(this.application.size());\n for (final Map.Entry<String, Entity> entry : this.application.entrySet()) {",
"score": 0.8182804584503174
},
{
"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.8125116229057312
},
{
"filename": "src/main/java/org/objectionary/parsing/Entities.java",
"retrieved_chunk": " return result;\n }\n /**\n * Reads nested entity.\n * @return The parsed nested entity.\n */\n public Map<String, Entity> nested() {\n final Map<String, Entity> result = new HashMap<>();\n while (true) {\n final Token token = this.tokenizer.getToken();",
"score": 0.805694043636322
}
] | 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/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.8278290629386902
},
{
"filename": "src/main/java/org/objectionary/entities/NestedObject.java",
"retrieved_chunk": " return this.application;\n }\n @Override\n public String toString() {\n final StringBuilder buffer = new StringBuilder();\n final int size = this.application.size();\n int count = 0;\n for (final Map.Entry<String, Entity> entry : this.getApplication().entrySet()) {\n buffer.append(entry.getKey()).append(\" ↦ \").append(entry.getValue());\n count += 1;",
"score": 0.7873860597610474
},
{
"filename": "src/main/java/org/objectionary/entities/NestedObject.java",
"retrieved_chunk": " copy.put(entry.getKey(), entry.getValue().copy());\n }\n return new NestedObject(this.getName(), copy);\n }\n @Override\n public Entity reframe() {\n final Map<String, Entity> reframed = new HashMap<>(this.application.size());\n for (final Map.Entry<String, Entity> entry : this.application.entrySet()) {\n reframed.put(entry.getKey(), entry.getValue().reframe());\n }",
"score": 0.786231517791748
},
{
"filename": "src/main/java/org/objectionary/entities/NestedObject.java",
"retrieved_chunk": " if (count < size) {\n buffer.append(\", \");\n }\n }\n return String.format(\"%s( %s )\", this.getName(), buffer);\n }\n @Override\n public Entity copy() {\n final Map<String, Entity> copy = new HashMap<>(this.application.size());\n for (final Map.Entry<String, Entity> entry : this.application.entrySet()) {",
"score": 0.7819646596908569
},
{
"filename": "src/main/java/org/objectionary/entities/FlatObject.java",
"retrieved_chunk": " return new FlatObject(this.name, this.locator);\n }\n @Override\n public Entity reframe() {\n final Entity entity;\n if (this.locator.isEmpty()) {\n entity = this.copy();\n } else {\n entity = new FlatObject(this.getName(), \"\");\n }",
"score": 0.7772682309150696
}
] | 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/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.8827876448631287
},
{
"filename": "src/main/java/org/objectionary/ObjectsBox.java",
"retrieved_chunk": " * Converts an object to a string.\n * @param name The name of the object.\n * @param bindings The bindings of the object.\n * @return The string representation of the object.\n */\n private static String serialize(\n final String name, final Map<String, Entity> bindings\n ) {\n final List<String> dataizations = Arrays.asList(\"Δ\", \"𝜑\", \"λ\");\n final List<String> result = new ArrayList<>(bindings.size());",
"score": 0.8706721067428589
},
{
"filename": "src/main/java/org/objectionary/ObjectsBox.java",
"retrieved_chunk": " }\n /**\n * Gets the box of objects.\n * @return The box of objects.\n */\n public Map<String, Map<String, Entity>> content() {\n return this.box;\n }\n /**\n * Converts the box of objects to a string.",
"score": 0.842816948890686
},
{
"filename": "src/main/java/org/objectionary/parsing/Entities.java",
"retrieved_chunk": " return result;\n }\n /**\n * Reads nested entity.\n * @return The parsed nested entity.\n */\n public Map<String, Entity> nested() {\n final Map<String, Entity> result = new HashMap<>();\n while (true) {\n final Token token = this.tokenizer.getToken();",
"score": 0.8418310880661011
},
{
"filename": "src/main/java/org/objectionary/ObjectsBox.java",
"retrieved_chunk": "/**\n * This class represents the objects box.\n * @since 0.1.0\n */\npublic final class ObjectsBox {\n /**\n * The box of objects.\n */\n private final Map<String, Map<String, Entity>> box;\n /**",
"score": 0.8389156460762024
}
] | java | box.get(object.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.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/main/java/org/objectionary/Tokenizer.java",
"retrieved_chunk": " private int position;\n /**\n * Constructor.\n *\n * @param input The input string.\n */\n public Tokenizer(final String input) {\n this.tokens = input.split(\" \");\n this.position = 0;\n }",
"score": 0.919619619846344
},
{
"filename": "src/main/java/org/objectionary/tokens/StringToken.java",
"retrieved_chunk": " * The value of the string.\n */\n private final String value;\n /**\n * Constructor.\n * @param value The value of the string.\n */\n public StringToken(final String value) {\n this.value = value;\n }",
"score": 0.9188872575759888
},
{
"filename": "src/main/java/org/objectionary/Tokenizer.java",
"retrieved_chunk": " /**\n * Checks if there are more tokens.\n * @return True if there are more tokens.\n */\n public boolean hasNext() {\n return this.position < this.tokens.length;\n }\n /**\n * Returns the current token.\n * @return The current token.",
"score": 0.9156913757324219
},
{
"filename": "src/main/java/org/objectionary/parsing/TypeChecker.java",
"retrieved_chunk": " * The token to check the type of.\n */\n private final String token;\n /**\n * Constructor.\n * @param token The token to check the type of.\n */\n public TypeChecker(final String token) {\n this.token = token;\n }",
"score": 0.9121385216712952
},
{
"filename": "src/main/java/org/objectionary/tokens/BracketToken.java",
"retrieved_chunk": " * The state of the bracket.\n */\n private final BracketType state;\n /**\n * Constructor.\n * @param state The state of the bracket.\n */\n public BracketToken(final BracketType state) {\n this.state = state;\n }",
"score": 0.9101652503013611
}
] | java | tokenizer.getToken(); |
/*
* 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/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.8370500206947327
},
{
"filename": "src/main/java/org/objectionary/ObjectsBox.java",
"retrieved_chunk": " * @checkstyle NoJavadocForOverriddenMethodsCheck (10 lines)\n */\n @Override\n public String toString() {\n if (!this.box.containsKey(\"ν0\")) {\n throw new IllegalArgumentException(\"The box does not contain the object ν0.\");\n }\n final List<String> results = new ArrayList<>(this.box.size());\n results.add(ObjectsBox.serialize(\"ν0\", this.box.get(\"ν0\")));\n for (final Map.Entry<String, Map<String, Entity>> entry : this.box.entrySet()) {",
"score": 0.8301708698272705
},
{
"filename": "src/main/java/org/objectionary/entities/NestedObject.java",
"retrieved_chunk": " return this.application;\n }\n @Override\n public String toString() {\n final StringBuilder buffer = new StringBuilder();\n final int size = this.application.size();\n int count = 0;\n for (final Map.Entry<String, Entity> entry : this.getApplication().entrySet()) {\n buffer.append(entry.getKey()).append(\" ↦ \").append(entry.getValue());\n count += 1;",
"score": 0.8230260610580444
},
{
"filename": "src/main/java/org/objectionary/entities/NestedObject.java",
"retrieved_chunk": " copy.put(entry.getKey(), entry.getValue().copy());\n }\n return new NestedObject(this.getName(), copy);\n }\n @Override\n public Entity reframe() {\n final Map<String, Entity> reframed = new HashMap<>(this.application.size());\n for (final Map.Entry<String, Entity> entry : this.application.entrySet()) {\n reframed.put(entry.getKey(), entry.getValue().reframe());\n }",
"score": 0.8103824853897095
},
{
"filename": "src/main/java/org/objectionary/entities/NestedObject.java",
"retrieved_chunk": " if (count < size) {\n buffer.append(\", \");\n }\n }\n return String.format(\"%s( %s )\", this.getName(), buffer);\n }\n @Override\n public Entity copy() {\n final Map<String, Entity> copy = new HashMap<>(this.application.size());\n for (final Map.Entry<String, Entity> entry : this.application.entrySet()) {",
"score": 0.800613284111023
}
] | java | ).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.7589183449745178
},
{
"filename": "src/main/java/org/example/service/RobotGroupMessagesService.java",
"retrieved_chunk": " config.protocol = \"https\";\n config.regionId = \"central\";\n robotClient = new Client(config);\n }\n /**\n * send message to group with openConversationId\n *\n * @param openConversationId conversationId\n * @return messageId\n * @throws Exception e",
"score": 0.7509369850158691
},
{
"filename": "src/main/java/org/example/StreamCallbackListener.java",
"retrieved_chunk": " private RobotMsgCallbackConsumer robotMsgCallbackConsumer;\n public StreamCallbackListener(@Autowired RobotMsgCallbackConsumer robotMsgCallbackConsumer) {\n this.robotMsgCallbackConsumer = robotMsgCallbackConsumer;\n }\n @PostConstruct\n public void init() throws Exception {\n // init stream client\n OpenDingTalkClient client = OpenDingTalkStreamClientBuilder\n .custom()\n .credential(new AuthClientCredential(appKey, appSecret))",
"score": 0.7325961589813232
},
{
"filename": "src/main/java/org/example/service/RobotGroupMessagesService.java",
"retrieved_chunk": " orgGroupSendRequest.setMsgParam(msgParam.toJSONString());\n try {\n OrgGroupSendResponse orgGroupSendResponse = robotClient.orgGroupSendWithOptions(orgGroupSendRequest,\n orgGroupSendHeaders, new com.aliyun.teautil.models.RuntimeOptions());\n if (Objects.isNull(orgGroupSendResponse) || Objects.isNull(orgGroupSendResponse.getBody())) {\n log.error(\"RobotGroupMessagesService_send orgGroupSendWithOptions return error, response={}\",\n orgGroupSendResponse);\n return null;\n }\n return orgGroupSendResponse.getBody().getProcessQueryKey();",
"score": 0.7294045686721802
},
{
"filename": "src/main/java/org/example/service/RobotGroupMessagesService.java",
"retrieved_chunk": " } catch (TeaException e) {\n log.error(\"RobotGroupMessagesService_send orgGroupSendWithOptions throw TeaException, errCode={}, \" +\n \"errorMessage={}\", e.getCode(), e.getMessage(), e);\n throw e;\n } catch (Exception e) {\n log.error(\"RobotGroupMessagesService_send orgGroupSendWithOptions throw Exception\", e);\n throw e;\n }\n }\n}",
"score": 0.7031300663948059
}
] | 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;
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/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.7867449522018433
},
{
"filename": "src/main/java/org/objectionary/entities/NestedObject.java",
"retrieved_chunk": " copy.put(entry.getKey(), entry.getValue().copy());\n }\n return new NestedObject(this.getName(), copy);\n }\n @Override\n public Entity reframe() {\n final Map<String, Entity> reframed = new HashMap<>(this.application.size());\n for (final Map.Entry<String, Entity> entry : this.application.entrySet()) {\n reframed.put(entry.getKey(), entry.getValue().reframe());\n }",
"score": 0.7825279831886292
},
{
"filename": "src/main/java/org/objectionary/parsing/Entities.java",
"retrieved_chunk": " private Entity createObject(final String value) {\n final Entity result;\n if (value.contains(\")\")) {\n result = new FlatObject(\n value.substring(0, value.indexOf('(')),\n value.substring(value.indexOf('(') + 1, value.indexOf(')'))\n );\n } else if (value.contains(\"(\")) {\n this.tokenizer.next();\n final Map<String, Entity> application = this.nested();",
"score": 0.7241000533103943
},
{
"filename": "src/main/java/org/objectionary/entities/FlatObject.java",
"retrieved_chunk": " return new FlatObject(this.name, this.locator);\n }\n @Override\n public Entity reframe() {\n final Entity entity;\n if (this.locator.isEmpty()) {\n entity = this.copy();\n } else {\n entity = new FlatObject(this.getName(), \"\");\n }",
"score": 0.722217857837677
},
{
"filename": "src/main/java/org/objectionary/ObjectsBox.java",
"retrieved_chunk": " * @checkstyle NoJavadocForOverriddenMethodsCheck (10 lines)\n */\n @Override\n public String toString() {\n if (!this.box.containsKey(\"ν0\")) {\n throw new IllegalArgumentException(\"The box does not contain the object ν0.\");\n }\n final List<String> results = new ArrayList<>(this.box.size());\n results.add(ObjectsBox.serialize(\"ν0\", this.box.get(\"ν0\")));\n for (final Map.Entry<String, Map<String, Entity>> entry : this.box.entrySet()) {",
"score": 0.7088398933410645
}
] | java | ((FlatObject) binding.getValue()).getLocator())
); |
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.8225845694541931
},
{
"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.7869735956192017
},
{
"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.7641333341598511
},
{
"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.7102992534637451
},
{
"filename": "src/main/java/onebeastchris/util/PlayerDataUtil.java",
"retrieved_chunk": " public static boolean isVisitor(GameProfile gameProfile){\n return visitorMap.containsKey(gameProfile);\n }\n public static void removeVisitor(GameProfile gameProfile){\n visitorMap.remove(gameProfile);\n }\n}",
"score": 0.6782639026641846
}
] | 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.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": " 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.8491678237915039
},
{
"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.8416008353233337
},
{
"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.8360704779624939
},
{
"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.8066559433937073
},
{
"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.7770542502403259
}
] | 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": " 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.793526291847229
},
{
"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.7584676146507263
},
{
"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.7477531433105469
},
{
"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.7290132641792297
},
{
"filename": "src/main/java/committee/nova/flotage/init/TabRegistry.java",
"retrieved_chunk": " entries.add(new ItemStack(ItemRegistry.get(member.brokenRaft())));\n entries.add(new ItemStack(ItemRegistry.get(member.fence())));\n entries.add(new ItemStack(ItemRegistry.get(member.crossedFence())));\n entries.add(new ItemStack(ItemRegistry.get(member.rack())));\n }\n }))\n .icon(() -> new ItemStack(ItemRegistry.get(BlockMember.OAK.rack())))\n .texture(\"flotage.png\")\n .noRenderedName()\n .noScrollbar()",
"score": 0.7019323706626892
}
] | 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/util/BlockMember.java",
"retrieved_chunk": "package committee.nova.flotage.util;\nimport net.minecraft.block.Block;\nimport net.minecraft.block.Blocks;\nimport net.minecraft.registry.Registries;\nimport net.minecraft.util.Identifier;\npublic enum BlockMember {\n OAK(Blocks.OAK_LOG, \"橡木\"),\n SPRUCE(Blocks.SPRUCE_LOG, \"云杉木\"),\n BIRCH(Blocks.BIRCH_LOG, \"白桦木\"),\n JUNGLE(Blocks.JUNGLE_LOG, \"丛林木\"),",
"score": 0.6396040916442871
},
{
"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.6269938945770264
},
{
"filename": "src/main/java/committee/nova/flotage/compat/rei/FlotageREIPlugin.java",
"retrieved_chunk": "package committee.nova.flotage.compat.rei;\nimport committee.nova.flotage.Flotage;\nimport committee.nova.flotage.compat.rei.category.RackREICategory;\nimport committee.nova.flotage.compat.rei.display.RackREIDisplay;\nimport committee.nova.flotage.impl.recipe.RackRecipe;\nimport committee.nova.flotage.impl.recipe.RackRecipeType;\nimport committee.nova.flotage.init.BlockRegistry;\nimport me.shedaniel.rei.api.client.plugins.REIClientPlugin;\nimport me.shedaniel.rei.api.client.registry.category.CategoryRegistry;\nimport me.shedaniel.rei.api.client.registry.display.DisplayRegistry;",
"score": 0.6249107718467712
},
{
"filename": "src/main/java/committee/nova/flotage/compat/emi/recipe/RackEMIRecipe.java",
"retrieved_chunk": "package committee.nova.flotage.compat.emi.recipe;\nimport committee.nova.flotage.compat.emi.FlotageEMIPlugin;\nimport committee.nova.flotage.impl.recipe.RackRecipe;\nimport dev.emi.emi.api.recipe.EmiRecipe;\nimport dev.emi.emi.api.recipe.EmiRecipeCategory;\nimport dev.emi.emi.api.stack.EmiIngredient;\nimport dev.emi.emi.api.stack.EmiStack;\nimport dev.emi.emi.api.widget.WidgetHolder;\nimport net.minecraft.util.Identifier;\nimport org.jetbrains.annotations.Nullable;",
"score": 0.6165429353713989
},
{
"filename": "src/main/java/committee/nova/flotage/impl/block/RackBlock.java",
"retrieved_chunk": "package committee.nova.flotage.impl.block;\nimport committee.nova.flotage.impl.tile.RackBlockEntity;\nimport committee.nova.flotage.util.BlockMember;\nimport committee.nova.flotage.init.TileRegistry;\nimport net.minecraft.block.*;\nimport net.minecraft.block.entity.BlockEntity;\nimport net.minecraft.block.entity.BlockEntityTicker;\nimport net.minecraft.block.entity.BlockEntityType;\nimport net.minecraft.block.enums.Instrument;\nimport net.minecraft.entity.player.PlayerEntity;",
"score": 0.6147522926330566
}
] | 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": " 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.8618389964103699
},
{
"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.8085011839866638
},
{
"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.794622540473938
},
{
"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.7820780277252197
},
{
"filename": "src/main/java/committee/nova/flotage/init/TabRegistry.java",
"retrieved_chunk": " entries.add(new ItemStack(ItemRegistry.get(member.brokenRaft())));\n entries.add(new ItemStack(ItemRegistry.get(member.fence())));\n entries.add(new ItemStack(ItemRegistry.get(member.crossedFence())));\n entries.add(new ItemStack(ItemRegistry.get(member.rack())));\n }\n }))\n .icon(() -> new ItemStack(ItemRegistry.get(BlockMember.OAK.rack())))\n .texture(\"flotage.png\")\n .noRenderedName()\n .noScrollbar()",
"score": 0.726963222026825
}
] | 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": " 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.8199835419654846
},
{
"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.7733919620513916
},
{
"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.7658520340919495
},
{
"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.7593315839767456
},
{
"filename": "src/main/java/committee/nova/flotage/init/TabRegistry.java",
"retrieved_chunk": " entries.add(new ItemStack(ItemRegistry.get(member.brokenRaft())));\n entries.add(new ItemStack(ItemRegistry.get(member.fence())));\n entries.add(new ItemStack(ItemRegistry.get(member.crossedFence())));\n entries.add(new ItemStack(ItemRegistry.get(member.rack())));\n }\n }))\n .icon(() -> new ItemStack(ItemRegistry.get(BlockMember.OAK.rack())))\n .texture(\"flotage.png\")\n .noRenderedName()\n .noScrollbar()",
"score": 0.7180286049842834
}
] | 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.8600778579711914
},
{
"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.8086134195327759
},
{
"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.7897011041641235
},
{
"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.7798173427581787
},
{
"filename": "src/main/java/committee/nova/flotage/init/TabRegistry.java",
"retrieved_chunk": " entries.add(new ItemStack(ItemRegistry.get(member.brokenRaft())));\n entries.add(new ItemStack(ItemRegistry.get(member.fence())));\n entries.add(new ItemStack(ItemRegistry.get(member.crossedFence())));\n entries.add(new ItemStack(ItemRegistry.get(member.rack())));\n }\n }))\n .icon(() -> new ItemStack(ItemRegistry.get(BlockMember.OAK.rack())))\n .texture(\"flotage.png\")\n .noRenderedName()\n .noScrollbar()",
"score": 0.7291063070297241
}
] | 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": " 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.8524699211120605
},
{
"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.7963414788246155
},
{
"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.7949759364128113
},
{
"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.7748781442642212
},
{
"filename": "src/main/java/committee/nova/flotage/init/TabRegistry.java",
"retrieved_chunk": " entries.add(new ItemStack(ItemRegistry.get(member.brokenRaft())));\n entries.add(new ItemStack(ItemRegistry.get(member.fence())));\n entries.add(new ItemStack(ItemRegistry.get(member.crossedFence())));\n entries.add(new ItemStack(ItemRegistry.get(member.rack())));\n }\n }))\n .icon(() -> new ItemStack(ItemRegistry.get(BlockMember.OAK.rack())))\n .texture(\"flotage.png\")\n .noRenderedName()\n .noScrollbar()",
"score": 0.7293943166732788
}
] | 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": " 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.8167263269424438
},
{
"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.771159827709198
},
{
"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.7672326564788818
},
{
"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.7579686641693115
},
{
"filename": "src/main/java/committee/nova/flotage/init/TabRegistry.java",
"retrieved_chunk": " entries.add(new ItemStack(ItemRegistry.get(member.brokenRaft())));\n entries.add(new ItemStack(ItemRegistry.get(member.fence())));\n entries.add(new ItemStack(ItemRegistry.get(member.crossedFence())));\n entries.add(new ItemStack(ItemRegistry.get(member.rack())));\n }\n }))\n .icon(() -> new ItemStack(ItemRegistry.get(BlockMember.OAK.rack())))\n .texture(\"flotage.png\")\n .noRenderedName()\n .noScrollbar()",
"score": 0.717099666595459
}
] | 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.727451503276825
},
{
"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.7013229131698608
},
{
"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.7009894847869873
},
{
"filename": "src/main/java/committee/nova/flotage/compat/jade/provider/RackBlockTipProvider.java",
"retrieved_chunk": "import snownee.jade.api.ITooltip;\nimport snownee.jade.api.config.IPluginConfig;\npublic class RackBlockTipProvider implements IBlockComponentProvider, IServerDataProvider<BlockAccessor> {\n public static final RackBlockTipProvider INSTANCE = new RackBlockTipProvider();\n private RackBlockTipProvider() {}\n @Override\n public void appendTooltip(ITooltip tooltip, BlockAccessor accessor, IPluginConfig iPluginConfig) {\n if (accessor.getServerData().contains(\"WorkingMode\")) {\n WorkingMode mode = WorkingMode.match(accessor.getServerData().getString(\"WorkingMode\"));\n MutableText text = Text.translatable(\"tip.flotage.rack.mode\").append(Text.translatable(\"tip.flotage.rack.mode.\" + mode.toString()));",
"score": 0.6774078607559204
},
{
"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.6726185083389282
}
] | 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": " 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.7925688028335571
},
{
"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.7569370269775391
},
{
"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.7488640546798706
},
{
"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.7284225225448608
},
{
"filename": "src/main/java/committee/nova/flotage/init/TabRegistry.java",
"retrieved_chunk": " entries.add(new ItemStack(ItemRegistry.get(member.brokenRaft())));\n entries.add(new ItemStack(ItemRegistry.get(member.fence())));\n entries.add(new ItemStack(ItemRegistry.get(member.crossedFence())));\n entries.add(new ItemStack(ItemRegistry.get(member.rack())));\n }\n }))\n .icon(() -> new ItemStack(ItemRegistry.get(BlockMember.OAK.rack())))\n .texture(\"flotage.png\")\n .noRenderedName()\n .noScrollbar()",
"score": 0.7020246386528015
}
] | 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\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.8078362345695496
},
{
"filename": "src/main/java/com/orangomango/chess/MainApplication.java",
"retrieved_chunk": "\tpublic static void main(String[] args) throws IOException{\n\t\tif (args.length >= 1){\n\t\t\tString col = args[0];\n\t\t\tif (col.equals(\"WHITE\")){\n\t\t\t\tstartColor = Color.WHITE;\n\t\t\t} else {\n\t\t\t\tstartColor = Color.BLACK;\n\t\t\t}\n\t\t}\n\t\tlaunch(args);",
"score": 0.8061019778251648
},
{
"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.7957346439361572
},
{
"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.7588369846343994
},
{
"filename": "src/main/java/com/orangomango/chess/Board.java",
"retrieved_chunk": "\t\t}\n\t\tif (isCheckMate(piece.getColor() == Color.WHITE ? Color.BLACK : Color.WHITE)){\n\t\t\toutput += \"#\";\n\t\t} else if (check){\n\t\t\toutput += \"+\";\n\t\t}\n\t\treturn output;\n\t}\n\tpublic int getTime(Color color){\n\t\treturn color == Color.WHITE ? (int)this.whiteTime : (int)this.blackTime;",
"score": 0.7348088026046753
}
] | 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/Logger.java",
"retrieved_chunk": "\t\t\t}\n\t\t} catch (IOException ex){\n\t\t\tex.printStackTrace();\n\t\t}\n\t}\n\tpublic static void writeInfo(String msg){\n\t\twrite(\"INFO\", msg);\n\t}\n\tpublic static void writeError(String msg){\n\t\twrite(\"ERROR\", msg);",
"score": 0.7875956296920776
},
{
"filename": "src/main/java/com/orangomango/chess/multiplayer/Client.java",
"retrieved_chunk": "\t\t\t\tSystem.exit(0);\n\t\t\t}\n\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\tpublic boolean isConnected(){",
"score": 0.7862088680267334
},
{
"filename": "src/main/java/com/orangomango/chess/PieceAnimation.java",
"retrieved_chunk": "\t}\n\tpublic String getEndNotation(){\n\t\treturn this.end;\n\t}\n\tpublic Point2D getPosition(){\n\t\treturn this.pos;\n\t}\n}",
"score": 0.7706775069236755
},
{
"filename": "src/main/java/com/orangomango/chess/MainApplication.java",
"retrieved_chunk": "\t\t\t\t\t\t\tthis.dragX = e.getX();\n\t\t\t\t\t\t\tthis.dragY = e.getY();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (e.getClickCount() == 2){\n\t\t\t\t\tSystem.out.println(this.board.getFEN());\n\t\t\t\t\tSystem.out.println(this.board.getPGN());\n\t\t\t\t\tAlert alert = new Alert(Alert.AlertType.INFORMATION);\n\t\t\t\t\talert.setTitle(\"Settings\");\n\t\t\t\t\talert.setHeaderText(\"Setup game\");",
"score": 0.7597436904907227
},
{
"filename": "src/main/java/com/orangomango/chess/MainApplication.java",
"retrieved_chunk": "\t\t\tx = 7-x;\n\t\t\ty = 7-y;\n\t\t}\n\t\treturn Board.convertPosition(x, y);\n\t}\n\tprivate void reset(String text, long time, int inc){\n\t\tString fen = STARTPOS;\n\t\tif (text.startsWith(\"CUSTOM\\n\")){\n\t\t\tfen = text.split(\"\\n\")[1];\n\t\t}",
"score": 0.7503669261932373
}
] | 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.8058160543441772
},
{
"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.7658731341362
},
{
"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.7615975141525269
},
{
"filename": "src/main/java/org/swmaestro/kauth/core/jwt/JwtFilterChain.java",
"retrieved_chunk": "\t * @return 현재 인스턴스\n\t */\n\tpublic JwtFilterChain UsernamePassword(String pattern) {\n\t\tsuper.addFilterBefore(new JwtUsernamePasswordAuthenticationFilter(\"/\" + pattern,\n\t\t\t\tthis.jwtUtil, this.authenticationManager, this.objectMapper, refreshTokenManager, responseUtil),\n\t\t\tJwtAuthorizationFilter.class);\n\t\treturn this;\n\t}\n}",
"score": 0.7377630472183228
},
{
"filename": "src/main/java/org/swmaestro/kauth/core/jwt/JwtFilterChainBuilder.java",
"retrieved_chunk": "\tpublic JwtFilterChainBuilder(HttpSecurity httpSecurity, JwtUtil jwtUtil,\n\t\tAuthenticationManager authenticationManager, ObjectMapper objectMapper, HttpServletResponseUtil responseUtil,\n\t\tRefreshTokenManager refreshTokenManager) {\n\t\tsuper(httpSecurity, authenticationManager, responseUtil);\n\t\tthis.jwtUtil = jwtUtil;\n\t\tthis.objectMapper = objectMapper;\n\t\tthis.refreshTokenManager = refreshTokenManager;\n\t}\n\t/**\n\t * {@link JwtFilterChain} 인스턴스를 생성하고 반환한다.",
"score": 0.7049661874771118
}
] | java | username = jwtUtil.verifyToken(token); |
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": " //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.9415849447250366
},
{
"filename": "backend/src/main/java/com/upCycle/service/UsuarioService.java",
"retrieved_chunk": " }\n //Usuario user = oUser.orElseThrow(() -> new UserNotExistException(\"Este usuario no existe, intente con otro correo\"));//Corregir. Capturar excepción\n Usuario usuario = oUser.get();\n if(usuario.getRol().equals(Rol.ECOPROVEEDOR)){\n Optional<Ecoproveedor> oEcoproveedor = repository.buscarEcoproveedorPorId(usuario.getId());\n if(oEcoproveedor.isPresent()){\n Ecoproveedor ecoproveedor = oEcoproveedor.get();\n session.setAttribute(\"usuarioLogueado\", ecoproveedor);\n return ecoproveedorMapper.entidadADtoEcoproveedor(ecoproveedor);\n }",
"score": 0.9339805841445923
},
{
"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.9263842105865479
},
{
"filename": "backend/src/main/java/com/upCycle/service/ProductoService.java",
"retrieved_chunk": " */\n Optional<Producto> oProducto = repository.findById(id);\n if(oProducto.isPresent()){\n Producto producto = oProducto.get();\n Optional<Ecoproveedor> oEcoproveedor = usuarioRepository.buscarEcoproveedorPorId(producto.getEcoproveedor().getId());\n Ecoproveedor ecoproveedor = oEcoproveedor.orElse(null);\n assert ecoproveedor != null;\n return EcoproveedorMapper.entidadADtoEcoproveedor(ecoproveedor);\n }\n return null;",
"score": 0.9212219715118408
},
{
"filename": "backend/src/main/java/com/upCycle/mapper/EcoproveedorMapper.java",
"retrieved_chunk": " dtoEcoproveedor.setEmail(ecoproveedor.getEmail());\n dtoEcoproveedor.setCompanyName(ecoproveedor.getRazonSocial());\n dtoEcoproveedor.setRol(ecoproveedor.getRol().name());\n List<DtoProductoResponse> productos = publicacionMapper.entidadProductoListADtoList(ecoproveedor.getListaProductos());\n dtoEcoproveedor.setListaProductos(productos);\n return dtoEcoproveedor;\n }\n}",
"score": 0.9196047186851501
}
] | java | ecoproveedor.calcularPuntosTotales(); |
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\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.8358203172683716
},
{
"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.8097269535064697
},
{
"filename": "src/main/java/com/orangomango/chess/multiplayer/Client.java",
"retrieved_chunk": "\tprivate BufferedReader reader;\n\tprivate Color color;\n\tpublic Client(String ip, int port, Color color){\n\t\tthis.ip = ip;\n\t\tthis.port = port;\n\t\ttry {\n\t\t\tthis.socket = new Socket(ip, port);\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\tsendMessage(color == Color.WHITE ? \"WHITE\" : \"BLACK\");",
"score": 0.7786746621131897
},
{
"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.7597929835319519
},
{
"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.7570046186447144
}
] | java | cm.reply(); |
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/MainApplication.java",
"retrieved_chunk": "\t\t\tx = 7-x;\n\t\t\ty = 7-y;\n\t\t}\n\t\treturn Board.convertPosition(x, y);\n\t}\n\tprivate void reset(String text, long time, int inc){\n\t\tString fen = STARTPOS;\n\t\tif (text.startsWith(\"CUSTOM\\n\")){\n\t\t\tfen = text.split(\"\\n\")[1];\n\t\t}",
"score": 0.7627179622650146
},
{
"filename": "src/main/java/com/orangomango/chess/Board.java",
"retrieved_chunk": "\t\treturn this.gameTime;\n\t}\n\tpublic int getIncrementTime(){\n\t\treturn this.increment;\n\t}\n\tprivate void setupBoard(String fen){\n\t\tString[] data = fen.split(\" \");\n\t\tthis.whiteKing = null;\n\t\tthis.blackKing = null;\n\t\tint r = 0;",
"score": 0.7599374055862427
},
{
"filename": "src/main/java/com/orangomango/chess/Board.java",
"retrieved_chunk": "\t\tif (this.player == Color.WHITE){\n\t\t\tthis.whiteTime -= time;\n\t\t} else {\n\t\t\tthis.blackTime -= time;\n\t\t}\n\t\tthis.whiteTime = Math.max(this.whiteTime, 0);\n\t\tthis.blackTime = Math.max(this.blackTime, 0);\n\t\tthis.lastTime = System.currentTimeMillis();\n\t}\n\tpublic long getGameTime(){",
"score": 0.756799042224884
},
{
"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.7553483247756958
},
{
"filename": "src/main/java/com/orangomango/chess/MainApplication.java",
"retrieved_chunk": "\t\t\t\t\t\t\tthis.dragX = e.getX();\n\t\t\t\t\t\t\tthis.dragY = e.getY();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (e.getClickCount() == 2){\n\t\t\t\t\tSystem.out.println(this.board.getFEN());\n\t\t\t\t\tSystem.out.println(this.board.getPGN());\n\t\t\t\t\tAlert alert = new Alert(Alert.AlertType.INFORMATION);\n\t\t\t\t\talert.setTitle(\"Settings\");\n\t\t\t\t\talert.setHeaderText(\"Setup game\");",
"score": 0.7547705173492432
}
] | java | getIncrementTime(), b.getIncrementTime())); |
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/jwt/JwtReissueFilter.java",
"retrieved_chunk": "\t\tif (requestMatcher.matches(request)) {\n\t\t\ttry {\n\t\t\t\tString token = request.getHeader(\"Refresh-Token\");\n\t\t\t\tif (token == null) {\n\t\t\t\t\tthrow new RefreshTokenMissingException();\n\t\t\t\t}\n\t\t\t\tString username = jwtUtil.verifyToken(token);\n\t\t\t\tif (!refreshTokenManager.getRefreshToken(username).equals(token)) {\n\t\t\t\t\tresponseUtil.setUnauthorizedResponse(response,\n\t\t\t\t\t\tnew RefreshTokenMismatchException(\"RefreshTokens are not match.\"));",
"score": 0.7613070607185364
},
{
"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.7396191358566284
},
{
"filename": "src/main/java/org/swmaestro/kauth/authentication/jwt/JwtReissueFilter.java",
"retrieved_chunk": "\t\t\t\t}\n\t\t\t\tString accessToken = jwtUtil.createAccessToken(username);\n\t\t\t\tString refreshToken = jwtUtil.createRefreshToken(username);\n\t\t\t\trefreshTokenManager.setRefreshToken(refreshToken, username);\n\t\t\t\tresponseUtil.setHeader(response, \"Authorization\", accessToken);\n\t\t\t\tresponseUtil.setHeader(response, \"Refresh-Token\", refreshToken);\n\t\t\t} catch (RefreshTokenMissingException | RefreshTokenServiceUnavailableException |\n\t\t\t\t\t RefreshTokenMismatchException | JWTVerificationException e) {\n\t\t\t\tresponseUtil.setUnauthorizedResponse(response, e);\n\t\t\t}",
"score": 0.7279783487319946
},
{
"filename": "src/main/java/org/swmaestro/kauth/authentication/AuthenticationProvider.java",
"retrieved_chunk": "\t@Override\n\tpublic boolean isAuthenticated() {\n\t\treturn this.isAuthenticated;\n\t}\n\t/**\n\t * {@link #details}을 설정한다.\n\t * @param details {@link org.springframework.security.core.userdetails.UserDetails}\n\t */\n\tpublic void setDetails(Object details) {\n\t\tthis.details = details;",
"score": 0.6886255145072937
},
{
"filename": "src/test/java/org/swmaestro/kauth/integration/KSecurityConfigurationTests.java",
"retrieved_chunk": " return new BCryptPasswordEncoder();\n }\n @Bean\n UserDetailsService userDetailsService() {\n UserDetails user = User.withDefaultPasswordEncoder().username(\"user\").password(\"password\").roles(\"USER\").build();\n return new InMemoryUserDetailsManager(user);\n }\n }\n}",
"score": 0.6720962524414062
}
] | java | auth.eraseCredentials(); |
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.8490878343582153
},
{
"filename": "src/main/java/org/swmaestro/kauth/authentication/AuthenticationProvider.java",
"retrieved_chunk": "\t * @param credential {@link Object}\n\t */\n\tpublic AuthenticationProvider(Object principal, Object credential) {\n\t\tthis.principal = principal;\n\t\tthis.credential = credential;\n\t}\n\t/**\n\t * 권한을 설정한다.\n\t * @param authorities {@link Collection<GrantedAuthority>}\n\t */",
"score": 0.8402172327041626
},
{
"filename": "src/main/java/org/swmaestro/kauth/authentication/AbstractUsernamePasswordAuthenticationFilter.java",
"retrieved_chunk": "\t * @param response {@link HttpServletResponse}\n\t * @param failed {@link AuthenticationException}\n\t * @throws IOException\n\t * @throws ServletException\n\t */\n\t@Override\n\tprotected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,\n\t\tAuthenticationException failed) throws IOException, ServletException {\n\t\t// TODO 오류 메세지 형식\n\t\tif (failed.getClass().equals(UsernameNotFoundException.class)) {",
"score": 0.8399105072021484
},
{
"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.8335328102111816
},
{
"filename": "src/main/java/org/swmaestro/kauth/authentication/AuthenticationProvider.java",
"retrieved_chunk": "\t@Override\n\tpublic boolean isAuthenticated() {\n\t\treturn this.isAuthenticated;\n\t}\n\t/**\n\t * {@link #details}을 설정한다.\n\t * @param details {@link org.springframework.security.core.userdetails.UserDetails}\n\t */\n\tpublic void setDetails(Object details) {\n\t\tthis.details = details;",
"score": 0.8293170928955078
}
] | java | user = userDetailsService.loadUserByUsername((String)auth.getPrincipal()); |
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/MainApplication.java",
"retrieved_chunk": "\t\t\tx = 7-x;\n\t\t\ty = 7-y;\n\t\t}\n\t\treturn Board.convertPosition(x, y);\n\t}\n\tprivate void reset(String text, long time, int inc){\n\t\tString fen = STARTPOS;\n\t\tif (text.startsWith(\"CUSTOM\\n\")){\n\t\t\tfen = text.split(\"\\n\")[1];\n\t\t}",
"score": 0.7640831470489502
},
{
"filename": "src/main/java/com/orangomango/chess/Board.java",
"retrieved_chunk": "\t\treturn this.gameTime;\n\t}\n\tpublic int getIncrementTime(){\n\t\treturn this.increment;\n\t}\n\tprivate void setupBoard(String fen){\n\t\tString[] data = fen.split(\" \");\n\t\tthis.whiteKing = null;\n\t\tthis.blackKing = null;\n\t\tint r = 0;",
"score": 0.7619696855545044
},
{
"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.757700502872467
},
{
"filename": "src/main/java/com/orangomango/chess/MainApplication.java",
"retrieved_chunk": "\t\t\t\t\t\t\tthis.dragX = e.getX();\n\t\t\t\t\t\t\tthis.dragY = e.getY();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (e.getClickCount() == 2){\n\t\t\t\t\tSystem.out.println(this.board.getFEN());\n\t\t\t\t\tSystem.out.println(this.board.getPGN());\n\t\t\t\t\tAlert alert = new Alert(Alert.AlertType.INFORMATION);\n\t\t\t\t\talert.setTitle(\"Settings\");\n\t\t\t\t\talert.setHeaderText(\"Setup game\");",
"score": 0.7570290565490723
},
{
"filename": "src/main/java/com/orangomango/chess/Board.java",
"retrieved_chunk": "\t\tif (this.player == Color.WHITE){\n\t\t\tthis.whiteTime -= time;\n\t\t} else {\n\t\t\tthis.blackTime -= time;\n\t\t}\n\t\tthis.whiteTime = Math.max(this.whiteTime, 0);\n\t\tthis.blackTime = Math.max(this.blackTime, 0);\n\t\tthis.lastTime = System.currentTimeMillis();\n\t}\n\tpublic long getGameTime(){",
"score": 0.7559735774993896
}
] | java | Color.WHITE), b.getTime(Color.BLACK), b.getIncrementTime(), b.getIncrementTime())); |
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.684442400932312
},
{
"filename": "src/main/java/committee/nova/flotage/util/BlockMember.java",
"retrieved_chunk": "package committee.nova.flotage.util;\nimport net.minecraft.block.Block;\nimport net.minecraft.block.Blocks;\nimport net.minecraft.registry.Registries;\nimport net.minecraft.util.Identifier;\npublic enum BlockMember {\n OAK(Blocks.OAK_LOG, \"橡木\"),\n SPRUCE(Blocks.SPRUCE_LOG, \"云杉木\"),\n BIRCH(Blocks.BIRCH_LOG, \"白桦木\"),\n JUNGLE(Blocks.JUNGLE_LOG, \"丛林木\"),",
"score": 0.6377158761024475
},
{
"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.6348284482955933
},
{
"filename": "src/main/java/committee/nova/flotage/compat/rei/FlotageREIPlugin.java",
"retrieved_chunk": "package committee.nova.flotage.compat.rei;\nimport committee.nova.flotage.Flotage;\nimport committee.nova.flotage.compat.rei.category.RackREICategory;\nimport committee.nova.flotage.compat.rei.display.RackREIDisplay;\nimport committee.nova.flotage.impl.recipe.RackRecipe;\nimport committee.nova.flotage.impl.recipe.RackRecipeType;\nimport committee.nova.flotage.init.BlockRegistry;\nimport me.shedaniel.rei.api.client.plugins.REIClientPlugin;\nimport me.shedaniel.rei.api.client.registry.category.CategoryRegistry;\nimport me.shedaniel.rei.api.client.registry.display.DisplayRegistry;",
"score": 0.6163613796234131
},
{
"filename": "src/main/java/committee/nova/flotage/init/TabRegistry.java",
"retrieved_chunk": " entries.add(new ItemStack(ItemRegistry.get(member.brokenRaft())));\n entries.add(new ItemStack(ItemRegistry.get(member.fence())));\n entries.add(new ItemStack(ItemRegistry.get(member.crossedFence())));\n entries.add(new ItemStack(ItemRegistry.get(member.rack())));\n }\n }))\n .icon(() -> new ItemStack(ItemRegistry.get(BlockMember.OAK.rack())))\n .texture(\"flotage.png\")\n .noRenderedName()\n .noScrollbar()",
"score": 0.6112010478973389
}
] | 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}\n\tprivate boolean isPromotion(String a, String b){\n\t\tPiece piece = this.board.getBoard()[Board.convertNotation(a)[0]][Board.convertNotation(a)[1]];\n\t\tif (piece.getType().getName() == Piece.PIECE_PAWN){\n\t\t\tif (piece.getColor() == Color.WHITE && Board.convertNotation(b)[1] == 0){\n\t\t\t\treturn true;\n\t\t\t} else if (piece.getColor() == Color.BLACK && Board.convertNotation(b)[1] == 7){\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn false;",
"score": 0.7987140417098999
},
{
"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.7688367962837219
},
{
"filename": "src/main/java/com/orangomango/chess/MainApplication.java",
"retrieved_chunk": "\t\t\t\t\t\t\tPiece prom = new Piece(Piece.Pieces.QUEEN, this.draggingPiece.getColor(), -1, -1);\n\t\t\t\t\t\t\tif (this.draggingPiece.getColor() == Color.WHITE && y == 0 && this.draggingPiece.getY() == 1){\n\t\t\t\t\t\t\t\tthis.promotionPiece = prom;\n\t\t\t\t\t\t\t} else if (this.draggingPiece.getColor() == Color.BLACK && y == 7 && this.draggingPiece.getY() == 6){\n\t\t\t\t\t\t\t\tthis.promotionPiece = prom;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if ((e.getY() > oldY && this.draggingPiece.getColor() == Color.WHITE) || (e.getY() < oldY && this.draggingPiece.getColor() == Color.BLACK)){\n\t\t\t\t\t\tdouble y = this.draggingPiece.getColor() == Color.WHITE ? 0 : 8;\n\t\t\t\t\t\ty *= SQUARE_SIZE;",
"score": 0.7512989044189453
},
{
"filename": "src/main/java/com/orangomango/chess/MainApplication.java",
"retrieved_chunk": "\t\t}\n\t\tfor (int i = 0; i < 8; i++){\n\t\t\tfor (int j = 0; j < 8; j++){\n\t\t\t\tPiece piece = pieces[i][j];\n\t\t\t\tPoint2D pos = new Point2D(i, j);\n\t\t\t\tif (this.animation != null && this.animation.getStartNotation().equals(Board.convertPosition(i, j))){\n\t\t\t\t\tpos = this.animation.getPosition();\n\t\t\t\t}\n\t\t\t\tif (this.viewPoint == Color.BLACK){\n\t\t\t\t\tpos = new Point2D(7-pos.getX(), 7-pos.getY());",
"score": 0.7325681447982788
},
{
"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.7226684093475342
}
] | java | .stream().filter(piece -> piece.getType().getName() == Piece.PIECE_PAWN).count(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.