Now extends ThreadedModule

This commit is contained in:
Erik C. Thauvin 2019-04-09 15:58:13 -07:00
parent 0ce160c905
commit 70f6781e56
4 changed files with 83 additions and 92 deletions

View file

@ -59,7 +59,7 @@ import java.util.TreeMap;
* @created Feb 11, 2004 * @created Feb 11, 2004
* @since 1.0 * @since 1.0
*/ */
public final class CurrencyConverter extends AbstractModule { public final class CurrencyConverter extends ThreadedModule {
// The rates keyword. // The rates keyword.
static final String CURRENCY_RATES_KEYWORD = "rates"; static final String CURRENCY_RATES_KEYWORD = "rates";
// The currency command. // The currency command.
@ -78,7 +78,7 @@ public final class CurrencyConverter extends AbstractModule {
commands.add(CURRENCY_CMD); commands.add(CURRENCY_CMD);
} }
static Message convertCurrency(String query) throws ModuleException { static Message convertCurrency(final String query) throws ModuleException {
if (EXCHANGE_RATES.isEmpty()) { if (EXCHANGE_RATES.isEmpty()) {
try { try {
final SAXBuilder builder = new SAXBuilder(); final SAXBuilder builder = new SAXBuilder();
@ -168,7 +168,7 @@ public final class CurrencyConverter extends AbstractModule {
} }
} }
new Thread(() -> run(bot, sender, args)).start(); super.commandResponse(bot, sender, args, isPrivate);
} }
/** /**
@ -191,7 +191,7 @@ public final class CurrencyConverter extends AbstractModule {
* Converts the specified currencies. * Converts the specified currencies.
*/ */
@SuppressFBWarnings(value = "REDOS") @SuppressFBWarnings(value = "REDOS")
private void run(final Mobibot bot, final String sender, final String query) { void run(final Mobibot bot, final String sender, final String query) {
if (Utils.isValidString(sender) && Utils.isValidString(query)) { if (Utils.isValidString(sender) && Utils.isValidString(query)) {
if (query.matches("\\d+([,\\d]+)?(\\.\\d+)? [a-zA-Z]{3}+ to [a-zA-Z]{3}+")) { if (query.matches("\\d+([,\\d]+)?(\\.\\d+)? [a-zA-Z]{3}+ to [a-zA-Z]{3}+")) {
try { try {

View file

@ -50,7 +50,7 @@ import java.nio.charset.StandardCharsets;
* @created 2014-04-20 * @created 2014-04-20
* @since 1.0 * @since 1.0
*/ */
public final class Joke extends AbstractModule { public final class Joke extends ThreadedModule {
// The ICNDB URL. // The ICNDB URL.
private static final String JOKE_URL = private static final String JOKE_URL =
"http://api.icndb.com/jokes/random?escape=javascript&exclude=[explicit]&limitTo=[nerdy]"; "http://api.icndb.com/jokes/random?escape=javascript&exclude=[explicit]&limitTo=[nerdy]";
@ -94,14 +94,6 @@ public final class Joke extends AbstractModule {
} }
} }
/**
* {@inheritDoc}
*/
@Override
public void commandResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate) {
new Thread(() -> run(bot, sender)).start();
}
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@ -114,7 +106,7 @@ public final class Joke extends AbstractModule {
/** /**
* Returns a random joke from <a href="http://www.icndb.com/">The Internet Chuck Norris Database</a> * Returns a random joke from <a href="http://www.icndb.com/">The Internet Chuck Norris Database</a>
*/ */
private void run(final Mobibot bot, final String sender) { void run(final Mobibot bot, final String sender, String arg) {
try { try {
bot.send(bot.getChannel(), Utils.cyan(randomJoke().getMessage())); bot.send(bot.getChannel(), Utils.cyan(randomJoke().getMessage()));
} catch (ModuleException e) { } catch (ModuleException e) {

View file

@ -53,7 +53,7 @@ import java.util.ArrayList;
* @created Feb 7, 2004 * @created Feb 7, 2004
* @since 1.0 * @since 1.0
*/ */
public final class StockQuote extends AbstractModule { public final class StockQuote extends ThreadedModule {
/** /**
* The Alpha Advantage property key. * The Alpha Advantage property key.
*/ */
@ -79,81 +79,78 @@ public final class StockQuote extends AbstractModule {
* @return The stock quote. * @return The stock quote.
* @throws ModuleException If an errors occurs. * @throws ModuleException If an errors occurs.
*/ */
static ArrayList<Message> getQuote(String symbol, String apiKey) throws ModuleException { static ArrayList<Message> getQuote(final String symbol, final String apiKey) throws ModuleException {
final String debugMessage = "getQuote(" + symbol + ')'; if (!Utils.isValidString(apiKey)) {
final ArrayList<Message> messages = new ArrayList<>(); throw new ModuleException(Utils.capitalize(STOCK_CMD) + " is disabled. The API key is missing.");
final OkHttpClient client = new OkHttpClient(); }
final Request request =
new Request.Builder().url(ALAPHADVANTAGE_URL + "&symbol=" + symbol + "&apikey=" + apiKey).build();
try { if (Utils.isValidString(symbol)) {
final Response response = client.newCall(request).execute(); final String debugMessage = "getQuote(" + symbol + ')';
if (response.body() != null) { final ArrayList<Message> messages = new ArrayList<>();
final JSONObject json = new JSONObject(response.body().string()); final OkHttpClient client = new OkHttpClient();
final Request request =
new Request.Builder().url(ALAPHADVANTAGE_URL + "&symbol=" + symbol + "&apikey=" + apiKey).build();
try { try {
final String info = json.getString("Information"); final Response response = client.newCall(request).execute();
if (!info.isEmpty()) { if (response.body() != null) {
throw new ModuleException(debugMessage, Utils.unescapeXml(info)); final JSONObject json = new JSONObject(response.body().string());
try {
final String info = json.getString("Information");
if (!info.isEmpty()) {
throw new ModuleException(debugMessage, Utils.unescapeXml(info));
}
} catch (JSONException ignore) {
// Do nothing.
} }
} catch (JSONException ignore) {
// Do nothing.
}
try { try {
final String error = json.getString("Error Message"); final String error = json.getString("Error Message");
if (!error.isEmpty()) { if (!error.isEmpty()) {
throw new ModuleException(debugMessage, Utils.unescapeXml(error)); throw new ModuleException(debugMessage, Utils.unescapeXml(error));
}
} catch (JSONException ignore) {
// Do nothing.
} }
} catch (JSONException ignore) {
// Do nothing. final JSONObject quote = json.getJSONObject("Global Quote");
if (quote.isEmpty()) {
messages.add(new ErrorMessage("Invalid symbol."));
return messages;
}
messages.add(
new PublicMessage("Symbol: " + Utils.unescapeXml(quote.getString("01. symbol"))));
messages.add(
new PublicMessage(" Price: " + Utils.unescapeXml(quote.getString("05. price"))));
messages.add(
new PublicMessage(" Previous: "
+ Utils.unescapeXml(quote.getString("08. previous close"))));
messages.add(
new NoticeMessage(" Open: " + Utils.unescapeXml(quote.getString("02. open"))));
messages.add(
new NoticeMessage(" High: " + Utils.unescapeXml(quote.getString("03. high"))));
messages.add(
new NoticeMessage(" Low: " + Utils.unescapeXml(quote.getString("04. low"))));
messages.add(
new NoticeMessage(" Volume: " + Utils.unescapeXml(quote.getString("06. volume"))));
messages.add(
new NoticeMessage(" Latest: "
+ Utils.unescapeXml(quote.getString("07. latest trading day"))));
messages.add(
new NoticeMessage(" Change: " + Utils.unescapeXml(quote.getString("09. change"))
+ " [" + Utils.unescapeXml(quote.getString("10. change percent")) + ']'));
} }
} catch (IOException e) {
final JSONObject quote = json.getJSONObject("Global Quote"); throw new ModuleException(debugMessage, "An error has occurred retrieving a stock quote.", e);
if (quote.isEmpty()) {
messages.add(new ErrorMessage("Invalid symbol."));
return messages;
}
messages.add(
new PublicMessage("Symbol: " + Utils.unescapeXml(quote.getString("01. symbol"))));
messages.add(
new PublicMessage(" Price: " + Utils.unescapeXml(quote.getString("05. price"))));
messages.add(
new PublicMessage(" Previous: "
+ Utils.unescapeXml(quote.getString("08. previous close"))));
messages.add(
new NoticeMessage(" Open: " + Utils.unescapeXml(quote.getString("02. open"))));
messages.add(
new NoticeMessage(" High: " + Utils.unescapeXml(quote.getString("03. high"))));
messages.add(
new NoticeMessage(" Low: " + Utils.unescapeXml(quote.getString("04. low"))));
messages.add(
new NoticeMessage(" Volume: " + Utils.unescapeXml(quote.getString("06. volume"))));
messages.add(
new NoticeMessage(" Latest: "
+ Utils.unescapeXml(quote.getString("07. latest trading day"))));
messages.add(
new NoticeMessage(" Change: " + Utils.unescapeXml(quote.getString("09. change"))
+ " [" + Utils.unescapeXml(quote.getString("10. change percent")) + ']'));
} }
} catch (IOException e) { return messages;
throw new ModuleException(debugMessage, "An error has occurred retrieving a stock quote.", e);
}
return messages;
}
/**
* {@inheritDoc}
*/
@Override
public void commandResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate) {
if (args.length() > 0) {
new Thread(() -> run(bot, sender, args)).start();
} else { } else {
helpResponse(bot, sender, args, isPrivate); throw new ModuleException("Invalid symbol.");
} }
} }
/** /**
@ -168,17 +165,19 @@ public final class StockQuote extends AbstractModule {
/** /**
* Returns the specified stock quote from Alpha Advantage. * Returns the specified stock quote from Alpha Advantage.
*/ */
private void run(final Mobibot bot, final String sender, final String symbol) { void run(final Mobibot bot, final String sender, final String symbol) {
try { if (Utils.isValidString(symbol)) {
final ArrayList<Message> messages = try {
getQuote(symbol, properties.get(ALPHAVANTAGE_API_KEY_PROP)); final ArrayList<Message> messages = getQuote(symbol, properties.get(ALPHAVANTAGE_API_KEY_PROP));
for (Message msg : messages) { for (final Message msg : messages) {
bot.send(msg.isNotice() ? sender : bot.getChannel(), msg.getMessage()); bot.send(msg.isNotice() ? sender : bot.getChannel(), msg.getMessage());
}
} catch (ModuleException e) {
bot.getLogger().warn(e.getDebugMessage(), e);
bot.send(bot.getChannel(), e.getMessage());
} }
} else {
} catch (ModuleException e) { helpResponse(bot, sender, symbol, true);
bot.getLogger().warn(e.getDebugMessage(), e);
bot.send(sender, "An error has occurred retrieving a stock quote.");
} }
} }
} }

View file

@ -163,7 +163,7 @@ public final class WorldTime extends AbstractModule {
return String.format("%c%03d", '@', beats); return String.format("%c%03d", '@', beats);
} }
static Message worldTime(String query) { static Message worldTime(final String query) {
final String tz = (COUNTRIES_MAP.get((query.substring(query.indexOf(' ') + 1).trim().toUpperCase()))); final String tz = (COUNTRIES_MAP.get((query.substring(query.indexOf(' ') + 1).trim().toUpperCase())));
final String response; final String response;