📄
pasted-code-1792832172540.txt
txt
465 lines
▶
Create a complete, working Minecraft plugin called "PvP Toggle" for Minecraft Paper 26.2, using Java and Maven.
IMPORTANT:
Verify the correct Paper 26.2 API version, Java version, and build requirements before writing the code. Do not invent dependency versions. The finished project must compile and run on the intended server version.
==================================================
1. PLUGIN PURPOSE
==================================================
Create a plugin that allows authorized users to enable or disable PvP across the server, either permanently or for a specified duration.
Features:
- Enable and disable PvP.
- Optional duration in seconds, minutes, or hours.
- Infinite duration.
- Custom broadcast messages.
- Automatic restoration of the previous PvP state after a temporary duration.
- A broadcast countdown for the final 10 seconds.
- Sounds when PvP changes state.
- Configurable messages, sounds, and settings.
- Permission protection.
- Correct handling of multiple worlds.
- Optional persistence across server restarts.
Main command: /pvp
==================================================
2. COMMAND SYNTAX
==================================================
Support these commands:
/pvp on
Enable PvP indefinitely.
/pvp off
Disable PvP indefinitely.
/pvp on
Enable PvP for the specified duration.
/pvp off
Disable PvP for the specified duration.
/pvp on inf
Enable PvP indefinitely.
/pvp off inf
Disable PvP indefinitely.
/pvp on
Enable PvP for the specified duration and immediately broadcast a custom message.
/pvp off
Disable PvP for the specified duration and immediately broadcast a custom message.
/pvp on inf
Enable PvP indefinitely and immediately broadcast a custom message.
/pvp off inf
Disable PvP indefinitely and immediately broadcast a custom message.
The custom message is optional.
If no custom message is supplied, use the appropriate configurable default message.
==================================================
3. FLEXIBLE DURATION SYSTEM
==================================================
Allow ANY positive whole-number duration. Do not hardcode a list of permitted numbers.
Supported units:
- s = seconds
- m = minutes
- h = hours
- inf = infinite duration
Examples of valid durations:
1s, 2s, 3s, 4s, 5s, 10s, 37s, 59s, 120s, 3600s
1m, 2m, 3m, 5m, 10m, 30m, 60m, 120m, 500m
1h, 2h, 3h, 5h, 12h, 24h, 48h, 100h, 500h
inf
These numbers are examples, not a restriction. Accept other positive whole numbers whenever they can be safely represented and scheduled.
Example commands:
/pvp on 1s
/pvp off 2s
/pvp on 37s
/pvp off 120s
/pvp on 1m
/pvp off 17m
/pvp on 120m
/pvp off 3h
/pvp on 48h
/pvp off 100h
/pvp on inf
Do not limit durations to a predefined selection.
Parse the numeric part dynamically, recognize the unit, and convert the duration correctly.
Validation requirements:
- Accept positive whole numbers followed by s, m, or h.
- Reject zero durations.
- Reject negative durations.
- Reject decimals and malformed inputs.
- Reject unsupported units.
- Prevent integer overflow, multiplication overflow, and unsafe scheduler delays.
- Provide a helpful configurable error message for invalid durations.
- Never crash due to invalid user input.
- Handle very long but valid durations safely, without silently overflowing or firing early.
The inf value means no automatic expiration. It is not a very long timer.
==================================================
4. CUSTOM BROADCAST MESSAGES
==================================================
Anything after the command, state, and optional duration/inf argument must be treated as the custom broadcast message.
Preserve all spaces between words where practical, punctuation, and color codes.
Examples:
/pvp on 5m PvP is on!
Immediately broadcast:
PvP is on!
/pvp off 5m PvP is off!
Immediately broadcast:
PvP is off!
/pvp on 15s PvP will be enabled for 15 seconds!
Immediately broadcast that message.
/pvp off 2h PvP is disabled for two hours!
Immediately broadcast that message.
/pvp on inf PvP is permanently enabled!
Immediately broadcast that message.
/pvp off inf PvP is permanently disabled!
Immediately broadcast that message.
/pvp on PvP is now enabled!
Treat this as invalid syntax because a message without a duration is ambiguous. Display the command usage. For a custom message without a temporary duration, require the explicit inf argument.
IMPORTANT:
A custom message is broadcast immediately when the command executes. It must NOT wait until the timer expires.
If no custom message is provided, broadcast the appropriate configurable default message.
Support Minecraft color codes and a configurable prefix. Ensure malformed formatting never crashes the plugin.
Do not interpret extra message words as duration arguments.
==================================================
5. PVP STATE MANAGEMENT
==================================================
The plugin must change the actual PvP setting used by Paper, not just store a Boolean variable.
Apply PvP consistently across all relevant worlds. Implement a well-defined strategy for handling multiple worlds, including worlds that have different initial PvP settings.
Before a temporary change:
- Record the previous PvP state of every affected world.
- Apply the requested state.
- Schedule automatic restoration after the duration expires.
When the timer expires:
- Restore each affected world to its recorded previous PvP state.
- Send a configurable expiration broadcast.
- Play the appropriate sound if the actual PvP state changes.
If a new /pvp command is executed while a timer is active:
- Cancel the previous timer and all countdown tasks.
- Apply the new requested state.
- Start a new timer if the new command has a finite duration.
- Replace the stored restoration state according to the documented replacement rules.
- Prevent old tasks from restoring stale states or interfering with the new command.
Commands without a duration and commands using inf must cancel the active temporary timer.
The plugin must not create overlapping timers or duplicate countdowns.
If a world loads while a temporary or permanent global PvP setting is active, apply the current intended policy to that world.
Document how the plugin treats newly loaded worlds and worlds with different original PvP settings.
==================================================
6. AUTOMATIC RESTORATION
==================================================
Temporary changes must automatically expire after the specified duration.
Examples:
If PvP is originally OFF:
/pvp on 10s
PvP turns ON for 10 seconds, then returns to OFF.
If PvP is originally ON:
/pvp off 5m
PvP turns OFF for 5 minutes, then returns to ON.
If another command replaces the active timer, the new command takes control and the old restoration must never execute.
Permanent commands cancel temporary restoration and leave the requested state active until another command changes it, subject to the persistence configuration.
Keep the server responsive and use Paper/Bukkit scheduling correctly.
Use safe time calculations, including absolute expiration timestamps when persistence is enabled. Handle extremely long durations without relying on a single scheduler delay that may overflow.
==================================================
7. FINAL 10-SECOND COUNTDOWN
==================================================
For temporary durations of 10 seconds or longer, broadcast a countdown during the final 10 seconds.
Example:
PvP will change back in 10 seconds!
PvP will change back in 9 seconds!
PvP will change back in 8 seconds!
PvP will change back in 7 seconds!
PvP will change back in 6 seconds!
PvP will change back in 5 seconds!
PvP will change back in 4 seconds!
PvP will change back in 3 seconds!
PvP will change back in 2 seconds!
PvP will change back in 1 second!
The exact wording must be configurable in config.yml.
Requirements:
- Announce each remaining second, from 10 down to 1.
- Use singular/plural wording correctly where practical.
- Do not broadcast the countdown for durations shorter than 10 seconds.
- Start the countdown at the correct time.
- Cancel the countdown immediately if a new command replaces the timer.
- Do not let an old countdown continue after a timer has been cancelled.
- Avoid duplicate messages and scheduler task leaks.
- Run world changes and Bukkit/Paper API operations on the main server thread.
This is a countdown to automatic restoration, NOT a cooldown preventing commands.
==================================================
8. SOUNDS
==================================================
Play a configurable sound to all online players when PvP is actually enabled or disabled.
Requirements:
- Separate configurable sound for PvP ON.
- Separate configurable sound for PvP OFF.
- Configurable volume and pitch for each sound.
- Use valid Sound enum values for the target Paper API.
- Validate configured sound names and handle invalid values safely.
- Provide sensible defaults.
- Play sounds when the state actually changes.
- Do not play a misleading sound if the state is already the requested state.
- Play the correct sound during automatic restoration if the state changes.
- Do not play duplicate sounds because of multiple overlapping tasks.
Make sound settings editable in config.yml without recompiling the plugin.
==================================================
9. PERMISSIONS
==================================================
Create the permission:
pvptoggle.admin
Only users with this permission may execute /pvp.
Console execution should be supported so server administrators can use the command from the server console.
Include:
- Permission declarations in plugin.yml.
- Configurable no-permission message.
- Helpful usage message.
- Appropriate handling for console senders and player senders.
- No unnecessary player-only restrictions.
==================================================
10. TAB COMPLETION
==================================================
Implement useful tab completion for /pvp.
Suggestions should include:
- on
- off
- inf
- Duration examples such as 10s, 5m, and 1h when appropriate.
Tab completion suggestions are examples only. The parser must still accept any valid positive whole-number duration, not just the suggested values.
Do not interfere with custom messages after the recognized command arguments.
==================================================
11. CONFIGURATION FILE
==================================================
Create a complete, well-organized config.yml.
Include configurable settings for:
General:
- Plugin message prefix.
- Color formatting.
- Whether state is persisted across restarts.
- Which worlds are affected or the global world policy, if needed.
Broadcasts:
- Default PvP enabled message.
- Default PvP disabled message.
- Temporary timer expiration message.
- Countdown messages.
- Invalid command usage.
- Invalid duration.
- No permission.
- Successful state changes.
Sounds:
- PvP-on sound.
- PvP-off sound.
- Volume and pitch for both sounds.
Placeholders:
- Current PvP state.
- Requested PvP state.
- Duration.
- Remaining seconds.
- Previous state, where applicable.
Make the configuration readable, with comments explaining settings and examples.
If the config file is missing or contains invalid values, safely use defaults and log helpful warnings.
==================================================
12. RESTART PERSISTENCE
==================================================
Implement optional persistence.
When persistence is enabled:
- Save the current intended PvP state.
- Save previous world states needed for an active temporary timer.
- Save the timer expiration as an absolute timestamp.
- Save enough information to restore the intended behavior after a restart.
- Persist infinite states.
- On startup, calculate the remaining duration for active temporary timers.
- Resume an unexpired timer with the correct remaining time.
- If the timer expired while the server was offline, restore the previous state immediately.
- Avoid duplicate expiration broadcasts and countdown messages after restarting.
- Apply saved settings safely after worlds are available.
When persistence is disabled:
- Clearly document startup behavior.
- Do not leave worlds in an unexpected state.
- Do not accidentally preserve stale timer data.
Store runtime state separately from config.yml, using a safe persistence format such as a dedicated YAML data file. Save data safely to reduce the risk of corruption.
==================================================
13. IMPLEMENTATION AND CODE QUALITY
==================================================
Use clean, maintainable Java.
Requirements:
- Correct Paper 26.2 API compatibility.
- Correct Java and Maven dependency versions.
- A valid pom.xml.
- A valid plugin.yml.
- A complete config.yml.
- Every required Java source file.
- A dedicated timer/state-management implementation where appropriate.
- Proper plugin lifecycle handling.
- Correct event listener registration and cleanup.
- Cancel scheduled tasks on plugin shutdown.
- Handle missing worlds and world loading safely.
- Validate all arguments.
- Prevent stale timers and race conditions.
- Avoid deprecated APIs where practical.
- Avoid unnecessary dependencies.
- Do not use fake implementations or unsupported API methods.
- Do not leave TODOs, pseudocode, empty methods, or omitted sections.
- Do not claim the code compiles unless it has actually been verified.
If the requested Minecraft/Paper version is unavailable or has different requirements than expected, explain the issue and use a verified compatible setup rather than inventing version numbers.
==================================================
14. REQUIRED DELIVERABLES
==================================================
Provide:
1. A complete project directory tree.
2. The full contents of every required source and configuration file.
3. pom.xml with correct dependencies.
4. plugin.yml with command and permission declarations.
5. config.yml with all configurable messages and sounds.
6. Any data-storage implementation required for persistence.
7. Instructions to build the plugin using Maven.
8. The location of the resulting JAR file.
9. Instructions to install the JAR into the Paper server's plugins folder.
10. A complete command reference with examples.
11. A list of permissions.
12. Explanation of timer replacement and restoration behavior.
13. Explanation of multi-world PvP behavior.
14. A test checklist.
==================================================
15. TESTING CHECKLIST
==================================================
Test and verify:
- /pvp on
- /pvp off
- /pvp on 1s
- /pvp off 2s
- /pvp on 37s
- /pvp off 59s
- /pvp on 1m
- /pvp off 17m
- /pvp on 120m
- /pvp off 3h
- /pvp on 48h
- /pvp off 100h
- /pvp on inf
- /pvp off inf
- Temporary commands with custom messages.
- Infinite commands with custom messages.
- Immediate custom broadcasts.
- Default broadcasts when no custom message is provided.
- Final 10-second countdown.
- No countdown for durations under 10 seconds.
- Countdown cancellation after a new command.
- Timer replacement.
- Correct restoration of the previous PvP state.
- Sounds on actual state changes.
- No misleading sounds when the state does not change.
- Permission checks.
- Console execution.
- Tab completion.
- Invalid syntax.
- Invalid durations.
- Very large durations and overflow protection.
- Multiple worlds.
- World loading during a timer.
- Plugin disable and server restart.
- Persistence enabled and disabled.
- Expiration while the server is offline.
Fix any problems discovered during testing.
FINAL INSTRUCTION:
Deliver a complete, buildable, production-quality implementation of PvP Toggle for Paper 26.2. Prioritize correctness, safety, clear documentation, and reliable timer behavior. Do not omit any required files or existing features.
Verify Paper’s published API versions and runtime requirements.
Create the Maven project, plugin/config files, command handling, state/timer manager, and persistence.
Include usage, setup, and a practical test checklist.
Implemented PvP Toggle with a Maven project targeting Paper 26.2. Paper’s repository lists 26.2.build.134-stable, and Paper’s requirements specify Java 25 for 26.1+.
Project files
pom.xml
src/main/resources/
config.yml
plugin.yml
src/main/java/com/kodari/pvptoggle/
PvPTogglePlugin.java
command/PvPCommand.java
state/PvPStateManager.java
state/WorldListener.java
Commands
/pvp onor/pvp off— set the state indefinitely./pvp on <duration|inf> [message...]or/pvp off <duration|inf> [message...]— set it temporarily or indefinitely with an immediate custom broadcast.Durations accept any positive whole number followed by
s,m, orh, such as37s,120m, or48h.A custom message requires a duration or
inf;/pvp on PvP is enabled!displays usage.Permission:
pvptoggle.admin(default: operators). Console use is supported.
Timer and world behavior
Commands apply to every loaded world. Temporary changes save each world’s individual PvP setting for restoration.
Replacing a timer cancels its tasks and takes the worlds’ current settings as the new restoration baseline. Newly loaded worlds inherit the active policy and are included in an active timer’s restoration.
When persistence is enabled,
runtime.ymlstores the intended state, per-world restoration values, expiration timestamp, and countdown progress. If a timer expires while the server is offline, settings are restored at startup without replaying the expiration broadcast.With persistence disabled, startup leaves saved world settings alone; temporary settings are restored during normal plugin shutdown.
Build and install
On desktop, click Compile in the top bar. On phone, tap ⋮ → Compile Project.
Click Compile, then use Download on the successful build. The Maven artifact path is
target/pvp-toggle-1.0.0.jar.Place the JAR in the Paper server’s
pluginsfolder and restart the server.
The project includes configurable messages, prefix, sounds, and persistence settings in config.yml. I have not run a server test or verified a compile here.
Test checklist: Try permanent and inf commands; the requested durations (1s, 2s, 37s, 59s, 1m, 17m, 120m, 3h, 48h, 100h); custom and default broadcasts; countdown and cancellation; timer replacement and per-world restoration; sound changes; permissions, console, and tab completion; invalid and overflowing durations; world loading during a timer; and persistence across restart and offline expiration.
📄
pasted-code-1792832993883.txt
txt
65 lines
▶
UPDATE THE EXISTING PVP TOGGLE PLUGIN. Do not remove or break any existing functionality.
1. FIX THE EXPIRATION MESSAGE
Replace the current long message:
"[PvP] The temporary PvP change expired; the previous world settings were restored."
With a short, colorful message:
"§8[§cPvP§8] §aThe temporary PvP timer has ended! §7Previous PvP settings restored."
Make the message configurable in config.yml.
2. MATCH THE MINECRAFT CHAT STYLE IN THE SECOND SCREENSHOT
All PvP Toggle messages should use Minecraft chat formatting similar to the colorful server messages shown in the second screenshot.
Use a consistent prefix:
§8[§cPvP§8] §r
Use these default countdown messages:
§8[§cPvP§8] §ePvP will change back in §c10 §eseconds!
§8[§cPvP§8] §ePvP will change back in §c9 §eseconds!
Continue for every remaining second down to 1.
For the final second, use correct singular grammar:
§8[§cPvP§8] §ePvP will change back in §c1 §esecond!
3. FORMAT ALL PLUGIN MESSAGES
Use colorful, readable Minecraft legacy color codes:
- Prefix: dark gray brackets with "PvP" in red.
- Countdown text: yellow.
- Remaining number: red.
- Success messages: green.
- Informational text: gray or aqua.
- Errors: red.
Apply this formatting to:
- PvP enabled messages.
- PvP disabled messages.
- Countdown messages.
- Timer expiration messages.
- Invalid command and duration messages.
- Permission errors.
- Any default broadcast messages.
4. CONFIGURATION
Put the prefix and all message formats in config.yml.
Allow administrators to customize the text and colors without recompiling.
Support legacy color codes (& or §) and translate them correctly before sending messages.
If the existing project uses MiniMessage, use it consistently instead; do not mix formatting systems incorrectly.
5. CHAT DELIVERY
Send countdown and expiration messages as normal server-wide Minecraft chat messages, not action-bar messages, titles, boss bars, or console-only messages.
Broadcast each countdown message once per second to all online players.
Ensure the expiration message appears after the final countdown and the PvP settings are restored correctly.
6. FINAL EXPECTED RESULT
The chat should look similar to the second screenshot: a short colored [PvP] prefix followed by readable, colorful text.
Do not change the countdown timing, timer restoration logic, sound behavior, custom broadcast behavior, or flexible duration support. Preserve all existing features.
Make the expiration message short, colorful, and configurable.
Move all PvP message formats into config, with legacy
&/§color support.Ensure countdown and expiration are chat broadcasts while preserving timing and PvP restoration.
Updated
broadcasts.expiredto the short green-and-gray message; its Java fallback now matches.Updated countdown defaults with a red remaining number, yellow text, and correct singular grammar. The disabled confirmation is green.
Confirmed messages are sent as server-wide chat broadcasts, and PvP settings are restored before the expiration message. Timer timing, sounds, and custom broadcasts were left unchanged.
📄
pasted-code-1792834587144.txt
txt
82 lines
▶
Modify the existing PvP Toggle plugin. Preserve all existing functionality.
1. REMOVE THE OLD EXPIRATION MESSAGES
Completely remove these messages:
- "[PvP] The temporary PvP timer has ended!"
- "Previous PvP settings restored."
- Any other separate timer-expired or previous-settings-restored explanation.
2. RESTORATION MESSAGE AFTER THE COUNTDOWN
When a temporary PvP timer finishes, broadcast exactly ONE colorful, customizable Minecraft chat message indicating the restored PvP state.
If PvP is restored to ON, use this default:
§8[§cPvP§8] §6PvP has been §aenabled§6 again!
If PvP is restored to OFF, use this default:
§8[§cPvP§8] §6PvP has been §cdisabled§6 again!
The message must:
- Be sent to all online players in normal Minecraft chat.
- Use colorful Minecraft formatting similar to the welcome messages in my reference screenshot.
- Have a dark gray prefix, red PvP label, and colorful message text.
- Be configurable in config.yml.
- Reflect the actual state restored.
TIMING IS IMPORTANT:
- Keep the existing final 10-second countdown.
- Broadcast the countdown once per second from 10 down to 1.
- After the 1-second countdown message, restore the previous PvP state and then broadcast exactly ONE restoration message.
- Do not broadcast the restoration message before the countdown finishes.
- Do not send any extra expiration messages.
- For temporary durations shorter than 10 seconds, skip the countdown and broadcast the restoration message only when the timer expires and the previous state is restored.
- If a new /pvp command replaces the timer, cancel the old countdown and timer. The cancelled timer must not broadcast a restoration message.
3. USE THE SAME SOUND FOR PVP ON AND OFF
Whenever PvP is enabled or disabled, use the SAME configured sound for both states.
Specifically:
- PvP ON uses the PvP OFF sound.
- PvP OFF uses that exact same sound.
- Automatic restoration to ON or OFF uses the same sound too, but only if the actual PvP state changes.
- Do not play duplicate sounds.
- Keep the sound configurable in config.yml.
- Use one shared sound setting, with configurable volume and pitch, rather than separate ON and OFF sounds.
- Remove or ignore the old separate PvP-on sound setting so it cannot cause inconsistent behavior.
4. PRESERVE EVERYTHING ELSE
Do not break or remove:
- /pvp on and /pvp off.
- Any positive whole-number duration in seconds (s), minutes (m), or hours (h).
- Infinite duration using inf.
- Custom broadcast messages supplied in commands.
- Immediate broadcasting of command-supplied custom messages.
- Automatic restoration of the previous PvP state.
- Timer replacement and cancellation.
- Permissions and console execution.
- Multiple-world handling.
- Persistence across restarts, if implemented.
- Tab completion and configurable messages.
5. FINAL EXPECTED BEHAVIOR
Example: PvP was originally OFF and an administrator runs /pvp on 30s.
- PvP turns ON immediately.
- The requested custom message is broadcast immediately, if supplied.
- The same shared sound plays when PvP actually changes.
- During the final 10 seconds, broadcast the countdown from 10 to 1.
- After the 1-second countdown message, PvP is restored to OFF.
- Play the same shared sound because the state changed.
- Broadcast exactly one colorful message:
§8[§cPvP§8] §6PvP has been §cdisabled§6 again!
If PvP was originally ON and the temporary change restores it to ON, broadcast:
§8[§cPvP§8] §6PvP has been §aenabled§6 again!
Do not send any other restoration or expiration message.
Make these changes directly to the existing project and provide the complete updated files or a patch showing exactly what changed.
Update timer completion to restore state, play the shared sound only on an actual change, and send one state-specific chat message.
Replace separate PvP sounds with one configurable sound and keep timer replacement/cancellation intact.
Timer expiry now restores the prior PvP state, then sends exactly one configurable message:
broadcasts.restored.enabledorbroadcasts.restored.disabled. The old expiration message is no longer used.PvP changes and restoration now share
sounds.state-change; restoration plays it once only when at least one world’s PvP state changes.Existing countdown timing, short-duration behavior, timer replacement, persistence, and custom command broadcasts remain intact.
also make it so if the pvp off has ended, pvp is on and it will be broadcasted by the message you typed in the command.
Temporary /pvp off timers now reuse the command’s custom message when they expire and restore PvP to ON. The command message still broadcasts immediately, and it’s saved with the timer so it remains available after a restart. If no custom message was supplied, the configured restoration message is used.
ok so bassicly there is this bug whenever you do pvp off 10s and the timer ends, pvp i still off and it says pvp is disabled again. but doesnt it need to be pvp is on again??
Capture the actual pre-timer world state instead of relying on a potentially stale cached PvP value.
Use that captured state for timer restoration and its enabled/disabled message.
Fixed the timer snapshot to capture the actual PvP state in the world before the temporary change, rather than a potentially stale cached value. So if PvP was ON before /pvp off 10s, it restores to ON and announces that it’s enabled again. If it was already OFF beforehand, it remains OFF, consistent with restoring the previous state.
package com.kodari.pvptoggle;
import com.kodari.pvptoggle.command.PvPCommand;
import com.kodari.pvptoggle.state.PvPStateManager;
import com.kodari.pvptoggle.state.WorldListener;
import org.bukkit.Bukkit;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
public final class PvPTogglePlugin extends JavaPlugin {
private YamlConfiguration settings;
private PvPStateManager stateManager;
@Override
public void onEnable() {
loadSettingsSafely();
stateManager = new PvPStateManager(this);
getServer().getPluginManager().registerEvents(new WorldListener(stateManager), this);
PvPCommand commandHandler = new PvPCommand(this, stateManager);
if (getCommand("pvp") == null) {
getLogger().severe("The /pvp command is missing from plugin.yml; disabling the plugin.");
Bukkit.getPluginManager().disablePlugin(this);
return;
}
getCommand("pvp").setExecutor(commandHandler);
getCommand("pvp").setTabCompleter(commandHandler);
stateManager.initialize();
}
@Override
public void onDisable() {
if (stateManager != null) {
stateManager.shutdown();
}
}
public YamlConfiguration getSettings() {
return settings;
}
private void loadSettingsSafely() {
if (!getDataFolder().exists() && !getDataFolder().mkdirs()) {
getLogger().warning("Could not create the plugin data folder; configuration defaults will be used.");
}
File configFile = new File(getDataFolder(), "config.yml");
if (!configFile.exists()) {
saveResource("config.yml", false);
}
YamlConfiguration defaults = new YamlConfiguration();
try (InputStream resource = getResource("config.yml")) {
if (resource == null) {
throw new IOException("Embedded config.yml is missing.");
}
defaults.load(new InputStreamReader(resource, StandardCharsets.UTF_8));
} catch (IOException | InvalidConfigurationException exception) {
getLogger().severe("Could not load embedded defaults: " + exception.getMessage());
}
YamlConfiguration loaded = new YamlConfiguration();
try {
loaded.load(configFile);
} catch (IOException | InvalidConfigurationException exception) {
getLogger().warning("config.yml is invalid; using safe defaults. " + exception.getMessage());
loaded = new YamlConfiguration();
loaded.setDefaults(defaults);
loaded.options().copyDefaults(true);
try {
loaded.save(configFile);
} catch (IOException saveException) {
getLogger().warning("Could not replace invalid config.yml: " + saveException.getMessage());
}
}
loaded.setDefaults(defaults);
loaded.options().copyDefaults(true);
settings = loaded;
}
}