Skip to content

Commit

Permalink
Allow for implementations to provide a custom resource loader
Browse files Browse the repository at this point in the history
This will allow Geyser-Fabric to work without resource loading issues. This commit also ensures try-with-resources is used anywhere a resource is accessed.
  • Loading branch information
Camotoy committed Dec 3, 2021
1 parent 9084c59 commit 763743a
Show file tree
Hide file tree
Showing 22 changed files with 220 additions and 211 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -63,17 +63,21 @@ public class GeyserBungeePlugin extends Plugin implements GeyserBootstrap {

@Override
public void onEnable() {
GeyserLocale.init(this);

if (!getDataFolder().exists())
getDataFolder().mkdir();

try {
if (!getDataFolder().exists())
getDataFolder().mkdir();
File configFile = FileUtils.fileOrCopiedFromResource(new File(getDataFolder(), "config.yml"), "config.yml", (x) -> x.replaceAll("generateduuid", UUID.randomUUID().toString()));
File configFile = FileUtils.fileOrCopiedFromResource(new File(getDataFolder(), "config.yml"),
"config.yml", (x) -> x.replaceAll("generateduuid", UUID.randomUUID().toString()), this);
this.geyserConfig = FileUtils.loadConfig(configFile, GeyserBungeeConfiguration.class);
} catch (IOException ex) {
getLogger().log(Level.WARNING, GeyserLocale.getLocaleStringLog("geyser.config.failed"), ex);
getLogger().log(Level.SEVERE, GeyserLocale.getLocaleStringLog("geyser.config.failed"), ex);
ex.printStackTrace();
return;
}

if (getProxy().getConfig().getListeners().size() == 1) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,16 +79,21 @@ public class GeyserSpigotPlugin extends JavaPlugin implements GeyserBootstrap {

@Override
public void onEnable() {
GeyserLocale.init(this);

// This is manually done instead of using Bukkit methods to save the config because otherwise comments get removed
try {
if (!getDataFolder().exists()) {
getDataFolder().mkdir();
}
File configFile = FileUtils.fileOrCopiedFromResource(new File(getDataFolder(), "config.yml"), "config.yml", (x) -> x.replaceAll("generateduuid", UUID.randomUUID().toString()));
File configFile = FileUtils.fileOrCopiedFromResource(new File(getDataFolder(), "config.yml"), "config.yml",
(x) -> x.replaceAll("generateduuid", UUID.randomUUID().toString()), this);
this.geyserConfig = FileUtils.loadConfig(configFile, GeyserSpigotConfiguration.class);
} catch (IOException ex) {
getLogger().log(Level.WARNING, GeyserLocale.getLocaleStringLog("geyser.config.failed"), ex);
getLogger().log(Level.SEVERE, GeyserLocale.getLocaleStringLog("geyser.config.failed"), ex);
ex.printStackTrace();
Bukkit.getPluginManager().disablePlugin(this);
return;
}

try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,15 +71,19 @@ public class GeyserSpongePlugin implements GeyserBootstrap {

@Override
public void onEnable() {
GeyserLocale.init(this);

if (!configDir.exists())
configDir.mkdirs();

File configFile = null;
File configFile;
try {
configFile = FileUtils.fileOrCopiedFromResource(new File(configDir, "config.yml"), "config.yml", (file) -> file.replaceAll("generateduuid", UUID.randomUUID().toString()));
configFile = FileUtils.fileOrCopiedFromResource(new File(configDir, "config.yml"), "config.yml",
(file) -> file.replaceAll("generateduuid", UUID.randomUUID().toString()), this);
} catch (IOException ex) {
logger.warn(GeyserLocale.getLocaleStringLog("geyser.config.failed"));
logger.error(GeyserLocale.getLocaleStringLog("geyser.config.failed"));
ex.printStackTrace();
return;
}

try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,8 @@ public static void main(String[] args) {
boolean useGuiOpts = bootstrap.useGui;
String configFilenameOpt = bootstrap.configFilename;

GeyserLocale.init(bootstrap);

List<BeanPropertyDefinition> availableProperties = getPOJOForClass(GeyserJacksonConfiguration.class);

for (int i = 0; i < args.length; i++) {
Expand Down Expand Up @@ -188,7 +190,8 @@ public void onEnable() {
LoopbackUtil.checkLoopback(geyserLogger);

try {
File configFile = FileUtils.fileOrCopiedFromResource(new File(configFilename), "config.yml", (x) -> x.replaceAll("generateduuid", UUID.randomUUID().toString()));
File configFile = FileUtils.fileOrCopiedFromResource(new File(configFilename), "config.yml",
(x) -> x.replaceAll("generateduuid", UUID.randomUUID().toString()), this);
geyserConfig = FileUtils.loadConfig(configFile, GeyserStandaloneConfiguration.class);

handleArgsConfigOptions();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,16 +83,19 @@ public class GeyserVelocityPlugin implements GeyserBootstrap {

@Override
public void onEnable() {
GeyserLocale.init(this);

try {
if (!configFolder.toFile().exists())
//noinspection ResultOfMethodCallIgnored
configFolder.toFile().mkdirs();
File configFile = FileUtils.fileOrCopiedFromResource(configFolder.resolve("config.yml").toFile(),
"config.yml", (x) -> x.replaceAll("generateduuid", UUID.randomUUID().toString()));
"config.yml", (x) -> x.replaceAll("generateduuid", UUID.randomUUID().toString()), this);
this.geyserConfig = FileUtils.loadConfig(configFile, GeyserVelocityConfiguration.class);
} catch (IOException ex) {
logger.warn(GeyserLocale.getLocaleStringLog("geyser.config.failed"), ex);
logger.error(GeyserLocale.getLocaleStringLog("geyser.config.failed"), ex);
ex.printStackTrace();
return;
}

InetSocketAddress javaAddr = proxyServer.getBoundAddress();
Expand Down
31 changes: 28 additions & 3 deletions core/src/main/java/org/geysermc/geyser/GeyserBootstrap.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,16 @@

package org.geysermc.geyser;

import org.geysermc.geyser.GeyserImpl;
import org.geysermc.geyser.configuration.GeyserConfiguration;
import org.geysermc.geyser.GeyserLogger;
import org.geysermc.geyser.command.CommandManager;
import org.geysermc.geyser.configuration.GeyserConfiguration;
import org.geysermc.geyser.dump.BootstrapDumpInfo;
import org.geysermc.geyser.level.GeyserWorldManager;
import org.geysermc.geyser.level.WorldManager;
import org.geysermc.geyser.ping.IGeyserPingPassthrough;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.InputStream;
import java.net.SocketAddress;
import java.nio.file.Path;
import java.nio.file.Paths;
Expand Down Expand Up @@ -126,4 +126,29 @@ default SocketAddress getSocketAddress() {
default Path getLogsPath() {
return Paths.get("logs/latest.log");
}

/**
* Get an InputStream for the given resource path.
* Overridden on platforms that have different class loader properties.
*
* @param resource Resource to get
* @return InputStream of the given resource, or null if not found
*/
default @Nullable InputStream getResourceOrNull(String resource) {
return GeyserBootstrap.class.getClassLoader().getResourceAsStream(resource);
}

/**
* Get an InputStream for the given resource path, throws AssertionError if resource is not found.
*
* @param resource Resource to get
* @return InputStream of the given resource
*/
default @Nonnull InputStream getResource(String resource) {
InputStream stream = getResourceOrNull(resource);
if (stream == null) {
throw new AssertionError("Unable to find resource: " + resource);
}
return stream;
}
}
7 changes: 5 additions & 2 deletions core/src/main/java/org/geysermc/geyser/GeyserImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@

import javax.naming.directory.Attribute;
import javax.naming.directory.InitialDirContext;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
Expand Down Expand Up @@ -139,6 +140,8 @@ private GeyserImpl(PlatformType platformType, GeyserBootstrap bootstrap) {

this.platformType = platformType;

GeyserLocale.finalizeDefaultLocale(this);

logger.info("******************************************");
logger.info("");
logger.info(GeyserLocale.getLocaleStringLog("geyser.core.load", NAME, VERSION));
Expand Down Expand Up @@ -214,9 +217,9 @@ private GeyserImpl(PlatformType platformType, GeyserBootstrap bootstrap) {
String branch = "unknown";
int buildNumber = -1;
if (this.productionEnvironment()) {
try {
try (InputStream stream = bootstrap.getResource("git.properties")) {
Properties gitProperties = new Properties();
gitProperties.load(FileUtils.getResource("git.properties"));
gitProperties.load(stream);
branch = gitProperties.getProperty("git.branch");
String build = gitProperties.getProperty("git.build.number");
if (build != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,14 @@
import org.geysermc.geyser.GeyserImpl;
import org.geysermc.geyser.command.CommandSender;
import org.geysermc.geyser.command.GeyserCommand;
import org.geysermc.geyser.text.ChatColor;
import org.geysermc.geyser.network.MinecraftProtocol;
import org.geysermc.geyser.session.GeyserSession;
import org.geysermc.geyser.util.FileUtils;
import org.geysermc.geyser.text.ChatColor;
import org.geysermc.geyser.text.GeyserLocale;
import org.geysermc.geyser.util.WebUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
Expand Down Expand Up @@ -69,9 +69,9 @@ public void execute(GeyserSession session, CommandSender sender, String[] args)
// Disable update checking in dev mode and for players in Geyser Standalone
if (GeyserImpl.getInstance().productionEnvironment() && !(!sender.isConsole() && geyser.getPlatformType() == PlatformType.STANDALONE)) {
sender.sendMessage(GeyserLocale.getPlayerLocaleString("geyser.commands.version.checking", sender.getLocale()));
try {
try (InputStream stream = GeyserImpl.getInstance().getBootstrap().getResource("git.properties")) {
Properties gitProp = new Properties();
gitProp.load(FileUtils.getResource("git.properties"));
gitProp.load(stream);

String buildXML = WebUtils.getBody("https://ci.opencollab.dev/job/GeyserMC/job/Geyser/job/" +
URLEncoder.encode(gitProp.getProperty("git.branch"), StandardCharsets.UTF_8.toString()) + "/lastSuccessfulBuild/api/xml?xpath=//buildNumber");
Expand Down
5 changes: 3 additions & 2 deletions core/src/main/java/org/geysermc/geyser/dump/DumpInfo.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.InetSocketAddress;
Expand Down Expand Up @@ -78,9 +79,9 @@ public class DumpInfo {
public DumpInfo(boolean addLog) {
this.versionInfo = new VersionInfo();

try {
try (InputStream stream = GeyserImpl.getInstance().getBootstrap().getResource("git.properties")) {
this.gitInfo = new Properties();
this.gitInfo.load(FileUtils.getResource("git.properties"));
this.gitInfo.load(stream);
} catch (IOException ignored) {
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import org.geysermc.geyser.GeyserImpl;
import org.geysermc.geyser.util.FileUtils;

import java.io.IOException;
import java.io.InputStream;
Expand All @@ -45,10 +44,10 @@ public Object2IntMap<String> load(String input) {
// The server sends the corresponding Java network IDs, so we don't need to worry about that now.

// Reference variable for Jackson to read off of
TypeReference<Map<String, BiomeEntry>> biomeEntriesType = new TypeReference<Map<String, BiomeEntry>>() { };
TypeReference<Map<String, BiomeEntry>> biomeEntriesType = new TypeReference<>() { };
Map<String, BiomeEntry> biomeEntries;

try (InputStream stream = FileUtils.getResource("mappings/biomes.json")) {
try (InputStream stream = GeyserImpl.getInstance().getBootstrap().getResource("mappings/biomes.json")) {
biomeEntries = GeyserImpl.JSON_MAPPER.readValue(stream, biomeEntriesType);
} catch (IOException e) {
throw new AssertionError("Unable to load Bedrock runtime biomes", e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,8 @@ public Map<Integer, BlockCollision> load(Pair<String, String> input) {
}

// Load collision mappings file
InputStream stream = FileUtils.getResource(input.value());

List<BoundingBox[]> collisionList;
try {
try (InputStream stream = GeyserImpl.getInstance().getBootstrap().getResource(input.value())) {
ArrayNode collisionNode = (ArrayNode) GeyserImpl.JSON_MAPPER.readTree(stream);
collisionList = loadBoundingBoxes(collisionNode);
} catch (Exception e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@

import com.fasterxml.jackson.databind.JsonNode;
import org.geysermc.geyser.GeyserImpl;
import org.geysermc.geyser.util.FileUtils;

import java.io.InputStream;
import java.util.Map;
Expand All @@ -43,10 +42,9 @@ public abstract class EffectRegistryLoader<T> implements RegistryLoader<String,

public void loadFile(String input) {
if (!loadedFiles.containsKey(input)) {
InputStream effectsStream = FileUtils.getResource(input);
JsonNode effects;
try {
effects = GeyserImpl.JSON_MAPPER.readTree(effectsStream);
try (InputStream stream = GeyserImpl.getInstance().getBootstrap().getResource(input)) {
effects = GeyserImpl.JSON_MAPPER.readTree(stream);
} catch (Exception e) {
throw new AssertionError("Unable to load registrations for " + input, e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,11 @@
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
import org.geysermc.geyser.GeyserImpl;
import org.geysermc.geyser.network.MinecraftProtocol;
import org.geysermc.geyser.inventory.item.Enchantment.JavaEnchantment;
import org.geysermc.geyser.network.MinecraftProtocol;
import org.geysermc.geyser.registry.Registries;
import org.geysermc.geyser.registry.type.EnchantmentData;
import org.geysermc.geyser.registry.type.ItemMapping;
import org.geysermc.geyser.util.FileUtils;

import java.io.InputStream;
import java.util.EnumMap;
Expand All @@ -45,9 +44,8 @@
public class EnchantmentRegistryLoader implements RegistryLoader<String, Map<JavaEnchantment, EnchantmentData>> {
@Override
public Map<JavaEnchantment, EnchantmentData> load(String input) {
InputStream enchantmentsStream = FileUtils.getResource(input);
JsonNode enchantmentsNode;
try {
try (InputStream enchantmentsStream = GeyserImpl.getInstance().getBootstrap().getResource(input)) {
enchantmentsNode = GeyserImpl.JSON_MAPPER.readTree(enchantmentsStream);
} catch (Exception e) {
throw new AssertionError("Unable to load enchantment data", e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,7 @@
import com.nukkitx.nbt.NBTInputStream;
import com.nukkitx.nbt.NbtMap;
import com.nukkitx.nbt.NbtUtils;
import org.geysermc.geyser.util.FileUtils;

import java.io.InputStream;
import org.geysermc.geyser.GeyserImpl;

/**
* Loads NBT data from the given resource path.
Expand All @@ -39,8 +37,8 @@ public class NbtRegistryLoader implements RegistryLoader<String, NbtMap> {

@Override
public NbtMap load(String input) {
InputStream stream = FileUtils.getResource(input);
try (NBTInputStream nbtInputStream = NbtUtils.createNetworkReader(stream, true, true)) {
try (NBTInputStream nbtInputStream = NbtUtils.createNetworkReader(GeyserImpl.getInstance().getBootstrap().getResource(input),
true, true)) {
return (NbtMap) nbtInputStream.readTag();
} catch (Exception e) {
throw new AssertionError("Failed to load registrations for " + input, e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
import com.fasterxml.jackson.databind.JsonNode;
import org.geysermc.geyser.GeyserImpl;
import org.geysermc.geyser.registry.type.SoundMapping;
import org.geysermc.geyser.util.FileUtils;

import java.io.IOException;
import java.io.InputStream;
Expand All @@ -43,9 +42,8 @@ public class SoundRegistryLoader implements RegistryLoader<String, Map<String, S

@Override
public Map<String, SoundMapping> load(String input) {
InputStream stream = FileUtils.getResource(input);
JsonNode soundsTree;
try {
try (InputStream stream = GeyserImpl.getInstance().getBootstrap().getResource(input)) {
soundsTree = GeyserImpl.JSON_MAPPER.readTree(stream);
} catch (IOException e) {
throw new AssertionError("Unable to load sound mappings", e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@
import org.geysermc.geyser.registry.type.BlockMapping;
import org.geysermc.geyser.registry.type.BlockMappings;
import org.geysermc.geyser.util.BlockUtils;
import org.geysermc.geyser.util.FileUtils;

import java.io.DataInputStream;
import java.io.InputStream;
Expand Down Expand Up @@ -83,9 +82,9 @@ public static void populate() {

private static void registerBedrockBlocks() {
for (Map.Entry<ObjectIntPair<String>, BiFunction<String, NbtMapBuilder, String>> palette : BLOCK_MAPPERS.entrySet()) {
InputStream stream = FileUtils.getResource(String.format("bedrock/block_palette.%s.nbt", palette.getKey().key()));
NbtList<NbtMap> blocksTag;
try (NBTInputStream nbtInputStream = new NBTInputStream(new DataInputStream(new GZIPInputStream(stream)), true, true)) {
try (InputStream stream = GeyserImpl.getInstance().getBootstrap().getResource(String.format("bedrock/block_palette.%s.nbt", palette.getKey().key()));
NBTInputStream nbtInputStream = new NBTInputStream(new DataInputStream(new GZIPInputStream(stream)), true, true)) {
NbtMap blockPalette = (NbtMap) nbtInputStream.readTag();
blocksTag = (NbtList<NbtMap>) blockPalette.getList("blocks", NbtType.COMPOUND);
} catch (Exception e) {
Expand Down Expand Up @@ -208,10 +207,8 @@ private static void registerBedrockBlocks() {
}

private static void registerJavaBlocks() {
InputStream stream = FileUtils.getResource("mappings/blocks.json");

JsonNode blocksJson;
try {
try (InputStream stream = GeyserImpl.getInstance().getBootstrap().getResource("mappings/blocks.json")) {
blocksJson = GeyserImpl.JSON_MAPPER.readTree(stream);
} catch (Exception e) {
throw new AssertionError("Unable to load Java block mappings", e);
Expand Down
Loading

0 comments on commit 763743a

Please sign in to comment.