Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sonar Cloud code smell clean up #278

Merged
merged 1 commit into from
Feb 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
22 changes: 8 additions & 14 deletions src/main/java/world/bentobox/level/Level.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@
import world.bentobox.level.config.ConfigSettings;
import world.bentobox.level.listeners.IslandActivitiesListeners;
import world.bentobox.level.listeners.JoinLeaveListener;
import world.bentobox.level.objects.IslandLevels;
import world.bentobox.level.listeners.MigrationListener;
import world.bentobox.level.objects.IslandLevels;
import world.bentobox.level.objects.LevelsData;
import world.bentobox.level.objects.TopTenData;
import world.bentobox.level.requests.LevelRequestHandler;
Expand Down Expand Up @@ -176,20 +176,14 @@ private void hookExtensions()
{
this.visitHook = (VisitAddon) addon;
this.log("Level Addon hooked into Visit addon.");
}, () ->
{
this.visitHook = null;
});
}, () -> this.visitHook = null);

// Try to find Warps addon and if it does not exist, display a warning
this.getAddonByName("Warps").ifPresentOrElse(addon ->
{
this.warpHook = (Warp) addon;
this.log("Level Addon hooked into Warps addon.");
}, () ->
{
this.warpHook = null;
});
}, () -> this.warpHook = null);
}


Expand Down Expand Up @@ -230,9 +224,9 @@ private void registerPlaceholders(GameModeAddon gm) {
getPlugin().getPlaceholdersManager().registerPlaceholder(this,
gm.getDescription().getName().toLowerCase() + "_island_total_points",
user -> {
IslandLevels data = getManager().getLevelsData(this.getIslands().getIsland(gm.getOverWorld(), user));
return data.getTotalPoints()+"";
});
IslandLevels data = getManager().getLevelsData(this.getIslands().getIsland(gm.getOverWorld(), user));
return data.getTotalPoints()+"";
});

getPlugin().getPlaceholdersManager().registerPlaceholder(this,
gm.getDescription().getName().toLowerCase() + "_points_to_next_level",
Expand Down Expand Up @@ -478,7 +472,7 @@ public long getInitialIslandLevel(@NonNull Island island) {
* @param playerUUID - the target island member's UUID
* @deprecated Do not use this anymore. Use getManager().calculateLevel(playerUUID, island)
*/
@Deprecated
@Deprecated(since="2.3.0", forRemoval=true)
public void calculateIslandLevel(World world, @Nullable User user, @NonNull UUID playerUUID) {
Island island = getIslands().getIsland(world, playerUUID);
if (island != null) getManager().calculateLevel(playerUUID, island);
Expand All @@ -490,7 +484,7 @@ public void calculateIslandLevel(World world, @Nullable User user, @NonNull UUID
* @return LevelsData object or null if not found. Only island levels are set!
* @deprecated Do not use this anymore. Use {@link #getIslandLevel(World, UUID)}
*/
@Deprecated
@Deprecated(since="2.3.0", forRemoval=true)
public LevelsData getLevelsData(UUID targetPlayer) {
LevelsData ld = new LevelsData(targetPlayer);
getPlugin().getAddonsManager().getGameModeAddons().stream()
Expand Down
9 changes: 2 additions & 7 deletions src/main/java/world/bentobox/level/LevelsManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -152,8 +152,6 @@ public CompletableFuture<Results> calculateLevel(UUID targetPlayer, Island islan
addon.getPipeliner().addIsland(island).thenAccept(r -> {
// Results are irrelevant because the island is unowned or deleted, or IslandLevelCalcEvent is cancelled
if (r == null || fireIslandLevelCalcEvent(targetPlayer, island, r)) {
System.out.println("results are null or event canceled");

result.complete(null);
}
// Save result
Expand Down Expand Up @@ -337,7 +335,7 @@ public int getRank(@NonNull World world, UUID uuid) {
.filter(e -> addon.getIslands().isOwner(world, e.getKey()))
.filter(l -> l.getValue() > 0)
.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()));
return stream.takeWhile(x -> !x.getKey().equals(uuid)).map(Map.Entry::getKey).collect(Collectors.toList()).size() + 1;
return (int) (stream.takeWhile(x -> !x.getKey().equals(uuid)).map(Map.Entry::getKey).count() + 1);
}

/**
Expand All @@ -363,10 +361,7 @@ public void loadTopTens() {
addon.getIslands().getIslandById(il.getUniqueId()).ifPresent(i -> this.addToTopTen(i, il.getLevel()));
}
});
topTenLists.keySet().forEach(w -> {
addon.log("Generated rankings for " + w.getName());
});

topTenLists.keySet().forEach(w -> addon.log("Generated rankings for " + w.getName()));
});
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package world.bentobox.level.calculators;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
Expand Down Expand Up @@ -67,9 +67,10 @@ public class IslandLevelCalculator {
* @param str - equation to evaluate
* @return value of equation
*/
private static double eval(final String str) {
private static double eval(final String str) throws IOException {
return new Object() {
int pos = -1, ch;
int pos = -1;
int ch;

boolean eat(int charToEat) {
while (ch == ' ') nextChar();
Expand All @@ -84,10 +85,10 @@ void nextChar() {
ch = (++pos < str.length()) ? str.charAt(pos) : -1;
}

double parse() {
double parse() throws IOException {
nextChar();
double x = parseExpression();
if (pos < str.length()) throw new RuntimeException("Unexpected: " + (char)ch);
if (pos < str.length()) throw new IOException("Unexpected: " + (char)ch);
return x;
}

Expand All @@ -97,7 +98,7 @@ void nextChar() {
// factor = `+` factor | `-` factor | `(` expression `)`
// | number | functionName factor | factor `^` factor

double parseExpression() {
double parseExpression() throws IOException {
double x = parseTerm();
for (;;) {
if (eat('+')) x += parseTerm(); // addition
Expand All @@ -106,7 +107,7 @@ void nextChar() {
}
}

double parseFactor() {
double parseFactor() throws IOException {
if (eat('+')) return parseFactor(); // unary plus
if (eat('-')) return -parseFactor(); // unary minus

Expand Down Expand Up @@ -139,18 +140,18 @@ void nextChar() {
x = Math.log(x);
break;
default:
throw new RuntimeException("Unknown function: " + func);
throw new IOException("Unknown function: " + func);
}
} else {
throw new RuntimeException("Unexpected: " + (char)ch);
throw new IOException("Unexpected: " + (char)ch);
}

if (eat('^')) x = Math.pow(x, parseFactor()); // exponentiation

return x;
}

double parseTerm() {
double parseTerm() throws IOException {
double x = parseFactor();
for (;;) {
if (eat('*')) x *= parseFactor(); // multiplication
Expand All @@ -163,7 +164,7 @@ void nextChar() {
private final Level addon;
private final Queue<Pair<Integer, Integer>> chunksToCheck;
private final Island island;
private final HashMap<Material, Integer> limitCount;
private final Map<Material, Integer> limitCount;
private final CompletableFuture<Results> r;


Expand Down Expand Up @@ -192,7 +193,7 @@ public IslandLevelCalculator(Level addon, Island island, CompletableFuture<Resul
results = new Results();
duration = System.currentTimeMillis();
chunksToCheck = getChunksToScan(island);
this.limitCount = new HashMap<>(addon.getBlockConfig().getBlockLimits());
this.limitCount = new EnumMap<>(addon.getBlockConfig().getBlockLimits());
// Get the initial island level
results.initialLevel.set(addon.getInitialIslandLevel(island));
// Set up the worlds
Expand Down Expand Up @@ -223,7 +224,15 @@ public IslandLevelCalculator(Level addon, Island island, CompletableFuture<Resul
private long calculateLevel(long blockAndDeathPoints) {
String calcString = addon.getSettings().getLevelCalc();
String withValues = calcString.replace("blocks", String.valueOf(blockAndDeathPoints)).replace("level_cost", String.valueOf(this.addon.getSettings().getLevelCost()));
return (long)eval(withValues) - (addon.getSettings().isZeroNewIslandLevels() ? results.initialLevel.get() : 0);
long evalWithValues;
try {
evalWithValues = (long)eval(withValues);
return evalWithValues - (addon.getSettings().isZeroNewIslandLevels() ? results.initialLevel.get() : 0);

} catch (IOException e) {
addon.getPlugin().logStacktrace(e);
return 0L;
}
}

/**
Expand Down Expand Up @@ -426,7 +435,7 @@ private int limitCount(Material md) {
private void scanChests(Chunk chunk) {
// Count blocks in chests
for (BlockState bs : chunk.getTileEntities()) {
if (bs instanceof Container) {
if (bs instanceof Container container) {
if (addon.isAdvChestEnabled()) {
AdvancedChest<?,?> aChest = AdvancedChestsAPI.getChestManager().getAdvancedChest(bs.getLocation());
if (aChest != null && aChest.getChestType().getName().equals("NORMAL")) {
Expand All @@ -439,7 +448,7 @@ private void scanChests(Chunk chunk) {
}
}
// Regular chest
((Container)bs).getSnapshotInventory().forEach(this::countItemStack);
container.getSnapshotInventory().forEach(this::countItemStack);
}
}
}
Expand Down Expand Up @@ -509,7 +518,7 @@ private void scanAsync(ChunkPair cp) {
}
// Hook for Wild Stackers (Blocks and Spawners Only) - this has to use the real chunk
if (addon.isStackersEnabled() && (blockData.getMaterial().equals(Material.CAULDRON) || blockData.getMaterial().equals(Material.SPAWNER))) {
stackedBlocks.add(new Location(cp.world, x + cp.chunkSnapshot.getX() * 16,y,z + cp.chunkSnapshot.getZ() * 16));
stackedBlocks.add(new Location(cp.world, (double)x + cp.chunkSnapshot.getX() * 16, y, (double)z + cp.chunkSnapshot.getZ() * 16));
}
// Scan chests
if (addon.getSettings().isIncludeChests() && CHESTS.contains(blockData.getMaterial())) {
Expand Down Expand Up @@ -560,21 +569,21 @@ public CompletableFuture<Boolean> scanNextChunk() {
}

private Collection<String> sortedReport(int total, Multiset<Material> materialCount) {
Collection<String> r = new ArrayList<>();
Collection<String> result = new ArrayList<>();
Iterable<Multiset.Entry<Material>> entriesSortedByCount = Multisets.copyHighestCountFirst(materialCount).entrySet();
for (Entry<Material> en : entriesSortedByCount) {
Material type = en.getElement();

int value = getValue(type);

r.add(type.toString() + ":"
result.add(type.toString() + ":"
+ String.format("%,d", en.getCount()) + " blocks x " + value + " = " + (value * en.getCount()));
total += (value * en.getCount());

}
r.add("Subtotal = " + total);
r.add(LINE_BREAK);
return r;
result.add("Subtotal = " + total);
result.add(LINE_BREAK);
return result;
}


Expand Down Expand Up @@ -634,7 +643,7 @@ boolean isNotZeroIsland() {

public void scanIsland(Pipeliner pipeliner) {
// Scan the next chunk
scanNextChunk().thenAccept(r -> {
scanNextChunk().thenAccept(result -> {
if (!Bukkit.isPrimaryThread()) {
addon.getPlugin().logError("scanChunk not on Primary Thread!");
}
Expand All @@ -649,7 +658,7 @@ public void scanIsland(Pipeliner pipeliner) {
}
return;
}
if (Boolean.TRUE.equals(r) && !pipeliner.getTask().isCancelled()) {
if (Boolean.TRUE.equals(result) && !pipeliner.getTask().isCancelled()) {
// scanNextChunk returns true if there are more chunks to scan
scanIsland(pipeliner);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import world.bentobox.bentobox.api.commands.CompositeCommand;
import world.bentobox.bentobox.api.localization.TextVariables;
Expand Down Expand Up @@ -60,6 +59,6 @@ public boolean execute(User user, String label, List<String> args) {
@Override
public Optional<List<String>> tabComplete(User user, String alias, List<String> args) {
return Optional.of(addon.getManager().getTopTen(getWorld(), Level.TEN).keySet().stream().map(addon.getPlayers()::getName)
.filter(n -> !n.isEmpty()).collect(Collectors.toList()));
.filter(n -> !n.isEmpty()).toList());
}
}
25 changes: 13 additions & 12 deletions src/main/java/world/bentobox/level/commands/IslandValueCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

public class IslandValueCommand extends CompositeCommand
{
private static final String MATERIAL = "[material]";
private final Level addon;


Expand All @@ -45,7 +46,7 @@ public boolean execute(User user, String label, List<String> args)
if (args.size() > 1)
{
this.showHelp(this, user);
return true;
return false;
}

if (args.isEmpty())
Expand Down Expand Up @@ -73,8 +74,8 @@ else if (args.get(0).equalsIgnoreCase("HAND"))
if (material == null)
{
Utils.sendMessage(user,
user.getTranslation(this.getWorld(), "level.conversations.unknown-item",
"[material]", args.get(0)));
user.getTranslation(this.getWorld(), "level.conversations.unknown-item",
MATERIAL, args.get(0)));
}
else
{
Expand All @@ -98,24 +99,24 @@ private void printValue(User user, Material material)
if (value != null)
{
Utils.sendMessage(user,
user.getTranslation(this.getWorld(), "level.conversations.value",
"[value]", String.valueOf(value),
"[material]", Utils.prettifyObject(material, user)));
user.getTranslation(this.getWorld(), "level.conversations.value",
"[value]", String.valueOf(value),
MATERIAL, Utils.prettifyObject(material, user)));

double underWater = this.addon.getSettings().getUnderWaterMultiplier();

if (underWater > 1.0)
{
Utils.sendMessage(user,
user.getTranslation(this.getWorld(),"level.conversations.success-underwater",
"[value]", (underWater * value) + ""),
"[material]", Utils.prettifyObject(material, user));
user.getTranslation(this.getWorld(),"level.conversations.success-underwater",
"[value]", (underWater * value) + ""),
MATERIAL, Utils.prettifyObject(material, user));
}
}
else
{
Utils.sendMessage(user,
user.getTranslation(this.getWorld(),"level.conversations.no-value"));
user.getTranslation(this.getWorld(),"level.conversations.no-value"));
}
}

Expand All @@ -132,8 +133,8 @@ public Optional<List<String>> tabComplete(User user, String alias, List<String>
}

List<String> options = new ArrayList<>(Arrays.stream(Material.values()).
filter(Material::isBlock).
map(Material::name).toList());
filter(Material::isBlock).
map(Material::name).toList());

options.add("HAND");

Expand Down