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/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +\n \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +",
"score": 53.763148108085105
},
{
"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": 50.04762416391409
},
{
"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": 47.06369589773827
},
{
"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": 46.623986974178976
},
{
"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": 46.623986974178976
}
] | 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/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": 43.96052069833892
},
{
"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": 43.24963335755139
},
{
"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": 43.24963335755139
},
{
"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": 40.85004280663547
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java",
"retrieved_chunk": " }\n case POST_FIREWALL_CREATE: {\n return new Formatter().format(\"/firewall/gameshield/%s/%s\", values).toString();\n }\n case DELETE_FIREWALL: {\n return new Formatter().format(\"/firewall/gameshield/%s/%s\", values).toString();\n }\n case GET_PLANS_AVAILABLE: {\n return new Formatter().format(\"/plans/gameshield\", values).toString();\n }",
"score": 39.622621333205004
}
] | 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/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +\n \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +",
"score": 60.94150003513779
},
{
"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": 55.49787968270976
},
{
"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": 55.49787968270976
},
{
"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": 53.23799871177302
},
{
"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": 50.0612237243968
}
] | 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/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": 57.51717035691463
},
{
"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": 57.51717035691463
},
{
"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": 55.60901198501
},
{
"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": 49.69264909877744
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +\n \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +",
"score": 49.492510990781355
}
] | java | instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> { |
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
| instance.sendMessage(sender, " - /np toggle (option)"); |
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
| src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"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": 82.78983211362363
},
{
"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": 81.05756626993725
},
{
"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": 81.05756626993725
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/ChatListener.java",
"retrieved_chunk": " public ChatListener(NeoProtectBungee instance) {\n this.instance = instance;\n }\n @EventHandler\n public void onChat(ChatEvent event) {\n CommandSender sender = (CommandSender) event.getSender();\n if (!sender.hasPermission(\"neoprotect.admin\") || !instance.getCore().getPlayerInSetup().contains(sender) || event.isCommand())\n return;\n event.setCancelled(true);\n new NeoProtectExecutor.ExecutorBuilder()",
"score": 68.79365830849787
},
{
"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": 66.92113903289982
}
] | 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/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": 45.505589298334264
},
{
"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": 42.69021714731373
},
{
"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": 42.69021714731373
},
{
"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": 40.258007430582516
},
{
"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": 39.52265838649824
}
] | java | backendList = instance.getCore().getRestAPI().getBackends(); |
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
| instance.sendMessage(sender, " - /np debugTool (cancel / amount)"); |
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
| src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"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": 73.63469699289283
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/command/NeoProtectCommand.java",
"retrieved_chunk": " .neoProtectPlugin(instance)\n .sender(sender)\n .args(args)\n .executeCommand();\n return false;\n }\n}",
"score": 71.63144315369341
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/ChatListener.java",
"retrieved_chunk": " public ChatListener(NeoProtectBungee instance) {\n this.instance = instance;\n }\n @EventHandler\n public void onChat(ChatEvent event) {\n CommandSender sender = (CommandSender) event.getSender();\n if (!sender.hasPermission(\"neoprotect.admin\") || !instance.getCore().getPlayerInSetup().contains(sender) || event.isCommand())\n return;\n event.setCancelled(true);\n new NeoProtectExecutor.ExecutorBuilder()",
"score": 70.96953712562099
},
{
"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": 68.7725103540846
},
{
"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": 68.7725103540846
}
] | 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": 81.28245702008458
},
{
"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": 79.63855757968244
},
{
"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": 79.63855757968244
},
{
"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": 64.76647736269129
},
{
"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": 63.61230229611162
}
] | 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/command/NeoProtectCommand.java",
"retrieved_chunk": " .neoProtectPlugin(instance)\n .sender(sender)\n .args(args)\n .executeCommand();\n return false;\n }\n}",
"score": 59.5862357509586
},
{
"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": 54.851051480359736
},
{
"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": 53.96792964992024
},
{
"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": 53.96792964992024
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " .local((sender instanceof ProxiedPlayer) ? ((ProxiedPlayer) sender).getLocale() : Locale.ENGLISH)\n .neoProtectPlugin(instance)\n .sender(sender)\n .args(args)\n .executeCommand();\n }\n @Override\n public Iterable<String> onTabComplete(CommandSender commandSender, String[] args) {\n List<String> list = new ArrayList<>();\n List<String> completorList = new ArrayList<>();",
"score": 52.683337773116776
}
] | 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/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": 53.5932206521733
},
{
"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": 53.5932206521733
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/command/NeoProtectCommand.java",
"retrieved_chunk": " .neoProtectPlugin(instance)\n .sender(sender)\n .args(args)\n .executeCommand();\n return false;\n }\n}",
"score": 52.907863338397306
},
{
"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": 51.24819317713863
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " .local((sender instanceof ProxiedPlayer) ? ((ProxiedPlayer) sender).getLocale() : Locale.ENGLISH)\n .neoProtectPlugin(instance)\n .sender(sender)\n .args(args)\n .executeCommand();\n }\n @Override\n public Iterable<String> onTabComplete(CommandSender commandSender, String[] args) {\n List<String> list = new ArrayList<>();\n List<String> completorList = new ArrayList<>();",
"score": 46.14100940123951
}
] | java | instance.getCore().getRestAPI().testCredentials(); |
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
| instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)"); |
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
| src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"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": 81.68034167658817
},
{
"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": 77.86232263017995
},
{
"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": 77.86232263017995
},
{
"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": 68.7301902395123
},
{
"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": 67.5837610558294
}
] | java | instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)"); |
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
| instance.sendMessage(sender, " - /np directConnectWhitelist (ip)"); |
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
| src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"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": 80.92236947169253
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/command/NeoProtectCommand.java",
"retrieved_chunk": " .neoProtectPlugin(instance)\n .sender(sender)\n .args(args)\n .executeCommand();\n return false;\n }\n}",
"score": 80.58537354790509
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/ChatListener.java",
"retrieved_chunk": " public ChatListener(NeoProtectBungee instance) {\n this.instance = instance;\n }\n @EventHandler\n public void onChat(ChatEvent event) {\n CommandSender sender = (CommandSender) event.getSender();\n if (!sender.hasPermission(\"neoprotect.admin\") || !instance.getCore().getPlayerInSetup().contains(sender) || event.isCommand())\n return;\n event.setCancelled(true);\n new NeoProtectExecutor.ExecutorBuilder()",
"score": 79.65604823192326
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/command/NeoProtectCommand.java",
"retrieved_chunk": "public class NeoProtectCommand implements CommandExecutor {\n private final NeoProtectSpigot instance;\n public NeoProtectCommand(NeoProtectSpigot instance) {\n this.instance = instance;\n }\n @Override\n public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, @NotNull String[] args) {\n new NeoProtectExecutor.ExecutorBuilder()\n .viaConsole(!(sender instanceof Player))\n .local(JavaUtils.javaVersionCheck() != 8 ? ((sender instanceof Player) ? Locale.forLanguageTag(((Player) sender).getLocale()) : Locale.ENGLISH) : Locale.ENGLISH)",
"score": 77.08986787992859
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/ChatListener.java",
"retrieved_chunk": " .local(((ProxiedPlayer) sender).getLocale())\n .neoProtectPlugin(instance)\n .sender(event.getSender())\n .msg(event.getMessage())\n .executeChatEvent();\n }\n}",
"score": 76.75248217901962
}
] | java | instance.sendMessage(sender, " - /np directConnectWhitelist (ip)"); |
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
| instance.sendMessage(sender, " - /np setgameshield [id]"); |
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
| src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/command/NeoProtectCommand.java",
"retrieved_chunk": " .neoProtectPlugin(instance)\n .sender(sender)\n .args(args)\n .executeCommand();\n return false;\n }\n}",
"score": 89.53930394211677
},
{
"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": 88.21004195049224
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/ChatListener.java",
"retrieved_chunk": " public ChatListener(NeoProtectBungee instance) {\n this.instance = instance;\n }\n @EventHandler\n public void onChat(ChatEvent event) {\n CommandSender sender = (CommandSender) event.getSender();\n if (!sender.hasPermission(\"neoprotect.admin\") || !instance.getCore().getPlayerInSetup().contains(sender) || event.isCommand())\n return;\n event.setCancelled(true);\n new NeoProtectExecutor.ExecutorBuilder()",
"score": 86.86511106302282
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/ChatListener.java",
"retrieved_chunk": " .local(((ProxiedPlayer) sender).getLocale())\n .neoProtectPlugin(instance)\n .sender(event.getSender())\n .msg(event.getMessage())\n .executeChatEvent();\n }\n}",
"score": 85.28053575446624
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/command/NeoProtectCommand.java",
"retrieved_chunk": "public class NeoProtectCommand implements CommandExecutor {\n private final NeoProtectSpigot instance;\n public NeoProtectCommand(NeoProtectSpigot instance) {\n this.instance = instance;\n }\n @Override\n public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, @NotNull String[] args) {\n new NeoProtectExecutor.ExecutorBuilder()\n .viaConsole(!(sender instanceof Player))\n .local(JavaUtils.javaVersionCheck() != 8 ? ((sender instanceof Player) ? Locale.forLanguageTag(((Player) sender).getLocale()) : Locale.ENGLISH) : Locale.ENGLISH)",
"score": 84.13881081624349
}
] | java | instance.sendMessage(sender, " - /np setgameshield [id]"); |
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
| if(backend.isGeyser())continue; |
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
| src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/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": 46.45388856452455
},
{
"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": 45.59668665908065
},
{
"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": 45.59668665908065
},
{
"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": 40.361315912925505
},
{
"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": 39.629204689228125
}
] | java | if(backend.isGeyser())continue; |
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": 35.10853779728134
},
{
"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": 30.854885206412607
},
{
"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": 29.700585629751075
},
{
"filename": "src/main/java/com/cursework/WebArtSell/Models/Comment.java",
"retrieved_chunk": " }\n public void setUser(User user) {\n this.user = user;\n }\n public Product getProduct() {\n return product;\n }\n public void setProduct(Product product) {\n this.product = product;\n }",
"score": 27.29528017689612
},
{
"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": 27.118268251142467
}
] | java | product.setDescription("Это ваше объявление!"); |
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization | .get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId())); |
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
| src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " core.severe(\"Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield\");\n setup = false;\n return;\n } else if (isBackendInvalid(Config.getBackendID())) {\n core.severe(\"Backend is not valid! Please run /neoprotect setbackend to set the backend\");\n setup = false;\n return;\n }\n this.setup = true;\n setProxyProtocol(Config.isProxyProtocol());",
"score": 65.17197077316227
},
{
"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": 59.521858428584906
},
{
"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": 57.44049976393458
},
{
"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": 57.44049976393458
},
{
"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": 51.48656580270412
}
] | java | .get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.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/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": 31.041313640643178
},
{
"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": 31.041313640643178
},
{
"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": 30.54829324562969
},
{
"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": 29.891910168478276
},
{
"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": 27.41532313723688
}
] | java | setEmail(user.getEmail()); |
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": 58.57355916239463
},
{
"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": 54.53403025216765
},
{
"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": 54.53403025216765
},
{
"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": 50.49991104162186
},
{
"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": 49.56682820403104
}
] | java | gameshield.getName(), 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/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": 38.5672749427481
},
{
"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": 38.5672749427481
},
{
"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": 33.84338317457064
},
{
"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": 31.771794237428658
},
{
"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": 30.195691899949658
}
] | java | existUser.setRole(user.getRole()); |
package de.cubeattack.neoprotect.velocity;
import com.google.inject.Inject;
import com.velocitypowered.api.command.CommandSource;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ProxyServer;
import com.velocitypowered.proxy.connection.client.ConnectedPlayer;
import com.velocitypowered.proxy.protocol.packet.KeepAlive;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.Core;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.Permission;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.KeepAliveResponseKey;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.event.HoverEvent;
import org.bstats.charts.SimplePie;
import org.bstats.velocity.Metrics;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Objects;
import java.util.logging.Logger;
public class NeoProtectVelocity implements NeoProtectPlugin {
private final Metrics.Factory metricsFactory;
private final Logger logger;
private final ProxyServer proxy;
private Core core;
@Inject
public NeoProtectVelocity(ProxyServer proxy, Logger logger, Metrics.Factory metricsFactory) {
this.proxy = proxy;
this.logger = logger;
this.metricsFactory = metricsFactory;
}
@Subscribe
public void onProxyInitialize(ProxyInitializeEvent event) {
Metrics metrics = metricsFactory.make(this, 18727);
metrics.addCustomChart(new SimplePie("language", Config::getLanguage));
core = new Core(this);
new Startup(this);
}
public Core getCore() {
return core;
}
@Override
public Stats getStats() {
return new Stats(
getPluginType(),
getProxy().getVersion().getVersion(),
getProxy().getVersion().getName(),
System.getProperty("java.version"),
System.getProperty("os.name"),
System.getProperty("os.arch"),
System.getProperty("os.version"),
getPluginVersion(),
getCore().getVersionResult().getVersionStatus().toString(),
Config.getAutoUpdaterSettings().toString(),
getCore().isSetup() ? getCore().getRestAPI().getPlan() : "§cNOT CONNECTED",
Arrays.toString(getPlugins().stream().filter(p -> !p.startsWith("cmd_") && !p.equals("reconnect_yaml")).toArray()),
getProxy().getPlayerCount(),
getProxy().getAllServers().size(),
Runtime.getRuntime().availableProcessors(),
getProxy().getConfiguration().isOnlineMode(),
Config.isProxyProtocol()
);
}
public ProxyServer getProxy() {
return proxy;
}
@Override
public void sendMessage(Object receiver, String text) {
sendMessage(receiver, text, null, null, null, null);
}
@Override
@SuppressWarnings("unchecked")
public void sendMessage(Object receiver, String text, String clickAction, String clickMsg, String hoverAction, String hoverMsg) {
TextComponent msg = | Component.text(core.getPrefix() + text); |
if (clickAction != null)
msg = msg.clickEvent(ClickEvent.clickEvent(ClickEvent.Action.valueOf(clickAction), clickMsg));
if (hoverAction != null)
msg = msg.hoverEvent(HoverEvent.hoverEvent((HoverEvent.Action<Object>) Objects.requireNonNull(HoverEvent.Action.NAMES.value(hoverAction.toLowerCase())),
Component.text(hoverMsg)));
if (receiver instanceof CommandSource) ((CommandSource) receiver).sendMessage(msg);
}
@Override
public void sendAdminMessage(Permission permission, String text, String clickAction, String clickMsg, String hoverAction, String hoverMsg) {
getProxy().getAllPlayers().forEach(receiver -> {
if (receiver.hasPermission("neoprotect.admin") || receiver.hasPermission(permission.value))
sendMessage(receiver, text, clickAction, clickMsg, hoverAction, hoverMsg);
});
}
@Override
public void sendKeepAliveMessage(Object receiver, long id) {
if (receiver instanceof Player) {
KeepAlive keepAlive = new KeepAlive();
keepAlive.setRandomId(id);
((ConnectedPlayer) receiver).getConnection().getChannel().writeAndFlush(keepAlive);
getCore().getPingMap().put(new KeepAliveResponseKey(((Player) receiver).getRemoteAddress(), id), System.currentTimeMillis());
}
}
@Override
public long sendKeepAliveMessage(long id) {
for (Player player : this.proxy.getAllPlayers()) {
sendKeepAliveMessage(player, id);
}
return id;
}
@Override
public Logger getLogger() {
return logger;
}
@Override
public ArrayList<String> getPlugins() {
ArrayList<String> plugins = new ArrayList<>();
getProxy().getPluginManager().getPlugins().forEach(p -> plugins.add(p.getDescription().getName().orElseThrow(null)));
return plugins;
}
@Override
public PluginType getPluginType() {
return PluginType.VELOCITY;
}
@Override
public String getPluginVersion() {
return proxy.getPluginManager().ensurePluginContainer(this).getDescription().getVersion().orElse("");
}
}
| src/main/java/de/cubeattack/neoprotect/velocity/NeoProtectVelocity.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/NeoProtectBungee.java",
"retrieved_chunk": " }\n @Override\n public void sendMessage(Object receiver, String text, String clickAction, String clickMsg, String hoverAction, String hoverMsg) {\n TextComponent msg = new TextComponent(core.getPrefix() + text);\n if (clickAction != null)\n msg.setClickEvent(new ClickEvent(ClickEvent.Action.valueOf(clickAction), clickMsg));\n if (hoverAction != null)\n msg.setHoverEvent(new HoverEvent(HoverEvent.Action.valueOf(hoverAction), Collections.singletonList(new Text(hoverMsg))));\n if (receiver instanceof CommandSender) ((CommandSender) receiver).sendMessage(msg);\n }",
"score": 109.95105855604876
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/NeoProtectSpigot.java",
"retrieved_chunk": " public void sendMessage(Object receiver, String text, String clickAction, String clickMsg, String hoverAction, String hoverMsg) {\n TextComponent msg = new TextComponent(core.getPrefix() + text);\n if (clickAction != null)\n msg.setClickEvent(new ClickEvent(ClickEvent.Action.valueOf(clickAction), clickMsg));\n if (hoverAction != null)\n msg.setHoverEvent(new HoverEvent(HoverEvent.Action.valueOf(hoverAction), new ComponentBuilder(hoverMsg).create()));\n if (receiver instanceof ConsoleCommandSender) ((ConsoleCommandSender) receiver).sendMessage(msg.toLegacyText());\n if (receiver instanceof Player) ((Player) receiver).spigot().sendMessage(msg);\n }\n @Override",
"score": 109.29254920156495
},
{
"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": 96.74076017405659
},
{
"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": 96.00878309100415
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/NeoProtectPlugin.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core;\nimport de.cubeattack.neoprotect.core.model.Stats;\nimport java.util.ArrayList;\nimport java.util.logging.Logger;\npublic interface NeoProtectPlugin {\n void sendMessage(Object receiver, String text);\n void sendMessage(Object receiver, String text, String clickAction, String clickMsg, String hoverAction, String hoverMsg);\n void sendAdminMessage(Permission permission, String text, String clickAction, String clickMsg, String hoverAction, String hoverMsg);\n long sendKeepAliveMessage(long id);\n void sendKeepAliveMessage(Object receiver, long id);",
"score": 88.76704495928132
}
] | java | Component.text(core.getPrefix() + text); |
package com.cursework.WebArtSell.Controllers;
import com.cursework.WebArtSell.Models.User;
import com.cursework.WebArtSell.Repositories.UserRepository;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Optional;
@Controller
@RequestMapping("/authorisation")
public class AuthorisationController {
@Autowired
private UserRepository userRepository;
@GetMapping
public String getAllUsers(Model model) {
model.addAttribute("users", userRepository.findAll());
return "authorisation";
}
@PostMapping
public String userLogin(@RequestParam String email,
@RequestParam String password,
Model model,
HttpServletRequest request) {
Optional<User> optionalUser = userRepository.findByEmailAndPassword(email, password);
if (optionalUser.isPresent()) {
User user = optionalUser.get();
HttpSession session = request.getSession();
session.setAttribute("user", user);
if | (user.getRole().equals("ADMIN")) { |
return "redirect:/table-users";
} else {
return "redirect:/main-user";
}
} else {
model.addAttribute("error", "Неверный email или пароль");
return "authorisation";
}
}
}
| src/main/java/com/cursework/WebArtSell/Controllers/AuthorisationController.java | Neural-Enigma-Art-sales-Spring-Boot-57a8036 | [
{
"filename": "src/main/java/com/cursework/WebArtSell/Secure/RoleCheckInterceptor.java",
"retrieved_chunk": " HttpSession session = request.getSession();\n User user = (User) session.getAttribute(\"user\");\n if (user == null || !user.getRole().equals(\"ADMIN\")) {\n response.sendRedirect(\"/authorisation\");\n return false;\n }\n return true;\n }\n}",
"score": 35.98094519195297
},
{
"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": 32.023263225315254
},
{
"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": 30.259055663697694
},
{
"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": 28.075965106244727
},
{
"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": 27.16752569040121
}
] | java | (user.getRole().equals("ADMIN")) { |
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": 46.85724961605516
},
{
"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": 40.74275506546668
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/NeoProtectSpigot.java",
"retrieved_chunk": " return core;\n }\n @Override\n public Stats getStats() {\n return new Stats(\n getPluginType(),\n getServer().getVersion(),\n getServer().getName(),\n System.getProperty(\"java.version\"),\n System.getProperty(\"os.name\"),",
"score": 39.781437847359335
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +\n \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +",
"score": 37.0326493656923
},
{
"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": 32.99520013425305
}
] | java | set("general.pluginVersion", stats.getPluginVersion()); |
package com.cursework.WebArtSell.Controllers;
import com.cursework.WebArtSell.Models.Product;
import com.cursework.WebArtSell.Models.User;
import com.cursework.WebArtSell.Services.ProductService;
import com.cursework.WebArtSell.Services.TransactionService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.List;
@Controller
public class HomeController {
private final ProductService productService;
private final TransactionService transactionService;
public HomeController(ProductService productService, TransactionService transactionService) {
this.productService = productService;
this.transactionService = transactionService;
}
@GetMapping("/main-user")
public String getMainUserPage(Model model, HttpServletRequest request) {
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
List<Product> products = productService.findAll();
Long currentUserId = user.getId();
for (Product product : products) {
if (transactionService.isProductInTransactions(product)) {
product.setDescription("Этот товар уже продан!");
product.setDisableButton(true);
}
| if (product.getCreatedBy().getId().equals(currentUserId)) { |
product.setDescription("Это ваше объявление!");
product.setDisableButton(true);
}
}
model.addAttribute("products", products);
return "main-user";
}
@GetMapping("/")
public String home(Model model) {
List<Product> products = productService.findAll();
model.addAttribute("products", products);
return "main";
}
@GetMapping("/main-user/category/{category}")
public String getMainUserPageByCategory(@PathVariable String category, Model model, HttpServletRequest request) {
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
if (user == null) {
return "redirect:/authorisation";
}
List<Product> products = productService.findAllByCategory(category);
Long currentUserId = user.getId();
for (Product product : products) {
if (transactionService.isProductInTransactions(product)) {
product.setDescription("Этот товар уже продан!");
product.setDisableButton(true);
}
if (product.getCreatedBy().getId().equals(currentUserId)) {
product.setDescription("Это ваше объявление!");
product.setDisableButton(true);
}
}
model.addAttribute("products", products);
return "main-user";
}
}
| src/main/java/com/cursework/WebArtSell/Controllers/HomeController.java | Neural-Enigma-Art-sales-Spring-Boot-57a8036 | [
{
"filename": "src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java",
"retrieved_chunk": " } catch (Exception e) {\n model.addAttribute(\"error\", \"Ошибка\");\n model.addAttribute(\"transaction\", new Transaction());\n Optional<Product> product = productRepository.findById(productId);\n if (product.isPresent()) {\n model.addAttribute(\"product\", product.get());\n HttpSession session = request.getSession();\n User buyer = (User) session.getAttribute(\"user\");\n transaction.setBuyerId(buyer.getId());\n transaction.setSellerId(product.get().getCreatedBy().getId());",
"score": 39.51633777800742
},
{
"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": 35.44504874592708
},
{
"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": 35.14425719211567
},
{
"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": 33.02469276659264
},
{
"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": 32.42377931008388
}
] | 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/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": 46.85724961605516
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +\n \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +",
"score": 46.025807793303464
},
{
"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": 40.74275506546668
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/NeoProtectSpigot.java",
"retrieved_chunk": " return core;\n }\n @Override\n public Stats getStats() {\n return new Stats(\n getPluginType(),\n getServer().getVersion(),\n getServer().getName(),\n System.getProperty(\"java.version\"),\n System.getProperty(\"os.name\"),",
"score": 39.01113927514206
},
{
"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": 37.98731929898489
}
] | java | "general.ProxyVersion", stats.getServerVersion()); |
package com.cursework.WebArtSell.Controllers;
import com.cursework.WebArtSell.Models.User;
import com.cursework.WebArtSell.Repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.time.LocalDateTime;
@Controller
@RequestMapping("/registration")
public class RegistrationController {
@Autowired
private UserRepository userRepository;
@GetMapping
public String getAllUsers(Model model) {
model.addAttribute("users", userRepository.findAll());
return "registration";
}
@PostMapping
public String registerUser(@RequestParam String name, @RequestParam String email, @RequestParam String password,
@RequestParam String confirm_password, Model model) {
if (!password.equals(confirm_password)) {
model.addAttribute("error", "Пароли не совпадают!");
return "registration";
}
User user = new User();
user.setLogin(name);
user.setEmail(email);
user.setPassword(password);
user.setRole("USER");
user.setCreationDate(LocalDateTime.now());
| user.setStatus("Активный"); |
userRepository.save(user);
return "redirect:/authorisation";
}
}
| src/main/java/com/cursework/WebArtSell/Controllers/RegistrationController.java | Neural-Enigma-Art-sales-Spring-Boot-57a8036 | [
{
"filename": "src/main/java/com/cursework/WebArtSell/Controllers/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": 30.57384764311363
},
{
"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": 24.415749753088036
},
{
"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": 21.560673600296344
},
{
"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": 20.620531683830734
},
{
"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": 20.0125954028029
}
] | java | user.setStatus("Активный"); |
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": 46.85724961605516
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +\n \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +",
"score": 41.88361532419857
},
{
"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": 40.74275506546668
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/NeoProtectSpigot.java",
"retrieved_chunk": " return core;\n }\n @Override\n public Stats getStats() {\n return new Stats(\n getPluginType(),\n getServer().getVersion(),\n getServer().getName(),\n System.getProperty(\"java.version\"),\n System.getProperty(\"os.name\"),",
"score": 39.01113927514206
},
{
"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": 35.819042745019146
}
] | java | , stats.getServerName()); |
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": 34.17135242740842
},
{
"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": 32.57635862395969
},
{
"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": 31.321031171685952
},
{
"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": 29.350492163873234
},
{
"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": 29.162204797607117
}
] | java | (!currentUser.getId().equals(id)) { |
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName( | ), gameshield.getId())); |
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
| src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/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": 58.57355916239463
},
{
"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": 54.53403025216765
},
{
"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": 54.53403025216765
},
{
"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": 50.49991104162186
},
{
"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": 49.56682820403104
}
] | java | ), gameshield.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": 35.10709605092098
},
{
"filename": "src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java",
"retrieved_chunk": " @Autowired\n private TransactionService transactionService;\n @Autowired\n private TransactionRepository transactionRepository;\n @Autowired\n private ProductRepository productRepository;\n @GetMapping(\"/billing/{id}\")\n public String authorisationModel(@PathVariable Long id, Model model, HttpServletRequest request) {\n Optional<Product> product = productRepository.findById(id);\n if (product.isPresent()) {",
"score": 31.295321326175053
},
{
"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": 27.552421592386594
},
{
"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": 24.600777645152853
},
{
"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": 23.010397772812496
}
] | java | product.setArtist(updatedProduct.getArtist()); |
package com.cursework.WebArtSell.Controllers;
import com.cursework.WebArtSell.Models.User;
import com.cursework.WebArtSell.Repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.time.LocalDateTime;
@Controller
@RequestMapping("/registration")
public class RegistrationController {
@Autowired
private UserRepository userRepository;
@GetMapping
public String getAllUsers(Model model) {
model.addAttribute("users", userRepository.findAll());
return "registration";
}
@PostMapping
public String registerUser(@RequestParam String name, @RequestParam String email, @RequestParam String password,
@RequestParam String confirm_password, Model model) {
if (!password.equals(confirm_password)) {
model.addAttribute("error", "Пароли не совпадают!");
return "registration";
}
User user = new User();
user.setLogin(name);
user.setEmail(email);
user.setPassword(password);
user.setRole("USER");
| user.setCreationDate(LocalDateTime.now()); |
user.setStatus("Активный");
userRepository.save(user);
return "redirect:/authorisation";
}
}
| src/main/java/com/cursework/WebArtSell/Controllers/RegistrationController.java | Neural-Enigma-Art-sales-Spring-Boot-57a8036 | [
{
"filename": "src/main/java/com/cursework/WebArtSell/Controllers/AuthorisationController.java",
"retrieved_chunk": " User user = optionalUser.get();\n HttpSession session = request.getSession();\n session.setAttribute(\"user\", user);\n if (user.getRole().equals(\"ADMIN\")) {\n return \"redirect:/table-users\";\n } else {\n return \"redirect:/main-user\";\n }\n } else {\n model.addAttribute(\"error\", \"Неверный email или пароль\");",
"score": 26.102228727226905
},
{
"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": 24.895162649970224
},
{
"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": 22.857653234422237
},
{
"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": 22.31656019791267
},
{
"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": 19.779910057127605
}
] | java | user.setCreationDate(LocalDateTime.now()); |
package com.cursework.WebArtSell.Controllers;
import com.cursework.WebArtSell.Models.Product;
import com.cursework.WebArtSell.Models.Transaction;
import com.cursework.WebArtSell.Models.TransactionChartData;
import com.cursework.WebArtSell.Models.User;
import com.cursework.WebArtSell.Repositories.ProductRepository;
import com.cursework.WebArtSell.Repositories.TransactionRepository;
import com.cursework.WebArtSell.Services.TransactionService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@Controller
public class TransactionController {
@Autowired
private TransactionService transactionService;
@Autowired
private TransactionRepository transactionRepository;
@Autowired
private ProductRepository productRepository;
@GetMapping("/billing/{id}")
public String authorisationModel(@PathVariable Long id, Model model, HttpServletRequest request) {
Optional<Product> product = productRepository.findById(id);
if (product.isPresent()) {
model.addAttribute("product", product.get());
Transaction transaction = new Transaction();
HttpSession session = request.getSession();
User buyer = (User) session.getAttribute("user");
transaction.setBuyerId(buyer.getId());
transaction.setSellerId(product.get().getCreatedBy().getId());
transaction.setPurchaseDate(LocalDateTime.now());
transaction.setSum(product.get().getPrice().doubleValue());
transaction.setProductId(product.get().getId());
model.addAttribute("transaction", transaction);
model.addAttribute( | "productId", product.get().getId()); |
} else {
return "redirect:/billing";
}
return "billing";
}
@PostMapping("/billing-buy")
public String processTransaction(@ModelAttribute Transaction transaction, @RequestParam("productId") Long productId, Model model, HttpServletRequest request) {
try {
System.out.println(transaction.getBuyerId());
System.out.println(transaction.getSellerId());
System.out.println(transaction.getPurchaseDate());
System.out.println(transaction.getSum());
transactionRepository.save(transaction);
Optional<Product> product = productRepository.findById(productId);
if (product.isPresent()) {
model.addAttribute("product", product.get());
} else {
return "redirect:/main-user";
}
} catch (Exception e) {
model.addAttribute("error", "Ошибка");
model.addAttribute("transaction", new Transaction());
Optional<Product> product = productRepository.findById(productId);
if (product.isPresent()) {
model.addAttribute("product", product.get());
HttpSession session = request.getSession();
User buyer = (User) session.getAttribute("user");
transaction.setBuyerId(buyer.getId());
transaction.setSellerId(product.get().getCreatedBy().getId());
transaction.setPurchaseDate(LocalDateTime.now());
transaction.setSum(product.get().getPrice().doubleValue());
transaction.setProductId(product.get().getId());
}
return "billing";
}
return "redirect:/main-user";
}
@GetMapping("/api/transactions")
public List<Transaction> getTransactions() {
return transactionRepository.findAll();
}
@GetMapping("/api/transactionChartData")
public List<TransactionChartData> getTransactionChartData() {
List<TransactionChartData> chartData = transactionRepository.findTransactionChartData();
System.out.println(chartData);
return chartData;
}
@GetMapping("/table-transactions")
public String transactions(Model model) {
List<Transaction> transactions = transactionService.findAll();
Map<String, Double> chartData = transactionService.getMonthlySalesData();
model.addAttribute("transactions", transactions);
model.addAttribute("chartData", chartData);
return "table-transactions";
}
}
| src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java | Neural-Enigma-Art-sales-Spring-Boot-57a8036 | [
{
"filename": "src/main/java/com/cursework/WebArtSell/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": 58.22992249515757
},
{
"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": 33.321544163408326
},
{
"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": 31.475555445435557
},
{
"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": 31.111178108077304
},
{
"filename": "src/main/java/com/cursework/WebArtSell/Controllers/ProductController.java",
"retrieved_chunk": " }\n @GetMapping(\"/{id}\")\n public String getProductById(@PathVariable long id, Model model) {\n Optional<Product> product = productRepository.findById(id);\n if (product.isPresent()) {\n List<Comment> comments = commentRepository.findByProductId(id);\n model.addAttribute(\"product\", product.get());\n model.addAttribute(\"comments\", comments);\n return \"product-details\";\n }",
"score": 30.834405840662278
}
] | 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": 31.479011597875775
},
{
"filename": "src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java",
"retrieved_chunk": " @Autowired\n private TransactionService transactionService;\n @Autowired\n private TransactionRepository transactionRepository;\n @Autowired\n private ProductRepository productRepository;\n @GetMapping(\"/billing/{id}\")\n public String authorisationModel(@PathVariable Long id, Model model, HttpServletRequest request) {\n Optional<Product> product = productRepository.findById(id);\n if (product.isPresent()) {",
"score": 27.27875834697687
},
{
"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": 22.16705033110484
},
{
"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": 22.00220505235162
},
{
"filename": "src/main/java/com/cursework/WebArtSell/Models/Product.java",
"retrieved_chunk": " return id;\n }\n public void setId(Long id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;",
"score": 21.165239826282246
}
] | 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/TransactionController.java",
"retrieved_chunk": " @Autowired\n private TransactionService transactionService;\n @Autowired\n private TransactionRepository transactionRepository;\n @Autowired\n private ProductRepository productRepository;\n @GetMapping(\"/billing/{id}\")\n public String authorisationModel(@PathVariable Long id, Model model, HttpServletRequest request) {\n Optional<Product> product = productRepository.findById(id);\n if (product.isPresent()) {",
"score": 44.16087717893231
},
{
"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": 40.77288445970796
},
{
"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": 36.178686706782635
},
{
"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": 28.286478758155404
},
{
"filename": "src/main/java/com/cursework/WebArtSell/Controllers/TransactionController.java",
"retrieved_chunk": " transaction.setPurchaseDate(LocalDateTime.now());\n transaction.setSum(product.get().getPrice().doubleValue());\n transaction.setProductId(product.get().getId());\n }\n return \"billing\";\n }\n return \"redirect:/main-user\";\n }\n @GetMapping(\"/api/transactions\")\n public List<Transaction> getTransactions() {",
"score": 26.24079608559225
}
] | java | List<Comment> comments = commentRepository.findByProductId(id); |
package com.cursework.WebArtSell.Controllers;
import com.cursework.WebArtSell.Models.Comment;
import com.cursework.WebArtSell.Models.Product;
import com.cursework.WebArtSell.Models.User;
import com.cursework.WebArtSell.Repositories.CommentRepository;
import com.cursework.WebArtSell.Repositories.ProductRepository;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
@Controller
@RequestMapping("/table-products")
public class ProductController {
@Autowired
private ProductRepository productRepository;
@Autowired
private CommentRepository commentRepository;
@GetMapping
public String getAllProducts(Model model) {
List<Product> products = productRepository.findAll();
model.addAttribute("products", products);
return "table-products";
}
@GetMapping("/add")
public String addAnnouncement() {
return "product-add";
}
@PostMapping("/add")
public String createProduct(@ModelAttribute Product product, HttpServletRequest request) {
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
product.setCreatedBy(user);
| product.setCreationDate(LocalDateTime.now()); |
productRepository.save(product);
return "redirect:/main-user";
}
@GetMapping("/{id}")
public String getProductById(@PathVariable long id, Model model) {
Optional<Product> product = productRepository.findById(id);
if (product.isPresent()) {
List<Comment> comments = commentRepository.findByProductId(id);
model.addAttribute("product", product.get());
model.addAttribute("comments", comments);
return "product-details";
}
return "redirect:/table-products";
}
@GetMapping("/{id}/edit")
public String editProduct(@PathVariable long id, Model model) {
Optional<Product> product = productRepository.findById(id);
if (product.isPresent()) {
model.addAttribute("product", product.get());
return "product-edit";
}
return "redirect:/table-products";
}
@PostMapping("/{id}/edit")
public String updateProduct(@PathVariable long id, @ModelAttribute Product updatedProduct) {
Product product = productRepository.findById(id).orElseThrow();
product.setName(updatedProduct.getName());
product.setDescription(updatedProduct.getDescription());
product.setImageUrl(updatedProduct.getImageUrl());
product.setPrice(updatedProduct.getPrice());
product.setArtist(updatedProduct.getArtist());
product.setDimensions(updatedProduct.getDimensions());
productRepository.save(product);
return "redirect:/table-products";
}
@PostMapping("/{id}/remove")
public String deleteProduct(@PathVariable long id) {
productRepository.deleteById(id);
return "redirect:/table-products";
}
}
| src/main/java/com/cursework/WebArtSell/Controllers/ProductController.java | Neural-Enigma-Art-sales-Spring-Boot-57a8036 | [
{
"filename": "src/main/java/com/cursework/WebArtSell/Controllers/CommentController.java",
"retrieved_chunk": " public String addComment(@PathVariable long productId, @ModelAttribute Comment comment, HttpServletRequest request) {\n HttpSession session = request.getSession();\n User user = (User) session.getAttribute(\"user\");\n Product product = productRepository.findById(productId).orElseThrow();\n comment.setUser(user);\n comment.setProduct(product);\n comment.setCreationDate(LocalDateTime.now());\n commentRepository.save(comment);\n return \"redirect:/table-products/\" + productId;\n }",
"score": 38.55323620391898
},
{
"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": 34.122974257586954
},
{
"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": 28.248918865671527
},
{
"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": 26.417953474057693
},
{
"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": 25.995936139134173
}
] | java | product.setCreationDate(LocalDateTime.now()); |
package com.cursework.WebArtSell.Controllers;
import com.cursework.WebArtSell.Models.User;
import com.cursework.WebArtSell.Repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.time.LocalDateTime;
@Controller
@RequestMapping("/registration")
public class RegistrationController {
@Autowired
private UserRepository userRepository;
@GetMapping
public String getAllUsers(Model model) {
model.addAttribute("users", userRepository.findAll());
return "registration";
}
@PostMapping
public String registerUser(@RequestParam String name, @RequestParam String email, @RequestParam String password,
@RequestParam String confirm_password, Model model) {
if (!password.equals(confirm_password)) {
model.addAttribute("error", "Пароли не совпадают!");
return "registration";
}
User user = new User();
user.setLogin(name);
user.setEmail(email);
user.setPassword(password);
| user.setRole("USER"); |
user.setCreationDate(LocalDateTime.now());
user.setStatus("Активный");
userRepository.save(user);
return "redirect:/authorisation";
}
}
| src/main/java/com/cursework/WebArtSell/Controllers/RegistrationController.java | Neural-Enigma-Art-sales-Spring-Boot-57a8036 | [
{
"filename": "src/main/java/com/cursework/WebArtSell/Controllers/AuthorisationController.java",
"retrieved_chunk": " model.addAttribute(\"users\", userRepository.findAll());\n return \"authorisation\";\n }\n @PostMapping\n public String userLogin(@RequestParam String email,\n @RequestParam String password,\n Model model,\n HttpServletRequest request) {\n Optional<User> optionalUser = userRepository.findByEmailAndPassword(email, password);\n if (optionalUser.isPresent()) {",
"score": 26.820784927322013
},
{
"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": 25.357183674379115
},
{
"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": 22.99899183594961
},
{
"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": 22.58028156513865
},
{
"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": 20.923885481776562
}
] | 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/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": 48.60716201550501
},
{
"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": 33.881345125777514
},
{
"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": 32.74095442468684
},
{
"filename": "src/main/java/com/cursework/WebArtSell/Controllers/ProductController.java",
"retrieved_chunk": " }\n @GetMapping(\"/{id}\")\n public String getProductById(@PathVariable long id, Model model) {\n Optional<Product> product = productRepository.findById(id);\n if (product.isPresent()) {\n List<Comment> comments = commentRepository.findByProductId(id);\n model.addAttribute(\"product\", product.get());\n model.addAttribute(\"comments\", comments);\n return \"product-details\";\n }",
"score": 30.437226464346352
},
{
"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": 29.642919473225987
}
] | 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/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": 24.108297338735962
},
{
"filename": "src/main/java/com/cursework/WebArtSell/Models/Transaction.java",
"retrieved_chunk": " private Long productId;\n public Long getProductId() {\n return productId;\n }\n public void setProductId(Long productId) {\n this.productId = productId;\n }\n public Long getId() {\n return id;\n }",
"score": 23.79036368566909
},
{
"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": 21.631926577911504
},
{
"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": 20.618880208755606
},
{
"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": 19.491514401825565
}
] | 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/Services/ProductService.java",
"retrieved_chunk": " }\n productRepository.save(product);\n } else {\n throw new RuntimeException(\"Продукт не найден с id: \" + id);\n }\n }\n public void updateProduct(Product product) {\n Optional<Product> existingProduct = productRepository.findById(product.getId());\n if (existingProduct.isPresent()) {\n productRepository.save(product);",
"score": 34.65674930863592
},
{
"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": 20.62026562693963
},
{
"filename": "MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Controllers/OrderController.java",
"retrieved_chunk": " for (int i = 0; i < productIds.size(); i++) {\n Long productId = productIds.get(i);\n Product product = productService.getProductById(productId);\n int quantity = quantities.get(i);\n if (product.getStock() < quantity) {\n redirectAttrs.addFlashAttribute(\"error\", \"Недостаточное количество товара на складе для товара \" + product.getName());\n return \"redirect:/create-order\";\n }\n product.setStock(product.getStock() - quantity);\n product.setSales(product.getSales() + quantity);",
"score": 19.900732859129985
},
{
"filename": "MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Services/ProductService.java",
"retrieved_chunk": " }\n }\n public void decrementProductStock(Long id, Integer decrementAmount) throws RuntimeException {\n Optional<Product> optionalProduct = productRepository.findById(id);\n if (optionalProduct.isPresent()) {\n Product product = optionalProduct.get();\n if (product.getStock() >= decrementAmount) {\n product.setStock(product.getStock() - decrementAmount);\n } else {\n throw new RuntimeException(\"Товара на складе недостаточно с id: \" + id);",
"score": 19.872635445587672
},
{
"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": 19.67549373526975
}
] | java | <OrderItem> orderItems = productService.findOrderItemsByProduct(id); |
package com.example.MonitoringInternetShop.Controllers;
import com.example.MonitoringInternetShop.Models.User;
import com.example.MonitoringInternetShop.Repositories.UserRepository;
import com.example.MonitoringInternetShop.Services.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
@Controller
public class LoginController {
private static final String INVALID_USER = "Неверный логин или пароль";
private static final String UNKNOWN_ROLE = "Неизвестная роль пользователя";
private static final String INACTIVE_ACCOUNT = "Ваш аккаунт не активирован, обратитесь к администратору для активации";
private static final String LOGIN_EXISTS = "Пользователь с таким логином уже существует!";
private static final String EMAIL_EXISTS = "Пользователь с таким email уже существует!";
private static final String PASSWORD_MISMATCH = "Пароли не совпадают!";
private static final String REGISTRATION_SUCCESS = "Регистрация успешна. Ваш аккаунт ожидает активации.";
@Autowired
private UserService userService;
@Autowired
private UserRepository userRepository;
@GetMapping("/login")
public String showLoginPage() {
return "login";
}
@GetMapping("/register")
public String registerForm(Model model) {
model.addAttribute("user", new User());
return "registration";
}
@PostMapping("/login")
public String handleLogin(@RequestParam String username, @RequestParam String password, HttpSession session, Model model) {
| Optional<User> userOptional = userService.validateUser(username, password); |
if (userOptional.isPresent()) {
User user = userOptional.get();
if (User.Status.ACTIVE.equals(user.getStatus())) {
session.setAttribute("user", user);
if (User.Role.ADMIN.equals(user.getRole())) {
return "redirect:/dashboard";
} else if (User.Role.USER.equals(user.getRole())) {
return "redirect:/create-order";
} else {
model.addAttribute("error", UNKNOWN_ROLE);
return "login";
}
} else {
model.addAttribute("error", INACTIVE_ACCOUNT);
return "login";
}
} else {
model.addAttribute("error", INVALID_USER);
return "login";
}
}
@PostMapping("/register")
public String addUser(@ModelAttribute User user, @RequestParam String passwordConfirm, Model model) {
Optional<User> userFromDbOptional = userRepository.findByLogin(user.getLogin());
Optional<User> emailFromDbOptional = userRepository.findByMail(user.getMail());
if (userFromDbOptional.isPresent()) {
model.addAttribute("message", LOGIN_EXISTS);
return "registration";
}
if (emailFromDbOptional.isPresent()) {
model.addAttribute("message", EMAIL_EXISTS);
return "registration";
}
if (!user.getPassword().equals(passwordConfirm)) {
model.addAttribute("message", PASSWORD_MISMATCH);
return "registration";
}
user.setStatus(User.Status.INACTIVE);
user.setRole(User.Role.USER);
userRepository.save(user);
model.addAttribute("message", REGISTRATION_SUCCESS);
return "login";
}
}
| MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Controllers/LoginController.java | Neural-Enigma-Ecommerce-Sales-Dashboard-Spring-0130f60 | [
{
"filename": "MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Services/UserService.java",
"retrieved_chunk": "public class UserService {\n @Autowired\n private UserRepository userRepository;\n public Optional<User> findByName(String name) {\n return userRepository.findByName(name);\n }\n public Optional<User> validateUser(String username, String password) {\n Optional<User> userOptional = userRepository.findByLogin(username);\n if (userOptional.isPresent() && password.equals(userOptional.get().getPassword())) {\n return userOptional;",
"score": 41.88592543789344
},
{
"filename": "MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Controllers/OrderController.java",
"retrieved_chunk": " }\n @GetMapping(\"/user-orders\")\n public String viewOrders(Model model, HttpSession session) {\n User user = (User) session.getAttribute(\"user\");\n if (user == null) {\n return \"redirect:/login\";\n }\n List<Order> orders = orderService.findOrdersByUser(user);\n model.addAttribute(\"orders\", orders);\n return \"user-orders\";",
"score": 32.08367041956518
},
{
"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": 31.998762595403722
},
{
"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": 29.92890136373636
},
{
"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": 28.47874414382869
}
] | java | Optional<User> userOptional = userService.validateUser(username, password); |
package com.example.MonitoringInternetShop.Services;
import com.example.MonitoringInternetShop.Models.OrderItem;
import com.example.MonitoringInternetShop.Models.Product;
import com.example.MonitoringInternetShop.Repositories.OrderItemRepository;
import com.example.MonitoringInternetShop.Repositories.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
@Autowired
private OrderItemRepository orderItemRepository;
public List<Product> getFilteredAndSortedProducts(String category, String sortBy) {
List<Product> products;
if (category != null && !category.isEmpty()) {
products = productRepository.findByCategory(category);
} else {
products = productRepository.findAll();
}
if (sortBy != null && !sortBy.isEmpty()) {
if ("price".equalsIgnoreCase(sortBy)) {
products.sort(Comparator.comparing(Product::getPrice));
} else if ("popularity".equalsIgnoreCase(sortBy)) {
products.sort(Comparator.comparing(Product::getSales).reversed());
}
}
return products;
}
public void saveProduct(Product product) {
productRepository.save(product);
}
public List<Product> getTopProducts() {
return productRepository.findAll().stream()
.sorted((p1, p2) -> p2.getSales() - p1.getSales())
.limit(10)
.collect(Collectors.toList());
}
public List<Product> getAllProducts() {
return productRepository.findAll();
}
public Product findById(Long id) {
Optional<Product> productOptional = productRepository.findById(id);
return productOptional.orElse(null);
}
public Product getProductById(Long id) {
return productRepository.findById(id).orElse(null);
}
public void incrementProductStock(Long id, Integer incrementAmount) {
Optional<Product> optionalProduct = productRepository.findById(id);
if (optionalProduct.isPresent()) {
Product product = optionalProduct.get();
product.setStock(product.getStock() + incrementAmount);
productRepository.save(product);
} else {
throw new RuntimeException("Продукт не найден с id: " + id);
}
}
public void decrementProductStock(Long id, Integer decrementAmount) throws RuntimeException {
Optional<Product> optionalProduct = productRepository.findById(id);
if (optionalProduct.isPresent()) {
Product product = optionalProduct.get();
if (product.getStock() >= decrementAmount) {
product.setStock(product.getStock() - decrementAmount);
} else {
throw new RuntimeException("Товара на складе недостаточно с id: " + id);
}
productRepository.save(product);
} else {
throw new RuntimeException("Продукт не найден с id: " + id);
}
}
public void updateProduct(Product product) {
Optional<Product> existingProduct = productRepository.findById(product.getId());
if (existingProduct.isPresent()) {
productRepository.save(product);
}
}
public void deleteProduct(Long id) {
productRepository.deleteById(id);
}
public List<OrderItem> findOrderItemsByProduct(Long productId) {
| return orderItemRepository.findAllByProduct_Id(productId); |
}
}
| MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Services/ProductService.java | Neural-Enigma-Ecommerce-Sales-Dashboard-Spring-0130f60 | [
{
"filename": "MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Controllers/ProductController.java",
"retrieved_chunk": " }\n @PostMapping\n public String createProduct(@ModelAttribute Product product) {\n productService.saveProduct(product);\n return \"redirect:/products\";\n }\n @PostMapping(\"/{id}/edit\")\n public String editProduct(@PathVariable Long id, Product product) {\n Product existingProduct = productService.getProductById(id);\n if (existingProduct != null) {",
"score": 28.927072082312446
},
{
"filename": "MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Controllers/ProductController.java",
"retrieved_chunk": " existingProduct.setName(product.getName());\n existingProduct.setPrice(product.getPrice());\n existingProduct.setSales(product.getSales());\n existingProduct.setDescription(product.getDescription());\n existingProduct.setCategory(product.getCategory());\n existingProduct.setStock(product.getStock());\n productService.updateProduct(existingProduct);\n }\n return \"redirect:/products\";\n }",
"score": 23.71488117627693
},
{
"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": 20.405760035284054
},
{
"filename": "MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Services/UserService.java",
"retrieved_chunk": " public void updateUserStatus(Long id, User.Status status) {\n Optional<User> userOptional = userRepository.findById(id);\n if (userOptional.isPresent()) {\n User user = userOptional.get();\n user.setStatus(status);\n userRepository.save(user);\n }\n }\n}",
"score": 19.791785126696904
},
{
"filename": "MonitoringInternetShop/src/main/java/com/example/MonitoringInternetShop/Services/UserService.java",
"retrieved_chunk": " @Transactional\n public void updateUserPassword(Long id, String newPassword) {\n Optional<User> userOptional = userRepository.findById(id);\n if (userOptional.isPresent()) {\n User user = userOptional.get();\n user.setPassword(newPassword);\n userRepository.save(user);\n }\n }\n @Transactional",
"score": 19.520547037526175
}
] | 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": 33.044596188223615
},
{
"filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/JavaLanguageResolver.java",
"retrieved_chunk": " private List<RestItem> getRequestItemList(PsiClass psiClass, Module module) {\n List<PsiMethod> psiMethods = new ArrayList<>(Arrays.asList(psiClass.getMethods()));\n for (PsiClass aSuper : psiClass.getSupers()) {\n if (!\"java.lang.Object\".equals(aSuper.getQualifiedName())) {\n psiMethods.addAll(Arrays.asList(aSuper.getMethods()));\n }\n }\n if (psiMethods.size() == 0) {\n return Collections.emptyList();\n }",
"score": 14.307506330486067
},
{
"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": 13.178921932264522
},
{
"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": 12.888880449523416
},
{
"filename": "src/main/java/io/github/newhoo/restkit/ext/solon/helper/PsiAnnotationHelper.java",
"retrieved_chunk": " *\n * @param psiClass\n * @param fqn\n */\n public static PsiAnnotation getInheritedAnnotation(PsiClass psiClass, String fqn) {\n if (psiClass == null) {\n return null;\n }\n PsiAnnotation annotation = psiClass.getAnnotation(fqn);\n if (annotation != null) {",
"score": 12.792985531347417
}
] | 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": 13.097689966659281
},
{
"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": 12.047482243460705
},
{
"filename": "src/main/java/io/github/newhoo/restkit/ext/solon/util/TypeUtils.java",
"retrieved_chunk": " }\n }\n public static boolean isMap(String type) {\n if (type.contains(\"<\")) {\n type = type.substring(0, type.indexOf(\"<\"));\n }\n switch (type) {\n case \"java.util.Properties\":\n case \"java.util.Map\":\n case \"java.util.HashMap\":",
"score": 9.141210536432217
},
{
"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": 7.9051679768446075
},
{
"filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/JavaLanguageResolver.java",
"retrieved_chunk": " if (!(psiElement instanceof PsiMethod)) {\n return Collections.emptyList();\n }\n PsiMethod psiMethod = (PsiMethod) psiElement;\n return buildParamString(psiMethod);\n }\n @NotNull\n @Override\n public String buildRequestBodyJson(@NotNull PsiElement psiElement) {\n if (!(psiElement instanceof PsiMethod)) {",
"score": 6.017439279819508
}
] | 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": 18.04702171825106
},
{
"filename": "src/main/java/io/github/newhoo/restkit/ext/solon/helper/PsiAnnotationHelper.java",
"retrieved_chunk": " *\n * @param psiClass\n * @param fqn\n */\n public static PsiAnnotation getInheritedAnnotation(PsiClass psiClass, String fqn) {\n if (psiClass == null) {\n return null;\n }\n PsiAnnotation annotation = psiClass.getAnnotation(fqn);\n if (annotation != null) {",
"score": 15.015960061102358
},
{
"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": 13.933380251521351
},
{
"filename": "src/main/java/io/github/newhoo/restkit/ext/solon/SolonApiResolver.java",
"retrieved_chunk": " return \"Solon\";\n }\n @Override\n public List<RestItem> findRestItemListInModule(Module module, GlobalSearchScope globalSearchScope) {\n return new JavaLanguageResolver().findRestItemListInModule(module, globalSearchScope);\n }\n public static class SolonApiResolverProvider implements RestfulResolverProvider {\n @Override\n public RequestResolver createRequestResolver(@NotNull Project project) {\n return new SolonApiResolver();",
"score": 12.570347687406045
},
{
"filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/BaseLanguageResolver.java",
"retrieved_chunk": " parameterList.add(parameter);\n }\n return parameterList;\n }\n @NotNull\n @Override\n public Set<String> getParamFilterTypes(@NotNull Project project) {\n return Stream.of(\n \"java.util.Locale\",\n \"org.noear.solon.core.handle.Context\",",
"score": 11.775202968620654
}
] | java | = TypeUtils.primitiveToBox(typeCanonicalText); |
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": 124.16435414984106
},
{
"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": 88.18235963468197
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Core.java",
"retrieved_chunk": " }\n public ConcurrentHashMap<Long, Timestamp> getTimestampsMap() {\n return timestampsMap;\n }\n public ConcurrentHashMap<String, ArrayList<DebugPingResponse>> getDebugPingResponses() {\n return debugPingResponses;\n }\n public VersionUtils.Result getVersionResult() {\n return versionResult;\n }",
"score": 30.433515703313134
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java",
"retrieved_chunk": " \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +\n \"§bProxyProtocol§7: \" + Config.isProxyProtocol() + \" \\n\" +\n \"§bNeoProtectPlan§7: \" + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\") + \" \\n\" +\n \"§bVelocityName§7: \" + stats.getServerName() + \" \\n\" +\n \"§bVelocityVersion§7: \" + stats.getServerVersion() + \" \\n\" +\n \"§bVelocityPlugins§7: \" + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray());\n instance.sendMessage(player, \"§bHello \" + player.getUsername() + \" ;)\", null, null, \"SHOW_TEXT\", infos);\n instance.sendMessage(player, \"§bThis server uses your NeoPlugin\", null, null, \"SHOW_TEXT\", infos);",
"score": 26.726328667957755
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " configuration.load(file);\n configuration.set(\"general.osName\", System.getProperty(\"os.name\"));\n configuration.set(\"general.javaVersion\", System.getProperty(\"java.version\"));\n configuration.set(\"general.pluginVersion\", stats.getPluginVersion());\n configuration.set(\"general.ProxyName\", stats.getServerName());\n configuration.set(\"general.ProxyVersion\", stats.getServerVersion());\n configuration.set(\"general.ProxyPlugins\", instance.getPlugins());\n instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {\n List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);\n long maxPlayerToProxyLatenz = 0;",
"score": 25.788922080869177
}
] | java | instance.getCore().getDebugPingResponses().put(player.getUsername(), new ArrayList<>()); |
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": 23.169303367345943
},
{
"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": 20.652663283422253
},
{
"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": 12.16758301606425
},
{
"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": 10.162092304623764
},
{
"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": 8.540395844856945
}
] | java | if (TypeUtils.isPrimitiveOrSimpleType(fieldType.replaceAll("\\[]", ""))) { |
package io.github.newhoo.restkit.ext.solon.helper;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiEnumConstant;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiModifier;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiShortNamesCache;
import io.github.newhoo.restkit.ext.solon.util.TypeUtils;
import io.github.newhoo.restkit.util.JsonUtils;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* PsiClassHelper in Java
*
* @author newhoo
* @since 1.0.0
*/
public class PsiClassHelper {
private static final int MAX_CORRELATION_COUNT = 6;
public static String convertClassToJSON(String className, Project project) {
Object o = assemblePsiClass(className, project, 0, false);
return JsonUtils.toJson(o);
}
public static Object assemblePsiClass(String typeCanonicalText, Project project, int autoCorrelationCount, boolean putClass) {
boolean containsGeneric = typeCanonicalText.contains("<");
// 数组|集合
if (TypeUtils.isArray(typeCanonicalText) || TypeUtils.isList(typeCanonicalText)) {
String elementType = TypeUtils.isArray(typeCanonicalText)
? typeCanonicalText.replace("[]", "")
: containsGeneric
? typeCanonicalText.substring(typeCanonicalText.indexOf("<") + 1, typeCanonicalText.lastIndexOf(">"))
: Object.class.getCanonicalName();
return Collections.singletonList(assemblePsiClass(elementType, project, autoCorrelationCount, putClass));
}
PsiClass psiClass = PsiClassHelper.findPsiClass(typeCanonicalText, project);
if (psiClass == null) {
//简单常用类型
if (TypeUtils.isPrimitiveOrSimpleType(typeCanonicalText)) {
return | TypeUtils.getExampleValue(typeCanonicalText, false); |
}
return Collections.emptyMap();
}
//简单常用类型
if (TypeUtils.isPrimitiveOrSimpleType(typeCanonicalText)) {
return TypeUtils.getExampleValue(typeCanonicalText, false);
}
// 枚举
if (psiClass.isEnum()) {
PsiField[] enumFields = psiClass.getFields();
for (PsiField enumField : enumFields) {
if (enumField instanceof PsiEnumConstant) {
return enumField.getName();
}
}
return "";
}
// Map
if (TypeUtils.isMap(typeCanonicalText)) {
return Collections.emptyMap();
}
if (autoCorrelationCount > MAX_CORRELATION_COUNT) {
return Collections.emptyMap();
}
autoCorrelationCount++;
Map<String, Object> map = new LinkedHashMap<>();
if (putClass) {
if (containsGeneric) {
map.put("class", typeCanonicalText.substring(0, typeCanonicalText.indexOf("<")));
} else {
map.put("class", typeCanonicalText);
}
}
for (PsiField field : psiClass.getAllFields()) {
if (field.hasModifierProperty(PsiModifier.STATIC) || field.hasModifierProperty(PsiModifier.FINAL) || field.hasModifierProperty(PsiModifier.TRANSIENT)) {
continue;
}
String fieldType = field.getType().getCanonicalText();
// 不存在泛型
if (!containsGeneric) {
map.put(field.getName(), assemblePsiClass(fieldType, project, autoCorrelationCount, putClass));
continue;
}
// 存在泛型
if (TypeUtils.isPrimitiveOrSimpleType(fieldType.replaceAll("\\[]", ""))) {
map.put(field.getName(), assemblePsiClass(fieldType, project, autoCorrelationCount, putClass));
} else if (PsiClassHelper.findPsiClass(fieldType, project) == null) {
map.put(field.getName(), assemblePsiClass(typeCanonicalText.substring(typeCanonicalText.indexOf("<") + 1, typeCanonicalText.lastIndexOf(">")), project, autoCorrelationCount, putClass));
} else {
map.put(field.getName(), assemblePsiClass(fieldType, project, autoCorrelationCount, putClass));
}
}
return map;
}
/**
* 查找类
*
* @param typeCanonicalText 参数类型全限定名称
* @param project 当前project
* @return 查找到的类
*/
public static PsiClass findPsiClass(String typeCanonicalText, Project project) {
// 基本类型转化为对应包装类型
typeCanonicalText = TypeUtils.primitiveToBox(typeCanonicalText);
String className = typeCanonicalText;
if (className.contains("[]")) {
className = className.replaceAll("\\[]", "");
}
if (className.contains("<")) {
className = className.substring(0, className.indexOf("<"));
}
if (className.lastIndexOf(".") > 0) {
className = className.substring(className.lastIndexOf(".") + 1);
}
PsiClass[] classesByName = PsiShortNamesCache.getInstance(project).getClassesByName(className, GlobalSearchScope.allScope(project));
for (PsiClass psiClass : classesByName) {
if (typeCanonicalText.startsWith(psiClass.getQualifiedName())) {
return psiClass;
}
}
return null;
}
} | src/main/java/io/github/newhoo/restkit/ext/solon/helper/PsiClassHelper.java | newhoo-RestfulBox-Solon-8533971 | [
{
"filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/BaseLanguageResolver.java",
"retrieved_chunk": " // 数组|集合\n if (TypeUtils.isArray(paramType) || TypeUtils.isList(paramType)) {\n paramType = TypeUtils.isArray(paramType)\n ? paramType.replace(\"[]\", \"\")\n : paramType.contains(\"<\")\n ? paramType.substring(paramType.indexOf(\"<\") + 1, paramType.lastIndexOf(\">\"))\n : Object.class.getCanonicalName();\n }\n // 简单常用类型\n if (TypeUtils.isPrimitiveOrSimpleType(paramType)) {",
"score": 37.43870999705533
},
{
"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": 17.636012353857446
},
{
"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": 17.247879303290514
},
{
"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": 16.738392968083314
},
{
"filename": "src/main/java/io/github/newhoo/restkit/ext/solon/language/JavaLanguageResolver.java",
"retrieved_chunk": " private List<RestItem> getRequestItemList(PsiClass psiClass, Module module) {\n List<PsiMethod> psiMethods = new ArrayList<>(Arrays.asList(psiClass.getMethods()));\n for (PsiClass aSuper : psiClass.getSupers()) {\n if (!\"java.lang.Object\".equals(aSuper.getQualifiedName())) {\n psiMethods.addAll(Arrays.asList(aSuper.getMethods()));\n }\n }\n if (psiMethods.size() == 0) {\n return Collections.emptyList();\n }",
"score": 15.064306467435028
}
] | java | TypeUtils.getExampleValue(typeCanonicalText, false); |
package com.example.RestaurantManagement.Services;
import com.example.RestaurantManagement.Models.TableBooking;
import com.example.RestaurantManagement.Models.Tables;
import com.example.RestaurantManagement.Repositories.TableBookingRepository;
import com.example.RestaurantManagement.Repositories.TablesRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.sql.Date;
import java.sql.Time;
import java.util.List;
@Service
public class TableBookingService {
private final TableBookingRepository tableBookingRepository;
private final TablesRepository tablesRepository;
@Autowired
public TableBookingService(TableBookingRepository tableBookingRepository,
TablesRepository tablesRepository) {
this.tableBookingRepository = tableBookingRepository;
this.tablesRepository = tablesRepository;
}
public List<Tables> getAllTables() {
return tablesRepository.findAll();
}
public List<TableBooking> getAllBookings() {
return tableBookingRepository.findAll();
}
public String bookTable(int tableId, Date date, Time time, String info) {
Tables table = tablesRepository.findById(tableId).orElse(null);
if (table == null) {
return "Столик не найден";
}
TableBooking booking = new TableBooking();
booking.setTable(table);
booking.setDate(date);
booking.setTime(time);
booking.setInfo(info);
tableBookingRepository.save(booking);
return "Столик успешно забронирован";
}
public boolean isTableBooked(int tableId, Date date, Time time) {
List<TableBooking> bookings = this.getAllBookings();
for (TableBooking booking : bookings) {
if (booking.getTable().getId() == tableId && booking.getDate() | .equals(date) && booking.getTime().equals(time)) { |
return true;
}
}
return false;
}
public void deleteBooking(int id) {
tableBookingRepository.deleteById(id);
}
}
| RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/TableBookingService.java | Neural-Enigma-RestaurantManagement-Spring-Boot-Java-086881a | [
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Models/TableBooking.java",
"retrieved_chunk": " public void setTime(Time time) {\n this.time = time;\n }\n public String getInfo() {\n return info;\n }\n public void setInfo(String info) {\n this.info = info;\n }\n}",
"score": 39.603672533632164
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Models/TableBooking.java",
"retrieved_chunk": " }\n public Date getDate() {\n return date;\n }\n public void setDate(Date date) {\n this.date = date;\n }\n public Time getTime() {\n return time;\n }",
"score": 39.228046794933995
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/TableBookingController.java",
"retrieved_chunk": " }\n model.addAttribute(\"times\", times);\n return \"book-table\";\n }\n @PostMapping(\"/book-table\")\n public String bookTable(@RequestParam(\"table_id\") int tableId,\n @RequestParam(\"date\") Date date,\n @RequestParam(\"time\") String time,\n @RequestParam(\"info\") String info,\n Model model) {",
"score": 35.786647285525234
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Models/TableBooking.java",
"retrieved_chunk": " @ManyToOne\n @JoinColumn(name = \"table_id\")\n private Tables table;\n @Column(name = \"date\")\n private Date date;\n @Column(name = \"time\")\n private Time time;\n @Column(name = \"info\")\n private String info;\n public int getId() {",
"score": 34.507935309132215
},
{
"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": 27.289588213553543
}
] | 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/Models/TableBooking.java",
"retrieved_chunk": " public void setTime(Time time) {\n this.time = time;\n }\n public String getInfo() {\n return info;\n }\n public void setInfo(String info) {\n this.info = info;\n }\n}",
"score": 39.603672533632164
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Models/TableBooking.java",
"retrieved_chunk": " }\n public Date getDate() {\n return date;\n }\n public void setDate(Date date) {\n this.date = date;\n }\n public Time getTime() {\n return time;\n }",
"score": 39.228046794933995
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/TableBookingController.java",
"retrieved_chunk": " }\n model.addAttribute(\"times\", times);\n return \"book-table\";\n }\n @PostMapping(\"/book-table\")\n public String bookTable(@RequestParam(\"table_id\") int tableId,\n @RequestParam(\"date\") Date date,\n @RequestParam(\"time\") String time,\n @RequestParam(\"info\") String info,\n Model model) {",
"score": 35.786647285525234
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Models/TableBooking.java",
"retrieved_chunk": " @ManyToOne\n @JoinColumn(name = \"table_id\")\n private Tables table;\n @Column(name = \"date\")\n private Date date;\n @Column(name = \"time\")\n private Time time;\n @Column(name = \"info\")\n private String info;\n public int getId() {",
"score": 34.507935309132215
},
{
"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": 27.289588213553543
}
] | 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": 42.11456434493124
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/StaffController.java",
"retrieved_chunk": " @GetMapping(\"/staff\")\n public String getStaff(Model model) {\n model.addAttribute(\"staff\", staffService.getAllStaff());\n model.addAttribute(\"newStaff\", new Staff());\n model.addAttribute(\"currentUser\", getCurrentUser());\n return \"staff\";\n }\n @PostMapping(\"/staff/add\")\n public String addStaff(@ModelAttribute Staff staff, Model model) {\n if (staffService.loginExists(staff.getLogin())) {",
"score": 25.11627189682841
},
{
"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": 24.179993531528854
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/StaffController.java",
"retrieved_chunk": " @PostMapping(\"/staff/update\")\n public String updateStaff(@RequestParam(\"id\") int id, @RequestParam(\"role\") String role) {\n Staff staff = staffService.getStaffById(id);\n staff.setRole(role);\n staffService.updateStaff(staff);\n return \"redirect:/staff\";\n }\n @PostMapping(\"/staff/delete\")\n public String deleteStaff(@RequestParam(\"id\") int id) {\n Staff staff = staffService.getStaffById(id);",
"score": 23.599042720803446
},
{
"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": 21.753864280094025
}
] | java | staffRepository.findByLogin(login) != null; |
package com.example.RestaurantManagement.Controllers;
import com.example.RestaurantManagement.Models.Staff;
import com.example.RestaurantManagement.Services.StaffService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class StaffController {
@Autowired
private HttpSession session;
private final StaffService staffService;
@Autowired
public StaffController(StaffService staffService) {
this.staffService = staffService;
}
@GetMapping("/staff")
public String getStaff(Model model) {
model.addAttribute("staff", staffService.getAllStaff());
model.addAttribute("newStaff", new Staff());
model.addAttribute("currentUser", getCurrentUser());
return "staff";
}
@PostMapping("/staff/add")
public String addStaff(@ModelAttribute Staff staff, Model model) {
if (staffService.loginExists(staff.getLogin())) {
model.addAttribute("error", "Логин уже существует!");
model.addAttribute("staff", staffService.getAllStaff());
model.addAttribute("newStaff", staff);
return "redirect:/staff";
}
java.util.Date currentDate = new java.util.Date();
| staff.setApparatusEmployed(new java.sql.Date(currentDate.getTime())); |
staffService.saveStaff(staff);
return "redirect:/staff";
}
@PostMapping("/staff/update")
public String updateStaff(@RequestParam("id") int id, @RequestParam("role") String role) {
Staff staff = staffService.getStaffById(id);
staff.setRole(role);
staffService.updateStaff(staff);
return "redirect:/staff";
}
@PostMapping("/staff/delete")
public String deleteStaff(@RequestParam("id") int id) {
Staff staff = staffService.getStaffById(id);
staffService.deleteStaff(staff);
return "redirect:/staff";
}
public Staff getCurrentUser() {
return (Staff) session.getAttribute("staff");
}
}
| RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/StaffController.java | Neural-Enigma-RestaurantManagement-Spring-Boot-Java-086881a | [
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/TableBookingController.java",
"retrieved_chunk": " 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);\n 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);",
"score": 42.87417115797379
},
{
"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": 42.626608772875464
},
{
"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": 41.04682125858489
},
{
"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": 40.11978227897493
},
{
"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": 36.33520985029137
}
] | java | staff.setApparatusEmployed(new java.sql.Date(currentDate.getTime())); |
package com.example.RestaurantManagement.Controllers;
import com.example.RestaurantManagement.Models.Dish;
import com.example.RestaurantManagement.Models.DishType;
import com.example.RestaurantManagement.Repositories.DishTypeRepository;
import com.example.RestaurantManagement.Services.DishService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
@Controller
public class MenuController {
private final DishService dishService;
private final DishTypeRepository dishTypeRepository;
public MenuController(DishService dishService, DishTypeRepository dishTypeRepository) {
this.dishService = dishService;
this.dishTypeRepository = dishTypeRepository;
}
@GetMapping("/menu")
public String showMenu(Model model) {
List<Dish> dishes = dishService.getAllDishes();
List<DishType> dishTypes = dishTypeRepository.findAll();
model.addAttribute("dishes", dishes);
model.addAttribute("dishTypes", dishTypes);
return "menu";
}
@PostMapping("/menu/edit")
public String editDish(@RequestParam("id") int id, @RequestParam("name") String name,
@RequestParam("cost") double cost, @RequestParam("type") String typeName) {
if (dishService.checkIfDishIsOrdered(id)) {
} else {
dishService.editDish(id, name, cost, typeName);
}
return "redirect:/menu";
}
@PostMapping("/menu/delete")
public String deleteDish(@RequestParam("id") int id) {
if (dishService.checkIfDishIsOrdered(id)) {
} else {
dishService.deleteDish(id);
}
return "redirect:/menu";
}
@PostMapping("/menu/add")
public String addDish(@RequestParam("name") String name, @RequestParam("cost") double cost,
@RequestParam("type") String typeName) {
dishService.addDish(name, cost, typeName);
return "redirect:/menu";
}
@GetMapping("/menu/{id}/details")
public String showDishDetails(@PathVariable("id") int id, Model model) {
Dish dish = dishService.getDishById(id);
model.addAttribute("dish", dish);
return "dishDetails";
}
@PostMapping("/menu/{id}/edit")
public String editDishDetails(@PathVariable("id") int id, @RequestParam("name") String name,
@RequestParam("description") String description,
@RequestParam("recipe") String recipe){
// @RequestParam("image") MultipartFile image) throws IOException {
| dishService.editDishDetails(id, name, description, recipe); | //, image.getBytes());
return "redirect:/menu/{id}/details";
}
@GetMapping("kitchen/{id}/recipe")
public String showRecipe(@PathVariable("id") int id, Model model) {
Dish dish = dishService.getDishById(id);
model.addAttribute("dish", dish);
return "recipe";
}
}
| RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/MenuController.java | Neural-Enigma-RestaurantManagement-Spring-Boot-Java-086881a | [
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/DishService.java",
"retrieved_chunk": " dish.setCost(cost);\n dish.setType(dishType);\n dishRepository.save(dish);\n }\n }\n public Dish getDishById(int id) {\n return dishRepository.findById(id).orElse(null);\n }\n public void editDishDetails(int id, String name, String description, String recipe){//}, byte[] image) {\n Dish dish = getDishById(id);",
"score": 70.17347816425573
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Models/Dish.java",
"retrieved_chunk": " @Column(name = \"image\", nullable = true)\n private byte[] image;\n public String getDescription() {\n return description;\n }\n public void setDescription(String description) {\n this.description = description;\n }\n public void setRecipe(String recipe) {\n this.recipe = recipe;",
"score": 51.88108463220643
},
{
"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": 50.52000047893047
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Models/Dish.java",
"retrieved_chunk": " @Column(name = \"cost\")\n private double cost;\n @ManyToOne\n @JoinColumn(name = \"type_id\")\n private DishType type;\n @Column(name = \"description\", nullable = true)\n private String description;\n @Column(name = \"recipe\", nullable = true)\n private String recipe;\n @Lob",
"score": 36.72536600728215
},
{
"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": 34.18254234149115
}
] | java | dishService.editDishDetails(id, name, description, recipe); |
package com.example.RestaurantManagement.Services;
import com.example.RestaurantManagement.Models.Dish;
import com.example.RestaurantManagement.Models.DishType;
import com.example.RestaurantManagement.Models.OrderedDish;
import com.example.RestaurantManagement.Repositories.DishRepository;
import com.example.RestaurantManagement.Repositories.DishTypeRepository;
import com.example.RestaurantManagement.Repositories.OrderedDishRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class DishService {
private final DishRepository dishRepository;
private final OrderedDishRepository orderedDishRepository;
private final DishTypeRepository dishTypeRepository;
@Autowired
public DishService(DishRepository dishRepository, OrderedDishRepository orderedDishRepository, DishTypeRepository dishTypeRepository) {
this.dishRepository = dishRepository;
this.orderedDishRepository = orderedDishRepository;
this.dishTypeRepository = dishTypeRepository;
}
public List<Dish> getAllDishes() {
return dishRepository.findAll();
}
public boolean checkIfDishIsOrdered(int id) {
List<OrderedDish> orderedDishes = orderedDishRepository.findAllByDish_Id(id);
return !orderedDishes.isEmpty();
}
public void editDish(int id, String name, double cost, String typeName) {
Optional<Dish> optionalDish = dishRepository.findById(id);
if (optionalDish.isPresent()) {
Dish dish = optionalDish.get();
dish.setName(name);
dish.setCost(cost);
DishType dishType = dishTypeRepository.findByName(typeName);
if (dishType != null) {
dish.setType(dishType);
}
dishRepository.save(dish);
}
}
public void deleteDish(int id) {
dishRepository.deleteById(id);
}
public void addDish(String name, double cost, String typeName) {
| DishType dishType = dishTypeRepository.findByName(typeName); |
if (dishType != null) {
Dish dish = new Dish();
dish.setName(name);
dish.setCost(cost);
dish.setType(dishType);
dishRepository.save(dish);
}
}
public Dish getDishById(int id) {
return dishRepository.findById(id).orElse(null);
}
public void editDishDetails(int id, String name, String description, String recipe){//}, byte[] image) {
Dish dish = getDishById(id);
if (dish != null) {
dish.setName(name);
dish.setDescription(description);
dish.setRecipe(recipe);
// dish.setImage(image);
dishRepository.save(dish);
}
}
}
| RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/DishService.java | Neural-Enigma-RestaurantManagement-Spring-Boot-Java-086881a | [
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/MenuController.java",
"retrieved_chunk": " public String deleteDish(@RequestParam(\"id\") int id) {\n if (dishService.checkIfDishIsOrdered(id)) {\n } else {\n dishService.deleteDish(id);\n }\n return \"redirect:/menu\";\n }\n @PostMapping(\"/menu/add\")\n public String addDish(@RequestParam(\"name\") String name, @RequestParam(\"cost\") double cost,\n @RequestParam(\"type\") String typeName) {",
"score": 33.4822279202254
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/MenuController.java",
"retrieved_chunk": " dishService.addDish(name, cost, typeName);\n return \"redirect:/menu\";\n }\n @GetMapping(\"/menu/{id}/details\")\n public String showDishDetails(@PathVariable(\"id\") int id, Model model) {\n Dish dish = dishService.getDishById(id);\n model.addAttribute(\"dish\", dish);\n return \"dishDetails\";\n }\n @PostMapping(\"/menu/{id}/edit\")",
"score": 28.9189028346741
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/MenuController.java",
"retrieved_chunk": " @PostMapping(\"/menu/edit\")\n public String editDish(@RequestParam(\"id\") int id, @RequestParam(\"name\") String name,\n @RequestParam(\"cost\") double cost, @RequestParam(\"type\") String typeName) {\n if (dishService.checkIfDishIsOrdered(id)) {\n } else {\n dishService.editDish(id, name, cost, typeName);\n }\n return \"redirect:/menu\";\n }\n @PostMapping(\"/menu/delete\")",
"score": 26.15903932499761
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Models/Dish.java",
"retrieved_chunk": " this.name = name;\n }\n public double getCost() {\n return cost;\n }\n public void setCost(double cost) {\n this.cost = cost;\n }\n public DishType getType() {\n return type;",
"score": 21.588942590051744
},
{
"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": 17.44793086377194
}
] | java | DishType dishType = dishTypeRepository.findByName(typeName); |
package com.example.RestaurantManagement.Controllers;
import com.example.RestaurantManagement.Models.Dish;
import com.example.RestaurantManagement.Models.DishType;
import com.example.RestaurantManagement.Repositories.DishTypeRepository;
import com.example.RestaurantManagement.Services.DishService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
@Controller
public class MenuController {
private final DishService dishService;
private final DishTypeRepository dishTypeRepository;
public MenuController(DishService dishService, DishTypeRepository dishTypeRepository) {
this.dishService = dishService;
this.dishTypeRepository = dishTypeRepository;
}
@GetMapping("/menu")
public String showMenu(Model model) {
List<Dish> dishes = dishService.getAllDishes();
List<DishType> dishTypes = dishTypeRepository.findAll();
model.addAttribute("dishes", dishes);
model.addAttribute("dishTypes", dishTypes);
return "menu";
}
@PostMapping("/menu/edit")
public String editDish(@RequestParam("id") int id, @RequestParam("name") String name,
@RequestParam("cost") double cost, @RequestParam("type") String typeName) {
if | (dishService.checkIfDishIsOrdered(id)) { |
} else {
dishService.editDish(id, name, cost, typeName);
}
return "redirect:/menu";
}
@PostMapping("/menu/delete")
public String deleteDish(@RequestParam("id") int id) {
if (dishService.checkIfDishIsOrdered(id)) {
} else {
dishService.deleteDish(id);
}
return "redirect:/menu";
}
@PostMapping("/menu/add")
public String addDish(@RequestParam("name") String name, @RequestParam("cost") double cost,
@RequestParam("type") String typeName) {
dishService.addDish(name, cost, typeName);
return "redirect:/menu";
}
@GetMapping("/menu/{id}/details")
public String showDishDetails(@PathVariable("id") int id, Model model) {
Dish dish = dishService.getDishById(id);
model.addAttribute("dish", dish);
return "dishDetails";
}
@PostMapping("/menu/{id}/edit")
public String editDishDetails(@PathVariable("id") int id, @RequestParam("name") String name,
@RequestParam("description") String description,
@RequestParam("recipe") String recipe){
// @RequestParam("image") MultipartFile image) throws IOException {
dishService.editDishDetails(id, name, description, recipe);//, image.getBytes());
return "redirect:/menu/{id}/details";
}
@GetMapping("kitchen/{id}/recipe")
public String showRecipe(@PathVariable("id") int id, Model model) {
Dish dish = dishService.getDishById(id);
model.addAttribute("dish", dish);
return "recipe";
}
}
| RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/MenuController.java | Neural-Enigma-RestaurantManagement-Spring-Boot-Java-086881a | [
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/DishService.java",
"retrieved_chunk": " this.dishTypeRepository = dishTypeRepository;\n }\n public List<Dish> getAllDishes() {\n return dishRepository.findAll();\n }\n public boolean checkIfDishIsOrdered(int id) {\n List<OrderedDish> orderedDishes = orderedDishRepository.findAllByDish_Id(id);\n return !orderedDishes.isEmpty();\n }\n public void editDish(int id, String name, double cost, String typeName) {",
"score": 40.40981497008683
},
{
"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": 32.743772097877155
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Models/Dish.java",
"retrieved_chunk": " this.name = name;\n }\n public double getCost() {\n return cost;\n }\n public void setCost(double cost) {\n this.cost = cost;\n }\n public DishType getType() {\n return type;",
"score": 29.440684001563927
},
{
"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": 29.02482687888299
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/TableBookingController.java",
"retrieved_chunk": " }\n model.addAttribute(\"times\", times);\n return \"book-table\";\n }\n @PostMapping(\"/book-table\")\n public String bookTable(@RequestParam(\"table_id\") int tableId,\n @RequestParam(\"date\") Date date,\n @RequestParam(\"time\") String time,\n @RequestParam(\"info\") String info,\n Model model) {",
"score": 28.797642709202538
}
] | 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": 64.04531632048095
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java",
"retrieved_chunk": " orders = orders.stream()\n .filter(order -> order.getStartTime().toLocalDateTime().toLocalDate().equals(date))\n .collect(Collectors.toList());\n }\n model.addAttribute(\"orders\", orders);\n return \"view-orders\";\n }\n @PostMapping(\"/update-status/{id}\")\n public String updateStatus(@PathVariable int id, @RequestParam String status) {\n Optional<Order> optionalOrder = orderRepository.findById(id);",
"score": 44.57551356665936
},
{
"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": 43.079863751013214
},
{
"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": 33.90341149230931
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java",
"retrieved_chunk": " }\n if (date != null) {\n orders = orders.stream()\n .filter(order -> order.getStartTime().toLocalDateTime().toLocalDate().equals(date))\n .collect(Collectors.toList());\n }\n model.addAttribute(\"orders\", orders);\n return \"manage-orders\";\n }\n @PostMapping(\"/update-status-manager/{id}\")",
"score": 33.75201671830272
}
] | 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": 77.2027177448378
},
{
"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": 61.7312973791923
},
{
"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": 44.912651173535984
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java",
"retrieved_chunk": " orders = orders.stream()\n .filter(order -> order.getStartTime().toLocalDateTime().toLocalDate().equals(date))\n .collect(Collectors.toList());\n }\n model.addAttribute(\"orders\", orders);\n return \"view-orders\";\n }\n @PostMapping(\"/update-status/{id}\")\n public String updateStatus(@PathVariable int id, @RequestParam String status) {\n Optional<Order> optionalOrder = orderRepository.findById(id);",
"score": 33.12376301642098
},
{
"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": 32.10838421040155
}
] | java | <OrderedDish> dishesInOrder = orderedDishRepository.findAllByOrder(orderedDish.getOrder()); |
package com.example.RestaurantManagement.Controllers;
import com.example.RestaurantManagement.Models.Dish;
import com.example.RestaurantManagement.Models.DishType;
import com.example.RestaurantManagement.Repositories.DishTypeRepository;
import com.example.RestaurantManagement.Services.DishService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
@Controller
public class MenuController {
private final DishService dishService;
private final DishTypeRepository dishTypeRepository;
public MenuController(DishService dishService, DishTypeRepository dishTypeRepository) {
this.dishService = dishService;
this.dishTypeRepository = dishTypeRepository;
}
@GetMapping("/menu")
public String showMenu(Model model) {
List<Dish> dishes = dishService.getAllDishes();
List<DishType> dishTypes = dishTypeRepository.findAll();
model.addAttribute("dishes", dishes);
model.addAttribute("dishTypes", dishTypes);
return "menu";
}
@PostMapping("/menu/edit")
public String editDish(@RequestParam("id") int id, @RequestParam("name") String name,
@RequestParam("cost") double cost, @RequestParam("type") String typeName) {
if (dishService.checkIfDishIsOrdered(id)) {
} else {
dishService.editDish(id, name, cost, typeName);
}
return "redirect:/menu";
}
@PostMapping("/menu/delete")
public String deleteDish(@RequestParam("id") int id) {
| if (dishService.checkIfDishIsOrdered(id)) { |
} else {
dishService.deleteDish(id);
}
return "redirect:/menu";
}
@PostMapping("/menu/add")
public String addDish(@RequestParam("name") String name, @RequestParam("cost") double cost,
@RequestParam("type") String typeName) {
dishService.addDish(name, cost, typeName);
return "redirect:/menu";
}
@GetMapping("/menu/{id}/details")
public String showDishDetails(@PathVariable("id") int id, Model model) {
Dish dish = dishService.getDishById(id);
model.addAttribute("dish", dish);
return "dishDetails";
}
@PostMapping("/menu/{id}/edit")
public String editDishDetails(@PathVariable("id") int id, @RequestParam("name") String name,
@RequestParam("description") String description,
@RequestParam("recipe") String recipe){
// @RequestParam("image") MultipartFile image) throws IOException {
dishService.editDishDetails(id, name, description, recipe);//, image.getBytes());
return "redirect:/menu/{id}/details";
}
@GetMapping("kitchen/{id}/recipe")
public String showRecipe(@PathVariable("id") int id, Model model) {
Dish dish = dishService.getDishById(id);
model.addAttribute("dish", dish);
return "recipe";
}
}
| RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/MenuController.java | Neural-Enigma-RestaurantManagement-Spring-Boot-Java-086881a | [
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Services/DishService.java",
"retrieved_chunk": " 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": 44.32843073340633
},
{
"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": 41.844927127802755
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Models/Dish.java",
"retrieved_chunk": " this.name = name;\n }\n public double getCost() {\n return cost;\n }\n public void setCost(double cost) {\n this.cost = cost;\n }\n public DishType getType() {\n return type;",
"score": 30.065931719994683
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/StaffController.java",
"retrieved_chunk": " @PostMapping(\"/staff/update\")\n public String updateStaff(@RequestParam(\"id\") int id, @RequestParam(\"role\") String role) {\n Staff staff = staffService.getStaffById(id);\n staff.setRole(role);\n staffService.updateStaff(staff);\n return \"redirect:/staff\";\n }\n @PostMapping(\"/staff/delete\")\n public String deleteStaff(@RequestParam(\"id\") int id) {\n Staff staff = staffService.getStaffById(id);",
"score": 29.40015925241749
},
{
"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": 26.816051939638687
}
] | 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/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": 43.12074361914393
},
{
"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": 41.08134777121783
},
{
"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": 37.22362507288311
},
{
"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": 37.21782517945191
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/AuthorisationController.java",
"retrieved_chunk": " model.addAttribute(\"errorMessage\", \"Неверный логин или пароль\");\n return \"login\";\n }\n @GetMapping(\"/logout\")\n public String logout(HttpSession request) {\n request.setAttribute(\"staff\", null);\n return \"redirect:/login\";\n }\n}",
"score": 36.687255545477306
}
] | 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/Models/TableBooking.java",
"retrieved_chunk": " public void setTime(Time time) {\n this.time = time;\n }\n public String getInfo() {\n return info;\n }\n public void setInfo(String info) {\n this.info = info;\n }\n}",
"score": 43.26053487029332
},
{
"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": 42.49347939526694
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Models/TableBooking.java",
"retrieved_chunk": " @ManyToOne\n @JoinColumn(name = \"table_id\")\n private Tables table;\n @Column(name = \"date\")\n private Date date;\n @Column(name = \"time\")\n private Time time;\n @Column(name = \"info\")\n private String info;\n public int getId() {",
"score": 39.7907209864882
},
{
"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": 34.43335286494166
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Models/TableBooking.java",
"retrieved_chunk": " }\n public Date getDate() {\n return date;\n }\n public void setDate(Date date) {\n this.date = date;\n }\n public Time getTime() {\n return time;\n }",
"score": 21.740951825309512
}
] | java | <Tables> allTables = tableBookingService.getAllTables(); |
package com.example.RestaurantManagement.Controllers;
import com.example.RestaurantManagement.Models.Order;
import com.example.RestaurantManagement.Models.OrderedDish;
import com.example.RestaurantManagement.Repositories.OrderRepository;
import com.example.RestaurantManagement.Repositories.OrderedDishRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Controller
public class KitchenController {
@Autowired
private OrderedDishRepository orderedDishRepository;
@Autowired
private OrderRepository orderRepository;
@GetMapping("/kitchen")
public String getKitchen(Model model) {
List<OrderedDish> orderedDishes = orderedDishRepository.findAll();
List<OrderedDish> acceptedDishes = orderedDishes.stream()
.filter(dish -> dish.getStatus().equals("Принят"))
.collect(Collectors.toList());
model.addAttribute("orderedDishes", acceptedDishes);
return "kitchen";
}
@PostMapping("/update-dish-status/{id}")
public String updateDishStatus(@PathVariable("id") int id, @RequestParam("status") String status) {
Optional<OrderedDish> optionalOrderedDish = orderedDishRepository.findById(id);
if (optionalOrderedDish.isPresent()) {
OrderedDish orderedDish = optionalOrderedDish.get();
orderedDish.setStatus(status);
orderedDishRepository.save(orderedDish);
List<OrderedDish> dishesInOrder = orderedDishRepository.findAllByOrder(orderedDish.getOrder());
boolean allMatch = dishesInOrder.stream()
.allMatch(dish -> dish.getStatus().equals(status));
if (allMatch) {
Order order | = orderedDish.getOrder(); |
order.setStatus(status);
orderRepository.save(order);
}
}
return "redirect:/kitchen";
}
} | RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/KitchenController.java | Neural-Enigma-RestaurantManagement-Spring-Boot-Java-086881a | [
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java",
"retrieved_chunk": " 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": 65.84098998246394
},
{
"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": 59.068686807551124
},
{
"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": 41.89185373229084
},
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/OrderController.java",
"retrieved_chunk": " if (optionalOrder.isPresent()) {\n Order order = optionalOrder.get();\n order.setStatus(status);\n order.getOrderedDishes().forEach(dish -> dish.setStatus(status));\n if (status.equals(\"Закрыт\")) {\n order.setEndTime(Timestamp.valueOf(LocalDateTime.now()));\n }\n orderRepository.save(order);\n }\n return \"redirect:/view-orders\";",
"score": 36.7965620519328
},
{
"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": 34.56606483202989
}
] | java | = orderedDish.getOrder(); |
package com.example.RestaurantManagement.Controllers;
import com.example.RestaurantManagement.Models.Staff;
import com.example.RestaurantManagement.Services.StaffService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class StaffController {
@Autowired
private HttpSession session;
private final StaffService staffService;
@Autowired
public StaffController(StaffService staffService) {
this.staffService = staffService;
}
@GetMapping("/staff")
public String getStaff(Model model) {
model.addAttribute("staff", staffService.getAllStaff());
model.addAttribute("newStaff", new Staff());
model.addAttribute("currentUser", getCurrentUser());
return "staff";
}
@PostMapping("/staff/add")
public String addStaff(@ModelAttribute Staff staff, Model model) {
if (staffService. | loginExists(staff.getLogin())) { |
model.addAttribute("error", "Логин уже существует!");
model.addAttribute("staff", staffService.getAllStaff());
model.addAttribute("newStaff", staff);
return "redirect:/staff";
}
java.util.Date currentDate = new java.util.Date();
staff.setApparatusEmployed(new java.sql.Date(currentDate.getTime()));
staffService.saveStaff(staff);
return "redirect:/staff";
}
@PostMapping("/staff/update")
public String updateStaff(@RequestParam("id") int id, @RequestParam("role") String role) {
Staff staff = staffService.getStaffById(id);
staff.setRole(role);
staffService.updateStaff(staff);
return "redirect:/staff";
}
@PostMapping("/staff/delete")
public String deleteStaff(@RequestParam("id") int id) {
Staff staff = staffService.getStaffById(id);
staffService.deleteStaff(staff);
return "redirect:/staff";
}
public Staff getCurrentUser() {
return (Staff) session.getAttribute("staff");
}
}
| RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/StaffController.java | Neural-Enigma-RestaurantManagement-Spring-Boot-Java-086881a | [
{
"filename": "RestaurantManagement/src/main/java/com/example/RestaurantManagement/Controllers/AuthorisationController.java",
"retrieved_chunk": " public String login() {\n return \"login\";\n }\n @PostMapping(\"/login\")\n public String postLogin(@RequestParam String login, @RequestParam String password, Model model, HttpSession session) {\n Optional<Staff> optionalStaff = staffRepository.findStaffByLogin(login);\n if (optionalStaff.isPresent()) {\n Staff staff = optionalStaff.get();\n if (staff.getPassword().equals(password) && staff.getDismissalFromWork() == null) {\n session.setAttribute(\"staff\", staff);",
"score": 38.9953336332203
},
{
"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": 38.76192853056444
},
{
"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": 36.191320209562505
},
{
"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": 33.85145420943587
},
{
"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": 32.326026181240124
}
] | java | loginExists(staff.getLogin())) { |
/*
* Conventional Commits Version Policy
* Copyright (C) 2022-2023 Niels Basjes
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.basjes.maven.release.version.conventionalcommits;
import org.apache.maven.scm.ChangeSet;
import org.semver.Version;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The set of rules that determine from the commit history what the next version should be.
*/
public class VersionRules {
private final Pattern tagPattern;
private final List<Pattern> majorUpdatePatterns = new ArrayList<>();
private final List<Pattern> minorUpdatePatterns = new ArrayList<>();
public VersionRules(ConventionalCommitsVersionConfig config) {
int patternFlags = Pattern.MULTILINE | Pattern.DOTALL | Pattern.UNIX_LINES;
// The default assumes then entire tag is what we need
String tagRegex = "^(\\d+\\.\\d+\\.\\d+)$";
// The default rules following https://www.conventionalcommits.org/en/v1.0.0/
majorUpdatePatterns.add(Pattern.compile("^[a-zA-Z]+(?:\\([a-zA-Z\\d_-]+\\))?!: .*$", patternFlags));
majorUpdatePatterns.add(Pattern.compile("^BREAKING CHANGE:.*$", patternFlags));
minorUpdatePatterns.add(Pattern.compile("^feat(?:\\([a-zA-Z\\d_-]+\\))?: .*$", patternFlags));
if (config != null) {
String semverConfigVersionTag = config.getVersionTag();
if (semverConfigVersionTag != null && !semverConfigVersionTag.trim().isEmpty()) {
tagRegex = semverConfigVersionTag;
}
if ( | !config.getMajorRules().isEmpty() || !config.getMinorRules().isEmpty()) { |
majorUpdatePatterns.clear();
for (String majorRule : config.getMajorRules()) {
majorUpdatePatterns.add(Pattern.compile(majorRule, patternFlags));
}
minorUpdatePatterns.clear();
for (String minorRule : config.getMinorRules()) {
minorUpdatePatterns.add(Pattern.compile(minorRule, patternFlags));
}
}
}
tagPattern = Pattern.compile(tagRegex, Pattern.MULTILINE);
}
public Version.Element getMaxElementSinceLastVersionTag(CommitHistory commitHistory) {
Version.Element maxElement = Version.Element.PATCH;
for (ChangeSet change : commitHistory.getChanges()) {
if (isMajorUpdate(change.getComment())) {
// This is the highest possible: Immediately done
return Version.Element.MAJOR;
} else if (isMinorUpdate(change.getComment())) {
// Have to wait, there may be another MAJOR one.
maxElement = Version.Element.MINOR;
}
}
return maxElement;
}
public boolean isMajorUpdate(String input) {
return matchesAny(majorUpdatePatterns, input);
}
public boolean isMinorUpdate(String input) {
return matchesAny(minorUpdatePatterns, input);
}
private boolean matchesAny(List<Pattern> patterns, String input) {
for (Pattern pattern : patterns) {
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
return true;
}
}
return false;
}
public Pattern getTagPattern() {
return tagPattern;
}
public List<Pattern> getMajorUpdatePatterns() {
return majorUpdatePatterns;
}
public List<Pattern> getMinorUpdatePatterns() {
return minorUpdatePatterns;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append("Conventional Commits config:\n");
result.append(" VersionTag:\n");
result.append(" >>>").append(tagPattern).append("<<<\n");
result.append(" Major Rules:\n");
for (Pattern majorUpdatePattern : majorUpdatePatterns) {
result.append(" >>>").append(majorUpdatePattern).append("<<<\n");
}
result.append(" Minor Rules:\n");
for (Pattern minorUpdatePattern : minorUpdatePatterns) {
result.append(" >>>").append(minorUpdatePattern).append("<<<\n");
}
return result.toString();
}
}
| src/main/java/nl/basjes/maven/release/version/conventionalcommits/VersionRules.java | nielsbasjes-conventional-commits-maven-release-151e36d | [
{
"filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/ConfigParsingTest.java",
"retrieved_chunk": " 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": 54.43253782211159
},
{
"filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/mockscm/MockScmProvider.java",
"retrieved_chunk": " if (newTag != null && !newTag.trim().isEmpty()) {\n tags.add(newTag);\n }\n }\n if (!tags.isEmpty()) {\n changeSet.setTags(tags);\n }\n }\n return changeSet;\n }",
"score": 48.373814306632994
},
{
"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": 46.692134056029374
},
{
"filename": "src/main/java/nl/basjes/maven/release/version/conventionalcommits/ConventionalCommitsVersionConfig.java",
"retrieved_chunk": "import org.slf4j.LoggerFactory;\nimport java.util.ArrayList;\nimport java.util.List;\n@JacksonXmlRootElement(localName = \"ProjectVersionPolicyConfig\")\npublic class ConventionalCommitsVersionConfig {\n private static final XmlMapper XML_MAPPER = new XmlMapper();\n public static ConventionalCommitsVersionConfig fromXml(String configXml) {\n if (configXml == null || configXml.trim().isEmpty()) {\n return null;\n }",
"score": 26.059772002664765
},
{
"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": 25.555305993324048
}
] | 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": " 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": 54.43253782211159
},
{
"filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/mockscm/MockScmProvider.java",
"retrieved_chunk": " if (newTag != null && !newTag.trim().isEmpty()) {\n tags.add(newTag);\n }\n }\n if (!tags.isEmpty()) {\n changeSet.setTags(tags);\n }\n }\n return changeSet;\n }",
"score": 48.373814306632994
},
{
"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": 46.692134056029374
},
{
"filename": "src/main/java/nl/basjes/maven/release/version/conventionalcommits/ConventionalCommitsVersionConfig.java",
"retrieved_chunk": "import org.slf4j.LoggerFactory;\nimport java.util.ArrayList;\nimport java.util.List;\n@JacksonXmlRootElement(localName = \"ProjectVersionPolicyConfig\")\npublic class ConventionalCommitsVersionConfig {\n private static final XmlMapper XML_MAPPER = new XmlMapper();\n public static ConventionalCommitsVersionConfig fromXml(String configXml) {\n if (configXml == null || configXml.trim().isEmpty()) {\n return null;\n }",
"score": 26.059772002664765
},
{
"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": 25.555305993324048
}
] | 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": 93.98029273003803
},
{
"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": 79.32465038008529
},
{
"filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/NextVersionSpecificationTest.java",
"retrieved_chunk": "import static org.semver.Version.Element.PATCH;\nclass NextVersionSpecificationTest extends AbstractNextVersionTest {\n @Test\n void testConventionalCommitsExamples() {\n //Verifying the examples show on https://www.conventionalcommits.org/en/v1.0.0/#examples\n VersionRules rules = DEFAULT_VERSION_RULES;\n // Commit message with description and breaking change footer\n assertNextVersion(\n rules,\n \"feat: allow provided config object to extend other configs\\n\" +",
"score": 27.294984338929968
},
{
"filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/NextVersionSpecificationTest.java",
"retrieved_chunk": " rules,\n \"feat(api)!: send an email to the customer when a product is shipped\",\n MAJOR);\n // Commit message with both `!` and BREAKING CHANGE footer\n assertNextVersion(\n rules,\n \"chore!: drop support for Node 6\\n\" +\n \"\\n\" +\n \"BREAKING CHANGE: use JavaScript features not available in Node 6.\\n\",\n MAJOR);",
"score": 24.214509921403607
},
{
"filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/NextVersionSpecificationTest.java",
"retrieved_chunk": " \"\\n\" +\n \"BREAKING CHANGE: `extends` key in config file is now used for extending other config files\\n\",\n MAJOR);\n // Commit message with `!` to draw attention to breaking change\n assertNextVersion(\n rules,\n \"feat!: send an email to the customer when a product is shipped\",\n MAJOR);\n // Commit message with scope and `!` to draw attention to breaking change\n assertNextVersion(",
"score": 23.247257812359088
}
] | 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/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": 40.340748592150305
},
{
"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": 36.70828266362886
},
{
"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": 26.175881875379577
},
{
"filename": "src/test/java/nl/basjes/maven/release/version/conventionalcommits/NextVersionCalculationTest.java",
"retrieved_chunk": "import static org.junit.jupiter.api.Assertions.assertThrows;\nimport static org.semver.Version.Element.MAJOR;\nimport static org.semver.Version.Element.MINOR;\nimport static org.semver.Version.Element.PATCH;\npublic class NextVersionCalculationTest extends AbstractNextVersionTest {\n private static ConventionalCommitsVersionPolicy versionPolicy;\n @BeforeAll\n public static void setUp() {\n versionPolicy = new ConventionalCommitsVersionPolicy();\n }",
"score": 25.45249529454901
},
{
"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": 24.340662732989113
}
] | java | commitHistory.getChanges()) { |
package com.noq.backend.services;
import com.noq.backend.models.User;
import com.noq.backend.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@Service
public class UserService {
private UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public List<User> getAllUsers() {
return userRepository.getAllUsers();
}
public List<User> createUsers() {
User user1 = new User(
"1",
"Person Personsson",
false
);
User user2 = new User(
"2",
"Individ Individson",
true
);
userRepository.save(user1);
userRepository.save(user2);
return new ArrayList<>(userRepository.getAllUsers());
}
public User getUserById(String userId) {
User existingUser = userRepository.getUserByUserId(userId);
if (existingUser != null) {
return existingUser;
} else {
return | userRepository.getUserByUserId(userId); |
}
}
}
| noq-backend/src/main/java/com/noq/backend/services/UserService.java | noQ-sweden-noq-7f5b8d1 | [
{
"filename": "noq-backend/src/main/java/com/noq/backend/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": 28.551385050468255
},
{
"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": 27.856383338249625
},
{
"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": 25.793083310678057
},
{
"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": 22.335198626442352
},
{
"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": 21.732129637198867
}
] | java | userRepository.getUserByUserId(userId); |
/*
* Conventional Commits Version Policy
* Copyright (C) 2022-2023 Niels Basjes
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.basjes.maven.release.version.conventionalcommits;
import org.apache.maven.scm.ChangeSet;
import org.apache.maven.scm.ScmException;
import org.apache.maven.scm.ScmFileSet;
import org.apache.maven.scm.command.changelog.ChangeLogScmRequest;
import org.apache.maven.scm.command.changelog.ChangeLogSet;
import org.apache.maven.scm.provider.ScmProvider;
import org.apache.maven.scm.repository.ScmRepository;
import org.apache.maven.shared.release.policy.version.VersionPolicyRequest;
import org.apache.maven.shared.release.versions.VersionParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.stream.Collectors;
/**
* Helper class to manage the commit history of the SCM repository.
*/
public class CommitHistory {
private final List<ChangeSet> changes = new ArrayList<>();
private String latestVersionTag = null;
public List<ChangeSet> getChanges() {
return changes;
}
public void addChanges(ChangeSet change) {
this.changes.add(change);
}
public String getLastVersionTag() {
return latestVersionTag;
}
public CommitHistory(VersionPolicyRequest request, VersionRules versionRules)
throws ScmException, VersionParseException {
ScmRepository scmRepository = request.getScmRepository();
ScmProvider scmProvider = request.getScmProvider();
String workingDirectory = request.getWorkingDirectory();
if (scmRepository == null || scmProvider == null || workingDirectory == null) {
// We do not have a commit history so the changes and tags will remain empty
return;
}
ChangeLogScmRequest changeLogRequest = new ChangeLogScmRequest(
scmRepository,
new ScmFileSet(new File(workingDirectory))
);
Logger logger = LoggerFactory.getLogger(CommitHistory.class);
int limit = 0;
while (latestVersionTag == null) {
limit += 100; // Read the repository in incremental steps of 100
changeLogRequest.setLimit(null);
changeLogRequest.setLimit(limit);
changes.clear();
logger.debug("Checking the last {} commits.", limit);
ChangeLogSet changeLogSet = scmProvider.changeLog(changeLogRequest).getChangeLog();
if (changeLogSet == null) {
return;
}
List<ChangeSet> changeSets = changeLogSet.getChangeSets();
for (ChangeSet changeSet : changeSets) {
addChanges(changeSet);
List<String> changeSetTags = changeSet.getTags();
List<String> versionTags = changeSetTags
.stream()
.map(tag -> {
Matcher matcher | = versionRules.getTagPattern().matcher(tag); |
if (matcher.find()) {
return matcher.group(1);
}
return null;
}
)
.filter(Objects::nonNull)
.collect(Collectors.toList());
if (!versionTags.isEmpty()) {
// Found the previous release tag
if (versionTags.size() > 1) {
throw new VersionParseException("Most recent commit with tags has multiple version tags: "
+ versionTags);
}
latestVersionTag = versionTags.get(0);
logger.debug("Found tag");
break; // We have the last version tag
}
}
if (latestVersionTag == null &&
changeSets.size() < limit) {
// Apparently there are simply no more commits.
logger.debug("Did not find any tag");
break;
}
}
}
@Override
public String toString() {
List<String> logLines = new ArrayList<>();
logLines.add("Filtered commit history:");
for (ChangeSet changeSet : changes) {
logLines.add("-- Comment: \"" + changeSet.getComment() + "\"");
logLines.add(" Tags : " + changeSet.getTags());
}
StringBuilder sb = new StringBuilder();
for (String logLine : logLines) {
sb.append(logLine).append('\n');
}
return sb.toString();
}
}
| src/main/java/nl/basjes/maven/release/version/conventionalcommits/CommitHistory.java | nielsbasjes-conventional-commits-maven-release-151e36d | [
{
"filename": "src/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": 40.5470274825969
},
{
"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": 37.470342905146666
},
{
"filename": "src/main/java/nl/basjes/maven/release/version/conventionalcommits/VersionRules.java",
"retrieved_chunk": " return matchesAny(majorUpdatePatterns, input);\n }\n public boolean isMinorUpdate(String input) {\n return matchesAny(minorUpdatePatterns, input);\n }\n private boolean matchesAny(List<Pattern> patterns, String input) {\n for (Pattern pattern : patterns) {\n Matcher matcher = pattern.matcher(input);\n if (matcher.find()) {\n return true;",
"score": 30.624451775779065
},
{
"filename": "src/it/setup/maven-scm-provider-dummy/src/main/java/org/apache/maven/scm/provider/dummy/DummyTagsScmProvider.java",
"retrieved_chunk": " ChangeLogSet changeLogSet = new ChangeLogSet(\n Arrays.asList(\n changeSet( \"Commit 19\" ),\n changeSet( \"Commit 18\" ),\n changeSet( \"Commit 17\" ),\n changeSet( \"Commit 16\" ),\n changeSet( \"Commit 15\", \"tag 1\", \"tag 2\" ),\n changeSet( \"feat(it): This is a new feature.\" ), // For Conventional Commits.\n changeSet( \"Commit 13\" ),\n changeSet( \"Commit 12\", \"tag 3\" ),",
"score": 28.29680587431789
},
{
"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": 26.438579633119982
}
] | java | = versionRules.getTagPattern().matcher(tag); |
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": 40.61383757423211
},
{
"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": 34.635982642593476
},
{
"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": 29.727921346573815
},
{
"filename": "noq-backend/src/main/java/com/noq/backend/repository/ReservationRepository.java",
"retrieved_chunk": "package com.noq.backend.repository;\nimport com.noq.backend.models.Reservation;\nimport java.util.List;\npublic interface ReservationRepository {\n Reservation save (Reservation reservation);\n Reservation getReservationByReservationId(String reservationId);\n List<Reservation> getAllReservations();\n void saveAll(List<Reservation> reservations);\n}",
"score": 28.493748083000607
},
{
"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": 24.038848231610068
}
] | java | List<Reservation> reservations = reservationRepository.getAllReservations().stream()
.filter(res -> { |
/*
* 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/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": 30.38825003029231
},
{
"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": 27.607621923106834
},
{
"filename": "src/main/java/nl/basjes/maven/release/version/conventionalcommits/CommitHistory.java",
"retrieved_chunk": " }\n if (latestVersionTag == null &&\n changeSets.size() < limit) {\n // Apparently there are simply no more commits.\n logger.debug(\"Did not find any tag\");\n break;\n }\n }\n }\n @Override",
"score": 27.21738034249339
},
{
"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(0, config.getMajorRules().size());\n assertEquals(0, config.getMinorRules().size());\n VersionRules versionRules = new VersionRules(config);\n assertTagPatternIsDefault(versionRules);\n assertMajorIsDefault(versionRules);\n assertMinorIsDefault(versionRules);\n }\n @Test",
"score": 25.012876694235626
},
{
"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": 23.70029261861393
}
] | 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/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": 29.34495743112045
},
{
"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": 21.627983076211397
},
{
"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": 19.869979606547272
},
{
"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": 19.353943000549258
},
{
"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": 17.201733499616438
}
] | java | User existingUser = userRepository.getUserByUserId(userId); |
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/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": 23.592538680507865
},
{
"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": 15.188353760542022
},
{
"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": 14.455538547226325
},
{
"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": 11.76469520243978
},
{
"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": 11.60226434054392
}
] | java | ArrayList<>(userRepository.getAllUsers()); |
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": 36.92747379730598
},
{
"filename": "src/main/java/org/example/callback/robot/RobotMsgCallbackConsumer.java",
"retrieved_chunk": " }\n } catch (Exception e) {\n log.error(\"receive group message by robot error:\" + e.getMessage(), e);\n }\n return new JSONObject();\n }\n}",
"score": 16.21192303609771
},
{
"filename": "src/main/java/org/example/service/AccessTokenService.java",
"retrieved_chunk": " return false;\n } catch (Exception e) {\n log.error(\"AccessTokenService_getTokenFromRemoteServer getAccessToken throw Exception\", e);\n return false;\n }\n }\n public String getAccessToken() {\n return accessToken.accessToken;\n }\n public boolean isTokenNearlyExpired() {",
"score": 15.51675379524435
},
{
"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": 12.711313971849824
},
{
"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": 9.459290602534864
}
] | 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": 51.039574256380156
},
{
"filename": "src/main/java/org/objectionary/entities/NestedObject.java",
"retrieved_chunk": "public final class NestedObject extends Entity {\n /**\n * The name of the object with application.\n */\n private final String name;\n /**\n * The application of the object with application.\n */\n private final Map<String, Entity> application;\n /**",
"score": 47.045136815283065
},
{
"filename": "src/main/java/org/objectionary/entities/NestedObject.java",
"retrieved_chunk": " * @return The name of the object with application.\n */\n public String getName() {\n return this.name;\n }\n /**\n * Returns the application of the object with application.\n * @return The application of the object with application.\n */\n public Map<String, Entity> getApplication() {",
"score": 46.88917323754339
},
{
"filename": "src/main/java/org/objectionary/entities/NestedObject.java",
"retrieved_chunk": " * Constructor.\n * @param name The name of the object with application.\n * @param application The application of the object with application.\n */\n public NestedObject(final String name, final Map<String, Entity> application) {\n this.name = name;\n this.application = application;\n }\n /**\n * Returns the name of the object with application.",
"score": 44.60754369419064
},
{
"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": 41.7112141621643
}
] | 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": 63.57732036977016
},
{
"filename": "src/main/java/org/objectionary/ObjectsBox.java",
"retrieved_chunk": " }\n result.add(\n String.format(\"%s ↦ %s\", binding.getKey(), binding.getValue())\n );\n }\n return String.format(\n \"%s(𝜋) ↦ ⟦ %s ⟧\",\n name,\n String.join(\", \", result)\n );",
"score": 34.88885365263199
},
{
"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": 33.14742592650109
},
{
"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": 29.29925627463053
},
{
"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": 28.654081743978775
}
] | 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": 52.8550927503732
},
{
"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": 45.7834666088479
},
{
"filename": "src/main/java/org/objectionary/entities/NestedObject.java",
"retrieved_chunk": " * Constructor.\n * @param name The name of the object with application.\n * @param application The application of the object with application.\n */\n public NestedObject(final String name, final Map<String, Entity> application) {\n this.name = name;\n this.application = application;\n }\n /**\n * Returns the name of the object with application.",
"score": 43.07711860016265
},
{
"filename": "src/main/java/org/objectionary/entities/NestedObject.java",
"retrieved_chunk": "public final class NestedObject extends Entity {\n /**\n * The name of the object with application.\n */\n private final String name;\n /**\n * The application of the object with application.\n */\n private final Map<String, Entity> application;\n /**",
"score": 41.29434250195646
},
{
"filename": "src/main/java/org/objectionary/ObjectsBox.java",
"retrieved_chunk": " * Constructor.\n */\n public ObjectsBox() {\n this.box = new HashMap<>();\n }\n /**\n * Puts an object into the box.\n * @param name The name of the object.\n * @param bindings The bindings of the object.\n */",
"score": 40.54490470557333
}
] | java | box.get(object.getName())); |
package org.example.callback.robot;
import com.alibaba.fastjson.JSONObject;
import org.example.model.DingTalkBotMessage;
import org.example.model.Text;
import org.example.service.RobotGroupMessagesService;
import com.dingtalk.open.app.api.callback.OpenDingTalkCallbackListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author zeymo
*/
@Slf4j
@Component
public class RobotMsgCallbackConsumer implements OpenDingTalkCallbackListener<DingTalkBotMessage, JSONObject> {
private RobotGroupMessagesService robotGroupMessagesService;
@Autowired
public RobotMsgCallbackConsumer(RobotGroupMessagesService robotGroupMessagesService) {
this.robotGroupMessagesService = robotGroupMessagesService;
}
/**
* https://open.dingtalk.com/document/orgapp/the-application-robot-in-the-enterprise-sends-group-chat-messages
*
* @param message
* @return
*/
@Override
public JSONObject execute(DingTalkBotMessage message) {
try {
Text text = message.getText();
if (text != null) {
String msg = text.getContent();
log.info("receive bot message from user={}, msg={}", message.getSenderId(), msg);
String openConversationId = message.getConversationId();
try {
//发送机器人消息
| robotGroupMessagesService.send(openConversationId, "hello"); |
} catch (Exception e) {
log.error("send group message by robot error:" + e.getMessage(), e);
}
}
} catch (Exception e) {
log.error("receive group message by robot error:" + e.getMessage(), e);
}
return new JSONObject();
}
}
| src/main/java/org/example/callback/robot/RobotMsgCallbackConsumer.java | open-dingtalk-dingtalk-stream-sdk-java-quick-start-bb889b2 | [
{
"filename": "src/main/java/org/example/service/RobotGroupMessagesService.java",
"retrieved_chunk": " 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": 29.836854832068997
},
{
"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": 25.696804803098402
},
{
"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": 15.673990525912524
},
{
"filename": "src/main/java/org/example/StreamCallbackListener.java",
"retrieved_chunk": " * @author zeymo\n */\n@Component\npublic class StreamCallbackListener {\n @Value(\"${app.appKey}\")\n private String appKey;\n @Value(\"${app.appSecret}\")\n private String appSecret;\n @Value(\"${robot.msg.topic}\")\n private String robotMsgTopic;",
"score": 13.379025280497217
},
{
"filename": "src/main/java/org/example/service/AccessTokenService.java",
"retrieved_chunk": " break;\n }\n Thread.sleep(100);\n }\n if (maxTryTimes <= 0) {\n throw new RuntimeException(\"fail to get accessToken from remote, try 3 times, please check your appKey\" +\n \" and appSecret\");\n }\n }\n /**",
"score": 9.57494192141775
}
] | java | robotGroupMessagesService.send(openConversationId, "hello"); |
/*
* The MIT License (MIT)
*
* Copyright (c) 2023 Objectionary.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.objectionary.parsing;
import java.util.HashMap;
import java.util.Map;
import org.objectionary.Tokenizer;
import org.objectionary.entities.Data;
import org.objectionary.entities.Empty;
import org.objectionary.entities.Entity;
import org.objectionary.entities.FlatObject;
import org.objectionary.entities.Lambda;
import org.objectionary.entities.Locator;
import org.objectionary.entities.NestedObject;
import org.objectionary.tokens.BracketToken;
import org.objectionary.tokens.StringToken;
import org.objectionary.tokens.Token;
/**
* Entities reader.
* @since 0.1.0
* @checkstyle NonStaticMethodCheck (100 lines)
*/
public final class Entities {
/**
* The tokenizer.
*/
@SuppressWarnings({"PMD.UnusedPrivateField", "PMD.SingularField"})
private final Tokenizer tokenizer;
/**
* Constructor.
* @param tokenizer The tokenizer.
*/
public Entities(final Tokenizer tokenizer) {
this.tokenizer = tokenizer;
}
/**
* Reads one entity.
* @return The parsed entity.
*/
public Entity one() {
final Token token = this. | tokenizer.getToken(); |
if (!(token instanceof StringToken)) {
throw new IllegalArgumentException("Expected string token");
}
final String value = ((StringToken) token).getValue();
final Entity result;
final TypeChecker type = new TypeChecker(value);
if (type.isEmpty()) {
result = new Empty();
} else if (type.isLocator()) {
result = new Locator(value);
} else if (type.isData()) {
result = new Data(Integer.parseInt(value.substring(2), 16));
} else if (type.isLambda()) {
result = new Lambda(value);
} else if (type.isObject()) {
result = this.createObject(value);
} else {
throw new IllegalArgumentException("Unknown token");
}
return result;
}
/**
* Reads nested entity.
* @return The parsed nested entity.
*/
public Map<String, Entity> nested() {
final Map<String, Entity> result = new HashMap<>();
while (true) {
final Token token = this.tokenizer.getToken();
if (token instanceof BracketToken) {
final BracketToken bracket = (BracketToken) token;
if (bracket.getState() == BracketToken.BracketType.CLOSE) {
break;
}
}
final String name = ((StringToken) token).getValue();
this.tokenizer.next();
this.tokenizer.next();
final Entity entity = this.one();
result.put(name, entity);
this.tokenizer.next();
}
return result;
}
/**
* Creates an object.
* @param value The value to parse.
* @return The parsed entity.
*/
private Entity createObject(final String value) {
final Entity result;
if (value.contains(")")) {
result = new FlatObject(
value.substring(0, value.indexOf('(')),
value.substring(value.indexOf('(') + 1, value.indexOf(')'))
);
} else if (value.contains("(")) {
this.tokenizer.next();
final Map<String, Entity> application = this.nested();
result = new NestedObject(
value.substring(0, value.indexOf('(')), application
);
} else {
result = new FlatObject(value, "");
}
return result;
}
}
| src/main/java/org/objectionary/parsing/Entities.java | objectionary-flatty-688a3da | [
{
"filename": "src/test/java/org/objectionary/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": 35.3574962015044
},
{
"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": 34.650197867265184
},
{
"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": 28.208805819258096
},
{
"filename": "src/main/java/org/objectionary/entities/Entity.java",
"retrieved_chunk": " */\n public abstract Entity copy();\n /**\n * Add one pi to the entity.\n * @return The entity with one pi added.\n */\n public abstract Entity reframe();\n}",
"score": 27.310548722554934
},
{
"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": 18.934216929894152
}
] | 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": 65.13097206607243
},
{
"filename": "src/main/java/org/objectionary/ObjectsBox.java",
"retrieved_chunk": " }\n result.add(\n String.format(\"%s ↦ %s\", binding.getKey(), binding.getValue())\n );\n }\n return String.format(\n \"%s(𝜋) ↦ ⟦ %s ⟧\",\n name,\n String.join(\", \", result)\n );",
"score": 56.54655278443577
},
{
"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": 38.28366923667414
},
{
"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": 34.56590211331243
},
{
"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": 34.138137770257025
}
] | java | ).getName(); |
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": 41.93907791627097
},
{
"filename": "src/main/java/onebeastchris/util/PlayerInfoStorage.java",
"retrieved_chunk": " this.position = position;\n }\n public Text getName() {\n return name;\n }\n public ServerWorld getWorld() {\n return world;\n }\n public int[] getPosition() {\n return position;",
"score": 27.22390641159954
},
{
"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": 27.102010650267882
},
{
"filename": "src/main/java/onebeastchris/event/Timer.java",
"retrieved_chunk": " for (ServerPlayerEntity player : PlayerDataUtil.visitorMap.values()){\n player.sendMessage(Text.of(message), true);\n }\n }\n}",
"score": 25.24421774210359
},
{
"filename": "src/main/java/onebeastchris/event/ServerJoinEvent.java",
"retrieved_chunk": " player.setCustomNameVisible(true);\n //calling this once to ensure players see... something.\n player.sendMessage(Text.of(visitors.config.getWelcomeVisitorMessage1()), true);\n }\n }\n });\n }\n}",
"score": 24.0925759702079
}
] | java | (storage.getName()); |
/*
* The MIT License (MIT)
*
* Copyright (c) 2023 Objectionary.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.objectionary;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import org.objectionary.entities.Entity;
import org.objectionary.entities.FlatObject;
import org.objectionary.entities.Locator;
import org.objectionary.entities.NestedObject;
/**
* This class realizes the flattening of the objects.
* @since 0.1.0
*/
public final class Flatter {
/**
* The counter of created objects.
*/
private static int counter;
/**
* The objects box.
*/
private final ObjectsBox box;
/**
* Constructor.
* @param box The objects box.
*/
public Flatter(final ObjectsBox box) {
this.box = box;
}
/**
* Flattens the objects.
* @return The flattened objects box.
*/
public ObjectsBox flat() {
Flatter.counter = this.findMaxIndex() + 1;
boolean found = true;
while (found) {
found = false;
for (
final Map.Entry<String, Map<String, Entity>> entry : this.box.content().entrySet()
) {
for (final Map.Entry<String, Entity> binding : entry.getValue().entrySet()) {
if (binding.getValue() instanceof NestedObject) {
this.flatOne(
binding.getKey(),
(NestedObject) binding.getValue(),
entry.getValue()
);
found = true;
break;
}
}
if (found) {
break;
}
}
}
this.removeUnusedObjects();
this.resuspendLocalBinds();
this.renameObjects();
return this.box;
}
/**
* Flattens one object.
* @param key The name of binding to this non-flat object.
* @param object The non-flat object itself.
* @param user The object which contains the non-flat object.
*/
private void flatOne(
final String key,
final NestedObject object,
final Map<String, Entity> user
) {
final Map<String, Entity> bindings = deepCopy(this.box.get(object.getName()));
final Map<String, Entity> application = deepCopy(object.getApplication());
final Map<String, Entity> reframed = deepReframe(application);
for (final Map.Entry<String, Entity> entry : reframed.entrySet()) {
if (bindings.containsKey(entry.getKey())) {
bindings.put(entry.getKey(), entry.getValue());
}
}
final String name = String.format("ν%d", Flatter.counter);
Flatter.counter += 1;
this.box.put(name, bindings);
user.put(key, new FlatObject(name, "ξ"));
}
/**
* Removes unused objects from the box.
*/
private void removeUnusedObjects() {
final Set<String> uses = new HashSet<>();
final Queue<String> queue = new LinkedList<>();
queue.add("ν0");
while (!queue.isEmpty()) {
final String name = queue.poll();
uses.add(name);
for (final Map.Entry<String, Entity> binding : this.box.get(name).entrySet()) {
if (binding.getValue() instanceof FlatObject) {
final String value = ((FlatObject) binding.getValue()).getName();
if (!uses.contains(value)) {
queue.add(value);
}
}
}
}
this.box.content().entrySet().removeIf(entry -> !uses.contains(entry.getKey()));
}
/**
* Takes all locators to local variables and clearly sets them up.
*/
private void resuspendLocalBinds() {
for (final Map<String, Entity> bindings : this.box.content().values()) {
boolean found = true;
while (found) {
found = false;
for (final Map.Entry<String, Entity> binding : bindings.entrySet()) {
if (binding.getValue() instanceof Locator) {
final List<String> locator = ((Locator) binding.getValue()).getPath();
if (!locator.get(0).equals("ξ")) {
continue;
}
final String name = locator.get(1);
final Entity entity = bindings.get(name);
bindings.remove(name);
bindings.put(binding.getKey(), entity);
found = true;
break;
}
}
}
}
}
/**
* Renames the objects to use smaller indexes.
*/
private void renameObjects() {
final List<Integer> list = new ArrayList<>(0);
for (final String name : this.box.content().keySet()) {
list.add(Integer.parseInt(name.substring(1)));
}
Collections.sort(list);
final int size = this.box.content().size();
for (int idx = 0; idx < size; ++idx) {
final String end = String.valueOf(idx);
final String start = String.valueOf(list.get(idx));
if (end.equals(start)) {
continue;
}
this.changeName(String.format("ν%s", start), String.format("ν%s", end));
}
}
/**
* Changes the name of the object.
* @param start The old name.
* @param end The new name.
*/
private void changeName(final String start, final String end) {
for (
final Map.Entry<String, Map<String, Entity>> bindings
: this.box.content().entrySet()
) {
for (final Map.Entry<String, Entity> binding : bindings.getValue().entrySet()) {
if (
binding.getValue() instanceof FlatObject
&& ((FlatObject) binding.getValue()).getName().equals(start)
) {
binding.setValue(
new FlatObject(end, | ((FlatObject) binding.getValue()).getLocator())
); |
}
}
}
this.box.put(end, this.box.get(start));
this.box.content().remove(start);
}
/**
* Finds the maximum index of the objects.
* @return The maximum index of the objects.
*/
private int findMaxIndex() {
return this.box.content().keySet().stream()
.map(key -> Integer.parseInt(key.substring(1)))
.max(Integer::compareTo).orElse(0);
}
/**
* Returns the deep copy of the bindings.
* @param bindings The bindings.
* @return The deep copy of the bindings.
*/
private static Map<String, Entity> deepCopy(final Map<String, Entity> bindings) {
final Map<String, Entity> result = new HashMap<>(bindings.size());
for (final Map.Entry<String, Entity> entry : bindings.entrySet()) {
result.put(entry.getKey(), entry.getValue().copy());
}
return result;
}
/**
* Returns the deep reframe of the bindings.
* @param bindings The bindings.
* @return The deep reframe of the bindings.
*/
private static Map<String, Entity> deepReframe(final Map<String, Entity> bindings) {
final Map<String, Entity> result = new HashMap<>(bindings.size());
for (final Map.Entry<String, Entity> entry : bindings.entrySet()) {
result.put(entry.getKey(), entry.getValue().reframe());
}
return result;
}
}
| src/main/java/org/objectionary/Flatter.java | objectionary-flatty-688a3da | [
{
"filename": "src/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": 69.39736358315623
},
{
"filename": "src/main/java/org/objectionary/ObjectsBox.java",
"retrieved_chunk": " }\n result.add(\n String.format(\"%s ↦ %s\", binding.getKey(), binding.getValue())\n );\n }\n return String.format(\n \"%s(𝜋) ↦ ⟦ %s ⟧\",\n name,\n String.join(\", \", result)\n );",
"score": 57.20902779897265
},
{
"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": 38.35927971470796
},
{
"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": 28.468671581902925
},
{
"filename": "src/main/java/org/objectionary/ObjectsBox.java",
"retrieved_chunk": " if (entry.getKey().equals(\"ν0\")) {\n continue;\n }\n results.add(\n ObjectsBox.serialize(entry.getKey(), entry.getValue())\n );\n }\n return String.join(\"\\n\", results);\n }\n /**",
"score": 27.833220782213484
}
] | java | ((FlatObject) binding.getValue()).getLocator())
); |
/*
* The MIT License (MIT)
*
* Copyright (c) 2023 Objectionary.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.objectionary.parsing;
import java.util.HashMap;
import java.util.Map;
import org.objectionary.Tokenizer;
import org.objectionary.entities.Data;
import org.objectionary.entities.Empty;
import org.objectionary.entities.Entity;
import org.objectionary.entities.FlatObject;
import org.objectionary.entities.Lambda;
import org.objectionary.entities.Locator;
import org.objectionary.entities.NestedObject;
import org.objectionary.tokens.BracketToken;
import org.objectionary.tokens.StringToken;
import org.objectionary.tokens.Token;
/**
* Entities reader.
* @since 0.1.0
* @checkstyle NonStaticMethodCheck (100 lines)
*/
public final class Entities {
/**
* The tokenizer.
*/
@SuppressWarnings({"PMD.UnusedPrivateField", "PMD.SingularField"})
private final Tokenizer tokenizer;
/**
* Constructor.
* @param tokenizer The tokenizer.
*/
public Entities(final Tokenizer tokenizer) {
this.tokenizer = tokenizer;
}
/**
* Reads one entity.
* @return The parsed entity.
*/
public Entity one() {
final Token token = this.tokenizer.getToken();
if (!(token instanceof StringToken)) {
throw new IllegalArgumentException("Expected string token");
}
final String value = ((StringToken) token).getValue();
final Entity result;
final TypeChecker type = new TypeChecker(value);
if (type.isEmpty()) {
result = new Empty();
} else if (type.isLocator()) {
result = new Locator(value);
} else if (type.isData()) {
result = new Data(Integer.parseInt(value.substring(2), 16));
} else if (type.isLambda()) {
result = new Lambda(value);
} else if (type.isObject()) {
result = this.createObject(value);
} else {
throw new IllegalArgumentException("Unknown token");
}
return result;
}
/**
* Reads nested entity.
* @return The parsed nested entity.
*/
public Map<String, Entity> nested() {
final Map<String, Entity> result = new HashMap<>();
while (true) {
final Token token = this.tokenizer.getToken();
if (token instanceof BracketToken) {
final BracketToken bracket = (BracketToken) token;
if (bracket.getState() == BracketToken.BracketType.CLOSE) {
break;
}
}
final String name = ((StringToken) token).getValue();
| this.tokenizer.next(); |
this.tokenizer.next();
final Entity entity = this.one();
result.put(name, entity);
this.tokenizer.next();
}
return result;
}
/**
* Creates an object.
* @param value The value to parse.
* @return The parsed entity.
*/
private Entity createObject(final String value) {
final Entity result;
if (value.contains(")")) {
result = new FlatObject(
value.substring(0, value.indexOf('(')),
value.substring(value.indexOf('(') + 1, value.indexOf(')'))
);
} else if (value.contains("(")) {
this.tokenizer.next();
final Map<String, Entity> application = this.nested();
result = new NestedObject(
value.substring(0, value.indexOf('(')), application
);
} else {
result = new FlatObject(value, "");
}
return result;
}
}
| src/main/java/org/objectionary/parsing/Entities.java | objectionary-flatty-688a3da | [
{
"filename": "src/test/java/org/objectionary/TokenizerTest.java",
"retrieved_chunk": " );\n if (expected instanceof BracketToken) {\n MatcherAssert.assertThat(\n ((BracketToken) expected).getState(),\n Matchers.equalTo(((BracketToken) tokenizer.getToken()).getState())\n );\n }\n tokenizer.next();\n }\n }",
"score": 71.90650367603169
},
{
"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": 67.16825165050335
},
{
"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": 64.27201363905513
},
{
"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": 45.828224134936455
},
{
"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": 36.887824229774
}
] | 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": 93.40596016780592
},
{
"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": 70.86122836217864
},
{
"filename": "src/main/java/committee/nova/flotage/impl/block/RaftBlock.java",
"retrieved_chunk": " public final BlockMember member;\n public RaftBlock(Settings settings, BlockMember member) {\n super(settings);\n this.setDefaultState(this.getDefaultState().with(WATERLOGGED, true));\n this.member = member;\n }\n @Override\n protected void appendProperties(StateManager.Builder<Block, BlockState> builder) {\n builder.add(WATERLOGGED);\n }",
"score": 67.87594358845708
},
{
"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": 65.77014370922731
},
{
"filename": "src/main/java/committee/nova/flotage/init/TabRegistry.java",
"retrieved_chunk": "public class TabRegistry {\n public static final Identifier TEXTURE = new Identifier(\"textures/gui/container/creative_inventory/flotage.png\");\n public static ItemGroup TAB;\n public static void register() {\n TAB = Registry.register(Registries.ITEM_GROUP, Flotage.id(\"tab\"),\n FabricItemGroup.builder()\n .displayName(Text.translatable(\"itemGroup.flotage.tab\"))\n .entries(((displayContext, entries) -> {\n for (BlockMember member : BlockMember.values()) {\n entries.add(new ItemStack(ItemRegistry.get(member.raft())));",
"score": 65.47140124240201
}
] | 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/compat/rei/category/RackREICategory.java",
"retrieved_chunk": " Point origin = bounds.getLocation();\n final List<Widget> widgets = new ArrayList<>();\n widgets.add(Widgets.createRecipeBase(bounds));\n Rectangle bgBounds = centeredIntoRecipeBase(new Point(origin.x, origin.y), 91, 54);\n widgets.add(Widgets.createTexturedWidget(GUI_TEXTURE, new Rectangle(bgBounds.x, bgBounds.y, 91, 54), 10, 9));\n widgets.add(Widgets.createSlot(new Point(bgBounds.x + 7, bgBounds.y + 1))\n .entries(display.getInputEntries().get(0)).markInput().disableBackground());\n Arrow arrow = Widgets.createArrow(new Point(bgBounds.x + 39, bgBounds.y + 18)).animationDurationTicks(20);\n widgets.add(arrow);\n Text text = Text.translatable(\"tip.flotage.rack.mode\").append(Text.translatable(\"tip.flotage.rack.mode.\" + display.getMode().toString()));",
"score": 98.05353841810842
},
{
"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": 88.81993196128079
},
{
"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": 81.70721273291333
},
{
"filename": "src/main/java/committee/nova/flotage/impl/block/RaftBlock.java",
"retrieved_chunk": " public final BlockMember member;\n public RaftBlock(Settings settings, BlockMember member) {\n super(settings);\n this.setDefaultState(this.getDefaultState().with(WATERLOGGED, true));\n this.member = member;\n }\n @Override\n protected void appendProperties(StateManager.Builder<Block, BlockState> builder) {\n builder.add(WATERLOGGED);\n }",
"score": 77.18235391202234
},
{
"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": 76.49074475430264
}
] | 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": 109.70222504641956
},
{
"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": 85.11354584877019
},
{
"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": 76.6869250351314
},
{
"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": 75.62821302761273
},
{
"filename": "src/main/java/committee/nova/flotage/impl/block/RaftBlock.java",
"retrieved_chunk": " public final BlockMember member;\n public RaftBlock(Settings settings, BlockMember member) {\n super(settings);\n this.setDefaultState(this.getDefaultState().with(WATERLOGGED, true));\n this.member = member;\n }\n @Override\n protected void appendProperties(StateManager.Builder<Block, BlockState> builder) {\n builder.add(WATERLOGGED);\n }",
"score": 74.48064648075959
}
] | 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": 142.95268581919666
},
{
"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": 113.55267955272181
},
{
"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": 109.35862990351049
},
{
"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": 99.58414280517492
},
{
"filename": "src/main/java/committee/nova/flotage/init/BlockRegistry.java",
"retrieved_chunk": "public class BlockRegistry {\n public static void register() {\n for (BlockMember member : BlockMember.values()) {\n woodenRaft(member);\n brokenRaft(member);\n fence(member);\n crossedFence(member);\n rack(member);\n }\n }",
"score": 96.6641823101356
}
] | 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": 73.83846186027392
},
{
"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": 66.24797749971415
},
{
"filename": "src/main/java/committee/nova/flotage/init/TabRegistry.java",
"retrieved_chunk": "public class TabRegistry {\n public static final Identifier TEXTURE = new Identifier(\"textures/gui/container/creative_inventory/flotage.png\");\n public static ItemGroup TAB;\n public static void register() {\n TAB = Registry.register(Registries.ITEM_GROUP, Flotage.id(\"tab\"),\n FabricItemGroup.builder()\n .displayName(Text.translatable(\"itemGroup.flotage.tab\"))\n .entries(((displayContext, entries) -> {\n for (BlockMember member : BlockMember.values()) {\n entries.add(new ItemStack(ItemRegistry.get(member.raft())));",
"score": 61.444473904598716
},
{
"filename": "src/main/java/committee/nova/flotage/impl/block/RaftBlock.java",
"retrieved_chunk": " public final BlockMember member;\n public RaftBlock(Settings settings, BlockMember member) {\n super(settings);\n this.setDefaultState(this.getDefaultState().with(WATERLOGGED, true));\n this.member = member;\n }\n @Override\n protected void appendProperties(StateManager.Builder<Block, BlockState> builder) {\n builder.add(WATERLOGGED);\n }",
"score": 61.27124069615458
},
{
"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": 61.00651381357745
}
] | 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": 109.70222504641956
},
{
"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": 85.11354584877019
},
{
"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": 76.6869250351314
},
{
"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": 75.62821302761273
},
{
"filename": "src/main/java/committee/nova/flotage/impl/block/RaftBlock.java",
"retrieved_chunk": " public final BlockMember member;\n public RaftBlock(Settings settings, BlockMember member) {\n super(settings);\n this.setDefaultState(this.getDefaultState().with(WATERLOGGED, true));\n this.member = member;\n }\n @Override\n protected void appendProperties(StateManager.Builder<Block, BlockState> builder) {\n builder.add(WATERLOGGED);\n }",
"score": 74.48064648075959
}
] | 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": 142.95268581919666
},
{
"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": 113.55267955272181
},
{
"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": 109.35862990351049
},
{
"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": 99.58414280517492
},
{
"filename": "src/main/java/committee/nova/flotage/init/BlockRegistry.java",
"retrieved_chunk": "public class BlockRegistry {\n public static void register() {\n for (BlockMember member : BlockMember.values()) {\n woodenRaft(member);\n brokenRaft(member);\n fence(member);\n crossedFence(member);\n rack(member);\n }\n }",
"score": 96.6641823101356
}
] | 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": 128.1407785219061
},
{
"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": 101.39222516233157
},
{
"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": 94.7602118573365
},
{
"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": 89.49048122531231
},
{
"filename": "src/main/java/committee/nova/flotage/init/BlockRegistry.java",
"retrieved_chunk": "public class BlockRegistry {\n public static void register() {\n for (BlockMember member : BlockMember.values()) {\n woodenRaft(member);\n brokenRaft(member);\n fence(member);\n crossedFence(member);\n rack(member);\n }\n }",
"score": 84.62134769640242
}
] | 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": 93.40596016780592
},
{
"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": 70.86122836217864
},
{
"filename": "src/main/java/committee/nova/flotage/impl/block/RaftBlock.java",
"retrieved_chunk": " public final BlockMember member;\n public RaftBlock(Settings settings, BlockMember member) {\n super(settings);\n this.setDefaultState(this.getDefaultState().with(WATERLOGGED, true));\n this.member = member;\n }\n @Override\n protected void appendProperties(StateManager.Builder<Block, BlockState> builder) {\n builder.add(WATERLOGGED);\n }",
"score": 67.87594358845708
},
{
"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": 65.77014370922731
},
{
"filename": "src/main/java/committee/nova/flotage/init/TabRegistry.java",
"retrieved_chunk": "public class TabRegistry {\n public static final Identifier TEXTURE = new Identifier(\"textures/gui/container/creative_inventory/flotage.png\");\n public static ItemGroup TAB;\n public static void register() {\n TAB = Registry.register(Registries.ITEM_GROUP, Flotage.id(\"tab\"),\n FabricItemGroup.builder()\n .displayName(Text.translatable(\"itemGroup.flotage.tab\"))\n .entries(((displayContext, entries) -> {\n for (BlockMember member : BlockMember.values()) {\n entries.add(new ItemStack(ItemRegistry.get(member.raft())));",
"score": 65.47140124240201
}
] | 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": 26.437420119468356
},
{
"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": 22.788890172983585
},
{
"filename": "src/main/java/com/orangomango/chess/multiplayer/Server.java",
"retrieved_chunk": "\tpublic Server(String ip, int port){\n\t\tthis.ip = ip;\n\t\tthis.port = port;\n\t\ttry {\n\t\t\tthis.server = new ServerSocket(port, 10, InetAddress.getByName(ip));\n\t\t} catch (IOException ex){\n\t\t\tclose();\n\t\t}\n\t\tlisten();\n\t\tLogger.writeInfo(\"Server started\");",
"score": 21.49881821686657
},
{
"filename": "src/main/java/com/orangomango/chess/MainApplication.java",
"retrieved_chunk": "\t\t\t\t\t\t} catch (NumberFormatException ex){\n\t\t\t\t\t\t\tLogger.writeError(ex.getMessage());\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tTextArea data = new TextArea(this.board.getFEN()+\"\\n\\n\"+this.board.getPGN());\n\t\t\t\t\tButton connect = new Button(\"Connect\");\n\t\t\t\t\tconnect.setOnAction(ev -> {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tString ip = cip.getText().equals(\"\") ? \"192.168.1.247\" : cip.getText();\n\t\t\t\t\t\t\tint port = cport.getText().equals(\"\") ? 1234 : Integer.parseInt(cport.getText());",
"score": 19.603903517728757
},
{
"filename": "src/main/java/com/orangomango/chess/MainApplication.java",
"retrieved_chunk": "\t\t\t\t\tw.setOnAction(ev -> this.viewPoint = Color.WHITE);\n\t\t\t\t\tRadioButton b = new RadioButton(\"Black\");\n\t\t\t\t\tb.setOnAction(ev -> this.viewPoint = Color.BLACK);\n\t\t\t\t\tButton startServer = new Button(\"Start server\");\n\t\t\t\t\tstartServer.setOnAction(ev -> {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tString ip = sip.getText().equals(\"\") ? \"192.168.1.247\" : sip.getText();\n\t\t\t\t\t\t\tint port = sport.getText().equals(\"\") ? 1234 : Integer.parseInt(sport.getText());\n\t\t\t\t\t\t\tServer server = new Server(ip, port);\n\t\t\t\t\t\t\talert.close();",
"score": 18.467504259641366
}
] | 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/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": 20.58603798365186
},
{
"filename": "src/main/java/com/orangomango/chess/MainApplication.java",
"retrieved_chunk": "\t\t\t\t\t\t\treset(text, time, inc);\n\t\t\t\t\t\t\talert.close();\n\t\t\t\t\t\t} catch (Exception ex){\n\t\t\t\t\t\t\tLogger.writeError(ex.getMessage());\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tHBox serverInfo = new HBox(5, sip, sport, startServer);\n\t\t\t\t\tHBox clientInfo = new HBox(5, cip, cport, connect);\n\t\t\t\t\tHBox whiteBlack = new HBox(5, w, b);\n\t\t\t\t\tHBox rs = new HBox(5, reset, startEngine);",
"score": 18.126570375233918
},
{
"filename": "src/main/java/com/orangomango/chess/multiplayer/Server.java",
"retrieved_chunk": "\t\t} catch (IOException ex){\n\t\t\tex.printStackTrace();\n\t\t}\n\t}\n}",
"score": 16.077613376364422
},
{
"filename": "src/main/java/com/orangomango/chess/multiplayer/ClientManager.java",
"retrieved_chunk": "\t\t} catch (IOException ex){\n\t\t\tex.printStackTrace();\n\t\t}\n\t}\n}",
"score": 16.077613376364422
},
{
"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": 14.833265427446392
}
] | 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": 43.247765158076476
},
{
"filename": "src/main/java/org/swmaestro/kauth/authentication/AbstractAuthenticationFilter.java",
"retrieved_chunk": "\t * @param request {@link HttpServletRequest}\n\t * @param response {@link HttpServletResponse}\n\t * @throws IOException\n\t * @throws ServletException\n\t */\n\tprotected abstract void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,\n\t\tAuthenticationException failed) throws IOException, ServletException;\n}",
"score": 34.214014287086165
},
{
"filename": "src/main/java/org/swmaestro/kauth/authentication/jwt/JwtUsernamePasswordAuthenticationFilter.java",
"retrieved_chunk": "\t * @param response {@link HttpServletResponse}\n\t * @param chain {@link FilterChain}\n\t * @param authResult {@link Authentication}\n\t * @throws IOException\n\t * @throws ServletException\n\t */\n\t@Override\n\tprotected void successfulAuthentication(HttpServletRequest request,\n\t\tHttpServletResponse response, FilterChain chain, Authentication authResult)\n\t\tthrows IOException, ServletException {",
"score": 32.7317969667695
},
{
"filename": "src/main/java/org/swmaestro/kauth/authentication/AbstractAuthenticationFilter.java",
"retrieved_chunk": "\t * @param response {@link HttpServletResponse}\n\t * @param chain {@link FilterChain}\n\t * @param authResult {@link Authentication}\n\t * @throws IOException\n\t * @throws ServletException\n\t */\n\tprotected abstract void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,\n\t\tFilterChain chain, Authentication authResult) throws IOException, ServletException;\n\t/**\n\t * {@link #attemptAuthentication}에서 인증 실패시의 로직을 처리한다.",
"score": 30.283999773376028
},
{
"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": 29.935974183632432
}
] | java | username = jwtUtil.verifyToken(token); |
package com.orangomango.chess;
import java.io.*;
import javafx.scene.paint.Color;
public class Engine{
private static String COMMAND = "stockfish";
private OutputStreamWriter writer;
private BufferedReader reader;
private boolean running = true;
static {
File dir = new File(System.getProperty("user.home"), ".omchess");
String found = null;
if (dir.exists()){
for (File file : dir.listFiles()){
// Custom stockfish file
if (file.getName().startsWith("stockfish")){
found = file.getAbsolutePath();
break;
}
}
}
if (found != null) COMMAND = found;
}
public Engine(){
try {
Process process = Runtime.getRuntime().exec(COMMAND);
this.writer = new OutputStreamWriter(process.getOutputStream());
this.reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
getOutput(20);
} catch (IOException ex){
ex.printStackTrace();
Logger.writeError(ex.getMessage());
this.running = false;
}
}
public boolean isRunning(){
return this.running;
}
public void writeCommand(String command){
try {
this.writer.write(command+"\n");
this.writer.flush();
} catch (IOException ex){
ex.printStackTrace();
}
}
public String getOutput(int time){
StringBuilder builder = new StringBuilder();
try {
Thread.sleep(time);
writeCommand("isready");
while (true){
String line = this.reader.readLine();
if (line == null || line.equals("readyok")){
break;
} else {
builder.append(line+"\n");
}
}
} catch (Exception ex){
ex.printStackTrace();
System.exit(0);
}
return builder.toString();
}
public String getBestMove(Board b){
writeCommand("position fen "+b.getFEN());
writeCommand(String.format("go wtime %s btime %s winc %s binc %s", b.getTime(Color.WHITE), b.getTime(Color.BLACK), b. | getIncrementTime(), b.getIncrementTime())); |
String output = "";
while (true) {
try {
String line = this.reader.readLine();
if (line != null && line.contains("bestmove")){
output = line.split("bestmove ")[1].split(" ")[0];
break;
}
} catch (IOException ex){
ex.printStackTrace();
}
}
if (output.trim().equals("(none)")) return null;
char[] c = output.toCharArray();
return String.valueOf(c[0])+String.valueOf(c[1])+" "+String.valueOf(c[2])+String.valueOf(c[3])+(c.length == 5 ? " "+String.valueOf(c[4]) : "");
}
public String getEval(String fen){
writeCommand("position fen "+fen);
writeCommand("eval");
String output = getOutput(50).split("Final evaluation")[1].split("\\(")[0].trim();
if (output.startsWith(":")) output = output.substring(1).trim();
return output;
}
}
| src/main/java/com/orangomango/chess/Engine.java | OrangoMango-Chess-c4bd8f5 | [
{
"filename": "src/main/java/com/orangomango/chess/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": 34.74012304921874
},
{
"filename": "src/main/java/com/orangomango/chess/Piece.java",
"retrieved_chunk": "\t}\n\t@Override\n\tpublic String toString(){\n\t\treturn String.format(\"%s(%d)\", this.type.getName(), this.color == Color.WHITE ? 0 : 1);\n\t}\n}",
"score": 30.512847370300612
},
{
"filename": "src/main/java/com/orangomango/chess/Board.java",
"retrieved_chunk": "\t\treturn String.format(\"B:%d W:%d - BK:%s WK:%s - BCK:%s WCK:%s\\nChecks: %s %s\\n\",\n\t\t\tblackSum, whiteSum, getAttackers(this.blackKing) != null, getAttackers(this.whiteKing) != null,\n\t\t\tisCheckMate(Color.BLACK), isCheckMate(Color.WHITE),\n\t\t\tthis.blackChecks, this.whiteChecks);\n\t}\n\tpublic List<Piece> getMaterialList(Color color){\n\t\tList<Piece> list = new ArrayList<>(color == Color.WHITE ? this.whiteCaptured : this.blackCaptured);\n\t\tlist.sort((p1, p2) -> Integer.compare(p1.getType().getValue(), p2.getType().getValue()));\n\t\treturn list;\n\t}",
"score": 29.953569219969793
},
{
"filename": "src/main/java/com/orangomango/chess/MainApplication.java",
"retrieved_chunk": "\t\t\t\t\t\t\treset(text, time, inc);\n\t\t\t\t\t\t\talert.close();\n\t\t\t\t\t\t} catch (Exception ex){\n\t\t\t\t\t\t\tLogger.writeError(ex.getMessage());\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tHBox serverInfo = new HBox(5, sip, sport, startServer);\n\t\t\t\t\tHBox clientInfo = new HBox(5, cip, cport, connect);\n\t\t\t\t\tHBox whiteBlack = new HBox(5, w, b);\n\t\t\t\t\tHBox rs = new HBox(5, reset, startEngine);",
"score": 29.46068527797528
},
{
"filename": "src/main/java/com/orangomango/chess/Board.java",
"retrieved_chunk": "\t\tbuilder.append(\"[Event \\\"\"+String.format(\"%s vs %s\", this.playerA, this.playerB)+\"\\\"]\\n\");\n\t\tbuilder.append(\"[Site \\\"com.orangomango.chess\\\"]\\n\");\n\t\tbuilder.append(\"[Date \\\"\"+format.format(date)+\"\\\"]\\n\");\n\t\tbuilder.append(\"[Round \\\"1\\\"]\\n\");\n\t\tbuilder.append(\"[White \\\"\"+this.playerA+\"\\\"]\\n\");\n\t\tbuilder.append(\"[Black \\\"\"+this.playerB+\"\\\"]\\n\");\n\t\tString result = \"*\";\n\t\tif (isDraw()){\n\t\t\tresult = \"½-½\";\n\t\t} else if (isCheckMate(Color.WHITE)){",
"score": 28.837341063511598
}
] | java | getIncrementTime(), b.getIncrementTime())); |
package com.orangomango.chess;
import java.io.*;
import javafx.scene.paint.Color;
public class Engine{
private static String COMMAND = "stockfish";
private OutputStreamWriter writer;
private BufferedReader reader;
private boolean running = true;
static {
File dir = new File(System.getProperty("user.home"), ".omchess");
String found = null;
if (dir.exists()){
for (File file : dir.listFiles()){
// Custom stockfish file
if (file.getName().startsWith("stockfish")){
found = file.getAbsolutePath();
break;
}
}
}
if (found != null) COMMAND = found;
}
public Engine(){
try {
Process process = Runtime.getRuntime().exec(COMMAND);
this.writer = new OutputStreamWriter(process.getOutputStream());
this.reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
getOutput(20);
} catch (IOException ex){
ex.printStackTrace();
Logger.writeError(ex.getMessage());
this.running = false;
}
}
public boolean isRunning(){
return this.running;
}
public void writeCommand(String command){
try {
this.writer.write(command+"\n");
this.writer.flush();
} catch (IOException ex){
ex.printStackTrace();
}
}
public String getOutput(int time){
StringBuilder builder = new StringBuilder();
try {
Thread.sleep(time);
writeCommand("isready");
while (true){
String line = this.reader.readLine();
if (line == null || line.equals("readyok")){
break;
} else {
builder.append(line+"\n");
}
}
} catch (Exception ex){
ex.printStackTrace();
System.exit(0);
}
return builder.toString();
}
public String getBestMove(Board b){
writeCommand("position fen "+b.getFEN());
writeCommand(String.format("go wtime %s btime %s winc %s binc %s", b.getTime( | Color.WHITE), b.getTime(Color.BLACK), b.getIncrementTime(), b.getIncrementTime())); |
String output = "";
while (true) {
try {
String line = this.reader.readLine();
if (line != null && line.contains("bestmove")){
output = line.split("bestmove ")[1].split(" ")[0];
break;
}
} catch (IOException ex){
ex.printStackTrace();
}
}
if (output.trim().equals("(none)")) return null;
char[] c = output.toCharArray();
return String.valueOf(c[0])+String.valueOf(c[1])+" "+String.valueOf(c[2])+String.valueOf(c[3])+(c.length == 5 ? " "+String.valueOf(c[4]) : "");
}
public String getEval(String fen){
writeCommand("position fen "+fen);
writeCommand("eval");
String output = getOutput(50).split("Final evaluation")[1].split("\\(")[0].trim();
if (output.startsWith(":")) output = output.substring(1).trim();
return output;
}
}
| src/main/java/com/orangomango/chess/Engine.java | OrangoMango-Chess-c4bd8f5 | [
{
"filename": "src/main/java/com/orangomango/chess/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": 34.74012304921874
},
{
"filename": "src/main/java/com/orangomango/chess/Piece.java",
"retrieved_chunk": "\t}\n\t@Override\n\tpublic String toString(){\n\t\treturn String.format(\"%s(%d)\", this.type.getName(), this.color == Color.WHITE ? 0 : 1);\n\t}\n}",
"score": 30.512847370300612
},
{
"filename": "src/main/java/com/orangomango/chess/Board.java",
"retrieved_chunk": "\t\treturn String.format(\"B:%d W:%d - BK:%s WK:%s - BCK:%s WCK:%s\\nChecks: %s %s\\n\",\n\t\t\tblackSum, whiteSum, getAttackers(this.blackKing) != null, getAttackers(this.whiteKing) != null,\n\t\t\tisCheckMate(Color.BLACK), isCheckMate(Color.WHITE),\n\t\t\tthis.blackChecks, this.whiteChecks);\n\t}\n\tpublic List<Piece> getMaterialList(Color color){\n\t\tList<Piece> list = new ArrayList<>(color == Color.WHITE ? this.whiteCaptured : this.blackCaptured);\n\t\tlist.sort((p1, p2) -> Integer.compare(p1.getType().getValue(), p2.getType().getValue()));\n\t\treturn list;\n\t}",
"score": 29.953569219969793
},
{
"filename": "src/main/java/com/orangomango/chess/MainApplication.java",
"retrieved_chunk": "\t\t\t\t\t\t\treset(text, time, inc);\n\t\t\t\t\t\t\talert.close();\n\t\t\t\t\t\t} catch (Exception ex){\n\t\t\t\t\t\t\tLogger.writeError(ex.getMessage());\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tHBox serverInfo = new HBox(5, sip, sport, startServer);\n\t\t\t\t\tHBox clientInfo = new HBox(5, cip, cport, connect);\n\t\t\t\t\tHBox whiteBlack = new HBox(5, w, b);\n\t\t\t\t\tHBox rs = new HBox(5, reset, startEngine);",
"score": 29.46068527797528
},
{
"filename": "src/main/java/com/orangomango/chess/Board.java",
"retrieved_chunk": "\t\tbuilder.append(\"[Event \\\"\"+String.format(\"%s vs %s\", this.playerA, this.playerB)+\"\\\"]\\n\");\n\t\tbuilder.append(\"[Site \\\"com.orangomango.chess\\\"]\\n\");\n\t\tbuilder.append(\"[Date \\\"\"+format.format(date)+\"\\\"]\\n\");\n\t\tbuilder.append(\"[Round \\\"1\\\"]\\n\");\n\t\tbuilder.append(\"[White \\\"\"+this.playerA+\"\\\"]\\n\");\n\t\tbuilder.append(\"[Black \\\"\"+this.playerB+\"\\\"]\\n\");\n\t\tString result = \"*\";\n\t\tif (isDraw()){\n\t\t\tresult = \"½-½\";\n\t\t} else if (isCheckMate(Color.WHITE)){",
"score": 28.837341063511598
}
] | java | Color.WHITE), b.getTime(Color.BLACK), b.getIncrementTime(), b.getIncrementTime())); |
package com.orangomango.chess.multiplayer;
import java.io.*;
import java.net.*;
import java.util.*;
import com.orangomango.chess.Logger;
public class Server{
private String ip;
private int port;
private ServerSocket server;
public static List<ClientManager> clients = new ArrayList<>();
public Server(String ip, int port){
this.ip = ip;
this.port = port;
try {
this.server = new ServerSocket(port, 10, InetAddress.getByName(ip));
} catch (IOException ex){
close();
}
listen();
Logger.writeInfo("Server started");
}
private void listen(){
Thread listener = new Thread(() -> {
while (!this.server.isClosed()){
try {
Socket socket = this.server.accept();
ClientManager cm = new ClientManager(socket);
clients.add(cm);
| cm.reply(); |
} catch (IOException ex){
ex.printStackTrace();
}
}
});
listener.setDaemon(true);
listener.start();
}
private void close(){
try {
if (this.server != null) this.server.close();
} catch (IOException ex){
ex.printStackTrace();
}
}
}
| src/main/java/com/orangomango/chess/multiplayer/Server.java | OrangoMango-Chess-c4bd8f5 | [
{
"filename": "src/main/java/com/orangomango/chess/multiplayer/ClientManager.java",
"retrieved_chunk": "\t\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": 59.30805698782798
},
{
"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": 41.719185513400745
},
{
"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": 38.972765518508496
},
{
"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": 30.86365800526604
},
{
"filename": "src/main/java/com/orangomango/chess/MainApplication.java",
"retrieved_chunk": "\tpublic void start(Stage stage){\n\t\tThread counter = new Thread(() -> {\n\t\t\twhile (true){\n\t\t\t\ttry {\n\t\t\t\t\tthis.fps = this.frames;\n\t\t\t\t\tthis.frames = 0;\n\t\t\t\t\tThread.sleep(1000);\n\t\t\t\t} catch (InterruptedException ex){\n\t\t\t\t\tex.printStackTrace();\n\t\t\t\t}",
"score": 24.5262646025829
}
] | java | cm.reply(); |
package org.swmaestro.kauth.authentication;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AccountStatusUserDetailsChecker;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsChecker;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.swmaestro.kauth.core.user.PostAuthenticationService;
import org.swmaestro.kauth.core.user.KauthUserDetailsService;
/**
* Username + Password를 사용하는 {@link AuthenticationManager}
* @author ChangEn Yea
*/
@Lazy
@Component
public class UsernamePasswordAuthenticationManager implements AuthenticationManager {
private final KauthUserDetailsService userDetailsService;
private final PasswordEncoder passwordEncoder;
private final UserDetailsChecker userDetailsChecker = new AccountStatusUserDetailsChecker();
/**
* 인스턴스를 생성한다.
* @param userDetailsService {@link KauthUserDetailsService}
* @param passwordEncoder {@link PasswordEncoder}
*/
public UsernamePasswordAuthenticationManager(KauthUserDetailsService userDetailsService,
PasswordEncoder passwordEncoder) {
this.userDetailsService = userDetailsService;
this.passwordEncoder = passwordEncoder;
}
/**
* <pre>
* {@link UserDetailsService#loadUserByUsername}를 호출해서
* {@link Authentication}의 credentials과 {@link UserDetails}의 password를 {@link PasswordEncoder#matches}를 통해
* 일치 여부를 확인한다.
* 일치 한다면 {@link Authentication} 인스턴스를 인증 처리하고, credential를 삭제하고, 권한을 설정한다.
* </pre>
* @param authentication {@link Authentication}
* @return 인증 처리 된 {@link Authentication}
* @throws AuthenticationException
*/
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
AuthenticationProvider auth = (AuthenticationProvider)authentication;
UserDetails | user = userDetailsService.loadUserByUsername((String)auth.getPrincipal()); |
if (user == null) {
throw new UsernameNotFoundException("userDetailsService.loadUserByUsername returns null");
}
// AccountStatusException 체크
userDetailsChecker.check(user);
if (passwordEncoder.matches((String)auth.getCredentials(), user.getPassword())) {
auth.setAuthenticated(true);
auth.eraseCredentials();
auth.setAuthorities(user.getAuthorities());
userDetailsService.handleSuccessfulAuthentication(user);
return auth;
} else {
throw new BadCredentialsException("Password does not matches.");
}
}
/**
* {@link BadCredentialsException}을 처리하도록
* {@link PostAuthenticationService#handleBadCredentialsException}을 호출한다.
* @param username
* @return 비밀번호 틀린 횟수. (-1 이면 틀린 횟수를 알려주지 않는다)
*/
public Integer handleBadCredentialsException(String username) {
return userDetailsService.handleBadCredentialsException(username);
}
}
| src/main/java/org/swmaestro/kauth/authentication/UsernamePasswordAuthenticationManager.java | nsce9806q-k-spring-security-8e88d3d | [
{
"filename": "src/main/java/org/swmaestro/kauth/authentication/AbstractAuthenticationFilter.java",
"retrieved_chunk": "\t * @return 인증 된 {@link Authentication}\n\t * @throws AuthenticationException 로그인 오류, 계정 잠김 등 인증 실패 시\n\t * @throws IOException\n\t * @throws ServletException\n\t */\n\tpublic abstract Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)\n\t\tthrows AuthenticationException, IOException, ServletException;\n\t/**\n\t * {@link #attemptAuthentication}에서 인증 성공시의 로직을 처리한다.\n\t * @param request {@link HttpServletRequest}",
"score": 36.825470517344996
},
{
"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": 34.29436741458651
},
{
"filename": "src/main/java/org/swmaestro/kauth/authentication/AuthenticationProvider.java",
"retrieved_chunk": "package org.swmaestro.kauth.authentication;\nimport java.util.Collection;\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.core.CredentialsContainer;\nimport org.springframework.security.core.GrantedAuthority;\n/**\n * Kauth에서 사용하는 {@link Authentication} 구현 클래스\n * @author ChangEn Yea\n */\npublic class AuthenticationProvider implements Authentication, CredentialsContainer {",
"score": 31.317825069843664
},
{
"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": 30.758716695892428
},
{
"filename": "src/main/java/org/swmaestro/kauth/authentication/jwt/JwtUsernamePasswordAuthenticationFilter.java",
"retrieved_chunk": "\t * @param response {@link HttpServletResponse}\n\t * @param chain {@link FilterChain}\n\t * @param authResult {@link Authentication}\n\t * @throws IOException\n\t * @throws ServletException\n\t */\n\t@Override\n\tprotected void successfulAuthentication(HttpServletRequest request,\n\t\tHttpServletResponse response, FilterChain chain, Authentication authResult)\n\t\tthrows IOException, ServletException {",
"score": 25.079754540530434
}
] | java | user = userDetailsService.loadUserByUsername((String)auth.getPrincipal()); |
package com.upCycle.service;
import com.upCycle.dto.request.DtoEcoproveedor;
import com.upCycle.dto.response.DtoEcoproveedorResponse;
import com.upCycle.entity.Ecoproveedor;
import com.upCycle.entity.Producto;
import com.upCycle.entity.Usuario;
import com.upCycle.exception.UserAlreadyExistException;
import com.upCycle.exception.UserNotExistException;
import com.upCycle.mapper.EcoproveedorMapper;
import com.upCycle.repository.UsuarioRepository;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class EcoproveedorService {
private final UsuarioRepository repository;
private final EcoproveedorMapper ecoproveedorMapper;
@Autowired
public EcoproveedorService(UsuarioRepository repository, EcoproveedorMapper ecoproveedorMapper) {
this.repository = repository;
this.ecoproveedorMapper = ecoproveedorMapper;
}
public DtoEcoproveedorResponse registrarEcoproveedor(DtoEcoproveedor dtoEcoproveedor, HttpSession session) throws UserAlreadyExistException {
Optional<Usuario> usuario = repository.findByEmail(dtoEcoproveedor.getEmail());
if(usuario.isPresent()){
throw new UserAlreadyExistException("El usuario ya existe");
}
Ecoproveedor user = repository.save(ecoproveedorMapper.dtoEcoproveedorAEntidad(dtoEcoproveedor));
session.setAttribute("usuarioLogueado", user);
return ecoproveedorMapper.entidadADtoEcoproveedor(user);
}
public void guardarProducto(Ecoproveedor ecoproveedor, Producto producto){
ecoproveedor.getListaProductos().add(producto);
int puntos = | ecoproveedor.calcularPuntosTotales(); |
ecoproveedor.setPuntos(puntos);
//repository.save(ecoproveedor);
}
public Integer getEcopuntos(HttpSession session) throws UserNotExistException {
Usuario usuario = (Usuario) session.getAttribute("usuarioLogueado");
Ecoproveedor ecoproveedor = repository.buscarEcoproveedorPorId(usuario.getId()).orElseThrow(() -> new UserNotExistException("El usuario no existe"));
return ecoproveedor.getPuntos();
}
}
| backend/src/main/java/com/upCycle/service/EcoproveedorService.java | No-Country-c11-19-m-javareact-cf62efa | [
{
"filename": "backend/src/main/java/com/upCycle/service/EcocreadorService.java",
"retrieved_chunk": " }\n public DtoEcocreadorResponse registrarEcocreador(DtoEcocreador dtoEcocreador, HttpSession session) throws UserAlreadyExistException {\n Optional<Usuario> usuario = repository.findByEmail(dtoEcocreador.getEmail());\n if(usuario.isPresent()){\n throw new UserAlreadyExistException(\"El usuario ya existe\");\n }\n Ecocreador user = repository.save(ecocreadorMapper.dtoEcocreadorAEntidad(dtoEcocreador));\n session.setAttribute(\"usuarioLogueado\", user);\n return ecocreadorMapper.entidadADtoEcocreador(user);\n }",
"score": 47.08613675244272
},
{
"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": 41.61343467537031
},
{
"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": 39.87483223261289
},
{
"filename": "backend/src/main/java/com/upCycle/service/UsuarioService.java",
"retrieved_chunk": " public DtoUsuarioResponse getUsuario(HttpSession session) {\n Usuario usuario = (Usuario) session.getAttribute(\"usuarioLogueado\");\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 return ecoproveedorMapper.entidadADtoEcoproveedor(ecoproveedor);\n }",
"score": 36.6114504674215
},
{
"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": 33.54952179501237
}
] | java | ecoproveedor.calcularPuntosTotales(); |
package org.swmaestro.kauth.authentication;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AccountStatusUserDetailsChecker;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsChecker;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.swmaestro.kauth.core.user.PostAuthenticationService;
import org.swmaestro.kauth.core.user.KauthUserDetailsService;
/**
* Username + Password를 사용하는 {@link AuthenticationManager}
* @author ChangEn Yea
*/
@Lazy
@Component
public class UsernamePasswordAuthenticationManager implements AuthenticationManager {
private final KauthUserDetailsService userDetailsService;
private final PasswordEncoder passwordEncoder;
private final UserDetailsChecker userDetailsChecker = new AccountStatusUserDetailsChecker();
/**
* 인스턴스를 생성한다.
* @param userDetailsService {@link KauthUserDetailsService}
* @param passwordEncoder {@link PasswordEncoder}
*/
public UsernamePasswordAuthenticationManager(KauthUserDetailsService userDetailsService,
PasswordEncoder passwordEncoder) {
this.userDetailsService = userDetailsService;
this.passwordEncoder = passwordEncoder;
}
/**
* <pre>
* {@link UserDetailsService#loadUserByUsername}를 호출해서
* {@link Authentication}의 credentials과 {@link UserDetails}의 password를 {@link PasswordEncoder#matches}를 통해
* 일치 여부를 확인한다.
* 일치 한다면 {@link Authentication} 인스턴스를 인증 처리하고, credential를 삭제하고, 권한을 설정한다.
* </pre>
* @param authentication {@link Authentication}
* @return 인증 처리 된 {@link Authentication}
* @throws AuthenticationException
*/
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
AuthenticationProvider auth = (AuthenticationProvider)authentication;
UserDetails user = userDetailsService.loadUserByUsername((String)auth.getPrincipal());
if (user == null) {
throw new UsernameNotFoundException("userDetailsService.loadUserByUsername returns null");
}
// AccountStatusException 체크
userDetailsChecker.check(user);
if (passwordEncoder.matches((String)auth.getCredentials(), user.getPassword())) {
auth.setAuthenticated(true);
| auth.eraseCredentials(); |
auth.setAuthorities(user.getAuthorities());
userDetailsService.handleSuccessfulAuthentication(user);
return auth;
} else {
throw new BadCredentialsException("Password does not matches.");
}
}
/**
* {@link BadCredentialsException}을 처리하도록
* {@link PostAuthenticationService#handleBadCredentialsException}을 호출한다.
* @param username
* @return 비밀번호 틀린 횟수. (-1 이면 틀린 횟수를 알려주지 않는다)
*/
public Integer handleBadCredentialsException(String username) {
return userDetailsService.handleBadCredentialsException(username);
}
}
| src/main/java/org/swmaestro/kauth/authentication/UsernamePasswordAuthenticationManager.java | nsce9806q-k-spring-security-8e88d3d | [
{
"filename": "src/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": 33.378777086811354
},
{
"filename": "src/test/java/org/swmaestro/kauth/showcase/UserLoginWithJwtTests.java",
"retrieved_chunk": " return new BCryptPasswordEncoder();\n }\n @Bean\n UserDetailsService userDetailsService() {\n UserDetails user = User.withDefaultPasswordEncoder()\n .username(\"user\")\n .password(\"password\")\n .roles(\"USER\")\n .build();\n UserDetails expiredUser = User.withDefaultPasswordEncoder()",
"score": 31.52540303499513
},
{
"filename": "src/test/java/org/swmaestro/kauth/showcase/UserLoginWithJwtTests.java",
"retrieved_chunk": " .roles(\"USER\")\n .disabled(true)\n .build();\n return new InMemoryUserDetailsManager(user, expiredUser, lockedUser, credentialExpiredUser, disabledUser);\n }\n }\n}",
"score": 20.72658280355417
},
{
"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": 20.114718076456434
},
{
"filename": "src/main/java/org/swmaestro/kauth/oauth/service/KOAuth2UserService.java",
"retrieved_chunk": " public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {\n OAuth2User user = super.loadUser(userRequest);\n OAuth2UserInfo oAuth2UserInfo = makeOAuth2UserInfoByProvider(userRequest, user);\n return processMemberByOAuth2UserInfo(oAuth2UserInfo);\n }\n /**\n * 로그인한 Provider 가 무엇인지 판별하고 그에 맞는 OAuth2UserInfo 를\n * processMemberByOAuth2UserInfo 에 넘겨주는 메소드\n * @param userRequest\n * @param user",
"score": 15.216319896898648
}
] | java | auth.eraseCredentials(); |
package committee.nova.flotage.datagen;
import committee.nova.flotage.init.BlockRegistry;
import committee.nova.flotage.util.BlockMember;
import committee.nova.flotage.util.WorkingMode;
import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput;
import net.fabricmc.fabric.api.datagen.v1.provider.FabricLanguageProvider;
public class FloLangProvider {
public static class English extends FabricLanguageProvider {
public English(FabricDataOutput dataOutput) {
super(dataOutput);
}
@Override
public void generateTranslations(TranslationBuilder builder) {
builder.add("itemGroup.flotage.tab", "Flotage");
builder.add("modmenu.descriptionTranslation.flotage", "Survive on the sea!");
builder.add("tip.flotage.rack.processtime", "%s second(s) processing");
builder.add("tip.flotage.rack.mode", "Current Condition: ");
builder.add("block.flotage.rack", "Rack Processing");
builder.add("config.jade.plugin_flotage.rack_blockentity", "Rack Working Mode");
builder.add("emi.category.flotage.rack", "Rack Processing");
for (WorkingMode mode : WorkingMode.values()) {
builder.add("tip.flotage.rack.mode." + mode.toString(), beautifyName(mode.toString()));
}
for (BlockMember member : BlockMember.values()) {
builder.add(BlockRegistry.get(member.raft()), beautifyName(member.raft()));
builder.add(BlockRegistry.get(member.brokenRaft()), beautifyName(member.brokenRaft()));
builder.add(BlockRegistry.get(member.fence()), beautifyName(member.fence()));
builder.add(BlockRegistry.get(member.crossedFence()), beautifyName(member.crossedFence()));
builder.add(BlockRegistry.get(member.rack()), beautifyName(member.rack()));
}
}
}
public static class Chinese extends FabricLanguageProvider {
public Chinese(FabricDataOutput dataOutput) {
super(dataOutput, "zh_cn");
}
@Override
public void generateTranslations(TranslationBuilder builder) {
builder.add("itemGroup.flotage.tab", "漂浮物");
builder.add("modmenu.descriptionTranslation.flotage", "生存于大海之上!");
builder.add("tip.flotage.rack.processtime", "需要处理 %s 秒。");
builder.add("tip.flotage.rack.mode", "当前处理条件:");
builder.add("block.flotage.rack", "置物架");
builder.add("config.jade.plugin_flotage.rack_blockentity", "置物架模式");
builder.add("emi.category.flotage.rack", "置物架");
builder.add("tip.flotage.rack.mode.unconditional", "无条件");
builder.add("tip.flotage.rack.mode.sun", "白天");
builder.add("tip.flotage.rack.mode.night", "夜晚");
builder.add("tip.flotage.rack.mode.rain", "雨天");
builder.add("tip.flotage.rack.mode.snow", "雪天");
builder.add("tip.flotage.rack.mode.rain_at", "淋雨");
builder.add("tip.flotage.rack.mode.snow_at", "淋雪");
builder.add("tip.flotage.rack.mode.smoke", "烟熏");
for (BlockMember member : BlockMember.values()) {
builder.add(BlockRegistry.get(member.raft()), member.chinese + "筏");
| builder.add(BlockRegistry.get(member.brokenRaft()), "损坏的" + member.chinese + "筏"); |
builder.add(BlockRegistry.get(member.fence()), "简易" + member.chinese + "栅栏");
builder.add(BlockRegistry.get(member.crossedFence()), member.chinese + "十字栅栏");
builder.add(BlockRegistry.get(member.rack()), member.chinese + "置物架");
}
}
}
public static String beautifyName(String name) {
String[] str1 = name.split("_");
StringBuilder str2 = new StringBuilder();
for(int i = 0 ; i < str1.length; i++) {
str1[i] = str1[i].substring(0,1).toUpperCase() + str1[i].substring(1);
if(i == str1.length-1)
str2.append(str1[i]);
else
str2.append(str1[i]).append(" ");
}
return str2.toString();
}
}
| src/main/java/committee/nova/flotage/datagen/FloLangProvider.java | Nova-Committee-Flotage-Fabric-6478e2a | [
{
"filename": "src/main/java/committee/nova/flotage/datagen/FloBlockTagProvider.java",
"retrieved_chunk": " 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": 103.9164292790478
},
{
"filename": "src/main/java/committee/nova/flotage/compat/rei/category/RackREICategory.java",
"retrieved_chunk": " Point origin = bounds.getLocation();\n final List<Widget> widgets = new ArrayList<>();\n widgets.add(Widgets.createRecipeBase(bounds));\n Rectangle bgBounds = centeredIntoRecipeBase(new Point(origin.x, origin.y), 91, 54);\n widgets.add(Widgets.createTexturedWidget(GUI_TEXTURE, new Rectangle(bgBounds.x, bgBounds.y, 91, 54), 10, 9));\n widgets.add(Widgets.createSlot(new Point(bgBounds.x + 7, bgBounds.y + 1))\n .entries(display.getInputEntries().get(0)).markInput().disableBackground());\n Arrow arrow = Widgets.createArrow(new Point(bgBounds.x + 39, bgBounds.y + 18)).animationDurationTicks(20);\n widgets.add(arrow);\n Text text = Text.translatable(\"tip.flotage.rack.mode\").append(Text.translatable(\"tip.flotage.rack.mode.\" + display.getMode().toString()));",
"score": 102.41245697064514
},
{
"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": 91.98009154620432
},
{
"filename": "src/main/java/committee/nova/flotage/impl/block/RaftBlock.java",
"retrieved_chunk": " public final BlockMember member;\n public RaftBlock(Settings settings, BlockMember member) {\n super(settings);\n this.setDefaultState(this.getDefaultState().with(WATERLOGGED, true));\n this.member = member;\n }\n @Override\n protected void appendProperties(StateManager.Builder<Block, BlockState> builder) {\n builder.add(WATERLOGGED);\n }",
"score": 91.74261341225872
},
{
"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": 88.81993196128079
}
] | java | builder.add(BlockRegistry.get(member.brokenRaft()), "损坏的" + member.chinese + "筏"); |
package com.orangomango.chess;
import javafx.scene.paint.Color;
import java.util.*;
import java.text.SimpleDateFormat;
import java.util.stream.Collectors;
public class Board{
private Piece[][] board;
private boolean blackRightCastleAllowed = true, whiteRightCastleAllowed = true;
private boolean blackLeftCastleAllowed = true, whiteLeftCastleAllowed = true;
private List<Piece> blackCaptured = new ArrayList<>();
private List<Piece> whiteCaptured = new ArrayList<>();
private int whiteExtraMaterial, blackExtraMaterial;
private List<Piece> whiteChecks = new ArrayList<>();
private List<Piece> blackChecks = new ArrayList<>();
private Piece whiteKing, blackKing;
private Color player = Color.WHITE;
private int fifty = 0, movesN = 1;
private String enPassant = null;
private boolean[] canCastle = new boolean[4];
private Map<String, Integer> states = new HashMap<>();
private List<String> moves = new ArrayList<>();
public String playerA = System.getProperty("user.name"), playerB = "BLACK";
private volatile long whiteTime, blackTime;
private long lastTime, gameTime;
private int increment;
public Board(String fen, long time, int increment){
this.board = new Piece[8][8];
setupBoard(fen);
this.gameTime = time;
this.increment = increment;
this.whiteTime = time;
this.blackTime = time;
this.lastTime = System.currentTimeMillis();
}
public void tick(){
if (this.movesN == 1){
this.lastTime = System.currentTimeMillis();
return;
}
long time = System.currentTimeMillis()-this.lastTime;
if (this.player == Color.WHITE){
this.whiteTime -= time;
} else {
this.blackTime -= time;
}
this.whiteTime = Math.max(this.whiteTime, 0);
this.blackTime = Math.max(this.blackTime, 0);
this.lastTime = System.currentTimeMillis();
}
public long getGameTime(){
return this.gameTime;
}
public int getIncrementTime(){
return this.increment;
}
private void setupBoard(String fen){
String[] data = fen.split(" ");
this.whiteKing = null;
this.blackKing = null;
int r = 0;
for (String row : data[0].split("/")){
char[] p = row.toCharArray();
int pos = 0;
for (int i = 0; i < 8; i++){
try {
int n = Integer.parseInt(Character.toString(p[pos]));
i += n-1;
} catch (NumberFormatException ex){
Piece piece = new Piece(Piece.getType(String.valueOf(p[pos])), Character.isUpperCase(p[pos]) ? Color.WHITE : Color.BLACK, i, r);
this.board[i][r] = piece;
if (piece.getType().getName() == Piece.PIECE_KING){
if (piece.getColor() == Color.WHITE){
this.whiteKing = piece;
} else {
this.blackKing = piece;
}
}
}
pos++;
}
r++;
}
this.player = data[1].equals("w") ? Color.WHITE : Color.BLACK;
char[] c = data[2].toCharArray();
for (int i = 0; i < c.length; i++){
if (i == 0 && String.valueOf(c[i]).equals("-")){
this.whiteLeftCastleAllowed = false;
this.whiteRightCastleAllowed = false;
if (c.length == 1){
this.blackLeftCastleAllowed = false;
this.blackRightCastleAllowed = false;
}
} else if (String.valueOf(c[i]).equals("-")){
this.blackLeftCastleAllowed = false;
this.blackRightCastleAllowed = false;
} else {
String d = String.valueOf(c[i]);
if (d.equals("Q")) this.whiteLeftCastleAllowed = true;
if (d.equals("K")) this.whiteRightCastleAllowed = true;
if (d.equals("q")) this.blackLeftCastleAllowed = true;
if (d.equals("k")) this.blackRightCastleAllowed = true;
}
}
this.canCastle[0] = canCastleLeft(Color.WHITE);
this.canCastle[1] = canCastleRight(Color.WHITE);
this.canCastle[2] = canCastleLeft(Color.BLACK);
this.canCastle[3] = canCastleRight(Color.BLACK);
String ep = String.valueOf(data[3]);
if (!ep.equals("-")) this.enPassant = ep;
this.fifty = Integer.parseInt(String.valueOf(data[4]));
this.movesN = Integer.parseInt(String.valueOf(data[5]));
this.states.clear();
this.states.put(getFEN().split(" ")[0], 1);
setupCaptures(Color.WHITE);
setupCaptures(Color.BLACK);
this.blackChecks.clear();
this.whiteChecks.clear();
for (Piece boardPiece : getPiecesOnBoard()){
List<String> newLegalMoves = getLegalMoves(boardPiece);
if (boardPiece.getColor() == Color.WHITE && newLegalMoves.contains(convertPosition(this.blackKing.getX(), this.blackKing.getY()))){
this.blackChecks.add(boardPiece);
} else if (boardPiece.getColor() == Color.BLACK && newLegalMoves.contains(convertPosition(this.whiteKing.getX(), this.whiteKing.getY()))){
this.whiteChecks.add(boardPiece);
}
}
if (this.whiteKing == null || this.blackKing == null) throw new IllegalStateException("Missing king");
if (getAttackers(this.player == Color.WHITE ? this.blackKing : this.whiteKing) != null) throw new IllegalStateException("King is in check");
}
private void setupCaptures(Color color){
List<Piece> pieces = getPiecesOnBoard().stream().filter(piece -> piece.getColor() == color).toList();
List<Piece> captures = color == Color.WHITE ? this.blackCaptured : this.whiteCaptured;
int pawns = (int)pieces | .stream().filter(piece -> piece.getType().getName() == Piece.PIECE_PAWN).count(); |
int rooks = (int)pieces.stream().filter(piece -> piece.getType().getName() == Piece.PIECE_ROOK).count();
int knights = (int)pieces.stream().filter(piece -> piece.getType().getName() == Piece.PIECE_KNIGHT).count();
int bishops = (int)pieces.stream().filter(piece -> piece.getType().getName() == Piece.PIECE_BISHOP).count();
int queens = (int)pieces.stream().filter(piece -> piece.getType().getName() == Piece.PIECE_QUEEN).count();
for (int i = 0; i < 8-pawns; i++){
captures.add(new Piece(Piece.Pieces.PAWN, color, -1, -1));
}
for (int i = 0; i < 2-rooks; i++){
captures.add(new Piece(Piece.Pieces.ROOK, color, -1, -1));
}
for (int i = 0; i < 2-knights; i++){
captures.add(new Piece(Piece.Pieces.KNIGHT, color, -1, -1));
}
for (int i = 0; i < 2-bishops; i++){
captures.add(new Piece(Piece.Pieces.BISHOP, color, -1, -1));
}
if (queens == 0){
captures.add(new Piece(Piece.Pieces.QUEEN, color, -1, -1));
}
for (int i = 0; i < -(2-rooks); i++){
capture(new Piece(Piece.Pieces.PAWN, color, -1, -1));
promote(color, Piece.Pieces.ROOK);
}
for (int i = 0; i < -(2-knights); i++){
capture(new Piece(Piece.Pieces.PAWN, color, -1, -1));
promote(color, Piece.Pieces.KNIGHT);
}
for (int i = 0; i < -(2-bishops); i++){
capture(new Piece(Piece.Pieces.PAWN, color, -1, -1));
promote(color, Piece.Pieces.BISHOP);
}
for (int i = 0; i < -(1-queens); i++){
capture(new Piece(Piece.Pieces.PAWN, color, -1, -1));
promote(color, Piece.Pieces.QUEEN);
}
}
public int getMovesN(){
return this.movesN;
}
public List<String> getMoves(){
return this.moves;
}
public boolean move(String pos1, String pos, String prom){
if (pos1 == null || pos == null) return false;
int[] p1 = convertNotation(pos1);
Piece piece = this.board[p1[0]][p1[1]];
if (piece == null || piece.getColor() != this.player) return false;
List<String> legalMoves = getLegalMoves(piece);
if (legalMoves.contains(pos)){
int[] p2 = convertNotation(pos);
Piece[][] backup = createBackup();
List<Piece> identical = new ArrayList<>();
for (Piece p : getPiecesOnBoard()){
if (p != piece && p.getType() == piece.getType() && p.getColor() == piece.getColor()){
if (getValidMoves(p).contains(pos)) identical.add(p);
}
}
Piece capture = this.board[p2[0]][p2[1]];
if (this.enPassant != null && pos.equals(this.enPassant)){
capture = this.board[p2[0]][p1[1]];
this.board[capture.getX()][capture.getY()] = null;
}
this.board[p1[0]][p1[1]] = null;
setPiece(piece, p2[0], p2[1]);
if (getAttackers(piece.getColor() == Color.WHITE ? this.whiteKing : this.blackKing) != null){
restoreBackup(backup);
return false;
}
if (capture != null) capture(capture);
boolean castle = false;
if (piece.getType().getName() == Piece.PIECE_KING){
if (Math.abs(p2[0]-p1[0]) == 2){
if (p2[0] == 6){
castleRight(piece.getColor());
castle = true;
} else if (p2[0] == 2){
castleLeft(piece.getColor());
castle = true;
}
}
if (piece.getColor() == Color.WHITE){
this.whiteRightCastleAllowed = false;
this.whiteLeftCastleAllowed = false;
} else {
this.blackRightCastleAllowed = false;
this.blackLeftCastleAllowed = false;
}
}
if (piece.getType().getName() == Piece.PIECE_ROOK){
if (piece.getColor() == Color.WHITE){
if (this.whiteRightCastleAllowed && p1[0] == 7){
this.whiteRightCastleAllowed = false;
} else if (this.whiteLeftCastleAllowed && p1[0] == 0){
this.whiteLeftCastleAllowed = false;
}
} else {
if (this.blackRightCastleAllowed && p1[0] == 7){
this.blackRightCastleAllowed = false;
} else if (this.blackLeftCastleAllowed && p1[0] == 0){
this.blackLeftCastleAllowed = false;
}
}
}
if (piece.getType().getName() == Piece.PIECE_PAWN){
this.fifty = 0;
if ((piece.getColor() == Color.WHITE && piece.getY() == 0) || (piece.getColor() == Color.BLACK && piece.getY() == 7)){
Piece.Pieces promotion = Piece.getType(prom);
this.board[piece.getX()][piece.getY()] = new Piece(promotion, piece.getColor(), piece.getX(), piece.getY());
capture(piece);
promote(piece.getColor(), promotion);
}
if (Math.abs(p2[1]-p1[1]) == 2){
this.enPassant = convertPosition(piece.getX(), piece.getColor() == Color.WHITE ? piece.getY()+1 : piece.getY()-1);
} else {
this.enPassant = null;
}
} else {
this.fifty++;
this.enPassant = null;
}
this.canCastle[0] = canCastleLeft(Color.WHITE);
this.canCastle[1] = canCastleRight(Color.WHITE);
this.canCastle[2] = canCastleLeft(Color.BLACK);
this.canCastle[3] = canCastleRight(Color.BLACK);
this.blackChecks.clear();
this.whiteChecks.clear();
boolean check = false;
for (Piece boardPiece : getPiecesOnBoard()){
List<String> newLegalMoves = getLegalMoves(boardPiece);
if (boardPiece.getColor() == Color.WHITE && newLegalMoves.contains(convertPosition(this.blackKing.getX(), this.blackKing.getY()))){
this.blackChecks.add(boardPiece);
check = true;
} else if (boardPiece.getColor() == Color.BLACK && newLegalMoves.contains(convertPosition(this.whiteKing.getX(), this.whiteKing.getY()))){
this.whiteChecks.add(boardPiece);
check = true;
}
}
if (check){
MainApplication.playSound(MainApplication.CHECK_SOUND);
}
if (this.movesN > 1){
if (this.player == Color.WHITE){
this.whiteTime += this.increment*1000;
} else {
this.blackTime += this.increment*1000;
}
}
if (this.player == Color.BLACK) this.movesN++;
this.player = this.player == Color.WHITE ? Color.BLACK : Color.WHITE;
String fen = getFEN().split(" ")[0];
this.states.put(fen, this.states.getOrDefault(fen, 0)+1);
this.moves.add(moveToString(piece, pos1, pos, check, capture != null, prom, castle, identical));
if (capture != null){
MainApplication.playSound(MainApplication.CAPTURE_SOUND);
} else if (castle){
MainApplication.playSound(MainApplication.CASTLE_SOUND);
} else {
MainApplication.playSound(MainApplication.MOVE_SOUND);
}
return true;
}
return false;
}
private String moveToString(Piece piece, String start, String pos, boolean check, boolean capture, String prom, boolean castle, List<Piece> identical){
int[] coord = convertNotation(start);
String output = "";
if (piece.getType().getName() == Piece.PIECE_PAWN){
if (capture){
output = String.valueOf(start.charAt(0))+"x"+pos;
} else {
output = pos;
}
if (prom != null) output += "="+prom.toUpperCase();
} else if (castle){
output = piece.getX() == 2 ? "O-O-O" : "O-O";
} else {
String extra = "";
if (identical.size() >= 2){
extra = start;
} else if (identical.size() == 1){
Piece other = identical.get(0);
if (coord[0] != other.getX()){
extra = String.valueOf(start.charAt(0));
} else if (coord[1] != other.getY()){
extra = String.valueOf(start.charAt(1));
}
}
output = piece.getType().getName().toUpperCase()+extra+(capture ? "x" : "")+pos;
}
if (isCheckMate(piece.getColor() == Color.WHITE ? Color.BLACK : Color.WHITE)){
output += "#";
} else if (check){
output += "+";
}
return output;
}
public int getTime(Color color){
return color == Color.WHITE ? (int)this.whiteTime : (int)this.blackTime;
}
public void castleRight(Color color){
int ypos = color == Color.WHITE ? 7 : 0;
Piece king = color == Color.WHITE ? this.whiteKing : this.blackKing;
Piece rook = this.board[7][ypos];
if (canCastleRight(color)){
this.board[rook.getX()][rook.getY()] = null;
setPiece(rook, king.getX()-1, king.getY());
}
}
public void castleLeft(Color color){
int ypos = color == Color.WHITE ? 7 : 0;
Piece king = color == Color.WHITE ? this.whiteKing : this.blackKing;
Piece rook = this.board[0][ypos];
if (canCastleLeft(color)){
this.board[rook.getX()][rook.getY()] = null;
setPiece(rook, king.getX()+1, king.getY());
}
}
private boolean canCastleRight(Color color){
boolean moved = color == Color.WHITE ? this.whiteRightCastleAllowed : this.blackRightCastleAllowed;
return moved && getAttackers(color == Color.WHITE ? this.whiteKing : this.blackKing) == null && canCastle(new int[]{5, 6}, new int[]{5, 6}, color);
}
private boolean canCastleLeft(Color color){
boolean moved = color == Color.WHITE ? this.whiteLeftCastleAllowed : this.blackLeftCastleAllowed;
return moved && getAttackers(color == Color.WHITE ? this.whiteKing : this.blackKing) == null && canCastle(new int[]{2, 3}, new int[]{1, 2, 3}, color);
}
private boolean canCastle(int[] xpos, int[] checkXpos, Color color){
int ypos = color == Color.WHITE ? 7 : 0;
Piece king = color == Color.WHITE ? this.whiteKing : this.blackKing;
for (int i = 0; i < xpos.length; i++){
if (this.board[xpos[i]][ypos] != null && this.board[xpos[i]][ypos].getType().getName() != Piece.PIECE_KING) return false;
}
Piece[][] backup = createBackup();
for (int i = 0; i < checkXpos.length; i++){
this.board[king.getX()][king.getY()] = null;
setPiece(king, checkXpos[i], ypos);
if (getAttackers(king) != null){
restoreBackup(backup);
return false;
}
restoreBackup(backup);
}
return true;
}
public List<String> getValidMoves(Piece piece){
List<String> legalMoves = getLegalMoves(piece);
List<String> validMoves = new ArrayList<>();
if (piece.getColor() != this.player) return validMoves;
Piece[][] backup = createBackup();
for (String move : legalMoves){
int[] pos = convertNotation(move);
int oldY = piece.getY();
this.board[piece.getX()][oldY] = null;
setPiece(piece, pos[0], pos[1]);
if (move.equals(this.enPassant)){
int x = convertNotation(this.enPassant)[0];
this.board[x][oldY] = null;
}
if (getAttackers(piece.getColor() == Color.WHITE ? this.whiteKing : this.blackKing) == null){
restoreBackup(backup);
validMoves.add(move);
} else {
restoreBackup(backup);
}
}
return validMoves;
}
private List<String> getLegalMoves(Piece piece){
List<String> result = new ArrayList<>();
int extraMove = 0;
if (piece.getType().getName() == Piece.PIECE_PAWN){
if ((piece.getColor() == Color.WHITE && piece.getY() == 6) || (piece.getColor() == Color.BLACK && piece.getY() == 1)){
extraMove = 1;
}
int factor = piece.getColor() == Color.WHITE ? -1 : 1;
String not1 = convertPosition(piece.getX()-1, piece.getY()+factor);
String not2 = convertPosition(piece.getX()+1, piece.getY()+factor);
if (not1 != null && this.board[piece.getX()-1][piece.getY()+factor] != null && this.board[piece.getX()-1][piece.getY()+factor].getColor() != piece.getColor()) result.add(not1);
if (not2 != null && this.board[piece.getX()+1][piece.getY()+factor] != null && this.board[piece.getX()+1][piece.getY()+factor].getColor() != piece.getColor()) result.add(not2);
// En passant
if (this.enPassant != null && piece.getY() == convertNotation(this.enPassant)[1]+(piece.getColor() == Color.WHITE ? 1 : -1) && Math.abs(piece.getX()-convertNotation(this.enPassant)[0]) == 1){
result.add(this.enPassant);
}
}
if (piece.getType().getName() == Piece.PIECE_KING){
if ((piece.getColor() == Color.WHITE && this.canCastle[0]) || (piece.getColor() == Color.BLACK && this.canCastle[2])){
result.add(convertPosition(piece.getX()-2, piece.getY()));
}
if ((piece.getColor() == Color.WHITE && this.canCastle[1]) || (piece.getColor() == Color.BLACK && this.canCastle[3])){
result.add(convertPosition(piece.getX()+2, piece.getY()));
}
}
int[] dir = piece.getType().getDirections();
for (int i = 0; i < dir.length; i++){
int[][] comb = null;
if (dir[i] == Piece.MOVE_DIAGONAL){
comb = new int[][]{{1, -1}, {1, 1}, {-1, 1}, {-1, -1}};
} else if (dir[i] == Piece.MOVE_HORIZONTAL){
comb = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
} else if (dir[i] == Piece.MOVE_KNIGHT){
comb = new int[][]{{-2, -1}, {-1, -2}, {2, -1}, {1, -2}, {1, 2}, {2, 1}, {-1, 2}, {-2, 1}};
}
if (comb != null){
for (int c = 0; c < comb.length; c++){
for (int j = 1; j <= piece.getType().getAmount()+extraMove; j++){
int x = piece.getX()+comb[c][0]*j;
int y = piece.getY()+comb[c][1]*j;
if (piece.getType().getName() == Piece.PIECE_PAWN){
if (x != piece.getX() || (piece.getColor() == Color.WHITE && y > piece.getY()) || (piece.getColor() == Color.BLACK && y < piece.getY())){
continue;
}
}
Piece captured = getPieceAt(x, y);
String not = convertPosition(x, y);
if (not != null && (captured == null || captured.getColor() != piece.getColor())){
if (captured == null || piece.getType().getName() != Piece.PIECE_PAWN || captured.getX() != piece.getX()){
result.add(not);
}
}
if (captured != null){
break;
}
}
}
}
}
return result;
}
private Piece getPieceAt(int x, int y){
if (x >= 0 && y >= 0 && x < 8 && y < 8){
return this.board[x][y];
} else {
return null;
}
}
private void capture(Piece piece){
if (piece.getColor() == Color.WHITE){
this.blackCaptured.add(piece);
} else {
this.whiteCaptured.add(piece);
}
this.fifty = 0;
}
private void promote(Color color, Piece.Pieces type){
List<Piece> list = color == Color.BLACK ? this.whiteCaptured : this.blackCaptured;
Iterator<Piece> iterator = list.iterator();
boolean removed = false;
while (iterator.hasNext()){
Piece piece = iterator.next();
if (piece.getType() == type){
iterator.remove();
removed = true;
break;
}
}
if (!removed){
if (color == Color.WHITE){
this.whiteExtraMaterial += type.getValue();
} else {
this.blackExtraMaterial += type.getValue();
}
}
}
private List<Piece> getAttackers(Piece piece){
List<Piece> pieces = getPiecesOnBoard();
List<Piece> result = new ArrayList<>();
String pos = convertPosition(piece.getX(), piece.getY());
for (Piece boardPiece : pieces){
if (boardPiece.getColor() != piece.getColor() && getLegalMoves(boardPiece).contains(pos)){
result.add(boardPiece);
}
}
return result.size() == 0 ? null : result;
}
private boolean canKingMove(Color color){
Piece king = color == Color.WHITE ? this.whiteKing : this.blackKing;
Piece[][] backup = createBackup();
// Check if king has any legal moves
for (int x = king.getX()-1; x < king.getX()+2; x++){
for (int y = king.getY()-1; y < king.getY()+2; y++){
if (x >= 0 && y >= 0 && x < 8 && y < 8){
Piece piece = this.board[x][y];
if (piece == null || piece.getColor() != king.getColor()){
this.board[king.getX()][king.getY()] = null;
setPiece(king, x, y);
if (getAttackers(king) == null){
restoreBackup(backup);
return true;
} else {
restoreBackup(backup);
}
}
}
}
}
// If there is a single check, check if the piece can be captured or the ckeck can be blocked
List<Piece> checks = king.getColor() == Color.WHITE ? this.whiteChecks : this.blackChecks;
if (checks.size() == 1){
List<Piece> canCapture = getAttackers(checks.get(0));
if (canCapture != null){
for (Piece piece : canCapture){
this.board[piece.getX()][piece.getY()] = null;
setPiece(piece, checks.get(0).getX(), checks.get(0).getY());
if (getAttackers(king) == null){
restoreBackup(backup);
return true;
} else {
restoreBackup(backup);
}
}
} else {
List<String> legalMoves = getLegalMoves(checks.get(0));
List<Piece> pieces = getPiecesOnBoard();
for (Piece piece : pieces){
if (piece.getColor() == checks.get(0).getColor()) continue;
Set<String> intersection = getLegalMoves(piece).stream().distinct().filter(legalMoves::contains).collect(Collectors.toSet());
List<String> allowed = new ArrayList<>();
for (String move : intersection){
int[] pos = convertNotation(move);
this.board[piece.getX()][piece.getY()] = null;
setPiece(piece, pos[0], pos[1]);
if (getAttackers(piece.getColor() == Color.WHITE ? this.whiteKing : this.blackKing) == null){
restoreBackup(backup);
allowed.add(move);
} else {
restoreBackup(backup);
}
}
if (allowed.size() > 0){
return true;
}
}
}
}
return false;
}
private Piece[][] createBackup(){
Piece[][] backup = new Piece[8][8];
for (int i = 0; i < 8; i++){
for (int j = 0; j < 8; j++){
backup[i][j] = this.board[i][j];
}
}
return backup;
}
private void restoreBackup(Piece[][] backup){
for (int i = 0; i < 8; i++){
for (int j = 0; j < 8; j++){
Piece piece = backup[i][j];
if (piece == null){
this.board[i][j] = null;
} else {
setPiece(piece, i, j);
}
}
}
}
private List<Piece> getPiecesOnBoard(){
List<Piece> pieces = new ArrayList<>();
for (int i = 0; i < 8; i++){
for (int j = 0; j < 8; j++){
if (this.board[i][j] != null) pieces.add(this.board[i][j]);
}
}
return pieces;
}
private void setPiece(Piece piece, int x, int y){
this.board[x][y] = piece;
piece.setPos(x, y);
}
public static int[] convertNotation(String pos){
char[] c = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'};
char[] data = pos.toCharArray();
int x = -1;
for (int i = 0; i < 8; i++){
if (c[i] == data[0]){
x = i;
break;
}
}
int y = 8-Integer.parseInt(String.valueOf(data[1]));
if (x < 0 || y < 0 || y > 7){
return null;
} else {
return new int[]{x, y};
}
}
public static String convertPosition(int x, int y){
char[] c = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'};
if (x < 0 || y < 0 || x > 7 || y > 7){
return null;
} else {
return c[x]+Integer.toString(8-y);
}
}
public List<Piece> getCheckingPieces(Color color){
if (color == Color.WHITE){
return this.whiteChecks;
} else {
return this.blackChecks;
}
}
public Piece[][] getBoard(){
return this.board;
}
public String getPGN(){
StringBuilder builder = new StringBuilder();
SimpleDateFormat format = new SimpleDateFormat("YYYY/MM/dd");
Date date = new Date();
builder.append("[Event \""+String.format("%s vs %s", this.playerA, this.playerB)+"\"]\n");
builder.append("[Site \"com.orangomango.chess\"]\n");
builder.append("[Date \""+format.format(date)+"\"]\n");
builder.append("[Round \"1\"]\n");
builder.append("[White \""+this.playerA+"\"]\n");
builder.append("[Black \""+this.playerB+"\"]\n");
String result = "*";
if (isDraw()){
result = "½-½";
} else if (isCheckMate(Color.WHITE)){
result = "0-1";
} else if (isCheckMate(Color.BLACK)){
result = "1-0";
}
builder.append("[Result \""+result+"\"]\n\n");
for (int i = 0; i < this.moves.size(); i++){
if (i % 2 == 0) builder.append((i/2+1)+". ");
builder.append(this.moves.get(i)+" ");
}
builder.append(result);
return builder.toString();
}
public String getFEN(){
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 8; i++){
int empty = 0;
for (int j = 0; j < 8; j++){
Piece piece = this.board[j][i];
if (piece == null){
empty++;
} else {
if (empty > 0){
builder.append(empty);
empty = 0;
}
builder.append(piece.getColor() == Color.WHITE ? piece.getType().getName().toUpperCase() : piece.getType().getName().toLowerCase());
}
}
if (empty > 0) builder.append(empty);
if (i < 7) builder.append("/");
}
builder.append(this.player == Color.WHITE ? " w " : " b ");
boolean no = false;
if (!this.whiteLeftCastleAllowed && !this.whiteRightCastleAllowed){
builder.append("-");
no = true;
} else {
if (this.whiteRightCastleAllowed) builder.append("K");
if (this.whiteLeftCastleAllowed) builder.append("Q");
}
if (!this.blackLeftCastleAllowed && !this.blackRightCastleAllowed){
if (!no) builder.append("-");
} else {
if (this.blackRightCastleAllowed) builder.append("k");
if (this.blackLeftCastleAllowed) builder.append("q");
}
builder.append(" ");
builder.append(String.format("%s %d %d", this.enPassant == null ? "-" : this.enPassant, this.fifty, this.movesN));
return builder.toString();
}
private boolean isCheckMate(Color color){
Piece king = color == Color.WHITE ? this.whiteKing : this.blackKing;
return getAttackers(king) != null && !canKingMove(color);
}
private boolean isDraw(){
if (this.fifty >= 50) return true;
List<Piece> pieces = getPiecesOnBoard();
int whitePieces = pieces.stream().filter(piece -> piece.getColor() == Color.WHITE).mapToInt(p -> p.getType().getValue()).sum();
int blackPieces = pieces.stream().filter(piece -> piece.getColor() == Color.BLACK).mapToInt(p -> p.getType().getValue()).sum();
List<String> whiteLegalMoves = new ArrayList<>();
List<String> blackLegalMoves = new ArrayList<>();
for (Piece piece : pieces){
if (piece.getColor() == Color.WHITE){
whiteLegalMoves.addAll(getValidMoves(piece));
} else {
blackLegalMoves.addAll(getValidMoves(piece));
}
}
boolean whiteDraw = whitePieces == 0 || (whitePieces == 3 && pieces.stream().filter(piece -> piece.getColor() == Color.WHITE).count() == 2);
boolean blackDraw = blackPieces == 0 || (blackPieces == 3 && pieces.stream().filter(piece -> piece.getColor() == Color.BLACK).count() == 2);
if (whiteDraw && blackDraw) return true;
if ((getAttackers(this.blackKing) == null && !canKingMove(Color.BLACK) && blackLegalMoves.size() == 0 && this.player == Color.BLACK) || (getAttackers(this.whiteKing) == null && !canKingMove(Color.WHITE)) && whiteLegalMoves.size() == 0 && this.player == Color.WHITE){
return true;
}
if (this.states.values().contains(3)) return true;
return false;
}
public String getBoardInfo(){
int whiteSum = getMaterial(Color.WHITE);
int blackSum = getMaterial(Color.BLACK);
return String.format("B:%d W:%d - BK:%s WK:%s - BCK:%s WCK:%s\nChecks: %s %s\n",
blackSum, whiteSum, getAttackers(this.blackKing) != null, getAttackers(this.whiteKing) != null,
isCheckMate(Color.BLACK), isCheckMate(Color.WHITE),
this.blackChecks, this.whiteChecks);
}
public List<Piece> getMaterialList(Color color){
List<Piece> list = new ArrayList<>(color == Color.WHITE ? this.whiteCaptured : this.blackCaptured);
list.sort((p1, p2) -> Integer.compare(p1.getType().getValue(), p2.getType().getValue()));
return list;
}
public int getMaterial(Color color){
return getMaterialList(color).stream().mapToInt(p -> p.getType().getValue()).sum()+(color == Color.WHITE ? this.whiteExtraMaterial : this.blackExtraMaterial);
}
public Color getPlayer(){
return this.player;
}
public boolean isGameFinished(){
return isCheckMate(Color.WHITE) || isCheckMate(Color.BLACK) || isDraw() || this.whiteTime <= 0 || this.blackTime <= 0;
}
@Override
public String toString(){
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 8; i++){ // y
for (int j = 0; j < 8; j++){ // x
builder.append(this.board[j][i]+" ");
}
builder.append("\n");
}
builder.append(getBoardInfo());
return builder.toString();
}
}
| src/main/java/com/orangomango/chess/Board.java | OrangoMango-Chess-c4bd8f5 | [
{
"filename": "src/main/java/com/orangomango/chess/MainApplication.java",
"retrieved_chunk": "\t\t\t\t}\n\t\t\t\tif (piece != null){\n\t\t\t\t\tif (piece.getType().getName() == Piece.PIECE_KING){\n\t\t\t\t\t\tif ((piece.getColor() == Color.WHITE && this.board.getCheckingPieces(Color.WHITE).size() > 0) || (piece.getColor() == Color.BLACK && this.board.getCheckingPieces(Color.BLACK).size() > 0)){\n\t\t\t\t\t\t\tgc.setFill(Color.BLUE);\n\t\t\t\t\t\t\tgc.fillOval(pos.getX()*SQUARE_SIZE, pos.getY()*SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (piece != this.draggingPiece) gc.drawImage(piece.getImage(), pos.getX()*SQUARE_SIZE, pos.getY()*SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE);\n\t\t\t\t}",
"score": 50.99505245066252
},
{
"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": 49.70028131590759
},
{
"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": 49.51181795900068
},
{
"filename": "src/main/java/com/orangomango/chess/MainApplication.java",
"retrieved_chunk": "\t\tgc.save();\n\t\tfor (int i = 0; i < white.size(); i++){\n\t\t\tPiece piece = white.get(i);\n\t\t\tPiece prev = i == 0 ? null : white.get(i-1);\n\t\t\tif (i > 0) gc.translate(prev != null && prev.getType().getValue() == piece.getType().getValue() ? SQUARE_SIZE/4.0 : SQUARE_SIZE/2.0+SQUARE_SIZE/10.0, 0);\n\t\t\tgc.drawImage(piece.getImage(), WIDTH*0.05, this.viewPoint == Color.WHITE ? bd : wd, SQUARE_SIZE/2.0, SQUARE_SIZE/2.0);\n\t\t}\n\t\tgc.restore();\n\t\tfor (Map.Entry<String, List<String>> entry : this.hold.entrySet()){\n\t\t\tif (entry.getKey() == null || entry.getValue() == null) continue;",
"score": 41.741777900673846
},
{
"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": 39.46968094326166
}
] | java | .stream().filter(piece -> piece.getType().getName() == Piece.PIECE_PAWN).count(); |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.