Skip to content

Commit b035981

Browse files
Added a a bit more null safety to command configs
and enhanced code quality in a few places
1 parent bbab441 commit b035981

File tree

8 files changed

+66
-73
lines changed

8 files changed

+66
-73
lines changed

src/main/java/io/github/jdaapplications/guildbot/GuildBot.java

+7-7
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import io.github.jdaapplications.guildbot.executor.CommandExecutor;
44
import io.github.jdaapplications.guildbot.util.ExceptionUtils;
5-
import io.github.jdaapplications.guildbot.util.Properties;
5+
import io.github.jdaapplications.guildbot.util.PropertyUtil;
66
import net.dv8tion.jda.core.*;
77
import net.dv8tion.jda.core.entities.Game;
88
import net.dv8tion.jda.core.entities.impl.JDAImpl;
@@ -15,6 +15,7 @@
1515
import net.dv8tion.jda.core.requests.Requester;
1616
import net.dv8tion.jda.core.utils.IOUtil;
1717
import okhttp3.*;
18+
import org.apache.commons.io.FileUtils;
1819
import org.hjson.JsonObject;
1920
import org.hjson.JsonValue;
2021
import org.json.JSONArray;
@@ -25,7 +26,6 @@
2526
import java.awt.Color;
2627
import java.io.File;
2728
import java.io.FileNotFoundException;
28-
import java.io.FileReader;
2929
import java.io.IOException;
3030
import java.nio.file.Paths;
3131
import java.util.concurrent.ScheduledExecutorService;
@@ -53,10 +53,9 @@ public class GuildBot
5353

5454
private CommandExecutor commandExecutor;
5555

56-
@SuppressWarnings("resource")
5756
public GuildBot(final File config, final String token, final String errorWebhook) throws LoginException, IllegalArgumentException, RateLimitedException, FileNotFoundException, IOException
5857
{
59-
this.config = JsonValue.readHjson(new FileReader(config)).asObject();
58+
this.config = JsonValue.readHjson(FileUtils.readFileToString(config, "UTF-8")).asObject();
6059
this.webhookUrl = errorWebhook;
6160

6261
this.threadPool = new ScheduledThreadPoolExecutor(4, r ->
@@ -90,11 +89,11 @@ public static void main(final String[] args) throws Exception
9089
{
9190
final File config = new File(System.getProperty("guildbot.config", "config.hjson"));
9291

93-
String token = Properties.get("guildbot.token", Paths.get(".token"));
92+
String token = PropertyUtil.getProperty("guildbot.token", Paths.get(".token"));
9493
if (token == null)
9594
throw new RuntimeException("could not find a token");
9695

97-
String webhook = Properties.get("guildbot.webhook.error", Paths.get(".error-hook"));
96+
String webhook = PropertyUtil.getProperty("guildbot.webhook.error", Paths.get(".error-hook"));
9897
if (webhook == null)
9998
GuildBot.log.warn("could not find a error webhook token, disabling webhook");
10099

@@ -137,19 +136,20 @@ public void handleThrowable(final Throwable throwable, final String context)
137136
.setDescription(String.format("%.2048s", message))
138137
.build();
139138

140-
141139
final String body = new JSONObject()
142140
.put("embeds", new JSONArray()
143141
.put(embed.toJSONObject()))
144142
.toString();
145143

146144
OkHttpClient client = ((JDAImpl) getJDA()).getRequester().getHttpClient();
145+
147146
Request request = new Request.Builder().url(this.webhookUrl)
148147
.post(RequestBody.create(MediaType.parse("application/json"), body))
149148
.addHeader("user-agent", "GuildBot (https://github.com/JDA-Applications/GuildBot)")
150149
.addHeader("content-type", "application/json")
151150
.addHeader("accept-encoding", "gzip")
152151
.build();
152+
153153
Call call = client.newCall(request);
154154
try (Response response = call.execute())
155155
{

src/main/java/io/github/jdaapplications/guildbot/executor/Engine.java

+5-6
Original file line numberDiff line numberDiff line change
@@ -15,17 +15,16 @@
1515
*/
1616
public enum Engine
1717
{
18-
1918
GROOVY("groovy")
2019
{
2120
@Override
22-
public String getProxyMethod(final String name, final Class<?> type, final List<Pair<String, ? extends Class<?>>> params)
21+
public String getProxyMethod(final String methodName, final Class<?> type, final List<Pair<String, ? extends Class<?>>> params)
2322
{
24-
return type.getTypeName() + ' ' + name + '('
23+
return type.getTypeName() + ' ' + methodName + '('
2524
+ params.stream()
2625
.map(e -> e.getValue().getTypeName() + ' ' + e.getKey())
2726
.collect(Collectors.joining(", "))
28-
+ ") { " + name + ".invoke("
27+
+ ") { " + methodName + ".invoke("
2928
+ params.stream()
3029
.map(Pair::getKey)
3130
.collect(Collectors.joining(", "))
@@ -53,7 +52,7 @@ public String escapeCodeBlock(String script)
5352
JAVASCRIPT("js")
5453
{
5554
@Override
56-
public String getProxyMethod(final String name, final Class<?> type, final List<Pair<String, ? extends Class<?>>> params)
55+
public String getProxyMethod(final String methodName, final Class<?> type, final List<Pair<String, ? extends Class<?>>> params)
5756
{
5857
return null;
5958
}
@@ -104,7 +103,7 @@ public String getName()
104103
return this.name;
105104
}
106105

107-
public abstract String getProxyMethod(String name, Class<?> type, List<Pair<String, ? extends Class<?>>> params);
106+
public abstract String getProxyMethod(String methodName, Class<?> type, List<Pair<String, ? extends Class<?>>> params);
108107

109108
public abstract String getScript(String script, Collection<String> imports);
110109

src/main/java/io/github/jdaapplications/guildbot/executor/EngineMap.java

-2
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,6 @@ public EngineMap()
4747
((Bindings) scriptEngine.get("engines")).put(e.getName(), scriptEngine);
4848
return scriptEngine;
4949
});
50-
5150
}
5251

5352
public Set<Entry<Engine, ScriptEngine>> entrySet()
@@ -64,5 +63,4 @@ public ScriptContext getContext()
6463
{
6564
return this.context;
6665
}
67-
6866
}

src/main/java/io/github/jdaapplications/guildbot/executor/executable/Executable.java

+3-1
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,14 @@ public Executable(final GuildBot guildBot, final JsonObject config, final String
2727
this.engine = Engine.getEngine(config.getString("lang", "js"));
2828

2929
this.script = this.engine.escapeCodeBlock(script);
30-
30+
3131
final JsonValue importArray = config.get("imports");
3232
this.imports = Collections.unmodifiableSet(importArray == null
3333
? Collections.emptySet()
3434
: importArray.asArray().values().stream()
35+
.filter(JsonValue::isString)
3536
.map(JsonValue::asString)
37+
.filter(s -> !s.isEmpty())
3638
.collect(Collectors.toSet()));
3739
}
3840

src/main/java/io/github/jdaapplications/guildbot/executor/executable/Method.java

+8-10
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,13 @@
22

33
import io.github.jdaapplications.guildbot.GuildBot;
44
import io.github.jdaapplications.guildbot.executor.Engine;
5-
import java.util.Collections;
6-
import java.util.HashMap;
7-
import java.util.List;
8-
import java.util.Map;
5+
import java.util.*;
96
import java.util.concurrent.ExecutionException;
107
import java.util.concurrent.Future;
118
import java.util.concurrent.TimeUnit;
129
import java.util.concurrent.TimeoutException;
1310
import java.util.stream.Collectors;
11+
import java.util.stream.StreamSupport;
1412
import javax.script.ScriptContext;
1513
import javax.script.ScriptEngine;
1614
import org.apache.commons.collections4.map.LazyMap;
@@ -47,11 +45,12 @@ public Method(final GuildBot guildBot, final JsonObject config, final String nam
4745

4846
this.params = Collections.unmodifiableList(paramList == null
4947
? Collections.emptyList()
50-
: paramList.names().stream()
51-
.map(k -> {
48+
: StreamSupport.stream(paramList.spliterator(), false)
49+
.filter(m -> m.getValue().isString() && !m.getValue().asString().isEmpty())
50+
.map(m -> {
5251
try
5352
{
54-
return Pair.of(k, ClassUtils.getClass(paramList.get(k).asString()));
53+
return Pair.of(m.getName(), ClassUtils.getClass(m.getValue().asString()));
5554
}
5655
catch (ClassNotFoundException e)
5756
{
@@ -65,10 +64,9 @@ public Method(final GuildBot guildBot, final JsonObject config, final String nam
6564
this.proxyScript = this.engine.getScript(this.getScript(), this.imports);
6665
}
6766

68-
@SuppressWarnings("hiding")
69-
public String getExecutableScript(final Engine engine)
67+
public String getExecutableScript(final Engine targetEngine)
7068
{
71-
return this.executableScripts.get(engine);
69+
return this.executableScripts.get(targetEngine);
7270
}
7371

7472
public Map<Engine, String> getExecutableScripts()

src/main/java/io/github/jdaapplications/guildbot/util/ExceptionUtils.java

+2-4
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,12 @@
22

33
public class ExceptionUtils
44
{
5-
65
public static String getTrace(final Throwable throwable)
76
{
87
StringBuilder builder = new StringBuilder(throwable.getClass().getName())
98
.append(": ")
109
.append(throwable.getMessage());
11-
10+
1211
StackTraceElement[] elements = throwable.getStackTrace();
1312
for (int i = 0; i < elements.length && i < 15; i++)
1413
{
@@ -21,8 +20,7 @@ public static String getTrace(final Throwable throwable)
2120
}
2221
builder.append("\n\tat ").append(element.toString());
2322
}
24-
23+
2524
return builder.toString();
2625
}
27-
2826
}

src/main/java/io/github/jdaapplications/guildbot/util/GuildBotUtils.java

-2
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66

77
public class GuildBotUtils
88
{
9-
109
public static boolean isScriptChannel(final TextChannel channel)
1110
{
1211
return channel.getName().startsWith("cmd-") || channel.getName().startsWith("mthd-") || channel.getName().startsWith("vars-");
@@ -16,5 +15,4 @@ public static JsonObject readConfig(final TextChannel channel)
1615
{
1716
return channel.getTopic() == null || channel.getTopic().isEmpty() ? new JsonObject() : JsonValue.readHjson(channel.getTopic()).asObject();
1817
}
19-
2018
}
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,41 @@
1-
package io.github.jdaapplications.guildbot.util;
2-
3-
import io.github.jdaapplications.guildbot.GuildBot;
4-
import java.io.IOException;
5-
import java.nio.file.Files;
6-
import java.nio.file.Path;
7-
8-
public class Properties
9-
{
10-
public static String get(final String name, final Path path)
11-
{
12-
final String property = System.getProperty(name);
13-
if (property != null)
14-
return property;
15-
16-
try
17-
{
18-
if (!Files.exists(path))
19-
{
20-
GuildBot.log.warn(path.getFileName() + " file is empty");
21-
return null;
22-
}
23-
if (!Files.isReadable(path))
24-
{
25-
GuildBot.log.warn("Unable to read " + path.getFileName());
26-
return null;
27-
}
28-
if (Files.size(path) == 0L)
29-
{
30-
GuildBot.log.warn(path.getFileName() + " file is empty");
31-
return null;
32-
}
33-
return Files.newBufferedReader(path).lines().filter(l -> !l.startsWith("#")).findFirst().map(String::trim).orElse(null);
34-
}
35-
catch (final IOException e)
36-
{
37-
GuildBot.log.error("An error occurred while reading " + path.getFileName(), e);
38-
return null;
39-
}
40-
}
41-
}
1+
package io.github.jdaapplications.guildbot.util;
2+
3+
import io.github.jdaapplications.guildbot.GuildBot;
4+
import java.io.IOException;
5+
import java.nio.file.Files;
6+
import java.nio.file.Path;
7+
8+
public class PropertyUtil
9+
{
10+
public static String getProperty(final String name, final Path path)
11+
{
12+
final String property = System.getProperty(name);
13+
if (property != null)
14+
return property;
15+
16+
try
17+
{
18+
if (!Files.exists(path))
19+
{
20+
GuildBot.log.warn(path.getFileName() + " file is empty");
21+
return null;
22+
}
23+
if (!Files.isReadable(path))
24+
{
25+
GuildBot.log.warn("Unable to read " + path.getFileName());
26+
return null;
27+
}
28+
if (Files.size(path) == 0L)
29+
{
30+
GuildBot.log.warn(path.getFileName() + " file is empty");
31+
return null;
32+
}
33+
return Files.newBufferedReader(path).lines().filter(l -> !l.startsWith("#")).findFirst().map(String::trim).orElse(null);
34+
}
35+
catch (final IOException e)
36+
{
37+
GuildBot.log.error("An error occurred while reading " + path.getFileName(), e);
38+
return null;
39+
}
40+
}
41+
}

0 commit comments

Comments
 (0)