addressed sonar code smells

This commit is contained in:
Sheldan
2020-05-27 19:32:19 +02:00
parent 175a92408c
commit 3fa5edf67a
77 changed files with 164 additions and 243 deletions

View File

@@ -33,7 +33,7 @@ public class CommandCreationListener {
@EventListener
@Transactional
public void handleContextRefreshEvent(ContextRefreshedEvent ctxStartEvt) {
featureFlagService.getAllFeatureConfigs().forEach((featureFlagKey) -> {
featureFlagService.getAllFeatureConfigs().forEach(featureFlagKey -> {
String featureKey = featureFlagKey.getFeature().getKey();
if(!featureManagementService.featureExists(featureKey)) {
featureManagementService.createFeature(featureKey);
@@ -44,7 +44,7 @@ public class CommandCreationListener {
log.warn("Command {} has null configuration.", command);
return;
}
if(!commandService.doesCommandExist(command.getConfiguration().getName())) {
if(commandService.doesCommandExist(command.getConfiguration().getName())) {
commandService.createCommand(command.getConfiguration().getName(), command.getConfiguration().getModule(), command.getFeature());
}
});

View File

@@ -50,7 +50,7 @@ public class CommandServiceBean implements CommandService {
}
@Override
public Boolean doesCommandExist(String name) {
public boolean doesCommandExist(String name) {
return commandManagementService.doesCommandExist(name);
}
@@ -66,9 +66,7 @@ public class CommandServiceBean implements CommandService {
@Override
public void allowFeatureForRole(FeatureEnum featureEnum, ARole role) {
AFeature feature = featureManagementService.getFeature(featureEnum.getKey());
feature.getCommands().forEach(command -> {
this.allowCommandForRole(command, role);
});
feature.getCommands().forEach(command -> this.allowCommandForRole(command, role));
}
@Override
@@ -107,9 +105,7 @@ public class CommandServiceBean implements CommandService {
@Override
public void disAllowFeatureForRole(FeatureEnum featureEnum, ARole role) {
AFeature feature = featureManagementService.getFeature(featureEnum.getKey());
feature.getCommands().forEach(command -> {
this.disAllowCommandForRole(command, role);
});
feature.getCommands().forEach(command -> this.disAllowCommandForRole(command, role));
}
public ConditionResult isCommandExecutable(Command command, CommandContext commandContext) {

View File

@@ -44,7 +44,7 @@ public class CommandManagementServiceBean implements CommandManagementService {
}
@Override
public Boolean doesCommandExist(String name) {
public boolean doesCommandExist(String name) {
return findCommandByName(name) != null;
}

View File

@@ -4,6 +4,7 @@ import dev.sheldan.abstracto.core.command.condition.AbstractConditionableCommand
import dev.sheldan.abstracto.core.command.config.CommandConfiguration;
import dev.sheldan.abstracto.core.command.config.HelpInfo;
import dev.sheldan.abstracto.core.command.config.Parameter;
import dev.sheldan.abstracto.core.command.config.features.CoreFeatures;
import dev.sheldan.abstracto.core.command.execution.CommandContext;
import dev.sheldan.abstracto.core.command.execution.CommandResult;
import dev.sheldan.abstracto.core.command.models.database.ACommand;
@@ -11,12 +12,9 @@ import dev.sheldan.abstracto.core.command.service.CommandService;
import dev.sheldan.abstracto.core.command.service.management.CommandManagementService;
import dev.sheldan.abstracto.core.command.service.management.FeatureManagementService;
import dev.sheldan.abstracto.core.commands.config.ConfigModuleInterface;
import dev.sheldan.abstracto.core.config.FeatureConfig;
import dev.sheldan.abstracto.core.config.FeatureEnum;
import dev.sheldan.abstracto.core.command.config.features.CoreFeatures;
import dev.sheldan.abstracto.core.models.database.ARole;
import dev.sheldan.abstracto.core.service.FeatureConfigService;
import dev.sheldan.abstracto.core.service.FeatureFlagService;
import dev.sheldan.abstracto.core.service.management.RoleManagementService;
import dev.sheldan.abstracto.templating.service.TemplateService;
import org.springframework.beans.factory.annotation.Autowired;

View File

@@ -51,9 +51,9 @@ public class Disable extends AbstractConditionableCommand {
FeatureConfig feature = featureConfigService.getFeatureDisplayForFeature(flagKey);
featureFlagService.disableFeature(feature, commandContext.getGuild().getIdLong());
if(feature.getDependantFeatures() != null) {
feature.getDependantFeatures().forEach(featureDisplay -> {
featureFlagService.disableFeature(featureDisplay, commandContext.getUserInitiatedContext().getServer());
});
feature.getDependantFeatures().forEach(featureDisplay ->
featureFlagService.disableFeature(featureDisplay, commandContext.getUserInitiatedContext().getServer())
);
}
}
return CommandResult.fromSuccess();

View File

@@ -50,7 +50,7 @@ public class Enable extends AbstractConditionableCommand {
String flagKey = (String) commandContext.getParameters().getParameters().get(0);
FeatureConfig feature = featureConfigService.getFeatureDisplayForFeature(flagKey);
FeatureValidationResult featureSetup = featureConfigService.validateFeatureSetup(feature, commandContext.getUserInitiatedContext().getServer());
if(!featureSetup.getValidationResult()) {
if(Boolean.FALSE.equals(featureSetup.getValidationResult())) {
channelService.sendTextToChannelNoFuture(templateService.renderTemplatable(featureSetup), commandContext.getChannel());
}
featureFlagService.enableFeature(feature, commandContext.getUserInitiatedContext().getServer());

View File

@@ -89,7 +89,7 @@ public class Help implements Command {
ACommand aCommand = commandManagementService.findCommandByName(parameter);
ACommandInAServer aCommandInAServer = commandInServerManagementService.getCommandForServer(aCommand, commandContext.getUserInitiatedContext().getServer());
HelpCommandDetailsModel model = (HelpCommandDetailsModel) ContextConverter.fromCommandContext(commandContext, HelpCommandDetailsModel.class);
if(aCommandInAServer.getRestricted()) {
if(Boolean.TRUE.equals(aCommandInAServer.getRestricted())) {
model.setImmuneRoles(roleService.getRolesFromGuild(aCommandInAServer.getImmuneRoles()));
model.setAllowedRoles(roleService.getRolesFromGuild(aCommandInAServer.getAllowedRoles()));
model.setRestricted(true);

View File

@@ -2,7 +2,6 @@ package dev.sheldan.abstracto.core.interactive;
import com.jagrosh.jdautilities.commons.waiter.EventWaiter;
import com.jagrosh.jdautilities.menu.ButtonMenu;
import dev.sheldan.abstracto.core.models.FullUser;
import dev.sheldan.abstracto.core.models.database.AChannel;
import dev.sheldan.abstracto.core.models.database.AEmote;
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
@@ -14,16 +13,12 @@ import dev.sheldan.abstracto.templating.model.MessageToSend;
import dev.sheldan.abstracto.templating.service.TemplateService;
import lombok.extern.slf4j.Slf4j;
import net.dv8tion.jda.api.entities.Emote;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
@@ -100,7 +95,7 @@ public class InteractiveServiceBean implements InteractiveService {
private void addEmoteToBuilder(String key, Consumer<Void> consumer, Long serverId, ButtonMenu.Builder builder, HashMap<String, Consumer<Void>> actions) {
AEmote emoteOrFakeEmote = emoteService.getEmoteOrFakeEmote(key, serverId);
if(emoteOrFakeEmote.getCustom()){
if(Boolean.TRUE.equals(emoteOrFakeEmote.getCustom())){
Optional<Emote> emote = botService.getEmote(serverId, emoteOrFakeEmote);
emote.ifPresent(emote1 -> {
builder.addChoice(emote1);

View File

@@ -14,7 +14,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;

View File

@@ -46,7 +46,7 @@ public class FeatureFlagListener implements ServerConfigListener {
@Override
public void updateServerConfig(AServer server) {
log.info("Setting up feature flags if necessary.");
featureFlagService.getAllFeatureConfigs().forEach((featureFlagKey) -> {
featureFlagService.getAllFeatureConfigs().forEach(featureFlagKey -> {
String featureKey = featureFlagKey.getFeature().getKey();
AFeature feature = featureManagementService.getFeature(featureKey);
if(featureConfigLoader.getFeatures().containsKey(featureKey)) {

View File

@@ -42,7 +42,7 @@ public class ReactionUpdatedListener extends ListenerAdapter {
private List<ReactionClearedListener> clearedListenerList;
@Autowired
private List<ReactedRemovedListener> reactionRemovedListener;
private List<ReactedRemovedListener> reactionRemovedListeners;
@Autowired
private ReactionUpdatedListener self;
@@ -63,15 +63,15 @@ public class ReactionUpdatedListener extends ListenerAdapter {
return;
}
CompletableFuture<CachedMessage> asyncMessageFromCache = messageCache.getMessageFromCache(event.getGuild().getIdLong(), event.getChannel().getIdLong(), event.getMessageIdLong());
asyncMessageFromCache.thenAccept(cachedMessage -> {
asyncMessageFromCache.thenAccept(cachedMessage ->
messageCache.getCachedReactionFromReaction(event.getReaction()).thenAccept(reaction -> {
self.callAddedListeners(event, cachedMessage, reaction);
messageCache.putMessageInCache(cachedMessage);
}).exceptionally(throwable -> {
log.error("Failed to add reaction to message {} ", event.getMessageIdLong(), throwable);
return null;
});
}).exceptionally(throwable -> {
})
).exceptionally(throwable -> {
log.error("Message retrieval {} from cache failed. ", event.getMessageIdLong(), throwable);
return null;
});
@@ -146,7 +146,7 @@ public class ReactionUpdatedListener extends ListenerAdapter {
public void callRemoveListeners(@Nonnull GuildMessageReactionRemoveEvent event, CachedMessage cachedMessage, CachedReaction reaction) {
AUserInAServer userInAServer = userInServerManagementService.loadUser(event.getGuild().getIdLong(), event.getUserIdLong());
removeReactionIfThere(cachedMessage, reaction, userInAServer);
reactionRemovedListener.forEach(reactionRemovedListener -> {
reactionRemovedListeners.forEach(reactionRemovedListener -> {
FeatureConfig feature = featureConfigService.getFeatureDisplayForFeature(reactionRemovedListener.getFeature());
if(!featureFlagService.isFeatureEnabled(feature, event.getGuild().getIdLong())) {
return;

View File

@@ -131,7 +131,7 @@ public class BotServiceBean implements BotService {
@Override
public Optional<Emote> getEmote(Long serverId, AEmote emote) {
if(!emote.getCustom()) {
if(Boolean.FALSE.equals(emote.getCustom())) {
return Optional.empty();
}
Optional<Guild> guildById = getGuildById(serverId);

View File

@@ -21,9 +21,6 @@ import java.util.Optional;
@Component
public class ChannelGroupServiceBean implements ChannelGroupService {
private static final String CHANNEL_GROUP_NOT_FOUND = "Channel group %s was not found.";
private static final String COMMAND_NOT_FOUND = "Command %s not found.";
@Autowired
private ChannelGroupManagementService channelGroupManagementService;

View File

@@ -15,11 +15,11 @@ public class DelayedActionServiceBean implements DelayedActionService {
@Override
public void executeDelayedActions(List<DelayedActionConfig> delayedActionConfigList) {
delayedActionConfigList.forEach(delayedActionConfig -> {
delayedActionConfigList.forEach(delayedActionConfig ->
delayedActions.stream()
.filter(delayedAction -> delayedAction.handles(delayedActionConfig))
.findFirst()
.ifPresent(delayedAction -> delayedAction.execute(delayedActionConfig));
});
.ifPresent(delayedAction -> delayedAction.execute(delayedActionConfig))
);
}
}

View File

@@ -91,7 +91,8 @@ public class FeatureConfigServiceBean implements FeatureConfigService {
Predicate<PostTargetEnum> postTargetComparison = postTargetEnum -> postTargetEnum.getKey().equalsIgnoreCase(key);
Optional<FeatureConfig> foundFeature = availableFeatures.stream().filter(featureDisplay -> featureDisplay.getRequiredPostTargets().stream().anyMatch(postTargetComparison)).findAny();
if(foundFeature.isPresent()) {
return foundFeature.get().getRequiredPostTargets().stream().filter(postTargetComparison).findAny().get();
Optional<PostTargetEnum> any = foundFeature.get().getRequiredPostTargets().stream().filter(postTargetComparison).findAny();
return any.orElse(null);
}
throw new AbstractoRunTimeException(String.format("Post target %s not found.", key));
}
@@ -99,18 +100,18 @@ public class FeatureConfigServiceBean implements FeatureConfigService {
@Override
public FeatureValidationResult validateFeatureSetup(FeatureConfig featureConfig, AServer server) {
FeatureValidationResult featureValidationResult = FeatureValidationResult.validationSuccessful(featureConfig);
featureConfig.getRequiredPostTargets().forEach(s -> {
featureValidatorService.checkPostTarget(s, server, featureValidationResult);
});
featureConfig.getRequiredSystemConfigKeys().forEach(s -> {
featureValidatorService.checkSystemConfig(s, server, featureValidationResult);
});
featureConfig.getRequiredEmotes().forEach(s -> {
featureValidatorService.checkEmote(s, server, featureValidationResult);
});
featureConfig.getAdditionalFeatureValidators().forEach(featureValidator -> {
featureValidator.featureIsSetup(featureConfig, server, featureValidationResult);
});
featureConfig.getRequiredPostTargets().forEach(s ->
featureValidatorService.checkPostTarget(s, server, featureValidationResult)
);
featureConfig.getRequiredSystemConfigKeys().forEach(s ->
featureValidatorService.checkSystemConfig(s, server, featureValidationResult)
);
featureConfig.getRequiredEmotes().forEach(s ->
featureValidatorService.checkEmote(s, server, featureValidationResult)
);
featureConfig.getAdditionalFeatureValidators().forEach(featureValidator ->
featureValidator.featureIsSetup(featureConfig, server, featureValidationResult)
);
return featureValidationResult;
}

View File

@@ -3,10 +3,7 @@ package dev.sheldan.abstracto.core.service;
import dev.sheldan.abstracto.core.command.service.management.FeatureManagementService;
import dev.sheldan.abstracto.core.config.FeatureConfig;
import dev.sheldan.abstracto.core.config.FeatureEnum;
import dev.sheldan.abstracto.core.config.PostTargetEnum;
import dev.sheldan.abstracto.core.exception.AbstractoRunTimeException;
import dev.sheldan.abstracto.core.exception.FeatureNotFoundException;
import dev.sheldan.abstracto.core.models.FeatureValidationResult;
import dev.sheldan.abstracto.core.models.database.AFeature;
import dev.sheldan.abstracto.core.models.database.AFeatureFlag;
import dev.sheldan.abstracto.core.models.database.AServer;
@@ -15,11 +12,6 @@ import dev.sheldan.abstracto.core.service.management.ServerManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;
@Component
public class FeatureFlagServiceBean implements FeatureFlagService {

View File

@@ -88,15 +88,15 @@ public class MessageCacheBean implements MessageCache {
if(textChannelByIdOptional.isPresent()) {
TextChannel textChannel = textChannelByIdOptional.get();
textChannel.retrieveMessageById(messageId).queue(message ->
{
buildCachedMessageFromMessage(message)
.thenAccept(future::complete)
.exceptionally(throwable -> {
log.error("Failed to load message for caching.", throwable);
future.completeExceptionally(throwable);
return null;
});
}
})
);
} else {
log.error("Not able to load message {} in channel {} in guild {}. Text channel not found.", messageId, textChannelId, guildId);
@@ -123,9 +123,7 @@ public class MessageCacheBean implements MessageCache {
);
List<CompletableFuture<CachedReaction>> futures = new ArrayList<>();
message.getReactions().forEach(messageReaction -> {
futures.add(self.getCachedReactionFromReaction(messageReaction));
});
message.getReactions().forEach(messageReaction -> futures.add(self.getCachedReactionFromReaction(messageReaction)));
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).thenAccept(aVoid ->
future.complete(CachedMessage.builder()

View File

@@ -48,7 +48,7 @@ public class MessageServiceBean implements MessageService {
AEmote emote = emoteService.getEmoteOrFakeEmote(emoteKey, serverId);
if(guildByIdOptional.isPresent()) {
Guild guild = guildByIdOptional.get();
if(emote.getCustom()) {
if(Boolean.TRUE.equals(emote.getCustom())) {
Emote emoteById = botService.getInstance().getEmoteById(emote.getEmoteId());
if(emoteById != null) {
return message.addReaction(emoteById).submit();
@@ -68,9 +68,7 @@ public class MessageServiceBean implements MessageService {
@Override
public List<CompletableFuture<Void>> addReactionsToMessageWithFuture(List<String> emoteKeys, Long serverId, Message message) {
List<CompletableFuture<Void>> futures = new ArrayList<>();
emoteKeys.forEach(s -> {
futures.add(addReactionToMessageWithFuture(s, serverId, message));
});
emoteKeys.forEach(s -> futures.add(addReactionToMessageWithFuture(s, serverId, message)));
return futures;
}

View File

@@ -42,9 +42,7 @@ public class PaginatorServiceBean implements PaginatorService {
.setEventWaiter(waiter)
.waitOnSinglePage(true)
.setTimeout(ObjectUtils.defaultIfNull(configuration.getTimeoutSeconds(), 120L), TimeUnit.SECONDS)
.setFinalAction(message -> {
message.delete().queue();
})
.setFinalAction(message -> message.delete().queue())
.build();
}

View File

@@ -137,9 +137,7 @@ public class SetupServiceBean implements SetupService {
.delayedActionList(delayedActionConfigs)
.previousMessageId(initialMessage)
.build();
setupSummaryStep.execute(user, parameter).thenAccept(ignored -> {
self.notifyAboutCompletion(user, featureConfig);
});
setupSummaryStep.execute(user, parameter).thenAccept(ignored -> self.notifyAboutCompletion(user, featureConfig));
}
@Transactional

View File

@@ -23,26 +23,24 @@ public class UndoActionServiceBean implements UndoActionService {
actionsToPerform.forEach(undoActionInstance -> {
UndoAction action = undoActionInstance.getAction();
List<Long> ids = undoActionInstance.getIds();
switch (action) {
case DELETE_CHANNEL:
if(ids.size() != 2) {
log.error("Not the correct amount of ids provided for the channel deletion undo action.");
break;
}
deleteChannel(ids.get(0), ids.get(1));
break;
case DELETE_MESSAGE:
if(ids.size() != 2) {
log.error("Not the correct amount of ids provided for the message deletion undo action.");
break;
}
botService.deleteMessage(ids.get(0), ids.get(1));
if(action.equals(UndoAction.DELETE_CHANNEL)) {
if(ids.size() != 2) {
log.error("Not the correct amount of ids provided for the channel deletion undo action.");
return;
}
deleteChannel(ids.get(0), ids.get(1));
} else if(action.equals(UndoAction.DELETE_MESSAGE)) {
if(ids.size() != 2) {
log.error("Not the correct amount of ids provided for the message deletion undo action.");
return;
}
botService.deleteMessage(ids.get(0), ids.get(1));
}
});
}
private void deleteChannel(Long serverId, Long channelId) {
channelService.deleteTextChannel(serverId, channelId).exceptionally((throwable) -> {
channelService.deleteTextChannel(serverId, channelId).exceptionally(throwable -> {
log.error("Failed to execute undo action channel delete for channel {} in server {}", channelId, serverId, throwable);
return null;
});

View File

@@ -9,7 +9,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Optional;
@Component
public class FeatureFlagManagementServiceBean implements FeatureFlagManagementService {

View File

@@ -86,7 +86,7 @@ public class PostTargetManagementBean implements PostTargetManagement {
}
@Override
public Boolean postTargetExists(String name, Long serverId) {
public boolean postTargetExists(String name, Long serverId) {
AServer dbServer = serverManagementService.loadOrCreate(serverId);
return postTargetExists(name, dbServer);
}