Skip to content

Commit

Permalink
some sonarlint suggestions
Browse files Browse the repository at this point in the history
  • Loading branch information
Kyagara committed Sep 27, 2024
1 parent 1e94b0f commit d494ddd
Show file tree
Hide file tree
Showing 6 changed files with 79 additions and 66 deletions.
5 changes: 4 additions & 1 deletion common/src/main/java/com/cooptweaks/Configuration.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
import java.nio.file.StandardOpenOption;

public final class Configuration {
private Configuration() {
}

/** Main config folder path. */
private static final Path MAIN_PATH = Platform.getConfigFolder().resolve("cooptweaks");

Expand All @@ -26,7 +29,7 @@ public final class Configuration {
<li>discord.toml</li>
</ul>
*/
public static void Verify() {
public static void verify() {
if (!Files.exists(MAIN_PATH)) {
try {
Main.LOGGER.info("Creating config folder.");
Expand Down
3 changes: 3 additions & 0 deletions common/src/main/java/com/cooptweaks/Dimension.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
import java.util.concurrent.ConcurrentHashMap;

public final class Dimension {
private Dimension() {
}

/** Maps player names to their current dimension. */
private static final ConcurrentHashMap<String, String> PLAYER_CURRENT_DIMENSION_ID = new ConcurrentHashMap<>();

Expand Down
8 changes: 4 additions & 4 deletions common/src/main/java/com/cooptweaks/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public final class Main {
public static long STARTUP;

public static void init() {
Configuration.Verify();
Configuration.verify();

LifecycleEvent.SERVER_BEFORE_START.register(server -> DISCORD.Start());

Expand All @@ -30,7 +30,7 @@ public static void init() {

// Requires the server to be started since the seed won't be available until then.
// This might be changed if manually reading the level.dat, haven't seen any issue from doing it this way yet.
ADVANCEMENTS.LoadAdvancements(server);
ADVANCEMENTS.loadAdvancements(server);
});

LifecycleEvent.SERVER_LEVEL_SAVE.register(world -> DISCORD.CyclePresence(world.getPlayers()));
Expand All @@ -48,6 +48,8 @@ public static void init() {

PlayerEvent.PLAYER_QUIT.register(DISCORD::PlayerLeft);

PlayerEvent.PLAYER_ADVANCEMENT.register(ADVANCEMENTS::OnCriterion);

PlayerEvent.CHANGE_DIMENSION.register((player, oldWorld, newWorld) -> {
String name = player.getName().getString();
String dimensionId = newWorld.getValue().toString();
Expand Down Expand Up @@ -82,8 +84,6 @@ public static void init() {
return EventResult.pass();
});

PlayerEvent.PLAYER_ADVANCEMENT.register(ADVANCEMENTS::OnCriterion);

CommandRegistrationEvent.EVENT.register((dispatcher, registryAccess, environment) -> {
// Advancements
new Progress().register(dispatcher, registryAccess, environment);
Expand Down
65 changes: 33 additions & 32 deletions common/src/main/java/com/cooptweaks/advancements/Advancements.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@
import com.cooptweaks.Main;
import com.cooptweaks.discord.Discord;
import discord4j.rest.util.Color;
import net.minecraft.advancement.Advancement;
import net.minecraft.advancement.AdvancementCriterion;
import net.minecraft.advancement.AdvancementEntry;
import net.minecraft.advancement.PlayerAdvancementTracker;
import net.minecraft.advancement.*;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.MutableText;
Expand All @@ -28,7 +25,6 @@
/**
Manages advancements and criteria syncing.
<p>
<p>
Startup:
<ol>
<li>Load all advancements and criteria from the server loaded by mods and the game.</li>
Expand All @@ -53,25 +49,30 @@ public final class Advancements {
/**
Map of criteria for each advancement. Loaded at startup.
<p>
Maps the advancement {@link AdvancementEntry#id() identifier} to a list of criteria.
Maps the advancement {@link AdvancementEntry#id() Identifier} to a list of its criteria.
*/
private static final HashMap<Identifier, List<String>> ALL_CRITERIA = new HashMap<>(122);
private static final HashMap<Identifier, List<String>> ALL_CRITERIA = HashMap.newHashMap(122);

/**
Map of all completed advancements. Loaded from the save file.
<p>
Maps the advancement {@link AdvancementEntry#id() identifier} to the {@link AdvancementEntry}.
Maps the advancement {@link AdvancementEntry#id() Identifier} to its {@link AdvancementEntry}.
*/
private static final ConcurrentHashMap<Identifier, AdvancementEntry> COMPLETED_ADVANCEMENTS = new ConcurrentHashMap<>(122);

private static FileChannel CURRENT_SEED_FILE;

private static synchronized void appendToSave(String text) throws IOException {
private static synchronized void appendToSave(String text) {
ByteBuffer buffer = ByteBuffer.wrap(text.getBytes());
CURRENT_SEED_FILE.write(buffer);
try {
CURRENT_SEED_FILE.write(buffer);
} catch (IOException e) {
// This should be handled in another way, has to be recoverable, so we can try again.
throw new RuntimeException(e);
}
}

public void LoadAdvancements(MinecraftServer server) {
public void loadAdvancements(MinecraftServer server) {
SERVER = server;

int totalAdvancements = loadServerAdvancements(server);
Expand Down Expand Up @@ -199,36 +200,36 @@ public void OnCriterion(ServerPlayerEntity currentPlayer, AdvancementEntry entry
}
}

try {
String line = String.format("%s%n", id);
appendToSave(line);
} catch (IOException e) {
// This should be handled in another way, has to be recoverable, so we can try again.
throw new RuntimeException(e);
}
String line = String.format("%s%n", id);
appendToSave(line);

Optional<Text> advancementName = advancement.name();
if (advancementName.isEmpty()) {
advancementName = Optional.of(Text.literal(id.toString()));
}

// Send announcement to the server chat.
MutableText text = Text.literal(playerName + " has made the advancement ")
.append(advancementName.get());
sendAdvancementAnnouncement(playerName, id, advancementName.get(), display);
}
});
}

/** Sends an announcement to the server chat and Discord channel. */
private static void sendAdvancementAnnouncement(String playerName, Identifier advancementId, Text advancementName, AdvancementDisplay display) {
// Send announcement to the server chat.
MutableText text = Text.literal(playerName + " has made the advancement ")
.append(advancementName);

SERVER.getPlayerManager().broadcast(text, false);
SERVER.getPlayerManager().broadcast(text, false);

// Send announcement to the Discord channel.
String title = display.getTitle().getString();
if (title.isEmpty()) {
title = id.toString();
}
// Send announcement to the Discord channel.
String title = display.getTitle().getString();
if (title.isEmpty()) {
title = advancementId.toString();
}

String description = display.getDescription().getString();
String message = String.format("**%s** has made the advancement **%s**!%n*%s*", playerName, title, description);
DISCORD.SendEmbed(message, Color.GREEN);
}
});
String description = display.getDescription().getString();
String message = String.format("**%s** has made the advancement **%s**!%n*%s*", playerName, title, description);
DISCORD.sendEmbed(message, Color.GREEN);
}

/**
Expand Down
20 changes: 10 additions & 10 deletions common/src/main/java/com/cooptweaks/discord/Discord.java
Original file line number Diff line number Diff line change
Expand Up @@ -70,15 +70,15 @@ public final class Discord {
/** Queue of events to be processed after the bot is ready. */
private static final List<Runnable> QUEUE = new ArrayList<>(2);

public void QueueEvent(Runnable event) {
public void queueEvent(Runnable event) {
if (BOT_READY.get()) {
event.run();
} else {
QUEUE.add(event);
}
}

private static void ProcessQueue() {
private static void processQueue() {
QUEUE.forEach(Runnable::run);
QUEUE.clear();
}
Expand Down Expand Up @@ -132,7 +132,7 @@ public void Start() {
BOT_READY.set(true);

// Process queued events now that the bot is ready.
ProcessQueue();
processQueue();

Main.LOGGER.info("Discord bot online and ready.");
}))
Expand All @@ -141,7 +141,7 @@ public void Start() {

public void Stop() {
if (BOT_READY.get()) {
SendEmbed("Server stopping.", Color.RED);
sendEmbed("Server stopping.", Color.RED);
Main.LOGGER.info("Logging out of Discord.");
GATEWAY.logout().block();
}
Expand Down Expand Up @@ -250,7 +250,7 @@ private void onMessage(MessageCreateEvent event) {
}).subscribe();
}

public void SendEmbed(String message, Color color) {
public void sendEmbed(String message, Color color) {
if (!BOT_READY.get()) {
return;
}
Expand All @@ -266,7 +266,7 @@ public void SendEmbed(String message, Color color) {
public void NotifyStarted(MinecraftServer server) {
SERVER = server;
LAST_PRESENCE_UPDATE = System.currentTimeMillis();
QueueEvent(() -> SendEmbed("Server started!", Color.GREEN));
queueEvent(() -> sendEmbed("Server started!", Color.GREEN));
}

public void CyclePresence(List<ServerPlayerEntity> players) {
Expand Down Expand Up @@ -301,11 +301,11 @@ public void CyclePresence(List<ServerPlayerEntity> players) {

public void PlayerJoined(String name) {
// In the case on an integrated server, this event might not be called, so queue it instead.
QueueEvent(() -> SendEmbed(String.format("**%s** joined!", name), Color.GREEN));
queueEvent(() -> sendEmbed(String.format("**%s** joined!", name), Color.GREEN));
}

public void PlayerLeft(ServerPlayerEntity player) {
SendEmbed(String.format("**%s** left!", player.getName().getString()), Color.BLACK);
sendEmbed(String.format("**%s** left!", player.getName().getString()), Color.BLACK);
}

public void PlayerSentChatMessage(ServerPlayerEntity player, Text message) {
Expand All @@ -322,14 +322,14 @@ public void PlayerSentChatMessage(ServerPlayerEntity player, Text message) {

public void PlayerChangedDimension(String name, String dimension) {
String message = String.format("**%s** entered **%s**.", name, dimension);
SendEmbed(message, Color.BLACK);
sendEmbed(message, Color.BLACK);
}

public void PlayerDied(String name, BlockPos pos, Text deathMessage) {
String dimension = Dimension.getPlayerDimension(name);
String text = deathMessage.getString().replace(name, String.format("**%s**", name));

String message = String.format("%s%n*`%s` at %d, %d, %d*", text, dimension, pos.getX(), pos.getY(), pos.getZ());
SendEmbed(message, Color.RED);
sendEmbed(message, Color.RED);
}
}
44 changes: 25 additions & 19 deletions common/src/main/java/com/cooptweaks/utils/TimeSince.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ public TimeSince(long past) {
this.past = past;
}

private static final String AND = " and ";
private static final String COMMA = ", ";

/**
Returns a formatted string of time.
Expand All @@ -27,34 +30,37 @@ public String toString() {

StringBuilder time = new StringBuilder();

if (days > 0) {
time.append(days).append(" day").append(days > 1 ? "s" : "");
}
appendTimeUnit(time, formatTimeUnit(days, "day", "days"), true);
appendTimeUnit(time, formatTimeUnit(hours, "hour", "hours"), days > 0 && (minutes > 0 || seconds > 0));
appendTimeUnit(time, formatTimeUnit(minutes, "minute", "minutes"), (days > 0 || hours > 0) && seconds > 0);
appendTimeUnit(time, formatTimeUnit(seconds, "second", "seconds"), false);

if (hours > 0) {
if (!time.isEmpty()) {
time.append(days > 0 && (minutes > 0 || seconds > 0) ? ", " : " and ");
}

time.append(hours).append(" hour").append(hours > 1 ? "s" : "");
// If no units were added, append 0 seconds
if (time.isEmpty()) {
time.append("0 seconds");
}

if (minutes > 0) {
if (!time.isEmpty()) {
time.append((days > 0 || hours > 0) && seconds > 0 ? ", " : " and ");
}
return time.toString();
}

time.append(minutes).append(" minute").append(minutes > 1 ? "s" : "");
/** Format a unit of time. Example: "2 days", "1 hour". */
private String formatTimeUnit(long value, String singular, String plural) {
if (value > 0) {
String unit = value > 1 ? plural : singular;
return value + " " + unit;
}

if (seconds > 0 || time.isEmpty()) {
return "";
}

/** Add unit to the string with appropriate conjunctions. */
private void appendTimeUnit(StringBuilder time, String unit, boolean addComma) {
if (!unit.isEmpty()) {
if (!time.isEmpty()) {
time.append(" and ");
time.append(addComma ? COMMA : AND);
}

time.append(seconds).append(" second").append(seconds > 1 ? "s" : "");
time.append(unit);
}

return time.toString();
}
}

0 comments on commit d494ddd

Please sign in to comment.