Skip to content

Commit

Permalink
Migrate to the var keyword
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexProgrammerDE committed Oct 2, 2023
1 parent 1ea7952 commit b80aa36
Show file tree
Hide file tree
Showing 109 changed files with 915 additions and 972 deletions.
61 changes: 30 additions & 31 deletions src/main/java/net/pistonmaster/serverwrecker/AttackManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@
import org.slf4j.LoggerFactory;

import javax.inject.Inject;
import java.net.InetSocketAddress;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
Expand All @@ -74,28 +73,28 @@ public CompletableFuture<Void> start(SettingsHolder settingsHolder) {
throw new IllegalStateException("Attack is already running");
}

AccountList accountListSettings = settingsHolder.get(AccountList.class);
List<MinecraftAccount> accounts = new ArrayList<>(accountListSettings.accounts()
var accountListSettings = settingsHolder.get(AccountList.class);
var accounts = new ArrayList<>(accountListSettings.accounts()
.stream().filter(MinecraftAccount::enabled).toList());

ProxyList proxyListSettings = settingsHolder.get(ProxyList.class);
List<SWProxy> proxies = new ArrayList<>(proxyListSettings.proxies()
var proxyListSettings = settingsHolder.get(ProxyList.class);
var proxies = new ArrayList<>(proxyListSettings.proxies()
.stream().filter(SWProxy::enabled).toList());

BotSettings botSettings = settingsHolder.get(BotSettings.class);
AccountSettings accountSettings = settingsHolder.get(AccountSettings.class);
ProxySettings proxySettings = settingsHolder.get(ProxySettings.class);
var botSettings = settingsHolder.get(BotSettings.class);
var accountSettings = settingsHolder.get(AccountSettings.class);
var proxySettings = settingsHolder.get(ProxySettings.class);

serverWrecker.setupLogging(settingsHolder.get(DevSettings.class));

this.attackState = AttackState.RUNNING;

logger.info("Preparing bot attack at {}", botSettings.host());

int botAmount = botSettings.amount(); // How many bots to connect
int botsPerProxy = proxySettings.botsPerProxy(); // How many bots per proxy are allowed
int availableProxiesCount = proxies.size(); // How many proxies are available?
int maxBots = botsPerProxy > 0 ? botsPerProxy * availableProxiesCount : botAmount; // How many bots can be used at max
var botAmount = botSettings.amount(); // How many bots to connect
var botsPerProxy = proxySettings.botsPerProxy(); // How many bots per proxy are allowed
var availableProxiesCount = proxies.size(); // How many proxies are available?
var maxBots = botsPerProxy > 0 ? botsPerProxy * availableProxiesCount : botAmount; // How many bots can be used at max

if (botAmount > maxBots) {
logger.warn("You have specified {} bots, but only {} are available.", botAmount, maxBots);
Expand All @@ -104,7 +103,7 @@ public CompletableFuture<Void> start(SettingsHolder settingsHolder) {
botAmount = maxBots;
}

int availableAccounts = accounts.size();
var availableAccounts = accounts.size();

if (availableAccounts > 0 && botAmount > availableAccounts) {
logger.warn("You have specified {} bots, but only {} accounts are available.", botAmount, availableAccounts);
Expand All @@ -116,27 +115,27 @@ public CompletableFuture<Void> start(SettingsHolder settingsHolder) {
Collections.shuffle(accounts);
}

Object2IntMap<SWProxy> proxyUseMap = new Object2IntOpenHashMap<>();
for (SWProxy proxy : proxies) {
var proxyUseMap = new Object2IntOpenHashMap<SWProxy>();
for (var proxy : proxies) {
proxyUseMap.put(proxy, 0);
}

// Prepare an event loop group with enough threads for the attack
int threads = botAmount;
var threads = botAmount;
threads *= 2; // We need a monitor thread for each bot

EventLoopGroup attackEventLoopGroup = SWNettyHelper.createEventLoopGroup(threads, String.format("Attack-%d", id));
var attackEventLoopGroup = SWNettyHelper.createEventLoopGroup(threads, String.format("Attack-%d", id));

boolean isBedrock = SWConstants.isBedrock(botSettings.protocolVersion());
InetSocketAddress targetAddress = ResolveUtil.resolveAddress(isBedrock, settingsHolder, attackEventLoopGroup);
var isBedrock = SWConstants.isBedrock(botSettings.protocolVersion());
var targetAddress = ResolveUtil.resolveAddress(isBedrock, settingsHolder, attackEventLoopGroup);

Queue<BotConnectionFactory> factories = new ArrayBlockingQueue<>(botAmount);
for (int botId = 1; botId <= botAmount; botId++) {
SWProxy proxyData = getProxy(botsPerProxy, proxyUseMap).orElse(null);
MinecraftAccount minecraftAccount = getAccount(accountSettings, accounts, botId);
var factories = new ArrayBlockingQueue<BotConnectionFactory>(botAmount);
for (var botId = 1; botId <= botAmount; botId++) {
var proxyData = getProxy(botsPerProxy, proxyUseMap).orElse(null);
var minecraftAccount = getAccount(accountSettings, accounts, botId);

// AuthData will be used internally instead of the MCProtocol data
MinecraftProtocol protocol = new MinecraftProtocol(EMPTY_GAME_PROFILE, null);
var protocol = new MinecraftProtocol(EMPTY_GAME_PROFILE, null);

// Make sure this options is set to false, otherwise it will cause issues with ViaVersion
protocol.setUseDefaultListeners(false);
Expand All @@ -162,11 +161,11 @@ public CompletableFuture<Void> start(SettingsHolder settingsHolder) {
eventBus.post(new AttackStartEvent(this));

// Used for concurrent bot connecting
ExecutorService connectService = Executors.newFixedThreadPool(botSettings.concurrentConnects());
var connectService = Executors.newFixedThreadPool(botSettings.concurrentConnects());

return CompletableFuture.runAsync(() -> {
while (!factories.isEmpty()) {
BotConnectionFactory factory = factories.poll();
var factory = factories.poll();
if (factory == null) {
break;
}
Expand All @@ -180,7 +179,7 @@ public CompletableFuture<Void> start(SettingsHolder settingsHolder) {
TimeUtil.waitCondition(attackState::isPaused);

logger.debug("Connecting bot {}", factory.minecraftAccount().username());
BotConnection botConnection = factory.prepareConnection();
var botConnection = factory.prepareConnection();
botConnections.add(botConnection);

try {
Expand Down Expand Up @@ -233,16 +232,16 @@ public CompletableFuture<Void> stop() {
private void stopInternal() {
logger.info("Disconnecting bots");
do {
Set<EventLoopGroup> eventLoopGroups = new HashSet<>();
var eventLoopGroups = new HashSet<EventLoopGroup>();
var disconnectFuture = new ArrayList<CompletableFuture<Void>>();
for (BotConnection botConnection : List.copyOf(botConnections)) {
for (var botConnection : List.copyOf(botConnections)) {
disconnectFuture.add(botConnection.gracefulDisconnect());
eventLoopGroups.add(botConnection.session().getEventLoopGroup());
botConnections.remove(botConnection);
}

logger.info("Waiting for all bots to fully disconnect");
for (CompletableFuture<Void> future : disconnectFuture) {
for (var future : disconnectFuture) {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
Expand All @@ -251,7 +250,7 @@ private void stopInternal() {
}

logger.info("Shutting down attack event loop groups");
for (EventLoopGroup eventLoopGroup : eventLoopGroups) {
for (var eventLoopGroup : eventLoopGroups) {
try {
eventLoopGroup.shutdownGracefully().get();
} catch (InterruptedException | ExecutionException e) {
Expand Down
18 changes: 9 additions & 9 deletions src/main/java/net/pistonmaster/serverwrecker/SWConstants.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,14 @@ private SWConstants() {
}

public static List<ProtocolVersion> getVersionsSorted() {
List<ProtocolVersion> normalVersions = new ArrayList<>();
List<ProtocolVersion> legacyVersions = new ArrayList<>();
for (ProtocolVersion version : ProtocolVersion.getProtocols()) {
var normalVersions = new ArrayList<ProtocolVersion>();
var legacyVersions = new ArrayList<ProtocolVersion>();
for (var version : ProtocolVersion.getProtocols()) {
if (version == ProtocolVersion.unknown) {
continue; // Exclude unknown versions
}

int versionId = version.getVersion();
var versionId = version.getVersion();
if (versionId > CURRENT_PROTOCOL_VERSION.getVersion()) {
continue; // Exclude in-development versions
}
Expand All @@ -61,14 +61,14 @@ public static List<ProtocolVersion> getVersionsSorted() {
normalVersions.sort(Comparator.comparingInt(ProtocolVersion::getVersion));

legacyVersions.sort((o1, o2) -> {
int index1 = LegacyProtocolVersion.PROTOCOLS.indexOf(o1);
int index2 = LegacyProtocolVersion.PROTOCOLS.indexOf(o2);
var index1 = LegacyProtocolVersion.PROTOCOLS.indexOf(o1);
var index2 = LegacyProtocolVersion.PROTOCOLS.indexOf(o2);

return Integer.compare(index1, index2);
});

// Sort special case
int index = legacyVersions.indexOf(LegacyProtocolVersion.c0_28toc0_30);
var index = legacyVersions.indexOf(LegacyProtocolVersion.c0_28toc0_30);
legacyVersions.remove(LegacyProtocolVersion.c0_30cpe);
legacyVersions.add(index + 1, LegacyProtocolVersion.c0_30cpe);

Expand All @@ -77,9 +77,9 @@ public static List<ProtocolVersion> getVersionsSorted() {

@SafeVarargs
private static <T> List<T> mergeLists(List<T>... versions) {
List<T> result = new ArrayList<>();
var result = new ArrayList<T>();

for (List<T> version : versions) {
for (var version : versions) {
result.addAll(version);
}

Expand Down
38 changes: 17 additions & 21 deletions src/main/java/net/pistonmaster/serverwrecker/ServerWrecker.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
import net.kyori.adventure.text.TranslatableComponent;
import net.kyori.adventure.text.flattener.ComponentFlattener;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import net.pistonmaster.serverwrecker.api.Addon;
import net.pistonmaster.serverwrecker.api.ServerWreckerAPI;
import net.pistonmaster.serverwrecker.api.event.attack.AttackInitEvent;
import net.pistonmaster.serverwrecker.auth.AccountList;
Expand Down Expand Up @@ -73,13 +72,10 @@
import org.slf4j.LoggerFactory;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.NoSuchAlgorithmException;
Expand Down Expand Up @@ -143,7 +139,7 @@ public ServerWrecker(OperationMode operationMode, String host, int port) {
// Init API
ServerWreckerAPI.setServerWrecker(this);

SWLogAppender logAppender = new SWLogAppender();
var logAppender = new SWLogAppender();
logAppender.start();
injector.register(SWLogAppender.class, logAppender);
((org.apache.logging.log4j.core.Logger) LogManager.getRootLogger()).addAppender(logAppender);
Expand All @@ -155,7 +151,7 @@ public ServerWrecker(OperationMode operationMode, String host, int port) {
throw new RuntimeException(e);
}

SecretKey jwtKey = keyGen.generateKey();
var jwtKey = keyGen.generateKey();

rpcServer = new RPCServer(port, injector, jwtKey);
try {
Expand All @@ -169,12 +165,12 @@ public ServerWrecker(OperationMode operationMode, String host, int port) {

LOGGER.info("Starting ServerWrecker v{}...", BuildData.VERSION);

String jwt = Jwts.builder()
var jwt = Jwts.builder()
.setSubject("admin")
.signWith(jwtKey, SignatureAlgorithm.HS256)
.compact();

RPCClient rpcClient = new RPCClient(host, port, jwt);
var rpcClient = new RPCClient(host, port, jwt);
injector.register(RPCClient.class, rpcClient);

terminalConsole = injector.getSingleton(SWTerminalConsole.class);
Expand All @@ -194,8 +190,8 @@ public ServerWrecker(OperationMode operationMode, String host, int port) {
new MinecraftPacketSerializer<>(SWClientboundStatusResponsePacket::new)));

// Init via
Path viaPath = DATA_FOLDER.resolve("ViaVersion");
SWViaPlatform platform = new SWViaPlatform(viaPath);
var viaPath = DATA_FOLDER.resolve("ViaVersion");
var platform = new SWViaPlatform(viaPath);

Via.init(ViaManagerImpl.builder()
.platform(platform)
Expand All @@ -218,19 +214,19 @@ public ServerWrecker(OperationMode operationMode, String host, int port) {
new SWViaBedrock(DATA_FOLDER.resolve("ViaBedrock")).init();
});

ViaManagerImpl manager = (ViaManagerImpl) Via.getManager();
var manager = (ViaManagerImpl) Via.getManager();
manager.init();

manager.getPlatform().getConf().setCheckForUpdates(false);

manager.onServerLoaded();

SettingsPanel settingsPanel = injector.getIfAvailable(SettingsPanel.class);
var settingsPanel = injector.getIfAvailable(SettingsPanel.class);
if (settingsPanel != null) {
settingsPanel.registerVersions();
}

for (Addon addon : ServerWreckerAPI.getAddons()) {
for (var addon : ServerWreckerAPI.getAddons()) {
addon.onEnable(this);
}

Expand All @@ -244,8 +240,8 @@ public ServerWrecker(OperationMode operationMode, String host, int port) {

private boolean checkForUpdates() {
try {
URL url = URI.create("https://api.github.com/repos/AlexProgrammerDE/ServerWrecker/releases/latest").toURL();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
var url = URI.create("https://api.github.com/repos/AlexProgrammerDE/ServerWrecker/releases/latest").toURL();
var connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("User-Agent", "ServerWrecker");
connection.setConnectTimeout(5000);
Expand All @@ -257,11 +253,11 @@ private boolean checkForUpdates() {
}

JsonObject response;
try (InputStream stream = connection.getInputStream()) {
try (var stream = connection.getInputStream()) {
response = gson.fromJson(new InputStreamReader(stream), JsonObject.class);
}

String latestVersion = response.get("tag_name").getAsString();
var latestVersion = response.get("tag_name").getAsString();
if (VersionComparator.isNewer(BuildData.VERSION, latestVersion)) {
LOGGER.warn("ServerWrecker is outdated! Current version: {}, latest version: {}", BuildData.VERSION, latestVersion);
return true;
Expand Down Expand Up @@ -299,9 +295,9 @@ private void initPlugins(Path pluginDir) {
public void setupLogging(DevSettings devSettings) {
Via.getManager().debugHandler().setEnabled(devSettings.viaDebug());

Level level = devSettings.coreDebug() ? Level.DEBUG : Level.INFO;
Level nettyLevel = devSettings.nettyDebug() ? Level.DEBUG : Level.INFO;
Level grpcLevel = devSettings.grpcDebug() ? Level.DEBUG : Level.INFO;
var level = devSettings.coreDebug() ? Level.DEBUG : Level.INFO;
var nettyLevel = devSettings.nettyDebug() ? Level.DEBUG : Level.INFO;
var grpcLevel = devSettings.grpcDebug() ? Level.DEBUG : Level.INFO;
Configurator.setRootLevel(level);
Configurator.setLevel(LOGGER.getName(), level);
Configurator.setLevel("org.pf4j", level);
Expand Down Expand Up @@ -351,7 +347,7 @@ public int startAttack() {
}

public int startAttack(SettingsHolder settingsHolder) {
AttackManager attackManager = injector.newInstance(AttackManager.class);
var attackManager = injector.newInstance(AttackManager.class);
ServerWreckerAPI.postEvent(new AttackInitEvent(attackManager));

attacks.put(attackManager.getId(), attackManager);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ private ServerWreckerBootstrap() {
public static void main(String[] args) {
ServerWreckerLoader.injectJvm();

int port = ServerWreckerLoader.getAvailablePort();
boolean isHeadless = GraphicsEnvironment.isHeadless() || args.length > 0;
var port = ServerWreckerLoader.getAvailablePort();
var isHeadless = GraphicsEnvironment.isHeadless() || args.length > 0;
if (isHeadless) {
ServerWreckerLoader.loadInternalAddons();
ServerWreckerLoader.runHeadless(port, args);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public static void injectTheme() {
}

public static void loadInternalAddons() {
List<InternalAddon> addons = List.of(
var addons = List.of(
new BotTicker(), new ClientBrand(), new ClientSettings(),
new AutoReconnect(), new AutoRegister(), new AutoRespawn(),
new AutoTotem(), new AutoJump(), new AutoArmor(), new AutoEat(),
Expand All @@ -69,9 +69,9 @@ public static void loadInternalAddons() {
}

public static void runHeadless(int port, String[] args) {
ServerWrecker serverWrecker = new ServerWrecker(OperationMode.CLI, "localhost", port);
SWCommandDefinition serverWreckerCommand = new SWCommandDefinition(serverWrecker);
CommandLine commandLine = new CommandLine(serverWreckerCommand);
var serverWrecker = new ServerWrecker(OperationMode.CLI, "localhost", port);
var serverWreckerCommand = new SWCommandDefinition(serverWrecker);
var commandLine = new CommandLine(serverWreckerCommand);
serverWreckerCommand.setCommandLine(commandLine);
commandLine.setCaseInsensitiveEnumValuesAllowed(true);
commandLine.setUsageHelpAutoWidth(true);
Expand All @@ -86,19 +86,19 @@ public static void runHeadless(int port, String[] args) {
}

public static void runGUI(int port) {
ServerWrecker serverWrecker = new ServerWrecker(OperationMode.GUI, "localhost", port);
var serverWrecker = new ServerWrecker(OperationMode.GUI, "localhost", port);
serverWrecker.initConsole();

GUIManager guiManager = new GUIManager(serverWrecker, serverWrecker.getInjector().getSingleton(RPCClient.class));
var guiManager = new GUIManager(serverWrecker, serverWrecker.getInjector().getSingleton(RPCClient.class));
guiManager.initGUI();
}

public static int getAvailablePort() {
int initialPort = 38765;
var initialPort = 38765;

while (true) {
try {
ServerSocket serverSocket = new ServerSocket(initialPort);
var serverSocket = new ServerSocket(initialPort);
serverSocket.close();
break; // Port is available, exit the loop
} catch (IOException e) {
Expand Down
Loading

0 comments on commit b80aa36

Please sign in to comment.