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);
} catch (InterruptedException | ExecutionException 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.List;
import java.util.concurrent.ExecutionException;
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_CATEGORY = "modmailCategory";
public static final String MODMAIL_EXCEPTION_GENERIC_TEMPLATE = "modmail_exception_generic";
@Autowired
private ModMailThreadManagementService modMailThreadManagementService;
@@ -311,6 +312,7 @@ public class ModMailThreadServiceBean implements ModMailThreadService {
messages.add(messageToAdd);
} catch (InterruptedException | ExecutionException e) {
log.error("Error while executing future to retrieve reaction.", e);
Thread.currentThread().interrupt();
}
self.saveMessageIds(messages, modMailThread, modMailThread.getUser(), false, false);
modMailThreadManagementService.setModMailThreadState(modMailThread, ModMailThreadState.USER_REPLIED);
@@ -392,33 +394,7 @@ public class ModMailThreadServiceBean implements ModMailThreadService {
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);
}
try {
CompletableFutureList<Message> list = self.logModMailThread(modMailThreadId, messages, note);
list.getMainFuture().thenRun(() -> {
list.getFutures().forEach(messageCompletableFuture -> {
try {
Message message = messageCompletableFuture.get();
undoActions.add(UndoActionInstance.getMessageDeleteAction(message.getChannel().getIdLong(), message.getIdLong()));
} catch (InterruptedException | ExecutionException e) {
log.error("Failed to post logging messages.", e);
} catch (Exception e) {
log.error("Failed to handle the mod mail log messages.", e);
}
});
self.afterSuccessfulLog(modMailThreadId, feedBack, notifyUser, undoActions);
});
list.getMainFuture().exceptionally(innerThrowable -> {
sendModMailFailure("modmail_exception_generic", innerModMailThread.getUser(), modMailThreadId, feedBack, innerThrowable);
log.error("Failed to log messages for mod mail thread {}.", modMailThreadId, innerThrowable);
return null;
});
} catch (PostTargetNotFoundException po) {
log.error("Failed to log mod mail messages", po);
sendModMailFailure("modmail_exception_post_target_not_defined", innerModMailThread.getUser(), modMailThreadId, feedBack, po);
} catch (Exception e) {
log.error("Failed to log mod mail messages", e);
sendModMailFailure("modmail_exception_generic", innerModMailThread.getUser(), modMailThreadId, feedBack, e);
}
logMessagesToModMailLog(feedBack, note, notifyUser, modMailThreadId, undoActions, messages, innerModMailThread);
} else {
throw new ModMailThreadNotFoundException(modMailThreadId);
}
@@ -428,6 +404,37 @@ public class ModMailThreadServiceBean implements ModMailThreadService {
}
}
private void logMessagesToModMailLog(MessageChannel feedBack, String note, Boolean notifyUser, Long modMailThreadId, List<UndoActionInstance> undoActions, List<CompletableFuture<Message>> messages, ModMailThread innerModMailThread) {
try {
CompletableFutureList<Message> list = self.logModMailThread(modMailThreadId, messages, note);
list.getMainFuture().thenRun(() -> {
list.getFutures().forEach(messageCompletableFuture -> {
try {
Message message = messageCompletableFuture.get();
undoActions.add(UndoActionInstance.getMessageDeleteAction(message.getChannel().getIdLong(), message.getIdLong()));
} catch (InterruptedException | ExecutionException e) {
log.error("Failed to post logging messages.", e);
Thread.currentThread().interrupt();
} catch (Exception e) {
log.error("Failed to handle the mod mail log messages.", e);
}
});
self.afterSuccessfulLog(modMailThreadId, feedBack, notifyUser, undoActions);
});
list.getMainFuture().exceptionally(innerThrowable -> {
sendModMailFailure(MODMAIL_EXCEPTION_GENERIC_TEMPLATE, innerModMailThread.getUser(), modMailThreadId, feedBack, innerThrowable);
log.error("Failed to log messages for mod mail thread {}.", modMailThreadId, innerThrowable);
return null;
});
} catch (PostTargetNotFoundException po) {
log.error("Failed to log mod mail messages", po);
sendModMailFailure("modmail_exception_post_target_not_defined", innerModMailThread.getUser(), modMailThreadId, feedBack, po);
} catch (Exception e) {
log.error("Failed to log mod mail messages", e);
sendModMailFailure(MODMAIL_EXCEPTION_GENERIC_TEMPLATE, innerModMailThread.getUser(), modMailThreadId, feedBack, e);
}
}
@Transactional
public void afterSuccessfulLog(Long modMailThreadId, MessageChannel feedBack, Boolean notifyUser, List<UndoActionInstance> undoActions) {
log.trace("Mod mail logging for thread {} has completed. Starting post logging activities.", modMailThreadId);
@@ -456,7 +463,7 @@ public class ModMailThreadServiceBean implements ModMailThreadService {
});
} catch (Exception 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 -> {
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);
if(modMailThreadOpt.isPresent()) {
ModMailThread modMailThread = modMailThreadOpt.get();
String failureMessage = "Failed to delete text channel containing mod mail thread {}";
try {
channelService.deleteTextChannel(modMailThread.getChannel()).thenRun(() -> {
try {
@@ -481,15 +489,15 @@ public class ModMailThreadServiceBean implements ModMailThreadService {
}
}).exceptionally(throwable2 -> {
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;
});
} catch (InsufficientPermissionException ex) {
log.error("Failed to delete text channel containing mod mail thread {}", modMailThreadId, ex);
log.error(failureMessage, modMailThreadId, ex);
undoActionService.performActions(undoActions);
sendModMailFailure("modmail_exception_cannot_delete_channel", modMailThread.getUser(), modMailThreadId, feedBack, 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);
}
} else {
@@ -526,6 +534,7 @@ public class ModMailThreadServiceBean implements ModMailThreadService {
}
} catch (InterruptedException | ExecutionException e) {
log.error("Error while executing future to retrieve reaction.", e);
Thread.currentThread().interrupt();
} catch (Exception e) {
log.error("Failed handle the loaded messages.", e);
}
@@ -628,6 +637,7 @@ public class ModMailThreadServiceBean implements ModMailThreadService {
messages.add(messageToAdd);
} catch (InterruptedException | ExecutionException e) {
log.error("A future when sending the message to the user was interrupted.", e);
Thread.currentThread().interrupt();
} catch (Exception 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))) {
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);
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());
if(reaction != null) {
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.",
message.getMessageId(), message.getChannelId(), message.getServerId());
if(starboardPostOptional.isPresent()) {
StarboardPost starboardPost = starboardPostOptional.get();
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);
}
updateStarboardPost(message, userReacting, adding, starboardPostOptional.get(), userExceptAuthor);
} else {
log.info("Creating starboard post for message {} in channel {} in server {}", message.getMessageId(), message.getChannelId(), message.getServerId());
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) {
starboardService.deleteStarboardMessagePost(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.",
userRemoving.getUserReference().getId(), userRemoving.getServerReference().getId(), message.getMessageId());
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) {
log.error("Failed to post message embed.", e);
Thread.currentThread().interrupt();
}
}).exceptionally(throwable -> {
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) {
log.error("Failed to post messages.", e);
Thread.currentThread().interrupt();
}
}
@@ -162,6 +163,7 @@ public class StarboardServiceBean implements StarboardService {
}
} catch (InterruptedException | ExecutionException e) {
log.error("Failed to post starboard post.", e);
Thread.currentThread().interrupt();
}
}).exceptionally(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);
} catch (InterruptedException | ExecutionException e) {
log.warn("Failed to post suggestion", e);
Thread.currentThread().interrupt();
}
}) .exceptionally(throwable -> {
log.error("Failed to post suggestion {}", suggestionId, throwable);

View File

@@ -21,6 +21,6 @@ public class FeatureListener {
@EventListener
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;
}
@Override
public void shutdown() {
}
}

View File

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

View File

@@ -42,7 +42,8 @@ public class ChannelManagementServiceBean implements ChannelManagementService {
.build();
return repository.save(build);
} 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 {
private final Command command;
private final transient Command command;
private final String parameterName;
private final Class clazz;

View File

@@ -10,7 +10,7 @@ import java.util.HashMap;
@Getter
public class InsufficientParameters extends AbstractoRunTimeException implements Templatable {
private final Command command;
private final transient Command command;
private final 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 {
private final Command command;
private final transient Command command;
private final String parameterName;
private final Integer actualLength;
private final Integer maximumLength;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -31,8 +31,8 @@ import static org.quartz.TriggerBuilder.*;
public class SchedulerServiceBeanTest {
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 JOB_NAME = "jobName";
@InjectMocks
private SchedulerServiceBean classToTest;
@@ -65,7 +65,7 @@ public class SchedulerServiceBeanTest {
public void testStartingAllJobs() throws SchedulerException {
when(schedulerJobManagementServiceBean.findAll()).thenReturn(allCronJobsActive());
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));
}
@@ -73,7 +73,7 @@ public class SchedulerServiceBeanTest {
public void testStartSomeJobs() throws SchedulerException {
when(schedulerJobManagementServiceBean.findAll()).thenReturn(someCronJobsActive());
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));
}
@@ -81,14 +81,14 @@ public class SchedulerServiceBeanTest {
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()));
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));
}
@Test
public void scheduleSingleJob() throws SchedulerException {
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));
}

View File

@@ -7,6 +7,6 @@ import org.springframework.scheduling.quartz.QuartzJobBean;
public class TestJob extends QuartzJobBean {
@Override
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
public void closeTemplateSource(Object o) throws IOException {
// do nothing for now
}
}

View File

@@ -90,27 +90,7 @@ public class TemplateServiceBean implements TemplateService {
firstBuilder.setFooter(footer.getText(), footer.getIcon());
}
if(configuration.getFields() != null) {
for (int i = 0; i < configuration.getFields().size(); i++) {
EmbedField field = configuration.getFields().get(i);
if(field != null && field.getValue() != null) {
if(field.getValue().length() > MessageEmbed.VALUE_MAX_LENGTH) {
String substring = field.getValue().substring(MessageEmbed.VALUE_MAX_LENGTH);
field.setValue(field.getValue().substring(0, MessageEmbed.VALUE_MAX_LENGTH));
EmbedField secondPart = EmbedField.builder().inline(field.getInline()).name(field.getName() + " 2").value(substring).build();
configuration.getFields().add(i + 1, secondPart);
}
} else {
log.warn("Field {} in template {} is null.", i, key);
}
}
double neededIndex = Math.ceil(configuration.getFields().size() / 25D) - 1;
extendIfNecessary(embedBuilders, neededIndex);
for (int i = 0; i < configuration.getFields().size(); i++) {
double currentPart = Math.floor(i / 25D);
EmbedField embedField = configuration.getFields().get(i);
Boolean inline = embedField.getInline() != null ? embedField.getInline() : Boolean.FALSE;
embedBuilders.get((int) currentPart).addField(embedField.getName(), embedField.getValue(), inline);
}
createFieldsForEmbed(key, embedBuilders, configuration);
}
firstBuilder.setTimestamp(configuration.getTimeStamp());
@@ -133,6 +113,30 @@ public class TemplateServiceBean implements TemplateService {
.build();
}
private void createFieldsForEmbed(String key, List<EmbedBuilder> embedBuilders, EmbedConfiguration configuration) {
for (int i = 0; i < configuration.getFields().size(); i++) {
EmbedField field = configuration.getFields().get(i);
if(field != null && field.getValue() != null) {
if(field.getValue().length() > MessageEmbed.VALUE_MAX_LENGTH) {
String substring = field.getValue().substring(MessageEmbed.VALUE_MAX_LENGTH);
field.setValue(field.getValue().substring(0, MessageEmbed.VALUE_MAX_LENGTH));
EmbedField secondPart = EmbedField.builder().inline(field.getInline()).name(field.getName() + " 2").value(substring).build();
configuration.getFields().add(i + 1, secondPart);
}
} else {
log.warn("Field {} in template {} is null.", i, key);
}
}
double neededIndex = Math.ceil(configuration.getFields().size() / 25D) - 1;
extendIfNecessary(embedBuilders, neededIndex);
for (int i = 0; i < configuration.getFields().size(); i++) {
double currentPart = Math.floor(i / 25D);
EmbedField embedField = configuration.getFields().get(i);
Boolean inline = embedField.getInline() != null ? embedField.getInline() : Boolean.FALSE;
embedBuilders.get((int) currentPart).addField(embedField.getName(), embedField.getValue(), inline);
}
}
/**
* Enlarges the passed list of builders, if the passed index is not yet available within the list.
* When a new builder is needed, this will automatically set the footer with a page indicator.