Use orElseGet instead of orElse

orElse is a trap because it evaluates even if the Optional is empty.
orElseGet is the correct way.
This commit is contained in:
tastybento 2021-01-08 20:05:23 -08:00
parent 86af7b568c
commit 2c7f54fe10
15 changed files with 35 additions and 33 deletions

View File

@ -602,7 +602,7 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
return options;
}
// Add any tab completion from the subcommand
options.addAll(command.tabComplete(User.getInstance(sender), alias, new LinkedList<>(Arrays.asList(args))).orElse(new ArrayList<>()));
options.addAll(command.tabComplete(User.getInstance(sender), alias, new LinkedList<>(Arrays.asList(args))).orElseGet(() -> new ArrayList<>()));
if (command.hasSubCommands()) {
options.addAll(getSubCommandLabels(sender, command));
}

View File

@ -61,7 +61,9 @@ public class AdminRegisterCommand extends ConfirmableCommand {
}
// Check if island is owned
Optional<Island> island = getIslands().getIslandAt(user.getLocation());
if (island.map(Island::isOwned).orElse(false)) {
if (island.filter(Island::isOwned)
.filter(i -> !i.getOwner().equals(targetUUID))
.isPresent()) {
user.sendMessage("commands.admin.register.already-owned");
return false;
}

View File

@ -39,7 +39,7 @@ public class IslandSettingsCommand extends CompositeCommand {
@Override
public boolean execute(User user, String label, List<String> args) {
Island island = getIslands().getIslandAt(user.getLocation()).orElse(getIslands().getIsland(user.getWorld(), user.getUniqueId()));
Island island = getIslands().getIslandAt(user.getLocation()).orElseGet(() -> getIslands().getIsland(user.getWorld(), user.getUniqueId()));
new TabbedPanelBuilder()
.user(user)
.world(getWorld())

View File

@ -146,7 +146,7 @@ public abstract class FlagListener implements Listener {
} else {
report(user, e, loc, flag, flag.isSetForWorld(loc.getWorld()) ? Why.SETTING_ALLOWED_IN_WORLD : Why.SETTING_NOT_ALLOWED_IN_WORLD);
}
return island.map(x -> x.isAllowed(flag)).orElse(flag.isSetForWorld(loc.getWorld()));
return island.map(x -> x.isAllowed(flag)).orElseGet(() -> flag.isSetForWorld(loc.getWorld()));
}
// Protection flag

View File

@ -43,7 +43,7 @@ public interface DatabaseSetup {
.filter(plugin.getSettings().getDatabaseType()::equals)
.findFirst()
.map(t -> t.database)
.orElse(DatabaseType.JSON.database);
.orElseGet(() -> DatabaseType.JSON.database);
}
/**

View File

@ -29,7 +29,7 @@ public class PlaceholderAPIHook extends PlaceholderHook {
private Map<Addon, AddonPlaceholderExpansion> addonsExpansions;
private final Set<String> bentoBoxPlaceholders;
private final Map<Addon, Set<String>> addonPlaceholders;
public PlaceholderAPIHook() {
super("PlaceholderAPI");
@ -105,15 +105,15 @@ public class PlaceholderAPIHook extends PlaceholderHook {
}
/**
*
*
*/
@Override
@NonNull
public String replacePlaceholders(@NonNull Player player, @NonNull String string) {
// Transform [gamemode] in string to the game mode description name, or remove it for the default replacement
String newString = BentoBox.getInstance().getIWM().getAddon(player.getWorld()).map(gm ->
string.replace(TextVariables.GAMEMODE, gm.getDescription().getName().toLowerCase())
).orElse(removeGMPlaceholder(string));
String newString = BentoBox.getInstance().getIWM().getAddon(player.getWorld()).map(gm ->
string.replace(TextVariables.GAMEMODE, gm.getDescription().getName().toLowerCase())
).orElseGet(() -> removeGMPlaceholder(string));
return PlaceholderAPI.setPlaceholders(player, newString);
}
@ -121,10 +121,10 @@ public class PlaceholderAPIHook extends PlaceholderHook {
String newString = string;
// Get placeholders - TODO: my regex moh=jo isn't good enough to grab only placeholders with [gamemode] in yet!
Matcher m = Pattern.compile("(%)(.*?)(%)").matcher(string);
while (m.find()) {
String ph = m.group();
if (ph.contains(TextVariables.GAMEMODE)) newString = newString.replace(ph,"");
}
while (m.find()) {
String ph = m.group();
if (ph.contains(TextVariables.GAMEMODE)) newString = newString.replace(ph,"");
}
return newString;
}

View File

@ -150,7 +150,7 @@ public class PortalTeleportationListener implements Listener {
// If entering an ender portal in the End.
if (fromWorld.getEnvironment() == Environment.THE_END) {
// If this is from the island nether, then go to the same vector, otherwise try island home location
Location to = plugin.getIslands().getIslandAt(e.getFrom()).map(i -> i.getSpawnPoint(Environment.NORMAL)).orElse(e.getFrom().toVector().toLocation(overWorld));
Location to = plugin.getIslands().getIslandAt(e.getFrom()).map(i -> i.getSpawnPoint(Environment.NORMAL)).orElseGet(() -> e.getFrom().toVector().toLocation(overWorld));
e.setCancelled(true);
// Else other worlds teleport to the overworld
new SafeSpotTeleport.Builder(plugin)
@ -165,7 +165,7 @@ public class PortalTeleportationListener implements Listener {
World endWorld = plugin.getIWM().getEndWorld(overWorld);
// If this is to island End, then go to the same vector, otherwise try spawn
Optional<Island> optionalIsland = plugin.getIslands().getIslandAt(e.getFrom());
Location to = optionalIsland.map(i -> i.getSpawnPoint(Environment.THE_END)).orElse(e.getFrom().toVector().toLocation(endWorld));
Location to = optionalIsland.map(i -> i.getSpawnPoint(Environment.THE_END)).orElseGet(() -> e.getFrom().toVector().toLocation(endWorld));
e.setCancelled(true);
// Check if there is a missing end island
if (plugin.getIWM().isPasteMissingIslands(overWorld)
@ -247,7 +247,7 @@ public class PortalTeleportationListener implements Listener {
// If entering a nether portal in the nether, teleport to portal in overworld if there is one
if (fromWorld.getEnvironment() == Environment.NETHER) {
// If this is from the island nether, then go to the same vector, otherwise try island home location
Location to = plugin.getIslands().getIslandAt(e.getFrom()).map(i -> i.getSpawnPoint(Environment.NORMAL)).orElse(e.getFrom().toVector().toLocation(overWorld));
Location to = plugin.getIslands().getIslandAt(e.getFrom()).map(i -> i.getSpawnPoint(Environment.NORMAL)).orElseGet(() -> e.getFrom().toVector().toLocation(overWorld));
e.setCancelled(true);
// Else other worlds teleport to the nether
new SafeSpotTeleport.Builder(plugin)
@ -262,7 +262,7 @@ public class PortalTeleportationListener implements Listener {
World nether = plugin.getIWM().getNetherWorld(overWorld);
// If this is to island nether, then go to the same vector, otherwise try spawn
Optional<Island> optionalIsland = plugin.getIslands().getIslandAt(e.getFrom());
Location to = optionalIsland.map(i -> i.getSpawnPoint(Environment.NETHER)).orElse(e.getFrom().toVector().toLocation(nether));
Location to = optionalIsland.map(i -> i.getSpawnPoint(Environment.NETHER)).orElseGet(() -> e.getFrom().toVector().toLocation(nether));
e.setCancelled(true);
// Check if there is an island there or not
if (plugin.getIWM().isPasteMissingIslands(overWorld) &&

View File

@ -38,7 +38,7 @@ public class FireListener extends FlagListener {
return false;
}
// Check if the island exists and if fire is allowed
boolean cancel = getIslands().getIslandAt(l).map(i -> !i.isAllowed(flag)).orElse(!flag.isSetForWorld(l.getWorld()));
boolean cancel = getIslands().getIslandAt(l).map(i -> !i.isAllowed(flag)).orElseGet(() -> !flag.isSetForWorld(l.getWorld()));
e.setCancelled(cancel);
return cancel;
}

View File

@ -95,7 +95,7 @@ public class TNTListener extends FlagListener {
protected boolean protect(Location location) {
return getIslands().getProtectedIslandAt(location).map(i -> !i.isAllowed(Flags.TNT_DAMAGE))
.orElse(!Flags.WORLD_TNT_DAMAGE.isSetForWorld(location.getWorld()));
.orElseGet(() -> !Flags.WORLD_TNT_DAMAGE.isSetForWorld(location.getWorld()));
}
/**

View File

@ -29,6 +29,6 @@ public class DecayListener extends FlagListener {
Optional<Island> island = getIslands().getIslandAt(e.getBlock().getLocation());
// Cancel the event if needed - this means if this is not allowed on the island or in the world.
e.setCancelled(island.map(i -> !i.isAllowed(Flags.LEAF_DECAY)).orElse(!Flags.LEAF_DECAY.isSetForWorld(e.getBlock().getWorld())));
e.setCancelled(island.map(i -> !i.isAllowed(Flags.LEAF_DECAY)).orElseGet(() -> !Flags.LEAF_DECAY.isSetForWorld(e.getBlock().getWorld())));
}
}

View File

@ -54,7 +54,7 @@ public class MobSpawnListener extends FlagListener {
boolean cancelNatural = shouldCancel(e.getEntity(), e.getLocation(), Flags.ANIMAL_NATURAL_SPAWN, Flags.MONSTER_NATURAL_SPAWN);
e.setCancelled(cancelNatural);
return cancelNatural;
// Spawners
// Spawners
case SPAWNER:
boolean cancelSpawners = shouldCancel(e.getEntity(), e.getLocation(), Flags.ANIMAL_SPAWNERS_SPAWN, Flags.MONSTER_SPAWNERS_SPAWN);
e.setCancelled(cancelSpawners);
@ -67,9 +67,9 @@ public class MobSpawnListener extends FlagListener {
private boolean shouldCancel(Entity entity, Location loc, Flag animalSpawnFlag, Flag monsterSpawnFlag) {
Optional<Island> island = getIslands().getIslandAt(loc);
if (Util.isHostileEntity(entity) && !(entity instanceof PufferFish)) {
return island.map(i -> !i.isAllowed(monsterSpawnFlag)).orElse(!monsterSpawnFlag.isSetForWorld(entity.getWorld()));
return island.map(i -> !i.isAllowed(monsterSpawnFlag)).orElseGet(() -> !monsterSpawnFlag.isSetForWorld(entity.getWorld()));
} else if (Util.isPassiveEntity(entity) || entity instanceof PufferFish) {
return island.map(i -> !i.isAllowed(animalSpawnFlag)).orElse(!animalSpawnFlag.isSetForWorld(entity.getWorld()));
return island.map(i -> !i.isAllowed(animalSpawnFlag)).orElseGet(() -> !animalSpawnFlag.isSetForWorld(entity.getWorld()));
}
return false;
}

View File

@ -659,7 +659,7 @@ public class IslandWorldManager {
public List<String> getOnLeaveCommands(@NonNull World world) {
return gameModes.containsKey(world) ? gameModes.get(world).getWorldSettings().getOnLeaveCommands() : Collections.emptyList();
}
/**
* Returns a list of commands to execute when the player respawns and {@link Flags#ISLAND_RESPAWN} is true.
* @param world the World
@ -678,7 +678,7 @@ public class IslandWorldManager {
* @return data folder file object or the plugin's data folder if none found
*/
public File getDataFolder(@NonNull World world) {
return getAddon(world).map(GameModeAddon::getDataFolder).orElse(plugin.getDataFolder());
return getAddon(world).map(GameModeAddon::getDataFolder).orElseGet(() -> plugin.getDataFolder());
}
/**

View File

@ -296,7 +296,7 @@ public class PlayersManager {
return playerCache.values().stream()
.filter(p -> p.getPlayerName().equalsIgnoreCase(name)).findFirst()
.map(p -> UUID.fromString(p.getUniqueId()))
.orElse(names.objectExists(name) ? names.loadObject(name).getUuid() : null);
.orElseGet(() -> names.objectExists(name) ? names.loadObject(name).getUuid() : null);
}
/**
@ -548,7 +548,7 @@ public class PlayersManager {
target.getPlayer().getInventory().clear();
} else {
getPlayer(target.getUniqueId()).addToPendingKick(world);
}
}
}
if (plugin.getSettings().isUseEconomy() && plugin.getIWM().isOnLeaveResetMoney(world)) {

View File

@ -173,7 +173,7 @@ public class SafeSpotTeleport {
*/
private List<Pair<Integer, Integer>> getChunksToScan() {
List<Pair<Integer, Integer>> chunksToScan = new ArrayList<>();
int maxRadius = plugin.getIslands().getIslandAt(location).map(Island::getProtectionRange).orElse(plugin.getIWM().getIslandProtectionRange(location.getWorld()));
int maxRadius = plugin.getIslands().getIslandAt(location).map(Island::getProtectionRange).orElseGet(() -> plugin.getIWM().getIslandProtectionRange(location.getWorld()));
maxRadius = Math.min(MAX_RADIUS, maxRadius);
int x = location.getBlockX();
int z = location.getBlockZ();

View File

@ -439,10 +439,10 @@ public class PortalTeleportationListenerTest {
assertTrue(np.onNetherPortal(e));
// Verify
assertTrue(e.isCancelled());
// If nether islands, then to = from but in nether
verify(from).toVector();
// Do not go to spawn
verify(nether, never()).getSpawnLocation();
// If nether islands, then to spawn location
verify(island).getSpawnPoint(eq(Environment.NETHER));
// Do not go to from
verify(from, never()).toVector();
}
/**