Merge pull request #3014 from Multiverse/ben/mv5/a-lot-of-checkstyle

Fix a lot of checkstyles throughout
This commit is contained in:
Ben Woo 2023-09-12 00:29:14 +08:00 committed by GitHub
commit 9dbe7e20ad
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
42 changed files with 299 additions and 119 deletions

View File

@ -161,6 +161,8 @@
<property name="ignoreSetter" value="true"/> <property name="ignoreSetter" value="true"/>
<property name="setterCanReturnItsClass" value="true"/> <property name="setterCanReturnItsClass" value="true"/>
<property name="ignoreAbstractMethods" value="true"/> <property name="ignoreAbstractMethods" value="true"/>
<!-- Not smart enough -->
<property name="severity" value="ignore"/>
</module> </module>
<module name="IllegalCatch"/> <module name="IllegalCatch"/>
<module name="IllegalThrows"/> <module name="IllegalThrows"/>
@ -381,7 +383,8 @@
<module name="OuterTypeFilename"/> <module name="OuterTypeFilename"/>
<module name="TodoComment"> <module name="TodoComment">
<property name="format" value="TODO"/> <property name="format" value="TODO"/>
<property name="severity" value="warning"/> <!-- TODO change back to warning after MV5 -->
<property name="severity" value="info"/>
</module> </module>
<module name="TrailingComment"> <module name="TrailingComment">
<property name="legalComment" value="^\sSUPPRESS CHECKSTYLE:"/> <property name="legalComment" value="^\sSUPPRESS CHECKSTYLE:"/>
@ -404,6 +407,7 @@
RECORD_COMPONENT_DEF"/> RECORD_COMPONENT_DEF"/>
</module> </module>
<module name="AbstractClassName"> <module name="AbstractClassName">
<property name="ignoreName" value="true"/>
<message key="name.invalidPattern" <message key="name.invalidPattern"
value="Abstract class name ''{0}'' must match pattern ''{1}''."/> value="Abstract class name ''{0}'' must match pattern ''{1}''."/>
</module> </module>

View File

@ -84,12 +84,16 @@ public class MultiverseCore extends JavaPlugin implements MVCore {
@Override @Override
public void onLoad() { public void onLoad() {
// Create our DataFolder
getDataFolder().mkdirs();
// Setup our Logging // Setup our Logging
Logging.init(this); Logging.init(this);
// Create our DataFolder
if (!getDataFolder().exists() && !getDataFolder().mkdirs()) {
Logging.severe("Failed to create data folder!");
getServer().getPluginManager().disablePlugin(this);
return;
}
// Register our config classes // Register our config classes
SerializationConfig.registerAll(WorldProperties.class); SerializationConfig.registerAll(WorldProperties.class);
SerializationConfig.initLogging(Logging.getLogger()); SerializationConfig.initLogging(Logging.getLogger());
@ -373,6 +377,7 @@ public class MultiverseCore extends JavaPlugin implements MVCore {
* *
* @param contractOrImpl The contract or concrete implementation to get the best instance of * @param contractOrImpl The contract or concrete implementation to get the best instance of
* @param qualifiers The set of qualifiers that must match this service definition * @param qualifiers The set of qualifiers that must match this service definition
* @param <T> The type of the contract to get
* @return An instance of the contract or impl if it is a service and is already instantiated, null otherwise * @return An instance of the contract or impl if it is a service and is already instantiated, null otherwise
* @throws MultiException if there was an error during service lookup * @throws MultiException if there was an error during service lookup
*/ */

View File

@ -91,10 +91,10 @@ public class GamerulesCommand extends MultiverseCommand {
ParsedCommandFlags parsedFlags = parseFlags(flags); ParsedCommandFlags parsedFlags = parseFlags(flags);
ContentDisplay.create() ContentDisplay.create()
.addContent(new MapContentProvider<>(getGameRuleMap(world.getBukkitWorld().getOrNull())) // TODO: Handle null .addContent(MapContentProvider.forContent(getGameRuleMap(world.getBukkitWorld().getOrNull())) // TODO: Handle null
.withKeyColor(ChatColor.AQUA) .withKeyColor(ChatColor.AQUA)
.withValueColor(ChatColor.WHITE)) .withValueColor(ChatColor.WHITE))
.withSendHandler(new PagedSendHandler() .withSendHandler(PagedSendHandler.create()
.withHeader(this.getTitle(issuer, world.getBukkitWorld().getOrNull())) .withHeader(this.getTitle(issuer, world.getBukkitWorld().getOrNull()))
.doPagination(true) .doPagination(true)
.withTargetPage(parsedFlags.flagValue(PAGE_FLAG, 1)) .withTargetPage(parsedFlags.flagValue(PAGE_FLAG, 1))

View File

@ -28,6 +28,13 @@ class MVCoreConfigNodes {
return node; return node;
} }
// BEGIN CHECKSTYLE-SUPPRESSION: Javadoc
// BEGIN CHECKSTYLE-SUPPRESSION: MemberName
// BEGIN CHECKSTYLE-SUPPRESSION: Abbreviation
// BEGIN CHECKSTYLE-SUPPRESSION: VisibilityModifier
// BEGIN CHECKSTYLE-SUPPRESSION: MultipleStringLiterals
// BEGIN CHECKSTYLE-SUPPRESSION: LineLength
// TODO: hacky way to get the header to the top of the file // TODO: hacky way to get the header to the top of the file
private final ConfigHeaderNode HEADER = node(ConfigHeaderNode.builder("world") private final ConfigHeaderNode HEADER = node(ConfigHeaderNode.builder("world")
.comment("####################################################################################################") .comment("####################################################################################################")
@ -53,12 +60,12 @@ class MVCoreConfigNodes {
.comment("") .comment("")
.build()); .build());
// private final ConfigHeaderNode WORLD_HEADER = node(ConfigHeaderNode.builder("world") //private final ConfigHeaderNode WORLD_HEADER = node(ConfigHeaderNode.builder("world")
// .comment("") // .comment("")
// .comment("") // .comment("")
// .build()); // .build());
public final ConfigNode<Boolean> ENFORCE_ACCESS = node(ConfigNode.builder("world.enforce-access", Boolean.class) final ConfigNode<Boolean> ENFORCE_ACCESS = node(ConfigNode.builder("world.enforce-access", Boolean.class)
.comment("This setting will prevent players from entering worlds they don't have access to.") .comment("This setting will prevent players from entering worlds they don't have access to.")
.comment("If this is set to false, players will be able to enter any world they want.") .comment("If this is set to false, players will be able to enter any world they want.")
.comment("If this is set to true, players will only be able to enter worlds they have") .comment("If this is set to true, players will only be able to enter worlds they have")
@ -67,7 +74,7 @@ class MVCoreConfigNodes {
.name("enforce-access") .name("enforce-access")
.build()); .build());
public final ConfigNode<Boolean> ENFORCE_GAMEMODE = node(ConfigNode.builder("world.enforce-gamemode", Boolean.class) final ConfigNode<Boolean> ENFORCE_GAMEMODE = node(ConfigNode.builder("world.enforce-gamemode", Boolean.class)
.comment("") .comment("")
.comment("Sets whether Multiverse will should enforce gamemode on world change.") .comment("Sets whether Multiverse will should enforce gamemode on world change.")
.comment("If enabled, players will be forced into the gamemode of the world they are entering, unless they have") .comment("If enabled, players will be forced into the gamemode of the world they are entering, unless they have")
@ -76,14 +83,14 @@ class MVCoreConfigNodes {
.name("enforce-gamemode") .name("enforce-gamemode")
.build()); .build());
public final ConfigNode<Boolean> AUTO_PURGE_ENTITIES = node(ConfigNode.builder("world.auto-purge-entities", Boolean.class) final ConfigNode<Boolean> AUTO_PURGE_ENTITIES = node(ConfigNode.builder("world.auto-purge-entities", Boolean.class)
.comment("") .comment("")
.comment("Sets whether Multiverse will purge mobs and entities with be automatically.") .comment("Sets whether Multiverse will purge mobs and entities with be automatically.")
.defaultValue(false) .defaultValue(false)
.name("auto-purge-entities") .name("auto-purge-entities")
.build()); .build());
public final ConfigNode<Boolean> TELEPORT_INTERCEPT = node(ConfigNode.builder("world.teleport-intercept", Boolean.class) final ConfigNode<Boolean> TELEPORT_INTERCEPT = node(ConfigNode.builder("world.teleport-intercept", Boolean.class)
.comment("") .comment("")
.comment("If this is set to true, Multiverse will enforce access permissions for all teleportation,") .comment("If this is set to true, Multiverse will enforce access permissions for all teleportation,")
.comment("including teleportation from other plugins.") .comment("including teleportation from other plugins.")
@ -96,7 +103,7 @@ class MVCoreConfigNodes {
.comment("") .comment("")
.build()); .build());
public final ConfigNode<Boolean> FIRST_SPAWN_OVERRIDE = node(ConfigNode.builder("spawn.first-spawn-override", Boolean.class) final ConfigNode<Boolean> FIRST_SPAWN_OVERRIDE = node(ConfigNode.builder("spawn.first-spawn-override", Boolean.class)
.comment("Sets whether Multiverse will override the first spawn location of a world.") .comment("Sets whether Multiverse will override the first spawn location of a world.")
.comment("If enabled, Multiverse will set the first spawn location of a world to the spawn location of the world.") .comment("If enabled, Multiverse will set the first spawn location of a world to the spawn location of the world.")
.comment("If disabled, it will default to server.properties settings.") .comment("If disabled, it will default to server.properties settings.")
@ -104,7 +111,7 @@ class MVCoreConfigNodes {
.name("first-spawn-override") .name("first-spawn-override")
.build()); .build());
public final ConfigNode<String> FIRST_SPAWN_LOCATION = node(ConfigNode.builder("spawn.first-spawn-location", String.class) final ConfigNode<String> FIRST_SPAWN_LOCATION = node(ConfigNode.builder("spawn.first-spawn-location", String.class)
.comment("") .comment("")
.comment("Sets the world that Multiverse will use as the location for players that first join the server.") .comment("Sets the world that Multiverse will use as the location for players that first join the server.")
.comment("This only applies if first-spawn-override is set to true.") .comment("This only applies if first-spawn-override is set to true.")
@ -117,14 +124,14 @@ class MVCoreConfigNodes {
.comment("") .comment("")
.build()); .build());
public final ConfigNode<Boolean> USE_CUSTOM_PORTAL_SEARCH = node(ConfigNode.builder("portal.use-custom-portal-search", Boolean.class) final ConfigNode<Boolean> USE_CUSTOM_PORTAL_SEARCH = node(ConfigNode.builder("portal.use-custom-portal-search", Boolean.class)
.comment("This config option defines whether or not Multiverse should interfere with's Bukkit's default portal search radius.") .comment("This config option defines whether or not Multiverse should interfere with's Bukkit's default portal search radius.")
.comment("Setting it to false would mean you want to simply let Bukkit decides the search radius itself.") .comment("Setting it to false would mean you want to simply let Bukkit decides the search radius itself.")
.defaultValue(false) .defaultValue(false)
.name("use-custom-portal-search") .name("use-custom-portal-search")
.build()); .build());
public final ConfigNode<Integer> CUSTOM_PORTAL_SEARCH_RADIUS = node(ConfigNode.builder("portal.custom-portal-search-radius", Integer.class) final ConfigNode<Integer> CUSTOM_PORTAL_SEARCH_RADIUS = node(ConfigNode.builder("portal.custom-portal-search-radius", Integer.class)
.comment("") .comment("")
.comment("This config option defines the search radius Multiverse should use when searching for a portal.") .comment("This config option defines the search radius Multiverse should use when searching for a portal.")
.comment("This only applies if use-custom-portal-search is set to true.") .comment("This only applies if use-custom-portal-search is set to true.")
@ -140,14 +147,14 @@ class MVCoreConfigNodes {
.comment("") .comment("")
.build()); .build());
public final ConfigNode<Boolean> ENABLE_CHAT_PREFIX = node(ConfigNode.builder("messaging.enable-chat-prefix", Boolean.class) final ConfigNode<Boolean> ENABLE_CHAT_PREFIX = node(ConfigNode.builder("messaging.enable-chat-prefix", Boolean.class)
.comment("This config option defines whether or not Multiverse should prefix the chat with the world name.") .comment("This config option defines whether or not Multiverse should prefix the chat with the world name.")
.comment("This only applies if use-custom-portal-search is set to true.") .comment("This only applies if use-custom-portal-search is set to true.")
.defaultValue(false) .defaultValue(false)
.name("enable-chat-prefix") .name("enable-chat-prefix")
.build()); .build());
public final ConfigNode<String> CHAT_PREFIX_FORMAT = node(ConfigNode.builder("messaging.chat-prefix-format", String.class) final ConfigNode<String> CHAT_PREFIX_FORMAT = node(ConfigNode.builder("messaging.chat-prefix-format", String.class)
.comment("") .comment("")
.comment("This config option defines the format Multiverse should use when prefixing the chat with the world name.") .comment("This config option defines the format Multiverse should use when prefixing the chat with the world name.")
.comment("This only applies if enable-chat-prefix is set to true.") .comment("This only applies if enable-chat-prefix is set to true.")
@ -155,7 +162,7 @@ class MVCoreConfigNodes {
.name("chat-prefix-format") .name("chat-prefix-format")
.build()); .build());
public final ConfigNode<Boolean> REGISTER_PAPI_HOOK = node(ConfigNode.builder("messaging.register-papi-hook", Boolean.class) final ConfigNode<Boolean> REGISTER_PAPI_HOOK = node(ConfigNode.builder("messaging.register-papi-hook", Boolean.class)
.comment("") .comment("")
.comment("This config option defines whether or not Multiverse should register the PlaceholderAPI hook.") .comment("This config option defines whether or not Multiverse should register the PlaceholderAPI hook.")
.comment("This only applies if PlaceholderAPI is installed.") .comment("This only applies if PlaceholderAPI is installed.")
@ -168,7 +175,7 @@ class MVCoreConfigNodes {
.comment("") .comment("")
.build()); .build());
public final ConfigNode<Integer> GLOBAL_DEBUG = node(ConfigNode.builder("misc.global-debug", Integer.class) final ConfigNode<Integer> GLOBAL_DEBUG = node(ConfigNode.builder("misc.global-debug", Integer.class)
.comment("This is our debug flag to help identify issues with Multiverse.") .comment("This is our debug flag to help identify issues with Multiverse.")
.comment("If you are having issues with Multiverse, please set this to 3 and then post your log to pastebin.com") .comment("If you are having issues with Multiverse, please set this to 3 and then post your log to pastebin.com")
.comment("Otherwise, there's no need to touch this. If not instructed by a wiki page or developer.") .comment("Otherwise, there's no need to touch this. If not instructed by a wiki page or developer.")
@ -190,7 +197,7 @@ class MVCoreConfigNodes {
}) })
.build()); .build());
public final ConfigNode<Boolean> SILENT_START = node(ConfigNode.builder("misc.silent-start", Boolean.class) final ConfigNode<Boolean> SILENT_START = node(ConfigNode.builder("misc.silent-start", Boolean.class)
.comment("") .comment("")
.comment("If true, the startup console messages will no longer show.") .comment("If true, the startup console messages will no longer show.")
.defaultValue(false) .defaultValue(false)
@ -198,14 +205,14 @@ class MVCoreConfigNodes {
.onSetValue((oldValue, newValue) -> Logging.setShowingConfig(!newValue)) .onSetValue((oldValue, newValue) -> Logging.setShowingConfig(!newValue))
.build()); .build());
public final ConfigNode<Boolean> SHOW_DONATION_MESSAGE = node(ConfigNode.builder("misc.show-donation-message", Boolean.class) final ConfigNode<Boolean> SHOW_DONATION_MESSAGE = node(ConfigNode.builder("misc.show-donation-message", Boolean.class)
.comment("") .comment("")
.comment("If you don't want to donate, you can set this to false and Multiverse will stop nagging you.") .comment("If you don't want to donate, you can set this to false and Multiverse will stop nagging you.")
.defaultValue(true) .defaultValue(true)
.name("show-donation-message") .name("show-donation-message")
.build()); .build());
public final ConfigNode<Double> VERSION = node(ConfigNode.builder("version", Double.class) final ConfigNode<Double> VERSION = node(ConfigNode.builder("version", Double.class)
.comment("") .comment("")
.comment("") .comment("")
.comment("This just signifies the version number so we can see what version of config you have.") .comment("This just signifies the version number so we can see what version of config you have.")
@ -213,4 +220,11 @@ class MVCoreConfigNodes {
.defaultValue(MVCoreConfig.CONFIG_VERSION) .defaultValue(MVCoreConfig.CONFIG_VERSION)
.name(null) .name(null)
.build()); .build());
// END CHECKSTYLE-SUPPRESSION: Javadoc
// END CHECKSTYLE-SUPPRESSION: MemberName
// END CHECKSTYLE-SUPPRESSION: Abbreviation
// END CHECKSTYLE-SUPPRESSION: VisibilityModifier
// END CHECKSTYLE-SUPPRESSION: MultipleStringLiterals
// END CHECKSTYLE-SUPPRESSION: LineLength
} }

View File

@ -29,7 +29,11 @@ public class CommentedYamlConfigHandle extends FileConfigHandle<CommentedConfigu
return new Builder(configPath); return new Builder(configPath);
} }
protected CommentedYamlConfigHandle(@NotNull Path configPath, @Nullable Logger logger, @Nullable NodeGroup nodes, @Nullable ConfigMigrator migrator) { protected CommentedYamlConfigHandle(
@NotNull Path configPath,
@Nullable Logger logger,
@Nullable NodeGroup nodes,
@Nullable ConfigMigrator migrator) {
super(configPath, logger, nodes, migrator); super(configPath, logger, nodes, migrator);
} }
@ -64,10 +68,15 @@ public class CommentedYamlConfigHandle extends FileConfigHandle<CommentedConfigu
} }
} }
if (node instanceof ValueNode valueNode) { if (node instanceof ValueNode valueNode) {
set(valueNode, oldConfig.getObject(valueNode.getPath(), valueNode.getType(), valueNode.getDefaultValue())).onFailure(e -> { //noinspection unchecked
Logging.warning("Failed to set node " + valueNode.getPath() + " to " + valueNode.getDefaultValue()); set(valueNode, oldConfig.getObject(
setDefault(valueNode); valueNode.getPath(),
}); valueNode.getType(),
valueNode.getDefaultValue())).onFailure(e -> {
Logging.warning("Failed to set node " + valueNode.getPath()
+ " to " + valueNode.getDefaultValue());
setDefault(valueNode);
});
} }
}); });
} }
@ -81,6 +90,9 @@ public class CommentedYamlConfigHandle extends FileConfigHandle<CommentedConfigu
return Try.run(() -> config.save()); return Try.run(() -> config.save());
} }
/**
* Builder for {@link CommentedYamlConfigHandle}.
*/
public static class Builder extends FileConfigHandle.Builder<CommentedConfiguration, Builder> { public static class Builder extends FileConfigHandle.Builder<CommentedConfiguration, Builder> {
protected Builder(@NotNull Path configPath) { protected Builder(@NotNull Path configPath) {

View File

@ -13,6 +13,12 @@ import java.util.logging.Logger;
* Configuration handle for a single configuration section. * Configuration handle for a single configuration section.
*/ */
public class ConfigurationSectionHandle extends GenericConfigHandle<ConfigurationSection> { public class ConfigurationSectionHandle extends GenericConfigHandle<ConfigurationSection> {
/**
* Creates a new builder for a {@link ConfigurationSectionHandle}.
*
* @param configurationSection The configuration section.
* @return The builder.
*/
public static Builder<? extends Builder> builder(@NotNull ConfigurationSection configurationSection) { public static Builder<? extends Builder> builder(@NotNull ConfigurationSection configurationSection) {
return new Builder<>(configurationSection); return new Builder<>(configurationSection);
} }

View File

@ -31,16 +31,13 @@ public class DestinationsProvider {
private static final String PERMISSION_PREFIX = "multiverse.teleport."; private static final String PERMISSION_PREFIX = "multiverse.teleport.";
private final PluginManager pluginManager; private final PluginManager pluginManager;
private final SafeTTeleporter safeTTeleporter; private final SafeTTeleporter safetyTeleporter;
private final Map<String, Destination<?>> destinationMap; private final Map<String, Destination<?>> destinationMap;
/**
* Creates a new destinations provider.
*/
@Inject @Inject
public DestinationsProvider(@NotNull PluginManager pluginManager, @NotNull SafeTTeleporter safeTTeleporter) { DestinationsProvider(@NotNull PluginManager pluginManager, @NotNull SafeTTeleporter safetyTeleporter) {
this.pluginManager = pluginManager; this.pluginManager = pluginManager;
this.safeTTeleporter = safeTTeleporter; this.safetyTeleporter = safetyTeleporter;
this.destinationMap = new HashMap<>(); this.destinationMap = new HashMap<>();
} }
@ -66,9 +63,9 @@ public class DestinationsProvider {
* @param deststring The current destination string. * @param deststring The current destination string.
* @return A collection of tab completions. * @return A collection of tab completions.
*/ */
public @NotNull Collection<String> suggestDestinations(@NotNull BukkitCommandIssuer issuer, public @NotNull Collection<String> suggestDestinations(
@Nullable String deststring @NotNull BukkitCommandIssuer issuer,
) { @Nullable String deststring) {
return destinationMap.values().stream() return destinationMap.values().stream()
.filter(destination -> issuer.hasPermission(PERMISSION_PREFIX + "self." + destination.getIdentifier()) .filter(destination -> issuer.hasPermission(PERMISSION_PREFIX + "self." + destination.getIdentifier())
|| issuer.hasPermission(PERMISSION_PREFIX + "other." + destination.getIdentifier())) || issuer.hasPermission(PERMISSION_PREFIX + "other." + destination.getIdentifier()))
@ -129,11 +126,12 @@ public class DestinationsProvider {
* @param teleporter The teleporter. * @param teleporter The teleporter.
* @param teleportee The teleportee. * @param teleportee The teleportee.
* @param destination The destination. * @param destination The destination.
* @return The async teleport result.
*/ */
public CompletableFuture<TeleportResult> playerTeleportAsync(@NotNull BukkitCommandIssuer teleporter, public CompletableFuture<TeleportResult> playerTeleportAsync(
@NotNull Player teleportee, @NotNull BukkitCommandIssuer teleporter,
@NotNull ParsedDestination<?> destination @NotNull Player teleportee,
) { @NotNull ParsedDestination<?> destination) {
if (!checkTeleportPermissions(teleporter, teleportee, destination)) { if (!checkTeleportPermissions(teleporter, teleportee, destination)) {
return CompletableFuture.completedFuture(TeleportResult.FAIL_PERMISSION); return CompletableFuture.completedFuture(TeleportResult.FAIL_PERMISSION);
} }
@ -146,14 +144,15 @@ public class DestinationsProvider {
* @param teleporter The teleporter. * @param teleporter The teleporter.
* @param teleportee The teleportee. * @param teleportee The teleportee.
* @param destination The destination. * @param destination The destination.
* @return The async teleport result.
*/ */
public CompletableFuture<TeleportResult> teleportAsync(@NotNull BukkitCommandIssuer teleporter, public CompletableFuture<TeleportResult> teleportAsync(
@NotNull Entity teleportee, @NotNull BukkitCommandIssuer teleporter,
@NotNull ParsedDestination<?> destination @NotNull Entity teleportee,
) { @NotNull ParsedDestination<?> destination) {
Teleporter teleportHandler = destination.getDestination().getTeleporter(); Teleporter teleportHandler = destination.getDestination().getTeleporter();
if (teleportHandler == null) { if (teleportHandler == null) {
teleportHandler = safeTTeleporter; teleportHandler = safetyTeleporter;
} }
return teleportHandler.teleportAsync(teleporter, teleportee, destination); return teleportHandler.teleportAsync(teleporter, teleportee, destination);
} }
@ -166,7 +165,8 @@ public class DestinationsProvider {
* @param destination The destination. * @param destination The destination.
* @return True if the teleporter has permission, false otherwise. * @return True if the teleporter has permission, false otherwise.
*/ */
public boolean checkTeleportPermissions(CommandIssuer teleporter, Entity teleportee, ParsedDestination<?> destination) { public boolean checkTeleportPermissions(
CommandIssuer teleporter, Entity teleportee, ParsedDestination<?> destination) {
// TODO: Move permission checking to a separate class // TODO: Move permission checking to a separate class
String permission = PERMISSION_PREFIX String permission = PERMISSION_PREFIX
+ (teleportee.equals(teleporter.getIssuer()) ? "self" : "other") + "." + (teleportee.equals(teleporter.getIssuer()) ? "self" : "other") + "."

View File

@ -12,13 +12,16 @@ import org.jvnet.hk2.annotations.Service;
import java.util.Collection; import java.util.Collection;
/**
* {@link Destination} implementation for anchors.
*/
@Service @Service
public class AnchorDestination implements Destination<AnchorDestinationInstance> { public class AnchorDestination implements Destination<AnchorDestinationInstance> {
private final AnchorManager anchorManager; private final AnchorManager anchorManager;
@Inject @Inject
public AnchorDestination(AnchorManager anchorManager) { AnchorDestination(AnchorManager anchorManager) {
this.anchorManager = anchorManager; this.anchorManager = anchorManager;
} }

View File

@ -7,6 +7,9 @@ import org.bukkit.util.Vector;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
/**
* Destination instance implementation for the {@link AnchorDestination}.
*/
public class AnchorDestinationInstance implements DestinationInstance { public class AnchorDestinationInstance implements DestinationInstance {
private final String anchorName; private final String anchorName;
private final Location anchorLocation; private final Location anchorLocation;
@ -17,7 +20,7 @@ public class AnchorDestinationInstance implements DestinationInstance {
* @param anchorName The name of the anchor. * @param anchorName The name of the anchor.
* @param anchorLocation The location of the anchor. * @param anchorLocation The location of the anchor.
*/ */
public AnchorDestinationInstance(@NotNull String anchorName, @NotNull Location anchorLocation) { AnchorDestinationInstance(@NotNull String anchorName, @NotNull Location anchorLocation) {
this.anchorName = anchorName; this.anchorName = anchorName;
this.anchorLocation = anchorLocation; this.anchorLocation = anchorLocation;
} }

View File

@ -14,11 +14,14 @@ import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/**
* {@link Destination} implementation for beds.
*/
@Service @Service
public class BedDestination implements Destination<BedDestinationInstance> { public class BedDestination implements Destination<BedDestinationInstance> {
public static final String OWN_BED_STRING = "playerbed"; static final String OWN_BED_STRING = "playerbed";
public BedDestination() { BedDestination() {
} }
/** /**

View File

@ -8,6 +8,9 @@ import org.bukkit.util.Vector;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
/**
* Destination instance implementation for the {@link BedDestination}.
*/
public class BedDestinationInstance implements DestinationInstance { public class BedDestinationInstance implements DestinationInstance {
private final Player player; private final Player player;
@ -16,7 +19,7 @@ public class BedDestinationInstance implements DestinationInstance {
* *
* @param player The player whose bed to use. * @param player The player whose bed to use.
*/ */
public BedDestinationInstance(Player player) { BedDestinationInstance(Player player) {
this.player = player; this.player = player;
} }

View File

@ -15,13 +15,16 @@ import org.jvnet.hk2.annotations.Service;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
/**
* {@link Destination} implementation for cannons.
*/
@Service @Service
public class CannonDestination implements Destination<CannonDestinationInstance> { public class CannonDestination implements Destination<CannonDestinationInstance> {
private final WorldManager worldManager; private final WorldManager worldManager;
@Inject @Inject
public CannonDestination(WorldManager worldManager) { CannonDestination(WorldManager worldManager) {
this.worldManager = worldManager; this.worldManager = worldManager;
} }

View File

@ -7,6 +7,9 @@ import org.bukkit.util.Vector;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
/**
* Destination instance implementation for the {@link CannonDestination}.
*/
public class CannonDestinationInstance implements DestinationInstance { public class CannonDestinationInstance implements DestinationInstance {
private final Location location; private final Location location;
private final double speed; private final double speed;
@ -17,7 +20,7 @@ public class CannonDestinationInstance implements DestinationInstance {
* @param location The location to teleport to. * @param location The location to teleport to.
* @param speed The speed to fire the player at. * @param speed The speed to fire the player at.
*/ */
public CannonDestinationInstance(@NotNull Location location, double speed) { CannonDestinationInstance(@NotNull Location location, double speed) {
this.location = location; this.location = location;
this.speed = speed; this.speed = speed;
} }

View File

@ -15,6 +15,9 @@ import org.jvnet.hk2.annotations.Service;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
/**
* {@link Destination} implementation for exact locations.
*/
@Service @Service
public class ExactDestination implements Destination<ExactDestinationInstance> { public class ExactDestination implements Destination<ExactDestinationInstance> {

View File

@ -7,6 +7,9 @@ import org.bukkit.util.Vector;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
/**
* Destination instance implementation for the {@link ExactDestination}.
*/
public class ExactDestinationInstance implements DestinationInstance { public class ExactDestinationInstance implements DestinationInstance {
private final Location location; private final Location location;
@ -15,7 +18,7 @@ public class ExactDestinationInstance implements DestinationInstance {
* *
* @param location The location to teleport to. * @param location The location to teleport to.
*/ */
public ExactDestinationInstance(Location location) { ExactDestinationInstance(Location location) {
this.location = location; this.location = location;
} }

View File

@ -13,12 +13,15 @@ import org.jvnet.hk2.annotations.Service;
import java.util.Collection; import java.util.Collection;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/**
* {@link Destination} implementation for players.s
*/
@Service @Service
public class PlayerDestination implements Destination<PlayerDestinationInstance> { public class PlayerDestination implements Destination<PlayerDestinationInstance> {
/** /**
* Creates a new instance of the PlayerDestination. * Creates a new instance of the PlayerDestination.
*/ */
public PlayerDestination() { PlayerDestination() {
} }
/** /**

View File

@ -8,6 +8,9 @@ import org.bukkit.util.Vector;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
/**
* Destination instance implementation for the {@link PlayerDestination}.
*/
public class PlayerDestinationInstance implements DestinationInstance { public class PlayerDestinationInstance implements DestinationInstance {
private final Player player; private final Player player;
@ -16,7 +19,7 @@ public class PlayerDestinationInstance implements DestinationInstance {
* *
* @param player The player whose location to go to. * @param player The player whose location to go to.
*/ */
public PlayerDestinationInstance(Player player) { PlayerDestinationInstance(Player player) {
this.player = player; this.player = player;
} }

View File

@ -14,6 +14,9 @@ import org.jvnet.hk2.annotations.Service;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
/**
* {@link Destination} implementation for exact locations.
*/
@Service @Service
public class WorldDestination implements Destination<WorldDestinationInstance> { public class WorldDestination implements Destination<WorldDestinationInstance> {
@ -21,7 +24,7 @@ public class WorldDestination implements Destination<WorldDestinationInstance> {
private final LocationManipulation locationManipulation; private final LocationManipulation locationManipulation;
@Inject @Inject
public WorldDestination(WorldManager worldManager, LocationManipulation locationManipulation) { WorldDestination(WorldManager worldManager, LocationManipulation locationManipulation) {
this.worldManager = worldManager; this.worldManager = worldManager;
this.locationManipulation = locationManipulation; this.locationManipulation = locationManipulation;
} }

View File

@ -8,6 +8,9 @@ import org.bukkit.util.Vector;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
/**
* Destination instance implementation for the {@link WorldDestination}.
*/
public class WorldDestinationInstance implements DestinationInstance { public class WorldDestinationInstance implements DestinationInstance {
private final LoadedMultiverseWorld world; private final LoadedMultiverseWorld world;
private final String direction; private final String direction;
@ -16,9 +19,11 @@ public class WorldDestinationInstance implements DestinationInstance {
/** /**
* Constructor. * Constructor.
* *
* @param world The world to teleport to. * @param world The world to teleport to.
* @param direction The direction to face.
* @param yaw The yaw to face.
*/ */
public WorldDestinationInstance(@NotNull LoadedMultiverseWorld world, @Nullable String direction, float yaw) { WorldDestinationInstance(@NotNull LoadedMultiverseWorld world, @Nullable String direction, float yaw) {
this.world = world; this.world = world;
this.direction = direction; this.direction = direction;
this.yaw = yaw; this.yaw = yaw;

View File

@ -28,7 +28,7 @@ public class ContentDisplay {
private final List<ContentProvider> contentParsers = new ArrayList<>(); private final List<ContentProvider> contentParsers = new ArrayList<>();
private SendHandler sendHandler = DefaultSendHandler.getInstance(); private SendHandler sendHandler = DefaultSendHandler.getInstance();
public ContentDisplay() { ContentDisplay() {
} }
/** /**

View File

@ -3,10 +3,15 @@ package com.onarandombox.MultiverseCore.display.filters;
/** /**
* Default implementation of {@link ContentFilter} that doesn't filter anything. * Default implementation of {@link ContentFilter} that doesn't filter anything.
*/ */
public class DefaultContentFilter implements ContentFilter { public final class DefaultContentFilter implements ContentFilter {
public static DefaultContentFilter instance; private static DefaultContentFilter instance;
/**
* Gets the singleton instance of this class.
*
* @return The singleton instance of this class.
*/
public static DefaultContentFilter get() { public static DefaultContentFilter get() {
if (instance == null) { if (instance == null) {
instance = new DefaultContentFilter(); instance = new DefaultContentFilter();

View File

@ -18,7 +18,7 @@ public class RegexContentFilter implements ContentFilter {
/** /**
* Compile regex pattern to create a regex filter. * Compile regex pattern to create a regex filter.
* * <br/>
* When prefixed with 'r=', filter string is used as the full regex pattern. * When prefixed with 'r=', filter string is used as the full regex pattern.
* Else, set to regex that contains the filterString. * Else, set to regex that contains the filterString.
* *
@ -40,7 +40,7 @@ public class RegexContentFilter implements ContentFilter {
private final String regexString; private final String regexString;
private Pattern regexPattern; private Pattern regexPattern;
public RegexContentFilter(@Nullable String regexString) { RegexContentFilter(@Nullable String regexString) {
this.regexString = regexString; this.regexString = regexString;
convertToPattern(); convertToPattern();
} }
@ -85,14 +85,29 @@ public class RegexContentFilter implements ContentFilter {
return hasValidRegex(); return hasValidRegex();
} }
/**
* Check if the regex is valid.
*
* @return True if the regex is valid.
*/
public boolean hasValidRegex() { public boolean hasValidRegex() {
return regexPattern != null; return regexPattern != null;
} }
/**
* Get the regex string.
*
* @return The regex string.
*/
public String getRegexString() { public String getRegexString() {
return regexString; return regexString;
} }
/**
* Get the compiled regex pattern.
*
* @return The compiled regex pattern.
*/
public Pattern getRegexPattern() { public Pattern getRegexPattern() {
return regexPattern; return regexPattern;
} }

View File

@ -18,8 +18,19 @@ import java.util.stream.Collectors;
*/ */
public abstract class BaseSendHandler<T extends BaseSendHandler<?>> implements SendHandler { public abstract class BaseSendHandler<T extends BaseSendHandler<?>> implements SendHandler {
/**
* Header to be displayed.
*/
protected String header = ""; protected String header = "";
/**
* Filter to keep only contents that matches the filter.
*/
protected ContentFilter filter = DefaultContentFilter.get(); protected ContentFilter filter = DefaultContentFilter.get();
/**
* Fallback message to be displayed when there is no content to display.
*/
protected String noContentMessage = String.format("%sThere is no content to display.", ChatColor.RED); protected String noContentMessage = String.format("%sThere is no content to display.", ChatColor.RED);
/** /**
@ -75,9 +86,9 @@ public abstract class BaseSendHandler<T extends BaseSendHandler<?>> implements S
* @param replacements String formatting replacements. * @param replacements String formatting replacements.
* @return Same {@link T} for method chaining. * @return Same {@link T} for method chaining.
*/ */
public T withHeader(@NotNull String header, @NotNull Object...replacements) { public T withHeader(@NotNull String header, @NotNull Object... replacements) {
this.header = String.format(header, replacements); this.header = String.format(header, replacements);
return (T) this; return getT();
} }
/** /**
@ -88,7 +99,7 @@ public abstract class BaseSendHandler<T extends BaseSendHandler<?>> implements S
*/ */
public T withFilter(@NotNull ContentFilter filter) { public T withFilter(@NotNull ContentFilter filter) {
this.filter = filter; this.filter = filter;
return (T) this; return getT();
} }
/** /**
@ -99,6 +110,11 @@ public abstract class BaseSendHandler<T extends BaseSendHandler<?>> implements S
*/ */
public T noContentMessage(@Nullable String message) { public T noContentMessage(@Nullable String message) {
this.noContentMessage = message; this.noContentMessage = message;
return getT();
}
@SuppressWarnings("unchecked")
private @NotNull T getT() {
return (T) this; return (T) this;
} }

View File

@ -5,10 +5,18 @@ import org.jetbrains.annotations.NotNull;
import java.util.List; import java.util.List;
public class DefaultSendHandler implements SendHandler { /**
* Most basic implementation of {@link SendHandler} that just sends content with no formatting.
*/
public final class DefaultSendHandler implements SendHandler {
private static DefaultSendHandler instance; private static DefaultSendHandler instance;
/**
* Gets the singleton instance of this class.
*
* @return The singleton instance of this class.
*/
public static DefaultSendHandler getInstance() { public static DefaultSendHandler getInstance() {
if (instance == null) { if (instance == null) {
instance = new DefaultSendHandler(); instance = new DefaultSendHandler();

View File

@ -23,7 +23,7 @@ public class InlineSendHandler extends BaseSendHandler<InlineSendHandler> {
private String delimiter = ChatColor.WHITE + ", "; private String delimiter = ChatColor.WHITE + ", ";
private String prefix = null; private String prefix = null;
public InlineSendHandler() { InlineSendHandler() {
} }
/** /**

View File

@ -24,10 +24,10 @@ public class PagedSendHandler extends BaseSendHandler<PagedSendHandler> {
private boolean paginate = true; private boolean paginate = true;
private boolean paginateInConsole = false; private boolean paginateInConsole = false;
private boolean padEnd = true; private boolean padEnd = true;
private int linesPerPage = 8; private int linesPerPage = 8; // SUPPRESS CHECKSTYLE: MagicNumberCheck
private int targetPage = 1; private int targetPage = 1;
public PagedSendHandler() { PagedSendHandler() {
} }
/** /**

View File

@ -14,6 +14,7 @@ public interface ContentProvider {
* Parse the object to string(s) and add it to the content. * Parse the object to string(s) and add it to the content.
* *
* @param issuer The target which the content will be displayed to. * @param issuer The target which the content will be displayed to.
* @return The parsed content list.
*/ */
Collection<String> parse(@NotNull BukkitCommandIssuer issuer); Collection<String> parse(@NotNull BukkitCommandIssuer issuer);
} }

View File

@ -29,7 +29,7 @@ public class ListContentProvider<T> implements ContentProvider {
private String format = null; private String format = null;
public ListContentProvider(List<T> list) { ListContentProvider(List<T> list) {
this.list = list; this.list = list;
} }

View File

@ -35,7 +35,7 @@ public class MapContentProvider<K, V> implements ContentProvider {
private ChatColor valueColor = ChatColor.WHITE; private ChatColor valueColor = ChatColor.WHITE;
private String separator = ": "; private String separator = ": ";
public MapContentProvider(Map<K, V> map) { MapContentProvider(Map<K, V> map) {
this.map = map; this.map = map;
} }

View File

@ -7,6 +7,7 @@ import org.bukkit.inventory.ItemStack;
import java.util.HashMap; import java.util.HashMap;
// TODO: Make thsi no static
class ItemEconomy { class ItemEconomy {
private static final String ECONOMY_NAME = "Simple Item Economy"; private static final String ECONOMY_NAME = "Simple Item Economy";

View File

@ -103,7 +103,7 @@ public class MVEconomist {
} }
/** /**
* Pays for a given amount of currency either from the player's economy account or inventory if the currency * Pays for a given amount of currency either from the player's economy account or inventory if the currency.
* *
* @param player the player to take currency from. * @param player the player to take currency from.
* @param price the amount to take. * @param price the amount to take.

View File

@ -17,15 +17,16 @@ public class VaultHandler implements Listener {
private Economy economy; private Economy economy;
public VaultHandler(final Plugin plugin) { VaultHandler(final Plugin plugin) {
Bukkit.getPluginManager().registerEvents(new VaultListener(), plugin); Bukkit.getPluginManager().registerEvents(new VaultListener(), plugin);
setupVaultEconomy(); setupVaultEconomy();
} }
private boolean setupVaultEconomy() { private boolean setupVaultEconomy() {
if (Bukkit.getPluginManager().getPlugin("Vault") != null) { if (Bukkit.getPluginManager().getPlugin("Vault") != null) {
final RegisteredServiceProvider<Economy> economyProvider = final RegisteredServiceProvider<Economy> economyProvider = Bukkit
Bukkit.getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); .getServicesManager()
.getRegistration(net.milkbowl.vault.economy.Economy.class);
if (economyProvider != null) { if (economyProvider != null) {
Logging.fine("Vault economy enabled."); Logging.fine("Vault economy enabled.");
economy = economyProvider.getProvider(); economy = economyProvider.getProvider();
@ -38,7 +39,7 @@ public class VaultHandler implements Listener {
economy = null; economy = null;
} }
return (economy != null); return economy != null;
} }
/** /**
@ -62,7 +63,7 @@ public class VaultHandler implements Listener {
/** /**
* Listens for Vault plugin events. * Listens for Vault plugin events.
*/ */
private class VaultListener implements Listener { private final class VaultListener implements Listener {
@EventHandler @EventHandler
private void vaultEnabled(PluginEnableEvent event) { private void vaultEnabled(PluginEnableEvent event) {
if (event.getPlugin() != null && event.getPlugin().getName().equals("Vault")) { if (event.getPlugin() != null && event.getPlugin().getName().equals("Vault")) {

View File

@ -30,7 +30,7 @@ public final class PluginInjection {
* {@link org.bukkit.plugin.java.JavaPlugin}. * {@link org.bukkit.plugin.java.JavaPlugin}.
* *
* @param pluginBinder The plugin binder for the plugin. * @param pluginBinder The plugin binder for the plugin.
* @return * @return A {@link ServiceLocator} for the plugin.
*/ */
@NotNull @NotNull
public static Try<ServiceLocator> createServiceLocator(@NotNull PluginBinder<?> pluginBinder) { public static Try<ServiceLocator> createServiceLocator(@NotNull PluginBinder<?> pluginBinder) {
@ -74,8 +74,7 @@ public final class PluginInjection {
private PluginInjection( private PluginInjection(
@NotNull PluginBinder<?> pluginBinder, @NotNull PluginBinder<?> pluginBinder,
@NotNull ServiceLocatorFactory serviceLocatorFactory, @NotNull ServiceLocatorFactory serviceLocatorFactory,
@NotNull ServiceLocator serverServiceLocator @NotNull ServiceLocator serverServiceLocator) {
) {
this.pluginBinder = pluginBinder; this.pluginBinder = pluginBinder;
plugin = pluginBinder.getPlugin(); plugin = pluginBinder.getPlugin();
pluginServiceLocator = serviceLocatorFactory.create(plugin.getName(), serverServiceLocator); pluginServiceLocator = serviceLocatorFactory.create(plugin.getName(), serverServiceLocator);
@ -89,16 +88,14 @@ public final class PluginInjection {
@NotNull @NotNull
private static Try<ServiceLocator> createServerServiceLocator( private static Try<ServiceLocator> createServerServiceLocator(
@NotNull ServiceLocatorFactory serviceLocatorFactory, @NotNull ServiceLocatorFactory serviceLocatorFactory,
@NotNull ServiceLocator systemServiceLocator @NotNull ServiceLocator systemServiceLocator) {
) {
return Try.of(() -> serviceLocatorFactory.create("server", systemServiceLocator)) return Try.of(() -> serviceLocatorFactory.create("server", systemServiceLocator))
.andThenTry(locator -> ServiceLocatorUtilities.bind(locator, new ServerBinder())); .andThenTry(locator -> ServiceLocatorUtilities.bind(locator, new ServerBinder()));
} }
@NotNull @NotNull
private static Try<ServiceLocator> createSystemServiceLocator( private static Try<ServiceLocator> createSystemServiceLocator(
@NotNull ServiceLocatorFactory serviceLocatorFactory @NotNull ServiceLocatorFactory serviceLocatorFactory) {
) {
ServiceLocator serviceLocator = serviceLocatorFactory.create("system"); ServiceLocator serviceLocator = serviceLocatorFactory.create("system");
return Try.of(() -> serviceLocator.getService(DynamicConfigurationService.class)) return Try.of(() -> serviceLocator.getService(DynamicConfigurationService.class))
@ -111,15 +108,12 @@ public final class PluginInjection {
@NotNull @NotNull
private static Try<ServiceLocator> populatePluginServiceLocator( private static Try<ServiceLocator> populatePluginServiceLocator(
@NotNull ServiceLocator serviceLocator, @NotNull ServiceLocator serviceLocator,
@NotNull Plugin plugin @NotNull Plugin plugin) {
) {
return Try.of(() -> serviceLocator.getService(DynamicConfigurationService.class)) return Try.of(() -> serviceLocator.getService(DynamicConfigurationService.class))
.mapTry(dynamicConfigurationService -> { .mapTry(dynamicConfigurationService -> {
dynamicConfigurationService dynamicConfigurationService.getPopulator().populate(new ClasspathDescriptorFileFinder(
.getPopulator() plugin.getClass().getClassLoader(),
.populate(new ClasspathDescriptorFileFinder( plugin.getName()));
plugin.getClass().getClassLoader(),
plugin.getName()));
return serviceLocator; return serviceLocator;
}); });
} }

View File

@ -19,11 +19,10 @@ public class MVChatListener implements InjectableListener {
private final MVPlayerListener playerListener; private final MVPlayerListener playerListener;
@Inject @Inject
public MVChatListener( MVChatListener(
MVCoreConfig config, MVCoreConfig config,
WorldManager worldManager, WorldManager worldManager,
MVPlayerListener playerListener MVPlayerListener playerListener) {
) {
this.config = config; this.config = config;
this.worldManager = worldManager; this.worldManager = worldManager;
this.playerListener = playerListener; this.playerListener = playerListener;
@ -52,7 +51,7 @@ public class MVChatListener implements InjectableListener {
} }
String prefix = this.worldManager.getLoadedWorld(world) String prefix = this.worldManager.getLoadedWorld(world)
.map((mvworld) -> mvworld.isHidden() ? "" : mvworld.getAlias()) .map(mvworld -> mvworld.isHidden() ? "" : mvworld.getAlias())
.getOrElse(""); .getOrElse("");
String chat = event.getFormat(); String chat = event.getFormat();

View File

@ -32,10 +32,9 @@ public class MVEntityListener implements InjectableListener {
private final WorldPurger worldPurger; private final WorldPurger worldPurger;
@Inject @Inject
public MVEntityListener( MVEntityListener(
@NotNull WorldManager worldManager, @NotNull WorldManager worldManager,
@NotNull WorldPurger worldPurger @NotNull WorldPurger worldPurger) {
) {
this.worldManager = worldManager; this.worldManager = worldManager;
this.worldPurger = worldPurger; this.worldPurger = worldPurger;
} }
@ -53,7 +52,7 @@ public class MVEntityListener implements InjectableListener {
return; return;
} }
worldManager.getLoadedWorld(player.getWorld()) worldManager.getLoadedWorld(player.getWorld())
.peek((world) -> { .peek(world -> {
if (!world.getHunger() && event.getFoodLevel() < player.getFoodLevel()) { if (!world.getHunger() && event.getFoodLevel() < player.getFoodLevel()) {
event.setCancelled(true); event.setCancelled(true);
} }
@ -70,7 +69,7 @@ public class MVEntityListener implements InjectableListener {
return; return;
} }
worldManager.getLoadedWorld(event.getEntity().getWorld()) worldManager.getLoadedWorld(event.getEntity().getWorld())
.peek((world) -> { .peek(world -> {
if (!world.getAutoHeal()) { if (!world.getAutoHeal()) {
event.setCancelled(true); event.setCancelled(true);
} }
@ -96,7 +95,7 @@ public class MVEntityListener implements InjectableListener {
} }
worldManager.getLoadedWorld(event.getEntity().getWorld()) worldManager.getLoadedWorld(event.getEntity().getWorld())
.peek((world) -> { .peek(world -> {
if (this.worldPurger.shouldWeKillThisCreature(world, event.getEntity())) { if (this.worldPurger.shouldWeKillThisCreature(world, event.getEntity())) {
Logging.finer("Cancelling Creature Spawn Event for: " + event.getEntity()); Logging.finer("Cancelling Creature Spawn Event for: " + event.getEntity());
event.setCancelled(true); event.setCancelled(true);

View File

@ -68,7 +68,7 @@ public class MVPlayerListener implements InjectableListener {
private final Map<String, String> playerWorld = new ConcurrentHashMap<String, String>(); private final Map<String, String> playerWorld = new ConcurrentHashMap<String, String>();
@Inject @Inject
public MVPlayerListener( MVPlayerListener(
MultiverseCore plugin, MultiverseCore plugin,
MVCoreConfig config, MVCoreConfig config,
Provider<WorldManager> worldManagerProvider, Provider<WorldManager> worldManagerProvider,
@ -79,8 +79,7 @@ public class MVPlayerListener implements InjectableListener {
WorldEntryCheckerProvider worldEntryCheckerProvider, WorldEntryCheckerProvider worldEntryCheckerProvider,
Provider<MVCommandManager> commandManagerProvider, Provider<MVCommandManager> commandManagerProvider,
CorePermissionsChecker permissionsChecker, CorePermissionsChecker permissionsChecker,
DestinationsProvider destinationsProvider DestinationsProvider destinationsProvider) {
) {
this.plugin = plugin; this.plugin = plugin;
this.config = config; this.config = config;
this.worldManagerProvider = worldManagerProvider; this.worldManagerProvider = worldManagerProvider;
@ -103,6 +102,8 @@ public class MVPlayerListener implements InjectableListener {
} }
/** /**
* Gets the map of player and the world name they are in.
*
* @return the playerWorld-map * @return the playerWorld-map
*/ */
public Map<String, String> getPlayerWorld() { public Map<String, String> getPlayerWorld() {
@ -111,6 +112,7 @@ public class MVPlayerListener implements InjectableListener {
/** /**
* This method is called when a player respawns. * This method is called when a player respawns.
*
* @param event The Event that was fired. * @param event The Event that was fired.
*/ */
@EventHandler(priority = EventPriority.LOW) @EventHandler(priority = EventPriority.LOW)

View File

@ -34,7 +34,7 @@ public class MVPortalListener implements InjectableListener {
private final WorldManager worldManager; private final WorldManager worldManager;
@Inject @Inject
public MVPortalListener(@NotNull MVCoreConfig config, @NotNull WorldManager worldManager) { MVPortalListener(@NotNull MVCoreConfig config, @NotNull WorldManager worldManager) {
this.config = config; this.config = config;
this.worldManager = worldManager; this.worldManager = worldManager;
} }
@ -118,6 +118,7 @@ public class MVPortalListener implements InjectableListener {
/** /**
* Handles portal search radius adjustment. * Handles portal search radius adjustment.
*
* @param event The Event that was fired. * @param event The Event that was fired.
*/ */
@EventHandler @EventHandler

View File

@ -25,12 +25,13 @@ public class MVWeatherListener implements InjectableListener {
private final WorldManager worldManager; private final WorldManager worldManager;
@Inject @Inject
public MVWeatherListener(WorldManager worldManager) { MVWeatherListener(WorldManager worldManager) {
this.worldManager = worldManager; this.worldManager = worldManager;
} }
/** /**
* This method is called when the weather changes. * This method is called when the weather changes.
*
* @param event The Event that was fired. * @param event The Event that was fired.
*/ */
@EventHandler @EventHandler
@ -39,7 +40,7 @@ public class MVWeatherListener implements InjectableListener {
return; return;
} }
worldManager.getLoadedWorld(event.getWorld()) worldManager.getLoadedWorld(event.getWorld())
.peek((world) -> { .peek(world -> {
if (!world.getAllowWeather()) { if (!world.getAllowWeather()) {
Logging.fine("Cancelling weather for %s as getAllowWeather is false", world.getName()); Logging.fine("Cancelling weather for %s as getAllowWeather is false", world.getName());
event.setCancelled(true); event.setCancelled(true);
@ -49,6 +50,7 @@ public class MVWeatherListener implements InjectableListener {
/** /**
* This method is called when a big storm is going to start. * This method is called when a big storm is going to start.
*
* @param event The Event that was fired. * @param event The Event that was fired.
*/ */
@EventHandler @EventHandler
@ -57,7 +59,7 @@ public class MVWeatherListener implements InjectableListener {
return; return;
} }
worldManager.getLoadedWorld(event.getWorld()) worldManager.getLoadedWorld(event.getWorld())
.peek((world) -> { .peek(world -> {
if (!world.getAllowWeather()) { if (!world.getAllowWeather()) {
Logging.fine("Cancelling thunder for %s as getAllowWeather is false", world.getName()); Logging.fine("Cancelling thunder for %s as getAllowWeather is false", world.getName());
event.setCancelled(true); event.setCancelled(true);

View File

@ -29,7 +29,7 @@ public class MVWorldListener implements InjectableListener {
private final WorldManager worldManager; private final WorldManager worldManager;
@Inject @Inject
public MVWorldListener(WorldManager worldManager) { MVWorldListener(WorldManager worldManager) {
this.worldManager = worldManager; this.worldManager = worldManager;
} }

View File

@ -20,6 +20,7 @@ class GitHubPasteService extends PasteService {
GitHubPasteService(boolean isPrivate) { GitHubPasteService(boolean isPrivate) {
super(GITHUB_POST_REQUEST, ACCESS_TOKEN); super(GITHUB_POST_REQUEST, ACCESS_TOKEN);
this.isPrivate = isPrivate; this.isPrivate = isPrivate;
//noinspection ConstantValue - this is a placeholder that should be replaced with a real access token
if (ACCESS_TOKEN.endsWith("access-token")) { if (ACCESS_TOKEN.endsWith("access-token")) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@ -60,8 +61,8 @@ class GitHubPasteService extends PasteService {
@Override @Override
public String postData(String data) throws PasteFailedException { public String postData(String data) throws PasteFailedException {
try { try {
String stringJSON = this.exec(encodeData(data), ContentType.JSON); String stringJson = this.exec(encodeData(data), ContentType.JSON);
return (String) ((JSONObject) new JSONParser().parse(stringJSON)).get("html_url"); return (String) ((JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(stringJson)).get("html_url");
} catch (IOException | ParseException e) { } catch (IOException | ParseException e) {
throw new PasteFailedException(e); throw new PasteFailedException(e);
} }
@ -74,7 +75,7 @@ class GitHubPasteService extends PasteService {
public String postData(Map<String, String> data) throws PasteFailedException { public String postData(Map<String, String> data) throws PasteFailedException {
try { try {
String stringJSON = this.exec(encodeData(data), ContentType.JSON); String stringJSON = this.exec(encodeData(data), ContentType.JSON);
return (String) ((JSONObject) new JSONParser().parse(stringJSON)).get("html_url"); return (String) ((JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(stringJSON)).get("html_url");
} catch (IOException | ParseException e) { } catch (IOException | ParseException e) {
throw new PasteFailedException(e); throw new PasteFailedException(e);
} }

View File

@ -38,12 +38,19 @@ public enum AllowedPortalType {
/** /**
* Gets the text. * Gets the text.
*
* @return The text. * @return The text.
*/ */
public PortalType getActualPortalType() { public PortalType getActualPortalType() {
return this.type; return this.type;
} }
/**
* Checks if the given portal type is allowed.
*
* @param portalType The portal type.
* @return True if allowed, else false.
*/
public boolean isPortalAllowed(PortalType portalType) { public boolean isPortalAllowed(PortalType portalType) {
return this != NONE && (getActualPortalType() == portalType || this == ALL); return this != NONE && (getActualPortalType() == portalType || this == ALL);
} }

View File

@ -19,8 +19,14 @@ import java.util.List;
* Represents a world handled by Multiverse which has all the custom properties provided by Multiverse. * Represents a world handled by Multiverse which has all the custom properties provided by Multiverse.
*/ */
public class MultiverseWorld { public class MultiverseWorld {
/**
* This world's name.
*/
protected final String worldName; protected final String worldName;
/**
* This world's configuration.
*/
protected WorldConfig worldConfig; protected WorldConfig worldConfig;
MultiverseWorld(String worldName, WorldConfig worldConfig) { MultiverseWorld(String worldName, WorldConfig worldConfig) {
@ -49,14 +55,33 @@ public class MultiverseWorld {
return worldConfig.hasMVWorld(); return worldConfig.hasMVWorld();
} }
/**
* Gets the properties that can be configured on this world. Can be used for {@link #getProperty(String)} and
* {@link #setProperty(String, Object)}.
*
* @return A collection of property names.
*/
public Collection<String> getConfigurablePropertyNames() { public Collection<String> getConfigurablePropertyNames() {
return worldConfig.getConfigurablePropertyNames(); return worldConfig.getConfigurablePropertyNames();
} }
/**
* Gets a property on this world.
*
* @param name The name of the property.
* @return The value of the property.
*/
public Try<Object> getProperty(String name) { public Try<Object> getProperty(String name) {
return worldConfig.getProperty(name); return worldConfig.getProperty(name);
} }
/**
* Sets a property on this world.
*
* @param name The name of the property.
* @param value The value of the property.
* @return Result of setting property.
*/
public Try<Void> setProperty(String name, Object value) { public Try<Void> setProperty(String name, Object value) {
return worldConfig.setProperty(name, value); return worldConfig.setProperty(name, value);
} }
@ -74,6 +99,7 @@ public class MultiverseWorld {
* Sets whether or not Multiverse should auto-adjust the spawn for this world. * Sets whether or not Multiverse should auto-adjust the spawn for this world.
* *
* @param adjustSpawn True if multiverse should adjust the spawn, false if not. * @param adjustSpawn True if multiverse should adjust the spawn, false if not.
* @return Result of setting property.
*/ */
public Try<Void> setAdjustSpawn(boolean adjustSpawn) { public Try<Void> setAdjustSpawn(boolean adjustSpawn) {
return worldConfig.setAdjustSpawn(adjustSpawn); return worldConfig.setAdjustSpawn(adjustSpawn);
@ -94,6 +120,7 @@ public class MultiverseWorld {
* Sets the alias of the world. * Sets the alias of the world.
* *
* @param alias A string that is the new alias. * @param alias A string that is the new alias.
* @return Result of setting property.
*/ */
public Try<Void> setAlias(String alias) { public Try<Void> setAlias(String alias) {
return worldConfig.setAlias(alias); return worldConfig.setAlias(alias);
@ -112,6 +139,7 @@ public class MultiverseWorld {
* Sets whether or not players are allowed to fly in this world. * Sets whether or not players are allowed to fly in this world.
* *
* @param allowFlight True to allow flight in this world. * @param allowFlight True to allow flight in this world.
* @return Result of setting property.
*/ */
public Try<Void> setAllowFlight(boolean allowFlight) { public Try<Void> setAllowFlight(boolean allowFlight) {
return worldConfig.setAllowFlight(allowFlight); return worldConfig.setAllowFlight(allowFlight);
@ -131,6 +159,7 @@ public class MultiverseWorld {
* If set to false, Multiverse will disable the weather in the world immediately. * If set to false, Multiverse will disable the weather in the world immediately.
* *
* @param allowWeather True if weather events should occur in a world, false if not. * @param allowWeather True if weather events should occur in a world, false if not.
* @return Result of setting property.
*/ */
public Try<Void> setAllowWeather(boolean allowWeather) { public Try<Void> setAllowWeather(boolean allowWeather) {
return worldConfig.setAllowWeather(allowWeather); return worldConfig.setAllowWeather(allowWeather);
@ -149,6 +178,7 @@ public class MultiverseWorld {
* Sets whether or not a world will auto-heal players if the difficulty is on peaceful. * Sets whether or not a world will auto-heal players if the difficulty is on peaceful.
* *
* @param autoHeal True if the world will heal. * @param autoHeal True if the world will heal.
* @return Result of setting property.
*/ */
public Try<Void> setAutoHeal(boolean autoHeal) { public Try<Void> setAutoHeal(boolean autoHeal) {
return worldConfig.setAutoHeal(autoHeal); return worldConfig.setAutoHeal(autoHeal);
@ -169,6 +199,7 @@ public class MultiverseWorld {
* True is default. * True is default.
* *
* @param autoLoad True if multiverse should autoload this world the spawn, false if not. * @param autoLoad True if multiverse should autoload this world the spawn, false if not.
* @return Result of setting property.
*/ */
public Try<Void> setAutoLoad(boolean autoLoad) { public Try<Void> setAutoLoad(boolean autoLoad) {
return worldConfig.setAutoLoad(autoLoad); return worldConfig.setAutoLoad(autoLoad);
@ -191,6 +222,7 @@ public class MultiverseWorld {
* True is default. * True is default.
* *
* @param bedRespawn True if players dying in this world respawn at their bed. * @param bedRespawn True if players dying in this world respawn at their bed.
* @return Result of setting property.
*/ */
public Try<Void> setBedRespawn(boolean bedRespawn) { public Try<Void> setBedRespawn(boolean bedRespawn) {
return worldConfig.setBedRespawn(bedRespawn); return worldConfig.setBedRespawn(bedRespawn);
@ -211,6 +243,7 @@ public class MultiverseWorld {
* Use a value of null to specify a non-item based currency. * Use a value of null to specify a non-item based currency.
* *
* @param currency The Type of currency that will be used when users enter this world. * @param currency The Type of currency that will be used when users enter this world.
* @return Result of setting property.
*/ */
public Try<Void> setCurrency(Material currency) { public Try<Void> setCurrency(Material currency) {
return worldConfig.setEntryFeeCurrency(currency); return worldConfig.setEntryFeeCurrency(currency);
@ -231,6 +264,7 @@ public class MultiverseWorld {
* the name that resides in the Bukkit enum, ex. PEACEFUL * the name that resides in the Bukkit enum, ex. PEACEFUL
* *
* @param difficulty The new difficulty. * @param difficulty The new difficulty.
* @return Result of setting property.
*/ */
public Try<Void> setDifficulty(Difficulty difficulty) { public Try<Void> setDifficulty(Difficulty difficulty) {
return worldConfig.setDifficulty(difficulty); return worldConfig.setDifficulty(difficulty);
@ -258,6 +292,7 @@ public class MultiverseWorld {
* Sets the game mode of this world. * Sets the game mode of this world.
* *
* @param gameMode The new {@link GameMode}. * @param gameMode The new {@link GameMode}.
* @return Result of setting property.
*/ */
public Try<Void> setGameMode(GameMode gameMode) { public Try<Void> setGameMode(GameMode gameMode) {
return worldConfig.setGameMode(gameMode); return worldConfig.setGameMode(gameMode);
@ -287,6 +322,7 @@ public class MultiverseWorld {
* access permissions to go to this world. * access permissions to go to this world.
* *
* @param hidden True if the world should be hidden, false if not. * @param hidden True if the world should be hidden, false if not.
* @return Result of setting property.
*/ */
public Try<Void> setHidden(boolean hidden) { public Try<Void> setHidden(boolean hidden) {
return worldConfig.setHidden(hidden); return worldConfig.setHidden(hidden);
@ -305,6 +341,7 @@ public class MultiverseWorld {
* Sets whether or not the hunger level of players will go down in a world. * Sets whether or not the hunger level of players will go down in a world.
* *
* @param hunger True if hunger will go down, false to keep it at the level they entered a world with. * @param hunger True if hunger will go down, false to keep it at the level they entered a world with.
* @return Result of setting property.
*/ */
public Try<Void> setHunger(boolean hunger) { public Try<Void> setHunger(boolean hunger) {
return worldConfig.setHunger(hunger); return worldConfig.setHunger(hunger);
@ -325,6 +362,7 @@ public class MultiverseWorld {
* This will not happen immediately. * This will not happen immediately.
* *
* @param keepSpawnInMemory If true, CraftBukkit will keep the spawn chunks loaded in memory. * @param keepSpawnInMemory If true, CraftBukkit will keep the spawn chunks loaded in memory.
* @return Result of setting property.
*/ */
public Try<Void> setKeepSpawnInMemory(boolean keepSpawnInMemory) { public Try<Void> setKeepSpawnInMemory(boolean keepSpawnInMemory) {
return worldConfig.setKeepSpawnInMemory(keepSpawnInMemory); return worldConfig.setKeepSpawnInMemory(keepSpawnInMemory);
@ -345,6 +383,7 @@ public class MultiverseWorld {
* permission node will not be allowed in. A value of -1 or less signifies no limit * permission node will not be allowed in. A value of -1 or less signifies no limit
* *
* @param playerLimit The new limit * @param playerLimit The new limit
* @return Result of setting property.
*/ */
public Try<Void> setPlayerLimit(int playerLimit) { public Try<Void> setPlayerLimit(int playerLimit) {
return worldConfig.setPlayerLimit(playerLimit); return worldConfig.setPlayerLimit(playerLimit);
@ -363,6 +402,7 @@ public class MultiverseWorld {
* Sets The types of portals that are allowed in this world. * Sets The types of portals that are allowed in this world.
* *
* @param portalForm The type of portals allowed in this world. * @param portalForm The type of portals allowed in this world.
* @return Result of setting property.
*/ */
public Try<Void> setPortalForm(AllowedPortalType portalForm) { public Try<Void> setPortalForm(AllowedPortalType portalForm) {
return worldConfig.setPortalForm(portalForm); return worldConfig.setPortalForm(portalForm);
@ -383,6 +423,7 @@ public class MultiverseWorld {
* The type can be set with {@link #setCurrency(Material)} * The type can be set with {@link #setCurrency(Material)}
* *
* @param price The Amount of money/item to enter the world. * @param price The Amount of money/item to enter the world.
* @return Result of setting property.
*/ */
public Try<Void> setPrice(double price) { public Try<Void> setPrice(double price) {
return worldConfig.setEntryFeeAmount(price); return worldConfig.setEntryFeeAmount(price);
@ -401,6 +442,7 @@ public class MultiverseWorld {
* Turn pvp on or off. This setting is used to set the world's PVP mode. * Turn pvp on or off. This setting is used to set the world's PVP mode.
* *
* @param pvp True to enable PVP damage, false to disable it. * @param pvp True to enable PVP damage, false to disable it.
* @return Result of setting property.
*/ */
public Try<Void> setPvp(boolean pvp) { public Try<Void> setPvp(boolean pvp) {
return worldConfig.setPvp(pvp); return worldConfig.setPvp(pvp);
@ -429,6 +471,7 @@ public class MultiverseWorld {
* Returns true upon success, false upon failure. * Returns true upon success, false upon failure.
* *
* @param respawnWorld The name of a world that exists on the server. * @param respawnWorld The name of a world that exists on the server.
* @return Result of setting property.
*/ */
public Try<Void> setRespawnWorld(World respawnWorld) { public Try<Void> setRespawnWorld(World respawnWorld) {
return worldConfig.setRespawnWorld(respawnWorld.getName()); return worldConfig.setRespawnWorld(respawnWorld.getName());
@ -439,6 +482,7 @@ public class MultiverseWorld {
* Returns true upon success, false upon failure. * Returns true upon success, false upon failure.
* *
* @param respawnWorld The name of a world that exists on the server. * @param respawnWorld The name of a world that exists on the server.
* @return Result of setting property.
*/ */
public Try<Void> setRespawnWorld(MultiverseWorld respawnWorld) { public Try<Void> setRespawnWorld(MultiverseWorld respawnWorld) {
return worldConfig.setRespawnWorld(respawnWorld.getName()); return worldConfig.setRespawnWorld(respawnWorld.getName());
@ -449,6 +493,7 @@ public class MultiverseWorld {
* Returns true upon success, false upon failure. * Returns true upon success, false upon failure.
* *
* @param respawnWorld The name of a world that exists on the server. * @param respawnWorld The name of a world that exists on the server.
* @return Result of setting property.
*/ */
public Try<Void> setRespawnWorld(String respawnWorld) { public Try<Void> setRespawnWorld(String respawnWorld) {
return worldConfig.setRespawnWorld(respawnWorld); return worldConfig.setRespawnWorld(respawnWorld);
@ -464,11 +509,13 @@ public class MultiverseWorld {
return worldConfig.getScale(); return worldConfig.getScale();
} }
//TODO: we are removing mvnp
/** /**
* Sets the scale of this world. Really only has an effect if you use * Sets the scale of this world. Really only has an effect if you use
* Multiverse-NetherPortals. TODO: we are removing mvnp. * Multiverse-NetherPortals.
* *
* @param scale A scaling value, cannot be negative or 0. * @param scale A scaling value, cannot be negative or 0.
* @return Result of setting property.
*/ */
public Try<Void> setScale(double scale) { public Try<Void> setScale(double scale) {
return worldConfig.setScale(scale); return worldConfig.setScale(scale);
@ -496,6 +543,7 @@ public class MultiverseWorld {
* Sets the spawn location for a world. * Sets the spawn location for a world.
* *
* @param spawnLocation The spawn location for a world. * @param spawnLocation The spawn location for a world.
* @return Result of setting property.
*/ */
public Try<Void> setSpawnLocation(Location spawnLocation) { public Try<Void> setSpawnLocation(Location spawnLocation) {
return worldConfig.setSpawnLocation(spawnLocation); return worldConfig.setSpawnLocation(spawnLocation);
@ -517,6 +565,7 @@ public class MultiverseWorld {
* those animals become the exceptions, and will spawn * those animals become the exceptions, and will spawn
* *
* @param spawningAnimals True to allow spawning of monsters, false to prevent. * @param spawningAnimals True to allow spawning of monsters, false to prevent.
* @return Result of setting property.
*/ */
public Try<Void> setSpawningAnimals(boolean spawningAnimals) { public Try<Void> setSpawningAnimals(boolean spawningAnimals) {
return worldConfig.setSpawningAnimals(spawningAnimals); return worldConfig.setSpawningAnimals(spawningAnimals);