channel load and general file handling cleanup

This commit is contained in:
Jason Penilla committed 2023-07-12 13:04:48 -07:00
1 parent 702f5ad823
commit 0ae6a01128
6 files changed
+187 -113

No files matched your search

@@ -29,8 +29,6 @@ import com.google.inject.TypeLiteral;
import com.seiama.event.EventConfig;
import com.seiama.registry.Registry;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
@@ -39,7 +37,6 @@ import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;
import net.draycia.carbon.api.channels.ChannelRegistry;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.event.CarbonEventHandler;
@@ -55,6 +52,7 @@ import net.draycia.carbon.common.event.events.ChannelRegisterEventImpl;
import net.draycia.carbon.common.listeners.ChatListenerInternal;
import net.draycia.carbon.common.messages.CarbonMessages;
import net.draycia.carbon.common.util.Exceptions;
import net.draycia.carbon.common.util.FileUtil;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.text.Component;
@@ -181,57 +179,68 @@ public class CarbonChannelRegistry extends ChatListenerInternal implements Chann
this.defaultKey = this.configFactory.primaryConfig().defaultChannel();
if (!Files.exists(this.configChannelDir) || this.isPathEmpty(this.configChannelDir)) {
// no channels to register, register default channel
this.registerDefaultChannel();
return;
List<Path> channelConfigs = FileUtil.listDirectoryEntries(this.configChannelDir, "*.conf");
if (channelConfigs.isEmpty()) {
this.saveDefaultChannelConfig();
channelConfigs = FileUtil.listDirectoryEntries(this.configChannelDir, "*.conf");
}
// otherwise, register all channels found
try (final Stream<Path> paths = Files.walk(this.configChannelDir)) {
paths.forEach(path -> {
final String fileName = path.getFileName().toString();
if (!fileName.endsWith(".conf")) {
return;
}
final @Nullable ChatChannel chatChannel = this.channelFromPath(path);
if (chatChannel == null) {
this.logger.warn("Failed to load channel from file [" + fileName + "]");
return;
}
this.injector.injectMembers(chatChannel);
this.configChannels.add(chatChannel.key());
this.register(chatChannel);
if (firstRegister // We only support commands being registered at startup currently
&& chatChannel.shouldRegisterCommands()) {
this.registerChannelCommands(chatChannel);
}
});
if (this.channel(this.defaultKey) == null) {
this.logger.warn("No default channel found! Default channel key: [" + this.defaultKey().asString() + "]");
for (final Path channelConfigFile : channelConfigs) {
final String fileName = channelConfigFile.getFileName().toString();
if (!fileName.endsWith(".conf")) {
continue;
}
final List<String> channelList = new ArrayList<>();
for (final Key key : this.keys()) {
channelList.add(key.asString());
final @Nullable ChatChannel chatChannel = this.loadChannel(channelConfigFile);
if (chatChannel == null) {
continue;
}
final Key channelKey = chatChannel.key();
if (this.defaultKey.equals(channelKey)) {
this.logger.info("Default channel is [" + channelKey + "]");
}
final String channels = String.join(", ", channelList);
this.injector.injectMembers(chatChannel);
this.configChannels.add(chatChannel.key());
this.register(chatChannel);
this.logger.info("Registered channels: [" + channels + "]");
} catch (final IOException exception) {
throw Exceptions.rethrow(exception);
if (firstRegister // We only support commands being registered at startup currently
&& chatChannel.shouldRegisterCommands()) {
this.registerChannelCommands(chatChannel);
}
}
if (this.channel(this.defaultKey) == null) {
this.logger.warn("No default channel found! Default channel key: [" + this.defaultKey().asString() + "]");
}
final List<String> channelList = new ArrayList<>();
for (final Key key : this.keys()) {
channelList.add(key.asString());
}
final String channels = String.join(", ", channelList);
this.logger.info("Registered channels: [" + channels + "]");
this.eventHandler.emit(new ChannelRegisterEventImpl(this.keys(), this));
}
public @Nullable ChatChannel loadChannel(final Path channelFile) {
private void saveDefaultChannelConfig() {
try {
final Path configFile = this.configChannelDir.resolve("global.conf");
final ConfigChatChannel configChannel = this.injector.getInstance(ConfigChatChannel.class);
final ConfigurationLoader<?> loader = this.configFactory.configurationLoader(FileUtil.mkParentDirs(configFile));
final ConfigurationNode node = loader.createNode();
node.set(ConfigChatChannel.class, configChannel);
loader.save(node);
} catch (final IOException exception) {
throw Exceptions.rethrow(exception);
}
}
private @Nullable ChatChannel loadChannel(final Path channelFile) {
final ConfigurationLoader<?> loader = this.configFactory.configurationLoader(channelFile);
try {
@@ -239,51 +248,12 @@ public class CarbonChannelRegistry extends ChatListenerInternal implements Chann
loader.save(loaded);
return MAPPER.load(loaded);
} catch (final ConfigurateException exception) {
exception.printStackTrace();
this.logger.warn("Failed to load channel from file '{}'", channelFile, exception);
}
return null;
}
private void registerDefaultChannel() {
try {
Files.createDirectories(this.configChannelDir);
final Path configFile = this.configChannelDir.resolve("global.conf");
final ConfigurationLoader<?> loader = this.configFactory.configurationLoader(configFile);
final ConfigurationNode node = loader.load();
final ConfigChatChannel configChannel = this.injector.getInstance(ConfigChatChannel.class);
node.set(ConfigChatChannel.class, configChannel);
loader.save(node);
this.register(configChannel);
this.configChannels.add(configChannel.key());
} catch (final IOException exception) {
throw Exceptions.rethrow(exception);
}
}
private @Nullable ChatChannel channelFromPath(final Path channelPath) {
final @Nullable ChatChannel channel = this.loadChannel(channelPath);
if (channel == null) {
return null;
}
final Key channelKey = channel.key();
if (this.defaultKey.equals(channelKey)) {
this.logger.info("Default channel is [" + channelKey + "]");
}
//this.register(channel);
return channel;
}
private void sendMessageInChannelAsPlayer(
final CarbonPlayer sender,
final ChatChannel channel,
@@ -306,14 +276,6 @@ public class CarbonChannelRegistry extends ChatListenerInternal implements Chann
}
}
private boolean isPathEmpty(final Path path) {
try (DirectoryStream<Path> directory = Files.newDirectoryStream(path)) {
return !directory.iterator().hasNext();
} catch (final IOException exception) {
throw Exceptions.rethrow(exception);
}
}
@Override
public void registerChannelCommands(final ChatChannel channel) {
final CommandManager<Commander> commandManager =
@@ -38,6 +38,7 @@ import java.util.Set;
import java.util.UUID;
import net.draycia.carbon.common.DataDirectory;
import net.draycia.carbon.common.serialisation.gson.UUIDSerializerGson;
import net.draycia.carbon.common.util.FileUtil;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
@@ -178,11 +179,8 @@ public final class ProfileCache {
public synchronized void save() {
this.cleanup();
try {
Files.createDirectories(this.cacheFile.getParent());
try (final BufferedWriter writer = Files.newBufferedWriter(this.cacheFile)) {
this.gson.toJson(this.entries, writer);
}
try (final BufferedWriter writer = Files.newBufferedWriter(FileUtil.mkParentDirs(this.cacheFile))) {
this.gson.toJson(this.entries, writer);
} catch (final IOException ex) {
throw new RuntimeException("Failed to save cache", ex);
}
@@ -41,6 +41,7 @@ import net.draycia.carbon.common.users.CachingUserManager;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.users.PersistentUserProperty;
import net.draycia.carbon.common.users.ProfileResolver;
import net.draycia.carbon.common.util.FileUtil;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.NonNull;
@@ -131,7 +132,7 @@ public class JSONUserManager extends CachingUserManager {
throw new IllegalStateException("No data to save - toJson returned null or blank.");
}
Files.writeString(userFile, json);
Files.writeString(FileUtil.mkParentDirs(userFile), json);
} catch (final IOException exception) {
throw new RuntimeException("Exception while saving data for player [%s]".formatted(player.username()), exception);
}
@@ -177,10 +177,9 @@ public final class DependencyDownloader {
}
final HttpResponse<Path> response;
try {
Files.createDirectories(outputFile.getParent());
//this.logger.info("attempting to download " + urlString);
response = this.client.send(request, HttpResponse.BodyHandlers.ofFile(
outputFile,
FileUtil.mkParentDirs(outputFile),
StandardOpenOption.TRUNCATE_EXISTING,
StandardOpenOption.CREATE,
StandardOpenOption.WRITE
@@ -201,26 +200,13 @@ public final class DependencyDownloader {
throw new IllegalStateException(String.format("Could not resolve dependency %s from any of %s", dependency, this.repositories));
}
if (!checkHash(dependency, resolved)) {
throw new IllegalStateException("Hash for downloaded file %s was incorrect (expected: %s, got: %s)".formatted(resolved, dependency.sha256(), hashString(resolved)));
throw new IllegalStateException("Hash for downloaded file %s was incorrect (expected: %s, got: %s)".formatted(resolved, dependency.sha256(), FileUtil.hashString(resolved)));
}
return resolved;
}
private static boolean checkHash(final Dependency dependency, final Path resolved) throws IOException {
return hashString(resolved).equalsIgnoreCase(dependency.sha256());
}
private static String hashString(final Path resolved) throws IOException {
final byte[] hash = com.google.common.io.Files.asByteSource(resolved.toFile()).hash(Hashing.sha256()).asBytes();
return asHexString(hash);
}
private static String asHexString(final byte[] bytes) {
final StringBuilder sb = new StringBuilder(bytes.length * 2);
for (final byte b : bytes) {
sb.append("%02x".formatted(b & 0xFF));
}
return sb.toString();
return FileUtil.hashString(resolved).equalsIgnoreCase(dependency.sha256());
}
private ExecutorService makeExecutor() {
@@ -0,0 +1,119 @@
/*
* CarbonChat
*
* Copyright (c) 2023 Josua Parks (Vicarious)
* Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.draycia.carbon.common.util;
import com.google.common.hash.Hashing;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.DirectoryStream;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public final class FileUtil {
private FileUtil() {
}
/**
* Calculates the SHA256 hash of {@code file} and returns it as a hex string.
*
* @param file file to hash
* @return SHA256 hash string
* @throws IOException on I/O error
* @throws IllegalArgumentException when {@code file} is not a regular file
*/
public static String hashString(final Path file) throws IOException {
if (!Files.isRegularFile(file)) {
throw new IllegalArgumentException("Path '%s' is not a regular file, cannot generate hash string.".formatted(file));
}
final byte[] hash = com.google.common.io.Files.asByteSource(file.toFile()).hash(Hashing.sha256()).asBytes();
return Strings.asHexString(hash);
}
/**
* Lists directory entries in {@code path}.
*
* <p>If {@code path} does not exist, returns an empty list.</p>
* <p>If {@code path} exists, but is not a directory, throws {@link IllegalArgumentException}</p>
*
* @param path directory
* @return directory entries
* @throws IllegalArgumentException when {@code path} exists but is not a directory
* @throws UncheckedIOException on I/O error
*/
public static List<Path> listDirectoryEntries(final Path path) {
return listDirectoryEntries(path, "*");
}
/**
* Lists directory entries in {@code path} matching {@code glob}.
*
* <p>If {@code path} does not exist, returns an empty list.</p>
* <p>If {@code path} exists, but is not a directory, throws {@link IllegalArgumentException}</p>
*
* @param path directory
* @param glob glob pattern
* @return matching directory entries
* @throws IllegalArgumentException when {@code path} exists but is not a directory
* @throws UncheckedIOException on I/O error
*/
public static List<Path> listDirectoryEntries(final Path path, final String glob) {
if (!Files.exists(path)) {
return List.of();
} else if (!Files.isDirectory(path)) {
throw new IllegalArgumentException("Path '%s' exists but is not a directory!".formatted(path));
}
try (final DirectoryStream<Path> stream = Files.newDirectoryStream(path, glob)) {
final List<Path> ret = new ArrayList<>();
stream.forEach(ret::add);
return ret;
} catch (final IOException exception) {
throw new UncheckedIOException("Failed to list directory entries matching '%s' in path '%s'.".formatted(glob, path), exception);
}
}
/**
* Attempts to create the parent directories of {@code path} if necessary.
*
* <p>Returns {@code path} when successful.</p>
*
* @param path path
* @return {@code path}
* @throws IOException on I/O error
*/
public static Path mkParentDirs(final Path path) throws IOException {
final Path parent = path.getParent();
if (parent != null && !Files.isDirectory(parent)) {
try {
Files.createDirectories(parent);
} catch (final FileAlreadyExistsException ex) {
if (!Files.isDirectory(parent)) {
throw ex;
}
}
}
return path;
}
}
@@ -46,4 +46,12 @@ public final class Strings {
return s == null ? null : s.trim();
}
public static String asHexString(final byte[] bytes) {
final StringBuilder sb = new StringBuilder(bytes.length * 2);
for (final byte b : bytes) {
sb.append("%02x".formatted(b & 0xFF));
}
return sb.toString();
}
}