addressed some sonar issues

This commit is contained in:
Sheldan
2020-05-27 18:41:31 +02:00
parent f05f088d58
commit 175a92408c
31 changed files with 125 additions and 95 deletions

View File

@@ -258,6 +258,7 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
messageService.updateStatusMessage(channel, statusMessage.getIdLong(), status); messageService.updateStatusMessage(channel, statusMessage.getIdLong(), status);
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException e) {
log.info("Failed to synchronize users.", e); log.info("Failed to synchronize users.", e);
Thread.currentThread().interrupt();
} }
} }

View File

@@ -11,6 +11,7 @@ import dev.sheldan.abstracto.experience.models.database.AUserExperience;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer; import java.util.function.Consumer;
/** /**

View File

@@ -41,6 +41,7 @@ public class ModMailThreadServiceBean implements ModMailThreadService {
public static final String MODMAIL_CLOSING_MESSAGE_TEXT = "modMailClosingText"; public static final String MODMAIL_CLOSING_MESSAGE_TEXT = "modMailClosingText";
public static final String MODMAIL_CATEGORY = "modmailCategory"; public static final String MODMAIL_CATEGORY = "modmailCategory";
public static final String MODMAIL_EXCEPTION_GENERIC_TEMPLATE = "modmail_exception_generic";
@Autowired @Autowired
private ModMailThreadManagementService modMailThreadManagementService; private ModMailThreadManagementService modMailThreadManagementService;
@@ -311,6 +312,7 @@ public class ModMailThreadServiceBean implements ModMailThreadService {
messages.add(messageToAdd); messages.add(messageToAdd);
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException e) {
log.error("Error while executing future to retrieve reaction.", e); log.error("Error while executing future to retrieve reaction.", e);
Thread.currentThread().interrupt();
} }
self.saveMessageIds(messages, modMailThread, modMailThread.getUser(), false, false); self.saveMessageIds(messages, modMailThread, modMailThread.getUser(), false, false);
modMailThreadManagementService.setModMailThreadState(modMailThread, ModMailThreadState.USER_REPLIED); modMailThreadManagementService.setModMailThreadState(modMailThread, ModMailThreadState.USER_REPLIED);
@@ -392,6 +394,17 @@ public class ModMailThreadServiceBean implements ModMailThreadService {
if(throwable != null) { if(throwable != null) {
log.warn("Failed to load some mod mail messages for mod mail thread {}. Still trying to post the ones we got.", modMailThreadId, throwable); log.warn("Failed to load some mod mail messages for mod mail thread {}. Still trying to post the ones we got.", modMailThreadId, throwable);
} }
logMessagesToModMailLog(feedBack, note, notifyUser, modMailThreadId, undoActions, messages, innerModMailThread);
} else {
throw new ModMailThreadNotFoundException(modMailThreadId);
}
});
} else {
self.afterSuccessfulLog(modMailThreadId, feedBack, notifyUser, undoActions);
}
}
private void logMessagesToModMailLog(MessageChannel feedBack, String note, Boolean notifyUser, Long modMailThreadId, List<UndoActionInstance> undoActions, List<CompletableFuture<Message>> messages, ModMailThread innerModMailThread) {
try { try {
CompletableFutureList<Message> list = self.logModMailThread(modMailThreadId, messages, note); CompletableFutureList<Message> list = self.logModMailThread(modMailThreadId, messages, note);
list.getMainFuture().thenRun(() -> { list.getMainFuture().thenRun(() -> {
@@ -401,6 +414,7 @@ public class ModMailThreadServiceBean implements ModMailThreadService {
undoActions.add(UndoActionInstance.getMessageDeleteAction(message.getChannel().getIdLong(), message.getIdLong())); undoActions.add(UndoActionInstance.getMessageDeleteAction(message.getChannel().getIdLong(), message.getIdLong()));
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException e) {
log.error("Failed to post logging messages.", e); log.error("Failed to post logging messages.", e);
Thread.currentThread().interrupt();
} catch (Exception e) { } catch (Exception e) {
log.error("Failed to handle the mod mail log messages.", e); log.error("Failed to handle the mod mail log messages.", e);
} }
@@ -408,7 +422,7 @@ public class ModMailThreadServiceBean implements ModMailThreadService {
self.afterSuccessfulLog(modMailThreadId, feedBack, notifyUser, undoActions); self.afterSuccessfulLog(modMailThreadId, feedBack, notifyUser, undoActions);
}); });
list.getMainFuture().exceptionally(innerThrowable -> { list.getMainFuture().exceptionally(innerThrowable -> {
sendModMailFailure("modmail_exception_generic", innerModMailThread.getUser(), modMailThreadId, feedBack, innerThrowable); sendModMailFailure(MODMAIL_EXCEPTION_GENERIC_TEMPLATE, innerModMailThread.getUser(), modMailThreadId, feedBack, innerThrowable);
log.error("Failed to log messages for mod mail thread {}.", modMailThreadId, innerThrowable); log.error("Failed to log messages for mod mail thread {}.", modMailThreadId, innerThrowable);
return null; return null;
}); });
@@ -417,14 +431,7 @@ public class ModMailThreadServiceBean implements ModMailThreadService {
sendModMailFailure("modmail_exception_post_target_not_defined", innerModMailThread.getUser(), modMailThreadId, feedBack, po); sendModMailFailure("modmail_exception_post_target_not_defined", innerModMailThread.getUser(), modMailThreadId, feedBack, po);
} catch (Exception e) { } catch (Exception e) {
log.error("Failed to log mod mail messages", e); log.error("Failed to log mod mail messages", e);
sendModMailFailure("modmail_exception_generic", innerModMailThread.getUser(), modMailThreadId, feedBack, e); sendModMailFailure(MODMAIL_EXCEPTION_GENERIC_TEMPLATE, innerModMailThread.getUser(), modMailThreadId, feedBack, e);
}
} else {
throw new ModMailThreadNotFoundException(modMailThreadId);
}
});
} else {
self.afterSuccessfulLog(modMailThreadId, feedBack, notifyUser, undoActions);
} }
} }
@@ -456,7 +463,7 @@ public class ModMailThreadServiceBean implements ModMailThreadService {
}); });
} catch (Exception e) { } catch (Exception e) {
log.error("Failed to render closing user message", e); log.error("Failed to render closing user message", e);
sendModMailFailure("modmail_exception_generic", modMailThread.getUser(), modMailThreadId, feedBack, e); sendModMailFailure(MODMAIL_EXCEPTION_GENERIC_TEMPLATE, modMailThread.getUser(), modMailThreadId, feedBack, e);
} }
}, throwable -> { }, throwable -> {
log.error("Failed to load private channel with user {}", user.getIdLong(), throwable); log.error("Failed to load private channel with user {}", user.getIdLong(), throwable);
@@ -472,6 +479,7 @@ public class ModMailThreadServiceBean implements ModMailThreadService {
Optional<ModMailThread> modMailThreadOpt = modMailThreadManagementService.getById(modMailThreadId); Optional<ModMailThread> modMailThreadOpt = modMailThreadManagementService.getById(modMailThreadId);
if(modMailThreadOpt.isPresent()) { if(modMailThreadOpt.isPresent()) {
ModMailThread modMailThread = modMailThreadOpt.get(); ModMailThread modMailThread = modMailThreadOpt.get();
String failureMessage = "Failed to delete text channel containing mod mail thread {}";
try { try {
channelService.deleteTextChannel(modMailThread.getChannel()).thenRun(() -> { channelService.deleteTextChannel(modMailThread.getChannel()).thenRun(() -> {
try { try {
@@ -481,15 +489,15 @@ public class ModMailThreadServiceBean implements ModMailThreadService {
} }
}).exceptionally(throwable2 -> { }).exceptionally(throwable2 -> {
undoActionService.performActions(undoActions); undoActionService.performActions(undoActions);
log.error("Failed to delete text channel containing mod mail thread {}", modMailThread.getId(), throwable2); log.error(failureMessage, modMailThread.getId(), throwable2);
return null; return null;
}); });
} catch (InsufficientPermissionException ex) { } catch (InsufficientPermissionException ex) {
log.error("Failed to delete text channel containing mod mail thread {}", modMailThreadId, ex); log.error(failureMessage, modMailThreadId, ex);
undoActionService.performActions(undoActions); undoActionService.performActions(undoActions);
sendModMailFailure("modmail_exception_cannot_delete_channel", modMailThread.getUser(), modMailThreadId, feedBack, ex); sendModMailFailure("modmail_exception_cannot_delete_channel", modMailThread.getUser(), modMailThreadId, feedBack, ex);
} catch (Exception ex) { } catch (Exception ex) {
log.error("Failed to delete text channel containing mod mail thread {}", modMailThreadId, ex); log.error(failureMessage, modMailThreadId, ex);
undoActionService.performActions(undoActions); undoActionService.performActions(undoActions);
} }
} else { } else {
@@ -526,6 +534,7 @@ public class ModMailThreadServiceBean implements ModMailThreadService {
} }
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException e) {
log.error("Error while executing future to retrieve reaction.", e); log.error("Error while executing future to retrieve reaction.", e);
Thread.currentThread().interrupt();
} catch (Exception e) { } catch (Exception e) {
log.error("Failed handle the loaded messages.", e); log.error("Failed handle the loaded messages.", e);
} }
@@ -628,6 +637,7 @@ public class ModMailThreadServiceBean implements ModMailThreadService {
messages.add(messageToAdd); messages.add(messageToAdd);
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException e) {
log.error("A future when sending the message to the user was interrupted.", e); log.error("A future when sending the message to the user was interrupted.", e);
Thread.currentThread().interrupt();
} catch (Exception e) { } catch (Exception e) {
log.error("Failed to handle the send staff message.", e); log.error("Failed to handle the send staff message.", e);
} }

View File

@@ -69,11 +69,11 @@ public class StarboardListener implements ReactedAddedListener, ReactedRemovedLi
if(EmoteUtils.isReactionEmoteAEmote(reactionEmote, aEmote, emoteInGuild.orElse(null))) { if(EmoteUtils.isReactionEmoteAEmote(reactionEmote, aEmote, emoteInGuild.orElse(null))) {
log.trace("User {} in server {} reacted with star to put a message {} on starboard.", userAdding.getUserReference().getId(), userAdding.getServerReference().getId(), message.getMessageId()); log.trace("User {} in server {} reacted with star to put a message {} on starboard.", userAdding.getUserReference().getId(), userAdding.getServerReference().getId(), message.getMessageId());
Optional<CachedReaction> reactionOptional = EmoteUtils.getReactionFromMessageByEmote(message, aEmote); Optional<CachedReaction> reactionOptional = EmoteUtils.getReactionFromMessageByEmote(message, aEmote);
updateStarboardPost(message, reactionOptional.orElse(null), userAdding, true); handleStarboardPostChange(message, reactionOptional.orElse(null), userAdding, true);
} }
} }
private void updateStarboardPost(CachedMessage message, CachedReaction reaction, AUserInAServer userReacting, boolean adding) { private void handleStarboardPostChange(CachedMessage message, CachedReaction reaction, AUserInAServer userReacting, boolean adding) {
Optional<StarboardPost> starboardPostOptional = starboardPostManagementService.findByMessageId(message.getMessageId()); Optional<StarboardPost> starboardPostOptional = starboardPostManagementService.findByMessageId(message.getMessageId());
if(reaction != null) { if(reaction != null) {
AUserInAServer author = userInServerManagementService.loadUser(message.getServerId(), message.getAuthorId()); AUserInAServer author = userInServerManagementService.loadUser(message.getServerId(), message.getAuthorId());
@@ -83,16 +83,7 @@ public class StarboardListener implements ReactedAddedListener, ReactedRemovedLi
log.info("Post reached starboard minimum. Message {} in channel {} in server {} will be starred/updated.", log.info("Post reached starboard minimum. Message {} in channel {} in server {} will be starred/updated.",
message.getMessageId(), message.getChannelId(), message.getServerId()); message.getMessageId(), message.getChannelId(), message.getServerId());
if(starboardPostOptional.isPresent()) { if(starboardPostOptional.isPresent()) {
StarboardPost starboardPost = starboardPostOptional.get(); updateStarboardPost(message, userReacting, adding, starboardPostOptional.get(), userExceptAuthor);
starboardPost.setIgnored(false);
starboardService.updateStarboardPost(starboardPost, message, userExceptAuthor);
if(adding) {
log.trace("Adding reactor {} from message {}", userReacting.getUserReference().getId(), message.getMessageId());
starboardPostReactorManagementService.addReactor(starboardPost, userReacting);
} else {
log.trace("Removing reactor {} from message {}", userReacting.getUserReference().getId(), message.getMessageId());
starboardPostReactorManagementService.removeReactor(starboardPost, userReacting);
}
} else { } else {
log.info("Creating starboard post for message {} in channel {} in server {}", message.getMessageId(), message.getChannelId(), message.getServerId()); log.info("Creating starboard post for message {} in channel {} in server {}", message.getMessageId(), message.getChannelId(), message.getServerId());
starboardService.createStarboardPost(message, userExceptAuthor, userReacting, author); starboardService.createStarboardPost(message, userExceptAuthor, userReacting, author);
@@ -111,6 +102,18 @@ public class StarboardListener implements ReactedAddedListener, ReactedRemovedLi
} }
} }
private void updateStarboardPost(CachedMessage message, AUserInAServer userReacting, boolean adding, StarboardPost starboardPost, List<AUserInAServer> userExceptAuthor) {
starboardPost.setIgnored(false);
starboardService.updateStarboardPost(starboardPost, message, userExceptAuthor);
if(adding) {
log.trace("Adding reactor {} from message {}", userReacting.getUserReference().getId(), message.getMessageId());
starboardPostReactorManagementService.addReactor(starboardPost, userReacting);
} else {
log.trace("Removing reactor {} from message {}", userReacting.getUserReference().getId(), message.getMessageId());
starboardPostReactorManagementService.removeReactor(starboardPost, userReacting);
}
}
private void completelyRemoveStarboardPost(StarboardPost starboardPost) { private void completelyRemoveStarboardPost(StarboardPost starboardPost) {
starboardService.deleteStarboardMessagePost(starboardPost); starboardService.deleteStarboardMessagePost(starboardPost);
starboardPostManagementService.removePost(starboardPost); starboardPostManagementService.removePost(starboardPost);
@@ -130,7 +133,7 @@ public class StarboardListener implements ReactedAddedListener, ReactedRemovedLi
log.trace("User {} in server {} removed star reaction from message {} on starboard.", log.trace("User {} in server {} removed star reaction from message {} on starboard.",
userRemoving.getUserReference().getId(), userRemoving.getServerReference().getId(), message.getMessageId()); userRemoving.getUserReference().getId(), userRemoving.getServerReference().getId(), message.getMessageId());
Optional<CachedReaction> reactionOptional = EmoteUtils.getReactionFromMessageByEmote(message, aEmote); Optional<CachedReaction> reactionOptional = EmoteUtils.getReactionFromMessageByEmote(message, aEmote);
updateStarboardPost(message, reactionOptional.orElse(null), userRemoving, false); handleStarboardPostChange(message, reactionOptional.orElse(null), userRemoving, false);
} }
} }

View File

@@ -132,6 +132,7 @@ public class MessageEmbedServiceBean implements MessageEmbedService {
}); });
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException e) {
log.error("Failed to post message embed.", e); log.error("Failed to post message embed.", e);
Thread.currentThread().interrupt();
} }
}).exceptionally(throwable -> { }).exceptionally(throwable -> {
log.error("Failed to send message for embedding the link for message {} in channel {} in server {}", log.error("Failed to send message for embedding the link for message {} in channel {} in server {}",

View File

@@ -121,6 +121,7 @@ public class StarboardServiceBean implements StarboardService {
}); });
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException e) {
log.error("Failed to post messages.", e); log.error("Failed to post messages.", e);
Thread.currentThread().interrupt();
} }
} }
@@ -162,6 +163,7 @@ public class StarboardServiceBean implements StarboardService {
} }
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException e) {
log.error("Failed to post starboard post.", e); log.error("Failed to post starboard post.", e);
Thread.currentThread().interrupt();
} }
}).exceptionally(throwable -> { }).exceptionally(throwable -> {
log.error("Failed to update starboard post {}.", post.getId(), throwable); log.error("Failed to update starboard post {}.", post.getId(), throwable);

View File

@@ -73,6 +73,7 @@ public class SuggestionServiceBean implements SuggestionService {
messageService.addReactionToMessage(SUGGESTION_NO_EMOTE, guildId, message); messageService.addReactionToMessage(SUGGESTION_NO_EMOTE, guildId, message);
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException e) {
log.warn("Failed to post suggestion", e); log.warn("Failed to post suggestion", e);
Thread.currentThread().interrupt();
} }
}) .exceptionally(throwable -> { }) .exceptionally(throwable -> {
log.error("Failed to post suggestion {}", suggestionId, throwable); log.error("Failed to post suggestion {}", suggestionId, throwable);

View File

@@ -21,6 +21,6 @@ public class FeatureListener {
@EventListener @EventListener
public void handleContextRefreshEvent(ContextRefreshedEvent ctxStartEvt) { public void handleContextRefreshEvent(ContextRefreshedEvent ctxStartEvt) {
// Do nothing yet, because of a race condition between features and commands
} }
} }

View File

@@ -177,9 +177,4 @@ public class BotServiceBean implements BotService {
} }
return null; return null;
} }
@Override
public void shutdown() {
}
} }

View File

@@ -154,6 +154,7 @@ public class MessageCacheBean implements MessageCache {
reactions.add(cachedReaction); reactions.add(cachedReaction);
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException e) {
log.error("Error while executing future to retrieve reaction.", e); log.error("Error while executing future to retrieve reaction.", e);
Thread.currentThread().interrupt();
} }
}); });
return reactions; return reactions;

View File

@@ -42,7 +42,8 @@ public class ChannelManagementServiceBean implements ChannelManagementService {
.build(); .build();
return repository.save(build); return repository.save(build);
} else { } else {
return loadChannel(id).get(); Optional<AChannel> channelOptional = loadChannel(id);
return channelOptional.orElse(null);
} }
} }

View File

@@ -8,7 +8,7 @@ import java.util.HashMap;
public class IncorrectParameter extends AbstractoRunTimeException implements Templatable { public class IncorrectParameter extends AbstractoRunTimeException implements Templatable {
private final Command command; private final transient Command command;
private final String parameterName; private final String parameterName;
private final Class clazz; private final Class clazz;

View File

@@ -10,7 +10,7 @@ import java.util.HashMap;
@Getter @Getter
public class InsufficientParameters extends AbstractoRunTimeException implements Templatable { public class InsufficientParameters extends AbstractoRunTimeException implements Templatable {
private final Command command; private final transient Command command;
private final String parameterName; private final String parameterName;
public InsufficientParameters(String s, Command command, String parameterName) { public InsufficientParameters(String s, Command command, String parameterName) {

View File

@@ -9,7 +9,7 @@ import java.util.HashMap;
public class ParameterTooLong extends AbstractoRunTimeException implements Templatable { public class ParameterTooLong extends AbstractoRunTimeException implements Templatable {
private final Command command; private final transient Command command;
private final String parameterName; private final String parameterName;
private final Integer actualLength; private final Integer actualLength;
private final Integer maximumLength; private final Integer maximumLength;

View File

@@ -12,7 +12,7 @@ import java.util.List;
@Getter @Getter
@Setter @Setter
@Builder @Builder
public class CachedMessage implements Serializable { public class CachedMessage {
private Long serverId; private Long serverId;
private Long channelId; private Long channelId;
private Long messageId; private Long messageId;

View File

@@ -6,6 +6,7 @@ import net.dv8tion.jda.api.entities.ChannelType;
import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*; import javax.persistence.*;
import java.io.Serializable;
import java.time.Instant; import java.time.Instant;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
@@ -17,7 +18,7 @@ import java.util.Objects;
@AllArgsConstructor @AllArgsConstructor
@Cacheable @Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class AChannel implements SnowFlake { public class AChannel implements SnowFlake, Serializable {
@Id @Id
@Getter @Getter

View File

@@ -4,6 +4,7 @@ import lombok.*;
import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*; import javax.persistence.*;
import java.io.Serializable;
import java.time.Instant; import java.time.Instant;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
@@ -16,7 +17,7 @@ import java.util.Objects;
@Getter @Getter
@Cacheable @Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class AChannelGroup { public class AChannelGroup implements Serializable {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)

View File

@@ -5,6 +5,7 @@ import lombok.*;
import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*; import javax.persistence.*;
import java.io.Serializable;
import java.util.Objects; import java.util.Objects;
@Entity @Entity
@@ -15,7 +16,7 @@ import java.util.Objects;
@Getter @Getter
@Cacheable @Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class AChannelGroupCommand { public class AChannelGroupCommand implements Serializable {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)

View File

@@ -4,6 +4,7 @@ import lombok.*;
import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*; import javax.persistence.*;
import java.io.Serializable;
import java.time.Instant; import java.time.Instant;
import java.util.Objects; import java.util.Objects;
@@ -15,7 +16,7 @@ import java.util.Objects;
@Getter @Getter
@Cacheable @Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class AConfig { public class AConfig implements Serializable {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)

View File

@@ -3,6 +3,7 @@ package dev.sheldan.abstracto.core.models.database;
import lombok.*; import lombok.*;
import javax.persistence.*; import javax.persistence.*;
import java.io.Serializable;
import java.time.Instant; import java.time.Instant;
@Entity @Entity
@@ -11,7 +12,7 @@ import java.time.Instant;
@AllArgsConstructor @AllArgsConstructor
@NoArgsConstructor @NoArgsConstructor
@Getter @Getter
public class ADefaultConfig { public class ADefaultConfig implements Serializable {
@javax.persistence.Id @javax.persistence.Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer Id; private Integer Id;

View File

@@ -4,6 +4,7 @@ import lombok.*;
import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*; import javax.persistence.*;
import java.io.Serializable;
import java.time.Instant; import java.time.Instant;
import java.util.Objects; import java.util.Objects;
@@ -15,7 +16,7 @@ import java.util.Objects;
@Getter @Getter
@Cacheable @Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class AEmote { public class AEmote implements Serializable {
@javax.persistence.Id @javax.persistence.Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)

View File

@@ -6,6 +6,7 @@ import lombok.*;
import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*; import javax.persistence.*;
import java.io.Serializable;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
@@ -16,7 +17,7 @@ import java.util.Objects;
@AllArgsConstructor @AllArgsConstructor
@Cacheable @Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class AFeature implements SnowFlake { public class AFeature implements SnowFlake, Serializable {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)

View File

@@ -4,6 +4,7 @@ import lombok.*;
import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*; import javax.persistence.*;
import java.io.Serializable;
import java.time.Instant; import java.time.Instant;
import java.util.Objects; import java.util.Objects;
@@ -14,7 +15,7 @@ import java.util.Objects;
@AllArgsConstructor @AllArgsConstructor
@Cacheable @Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class AFeatureFlag { public class AFeatureFlag implements Serializable {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)

View File

@@ -4,6 +4,7 @@ import lombok.*;
import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*; import javax.persistence.*;
import java.io.Serializable;
import java.time.Instant; import java.time.Instant;
@Entity @Entity
@@ -13,7 +14,7 @@ import java.time.Instant;
@AllArgsConstructor @AllArgsConstructor
@Cacheable @Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class AFeatureMode { public class AFeatureMode implements Serializable {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Getter @Getter

View File

@@ -4,6 +4,7 @@ import lombok.*;
import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*; import javax.persistence.*;
import java.io.Serializable;
import java.time.Instant; import java.time.Instant;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
@@ -16,7 +17,7 @@ import java.util.Objects;
@Getter @Getter
@Cacheable @Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class AUser { public class AUser implements Serializable {
@Id @Id
private Long id; private Long id;

View File

@@ -4,6 +4,7 @@ import lombok.*;
import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*; import javax.persistence.*;
import java.io.Serializable;
import java.time.Instant; import java.time.Instant;
import java.util.Objects; import java.util.Objects;
@@ -14,7 +15,7 @@ import java.util.Objects;
@NoArgsConstructor @NoArgsConstructor
@Cacheable @Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class PostTarget { public class PostTarget implements Serializable {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)

View File

@@ -32,5 +32,4 @@ public interface BotService {
Optional<Guild> getGuildById(Long serverId); Optional<Guild> getGuildById(Long serverId);
Guild getGuildByIdNullable(Long serverId); Guild getGuildByIdNullable(Long serverId);
Member getBotInGuild(AServer server); Member getBotInGuild(AServer server);
void shutdown();
} }

View File

@@ -31,8 +31,8 @@ import static org.quartz.TriggerBuilder.*;
public class SchedulerServiceBeanTest { public class SchedulerServiceBeanTest {
public static final String JOB_CLASS = "dev.sheldan.abstracto.scheduling.factory.TestJob"; public static final String JOB_CLASS = "dev.sheldan.abstracto.scheduling.factory.TestJob";
public static final String JOB_NAME = "jobName";
public static final String GROUP_NAME = "groupName"; public static final String GROUP_NAME = "groupName";
public static final String JOB_NAME = "jobName";
@InjectMocks @InjectMocks
private SchedulerServiceBean classToTest; private SchedulerServiceBean classToTest;
@@ -65,7 +65,7 @@ public class SchedulerServiceBeanTest {
public void testStartingAllJobs() throws SchedulerException { public void testStartingAllJobs() throws SchedulerException {
when(schedulerJobManagementServiceBean.findAll()).thenReturn(allCronJobsActive()); when(schedulerJobManagementServiceBean.findAll()).thenReturn(allCronJobsActive());
classToTest.startScheduledJobs(); classToTest.startScheduledJobs();
verify(scheduler, times(2)).checkExists(eq(new JobKey("jobName", "groupName"))); verify(scheduler, times(2)).checkExists(eq(new JobKey(JOB_NAME, GROUP_NAME)));
verify(scheduler, times(2)).addJob(any(JobDetail.class), eq(true)); verify(scheduler, times(2)).addJob(any(JobDetail.class), eq(true));
} }
@@ -73,7 +73,7 @@ public class SchedulerServiceBeanTest {
public void testStartSomeJobs() throws SchedulerException { public void testStartSomeJobs() throws SchedulerException {
when(schedulerJobManagementServiceBean.findAll()).thenReturn(someCronJobsActive()); when(schedulerJobManagementServiceBean.findAll()).thenReturn(someCronJobsActive());
classToTest.startScheduledJobs(); classToTest.startScheduledJobs();
verify(scheduler, times(1)).checkExists(eq(new JobKey("jobName", "groupName"))); verify(scheduler, times(1)).checkExists(eq(new JobKey(JOB_NAME, GROUP_NAME)));
verify(scheduler, times(1)).addJob(any(JobDetail.class), eq(true)); verify(scheduler, times(1)).addJob(any(JobDetail.class), eq(true));
} }
@@ -81,14 +81,14 @@ public class SchedulerServiceBeanTest {
public void testInvalidClass() throws SchedulerException { public void testInvalidClass() throws SchedulerException {
when(schedulerJobManagementServiceBean.findAll()).thenReturn(Arrays.asList(SchedulerJob.builder().active(true).cronExpression("*").clazz("invalidJob").groupName(GROUP_NAME).name(JOB_NAME).build())); when(schedulerJobManagementServiceBean.findAll()).thenReturn(Arrays.asList(SchedulerJob.builder().active(true).cronExpression("*").clazz("invalidJob").groupName(GROUP_NAME).name(JOB_NAME).build()));
classToTest.startScheduledJobs(); classToTest.startScheduledJobs();
verify(scheduler, times(0)).checkExists(eq(new JobKey("jobName", "groupName"))); verify(scheduler, times(0)).checkExists(eq(new JobKey(JOB_NAME, GROUP_NAME)));
verify(scheduler, times(0)).addJob(any(JobDetail.class), eq(true)); verify(scheduler, times(0)).addJob(any(JobDetail.class), eq(true));
} }
@Test @Test
public void scheduleSingleJob() throws SchedulerException { public void scheduleSingleJob() throws SchedulerException {
classToTest.scheduleJob(activeJobCronJob()); classToTest.scheduleJob(activeJobCronJob());
verify(scheduler, times(1)).checkExists(eq(new JobKey("jobName", "groupName"))); verify(scheduler, times(1)).checkExists(eq(new JobKey(JOB_NAME, GROUP_NAME)));
verify(scheduler, times(1)).addJob(any(JobDetail.class), eq(true)); verify(scheduler, times(1)).addJob(any(JobDetail.class), eq(true));
} }

View File

@@ -7,6 +7,6 @@ import org.springframework.scheduling.quartz.QuartzJobBean;
public class TestJob extends QuartzJobBean { public class TestJob extends QuartzJobBean {
@Override @Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException { protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
// do nothing, just needed to have a class found on the path for the test
} }
} }

View File

@@ -56,6 +56,6 @@ public class DatabaseTemplateLoader implements TemplateLoader {
@Override @Override
public void closeTemplateSource(Object o) throws IOException { public void closeTemplateSource(Object o) throws IOException {
// do nothing for now
} }
} }

View File

@@ -90,6 +90,30 @@ public class TemplateServiceBean implements TemplateService {
firstBuilder.setFooter(footer.getText(), footer.getIcon()); firstBuilder.setFooter(footer.getText(), footer.getIcon());
} }
if(configuration.getFields() != null) { if(configuration.getFields() != null) {
createFieldsForEmbed(key, embedBuilders, configuration);
}
firstBuilder.setTimestamp(configuration.getTimeStamp());
firstBuilder.setImage(configuration.getImageUrl());
EmbedColor color = configuration.getColor();
if(color != null) {
int colorToSet = new Color(color.getR(), color.getG(), color.getB()).getRGB();
embedBuilders.forEach(embedBuilder -> embedBuilder.setColor(colorToSet));
}
List<MessageEmbed> embeds = new ArrayList<>();
if(embedBuilders.size() > 1 || !embedBuilders.get(0).isEmpty()) {
embeds = embedBuilders.stream().map(EmbedBuilder::build).collect(Collectors.toList());
}
return MessageToSend.builder()
.embeds(embeds)
.message(configuration.getAdditionalMessage())
.build();
}
private void createFieldsForEmbed(String key, List<EmbedBuilder> embedBuilders, EmbedConfiguration configuration) {
for (int i = 0; i < configuration.getFields().size(); i++) { for (int i = 0; i < configuration.getFields().size(); i++) {
EmbedField field = configuration.getFields().get(i); EmbedField field = configuration.getFields().get(i);
if(field != null && field.getValue() != null) { if(field != null && field.getValue() != null) {
@@ -112,26 +136,6 @@ public class TemplateServiceBean implements TemplateService {
embedBuilders.get((int) currentPart).addField(embedField.getName(), embedField.getValue(), inline); embedBuilders.get((int) currentPart).addField(embedField.getName(), embedField.getValue(), inline);
} }
} }
firstBuilder.setTimestamp(configuration.getTimeStamp());
firstBuilder.setImage(configuration.getImageUrl());
EmbedColor color = configuration.getColor();
if(color != null) {
int colorToSet = new Color(color.getR(), color.getG(), color.getB()).getRGB();
embedBuilders.forEach(embedBuilder -> embedBuilder.setColor(colorToSet));
}
List<MessageEmbed> embeds = new ArrayList<>();
if(embedBuilders.size() > 1 || !embedBuilders.get(0).isEmpty()) {
embeds = embedBuilders.stream().map(EmbedBuilder::build).collect(Collectors.toList());
}
return MessageToSend.builder()
.embeds(embeds)
.message(configuration.getAdditionalMessage())
.build();
}
/** /**
* Enlarges the passed list of builders, if the passed index is not yet available within the list. * Enlarges the passed list of builders, if the passed index is not yet available within the list.