Fix more sonar smells

This commit is contained in:
Aurora Lahtela 2023-01-20 22:54:54 +02:00
parent 52a80622ce
commit dda7199a1a
26 changed files with 78 additions and 99 deletions

View File

@ -31,9 +31,8 @@ public class ComponentSvc implements ComponentService {
private ComponentConverter converter;
// This is required to inject
@Inject
public ComponentSvc() {}
public ComponentSvc() {/* Dagger constructor */}
@Override
public String translateLegacy(String input, char inputCharacter, char outputCharacter) {

View File

@ -46,8 +46,8 @@ public class RetentionData {
totalPlayersOnline += retentionData.getOnlineOnJoin();
}
double averageIndex = totalIndex / (double) size;
double averagePlayersOnline = totalPlayersOnline / (double) size;
double averageIndex = totalIndex / size;
double averagePlayersOnline = totalPlayersOnline / size;
return new RetentionData(averageIndex, averagePlayersOnline);
}

View File

@ -59,7 +59,7 @@ class ActivityStackGraph extends StackGraph {
for (Map<String, Integer> data : activityData.values()) {
for (int j = 0; j < groups.length; j++) {
dataSets[j].add((double) data.getOrDefault(defaultGroups[j], 0));
dataSets[j].add(data.getOrDefault(defaultGroups[j], 0));
}
}

View File

@ -127,9 +127,9 @@ public class WebAssetVersionCheckTask extends TaskSystem.Task {
}
private static class AssetInfo {
public String filename;
public long modifiedAt;
public long expectedModifiedAt;
private final String filename;
private final long modifiedAt;
private final long expectedModifiedAt;
public AssetInfo(String filename, long modifiedAt, long expectedModifiedAt) {
this.filename = filename;

View File

@ -73,12 +73,10 @@ public class PassBruteForceGuard {
}
@Override
public void increaseAttemptCountOnFailedLogin(String accessor) {
}
public void increaseAttemptCountOnFailedLogin(String accessor) { /* Disabled */ }
@Override
public void resetAttemptCount(String accessor) {
}
public void resetAttemptCount(String accessor) { /* Disabled */ }
}
}

View File

@ -41,7 +41,7 @@ import java.util.concurrent.TimeUnit;
public class ActiveCookieStore implements SubSystem {
private static final Map<String, User> USERS_BY_COOKIE = new ConcurrentHashMap<>();
public static long cookieExpiresAfterMs = TimeUnit.HOURS.toMillis(2L);
private static long cookieExpiresAfterMs = TimeUnit.HOURS.toMillis(2L);
private final ActiveCookieExpiryCleanupTask activeCookieExpiryCleanupTask;
@ -67,6 +67,10 @@ public class ActiveCookieStore implements SubSystem {
this.processing = processing;
}
public static long getCookieExpiresAfterMs() {
return cookieExpiresAfterMs;
}
private static void removeCookieStatic(String cookie) {
Holder.getActiveCookieStore().removeCookie(cookie);
}

View File

@ -59,7 +59,7 @@ public class JSONFileStorage implements JSONStorage {
private final Path jsonDirectory;
private final ReentrantLockHelper readWriteProtectionLock = new ReentrantLockHelper();
private final Pattern timestampRegex = Pattern.compile(".*-([0-9]*).json");
private final Pattern timestampRegex = Pattern.compile(".*-(\\d*).json");
private static final String JSON_FILE_EXTENSION = ".json";
private final Formatter<Long> dateFormatter;

View File

@ -88,7 +88,7 @@ public class LoginResolver implements NoAuthResolver {
public Response getResponse(String cookie) {
return Response.builder()
.setStatus(200)
.setHeader("Set-Cookie", "auth=" + cookie + "; Path=/; Max-Age=" + ActiveCookieStore.cookieExpiresAfterMs + "; SameSite=Lax; Secure;")
.setHeader("Set-Cookie", "auth=" + cookie + "; Path=/; Max-Age=" + ActiveCookieStore.getCookieExpiresAfterMs() + "; SameSite=Lax; Secure;")
.setJSONContent(Collections.singletonMap("success", true))
.build();
}

View File

@ -44,11 +44,10 @@ public abstract class ServerInfo implements SubSystem {
}
public ServerUUID getServerUUID() {
return getServer().getUuid();
return server.getUuid();
}
public ServerIdentifier getServerIdentifier() {
Server server = getServer();
return new ServerIdentifier(server.getUuid(), server.getIdentifiableName());
}

View File

@ -23,4 +23,8 @@ import com.djrapitops.plan.settings.config.paths.key.StringSetting;
public class CustomizedFileSettings {
public static final Setting<Boolean> WEB_DEV_MODE = new BooleanSetting("Customized_files.Enable_web_dev_mode");
public static final Setting<String> PATH = new StringSetting("Customized_files.Path");
private CustomizedFileSettings() {
/* static variable class*/
}
}

View File

@ -117,6 +117,7 @@ class TranslatedString {
@Override
public void translate(String replace, String with) {
/* Some elements should not be translated, like URLs */
}
@Override

View File

@ -125,12 +125,7 @@ public class MySQLDB extends SQLDB {
increment();
hikariConfig.setAutoCommit(false);
try {
hikariConfig.setMaximumPoolSize(config.get(DatabaseSettings.MAX_CONNECTIONS));
} catch (IllegalStateException e) {
logger.warn(e.getMessage() + ", using 1 as maximum for now.");
hikariConfig.setMaximumPoolSize(1);
}
setMaxConnections(hikariConfig);
hikariConfig.setMaxLifetime(TimeUnit.MINUTES.toMillis(25L));
hikariConfig.setLeakDetectionThreshold(TimeUnit.SECONDS.toMillis(29L));
@ -145,6 +140,15 @@ public class MySQLDB extends SQLDB {
currentThread.setContextClassLoader(previousClassLoader);
}
private void setMaxConnections(HikariConfig hikariConfig) {
try {
hikariConfig.setMaximumPoolSize(config.get(DatabaseSettings.MAX_CONNECTIONS));
} catch (IllegalStateException e) {
logger.warn(e.getMessage() + ", using 1 as maximum for now.");
hikariConfig.setMaximumPoolSize(1);
}
}
private void unloadMySQLDriver() {
// Avoid issues with other plugins by removing the mysql driver from driver manager
Enumeration<Driver> drivers = DriverManager.getDrivers();

View File

@ -16,13 +16,9 @@
*/
package com.djrapitops.plan.storage.database.transactions.init;
import com.djrapitops.plan.storage.database.queries.HasMoreThanZeroQueryStatement;
import com.djrapitops.plan.storage.database.queries.Query;
import com.djrapitops.plan.storage.database.transactions.patches.Patch;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import static com.djrapitops.plan.storage.database.sql.building.Sql.*;
/**
@ -30,24 +26,21 @@ import static com.djrapitops.plan.storage.database.sql.building.Sql.*;
*/
public class RemoveIncorrectTebexPackageDataPatch extends Patch {
private static final String TABLE_NAME = "plan_tebex_payments";
@Override
public boolean hasBeenApplied() {
return !hasTable("plan_tebex_payments") || !query(hasWrongRows());
return !hasTable(TABLE_NAME) || !query(hasWrongRows());
}
private Query<Boolean> hasWrongRows() {
return new HasMoreThanZeroQueryStatement(
SELECT + "COUNT(*) as c" + FROM + "plan_tebex_payments" +
WHERE + "packages LIKE 'TebexPackage%'"
) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
}
};
String sql = SELECT + "COUNT(*) as c" + FROM + TABLE_NAME +
WHERE + "packages LIKE 'TebexPackage%'";
return db -> db.queryOptional(sql, set -> set.getInt("c") > 0).orElse(false);
}
@Override
protected void applyPatch() {
execute(DELETE_FROM + "plan_tebex_payments" + WHERE + "packages LIKE 'TebexPackage%'");
execute(DELETE_FROM + TABLE_NAME + WHERE + "packages LIKE 'TebexPackage%'");
}
}

View File

@ -26,7 +26,6 @@ import com.djrapitops.plan.storage.database.transactions.ExecBatchStatement;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Set;
import static com.djrapitops.plan.storage.database.sql.building.Sql.*;
@ -110,13 +109,4 @@ public class AfterBadJoinAddressDataCorrectionPatch extends Patch {
return query(db -> db.queryOptional(sql, results -> results.getInt("c") > 0))
.orElse(false);
}
private Set<Integer> getBadAddressIds() {
String sql = SELECT + DISTINCT + SessionsTable.JOIN_ADDRESS_ID +
FROM + SessionsTable.TABLE_NAME +
WHERE + SessionsTable.JOIN_ADDRESS_ID + " NOT IN (" +
SELECT + JoinAddressTable.ID + FROM + JoinAddressTable.TABLE_NAME +
")";
return query(db -> db.querySet(sql, results -> results.getInt(SessionsTable.JOIN_ADDRESS_ID)));
}
}

View File

@ -18,6 +18,10 @@ package com.djrapitops.plan.utilities.analysis;
public class Percentage {
private Percentage() {
/* static utility method class */
}
public static double calculate(double amount, long total) {
return calculate(amount, total, 0);
}

View File

@ -23,7 +23,7 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class VersionNumber implements Comparable<VersionNumber> {
private static final Pattern MATCH_NUMBERS = Pattern.compile("([0-9]+)");
private static final Pattern MATCH_NUMBERS = Pattern.compile("(\\d+)");
private final String version;
private final List<Long> versionNumbers;

View File

@ -26,34 +26,34 @@ import org.junit.jupiter.api.extension.ExtendWith;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ExtendWith(FullSystemExtension.class)
public class ComponentServiceTest {
class ComponentServiceTest {
static ComponentSvc service;
@BeforeAll
public static void enableSystem(PlanSystem system) {
static void enableSystem(PlanSystem system) {
system.enable();
service = (ComponentSvc) ComponentService.getInstance();
}
@AfterAll
public static void tearDown(PlanSystem system) {
static void tearDown(PlanSystem system) {
service = null;
system.disable();
}
@Test
public void translateTest() {
void translateTest() {
assertEquals("§cred", service.translateLegacy("&cred"));
}
@Test
public void invalidTranslateTest() {
void invalidTranslateTest() {
assertEquals("&zinvalid color code", service.translateLegacy("&zinvalid color code"));
}
@Test
public void testAutoDetermine() {
void testAutoDetermine() {
assertEquals("§cred", service.convert(service.fromAutoDetermine("<red>red"), ComponentOperation.LEGACY, Component.SECTION));
assertEquals("§cred", service.convert(service.fromAutoDetermine("&cred"), ComponentOperation.LEGACY, Component.SECTION));
assertEquals("&cred", service.convert(service.fromAutoDetermine("§cred"), ComponentOperation.LEGACY, Component.AMPERSAND));

View File

@ -28,7 +28,7 @@ import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ClassValuePairOrderTest {
class ClassValuePairOrderTest {
@Test
void providedConditionsComeBeforeConditions() throws NoSuchMethodException {

View File

@ -25,7 +25,7 @@ import java.util.Collections;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class ExtensionDataBuilderTest {
class ExtensionDataBuilderTest {
@Test
void nullTextWhenCreatingValueBuilderThrowsException() {
ExtDataBuilder builder = new ExtDataBuilder(new Extension());

View File

@ -17,6 +17,8 @@
package com.djrapitops.plan.settings.config;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.time.ZoneId;
import java.util.Optional;
@ -31,33 +33,16 @@ import static org.junit.jupiter.api.Assertions.*;
*/
class TimeZoneUtilityTest {
@Test
void utcIsValidZoneID() {
ZoneId zone = ZoneId.of("UTC");
assertNotNull(zone);
}
@Test
void gmtPlusIsValidZoneID() {
ZoneId zone = ZoneId.of("GMT+3");
assertNotNull(zone);
}
@Test
void gmtMinusIsValidZoneID() {
ZoneId zone = ZoneId.of("GMT-3");
assertNotNull(zone);
}
@Test
void gmtPlusMinutesIsValidZoneID() {
ZoneId zone = ZoneId.of("GMT+03:30");
assertNotNull(zone);
}
@Test
void gmtMinusMinutesIsValidZoneID() {
ZoneId zone = ZoneId.of("GMT-03:30");
@ParameterizedTest
@CsvSource({
"UTC",
"GMT+3",
"GMT-3",
"GMT+03:30",
"GMT-03:30"
})
void isValidZoneId(String zoneId) {
ZoneId zone = ZoneId.of(zoneId);
assertNotNull(zone);
}

View File

@ -68,7 +68,7 @@ public class ComponentConverterImpl implements ComponentConverter {
boolean isMM = false;
try {
isMM = MiniMessage.miniMessage().stripTags(input).length() != input.length();
} catch (Throwable ignored) {
} catch (Exception ignored) {
// MiniMessage may in some cases throw an exception, for example when it is given a legacy section.
}

View File

@ -27,7 +27,7 @@ public class FabricPlayerPositionTracker {
private static final double[] EMPTY_POSITION = new double[5];
public FabricPlayerPositionTracker() {
private FabricPlayerPositionTracker() {
// Static method class
}

View File

@ -46,15 +46,16 @@ public class FabricVersionChecker extends VersionChecker {
super(currentVersion, locale, config, logger, runnableFactory, errorLogger);
}
@Override
public Optional<VersionInfo> getNewVersionAvailable() {
if (newVersionAvailable == null) {
return Optional.empty();
} else {
return Optional.of(new VersionInfo(
newVersionAvailable.isRelease(),
newVersionAvailable.getVersion(),
newVersionAvailable.getDownloadUrl().replace("Plan-", "PlanFabric-"),
newVersionAvailable.getChangeLogUrl()
newVersionAvailable.isRelease(),
newVersionAvailable.getVersion(),
newVersionAvailable.getDownloadUrl().replace("Plan-", "PlanFabric-"),
newVersionAvailable.getChangeLogUrl()
));
}
}

View File

@ -34,13 +34,13 @@ public class FabricListeners implements Listeners {
public void registerListener(Object listener) {
if (listener == null) {
throw new IllegalArgumentException("Listener can not be null!");
} else if (!(listener instanceof FabricListener)) {
throw new IllegalArgumentException("Listener needs to be of type " + listener.getClass().getName() + ", but was " + listener.getClass());
} else {
if (!((FabricListener) listener).isEnabled()) {
((FabricListener) listener).register();
listeners.add((FabricListener) listener);
} else if (listener instanceof FabricListener fabricListener) {
if (!fabricListener.isEnabled()) {
fabricListener.register();
listeners.add(fabricListener);
}
} else {
throw new IllegalArgumentException("Listener needs to be of type " + listener.getClass().getName() + ", but was " + listener.getClass());
}
}

View File

@ -62,6 +62,7 @@ public class SpongeSensor implements ServerSensor<ServerWorld> {
return -1;
}
@SuppressWarnings("unused") // This remains here so that it is not enabled, it causes lag.
private int getLaggyChunkCount(ServerWorld world) {
Iterator<WorldChunk> chunks = world.loadedChunks().iterator();
int count = 0;

View File

@ -185,8 +185,4 @@ public class PlanVelocity implements PlanPlugin {
public File getDataFolder() {
return dataFolderPath.toFile();
}
private String fixMsgParams(String message) {
return message.replaceAll("\\{\\d+}", "{}");
}
}