Switched to MutableList vs ArrayList whenever possible.

Made sure logging level is enabled before logging.
This commit is contained in:
Erik C. Thauvin 2020-12-06 01:49:02 -08:00
parent ece6ae98a0
commit 5a831f2c7c
20 changed files with 75 additions and 98 deletions

View file

@ -34,17 +34,16 @@ package net.thauvin.erik.mobibot
import net.thauvin.erik.mobibot.commands.AbstractCommand
import net.thauvin.erik.mobibot.modules.AbstractModule
import java.util.*
import kotlin.collections.ArrayList
/**
* Modules and Commands addons.
*/
class Addons {
val commands: MutableList<AbstractCommand> = ArrayList()
val modules: MutableList<AbstractModule> = ArrayList()
val modulesNames: MutableList<String> = ArrayList()
val names: MutableList<String> = ArrayList()
val ops: MutableList<String> = ArrayList()
val commands: MutableList<AbstractCommand> = mutableListOf()
val modules: MutableList<AbstractModule> = mutableListOf()
val modulesNames: MutableList<String> = mutableListOf()
val names: MutableList<String> = mutableListOf()
val ops: MutableList<String> = mutableListOf()
/**
* Add a module with properties.

View file

@ -69,10 +69,10 @@ class FeedReader(
}
}
} catch (e: MalformedURLException) {
logger.debug("Invalid feed URL.", e)
if (logger.isDebugEnabled) logger.debug("Invalid feed URL.", e)
send(sender, "The feed URL is invalid.", false)
} catch (e: Exception) {
logger.debug("Unable to fetch the feed.", e)
if (logger.isDebugEnabled) logger.debug("Unable to fetch the feed.", e)
send(sender, "An error has occurred while fetching the feed: ${e.message}", false)
}
}

View file

@ -136,25 +136,25 @@ class Mobibot(nickname: String, channel: String, logsDirPath: String, p: Propert
private val pinboard: PinboardPoster = PinboardPoster()
/** Tell command. */
val tell: Tell
val tell: Tell = Tell(this)
/** Today's date. */
val today = today()
/** Twitter module. */
val twitter: Twitter
val twitter: Twitter = Twitter(this)
/** The backlogs URL. */
var backlogsUrl = ""
val backlogsUrl: String
// Ident message
private var identMsg = ""
private val identMsg: String
// Ident nick
private var identNick = ""
private val identNick: String
// NickServ ident password
private var identPwd = ""
private val identPwd: String
// Is pinboard enabled?
private var isPinboardEnabled = false
@ -163,7 +163,7 @@ class Mobibot(nickname: String, channel: String, logsDirPath: String, p: Propert
val timer = Timer(true)
/** Weblog URL */
var weblogUrl = ""
val weblogUrl: String
/** The current channel name. */
private val channelName: String
@ -212,7 +212,9 @@ class Mobibot(nickname: String, channel: String, logsDirPath: String, p: Propert
connect(ircServer, ircPort)
} catch (ex: Exception) {
if (retries == MAX_RECONNECT) {
logger.debug("Unable to reconnect to $ircServer, after $MAX_RECONNECT retries.", ex)
if (logger.isDebugEnabled) {
logger.debug("Unable to reconnect to $ircServer, after $MAX_RECONNECT retries.", ex)
}
e.printStackTrace(System.err)
exitProcess(1)
}
@ -350,7 +352,7 @@ class Mobibot(nickname: String, channel: String, logsDirPath: String, p: Propert
hostname: String,
message: String
) {
logger.debug(">>> $sender: $message")
if (logger.isDebugEnabled) logger.debug(">>> $sender: $message")
tell.send(sender, true)
if (message.matches("(?i)${Pattern.quote(nick)}:.*".toRegex())) { // mobibot: <command>
val cmds = message.substring(message.indexOf(':') + 1).trim().split(" ".toRegex(), 2)
@ -396,9 +398,7 @@ class Mobibot(nickname: String, channel: String, logsDirPath: String, p: Propert
hostname: String,
message: String
) {
if (logger.isDebugEnabled) {
logger.debug(">>> $sender : $message")
}
if (logger.isDebugEnabled) logger.debug(">>> $sender : $message")
val cmds = message.split(" ".toRegex(), 2)
val cmd = cmds[0].toLowerCase()
val args = if (cmds.size > 1) {
@ -467,10 +467,10 @@ class Mobibot(nickname: String, channel: String, logsDirPath: String, p: Propert
fun send(sender: String, message: String?, isPrivate: Boolean) {
if (message != null && sender.isNotBlank()) {
if (isPrivate) {
logger.debug("Sending message to $sender : $message")
if (logger.isDebugEnabled) logger.debug("Sending message to $sender : $message")
sendMessage(sender, message)
} else {
logger.debug("Sending notice to $sender: $message")
if (logger.isDebugEnabled) logger.debug("Sending notice to $sender: $message")
sendNotice(sender, message)
}
}
@ -597,7 +597,7 @@ class Mobibot(nickname: String, channel: String, logsDirPath: String, p: Propert
try {
commandLine = parser.parse(options, args)
} catch (e: ParseException) {
System.err.println("CLI Parsing failed. Reason: ${e.message}")
System.err.println("CLI Parsing failed. Reason: ${e.message}")
e.printStackTrace(System.err)
exitProcess(1)
}
@ -684,13 +684,13 @@ class Mobibot(nickname: String, channel: String, logsDirPath: String, p: Propert
this.channel = channel
logsDir = logsDirPath
// Set the default logger level
// Store the default logger level
loggerLevel = logger.level
// Load the current entries and backlogs, if any
try {
startup(logsDir + EntriesMgr.CURRENT_XML, logsDir + EntriesMgr.NAV_XML, this.channel)
logger.debug("Last feed: $startDate")
if (logger.isDebugEnabled) logger.debug("Last feed: $startDate")
} catch (e: Exception) {
logger.error("An error occurred while loading the logs.", e)
}
@ -712,7 +712,7 @@ class Mobibot(nickname: String, channel: String, logsDirPath: String, p: Propert
backlogsUrl = ensureDir(p.getProperty("backlogs", weblogUrl), true)
// Set the pinboard authentication
setPinboardAuth(p.getProperty("pinboard-api-token"))
setPinboardAuth(p.getProperty("pinboard-api-token", ""))
// Load the commands
addons.add(AddLog(this), p)
@ -730,7 +730,6 @@ class Mobibot(nickname: String, channel: String, logsDirPath: String, p: Propert
addons.add(Versions(this), p)
// Tell command
tell = Tell(this)
addons.add(tell, p)
// Load the links commands
@ -755,7 +754,6 @@ class Mobibot(nickname: String, channel: String, logsDirPath: String, p: Propert
addons.add(WorldTime(this), p)
// Twitter module
twitter = Twitter(this)
addons.add(twitter, p)
// Sort the addons

View file

@ -36,7 +36,6 @@ import net.thauvin.erik.mobibot.Mobibot
import net.thauvin.erik.mobibot.Utils
import java.time.Clock
import java.time.LocalDateTime
import java.util.*
class Recap(bot: Mobibot) : AbstractCommand(bot) {
override val name = "recap"
@ -49,7 +48,7 @@ class Recap(bot: Mobibot) : AbstractCommand(bot) {
override val isVisible = true
companion object {
private val recaps = ArrayList<String>(0)
private val recaps = mutableListOf<String>()
@JvmStatic
fun recapCount(): Int {

View file

@ -35,7 +35,6 @@ package net.thauvin.erik.mobibot.commands
import net.thauvin.erik.mobibot.Mobibot
import net.thauvin.erik.mobibot.Utils
import org.jibble.pircbot.User
import java.util.*
class Users(bot: Mobibot) : AbstractCommand(bot) {
override val name = "users"
@ -56,7 +55,7 @@ class Users(bot: Mobibot) : AbstractCommand(bot) {
isPrivate: Boolean
) {
val users: Array<User> = bot.getUsers(bot.channel)
val nicks = ArrayList<String>()
val nicks = mutableListOf<String>()
users.forEach { user ->
if (bot.isOp(user.nick)) {
nicks.add("@${user.nick}")

View file

@ -44,8 +44,8 @@ import org.jsoup.Jsoup
import java.io.IOException
class LinksMgr(bot: Mobibot) : AbstractCommand(bot) {
private val keywords: MutableList<String> = ArrayList()
private val defaultTags: MutableList<String> = ArrayList()
private val keywords: MutableList<String> = mutableListOf()
private val defaultTags: MutableList<String> = mutableListOf()
override val name = Constants.LINK_CMD
override val help = emptyList<String>()
@ -65,11 +65,11 @@ class LinksMgr(bot: Mobibot) : AbstractCommand(bot) {
// Entries array
@JvmField
val entries = ArrayList<EntryLink>(0)
val entries = mutableListOf<EntryLink>()
// History/backlogs array
@JvmField
val history = ArrayList<String>(0)
val history = mutableListOf<String>()
@JvmStatic
@ -207,7 +207,7 @@ class LinksMgr(bot: Mobibot) : AbstractCommand(bot) {
return false
}
private fun matchTagKeywords(title: String, tags: ArrayList<String>) {
private fun matchTagKeywords(title: String, tags: MutableList<String>) {
for (match in keywords) {
val m = Regex.escape(match)
if (title.matches("(?i).*\\b$m\\b.*".toRegex())) {

View file

@ -41,14 +41,13 @@ import net.thauvin.erik.mobibot.Utils.Companion.reverseColor
import net.thauvin.erik.mobibot.Utils.Companion.utcDateTime
import net.thauvin.erik.mobibot.commands.AbstractCommand
import net.thauvin.erik.mobibot.commands.links.View
import java.util.concurrent.CopyOnWriteArrayList
/**
* The `Tell` command.
*/
class Tell(bot: Mobibot) : AbstractCommand(bot) {
// Messages queue
private val messages: MutableList<TellMessage> = CopyOnWriteArrayList()
private val messages: MutableList<TellMessage> = mutableListOf()
// Serialized object file
private val serializedObject: String
@ -63,9 +62,7 @@ class Tell(bot: Mobibot) : AbstractCommand(bot) {
* Cleans the messages queue.
*/
private fun clean(): Boolean {
if (bot.logger.isDebugEnabled) {
bot.logger.debug("Cleaning the messages.")
}
if (bot.logger.isDebugEnabled) bot.logger.debug("Cleaning the messages.")
return TellMessagesMgr.clean(messages, maxDays)
}

View file

@ -66,9 +66,7 @@ internal class TellMessagesMgr private constructor() {
ObjectInputStream(
BufferedInputStream(Files.newInputStream(Paths.get(file)))
).use { input ->
if (logger.isDebugEnabled) {
logger.debug("Loading the messages.")
}
if (logger.isDebugEnabled) logger.debug("Loading the messages.")
@Suppress("UNCHECKED_CAST")
return input.readObject() as List<TellMessage>
}
@ -79,7 +77,7 @@ internal class TellMessagesMgr private constructor() {
} catch (e: ClassNotFoundException) {
logger.error("An error occurred loading the messages queue.", e)
}
return ArrayList()
return listOf()
}
/**
@ -89,9 +87,7 @@ internal class TellMessagesMgr private constructor() {
try {
BufferedOutputStream(Files.newOutputStream(Paths.get(file))).use { bos ->
ObjectOutputStream(bos).use { output ->
if (logger.isDebugEnabled) {
logger.debug("Saving the messages.")
}
if (logger.isDebugEnabled) logger.debug("Saving the messages.")
output.writeObject(messages)
}
}

View file

@ -48,7 +48,6 @@ import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Paths
import java.util.*
import kotlin.collections.ArrayList
/**
* Manages the feed entries.
@ -79,7 +78,7 @@ class EntriesMgr private constructor() {
* Loads the backlogs.
*/
@Throws(IOException::class, FeedException::class)
fun loadBacklogs(file: String, history: ArrayList<String>) {
fun loadBacklogs(file: String, history: MutableList<String>) {
history.clear()
val input = SyndFeedInput()
InputStreamReader(Files.newInputStream(Paths.get(file)), StandardCharsets.UTF_8).use { reader ->
@ -95,7 +94,7 @@ class EntriesMgr private constructor() {
* Loads the current entries.
*/
@Throws(IOException::class, FeedException::class)
fun loadEntries(file: String, channel: String, entries: ArrayList<EntryLink>): String {
fun loadEntries(file: String, channel: String, entries: MutableList<EntryLink>): String {
entries.clear()
val input = SyndFeedInput()
var today: String
@ -139,14 +138,12 @@ class EntriesMgr private constructor() {
history: MutableList<String>,
isDayBackup: Boolean
) {
if (bot.logger.isDebugEnabled) {
bot.logger.debug("Saving the feeds...")
}
if (bot.logger.isDebugEnabled) bot.logger.debug("Saving the feeds...")
if (bot.logsDir.isNotBlank() && bot.weblogUrl.isNotBlank()) {
try {
val output = SyndFeedOutput()
var rss: SyndFeed = SyndFeedImpl()
val items: MutableList<SyndEntry> = ArrayList(0)
val items: MutableList<SyndEntry> = mutableListOf()
var item: SyndEntry
OutputStreamWriter(
Files.newOutputStream(Paths.get(bot.logsDir + CURRENT_XML)), StandardCharsets.UTF_8
@ -194,9 +191,7 @@ class EntriesMgr private constructor() {
}
}
rss.entries = items
if (bot.logger.isDebugEnabled) {
bot.logger.debug("Writing the entries feed.")
}
if (bot.logger.isDebugEnabled) bot.logger.debug("Writing the entries feed.")
output.output(rss, fw)
}
OutputStreamWriter(
@ -238,9 +233,7 @@ class EntriesMgr private constructor() {
items.add(item)
}
rss.entries = items
if (bot.logger.isDebugEnabled) {
bot.logger.debug("Writing the backlog feed.")
}
if (bot.logger.isDebugEnabled) bot.logger.debug("Writing the backlog feed.")
output.output(rss, fw)
}
} else {
@ -248,12 +241,14 @@ class EntriesMgr private constructor() {
}
}
} catch (e: FeedException) {
bot.logger.warn("Unable to generate the entries feed.", e)
if (bot.logger.isWarnEnabled) bot.logger.warn("Unable to generate the entries feed.", e)
} catch (e: IOException) {
bot.logger.warn("Unable to generate the entries feed.", e)
if (bot.logger.isWarnEnabled) bot.logger.warn("Unable to generate the entries feed.", e)
}
} else {
bot.logger.warn("Unable to generate the entries feed. A required property is missing.")
if (bot.logger.isWarnEnabled) {
bot.logger.warn("Unable to generate the entries feed. A required property is missing.")
}
}
}
}

View file

@ -37,17 +37,16 @@ import net.thauvin.erik.mobibot.commands.links.LinksMgr
import org.apache.commons.lang3.StringUtils
import java.io.Serializable
import java.util.*
import java.util.concurrent.CopyOnWriteArrayList
/**
* The class used to store link entries.
*/
class EntryLink : Serializable {
// Link's comments
val comments: MutableList<EntryComment> = CopyOnWriteArrayList()
val comments: MutableList<EntryComment> = mutableListOf()
// Tags/categories
val tags: MutableList<SyndCategory> = CopyOnWriteArrayList()
val tags: MutableList<SyndCategory> = mutableListOf()
// Channel
var channel: String

View file

@ -33,8 +33,6 @@ package net.thauvin.erik.mobibot.modules
import net.thauvin.erik.mobibot.Mobibot
import net.thauvin.erik.mobibot.Utils
import java.util.*
import java.util.concurrent.ConcurrentHashMap
/**
* The `Module` abstract class.
@ -44,11 +42,11 @@ abstract class AbstractModule(val bot: Mobibot) {
* The module's commands, if any.
*/
@JvmField
val commands: MutableList<String> = ArrayList()
val commands: MutableList<String> = mutableListOf()
@JvmField
val help: MutableList<String> = ArrayList()
val properties: MutableMap<String, String> = ConcurrentHashMap()
val help: MutableList<String> = mutableListOf()
val properties: MutableMap<String, String> = mutableMapOf()
/**
* Responds to a command.

View file

@ -43,7 +43,6 @@ import org.jdom2.input.SAXBuilder
import java.io.IOException
import java.net.URL
import java.text.NumberFormat
import java.util.*
import javax.xml.XMLConstants
/**
@ -73,7 +72,7 @@ class CurrencyConverter(bot: Mobibot) : ThreadedModule(bot) {
try {
loadRates()
} catch (e: ModuleException) {
logger.warn(e.debugMessage, e)
if (bot.logger.isWarnEnabled)logger.warn(e.debugMessage, e)
}
}
@ -100,7 +99,7 @@ class CurrencyConverter(bot: Mobibot) : ThreadedModule(bot) {
try {
loadRates()
} catch (e: ModuleException) {
logger.debug(e.debugMessage, e)
if (logger.isDebugEnabled) logger.debug(e.debugMessage, e)
}
}
if (EXCHANGE_RATES.isEmpty()) {
@ -139,7 +138,7 @@ class CurrencyConverter(bot: Mobibot) : ThreadedModule(bot) {
private const val EMPTY_RATE_TABLE = "Sorry, but the exchange rate table is empty."
// Exchange rates
private val EXCHANGE_RATES: MutableMap<String, String> = TreeMap()
private val EXCHANGE_RATES: MutableMap<String, String> = mutableMapOf()
// Exchange rates table URL
private const val EXCHANGE_TABLE_URL = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"
@ -183,7 +182,7 @@ class CurrencyConverter(bot: Mobibot) : ThreadedModule(bot) {
@JvmStatic
fun currencyRates(): List<String> {
val rates = ArrayList<String>(33)
val rates = mutableListOf<String>()
for ((key, value) in EXCHANGE_RATES) {
rates.add(" $key: ${StringUtils.leftPad(value, 8)}")
}

View file

@ -41,7 +41,6 @@ import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import java.net.URL
import java.util.*
/**
* The GoogleSearch module.
@ -62,7 +61,7 @@ class GoogleSearch(bot: Mobibot) : ThreadedModule(bot) {
send(sender, msg)
}
} catch (e: ModuleException) {
logger.warn(e.debugMessage, e)
if (logger.isWarnEnabled) logger.warn(e.debugMessage, e)
send(sender, e.message, isPrivate)
}
} else {
@ -91,7 +90,7 @@ class GoogleSearch(bot: Mobibot) : ThreadedModule(bot) {
throw ModuleException("${StringUtils.capitalize(GOOGLE_CMD)} is disabled. The API keys are missing.")
}
return if (query.isNotBlank()) {
val results = ArrayList<Message>()
val results = mutableListOf<Message>()
try {
val url = URL(
"https://www.googleapis.com/customsearch/v1?key=$apiKey&cx=$cseKey" +

View file

@ -60,7 +60,7 @@ class Joke(bot: Mobibot) : ThreadedModule(bot) {
try {
bot.send(Utils.cyan(randomJoke().msg))
} catch (e: ModuleException) {
bot.logger.warn(e.debugMessage, e)
if (bot.logger.isWarnEnabled) bot.logger.warn(e.debugMessage, e)
bot.send(sender, e.message, isPrivate)
}
}

View file

@ -76,7 +76,9 @@ class Lookup(bot: Mobibot) : AbstractModule(bot) {
send("Unknown host.")
}
} catch (ioe: IOException) {
logger.debug("Unable to perform whois IP lookup: {}", args, ioe)
if (logger.isDebugEnabled) {
logger.debug("Unable to perform whois IP lookup: $args", ioe)
}
send("Unable to perform whois IP lookup: ${ioe.message}")
}
} else {

View file

@ -41,7 +41,6 @@ import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import java.net.URL
import java.util.*
/**
* The StockQuote module.
@ -59,7 +58,7 @@ class StockQuote(bot: Mobibot) : ThreadedModule(bot) {
send(sender, msg)
}
} catch (e: ModuleException) {
logger.warn(e.debugMessage, e)
if (logger.isWarnEnabled) logger.warn(e.debugMessage, e)
send(e.message)
}
} else {
@ -126,7 +125,7 @@ class StockQuote(bot: Mobibot) : ThreadedModule(bot) {
}
return if (symbol.isNotBlank()) {
val debugMessage = "getQuote($symbol)"
val messages = ArrayList<Message>()
val messages = mutableListOf<Message>()
var response: String
try {
with(messages) {

View file

@ -91,11 +91,9 @@ class Twitter(bot: Mobibot) : ThreadedModule(bot) {
Thread {
try {
post(message = msg, isDm = true)
if (logger.isDebugEnabled) {
logger.debug("Notified @{}: {}", handle, msg)
}
if (logger.isDebugEnabled) logger.debug("Notified @$handle: $msg")
} catch (e: ModuleException) {
logger.warn("Failed to notify @{}: {}", handle, msg, e)
if (logger.isWarnEnabled) logger.warn("Failed to notify @$handle: $msg", e)
}
}.start()
}
@ -133,7 +131,7 @@ class Twitter(bot: Mobibot) : ThreadedModule(bot) {
}
post(message = msg, isDm = false)
} catch (e: ModuleException) {
logger.warn("Failed to post entry on Twitter.", e)
if (bot.logger.isWarnEnabled) logger.warn("Failed to post entry on Twitter.", e)
}
}.start()
removeEntry(index)
@ -167,7 +165,7 @@ class Twitter(bot: Mobibot) : ThreadedModule(bot) {
isPrivate
)
} catch (e: ModuleException) {
logger.warn(e.debugMessage, e)
if (logger.isWarnEnabled) logger.warn(e.debugMessage, e)
send(sender, e.message, isPrivate)
}
}

View file

@ -42,7 +42,6 @@ import net.thauvin.erik.mobibot.msg.Message
import net.thauvin.erik.mobibot.msg.NoticeMessage
import net.thauvin.erik.mobibot.msg.PublicMessage
import org.jibble.pircbot.Colors
import java.util.*
import kotlin.math.roundToInt
/**
@ -64,7 +63,7 @@ class Weather2(bot: Mobibot) : ThreadedModule(bot) {
}
}
} catch (e: ModuleException) {
bot.logger.debug(e.debugMessage, e)
if (bot.logger.isDebugEnabled) bot.logger.debug(e.debugMessage, e)
bot.send(e.message)
}
} else {
@ -104,7 +103,7 @@ class Weather2(bot: Mobibot) : ThreadedModule(bot) {
throw ModuleException("${WEATHER_CMD.capitalize()} is disabled. The API key is missing.")
}
val owm = OWM(apiKey)
val messages = ArrayList<Message>()
val messages = mutableListOf<Message>()
owm.unit = OWM.Unit.IMPERIAL
if (query.isNotBlank()) {
val argv = query.split(",")

View file

@ -41,6 +41,7 @@ import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoField
import java.util.*
import kotlin.collections.ArrayList
/**
* The WorldTime module.
@ -94,7 +95,7 @@ class WorldTime(bot: Mobibot) : AbstractModule(bot) {
init {
// Initialize the countries map
val countries = TreeMap<String, String>()
val countries = mutableMapOf<String, String>()
countries["AE"] = "Asia/Dubai"
countries["AF"] = "Asia/Kabul"
countries["AQ"] = "Antarctica/South_Pole"