Skip to content

Commit

Permalink
Fix java linting
Browse files Browse the repository at this point in the history
  • Loading branch information
duncte123 committed Jan 18, 2024
1 parent 7428cc5 commit 07d0413
Show file tree
Hide file tree
Showing 16 changed files with 66 additions and 54 deletions.
7 changes: 6 additions & 1 deletion bot/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ plugins {
id("com.github.breadmoirai.github-release")
}

val pmdVersion = "7.0.0-rc4"

val numberVersion = "3.108.0"

project.group = "me.duncte123.skybot"
Expand Down Expand Up @@ -69,6 +71,9 @@ dependencies {
implementation(libs.redis)
implementation(libs.mariadb)
implementation(libs.bundles.database)

pmd("net.sourceforge.pmd:pmd-ant:$pmdVersion")
pmd("net.sourceforge.pmd:pmd-java:$pmdVersion")
}

val compileKotlin: KotlinCompile by tasks
Expand Down Expand Up @@ -183,7 +188,7 @@ kotlinter {

pmd {
isConsoleOutput = true
toolVersion = "6.55.0"
toolVersion = pmdVersion
rulesMinimumPriority.set(5)
ruleSets = listOf()
ruleSetFiles(File("linters/pmd.xml"))
Expand Down
27 changes: 25 additions & 2 deletions bot/linters/pmd.xml
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@
<exclude name="OnlyOneReturn"/>
<exclude name="UseUnderscoresInNumericLiterals"/>
<exclude name="TooManyStaticImports"/>
<exclude name="DefaultPackage"/>
<exclude name="CommentDefaultAccessModifier"/>
<exclude name="UselessParentheses"/>
<exclude name="LinguisticNaming"/>
</rule>

Expand All @@ -66,6 +67,7 @@
<exclude name="TooManyMethods"/>
<exclude name="NcssCount"/>
<exclude name="ExcessiveMethodLength"/>
<exclude name="MutableStaticState"/>
</rule>

<rule ref="category/java/design.xml/NPathComplexity">
Expand All @@ -74,6 +76,26 @@
</properties>
</rule>

<!-- TODO: make sure this is as low as you can get it -->
<rule ref="category/java/design.xml/CognitiveComplexity">
<properties>
<property name="reportLevel" value="40" />
</properties>
</rule>

<rule ref="category/java/bestpractices.xml/LooseCoupling">
<properties>
<property name="allowedTypes" value="java.util.Properties,com.jagrosh.jagtag.Environment,me.duncte123.skybot.objects.DBMap" />
</properties>
</rule>

<!-- TODO: make sure this is as low as you can get it -->
<rule ref="category/java/design.xml/CouplingBetweenObjects">
<properties>
<property name="threshold" value="40" />
</properties>
</rule>

<rule ref="category/java/errorprone.xml/AssignmentInOperand">
<properties>
<property name="allowIf" value="false" />
Expand All @@ -89,18 +111,19 @@

<rule ref="category/java/errorprone.xml">
<exclude name="AvoidCatchingThrowable"/>
<exclude name="AssignmentToNonFinalStatic"/>
<exclude name="CallSuperFirst"/>
<exclude name="CallSuperLast"/>
<exclude name="CloseResource"/>
<exclude name="DoNotCallGarbageCollectionExplicitly"/>
<exclude name="DoNotTerminateVM"/>
<exclude name="MissingSerialVersionUID"/>
<exclude name="OverrideBothEqualsAndHashcode"/>
<exclude name="BeanMembersShouldSerialize"/>
<exclude name="AvoidLiteralsInIfCondition"/>
<exclude name="UseLocaleWithCaseConversions"/>
<exclude name="AvoidDuplicateLiterals"/>
<exclude name="SimpleDateFormatNeedsLocale"/>
<exclude name="ReturnEmptyCollectionRatherThanNull"/>
</rule>

<rule ref="category/java/multithreading.xml">
Expand Down
6 changes: 1 addition & 5 deletions bot/src/main/java/fredboat/audio/player/LavalinkManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -107,11 +107,7 @@ public boolean isConnected(Guild guild) {
}

public boolean isConnected(long guildId) {
if (!isEnabled()) {
return false;
}

return lavalink.getLink(guildId).getState() == LinkState.CONNECTED;
return !isEnabled() || lavalink.getLink(guildId).getState() == LinkState.CONNECTED;
}

@SuppressWarnings("ConstantConditions") // cache is enabled
Expand Down
8 changes: 4 additions & 4 deletions bot/src/main/java/me/duncte123/skybot/SkyBot.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,10 @@
import static net.dv8tion.jda.api.utils.MemberCachePolicy.PENDING;

public final class SkyBot {
public static ScheduledExecutorService SYSTEM_POOL = Executors.newSingleThreadScheduledExecutor((r) -> {
final Thread t = new Thread(r, "System Pool");
t.setDaemon(true);
return t;
public static final ScheduledExecutorService SYSTEM_POOL = Executors.newSingleThreadScheduledExecutor((r) -> {
final Thread thread = new Thread(r, "System Pool");
thread.setDaemon(true);
return thread;
});

private static SkyBot instance;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import static me.duncte123.botcommons.messaging.MessageUtils.sendEmbed;
import static me.duncte123.botcommons.messaging.MessageUtils.sendMsg;

@SuppressWarnings("PMD.TestClassWithoutTestCases")
public class TestTagCommand extends Command {

public TestTagCommand() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ private void handleComplete(int count, CommandContext ctx) {
*
* @return the future with a different timeout
*/
@SuppressWarnings({"rawtypes", "unchecked"})
@SuppressWarnings({"rawtypes", "unchecked", "PMD.AvoidAccessibilityAlteration"})
private CompletableFuture<Void> hackTimeout(CompletableFuture<Void> future) {
if (!(future instanceof RestFuture)) {
// Ignore stuff that is not a rest future
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ private boolean canSendFile(CommandContext ctx) {
}

@SuppressWarnings("BooleanMethodIsAlwaysInverted")
/* package */ boolean passes(CommandContext ctx) {
/* package */ boolean passes(CommandContext ctx) {
return passes(ctx, true);
}

Expand Down Expand Up @@ -120,18 +120,18 @@ protected String getImageFromCommand(CommandContext ctx) {

// I hate this so much
// But I won't change one pmd rule just for the sake of using !isEmpty here
if (ctx.getMessage().getAttachments().size() > 0) {
if (ctx.getMessage().getAttachments().isEmpty()) {
url = tryGetAttachment(ctx);
} else if (!mentionedUsers.isEmpty()) {
url = getAvatarUrl(mentionedUsers.get(0));
url = getAvatarUrl(mentionedUsers.getFirst());
} else if (!args.isEmpty()) {
if (AirUtils.isURL(args.get(0))) {
url = tryGetUrl(ctx, args.get(0));
if (AirUtils.isURL(args.getFirst())) {
url = tryGetUrl(ctx, args.getFirst());
} else {
final List<Member> textMentions = FinderUtils.searchMembers(ctx.getArgsJoined(), ctx);

if (!textMentions.isEmpty()) {
url = getAvatarUrl(textMentions.get(0).getUser());
url = getAvatarUrl(textMentions.getFirst().getUser());
}
}
}
Expand All @@ -145,7 +145,7 @@ protected String getImageFromCommand(CommandContext ctx) {

@Nullable
private String tryGetAttachment(CommandContext ctx) {
final Attachment attachment = ctx.getMessage().getAttachments().get(0);
final Attachment attachment = ctx.getMessage().getAttachments().getFirst();

try (attachment) {
final File file = new File(attachment.getFileName());
Expand Down Expand Up @@ -200,7 +200,7 @@ protected String[] splitString(CommandContext ctx) {
return null;
}

if ("".equals(split[0].trim()) || "".equals(split[1].trim())) {
if (split[0].isBlank() || split[1].isBlank()) {
sendMsg(ctx, "Missing arguments, check `" + ctx.getPrefix() + "help " + getName() + '`');
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ public RedisConnection() {
connect();
}

@SuppressWarnings("PMD.AvoidThrowingRawExceptionTypes")
private void connect() {
if (!canConnect) {
throw new RuntimeException("Shutdown method was called, new connection not allowed");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ private void onGuildMemberRemove(GuildMemberRemoveEvent event) {

final Guild guild = event.getGuild();
final long guildId = guild.getIdLong();
final GuildMemberInfo guildCounts = GuildUtils.GUILD_MEMBER_COUNTS.getIfPresent(guildId);
final GuildMemberInfo guildCounts = GuildUtils.GUILD_MEMBER_COUNTS.get(guildId);

if (guildCounts != null) {
if (user.isBot()) {
Expand Down Expand Up @@ -327,7 +327,7 @@ private void logMemberNotification(User user, Guild guild, String titlePart, Str
}

private void updateGuildCount(GuildMemberJoinEvent event, Guild guild) {
final GuildMemberInfo guildCounts = GuildUtils.GUILD_MEMBER_COUNTS.getIfPresent(guild.getIdLong());
final GuildMemberInfo guildCounts = GuildUtils.GUILD_MEMBER_COUNTS.get(guild.getIdLong());

if (guildCounts != null) {
final User user = event.getUser();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,7 @@ private void handleMessageEventChecked(String raw, Guild guild, MessageReceivedE
}
}

@SuppressWarnings("PMD.SimplifyBooleanReturns")
private boolean doesNotStartWithPrefix(long selfId, String raw, String customPrefix) {
final String rwLower = raw.toLowerCase();

Expand Down Expand Up @@ -418,11 +419,7 @@ private boolean hasCorrectCategory(@Nonnull String raw, @Nonnull String category
getCommandName(customPrefix, raw).toLowerCase()
);

if (command == null) {
return false;
}

return command.getCategory() == CommandCategory.valueOf(categoryName.toUpperCase());
return command == null || command.getCategory() == CommandCategory.valueOf(categoryName.toUpperCase());
}

@SuppressWarnings("ConstantConditions")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,15 +182,7 @@ public String toString() {

@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}

if (!(obj instanceof final Command command)) {
return false;
}

return this.name.equals(command.getName());
return (obj instanceof final Command command) && this.name.equals(command.getName());
}

private String getCooldownKey(CommandContext ctx) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -217,11 +217,7 @@ public long getSendId() {
}

public boolean isChannelNSFW() {
if (getChannel() instanceof IAgeRestrictedChannel channel) {
return channel.isNSFW();
}

return false;
return (getChannel() instanceof IAgeRestrictedChannel channel) && channel.isNSFW();
}

// --------------- Methods that are in the GuildMessageReceivedEvent --------------- //
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public String getDefaultAvatarId() {
@Nonnull
@Override
public String getDefaultAvatarUrl() {
return String.format(User.DEFAULT_AVATAR_URL, getDefaultAvatarId());
return String.format(DEFAULT_AVATAR_URL, getDefaultAvatarId());
}

@Nonnull
Expand Down
4 changes: 2 additions & 2 deletions bot/src/main/java/me/duncte123/skybot/utils/AudioUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,8 @@ public TLongObjectMap<GuildMusicManager> getMusicManagers() {

public static String getTimestamp(long milliseconds) {
final int seconds = (int) (milliseconds / 1000) % 60;
final int minutes = (int) ((milliseconds / (1000 * 60)) % 60);
final int hours = (int) ((milliseconds / (1000 * 60 * 60)) % 24);
final int minutes = (int) (milliseconds / (1000 * 60)) % 60;
final int hours = (int) (milliseconds / (1000 * 60 * 60)) % 24;

if (hours > 0) {
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
Expand Down
14 changes: 7 additions & 7 deletions bot/src/main/java/me/duncte123/skybot/utils/GuildUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@

import io.sentry.Sentry;
import me.duncte123.skybot.database.AbstractDatabase;
import me.duncte123.skybot.objects.DBMap;
import me.duncte123.skybot.objects.GuildMemberInfo;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Guild.VerificationLevel;
Expand All @@ -33,15 +32,16 @@

import javax.annotation.Nonnull;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class GuildUtils {
public static final DBMap<Long, GuildMemberInfo> GUILD_MEMBER_COUNTS = new DBMap<>(ExpiringMap.builder()
public static final Map<Long, GuildMemberInfo> GUILD_MEMBER_COUNTS = ExpiringMap.builder()
.expirationPolicy(ExpirationPolicy.ACCESSED)
.expiration(1, TimeUnit.HOURS)
.build());
.build();
private static final Logger LOGGER = LoggerFactory.getLogger(GuildUtils.class);

private GuildUtils() {}
Expand Down Expand Up @@ -73,7 +73,7 @@ public static long[] getBotAndUserCount(Guild guild) {
}
}

final GuildMemberInfo guildCount = GUILD_MEMBER_COUNTS.getIfPresent(guild.getIdLong());
final GuildMemberInfo guildCount = GUILD_MEMBER_COUNTS.get(guild.getIdLong());

// This should never happen
if (guildCount == null) {
Expand Down Expand Up @@ -105,10 +105,10 @@ public static double[] getBotRatio(Guild guild) {
final double botCount = counts[1];

//percent in users
final double userCountP = (userCount / totalCount) * 100;
final double userCountP = userCount / totalCount * 100;

//percent in bots
final double botCountP = (botCount / totalCount) * 100;
final double botCountP = botCount / totalCount * 100;

LOGGER.debug("In the guild {}({} Members), {}% are users, {}% are bots",
guild.getName(),
Expand All @@ -125,7 +125,7 @@ public static double[] getBotRatio(Guild guild) {
}

public static long getNitroUserCountCache(Guild guild) {
final GuildMemberInfo guildCount = GUILD_MEMBER_COUNTS.getIfPresent(guild.getIdLong());
final GuildMemberInfo guildCount = GUILD_MEMBER_COUNTS.get(guild.getIdLong());

// This should never happen
if (guildCount == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@ public static float checkSwearFilter(String text, String channelId, String apiKe
return 0f;
}

throw new HttpException("Error while handling perspective api request: " + json);
Sentry.captureException(new HttpException("Error while handling perspective api request: " + json));

return 0f;
}

final JsonNode score = json.get("attributeScores")
Expand All @@ -67,7 +69,6 @@ public static float checkSwearFilter(String text, String channelId, String apiKe
}
catch (Exception e) {
Sentry.captureException(e);
e.printStackTrace();

return 0f;
}
Expand Down

0 comments on commit 07d0413

Please sign in to comment.