Additional cleanup

This commit is contained in:
Yannick Lamprecht 2018-11-28 16:32:37 +01:00
parent b361845502
commit 0fa2b829d0
25 changed files with 88 additions and 92 deletions

View file

@ -439,7 +439,7 @@ public class NurseNoakes extends TelegramLongPollingBot {
logger.info("Loading dependencies.");
loader.loadDependencies();
logger.info("Loading regular modules.");
loader.loadModules(module -> loadModule(module));
loader.loadModules(this::loadModule);
if (ModelManager.wasAnythingCreated()) {
@ -466,14 +466,7 @@ public class NurseNoakes extends TelegramLongPollingBot {
public void stop() {
logger.info("Shuting down...");
for(Module module : activeModules) {
logger.verbose("Shutting down module " + module.getName() + "...");
module.shutdown();
}
for(Module module : inactiveModules) {
logger.verbose("Shutting down module " + module.getName() + "...");
module.shutdown();
}
disableModules();
logger.debug("Closing database connection.");
connector.close();
@ -481,9 +474,8 @@ public class NurseNoakes extends TelegramLongPollingBot {
logger.info("Shutdown complete.");
System.exit(EXIT_CODE_SHUTDOWN);
}
public void restart() {
logger.info("Restarting...");
private void disableModules() {
for(Module module : activeModules) {
logger.verbose("Shutting down module " + module.getName() + "...");
module.shutdown();
@ -492,7 +484,12 @@ public class NurseNoakes extends TelegramLongPollingBot {
logger.verbose("Shutting down module " + module.getName() + "...");
module.shutdown();
}
}
public void restart() {
logger.info("Restarting...");
disableModules();
connector.close();
System.exit(EXIT_CODE_RESTART);

View file

@ -13,6 +13,7 @@ public class CommandCategory {
}
@Override
public boolean equals(Object object) {
if (!(object instanceof CommandCategory))
return false;

View file

@ -1,21 +1,20 @@
package asylum.nursebot.executor;
import asylum.nursebot.exceptions.WhatTheFuckException;
import java.util.HashMap;
import asylum.nursebot.exceptions.WhatTheFuckException;
public class CallbackContext extends HashMap<Class<?>, Object>{
private static final long serialVersionUID = 1988125468800948893L;
public void put(Object object) {
put(object.getClass(), object);
}
@SuppressWarnings("unchecked")
public <T> T get(Class<T> clazz) {
Object obj = ((HashMap<Class<?>, Object>) this).get(clazz);
Object obj = this.get(clazz);
if (!(clazz.isInstance(obj)))
throw new WhatTheFuckException("WAT?");
return (T) obj;
return clazz.cast(obj);
}
}

View file

@ -8,7 +8,6 @@ public class ExitCode {
}
public ExitCode(int value) {
super();
this.value = value;
}
}

View file

@ -6,12 +6,11 @@ import asylum.nursebot.objects.Module;
public class ModuleDependencies extends HashMap<Class<? extends Module>, Module>{
private static final long serialVersionUID = 1L;
@SuppressWarnings("unchecked")
public <C extends Module> C get(Class<C> clazz) {
Module m = super.get(clazz);
if (!(clazz.isInstance(m)))
throw new IllegalArgumentException();
return (C) m;
return clazz.cast(m);
}
}

View file

@ -5,9 +5,6 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import asylum.nursebot.utils.log.Logger;
import org.reflections.Reflections;
import com.google.inject.Guice;
import com.google.inject.Injector;
@ -15,9 +12,8 @@ import asylum.nursebot.NurseNoakes;
import asylum.nursebot.commands.CommandHandler;
import asylum.nursebot.objects.Module;
import asylum.nursebot.semantics.SemanticsHandler;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.reflections.util.FilterBuilder;
import asylum.nursebot.utils.log.Logger;
import org.reflections.Reflections;
public class ModuleLoader {
private List<Provider> providers;
@ -37,25 +33,23 @@ public class ModuleLoader {
this.providers.add(new BaseProvider(nurse, commandHandler, semanticsHandler, dependencies));
}
@SuppressWarnings("unchecked")
public void loadDependencies() {
Set<Class<?>> list = reflections.getTypesAnnotatedWith(AutoDependency.class);
for (Class<?> clazz : list) {
if (Module.class.isAssignableFrom(clazz)) {
dependencyClasses.add((Class<? extends Module>) clazz);
dependencyClasses.add(clazz.asSubclass(Module.class));
}
}
}
@SuppressWarnings("unchecked")
public void loadModules(ModuleHandler handler) {
Injector injector = Guice.createInjector(providers);
Set<Class<?>> annotatedClasses = reflections.getTypesAnnotatedWith(AutoModule.class);
Set<Class<?>> dependenciesToLoad = new HashSet<Class<?>>();
Set<Class<?>> regularModulesToLoad = new HashSet<Class<?>>();
Set<Class<?>> dependenciesToLoad = new HashSet<>();
Set<Class<?>> regularModulesToLoad = new HashSet<>();
for (Class<?> clazz : annotatedClasses) {
if (!Module.class.isAssignableFrom(clazz)) {
@ -81,7 +75,7 @@ public class ModuleLoader {
handler.handle(module);
logger.verbose("Adding " + clazz.getCanonicalName() + " as dependency.");
dependencies.put((Class<? extends Module>) clazz, module);
dependencies.put(clazz.asSubclass(Module.class), module);
}
for (Class<?> clazz : regularModulesToLoad) {

View file

@ -1,5 +1,6 @@
package asylum.nursebot.modules;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
@ -203,8 +204,8 @@ public class Appointments implements Module {
return;
}
boolean abs = "absolut".equals(list.get(1).toLowerCase()) || "absolute".equals(list.get(1).toLowerCase());
boolean rel = "relativ".equals(list.get(1).toLowerCase()) || "relative".equals(list.get(1).toLowerCase());
boolean abs = Arrays.asList("absolut", "absolute").contains(list.get(1).toLowerCase());
boolean rel = Arrays.asList("relativ","relative").contains(list.get(1).toLowerCase());
long time = 0;
boolean fail = false;
try {

View file

@ -11,6 +11,7 @@ import java.util.Random;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import com.google.inject.Inject;
@ -142,7 +143,7 @@ public class Birthdays implements Module {
logger.debug("Size of congratulations list: " + congratulations.size());
for (BirthdaysCongratulation congratulation : congratulations) {
Random random = new Random();
Random random = ThreadLocalRandom.current();
String text = String.format(CONGRATULATIONS[random.nextInt(CONGRATULATIONS.length)], StringTools.makeMention(user));
ThreadHelper.ignore(TelegramApiException.class, () -> sender.send(congratulation.getChatId(), text, true));
@ -250,7 +251,7 @@ public class Birthdays implements Module {
return;
}
LocalDate date = null;
LocalDate date;
try {
date = LocalDate.parse(arguments.get(0));
@ -390,7 +391,7 @@ public class Birthdays implements Module {
}
c.getSender().reply(builder.toString(), c.getMessage());
} else if (parameters.get(0).toLowerCase().equals("all")) {
} else if (parameters.get(0).equalsIgnoreCase("all")) {
if (!isGroupChat) {
c.getSender().reply("Diese Funktion ist nur in Gruppenchats sinnvoll.", c.getMessage());
return;
@ -405,7 +406,7 @@ public class Birthdays implements Module {
List<BirthdaysCongratulation> congratulations = BirthdaysCongratulation.findByChatId(chat.getId());
if (congratulations.size() == 0) {
if (congratulations.isEmpty()) {
c.getSender().reply("In diesem Chat gratuliere ich im Moment niemandem zum Geburtstag.\nWenn du die erste Person sein willst, denn benutze /enablebirthday.", c.getMessage());
return;
}

View file

@ -24,6 +24,7 @@ import asylum.nursebot.persistence.modules.BusinessCardsEntry;
import asylum.nursebot.persistence.modules.BusinessCardsField;
import asylum.nursebot.utils.StringTools;
import org.javalite.activejdbc.Base;
import org.javalite.activejdbc.Model;
import org.telegram.telegrambots.meta.api.objects.User;
@AutoModule(load=true)
@ -165,13 +166,14 @@ public class BusinessCards implements Module {
String cardname = args.get(0);
List<BusinessCardsCard> tmp = BusinessCardsCard.getByName(cardname, c.getMessage().getFrom().getId().intValue());
List<BusinessCardsCard> tmp = BusinessCardsCard.getByName(cardname,
c.getMessage().getFrom().getId());
if (tmp == null || tmp.isEmpty()) {
throw new ParsingException("Diese Karte existiert nicht.");
}
args = args.subList(1, args.size());
boolean isPublic = args.get(0).toLowerCase().equals("public");
boolean isPublic = args.get(0).equalsIgnoreCase("public");
if (isPublic)
args = args.subList(1, args.size());
@ -180,7 +182,7 @@ public class BusinessCards implements Module {
card.saveIt();
List<BusinessCardsEntry> entries = card.getAll(BusinessCardsEntry.class);
entries.forEach(e -> e.delete());
entries.forEach(Model::delete);
modifyFields(card, args);
@ -211,13 +213,14 @@ public class BusinessCards implements Module {
try {
String cardname = args.get(0);
List<BusinessCardsCard> tmp = BusinessCardsCard.getByName(cardname, c.getMessage().getFrom().getId().intValue());
List<BusinessCardsCard> tmp = BusinessCardsCard.getByName(cardname,
c.getMessage().getFrom().getId());
if (tmp == null || tmp.isEmpty()) {
throw new ParsingException("Es wurde keine Karte mit diesem Namen gefunden.");
}
BusinessCardsCard card = tmp.get(0);
card.getAll(BusinessCardsEntry.class).forEach(e -> e.delete());
card.getAll(BusinessCardsEntry.class).forEach(Model::delete);
card.delete();
c.getSender().send("Visitenkarte " + cardname + " wurde erfolgreich gelösch.");
@ -236,7 +239,7 @@ public class BusinessCards implements Module {
.setAction(c -> {
String help = "Synopsis: /showcard CARDNAME";
List<String> args = StringTools.tokenize(c.getParameter());
if (args.size() < 1) {
if (args.isEmpty()) {
c.getSender().send(help);
return;
}
@ -255,11 +258,6 @@ public class BusinessCards implements Module {
List<BusinessCardsEntry> list = card.getAll(BusinessCardsEntry.class);
for (BusinessCardsEntry entry : list) {
/*List<BusinessCardsField> fields = entry.getAll(BusinessCardsField.class);
if ((fields == null) || fields.isEmpty()) {
throw new WhatTheFuckException("Field object is inconsistent.");
}
BusinessCardsField field = fields.get(0);*/
BusinessCardsField field = entry.parent(BusinessCardsField.class);
builder.append(field.getLabel()).append(": ");
builder.append(entry.getValue()).append("\n");
@ -281,7 +279,7 @@ public class BusinessCards implements Module {
.setAction(c -> {
String help = "Synopsis: /givecard CARDNAME USERNAME";
List<String> args = StringTools.tokenize(c.getParameter());
if (args.size() < 1) {
if (args.isEmpty()) {
c.getSender().send(help);
return;
}
@ -315,7 +313,8 @@ public class BusinessCards implements Module {
builder.append("Visitenkarte ").append(StringTools.makeMention(c.getMessage().getFrom())).append(" ").append(cardname).append(":\n\n");
List<BusinessCardsCard> tmp = BusinessCardsCard.getByName(cardname, c.getMessage().getFrom().getId().intValue());
List<BusinessCardsCard> tmp = BusinessCardsCard.getByName(cardname,
c.getMessage().getFrom().getId());
if (tmp == null || tmp.isEmpty()) {
throw new ParsingException("Diese Visitenkarte existiert nicht.\nNeue Karten können mit /createcard hinzugefügt werden.");
}
@ -357,12 +356,13 @@ public class BusinessCards implements Module {
.setAction(c -> {
String help = "Synopsis: /showcards";
List<String> args = StringTools.tokenize(c.getParameter());
if (args.size() != 0) {
if (!args.isEmpty()) {
c.getSender().send(help);
return;
}
List<BusinessCardsCard> tmp = BusinessCardsCard.getByUserid(c.getMessage().getFrom().getId().intValue());
List<BusinessCardsCard> tmp = BusinessCardsCard.getByUserid(
c.getMessage().getFrom().getId());
if (tmp == null || tmp.isEmpty()) {
c.getSender().send("Keine Visitenkarten gefunden.");
return;
@ -435,7 +435,7 @@ public class BusinessCards implements Module {
.setAction(c -> {
String help = "Synopsis: /showcardfields";
List<String> args = StringTools.tokenize(c.getParameter());
if (args.size() != 0) {
if (!args.isEmpty()) {
c.getSender().send(help);
return;
}
@ -490,7 +490,7 @@ public class BusinessCards implements Module {
throw new NurseException("Es wurde kein Feld mit diesem Namen gefunden.");
if ("delete".equals(command)) {
field.getAll(BusinessCardsEntry.class).forEach(e -> e.delete());
field.getAll(BusinessCardsEntry.class).forEach(Model::delete);
field.delete();
c.getSender().send("Das Feld " + name + " wurde erfogreich mit allen Abhängigkiten gelöscht.");
} else if ("set".equals(command)) {
@ -523,7 +523,6 @@ public class BusinessCards implements Module {
} catch (NurseException e) {
Base.rollbackTransaction();
c.getSender().send(help + "\n\n" + e.getMessage());
return;
}
}));
}

View file

@ -1,16 +1,16 @@
package asylum.nursebot.modules;
import asylum.nursebot.NurseNoakes;
import java.util.LinkedList;
import java.util.List;
import com.google.inject.Inject;
import asylum.nursebot.loader.AutoModule;
import asylum.nursebot.modules.buzzwords.Buzzword;
import asylum.nursebot.objects.Module;
import asylum.nursebot.objects.ModuleType;
import asylum.nursebot.semantics.SemanticsHandler;
import asylum.nursebot.semantics.WakeWordType;
import com.google.inject.Inject;
import java.util.LinkedList;
import java.util.List;
@AutoModule(load=true)
public class Buzzwords implements Module {

View file

@ -4,6 +4,7 @@ import java.time.Duration;
import java.time.Instant;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
import com.google.inject.Inject;
@ -22,9 +23,9 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
@AutoModule(load=true)
public class ConversationStarter implements Module {
private final Duration SLEEP_TIME = Duration.ofSeconds(30);
private final Duration IDLE_TIME = Duration.ofHours(7);
private final String[] STARTERS = {
private static final Duration SLEEP_TIME = Duration.ofSeconds(30);
private static final Duration IDLE_TIME = Duration.ofHours(7);
private static final String[] STARTERS = {
"Mir fällt gerade auf: Alles, was ich jemals sagen werde, ist durch mein Programm vorherbestimmt.\n" +
"Ob sich wohl die ganze Welt so verhält?",
@ -214,7 +215,7 @@ public class ConversationStarter implements Module {
Long chatid = c.getMessage().getChat().getId();
if (!lastMessages.containsKey(chatid)) {
new Thread(() -> {
Random random = new Random();
Random random = ThreadLocalRandom.current();
while(true) {
ThreadHelper.ignore(InterruptedException.class, () -> Thread.sleep(SLEEP_TIME.toMillis()));
if (!active)

View file

@ -135,7 +135,7 @@ public class Dices implements Module {
throw new NurseException("Synopsis: /dice {[ANZAHL.]WÜRFEL}");
}
}
if (dices.size() == 0)
if (dices.isEmpty())
throw new NurseException("Mathematisch gesehen gibt es für das Ergebnis nur eine Möglichkeit, wenn man mit gar keinen Würfel spielt. Nämlich das da:");
if (dices.size() > 10)
throw new NurseException("*stolpert, und verteilt " + dices.size() + " Würfel auf dem Boden*\nOh nein... \uD83D\uDE1E");
@ -165,7 +165,8 @@ public class Dices implements Module {
builder.append(", ");
}
dice.roll();
builder.append(dice.display() + " (" + dice.toString() + ")");
builder.append(dice.display()).append(" (").append(dice.toString())
.append(")");
}
}
@ -191,7 +192,7 @@ public class Dices implements Module {
tokens.remove(0);
if (tokens.size() > 0) {
if (!tokens.isEmpty()) {
Number[] parameters = new Number[tokens.size()];
for (int i = 0; i < tokens.size(); i++) {
String tmp = tokens.get(i);

View file

@ -2,6 +2,7 @@ package asylum.nursebot.modules;
import java.util.Calendar;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import com.google.inject.Inject;
@ -109,7 +110,7 @@ public class Eastereggs implements Module {
"Gern geschehen.", "Hab ich gerne gemacht."
};
Random random = new Random();
Random random = ThreadLocalRandom.current();
c.getSender().reply(replys[random.nextInt(replys.length)], c.getMessage());
}));
@ -126,7 +127,7 @@ public class Eastereggs implements Module {
"Heast!"
};
Random random = new Random();
Random random = ThreadLocalRandom.current();
c.getSender().reply(replys[random.nextInt(replys.length)], c.getMessage());
}));
@ -152,7 +153,7 @@ public class Eastereggs implements Module {
if (!(hour < 2 || hour > 21))
return;
Random random = new Random();
Random random = ThreadLocalRandom.current();
c.getSender().reply(replys[random.nextInt(replys.length)], c.getMessage());
}));
}

View file

@ -127,7 +127,7 @@ public class PrivateNotifier implements Module {
if (!chats.contains(user.getId())) {
return;
}
chats.remove(new Long(user.getId()));
chats.remove(user.getId());
PrivateNotifierChat chat = PrivateNotifierChat.find(user.getId());
chat.delete();
}

View file

@ -80,7 +80,7 @@ public class RandomHugs implements Module {
if (properties.next.compareTo(Calendar.getInstance()) < 0) {
List<User> users = new LinkedList<User>(properties.users.values());
if (users.size() != 0) {
if (!users.isEmpty()) {
User user = users.get(random.nextInt(users.size()));
ThreadHelper.ignore(
TelegramApiException.class, () -> sender.mention(user, "\\*random hug\\*"));

View file

@ -129,8 +129,6 @@ public class Statistics implements Module {
chart.setSize(600, 450);
chart.setTitle(title, Color.WHITE, 14);
//chart.addHorizontalRangeMarker(40, 60, Color.newColor(Color.RED, 30));
//chart.addVerticalRangeMarker(70, 90, Color.newColor(Color.GREEN, 30));
double xgrid = 100 / (double) (xLabels.length - 1);
while (xgrid < 10)

View file

@ -73,7 +73,7 @@ public class UserDetails implements Module {
c.getSender().reply(synopsis, c.getMessage());
return;
}
if (users.size() < 1) {
if (users.isEmpty()) {
c.getSender().reply("Der User wurde nicht gefunden. Möglicherweise ist er noch nicht vom UserLookup erfasst.", c.getMessage());
return;
}
@ -116,7 +116,7 @@ public class UserDetails implements Module {
c.getSender().reply("Bitte nicht so viele auf einmal.", c.getMessage());
return;
}
if (users.size() == 0) {
if (users.isEmpty()) {
c.getSender().reply("Diese User kenne ich nicht.", c.getMessage());
return;
}
@ -141,7 +141,7 @@ public class UserDetails implements Module {
okay = true;
builder.append("von ");
if (infoAuthor.getId() == author.getId()) {
if (infoAuthor.getId().equals(author.getId())) {
builder.append("dir");
} else {
builder.append(infoAuthor.getFirstName());

View file

@ -24,7 +24,7 @@ public enum Privacy {
public static Privacy fromString(String name) {
name = name.toLowerCase().replace('-', '_');
for (Privacy privacy : Privacy.values()) {
if (privacy.name().toLowerCase().equals(name))
if (privacy.name().equalsIgnoreCase(name))
return privacy;
}
return null;

View file

@ -2,6 +2,7 @@ package asylum.nursebot.modules.buzzwords;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import asylum.nursebot.objects.Locality;
@ -100,7 +101,8 @@ public class Buzzword extends SemanticInterpreter implements SemanticAction {
@Override
public void action(SemanticContext context) {
Random random = new Random();
Random random = ThreadLocalRandom.current();
if (random.nextDouble() >= chance)
return;

View file

@ -3,6 +3,6 @@ package asylum.nursebot.modules.dices;
public class D12 extends StandardDice {
public D12() {
super(5);
super(12);
}
}

View file

@ -5,7 +5,7 @@ public class D6 extends StandardDice {
super(6);
}
private final String[] images = {"", "", "", "", "", ""};
private static final String[] images = {"", "", "", "", "", ""};
@Override
public String display() {

View file

@ -48,7 +48,7 @@ public class Connector {
logger.exception(e1);
try {
Base.close();
} catch (Exception e2) {
} catch (Exception ignored) {
}
connect();
}

View file

@ -22,7 +22,7 @@ public class NurseModule extends Model implements Selfbuilding {
static public NurseModule byName(String name) {
List<NurseModule> list = NurseModule.where("module = ?", name);
if (list == null || list.size() == 0)
if (list == null || list.isEmpty())
return null;
return list.get(0);
}

View file

@ -22,7 +22,7 @@ public class PrivateNotifierChat extends Model implements Selfbuilding {
public static PrivateNotifierChat find(long userid) {
List<PrivateNotifierChat> list = NurseModule.where("userid = ?", userid);
if (list == null || list.size() == 0)
if (list == null || list.isEmpty())
return null;
return list.get(0);
}

View file

@ -9,6 +9,9 @@ public abstract class Logger {
public final static int EXCEPTION = 3;
public final static int CRITICAL = 4;
public static final String END_ANSI = "\033[0m";
public static final String BLINK = "\033[1m";
protected final static int DEFAULT_VERBOSITY = INFO;
protected enum LogColor {
@ -25,11 +28,11 @@ public abstract class Logger {
}
public String endANSI() {
return "\033[0m";
return END_ANSI;
}
public String blink() {
return "\033[1m";
return BLINK;
}
}