Skip to content

Commit

Permalink
Updated libraries, and cleaned up code for performance purposes.
Browse files Browse the repository at this point in the history
  • Loading branch information
dawson committed Dec 4, 2023
1 parent 7f96c49 commit 31a9412
Show file tree
Hide file tree
Showing 13 changed files with 115 additions and 179 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,11 @@
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;

import java.net.InetAddress;
import java.net.InetSocketAddress;
Expand All @@ -26,11 +24,9 @@
import java.util.logging.Level;

public class BukkitListener extends VPNExecutor implements Listener {

private BukkitTask cacheResetTask;
private final Cache<UUID, VPNResponse> responseCache = CacheBuilder.newBuilder()
.expireAfterWrite(5, TimeUnit.MINUTES)
.maximumSize(10000)
.maximumSize(2000)
.build();

@Override
Expand All @@ -39,22 +35,9 @@ public void registerListeners() {
.registerEvents(this, BukkitPlugin.pluginInstance);
}

@Override
public void runCacheReset() {
// Reset cache every 20 minutes
cacheResetTask = new BukkitRunnable() {
public void run() {
resetCache();
}
}.runTaskTimerAsynchronously(BukkitPlugin.pluginInstance, 24000, 24000);

HandlerList.unregisterAll(this);
threadExecutor.shutdown();
}

@Override
public void shutdown() {
if(cacheResetTask != null && !cacheResetTask.isCancelled()) cacheResetTask.cancel();

}

@Override
Expand Down Expand Up @@ -133,15 +116,15 @@ public void run() {

// If the countryList() size is zero, no need to check.
// Running country check first
if(AntiVPN.getInstance().getVpnConfig().countryList().size() > 0
if(!AntiVPN.getInstance().getVpnConfig().countryList().isEmpty()
// This bit of code will decide whether or not to kick the player
// If it contains the code and it is set to whitelist, it will not kick as they are equal
// and vise versa. However, if the contains does not match the state, it will kick.
&& AntiVPN.getInstance().getVpnConfig().countryList()
.contains(result.getCountryCode())
!= AntiVPN.getInstance().getVpnConfig().whitelistCountries()) {
//Using our built in kicking system if no commands are configured
if(AntiVPN.getInstance().getVpnConfig().countryKickCommands().size() == 0) {
if(AntiVPN.getInstance().getVpnConfig().countryKickCommands().isEmpty()) {
final String kickReason = AntiVPN.getInstance().getVpnConfig()
.countryVanillaKickReason();
// Kicking our player
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public class BungeeListener extends VPNExecutor implements Listener {

private final Cache<UUID, VPNResponse> responseCache = CacheBuilder.newBuilder()
.expireAfterWrite(5, TimeUnit.MINUTES)
.maximumSize(10000)
.maximumSize(2000)
.build();

@Override
Expand All @@ -35,12 +35,6 @@ public void registerListeners() {
.registerListener(BungeePlugin.pluginInstance, this);
}

@Override
public void runCacheReset() {
cacheResetTask = BungeePlugin.pluginInstance.getProxy().getScheduler().schedule(BungeePlugin.pluginInstance,
this::resetCache, 20, 20, TimeUnit.MINUTES);
}

@Override
public void shutdown() {
if(cacheResetTask != null) {
Expand Down
6 changes: 3 additions & 3 deletions Common/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -87,18 +87,18 @@
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>2.0</version>
<version>2.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>32.0.0-jre</version>
<version>32.1.3-jre</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.11</version>
<version>3.12.14</version>
<scope>provided</scope>
</dependency>
</dependencies>
Expand Down
2 changes: 1 addition & 1 deletion Common/src/main/java/dev/brighten/antivpn/AntiVPN.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
@Getter
@Setter(AccessLevel.PRIVATE)
@MavenLibrary(groupId = "com.h2database", artifactId ="h2", version = "2.2.224")
@MavenLibrary(groupId = "org.mongodb", artifactId = "mongo-java-driver", version = "3.12.11")
@MavenLibrary(groupId = "org.mongodb", artifactId = "mongo-java-driver", version = "3.12.14")
@MavenLibrary(groupId = "com.mysql", artifactId = "mysql-connector-j", version = "8.2.0")
public class AntiVPN {

Expand Down
103 changes: 43 additions & 60 deletions Common/src/main/java/dev/brighten/antivpn/api/VPNExecutor.java
Original file line number Diff line number Diff line change
@@ -1,35 +1,36 @@
package dev.brighten.antivpn.api;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import dev.brighten.antivpn.AntiVPN;
import dev.brighten.antivpn.utils.EvictingMap;
import dev.brighten.antivpn.web.objects.VPNResponse;
import dev.brighten.antivpn.utils.json.JSONException;
import dev.brighten.antivpn.web.FunkemunkyAPI;
import dev.brighten.antivpn.web.objects.VPNResponse;
import lombok.Getter;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.Level;

public abstract class VPNExecutor {
public static ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
public static ScheduledExecutorService threadExecutor = Executors.newScheduledThreadPool(2);

public static final Map<String, VPNResponse> responseCache = new EvictingMap<>(5000);
@Getter
private final Set<UUID> whitelisted = Collections.synchronizedSet(new HashSet<>());
@Getter
private final Set<String> whitelistedIps = Collections.synchronizedSet(new HashSet<>());

public abstract void registerListeners();

public abstract void runCacheReset();
private final Cache<String, VPNResponse> responseCache = CacheBuilder.newBuilder()
.expireAfterWrite(20, TimeUnit.MINUTES)
.maximumSize(4000)
.build();

public void resetCache() {
responseCache.clear();
}
public abstract void registerListeners();

public abstract void shutdown();

Expand All @@ -52,60 +53,42 @@ public boolean isWhitelisted(String ip) {
}

public void checkIp(String ip, boolean cachedResults, Consumer<VPNResponse> result) {
threadExecutor.execute(() -> result.accept(responseCache.compute(ip, (key, val) -> {
if(val == null) {
Optional<VPNResponse> cachedRes = AntiVPN.getInstance().getDatabase().getStoredResponse(ip);

if(cachedRes.isPresent()) return cachedRes.get();
else {
try {
VPNResponse response = FunkemunkyAPI
.getVPNResponse(ip, AntiVPN.getInstance().getVpnConfig().getLicense(), cachedResults);

if(response.isSuccess()) {
AntiVPN.getInstance().getDatabase().cacheResponse(response);
} else {
log("Query to VPN API failed! Reason: " + response.getFailureReason());
}

return response;
} catch (JSONException | IOException e) {
log("Query to VPN API failed! Reason: Java Exception");
e.printStackTrace();
}
threadExecutor.execute(() -> {
if(cachedResults) {
try {
result.accept(responseCache.get(ip, () -> checkIp(ip)));
} catch (ExecutionException e) {
log("Failed to process checkIp() method! Reason: " + e.getMessage());
result.accept(VPNResponse.FAILED_RESPONSE);
}
} else {
result.accept(checkIp(ip));
}

return val;
})));
});
}

public VPNResponse checkIp(String ip, boolean cachedResults) {
return responseCache.compute(ip, (key, val) -> {
if(val == null) {
Optional<VPNResponse> cachedRes = AntiVPN.getInstance().getDatabase().getStoredResponse(ip);

if(cachedRes.isPresent()) return cachedRes.get();
else {
try {
VPNResponse response = FunkemunkyAPI
.getVPNResponse(ip, AntiVPN.getInstance().getVpnConfig().getLicense(), cachedResults);

if(response.isSuccess()) {
threadExecutor.execute(() -> AntiVPN.getInstance().getDatabase().cacheResponse(response));
} else {
log("Query to VPN API failed! Reason: " + response.getFailureReason());
}

return response;
} catch (JSONException | IOException e) {
log("Query to VPN API failed! Reason: Java Exception");
e.printStackTrace();
}
public VPNResponse checkIp(String ip) {
Optional<VPNResponse> cachedRes = AntiVPN.getInstance().getDatabase().getStoredResponse(ip);

if(cachedRes.isPresent()) {
return cachedRes.get();
}
else {
try {
VPNResponse response = FunkemunkyAPI
.getVPNResponse(ip, AntiVPN.getInstance().getVpnConfig().getLicense(), true);

if (response.isSuccess()) {
AntiVPN.getInstance().getDatabase().cacheResponse(response);
} else {
log("Query to VPN API failed! Reason: " + response.getFailureReason());
}
}

return val;
});
return response;
} catch (JSONException | IOException e) {
log("Query to VPN API failed! Reason: " + e.getMessage());
return VPNResponse.FAILED_RESPONSE;
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package dev.brighten.antivpn.command.impl;

import dev.brighten.antivpn.AntiVPN;
import dev.brighten.antivpn.api.VPNExecutor;
import dev.brighten.antivpn.command.Command;
import dev.brighten.antivpn.command.CommandExecutor;

Expand Down Expand Up @@ -47,7 +46,6 @@ public Command[] children() {
@Override
public String execute(CommandExecutor executor, String[] args) {
AntiVPN.getInstance().getDatabase().clearResponses();
VPNExecutor.responseCache.clear();
return "&aCleared all cached API response information!";
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
package dev.brighten.antivpn.command.impl;

import dev.brighten.antivpn.AntiVPN;
import dev.brighten.antivpn.api.VPNExecutor;
import dev.brighten.antivpn.command.Command;
import dev.brighten.antivpn.command.CommandExecutor;
import dev.brighten.antivpn.database.local.H2VPN;
import dev.brighten.antivpn.database.mongo.MongoVPN;
import dev.brighten.antivpn.database.sql.MySqlVPN;
import dev.brighten.antivpn.message.VpnString;

import java.util.Collections;
import java.util.List;
Expand Down Expand Up @@ -58,9 +53,6 @@ public String execute(CommandExecutor executor, String[] args) {

AntiVPN.getInstance().getMessageHandler().reloadStrings();

// Clearing the local response cache
VPNExecutor.responseCache.clear();

AntiVPN.getInstance().reloadDatabase();

return AntiVPN.getInstance().getMessageHandler().getString("command-reload-complete").getMessage();
Expand Down
40 changes: 13 additions & 27 deletions Common/src/main/java/dev/brighten/antivpn/database/local/H2VPN.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,34 +20,20 @@

public class H2VPN implements VPNDatabase {

private Thread whitelistedThread;

public H2VPN() {
whitelistedThread = new Thread(() -> {
try {
Thread.sleep(TimeUnit.SECONDS.toMillis(2));
} catch (InterruptedException e) {
e.printStackTrace();
}
while (true) {
// Updating from database
if (AntiVPN.getInstance().getVpnConfig().isDatabaseEnabled()) {
AntiVPN.getInstance().getExecutor().getWhitelisted().clear();
AntiVPN.getInstance().getExecutor().getWhitelisted()
.addAll(AntiVPN.getInstance().getDatabase().getAllWhitelisted());
AntiVPN.getInstance().getExecutor().getWhitelistedIps().clear();
AntiVPN.getInstance().getExecutor().getWhitelistedIps()
.addAll(AntiVPN.getInstance().getDatabase().getAllWhitelistedIps());
}
try {
Thread.sleep(TimeUnit.SECONDS.toMillis(4));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});

whitelistedThread.start();
VPNExecutor.threadExecutor.scheduleAtFixedRate(() -> {
if(!AntiVPN.getInstance().getVpnConfig().isDatabaseEnabled() || MySQL.isClosed()) return;

//Refreshing whitelisted players
AntiVPN.getInstance().getExecutor().getWhitelisted().clear();
AntiVPN.getInstance().getExecutor().getWhitelisted()
.addAll(AntiVPN.getInstance().getDatabase().getAllWhitelisted());

//Refreshing whitlisted IPs
AntiVPN.getInstance().getExecutor().getWhitelistedIps().clear();
AntiVPN.getInstance().getExecutor().getWhitelistedIps()
.addAll(AntiVPN.getInstance().getDatabase().getAllWhitelistedIps());
}, 2, 30, TimeUnit.SECONDS);
}

@Override
Expand Down
Loading

0 comments on commit 31a9412

Please sign in to comment.