Skip to content

Commit

Permalink
Refactor HTTP client and remove OkHttp dependency
Browse files Browse the repository at this point in the history
  • Loading branch information
MrMicky-FR committed Dec 30, 2022
1 parent 3ce3876 commit 2579ece
Show file tree
Hide file tree
Showing 18 changed files with 267 additions and 245 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# AzLink

[![Tests](https://img.shields.io/github/workflow/status/Azuriom/AzLink/Java%20CI?style=flat-square)](https://github.com/Azuriom/AzLink/actions)
[![Language grade](https://img.shields.io/lgtm/grade/java/github/Azuriom/AzLink?label=code%20quality&logo=lgtm&logoWidth=18&style=flat-square)](https://lgtm.com/projects/g/Azuriom/AzLink/context:java)
[![Tests](https://img.shields.io/github/actions/workflow/status/Azuriom/AzLink/build.yml?branch=master&style=flat-square)](https://github.com/Azuriom/AzLink/actions/workflows/build.yml)
[![Chat](https://img.shields.io/discord/625774284823986183?color=5865f2&label=Discord&logo=discord&logoColor=fff&style=flat-square)](https://azuriom.com/discord)

AzLink is a plugin to link a Minecraft server or proxy with [Azuriom](https://azuriom.com/).
Expand All @@ -11,11 +10,12 @@ This plugin currently supports the following platforms:
* [BungeeCord](https://github.com/SpigotMC/BungeeCord)
* [Sponge](https://www.spongepowered.org/)
* [Velocity](https://velocitypowered.com/)
* [Nukkit](https://nukkitx.com/)
* [Nukkit](https://cloudburstmc.org/articles/)

## Setup

### Installation

The plugin works with the same .jar for all the platforms, except Bukkit/Spigot 1.7.10 which requires the legacy version of the plugin.

You just need to download the plugin, add it to the `plugins` folder of your server, and restart your server.
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
allprojects {
group 'com.azuriom'
version '1.1.2'
version '1.2.0'
}

subprojects {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,10 @@
import fr.xephi.authme.security.crypts.EncryptionMethod;
import fr.xephi.authme.security.crypts.HashedPassword;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;

import java.io.IOException;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.InetSocketAddress;
Expand Down Expand Up @@ -55,13 +53,14 @@ public void onPasswordEncryption(PasswordEncryptionEvent event) {
public void onEmailChanged(EmailChangedEvent event) {
Player player = event.getPlayer();

runAsync(event, () -> {
try {
this.plugin.getPlugin().getHttpClient().updateEmail(player.getUniqueId(), event.getNewEmail());
} catch (IOException e) {
this.plugin.getLoggerAdapter().error("Unable to update email for " + player.getName(), e);
}
});
this.plugin.getPlugin()
.getHttpClient()
.updateEmail(player.getUniqueId(), event.getNewEmail())
.exceptionally(ex -> {
this.plugin.getLoggerAdapter().error("Unable to update email for " + player.getName(), ex);

return null;
});
}

@EventHandler
Expand All @@ -80,24 +79,14 @@ public void onRegister(RegisterEvent event) {
return;
}

runAsync(event, () -> {
try {
this.plugin.getPlugin()
.getHttpClient()
.registerUser(player.getName(), email, player.getUniqueId(), password, ip);
} catch (IOException e) {
this.plugin.getLoggerAdapter().error("Unable to register " + player.getName(), e);
}
});
}

private void runAsync(Event event, Runnable runnable) {
if (event.isAsynchronous()) {
runnable.run();
return;
}
this.plugin.getPlugin()
.getHttpClient()
.registerUser(player.getName(), email, player.getUniqueId(), password, ip)
.exceptionally(ex -> {
this.plugin.getLoggerAdapter().error("Unable to register " + player.getName(), ex);

this.plugin.getSchedulerAdapter().executeAsync(runnable);
return null;
});
}

public class ForwardingEncryptionMethod implements EncryptionMethod {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@
import com.azuriom.azlink.common.scheduler.SchedulerAdapter;
import net.md_5.bungee.api.scheduler.ScheduledTask;

import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;

public class BungeeSchedulerAdapter implements SchedulerAdapter {

private final Executor executor = this::executeAsync;

private final AzLinkBungeePlugin plugin;

public BungeeSchedulerAdapter(AzLinkBungeePlugin plugin) {
Expand All @@ -24,6 +27,16 @@ public void executeAsync(Runnable runnable) {
this.plugin.getProxy().getScheduler().runAsync(this.plugin, runnable);
}

@Override
public Executor syncExecutor() {
return this.executor;
}

@Override
public Executor asyncExecutor() {
return this.executor;
}

@Override
public CancellableTask executeAsyncLater(Runnable runnable, long delay, TimeUnit unit) {
ScheduledTask task = this.plugin.getProxy()
Expand Down
4 changes: 1 addition & 3 deletions common/build.gradle
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
dependencies {
implementation 'com.squareup.okhttp3:okhttp:3.14.9'

compileOnly 'org.slf4j:slf4j-api:1.7.36'
compileOnly 'com.google.code.gson:gson:2.9.1'
compileOnly 'io.netty:netty-all:4.1.25.Final'
compileOnly 'io.netty:netty-all:4.1.42.Final'

testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.0'
testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.9.0'
Expand Down
51 changes: 26 additions & 25 deletions common/src/main/java/com/azuriom/azlink/common/AzLinkPlugin.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

Expand Down Expand Up @@ -71,10 +72,16 @@ public void init() {

this.httpServer = createHttpServer();

LocalDateTime start = LocalDateTime.now().truncatedTo(ChronoUnit.MINUTES).plusMinutes(1);
long startDelay = Duration.between(LocalDateTime.now(), start).plusMillis(500).toMillis(); // Add 0.5s to ensure we are not in the previous hour
// Add a random start delay to prevent important load on shared web hosts
// caused by many servers sending request at the same time
LocalDateTime start = LocalDateTime.now()
.truncatedTo(ChronoUnit.MINUTES)
.plusMinutes(1)
.plusSeconds(1 + (long) (Math.random() * 30));
long startDelay = Duration.between(LocalDateTime.now(), start).toMillis();
long repeatDelay = TimeUnit.MINUTES.toMillis(1);

getScheduler().executeAsyncRepeating(this.fetcherTask, startDelay, TimeUnit.MINUTES.toMillis(1), TimeUnit.MILLISECONDS);
getScheduler().executeAsyncRepeating(this.fetcherTask, startDelay, repeatDelay, TimeUnit.MILLISECONDS);

if (!this.config.isValid()) {
getLogger().warn("Invalid configuration, please use '/azlink' to setup the plugin.");
Expand All @@ -91,15 +98,13 @@ public void init() {
getScheduler().executeAsync(updateChecker::checkUpdates);
}

getScheduler().executeAsync(() -> {
try {
this.httpClient.verifyStatus();
this.httpClient.verifyStatus()
.thenRun(() -> getLogger().info("Successfully connected to " + this.config.getSiteUrl()))
.exceptionally(ex -> {
getLogger().warn("Unable to verify the website connection: " + ex.getMessage());

getLogger().info("Successfully connected to " + this.config.getSiteUrl());
} catch (IOException e) {
getLogger().warn("Unable to verify the website connection: " + e.getMessage() + " - " + e.getClass().getName());
}
});
return null;
});
}

public void restartHttpServer() {
Expand Down Expand Up @@ -127,10 +132,6 @@ public void shutdown() {
}
}

public void setConfig(PluginConfig config) {
this.config = config;
}

public void saveConfig() throws IOException {
if (!Files.isDirectory(this.platform.getDataDirectory())) {
Files.createDirectories(this.platform.getDataDirectory());
Expand Down Expand Up @@ -161,8 +162,8 @@ public ServerData getServerData(boolean fullData) {
return new ServerData(platformData, version, players, max, system, world, fullData);
}

public void fetchNow() {
getScheduler().executeAsync(this.fetcherTask);
public CompletableFuture<Void> fetch() {
return this.fetcherTask.fetch();
}

public LoggerAdapter getLogger() {
Expand All @@ -189,14 +190,6 @@ public HttpServer getHttpServer() {
return this.httpServer;
}

public static Gson getGson() {
return GSON;
}

public static Gson getGsonPrettyPrint() {
return GSON_PRETTY_PRINT;
}

public Optional<UserInfo> getUser(String name) {
return this.fetcherTask.getUser(name);
}
Expand All @@ -217,4 +210,12 @@ private double getCpuUsage() {
}
return -1;
}

public static Gson getGson() {
return GSON;
}

public static Gson getGsonPrettyPrint() {
return GSON_PRETTY_PRINT;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

public class AzLinkCommand {
Expand Down Expand Up @@ -42,13 +43,18 @@ public void execute(CommandSender sender, String[] args) {
}

if (args[0].equalsIgnoreCase("status")) {
plugin.getScheduler().executeAsync(() -> showStatus(sender));
showStatus(sender);
return;
}

if (args[0].equalsIgnoreCase("fetch")) {
this.plugin.fetchNow();
sender.sendMessage("&6Data has been fetched successfully.");
this.plugin.fetch()
.thenRun(() -> sender.sendMessage("&6Data has been fetched successfully."))
.exceptionally(ex -> {
sender.sendMessage("&cUnable to fetch data: " + ex.getMessage());

return null;
});
return;
}

Expand Down Expand Up @@ -79,7 +85,8 @@ public void execute(CommandSender sender, String[] args) {

sender.sendMessage("&aHTTP server started on port " + port);
} catch (Exception e) {
sender.sendMessage("&cAn error occurred while starting the HTTP server: " + e.getMessage() + " - " + e.getClass().getName());
String info = e.getMessage() + " - " + e.getClass().getName();
sender.sendMessage("&cAn error occurred while starting the HTTP server: " + info);
this.plugin.getLogger().error("Error while starting the HTTP server", e);
return;
}
Expand Down Expand Up @@ -123,43 +130,38 @@ private void setup(CommandSender sender, String url, String key) {
url = url.substring(0, url.length() - 1);
}

if (startsWithIgnoreCase(url, "http:")) {
sender.sendMessage("&6You should use https to improve security!");
}

this.plugin.getConfig().setSiteKey(key);
this.plugin.getConfig().setSiteUrl(url);

if (showStatus(sender)) {
if (startsWithIgnoreCase(url, "http://")) {
sender.sendMessage("&6You should use https to improve security.");
}

saveConfig(sender);

this.plugin.restartHttpServer();
}
showStatus(sender)
.thenRun(() -> saveConfig(sender))
.thenRun(this.plugin::restartHttpServer);
}

private void saveConfig(CommandSender sender) {
try {
this.plugin.saveConfig();
} catch (IOException e) {
sender.sendMessage("&cAn error occurred while saving config: " + e.getMessage() + " - " + e.getClass().getName());
String info = e.getMessage() + " - " + e.getClass().getName();
sender.sendMessage("&cAn error occurred while saving config: " + info);
this.plugin.getLogger().error("Error while saving config", e);
}
}

private boolean showStatus(CommandSender sender) {
try {
this.plugin.getHttpClient().verifyStatus();

sender.sendMessage("&aLinked to the website successfully.");

this.plugin.fetchNow();

return true;
} catch (Exception e) {
sender.sendMessage("&cUnable to connect to the website: " + e.getMessage() + " - " + e.getClass().getName());

return false;
}
private CompletableFuture<Void> showStatus(CommandSender sender) {
return this.plugin.getHttpClient()
.verifyStatus()
.thenRun(() -> sender.sendMessage("&aLinked to the website successfully."))
.thenRun(this.plugin::fetch)
.whenComplete((v, ex) -> {
if (ex != null) {
sender.sendMessage("&cUnable to connect to the website: " + ex.getMessage());
}
});
}

private static boolean startsWithIgnoreCase(String string, String prefix) {
Expand Down
Loading

0 comments on commit 2579ece

Please sign in to comment.