Code formmating, tabs to spaces, etc.

This commit is contained in:
Erik C. Thauvin 2016-07-16 18:15:14 -07:00
parent e90992a7f6
commit ad36c18124
29 changed files with 4375 additions and 5286 deletions

View file

@ -13,16 +13,14 @@ def packageName = 'net.thauvin.erik.mobibot'
def deployDir = 'deploy'
def isRelease = 'release' in gradle.startParameter.taskNames
def getVersion(isIncrement = false)
{
def getVersion(isIncrement = false) {
def propsFile = 'version.properties'
def majorKey = 'version.major'
def minorKey = 'version.minor'
def patchKey = 'version.patch'
def metaKey = 'version.buildmeta'
def preKey = 'version.prerelease'
if (isIncrement)
{
if (isIncrement) {
ant.propertyfile(file: propsFile) {
entry(key: patchKey,
type: 'int',

View file

@ -13,8 +13,8 @@ import java.util.Date;
* Annotation Processor</a>
*/
public final class ReleaseInfo {
private final static String buildmeta = "006";
private final static Date date = new Date(1468655027549L);
private final static String buildmeta = "008";
private final static Date date = new Date(1468718052505L);
private final static int major = 0;
private final static int minor = 7;
private final static int patch = 0;

View file

@ -38,8 +38,7 @@ package net.thauvin.erik.mobibot;
* @created 2014-04-26
* @since 1.0
*/
final class Commands
{
final class Commands {
/**
* The add (back)log command.
*/
@ -161,8 +160,7 @@ final class Commands
* @throws UnsupportedOperationException If the constructor is called.
*/
private Commands()
throws UnsupportedOperationException
{
throws UnsupportedOperationException {
throw new UnsupportedOperationException("Illegal constructor call.");
}
}

View file

@ -42,10 +42,8 @@ import javax.swing.*;
* @created Mar 5, 2005
* @since 1.0
*/
class DeliciousPoster
{
class DeliciousPoster {
private final Delicious delicious;
private final String ircServer;
/**
@ -55,8 +53,7 @@ class DeliciousPoster
* @param password The del.icio.us password.
* @param ircServer The IRC server.
*/
public DeliciousPoster(final String username, final String password, final String ircServer)
{
public DeliciousPoster(final String username, final String password, final String ircServer) {
delicious = new Delicious(username, password);
this.ircServer = ircServer;
}
@ -66,14 +63,11 @@ class DeliciousPoster
*
* @param entry The entry to add.
*/
public final void addPost(final EntryLink entry)
{
final SwingWorker<Boolean, Void> worker = new SwingWorker<Boolean, Void>()
{
public final void addPost(final EntryLink entry) {
final SwingWorker<Boolean, Void> worker = new SwingWorker<Boolean, Void>() {
@Override
protected Boolean doInBackground()
throws Exception
{
throws Exception {
return delicious.addPost(entry.getLink(),
entry.getTitle(),
postedBy(entry),
@ -85,56 +79,47 @@ class DeliciousPoster
worker.execute();
}
/**
* Deletes a post to del.icio.us.
*
* @param entry The entry to delete.
*/
public final void deletePost(final EntryLink entry) {
final String link = entry.getLink();
final SwingWorker<Boolean, Void> worker = new SwingWorker<Boolean, Void>() {
@Override
protected Boolean doInBackground()
throws Exception {
return delicious.deletePost(link);
}
};
worker.execute();
}
/**
* Returns he del.icio.us extended attribution line.
*
* @param entry The entry.
*
* @return The extended attribution line.
*/
private String postedBy(final EntryLink entry)
{
private String postedBy(final EntryLink entry) {
return "Posted by " + entry.getNick() + " on " + entry.getChannel() + " (" + ircServer + ')';
}
/**
* Deletes a post to del.icio.us.
*
* @param entry The entry to delete.
*/
public final void deletePost(final EntryLink entry)
{
final String link = entry.getLink();
final SwingWorker<Boolean, Void> worker = new SwingWorker<Boolean, Void>()
{
@Override
protected Boolean doInBackground()
throws Exception
{
return delicious.deletePost(link);
}
};
worker.execute();
}
/**
* Updates a post to del.icio.us.
*
* @param oldUrl The old post URL.
* @param entry The entry to add.
*/
public final void updatePost(final String oldUrl, final EntryLink entry)
{
final SwingWorker<Boolean, Void> worker = new SwingWorker<Boolean, Void>()
{
public final void updatePost(final String oldUrl, final EntryLink entry) {
final SwingWorker<Boolean, Void> worker = new SwingWorker<Boolean, Void>() {
@Override
protected Boolean doInBackground()
throws Exception
{
if (!oldUrl.equals(entry.getLink()))
{
throws Exception {
if (!oldUrl.equals(entry.getLink())) {
delicious.deletePost(oldUrl);
return delicious.addPost(entry.getLink(),
@ -142,9 +127,7 @@ class DeliciousPoster
postedBy(entry),
entry.getDeliciousTags(),
entry.getDate());
}
else
{
} else {
return delicious.addPost(entry.getLink(),
entry.getTitle(),
postedBy(entry),

View file

@ -48,8 +48,7 @@ import java.util.List;
* @created 2014-04-28
* @since 1.0
*/
final class EntriesMgr
{
final class EntriesMgr {
/**
* The name of the file containing the current entries.
*/
@ -76,8 +75,7 @@ final class EntriesMgr
* @throws UnsupportedOperationException If the constructor is called.
*/
private EntriesMgr()
throws UnsupportedOperationException
{
throws UnsupportedOperationException {
throw new UnsupportedOperationException("Illegal constructor call.");
}
@ -86,27 +84,23 @@ final class EntriesMgr
*
* @param file The file containing the backlogs.
* @param history The history list.
*
* @throws IOException If the file was not found or could not be read.
* @throws FeedException If an error occurred while reading the feed.
*/
public static void loadBacklogs(final String file, final List<String> history)
throws IOException, FeedException
{
throws IOException, FeedException {
history.clear();
final SyndFeedInput input = new SyndFeedInput();
try (final InputStreamReader reader = new InputStreamReader(new FileInputStream(new File(file))))
{
try (final InputStreamReader reader = new InputStreamReader(new FileInputStream(new File(file)))) {
final SyndFeed feed = input.build(reader);
final List items = feed.getEntries();
SyndEntry item;
for (int i = items.size() - 1; i >= 0; i--)
{
for (int i = items.size() - 1; i >= 0; i--) {
item = (SyndEntryImpl) items.get(i);
history.add(item.getTitle());
}
@ -119,24 +113,20 @@ final class EntriesMgr
* @param file The file containing the current entries.
* @param channel The channel
* @param entries The entries.
*
* @return The feed's last published date.
*
* @throws IOException If the file was not found or could not be read.
* @throws FeedException If an error occurred while reading the feed.
*/
@SuppressWarnings("unchecked")
public static String loadEntries(final String file, final String channel, final List<EntryLink> entries)
throws IOException, FeedException
{
throws IOException, FeedException {
entries.clear();
final SyndFeedInput input = new SyndFeedInput();
final String today;
try (InputStreamReader reader = new InputStreamReader(new FileInputStream(new File(file))))
{
try (InputStreamReader reader = new InputStreamReader(new FileInputStream(new File(file)))) {
final SyndFeed feed = input.build(reader);
today = Utils.ISO_SDF.format(feed.getPublishedDate());
@ -148,8 +138,7 @@ final class EntriesMgr
String author;
EntryLink entry;
for (int i = items.size() - 1; i >= 0; i--)
{
for (int i = items.size() - 1; i >= 0; i--) {
item = (SyndEntryImpl) items.get(i);
author = item.getAuthor()
.substring(item.getAuthor().lastIndexOf('(') + 1, item.getAuthor().length() - 1);
@ -163,12 +152,10 @@ final class EntriesMgr
comments = description.getValue().split("<br/>");
int split;
for (final String comment : comments)
{
for (final String comment : comments) {
split = comment.indexOf(": ");
if (split != -1)
{
if (split != -1) {
entry.addComment(comment.substring(split + 2).trim(), comment.substring(0, split).trim());
}
}
@ -189,19 +176,15 @@ final class EntriesMgr
* @param isDayBackup Set the true if the daily backup file should also be created.
*/
public static void saveEntries(final Mobibot bot, final List<EntryLink> entries, final List<String> history,
final boolean isDayBackup)
{
if (bot.getLogger().isDebugEnabled())
{
final boolean isDayBackup) {
if (bot.getLogger().isDebugEnabled()) {
bot.getLogger().debug("Saving the feeds...");
}
if (Utils.isValidString(bot.getLogsDir()) && Utils.isValidString(bot.getWeblogUrl()))
{
if (Utils.isValidString(bot.getLogsDir()) && Utils.isValidString(bot.getWeblogUrl())) {
FileWriter fw = null;
try
{
try {
fw = new FileWriter(new File(bot.getLogsDir() + CURRENT_XML));
SyndFeed rss = new SyndFeedImpl();
@ -219,26 +202,22 @@ final class EntriesMgr
SyndEntry item;
SyndContent description;
for (int i = (entries.size() - 1); i >= 0; --i)
{
for (int i = (entries.size() - 1); i >= 0; --i) {
entry = entries.get(i);
buff = new StringBuffer(
"Posted by <b>" + entry.getNick() + "</b> on <a href=\"irc://" + bot.getIrcServer() + '/'
+ entry.getChannel() + "\"><b>" + entry.getChannel() + "</b></a>");
if (entry.getCommentsCount() > 0)
{
if (entry.getCommentsCount() > 0) {
buff.append(" <br/><br/>");
final EntryComment[] comments = entry.getComments();
for (int j = 0; j < comments.length; j++)
{
for (int j = 0; j < comments.length; j++) {
comment = comments[j];
if (j > 0)
{
if (j > 0) {
buff.append(" <br/>");
}
@ -262,8 +241,7 @@ final class EntriesMgr
rss.setEntries(items);
if (bot.getLogger().isDebugEnabled())
{
if (bot.getLogger().isDebugEnabled()) {
bot.getLogger().debug("Writing the entries feed.");
}
@ -274,16 +252,12 @@ final class EntriesMgr
fw = new FileWriter(new File(bot.getLogsDir() + bot.getToday() + XML_EXT));
output.output(rss, fw);
if (isDayBackup)
{
if (Utils.isValidString(bot.getBacklogsUrl()))
{
if (history.indexOf(bot.getToday()) == -1)
{
if (isDayBackup) {
if (Utils.isValidString(bot.getBacklogsUrl())) {
if (history.indexOf(bot.getToday()) == -1) {
history.add(bot.getToday());
while (history.size() > MAX_BACKLOGS)
{
while (history.size() > MAX_BACKLOGS) {
history.remove(0);
}
}
@ -300,8 +274,7 @@ final class EntriesMgr
String date;
items.clear();
for (int i = (history.size() - 1); i >= 0; --i)
{
for (int i = (history.size() - 1); i >= 0; --i) {
date = history.get(i);
item = new SyndEntryImpl();
@ -316,40 +289,27 @@ final class EntriesMgr
rss.setEntries(items);
if (bot.getLogger().isDebugEnabled())
{
if (bot.getLogger().isDebugEnabled()) {
bot.getLogger().debug("Writing the backlog feed.");
}
output.output(rss, fw);
}
else
{
} else {
bot.getLogger().warn("Unable to generate the backlogs feed. No property configured.");
}
}
}
catch (Exception e)
{
} catch (Exception e) {
bot.getLogger().warn("Unable to generate the entries feed.", e);
}
finally
{
try
{
if (fw != null)
{
} finally {
try {
if (fw != null) {
fw.close();
}
}
catch (Exception ignore)
{
} catch (Exception ignore) {
; // Do nothing
}
}
}
else
{
} else {
bot.getLogger()
.warn("Unable to generate the entries feed. At least one of the required property is missing.");
}

View file

@ -42,8 +42,7 @@ import java.util.Date;
* @created Jan 31, 2004
* @since 1.0
*/
public class EntryComment implements Serializable
{
public class EntryComment implements Serializable {
/**
* The serial version UID.
*/
@ -55,7 +54,6 @@ public class EntryComment implements Serializable
private final Date date = Calendar.getInstance().getTime();
private String comment = "";
private String nick = "";
/**
@ -64,8 +62,7 @@ public class EntryComment implements Serializable
* @param comment The new comment.
* @param nick The nickname of the comment's author.
*/
public EntryComment(final String comment, final String nick)
{
public EntryComment(final String comment, final String nick) {
this.comment = comment;
this.nick = nick;
}
@ -74,8 +71,7 @@ public class EntryComment implements Serializable
* Creates a new comment.
*/
@SuppressWarnings("UnusedDeclaration")
protected EntryComment()
{
protected EntryComment() {
; // Required for serialization.
}
@ -84,8 +80,7 @@ public class EntryComment implements Serializable
*
* @return The comment.
*/
public final String getComment()
{
public final String getComment() {
return comment;
}
@ -95,8 +90,7 @@ public class EntryComment implements Serializable
* @param comment The actual comment.
*/
@SuppressWarnings("UnusedDeclaration")
public final void setComment(final String comment)
{
public final void setComment(final String comment) {
this.comment = comment;
}
@ -106,8 +100,7 @@ public class EntryComment implements Serializable
* @return The date.
*/
@SuppressWarnings("UnusedDeclaration")
public final Date getDate()
{
public final Date getDate() {
return date;
}
@ -116,8 +109,7 @@ public class EntryComment implements Serializable
*
* @return The nickname.
*/
public final String getNick()
{
public final String getNick() {
return nick;
}
@ -126,8 +118,7 @@ public class EntryComment implements Serializable
*
* @param nick The new nickname.
*/
public final void setNick(final String nick)
{
public final void setNick(final String nick) {
this.nick = nick;
}
}

View file

@ -47,8 +47,7 @@ import java.util.concurrent.CopyOnWriteArrayList;
* @created Jan 31, 2004
* @since 1.0
*/
public class EntryLink implements Serializable
{
public class EntryLink implements Serializable {
/**
* The serial version UID.
*/
@ -89,8 +88,7 @@ public class EntryLink implements Serializable
* @param tags The entry's tags/categories.
*/
public EntryLink(final String link, final String title, final String nick, final String login, final String channel,
final String tags)
{
final String tags) {
this.link = link;
this.title = title;
this.nick = nick;
@ -100,61 +98,6 @@ public class EntryLink implements Serializable
setTags(tags);
}
/**
* Sets the tags.
*
* @param tags The space-delimited tags.
*/
public final void setTags(final String tags)
{
if (tags != null)
{
final String[] parts = tags.replaceAll(", ", " ").replaceAll(",", " ").split(" ");
SyndCategoryImpl tag;
String part;
char mod;
for (final String rawPart : parts)
{
part = rawPart.trim();
if (part.length() >= 2)
{
tag = new SyndCategoryImpl();
tag.setName(part.substring(1).toLowerCase());
mod = part.charAt(0);
if (mod == '-')
{
// Don't remove the channel tag, if any.
if (!tag.getName().equals(channel.substring(1)))
{
this.tags.remove(tag);
}
}
else if (mod == '+')
{
if (!this.tags.contains(tag))
{
this.tags.add(tag);
}
}
else
{
tag.setName(part.trim().toLowerCase());
if (!this.tags.contains(tag))
{
this.tags.add(tag);
}
}
}
}
}
}
/**
* Creates a new entry.
*
@ -166,8 +109,7 @@ public class EntryLink implements Serializable
* @param tags The entry's tags/categories.
*/
public EntryLink(final String link, final String title, final String nick, final String channel, final Date date,
final List<SyndCategory> tags)
{
final List<SyndCategory> tags) {
this.link = link;
this.title = title;
this.nick = nick;
@ -182,11 +124,9 @@ public class EntryLink implements Serializable
*
* @param comment The actual comment.
* @param nick The nickname of the author of the comment.
*
* @return The total number of comments for this entry.
*/
public final int addComment(final String comment, final String nick)
{
public final int addComment(final String comment, final String nick) {
comments.add(new EntryComment(comment, nick));
return (comments.size() - 1);
@ -197,10 +137,8 @@ public class EntryLink implements Serializable
*
* @param index The index of the comment to delete.
*/
public final void deleteComment(final int index)
{
if (index < comments.size())
{
public final void deleteComment(final int index) {
if (index < comments.size()) {
comments.remove(index);
}
}
@ -210,8 +148,7 @@ public class EntryLink implements Serializable
*
* @return The channel
*/
public final String getChannel()
{
public final String getChannel() {
return channel;
}
@ -221,8 +158,7 @@ public class EntryLink implements Serializable
* @param channel The channel.
*/
@SuppressWarnings("UnusedDeclaration")
public final void setChannel(final String channel)
{
public final void setChannel(final String channel) {
this.channel = channel;
}
@ -230,11 +166,9 @@ public class EntryLink implements Serializable
* Returns a comment.
*
* @param index The comment's index.
*
* @return The specific comment.
*/
public final EntryComment getComment(final int index)
{
public final EntryComment getComment(final int index) {
return (comments.get(index));
}
@ -243,8 +177,7 @@ public class EntryLink implements Serializable
*
* @return The comments.
*/
public final EntryComment[] getComments()
{
public final EntryComment[] getComments() {
return (comments.toArray(new EntryComment[comments.size()]));
}
@ -253,8 +186,7 @@ public class EntryLink implements Serializable
*
* @return The count of comments.
*/
public final int getCommentsCount()
{
public final int getCommentsCount() {
return comments.size();
}
@ -263,8 +195,7 @@ public class EntryLink implements Serializable
*
* @return The date.
*/
public final Date getDate()
{
public final Date getDate() {
return date;
}
@ -273,12 +204,10 @@ public class EntryLink implements Serializable
*
* @return The tags as a comma-delimited string.
*/
public final String getDeliciousTags()
{
public final String getDeliciousTags() {
final StringBuilder tags = new StringBuilder(nick);
for (final Object tag : this.tags)
{
for (final Object tag : this.tags) {
tags.append(',');
tags.append(((SyndCategoryImpl) tag).getName());
}
@ -291,8 +220,7 @@ public class EntryLink implements Serializable
*
* @return The link.
*/
public final String getLink()
{
public final String getLink() {
return link;
}
@ -301,8 +229,7 @@ public class EntryLink implements Serializable
*
* @param link The new link.
*/
public final void setLink(final String link)
{
public final void setLink(final String link) {
this.link = link;
}
@ -311,8 +238,7 @@ public class EntryLink implements Serializable
*
* @return The login;
*/
public final String getLogin()
{
public final String getLogin() {
return login;
}
@ -322,8 +248,7 @@ public class EntryLink implements Serializable
* @param login The new login.
*/
@SuppressWarnings("UnusedDeclaration")
public final void setLogin(final String login)
{
public final void setLogin(final String login) {
this.login = login;
}
@ -332,8 +257,7 @@ public class EntryLink implements Serializable
*
* @return The nickname.
*/
public final String getNick()
{
public final String getNick() {
return nick;
}
@ -342,8 +266,7 @@ public class EntryLink implements Serializable
*
* @param nick The new nickname.
*/
public final void setNick(final String nick)
{
public final void setNick(final String nick) {
this.nick = nick;
}
@ -352,8 +275,7 @@ public class EntryLink implements Serializable
*
* @return The tags.
*/
public final List<SyndCategory> getTags()
{
public final List<SyndCategory> getTags() {
return tags;
}
@ -362,8 +284,7 @@ public class EntryLink implements Serializable
*
* @param tags The tags.
*/
private void setTags(final List<SyndCategory> tags)
{
private void setTags(final List<SyndCategory> tags) {
this.tags.addAll(tags);
}
@ -372,8 +293,7 @@ public class EntryLink implements Serializable
*
* @return The title.
*/
public final String getTitle()
{
public final String getTitle() {
return title;
}
@ -382,8 +302,7 @@ public class EntryLink implements Serializable
*
* @param title The new title.
*/
public final void setTitle(final String title)
{
public final void setTitle(final String title) {
this.title = title;
}
@ -392,8 +311,7 @@ public class EntryLink implements Serializable
*
* @return true if there are comments, false otherwise.
*/
public final boolean hasComments()
{
public final boolean hasComments() {
return (!comments.isEmpty());
}
@ -402,8 +320,7 @@ public class EntryLink implements Serializable
*
* @return true if there are tags, false otherwise.
*/
public final boolean hasTags()
{
public final boolean hasTags() {
return (!tags.isEmpty());
}
@ -414,21 +331,61 @@ public class EntryLink implements Serializable
* @param comment The actual comment.
* @param nick The nickname of the author of the comment.
*/
public final void setComment(final int index, final String comment, final String nick)
{
if (index < comments.size())
{
public final void setComment(final int index, final String comment, final String nick) {
if (index < comments.size()) {
comments.set(index, new EntryComment(comment, nick));
}
}
/**
* Sets the tags.
*
* @param tags The space-delimited tags.
*/
public final void setTags(final String tags) {
if (tags != null) {
final String[] parts = tags.replaceAll(", ", " ").replaceAll(",", " ").split(" ");
SyndCategoryImpl tag;
String part;
char mod;
for (final String rawPart : parts) {
part = rawPart.trim();
if (part.length() >= 2) {
tag = new SyndCategoryImpl();
tag.setName(part.substring(1).toLowerCase());
mod = part.charAt(0);
if (mod == '-') {
// Don't remove the channel tag, if any.
if (!tag.getName().equals(channel.substring(1))) {
this.tags.remove(tag);
}
} else if (mod == '+') {
if (!this.tags.contains(tag)) {
this.tags.add(tag);
}
} else {
tag.setName(part.trim().toLowerCase());
if (!this.tags.contains(tag)) {
this.tags.add(tag);
}
}
}
}
}
}
/**
* Returns a string representation of the object.
*
* @return A string representation of the object.
*/
public final String toString()
{
public final String toString() {
return super.toString() + "[ channel -> '" + channel + '\'' + ", comments -> " + comments + ", date -> " + date
+ ", link -> '" + link + '\'' + ", login -> '" + login + '\'' + ", nick -> '" + nick + '\''

View file

@ -48,8 +48,7 @@ import java.util.List;
* @created Feb 1, 2004
* @since 1.0
*/
class FeedReader implements Runnable
{
class FeedReader implements Runnable {
/**
* The maximum number of feed items to display.
*/
@ -82,8 +81,7 @@ class FeedReader implements Runnable
* @param sender The nick of the person who sent the message.
* @param url The URL to fetch.
*/
public FeedReader(final Mobibot bot, final String sender, final String url)
{
public FeedReader(final Mobibot bot, final String sender, final String url) {
this.bot = bot;
this.sender = sender;
this.url = url;
@ -92,30 +90,23 @@ class FeedReader implements Runnable
/**
* Fetches the Feed's items.
*/
public final void run()
{
try
{
public final void run() {
try {
final SyndFeedInput input = new SyndFeedInput();
final SyndFeed feed = input.build(new XmlReader(new URL(url)));
SyndEntry item;
final List items = feed.getEntries();
for (int i = 0; (i < items.size()) && (i < MAX_ITEMS); i++)
{
for (int i = 0; (i < items.size()) && (i < MAX_ITEMS); i++) {
item = (SyndEntryImpl) items.get(i);
bot.send(sender, item.getTitle());
bot.send(sender, TAB_INDENT + Utils.green(item.getLink()));
}
}
catch (MalformedURLException e)
{
} catch (MalformedURLException e) {
bot.getLogger().debug("Invalid feed URL.", e);
bot.send(sender, "The feed URL is invalid.");
}
catch (Exception e)
{
} catch (Exception e) {
bot.getLogger().debug("Unable to fetch the feed.", e);
bot.send(sender, "An error has occurred while fetching the feed: " + e.getMessage());
}

File diff suppressed because it is too large Load diff

View file

@ -41,8 +41,7 @@ import java.util.concurrent.CopyOnWriteArrayList;
* @created 2016-07-02
* @since 1.0
*/
public class Tell
{
public class Tell {
/**
* The all keyword.
*/
@ -61,7 +60,6 @@ public class Tell
/**
* The default maximum number of days to keep messages.
*/
private static final int DEFAULT_TELL_MAX_DAYS = 7;
/**
@ -99,8 +97,7 @@ public class Tell
*/
private final String serializedObject;
public Tell(final Mobibot bot, final String maxDays, final String maxSize)
{
public Tell(final Mobibot bot, final String maxDays, final String maxSize) {
this.bot = bot;
this.maxDays = Utils.getIntProperty(maxDays, DEFAULT_TELL_MAX_DAYS);
this.maxSize = Utils.getIntProperty(maxSize, DEFAULT_TELL_MAX_SIZE);
@ -109,8 +106,7 @@ public class Tell
serializedObject = bot.getLogsDir() + bot.getName() + SER_EXT;
messages.addAll(TellMessagesMgr.load(serializedObject, bot.getLogger()));
if (clean())
{
if (clean()) {
save();
}
}
@ -120,217 +116,20 @@ public class Tell
*
* @return <code>True</code> if the queue was cleaned.
*/
private boolean clean()
{
if (bot.getLogger().isDebugEnabled())
{
private boolean clean() {
if (bot.getLogger().isDebugEnabled()) {
bot.getLogger().debug("Cleaning the messages.");
}
return TellMessagesMgr.clean(messages, maxDays);
}
/**
* Saves the messages queue.
*/
private void save()
{
TellMessagesMgr.save(serializedObject, messages, bot.getLogger());
}
/**
* Processes the commands.
*
* @param sender The sender's nick.
* @param cmds The commands string.
*/
public void response(final String sender, final String cmds)
{
if (!Utils.isValidString(cmds))
{
helpResponse(sender);
}
else if (cmds.startsWith(Commands.VIEW_CMD))
{
if (bot.isOp(sender) && cmds.equals(Commands.VIEW_CMD + ' ' + TELL_ALL_KEYWORD))
{
if (messages.size() > 0)
{
for (final TellMessage message : messages)
{
bot.send(sender,
Utils.bold(message.getSender()) + " --> " + Utils.bold(message.getRecipient())
+ " [ID: " + message.getId() + ", " + (message.isReceived() ? "DELIVERED" : "QUEUED")
+ ']',
true);
}
}
else
{
bot.send(sender, "There are no messages in the queue.", true);
}
}
else
{
boolean hasMessage = false;
for (final TellMessage message : messages)
{
if (message.isMatch(sender))
{
if (!hasMessage)
{
hasMessage = true;
bot.send(sender, "Here are your messages: ", true);
}
if (message.isReceived())
{
bot.send(sender,
Utils.bold(message.getSender()) + " --> " + Utils.bold(message.getRecipient())
+ " [" + Utils.UTC_SDF.format(message.getReceived()) + ", ID: " + message.getId()
+ ", DELIVERED]",
true);
}
else
{
bot.send(sender,
Utils.bold(message.getSender()) + " --> " + Utils.bold(message.getRecipient())
+ " [" + Utils.UTC_SDF.format(message.getQueued()) + ", ID: " + message.getId()
+ ", QUEUED]",
true);
}
bot.send(sender, bot.helpIndent(message.getMessage(), false), true);
}
}
if (!hasMessage)
{
bot.send(sender, "You have no messages in the queue.", true);
}
else
{
bot.send(sender, "To delete one or all delivered messages:");
bot.send(sender,
bot.helpIndent(bot.getNick() + ": " + TELL_CMD + ' ' + TELL_DEL_KEYWORD + " <id|"
+ TELL_ALL_KEYWORD + '>'));
bot.send(sender,
"Messages are kept for " + Utils.bold(maxDays) + Utils.plural(maxDays, " day.", " days."));
}
}
}
else if (cmds.startsWith(TELL_DEL_KEYWORD + ' '))
{
final String[] split = cmds.split(" ");
if (split.length == 2)
{
final String id = split[1];
boolean deleted = false;
if (id.equalsIgnoreCase(TELL_ALL_KEYWORD))
{
for (final TellMessage message : messages)
{
if (message.getSender().equalsIgnoreCase(sender) && message.isReceived())
{
messages.remove(message);
deleted = true;
}
}
if (deleted)
{
save();
bot.send(sender, "Delivered messages have been deleted.", true);
}
else
{
bot.send(sender, "No delivered messages were found.", true);
}
}
else
{
boolean found = false;
for (final TellMessage message : messages)
{
found = message.isMatchId(id);
if (found && (message.getSender().equalsIgnoreCase(sender) || bot.isOp(sender)))
{
messages.remove(message);
save();
bot.send(sender, "Your message was deleted from the queue.", true);
deleted = true;
break;
}
}
if (!deleted)
{
if (found)
{
bot.send(sender, "Only messages that you sent can be deleted.", true);
}
else
{
bot.send(sender, "The specified message [ID " + id + "] could not be found.", true);
}
}
}
}
else
{
helpResponse(sender);
}
}
else
{
final String[] split = cmds.split(" ", 2);
if (split.length == 2 && (Utils.isValidString(split[1]) && split[1].contains(" ")))
{
if (messages.size() < maxSize)
{
final TellMessage message = new TellMessage(sender, split[0], split[1].trim());
messages.add(message);
save();
bot.send(sender,
"Message [ID " + message.getId() + "] was queued for " + Utils
.bold(message.getRecipient()), true);
}
else
{
bot.send(sender, "Sorry, the messages queue is currently full.", true);
}
}
else
{
helpResponse(sender);
}
}
if (clean())
{
save();
}
}
/**
* Responds with help.
*
* @param sender The sender.
*/
public void helpResponse(final String sender)
{
public void helpResponse(final String sender) {
bot.send(sender, "To send a message to someone when they join the channel:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + TELL_CMD + " <nick> <message>"));
@ -341,13 +140,153 @@ public class Tell
}
/**
* Checks and sends messages.
* Returns <code>true</code> if enabled.
*
* @param nickname The user's nickname.
* @return <code>true</code> or <code>false</code>
*/
public void send(final String nickname)
{
send(nickname, false);
public boolean isEnabled() {
return maxSize > 0 && maxDays > 0;
}
/**
* Processes the commands.
*
* @param sender The sender's nick.
* @param cmds The commands string.
*/
public void response(final String sender, final String cmds) {
if (!Utils.isValidString(cmds)) {
helpResponse(sender);
} else if (cmds.startsWith(Commands.VIEW_CMD)) {
if (bot.isOp(sender) && cmds.equals(Commands.VIEW_CMD + ' ' + TELL_ALL_KEYWORD)) {
if (messages.size() > 0) {
for (final TellMessage message : messages) {
bot.send(sender, Utils.bold(message.getSender()) + " --> " + Utils.bold(message.getRecipient())
+ " [ID: " + message.getId() + ", "
+ (message.isReceived() ? "DELIVERED" : "QUEUED") + ']',
true);
}
} else {
bot.send(sender, "There are no messages in the queue.", true);
}
} else {
boolean hasMessage = false;
for (final TellMessage message : messages) {
if (message.isMatch(sender)) {
if (!hasMessage) {
hasMessage = true;
bot.send(sender, "Here are your messages: ", true);
}
if (message.isReceived()) {
bot.send(sender,
Utils.bold(message.getSender()) + " --> " + Utils.bold(message.getRecipient())
+ " [" + Utils.UTC_SDF.format(message.getReceived()) + ", ID: "
+ message.getId() + ", DELIVERED]",
true);
} else {
bot.send(sender,
Utils.bold(message.getSender()) + " --> " + Utils.bold(message.getRecipient())
+ " [" + Utils.UTC_SDF.format(message.getQueued()) + ", ID: "
+ message.getId() + ", QUEUED]",
true);
}
bot.send(sender, bot.helpIndent(message.getMessage(), false), true);
}
}
if (!hasMessage) {
bot.send(sender, "You have no messages in the queue.", true);
} else {
bot.send(sender, "To delete one or all delivered messages:");
bot.send(sender,
bot.helpIndent(bot.getNick() + ": " + TELL_CMD + ' ' + TELL_DEL_KEYWORD + " <id|"
+ TELL_ALL_KEYWORD + '>'));
bot.send(sender, "Messages are kept for " + Utils.bold(maxDays)
+ Utils.plural(maxDays, " day.", " days."));
}
}
} else if (cmds.startsWith(TELL_DEL_KEYWORD + ' ')) {
final String[] split = cmds.split(" ");
if (split.length == 2) {
final String id = split[1];
boolean deleted = false;
if (id.equalsIgnoreCase(TELL_ALL_KEYWORD)) {
for (final TellMessage message : messages) {
if (message.getSender().equalsIgnoreCase(sender) && message.isReceived()) {
messages.remove(message);
deleted = true;
}
}
if (deleted) {
save();
bot.send(sender, "Delivered messages have been deleted.", true);
} else {
bot.send(sender, "No delivered messages were found.", true);
}
} else {
boolean found = false;
for (final TellMessage message : messages) {
found = message.isMatchId(id);
if (found && (message.getSender().equalsIgnoreCase(sender) || bot.isOp(sender))) {
messages.remove(message);
save();
bot.send(sender, "Your message was deleted from the queue.", true);
deleted = true;
break;
}
}
if (!deleted) {
if (found) {
bot.send(sender, "Only messages that you sent can be deleted.", true);
} else {
bot.send(sender, "The specified message [ID " + id + "] could not be found.", true);
}
}
}
} else {
helpResponse(sender);
}
} else {
final String[] split = cmds.split(" ", 2);
if (split.length == 2 && (Utils.isValidString(split[1]) && split[1].contains(" "))) {
if (messages.size() < maxSize) {
final TellMessage message = new TellMessage(sender, split[0], split[1].trim());
messages.add(message);
save();
bot.send(sender, "Message [ID " + message.getId() + "] was queued for "
+ Utils.bold(message.getRecipient()), true);
} else {
bot.send(sender, "Sorry, the messages queue is currently full.", true);
}
} else {
helpResponse(sender);
}
}
if (clean()) save();
}
/**
* Saves the messages queue.
*/
private void save() {
TellMessagesMgr.save(serializedObject, messages, bot.getLogger());
}
/**
@ -356,20 +295,15 @@ public class Tell
* @param nickname The user's nickname.
* @param isMessage The message flag.
*/
public void send(final String nickname, final boolean isMessage)
{
if (!nickname.equals(bot.getNick()) && isEnabled())
{
messages.stream().filter(message -> message.isMatch(nickname)).forEach(message -> {
if (message.getRecipient().equalsIgnoreCase(nickname) && !message.isReceived())
{
if (message.getSender().equals(nickname))
{
if (!isMessage)
{
bot.send(nickname,
Utils.bold("You") + " wanted me to remind you: " + Utils
.reverseColor(message.getMessage()),
public void send(final String nickname, final boolean isMessage) {
if (!nickname.equals(bot.getNick()) && isEnabled()) {
messages.stream().filter(message -> message.isMatch(nickname)).forEach(
message -> {
if (message.getRecipient().equalsIgnoreCase(nickname) && !message.isReceived()) {
if (message.getSender().equals(nickname)) {
if (!isMessage) {
bot.send(nickname, Utils.bold("You") + " wanted me to remind you: "
+ Utils.reverseColor(message.getMessage()),
true);
message.setIsReceived();
@ -377,26 +311,22 @@ public class Tell
save();
}
}
else
{
bot.send(nickname,
message.getSender() + " wanted me to tell you: " + Utils
.reverseColor(message.getMessage()),
} else {
bot.send(nickname, message.getSender() + " wanted me to tell you: "
+ Utils.reverseColor(message.getMessage()),
true);
message.setIsReceived();
save();
}
}
else if (message.getSender().equalsIgnoreCase(nickname) && message.isReceived() && !message
.isNotified())
{
} else if (message.getSender().equalsIgnoreCase(nickname) && message.isReceived()
&& !message.isNotified()) {
bot.send(nickname,
"Your message " + Utils.reverseColor("[ID " + message.getId() + ']') + " was sent to "
+ Utils.bold(message.getRecipient()) + " on " + Utils.UTC_SDF
.format(message.getReceived()),
"Your message "
+ Utils.reverseColor("[ID " + message.getId() + ']') + " was sent to "
+ Utils.bold(message.getRecipient()) + " on "
+ Utils.UTC_SDF.format(message.getReceived()),
true);
message.setIsNotified();
@ -408,13 +338,12 @@ public class Tell
}
/**
* Returns <code>true</code> if enabled.
* Checks and sends messages.
*
* @return <code>true</code> or <code>false</code>
* @param nickname The user's nickname.
*/
public boolean isEnabled()
{
return maxSize > 0 && maxDays > 0;
public void send(final String nickname) {
send(nickname, false);
}
/**
@ -422,8 +351,7 @@ public class Tell
*
* @return The size.
*/
public int size()
{
public int size() {
return messages.size();
}
}

View file

@ -42,24 +42,15 @@ import java.util.Date;
* @created 2014-04-24
* @since 1.0
*/
public class TellMessage implements Serializable
{
public class TellMessage implements Serializable {
private static final long serialVersionUID = 1L;
private final String id;
private final String message;
final private Date queued;
private final String recipient;
private final String sender;
private boolean isNotified;
private boolean isReceived;
private Date received;
/**
@ -69,8 +60,7 @@ public class TellMessage implements Serializable
* @param recipient The recipient's nick.
* @param message The message.
*/
public TellMessage(final String sender, final String recipient, final String message)
{
public TellMessage(final String sender, final String recipient, final String message) {
this.sender = sender;
this.recipient = recipient;
this.message = message;
@ -85,8 +75,7 @@ public class TellMessage implements Serializable
*
* @return The message id.
*/
public String getId()
{
public String getId() {
return id;
}
@ -95,8 +84,7 @@ public class TellMessage implements Serializable
*
* @return The text of the message.
*/
public String getMessage()
{
public String getMessage() {
return message;
}
@ -105,8 +93,7 @@ public class TellMessage implements Serializable
*
* @return <code>true</code> if the message is queued.
*/
public Date getQueued()
{
public Date getQueued() {
return queued;
}
@ -115,8 +102,7 @@ public class TellMessage implements Serializable
*
* @return <code>true</code> if the message has been received.
*/
public Date getReceived()
{
public Date getReceived() {
return received;
}
@ -125,8 +111,7 @@ public class TellMessage implements Serializable
*
* @return The recipient of the message.
*/
public String getRecipient()
{
public String getRecipient() {
return recipient;
}
@ -135,8 +120,7 @@ public class TellMessage implements Serializable
*
* @return The sender of the message.
*/
public String getSender()
{
public String getSender() {
return sender;
}
@ -144,11 +128,9 @@ public class TellMessage implements Serializable
* Matches the message sender or recipient.
*
* @param nick The nickname to match with.
*
* @return <code>true</code> if the nickname matches.
*/
public boolean isMatch(final String nick)
{
public boolean isMatch(final String nick) {
return (sender.equalsIgnoreCase(nick) || recipient.equalsIgnoreCase(nick));
}
@ -156,11 +138,9 @@ public class TellMessage implements Serializable
* Match the message ID.
*
* @param id The ID to match with.
*
* @return <code>true</code> if the id matches.
*/
public boolean isMatchId(final String id)
{
public boolean isMatchId(final String id) {
return this.id.equals(id);
}
@ -169,8 +149,7 @@ public class TellMessage implements Serializable
*
* @return <code>true</code> if the sender has been notified.
*/
public boolean isNotified()
{
public boolean isNotified() {
return isNotified;
}
@ -179,24 +158,21 @@ public class TellMessage implements Serializable
*
* @return <code>true</code> if the message was received.
*/
public boolean isReceived()
{
public boolean isReceived() {
return isReceived;
}
/**
* Sets the notified flag.
*/
public void setIsNotified()
{
public void setIsNotified() {
isNotified = true;
}
/**
* Sets the received flag.
*/
public void setIsReceived()
{
public void setIsReceived() {
received = Calendar.getInstance().getTime();
isReceived = true;
}

View file

@ -46,16 +46,14 @@ import java.util.List;
* @created 2014-04-26
* @since 1.0
*/
final class TellMessagesMgr
{
final class TellMessagesMgr {
/**
* Disables the default constructor.
*
* @throws UnsupportedOperationException If the constructor is called.
*/
private TellMessagesMgr()
throws UnsupportedOperationException
{
throws UnsupportedOperationException {
throw new UnsupportedOperationException("Illegal constructor call.");
}
@ -64,22 +62,18 @@ final class TellMessagesMgr
*
* @param tellMessages The messages list.
* @param tellMaxDays The maximum number of days to keep messages for.
*
* @return <code>True</code> if the queue was cleaned.
*/
public static boolean clean(final List<TellMessage> tellMessages, final int tellMaxDays)
{
public static boolean clean(final List<TellMessage> tellMessages, final int tellMaxDays) {
final Calendar maxDate = Calendar.getInstance();
final Date today = new Date();
boolean cleaned = false;
for (final TellMessage message : tellMessages)
{
for (final TellMessage message : tellMessages) {
maxDate.setTime(message.getQueued());
maxDate.add(Calendar.DATE, tellMaxDays);
if (maxDate.getTime().before(today))
{
if (maxDate.getTime().before(today)) {
tellMessages.remove(message);
cleaned = true;
}
@ -93,35 +87,24 @@ final class TellMessagesMgr
*
* @param file The serialized objects file.
* @param logger The logger.
*
* @return The {@link net.thauvin.erik.mobibot.TellMessage} array.
*/
@SuppressWarnings("unchecked")
public static List<TellMessage> load(final String file, final Log4JLogger logger)
{
try
{
public static List<TellMessage> load(final String file, final Log4JLogger logger) {
try {
try (ObjectInput input = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file))))
{
if (logger.isDebugEnabled())
{
try (ObjectInput input = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)))) {
if (logger.isDebugEnabled()) {
logger.debug("Loading the messages.");
}
return ((List<TellMessage>) input.readObject());
}
}
catch (FileNotFoundException ignore)
{
} catch (FileNotFoundException ignore) {
; // Do nothing.
}
catch (IOException e)
{
} catch (IOException e) {
logger.error("An IO error occurred loading the messages queue.", e);
}
catch (Exception e)
{
} catch (Exception e) {
logger.getLogger().error("An error occurred loading the messages queue.", e);
}
@ -135,23 +118,17 @@ final class TellMessagesMgr
* @param messages The {@link net.thauvin.erik.mobibot.TellMessage} array.
* @param logger The logger.
*/
public static void save(final String file, final List<TellMessage> messages, final Log4JLogger logger)
{
try
{
public static void save(final String file, final List<TellMessage> messages, final Log4JLogger logger) {
try {
try (ObjectOutput output = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file))))
{
if (logger.isDebugEnabled())
{
try (ObjectOutput output = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)))) {
if (logger.isDebugEnabled()) {
logger.debug("Saving the messages.");
}
output.writeObject(messages);
}
}
catch (IOException e)
{
} catch (IOException e) {
logger.error("Unable to save messages queue.", e);
}
}

View file

@ -9,65 +9,58 @@ import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* The <code>TwitterOAuth</code> class. <p> Go to <a href="http://twitter.com/oauth_clients/new">http://twitter.com/oauth_clients/new</a>
* to register your bot. </p> Then execute: <p> <code>java -cp "mobibot.jar:lib/*"
* net.thauvin.erik.mobibot.TwitterOAuth
* &lt;consumerKey&gt; &lt;consumerSecret&gt;</code> </p> and follow the prompts/instructions.
* The <code>TwitterOAuth</code> class.
* <p>
* Go to <a href="http://twitter.com/oauth_clients/new">http://twitter.com/oauth_clients/new</a> to register your bot.
* </p>
* Then execute:
* <p>
* <code>
* java -cp "mobibot.jar:lib/*"net.thauvin.erik.mobibot.TwitterOAuth &lt;consumerKey&gt; &lt;consumerSecret&gt;
* </code>
* </p>
* and follow the prompts/instructions.
*
* @author <a href="mailto:erik@thauvin.net">Erik C. Thauvin</a>
* @author <a href="http://twitter4j.org/en/code-examples.html#oauth">http://twitter4j.org/en/code-examples.html#oauth</a>
* @created Sep 13, 2010
* @since 1.0
*/
public final class TwitterOAuth
{
public final class TwitterOAuth {
public static void main(final String[] args)
throws Exception
{
if (args.length == 2)
{
throws Exception {
if (args.length == 2) {
final twitter4j.Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(args[0], args[1]);
final RequestToken requestToken = twitter.getOAuthRequestToken();
AccessToken accessToken = null;
final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (null == accessToken)
{
while (null == accessToken) {
System.out.println("Open the following URL and grant access to your account:");
System.out.println(requestToken.getAuthorizationURL());
System.out.print("Enter the PIN (if available) or just hit enter.[PIN]:");
final String pin = br.readLine();
try
{
if (pin.length() > 0)
{
try {
if (pin.length() > 0) {
accessToken = twitter.getOAuthAccessToken(requestToken, pin);
}
else
{
} else {
accessToken = twitter.getOAuthAccessToken();
}
System.out.println(
"Please add the following to the bot's property file:" + "\n\n" + "twitter-consumerKey="
+ args[0] + '\n' + "twitter-consumerSecret=" + args[1] + '\n' + "twitter-token="
+ accessToken.getToken() + '\n' + "twitter-tokenSecret=" + accessToken.getTokenSecret());
}
catch (TwitterException te)
{
if (401 == te.getStatusCode())
{
+ accessToken.getToken() + '\n' + "twitter-tokenSecret=" + accessToken
.getTokenSecret());
} catch (TwitterException te) {
if (401 == te.getStatusCode()) {
System.out.println("Unable to get the access token.");
}
else
{
} else {
te.printStackTrace();
}
}
}
}
else
{
} else {
System.out.println("Usage: " + TwitterOAuth.class.getName() + " <consumerKey> <consumerSecret>");
}

View file

@ -44,18 +44,15 @@ import java.util.Calendar;
* @created 2014-04-26
* @since 1.0
*/
final public class Utils
{
final public class Utils {
/**
* The ISO (YYYY-MM-DD) simple date format.
*/
public static final SimpleDateFormat ISO_SDF = new SimpleDateFormat("yyyy-MM-dd");
/**
* The timestamp simple date format.
*/
public static final SimpleDateFormat TIMESTAMP_SDF = new SimpleDateFormat("yyyyMMddHHmmss");
/**
* The UTC (yyyy-MM-dd HH:mm) simple date format.
*/
@ -67,8 +64,7 @@ final public class Utils
* @throws UnsupportedOperationException If the constructor is called.
*/
private Utils()
throws UnsupportedOperationException
{
throws UnsupportedOperationException {
throw new UnsupportedOperationException("Illegal constructor call.");
}
@ -76,11 +72,9 @@ final public class Utils
* Makes the given int bold.
*
* @param i The int.
*
* @return The bold string.
*/
public static String bold(final int i)
{
public static String bold(final int i) {
return bold(Integer.toString(i));
}
@ -88,11 +82,9 @@ final public class Utils
* Makes the given string bold.
*
* @param s The string.
*
* @return The bold string.
*/
public static String bold(final String s)
{
public static String bold(final String s) {
return Colors.BOLD + s + Colors.BOLD;
}
@ -102,11 +94,9 @@ final public class Utils
* @param entryIndex The entry's index.
* @param commentIndex The comment's index.
* @param comment The {@link net.thauvin.erik.mobibot.EntryComment comment} object.
*
* @return The entry's comment.
*/
static String buildComment(final int entryIndex, final int commentIndex, final EntryComment comment)
{
static String buildComment(final int entryIndex, final int commentIndex, final EntryComment comment) {
return (Commands.LINK_CMD + (entryIndex + 1) + '.' + (commentIndex + 1) + ": [" + comment.getNick() + "] "
+ comment.getComment());
}
@ -116,13 +106,10 @@ final public class Utils
*
* @param index The entry's index.
* @param entry The {@link net.thauvin.erik.mobibot.EntryLink entry} object.
*
* @return The entry's link.
*
* @see #buildLink(int, net.thauvin.erik.mobibot.EntryLink, boolean)
*/
static String buildLink(final int index, final EntryLink entry)
{
static String buildLink(final int index, final EntryLink entry) {
return buildLink(index, entry, false);
}
@ -132,28 +119,22 @@ final public class Utils
* @param index The entry's index.
* @param entry The {@link net.thauvin.erik.mobibot.EntryLink entry} object.
* @param isView Set to true to display the number of comments.
*
* @return The entry's link.
*/
static String buildLink(final int index, final EntryLink entry, final boolean isView)
{
static String buildLink(final int index, final EntryLink entry, final boolean isView) {
final StringBuilder buff = new StringBuilder(Commands.LINK_CMD + (index + 1) + ": ");
buff.append('[').append(entry.getNick()).append(']');
if (isView && entry.hasComments())
{
if (isView && entry.hasComments()) {
buff.append("[+").append(entry.getCommentsCount()).append(']');
}
buff.append(' ');
if (Mobibot.NO_TITLE.equals(entry.getTitle()))
{
if (Mobibot.NO_TITLE.equals(entry.getTitle())) {
buff.append(entry.getTitle());
}
else
{
} else {
buff.append(bold(entry.getTitle()));
}
@ -162,28 +143,14 @@ final public class Utils
return buff.toString();
}
/**
* Makes the given string green.
*
* @param s The string.
*
* @return The bold string.
*/
public static String green(final String s)
{
return Colors.DARK_GREEN + s + Colors.NORMAL;
}
/**
* Build an entry's tags/categories for display on the channel.
*
* @param entryIndex The entry's index.
* @param entry The {@link net.thauvin.erik.mobibot.EntryLink entry} object.
*
* @return The entry's tags.
*/
static String buildTags(final int entryIndex, final EntryLink entry)
{
static String buildTags(final int entryIndex, final EntryLink entry) {
return (Commands.LINK_CMD + (entryIndex + 1) + "T: " + entry.getDeliciousTags().replaceAll(",", ", "));
}
@ -192,30 +159,19 @@ final public class Utils
*
* @param location The File or URL location.
* @param isUrl Set to true if the location is a URL
*
* @return The location ending with a slash.
*/
static String ensureDir(final String location, final boolean isUrl)
{
if (isUrl)
{
if (location.charAt(location.length() - 1) == '/')
{
static String ensureDir(final String location, final boolean isUrl) {
if (isUrl) {
if (location.charAt(location.length() - 1) == '/') {
return location;
}
else
{
} else {
return location + '/';
}
}
else
{
if (location.charAt(location.length() - 1) == File.separatorChar)
{
} else {
if (location.charAt(location.length() - 1) == File.separatorChar) {
return location;
}
else
{
} else {
return location + File.separatorChar;
}
}
@ -226,43 +182,43 @@ final public class Utils
*
* @param property The port property value.
* @param def The default property value.
*
* @return The port or default value if invalid.
*/
public static int getIntProperty(final String property, final int def)
{
public static int getIntProperty(final String property, final int def) {
int prop;
try
{
try {
prop = Integer.parseInt(property);
}
catch (NumberFormatException ignore)
{
} catch (NumberFormatException ignore) {
prop = def;
}
return prop;
}
/**
* Makes the given string green.
*
* @param s The string.
* @return The bold string.
*/
public static String green(final String s) {
return Colors.DARK_GREEN + s + Colors.NORMAL;
}
/**
* Returns <code>true</code> if the given string is <em>not</em> blank or null.
*
* @param s The string to check.
*
* @return <code>true</code> if the string is valid, <code>false</code> otherwise.
*/
public static boolean isValidString(final CharSequence s)
{
public static boolean isValidString(final CharSequence s) {
final int len;
if (s == null || (len = s.length()) == 0)
{
if (s == null || (len = s.length()) == 0) {
return false;
}
for (int i = 0; i < len; i++)
{
if (!Character.isWhitespace(s.charAt(i)))
{
for (int i = 0; i < len; i++) {
if (!Character.isWhitespace(s.charAt(i))) {
return true;
}
}
@ -276,14 +232,10 @@ final public class Utils
* @param word The word.
* @param plural The plural word.
*/
public static String plural(final long count, final String word, final String plural)
{
if (count > 1)
{
public static String plural(final long count, final String word, final String plural) {
if (count > 1) {
return plural;
}
else
{
} else {
return word;
}
}
@ -292,11 +244,9 @@ final public class Utils
* Makes the given string reverse color.
*
* @param s The string.
*
* @return The reverse color string.
*/
public static String reverseColor(final String s)
{
public static String reverseColor(final String s) {
return Colors.REVERSE + s + Colors.REVERSE;
}
@ -305,8 +255,7 @@ final public class Utils
*
* @return Today's date in {@link #ISO_SDF ISO} format.
*/
public static String today()
{
public static String today() {
return ISO_SDF.format(Calendar.getInstance().getTime());
}
@ -314,11 +263,9 @@ final public class Utils
* Converts XML/XHTML entities to plain text.
*
* @param str The string to unescape.
*
* @return The unescaped string.
*/
public static String unescapeXml(final String str)
{
public static String unescapeXml(final String str) {
String s = str.replaceAll("&amp;", "&");
s = s.replaceAll("&lt;", "<");
s = s.replaceAll("&gt;", ">");

View file

@ -43,11 +43,8 @@ import java.util.*;
* @created 2016-07-01
* @since 1.0
*/
public abstract class AbstractModule
{
public abstract class AbstractModule {
final List<String> commands = new ArrayList<>();
final Map<String, String> properties = new HashMap<>();
/**
@ -68,8 +65,7 @@ public abstract class AbstractModule
*
* @return The commands.
*/
public List<String> getCommands()
{
public List<String> getCommands() {
return commands;
}
@ -78,8 +74,7 @@ public abstract class AbstractModule
*
* @return The keys.
*/
public Set<String> getPropertyKeys()
{
public Set<String> getPropertyKeys() {
return properties.keySet();
}
@ -88,8 +83,7 @@ public abstract class AbstractModule
*
* @return <code>true</code> or <code>false</code> .
*/
public boolean hasProperties()
{
public boolean hasProperties() {
return !properties.isEmpty();
}
@ -111,8 +105,7 @@ public abstract class AbstractModule
*
* @return <code>true</code> or <code>false</code>
*/
public boolean isEnabled()
{
public boolean isEnabled() {
return true;
}
@ -121,8 +114,7 @@ public abstract class AbstractModule
*
* @return <code>true</code> or <code>false</code>
*/
public boolean isPrivateMsgEnabled()
{
public boolean isPrivateMsgEnabled() {
return false;
}
@ -131,12 +123,9 @@ public abstract class AbstractModule
*
* @return <code>true</code> if the properties are valid, <code>false</code> otherwise.
*/
public boolean isValidProperties()
{
for (final String s : getPropertyKeys())
{
if (!Utils.isValidString(properties.get(s)))
{
public boolean isValidProperties() {
for (final String s : getPropertyKeys()) {
if (!Utils.isValidString(properties.get(s))) {
return false;
}
}
@ -150,10 +139,8 @@ public abstract class AbstractModule
* @param key The key.
* @param value The value.
*/
public void setProperty(final String key, final String value)
{
if (Utils.isValidString(key))
{
public void setProperty(final String key, final String value) {
if (Utils.isValidString(key)) {
properties.put(key, value);
}
}

View file

@ -45,8 +45,7 @@ import java.text.DecimalFormat;
* @created 2016-07-01
* @since 1.0
*/
public class Calc extends AbstractModule
{
public class Calc extends AbstractModule {
/**
* The Calc command.
*/
@ -55,43 +54,33 @@ public class Calc extends AbstractModule
/**
* The default constructor.
*/
public Calc()
{
public Calc() {
commands.add(CALC_CMD);
}
@Override
public void commandResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate)
{
if (Utils.isValidString(args))
{
public void commandResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate) {
if (Utils.isValidString(args)) {
final DecimalFormat decimalFormat = new DecimalFormat("#.##");
try
{
try {
final Expression calc = new ExpressionBuilder(args).build();
bot.send(bot.getChannel(), args.replaceAll(" ", "") + " = " + decimalFormat.format(calc.evaluate()));
}
catch (Exception e)
{
if (bot.getLogger().isDebugEnabled())
{
} catch (Exception e) {
if (bot.getLogger().isDebugEnabled()) {
bot.getLogger().debug("Unable to calculate: " + args, e);
}
bot.send(bot.getChannel(), "No idea. This is the kind of math I don't get.");
}
}
else
{
} else {
helpResponse(bot, sender, args, isPrivate);
}
}
@Override
public void helpResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate)
{
public void helpResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate) {
bot.send(sender, "To solve a mathematical calculation:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + CALC_CMD + " <calculation>"));
}

View file

@ -54,8 +54,7 @@ import java.util.TreeMap;
* @created Feb 11, 2004
* @since 1.0
*/
final public class CurrencyConverter extends AbstractModule
{
final public class CurrencyConverter extends AbstractModule {
/**
* The currency command.
*/
@ -79,23 +78,19 @@ final public class CurrencyConverter extends AbstractModule
/**
* The last exchange rates table publication date.
*/
private String pubDate = "";
private static String pubDate = "";
/**
* Creates a new {@link CurrencyConverter} instance.
*/
public CurrencyConverter()
{
public CurrencyConverter() {
commands.add(CURRENCY_CMD);
}
@Override
public void commandResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate)
{
synchronized (this)
{
if (!pubDate.equals(Utils.today()))
{
public void commandResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate) {
synchronized (this) {
if (!pubDate.equals(Utils.today())) {
EXCHANGE_RATES.clear();
}
}
@ -104,13 +99,11 @@ final public class CurrencyConverter extends AbstractModule
}
@Override
public void helpResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate)
{
public void helpResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate) {
bot.send(sender, "To convert from one currency to another:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + CURRENCY_CMD + " [100 USD to EUR]"));
if (args.endsWith(CURRENCY_CMD))
{
if (args.endsWith(CURRENCY_CMD)) {
bot.send(sender, "For a listing of currency rates:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + CURRENCY_CMD) + ' ' + CURRENCY_RATES_KEYWORD);
bot.send(sender, "For a listing of supported currencies:");
@ -121,14 +114,10 @@ final public class CurrencyConverter extends AbstractModule
/**
* Converts the specified currencies.
*/
private void run(final Mobibot bot, final String sender, final String query)
{
if (Utils.isValidString(sender))
{
if (EXCHANGE_RATES.isEmpty())
{
try
{
private void run(final Mobibot bot, final String sender, final String query) {
if (Utils.isValidString(sender)) {
if (EXCHANGE_RATES.isEmpty()) {
try {
final SAXBuilder builder = new SAXBuilder();
builder.setIgnoringElementContentWhitespace(true);
@ -143,8 +132,7 @@ final public class CurrencyConverter extends AbstractModule
final List cubes = cubeTime.getChildren();
Element cube;
for (final Object rawCube : cubes)
{
for (final Object rawCube : cubes) {
cube = (Element) rawCube;
EXCHANGE_RATES.put(
cube.getAttribute("currency").getValue(),
@ -152,43 +140,29 @@ final public class CurrencyConverter extends AbstractModule
}
EXCHANGE_RATES.put("EUR", "1");
}
catch (JDOMException e)
{
} catch (JDOMException e) {
bot.getLogger().debug("Unable to parse the exchange rates table.", e);
bot.send(sender, "An error has occurred while parsing the exchange rates table.");
}
catch (IOException e)
{
} catch (IOException e) {
bot.getLogger().debug("Unable to fetch the exchange rates table.", e);
bot.send(sender,
"An error has occurred while fetching the exchange rates table: " + e.getMessage());
}
}
if (EXCHANGE_RATES.isEmpty())
{
if (EXCHANGE_RATES.isEmpty()) {
bot.getLogger().debug("The exchange rate table is empty.");
bot.send(sender, "Sorry, but the exchange rate table is empty.");
}
else if (Utils.isValidString(query))
{
if (!EXCHANGE_RATES.isEmpty())
{
if (query.matches("\\d+([,\\d]+)?(\\.\\d+)? [a-zA-Z]{3}+ to [a-zA-Z]{3}+"))
{
} else if (Utils.isValidString(query)) {
if (!EXCHANGE_RATES.isEmpty()) {
if (query.matches("\\d+([,\\d]+)?(\\.\\d+)? [a-zA-Z]{3}+ to [a-zA-Z]{3}+")) {
final String[] cmds = query.split(" ");
if (cmds.length == 4)
{
if (cmds[3].equals(cmds[1]) || cmds[0].equals("0"))
{
if (cmds.length == 4) {
if (cmds[3].equals(cmds[1]) || cmds[0].equals("0")) {
bot.send(sender, "You're kidding, right?");
}
else
{
try
{
} else {
try {
final double amt = Double.parseDouble(cmds[0].replaceAll(",", ""));
final double from = Double.parseDouble(EXCHANGE_RATES.get(cmds[1].toUpperCase()));
final double to = Double.parseDouble(EXCHANGE_RATES.get(cmds[3].toUpperCase()));
@ -203,25 +177,19 @@ final public class CurrencyConverter extends AbstractModule
.substring(1)
+ ' '
+ cmds[3].toUpperCase());
}
catch (NullPointerException ignored)
{
} catch (NullPointerException ignored) {
bot.send(sender,
"The supported currencies are: " + EXCHANGE_RATES.keySet().toString());
}
}
}
}
else if (query.equals(CURRENCY_RATES_KEYWORD))
{
} else if (query.equals(CURRENCY_RATES_KEYWORD)) {
bot.send(sender, "Last Update: " + pubDate);
final StringBuilder buff = new StringBuilder(0);
for (final Map.Entry<String, String> rate : EXCHANGE_RATES.entrySet())
{
if (buff.length() > 0)
{
for (final Map.Entry<String, String> rate : EXCHANGE_RATES.entrySet()) {
if (buff.length() > 0) {
buff.append(", ");
}
buff.append(rate.getKey()).append(": ").append(rate.getValue());
@ -230,9 +198,7 @@ final public class CurrencyConverter extends AbstractModule
bot.send(sender, buff.toString());
}
}
}
else
{
} else {
helpResponse(bot, sender, CURRENCY_CMD + ' ' + query, true);
bot.send(sender, "The supported currencies are: " + EXCHANGE_RATES.keySet().toString());
}

View file

@ -43,8 +43,7 @@ import java.util.Random;
* @created 2014-04-28
* @since 1.0
*/
final public class Dice extends AbstractModule
{
final public class Dice extends AbstractModule {
/**
* The dice command.
*/
@ -53,8 +52,7 @@ final public class Dice extends AbstractModule
/**
* The default constructor.
*/
public Dice()
{
public Dice() {
commands.add(DICE_CMD);
}
@ -67,8 +65,7 @@ final public class Dice extends AbstractModule
* @param isPrivate Set to <code>true</code> if the response should be sent as a private message.
*/
@Override
public void commandResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate)
{
public void commandResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate) {
final Random r = new Random();
int i = r.nextInt(6) + 1;
@ -86,30 +83,23 @@ final public class Dice extends AbstractModule
bot.action(
"rolled two dice: " + Utils.bold(i) + " and " + Utils.bold(y) + " for a total of " + Utils.bold(total));
if (playerTotal < total)
{
if (playerTotal < total) {
bot.action("wins.");
}
else if (playerTotal > total)
{
} else if (playerTotal > total) {
bot.action("lost.");
}
else
{
} else {
bot.action("tied.");
}
}
@Override
public void helpResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate)
{
public void helpResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate) {
bot.send(sender, "To roll the dice:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + DICE_CMD));
}
@Override
public boolean isEnabled()
{
public boolean isEnabled() {
return true;
}
}

View file

@ -49,8 +49,7 @@ import java.net.URLEncoder;
* @created Feb 7, 2004
* @since 1.0
*/
final public class GoogleSearch extends AbstractModule
{
final public class GoogleSearch extends AbstractModule {
/**
* The Google API Key property.
*/
@ -74,40 +73,45 @@ final public class GoogleSearch extends AbstractModule
/**
* Creates a new {@link GoogleSearch} instance.
*/
public GoogleSearch()
{
public GoogleSearch() {
commands.add(GOOGLE_CMD);
properties.put(GOOGLE_API_KEY_PROP, "");
properties.put(GOOGLE_CSE_KEY_PROP, "");
}
@Override
public void commandResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate)
{
if (isEnabled() && args.length() > 0)
{
if (args.length() > 0)
{
public void commandResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate) {
if (isEnabled() && args.length() > 0) {
if (args.length() > 0) {
new Thread(() -> run(bot, sender, args)).start();
} else {
helpResponse(bot, sender, args, isPrivate);
}
else
{
} else {
helpResponse(bot, sender, args, isPrivate);
}
}
else
{
helpResponse(bot, sender, args, isPrivate);
@Override
public void helpResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate) {
if (isEnabled()) {
bot.send(sender, "To search Google:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + GOOGLE_CMD + " <query>"));
} else {
bot.send(sender, "The Google searching facility is disabled.");
}
}
@Override
public boolean isEnabled() {
return isValidProperties();
}
/**
* Searches Google.
*/
private void run(final Mobibot bot, final String sender, final String query)
{
try
{
private void run(final Mobibot bot, final String sender, final String query) {
try {
final String q = URLEncoder.encode(query, "UTF-8");
final URL url =
@ -121,49 +125,24 @@ final public class GoogleSearch extends AbstractModule
final URLConnection conn = url.openConnection();
final StringBuilder sb = new StringBuilder();
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())))
{
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null)
{
while ((line = reader.readLine()) != null) {
sb.append(line);
}
final JSONObject json = new JSONObject(sb.toString());
final JSONArray ja = json.getJSONArray("items");
for (int i = 0; i < ja.length(); i++)
{
for (int i = 0; i < ja.length(); i++) {
final JSONObject j = ja.getJSONObject(i);
bot.send(sender, Utils.unescapeXml(j.getString("title")));
bot.send(sender, TAB_INDENT + Utils.green(j.getString("link")));
}
}
}
catch (Exception e)
{
} catch (Exception e) {
bot.getLogger().warn("Unable to search in Google for: " + query, e);
bot.send(sender, "An error has occurred searching in Google: " + e.getMessage());
}
}
@Override
public void helpResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate)
{
if (isEnabled())
{
bot.send(sender, "To search Google:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + GOOGLE_CMD + " <query>"));
}
else
{
bot.send(sender, "The Google searching facility is disabled.");
}
}
@Override
public boolean isEnabled()
{
return isValidProperties();
}
}

View file

@ -47,9 +47,7 @@ import java.net.URLConnection;
* @created 2014-04-20
* @since 1.0
*/
final public class Joke extends AbstractModule
{
final public class Joke extends AbstractModule {
/**
* The joke command.
*/
@ -64,20 +62,17 @@ final public class Joke extends AbstractModule
/**
* Creates a new {@link Joke} instance.
*/
public Joke()
{
public Joke() {
commands.add(JOKE_CMD);
}
@Override
public void commandResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate)
{
public void commandResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate) {
new Thread(() -> run(bot, sender)).start();
}
@Override
public void helpResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate)
{
public void helpResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate) {
bot.send(sender, "To retrieve a random joke:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + JOKE_CMD));
}
@ -85,19 +80,15 @@ final public class Joke extends AbstractModule
/**
* 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)
{
try
{
private void run(final Mobibot bot, final String sender) {
try {
final URL url = new URL(JOKE_URL);
final URLConnection conn = url.openConnection();
final StringBuilder sb = new StringBuilder();
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())))
{
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null)
{
while ((line = reader.readLine()) != null) {
sb.append(line);
}
@ -109,9 +100,7 @@ final public class Joke extends AbstractModule
.replaceAll("\\\"", "\"")
+ Colors.NORMAL);
}
}
catch (Exception e)
{
} catch (Exception e) {
bot.getLogger().warn("Unable to retrieve random joke.", e);
bot.send(sender, "An error has occurred retrieving a random joke: " + e.getMessage());
}

View file

@ -45,8 +45,7 @@ import java.net.UnknownHostException;
* @created 2014-04-26
* @since 1.0
*/
final public class Lookup extends AbstractModule
{
final public class Lookup extends AbstractModule {
/**
* THe lookup command.
*/
@ -60,113 +59,36 @@ final public class Lookup extends AbstractModule
/**
* The default constructor
*/
public Lookup()
{
public Lookup() {
commands.add(LOOKUP_CMD);
}
/**
* Process a command.
*
* @param bot The bot's instance.
* @param sender The sender.
* @param args The command arguments.
* @param isPrivate Set to <code>true</code> if the response should be sent as a private message.
*/
@Override
public void commandResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate)
{
if (args.matches("(\\S.)+(\\S)+"))
{
try
{
bot.send(bot.getChannel(), Lookup.lookup(args));
}
catch (UnknownHostException ignore)
{
if (args.matches(
"(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"))
{
try
{
final String[] lines = Lookup.whois(args);
if ((lines != null) && (lines.length > 0))
{
String line;
for (final String rawLine : lines)
{
line = rawLine.trim();
if ((line.length() > 0) && (line.charAt(0) != '#'))
{
bot.send(bot.getChannel(), line);
}
}
}
else
{
bot.send(bot.getChannel(), "Unknown host.");
}
}
catch (IOException ioe)
{
if (bot.getLogger().isDebugEnabled())
{
bot.getLogger().debug("Unable to perform whois IP lookup: " + args, ioe);
}
bot.send(bot.getChannel(), "Unable to perform whois IP lookup: " + ioe.getMessage());
}
}
else
{
bot.send(bot.getChannel(), "Unknown host.");
}
}
}
else
{
helpResponse(bot, sender, args, true);
}
}
/**
* Performs a DNS lookup on the specified query.
*
* @param query The IP address or hostname.
*
* @return The lookup query result string.
*
* @throws java.net.UnknownHostException If the host is unknown.
*/
private static String lookup(final String query)
throws UnknownHostException
{
throws UnknownHostException {
final StringBuilder buffer = new StringBuilder("");
final InetAddress[] results = InetAddress.getAllByName(query);
String hostInfo;
for (final InetAddress result : results)
{
if (result.getHostAddress().equals(query))
{
for (final InetAddress result : results) {
if (result.getHostAddress().equals(query)) {
hostInfo = result.getHostName();
if (hostInfo.equals(query))
{
if (hostInfo.equals(query)) {
throw new UnknownHostException();
}
}
else
{
} else {
hostInfo = result.getHostAddress();
}
if (buffer.length() > 0)
{
if (buffer.length() > 0) {
buffer.append(", ");
}
@ -180,14 +102,11 @@ final public class Lookup extends AbstractModule
* Performs a whois IP query.
*
* @param query The IP address.
*
* @return The IP whois data, if any.
*
* @throws java.io.IOException If a connection error occurs.
*/
private static String[] whois(final String query)
throws IOException
{
throws IOException {
return whois(query, WHOIS_HOST);
}
@ -196,38 +115,80 @@ final public class Lookup extends AbstractModule
*
* @param query The IP address.
* @param host The whois host.
*
* @return The IP whois data, if any.
*
* @throws java.io.IOException If a connection error occurs.
*/
@SuppressWarnings("WeakerAccess, SameParameterValue")
public static String[] whois(final String query, final String host)
throws IOException
{
throws IOException {
final WhoisClient whois = new WhoisClient();
String[] lines;
try
{
try {
whois.setDefaultTimeout(Mobibot.CONNECT_TIMEOUT);
whois.connect(host);
whois.setSoTimeout(Mobibot.CONNECT_TIMEOUT);
whois.setSoLinger(false, 0);
lines = whois.query('-' + query).split("\n");
}
finally
{
} finally {
whois.disconnect();
}
return lines;
}
/**
* Process a command.
*
* @param bot The bot's instance.
* @param sender The sender.
* @param args The command arguments.
* @param isPrivate Set to <code>true</code> if the response should be sent as a private message.
*/
@Override
public void helpResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate)
{
public void commandResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate) {
if (args.matches("(\\S.)+(\\S)+")) {
try {
bot.send(bot.getChannel(), Lookup.lookup(args));
} catch (UnknownHostException ignore) {
if (args.matches(
"(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." +
"(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)")) {
try {
final String[] lines = Lookup.whois(args);
if ((lines != null) && (lines.length > 0)) {
String line;
for (final String rawLine : lines) {
line = rawLine.trim();
if ((line.length() > 0) && (line.charAt(0) != '#')) {
bot.send(bot.getChannel(), line);
}
}
} else {
bot.send(bot.getChannel(), "Unknown host.");
}
} catch (IOException ioe) {
if (bot.getLogger().isDebugEnabled()) {
bot.getLogger().debug("Unable to perform whois IP lookup: " + args, ioe);
}
bot.send(bot.getChannel(), "Unable to perform whois IP lookup: " + ioe.getMessage());
}
} else {
bot.send(bot.getChannel(), "Unknown host.");
}
}
} else {
helpResponse(bot, sender, args, true);
}
}
@Override
public void helpResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate) {
bot.send(sender, "To perform a DNS lookup query:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + LOOKUP_CMD + " <ip address or hostname>"));
}

View file

@ -44,12 +44,13 @@ import java.util.Random;
* @created 2016-07-02
* @since 1.0
*/
public class Ping extends AbstractModule
{
public class Ping extends AbstractModule {
/**
* The ping responses.
*/
private static final List<String> PINGS = Arrays.asList("is barely alive.",
private static final List<String> PINGS =
Arrays.asList(
"is barely alive.",
"is trying to stay awake.",
"has gone fishing.",
"is somewhere over the rainbow.",
@ -70,22 +71,19 @@ public class Ping extends AbstractModule
/**
* The default constructor.
*/
public Ping()
{
public Ping() {
commands.add(PING_CMD);
}
@Override
public void commandResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate)
{
public void commandResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate) {
final Random r = new Random();
bot.action(PINGS.get(r.nextInt(PINGS.size())));
}
@Override
public void helpResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate)
{
public void helpResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate) {
bot.send(sender, "To ping the bot:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + PING_CMD));
}

View file

@ -45,8 +45,7 @@ import java.io.IOException;
* @created Feb 7, 2004
* @since 1.0
*/
final public class StockQuote extends AbstractModule
{
final public class StockQuote extends AbstractModule {
/**
* The quote command.
*/
@ -60,27 +59,21 @@ final public class StockQuote extends AbstractModule
/**
* Creates a new {@link StockQuote} instance.
*/
public StockQuote()
{
public StockQuote() {
commands.add(STOCK_CMD);
}
@Override
public void commandResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate)
{
if (args.length() > 0)
{
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);
}
}
@Override
public void helpResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate)
{
public void helpResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate) {
bot.send(sender, "To retrieve a stock quote:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + STOCK_CMD + " <symbol[.country code]>"));
}
@ -88,10 +81,8 @@ final public class StockQuote extends AbstractModule
/**
* Returns the specified stock quote from Yahoo!
*/
private void run(final Mobibot bot, final String sender, final String symbol)
{
try
{
private void run(final Mobibot bot, final String sender, final String symbol) {
try {
final HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(Mobibot.CONNECT_TIMEOUT);
client.getHttpConnectionManager().getParams().setSoTimeout(Mobibot.CONNECT_TIMEOUT);
@ -101,62 +92,44 @@ final public class StockQuote extends AbstractModule
final String[][] lines = CSVParser.parse(getMethod.getResponseBodyAsString());
if (lines.length > 0)
{
if (lines.length > 0) {
final String[] quote = lines[0];
if (quote.length > 0)
{
if ((quote.length > 3) && (!"N/A".equalsIgnoreCase(quote[3])))
{
if (quote.length > 0) {
if ((quote.length > 3) && (!"N/A".equalsIgnoreCase(quote[3]))) {
bot.send(bot.getChannel(), "Symbol: " + quote[0] + " [" + quote[1] + ']');
if (quote.length > 5)
{
if (quote.length > 5) {
bot.send(bot.getChannel(), "Last Trade: " + quote[2] + " (" + quote[5] + ')');
}
else
{
} else {
bot.send(bot.getChannel(), "Last Trade: " + quote[2]);
}
if (quote.length > 4)
{
if (quote.length > 4) {
bot.send(sender, "Time: " + quote[3] + ' ' + quote[4]);
}
if (quote.length > 6 && !"N/A".equalsIgnoreCase(quote[6]))
{
if (quote.length > 6 && !"N/A".equalsIgnoreCase(quote[6])) {
bot.send(sender, "Open: " + quote[6]);
}
if (quote.length > 7 && !"N/A".equalsIgnoreCase(quote[7]) && !"N/A".equalsIgnoreCase(quote[8]))
{
if (quote.length > 7 && !"N/A".equalsIgnoreCase(quote[7]) && !"N/A".equalsIgnoreCase(quote[8])) {
bot.send(sender, "Day's Range: " + quote[7] + " - " + quote[8]);
}
if (quote.length > 9 && !"0".equalsIgnoreCase(quote[9]))
{
if (quote.length > 9 && !"0".equalsIgnoreCase(quote[9])) {
bot.send(sender, "Volume: " + quote[9]);
}
}
else
{
} else {
bot.send(sender, "Invalid ticker symbol.");
}
}
else
{
} else {
bot.send(sender, "No values returned.");
}
}
else
{
} else {
bot.send(sender, "No data returned.");
}
}
catch (IOException e)
{
} catch (IOException e) {
bot.getLogger().debug("Unable to retrieve stock quote for: " + symbol, e);
bot.send(sender, "An error has occurred retrieving a stock quote: " + e.getMessage());
}

View file

@ -43,14 +43,10 @@ import twitter4j.conf.ConfigurationBuilder;
* @created Sept 10, 2008
* @since 1.0
*/
final public class Twitter extends AbstractModule
{
final public class Twitter extends AbstractModule {
private final static String CONSUMER_KEY_PROP = "twitter-consumerKey";
private final static String CONSUMER_SECRET_PROP = "twitter-consumerSecret";
private final static String TOKEN_PROP = "twitter-token";
private final static String TOKEN_SECRET_PROP = "twitter-tokenSecret";
/**
@ -61,8 +57,7 @@ final public class Twitter extends AbstractModule
/**
* Creates a new {@link Twitter} instance.
*/
public Twitter()
{
public Twitter() {
commands.add(TWITTER_CMD);
properties.put(CONSUMER_SECRET_PROP, "");
properties.put(CONSUMER_KEY_PROP, "");
@ -71,45 +66,34 @@ final public class Twitter extends AbstractModule
}
@Override
public void commandResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate)
{
if (isEnabled() && args.length() > 0)
{
public void commandResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate) {
if (isEnabled() && args.length() > 0) {
new Thread(() -> run(bot, sender, args)).start();
}
else
{
} else {
helpResponse(bot, sender, args, isPrivate);
}
}
@Override
public void helpResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate)
{
if (isEnabled())
{
public void helpResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate) {
if (isEnabled()) {
bot.send(sender, "To post to Twitter:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + TWITTER_CMD + " <message>"));
}
else
{
} else {
bot.send(sender, "The Twitter posting facility is disabled.");
}
}
@Override
public boolean isEnabled()
{
public boolean isEnabled() {
return isValidProperties();
}
/**
* Posts to twitter.
*/
private void run(final Mobibot bot, final String sender, final String message)
{
try
{
private void run(final Mobibot bot, final String sender, final String message) {
try {
final ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(properties.get(CONSUMER_KEY_PROP))
@ -124,9 +108,7 @@ final public class Twitter extends AbstractModule
bot.send(sender,
"You message was posted to http://twitter.com/" + twitter.getScreenName() + "/statuses/" + status
.getId());
}
catch (Exception e)
{
} catch (Exception e) {
bot.getLogger().warn("Unable to post to Twitter: " + message, e);
bot.send(sender, "An error has occurred: " + e.getMessage());
}

View file

@ -43,8 +43,7 @@ import java.util.Random;
* @created 2014-04-28
* @since 1.0
*/
final public class War extends AbstractModule
{
final public class War extends AbstractModule {
/**
* The war command.
*/
@ -64,8 +63,7 @@ final public class War extends AbstractModule
/**
* The default constructor.
*/
public War()
{
public War() {
commands.add(WAR_CMD);
}
@ -78,15 +76,13 @@ final public class War extends AbstractModule
* @param isPrivate Set to <code>true</code> if the response should be sent as a private message.
*/
@Override
public void commandResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate)
{
public void commandResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate) {
final Random r = new Random();
int i;
int y;
while (true)
{
while (true) {
i = r.nextInt(WAR_DECK.length);
y = r.nextInt(WAR_DECK.length);
@ -94,27 +90,22 @@ final public class War extends AbstractModule
sender + " drew the " + Utils.bold(WAR_DECK[i]) + " of " + WAR_SUITS[r.nextInt(WAR_SUITS.length)]);
bot.action("drew the " + Utils.bold(WAR_DECK[y]) + " of " + WAR_SUITS[r.nextInt(WAR_SUITS.length)]);
if (i != y)
{
if (i != y) {
break;
}
bot.send(bot.getChannel(), "This means " + Utils.bold("WAR") + '!');
}
if (i < y)
{
if (i < y) {
bot.action("lost.");
}
else if (i > y)
{
} else if (i > y) {
bot.action("wins.");
}
}
@Override
public void helpResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate)
{
public void helpResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate) {
bot.send(sender, "To play war:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + WAR_CMD));
}

View file

@ -47,8 +47,7 @@ import java.util.Date;
* @created Feb 7, 2004
* @since 1.0
*/
final public class Weather extends AbstractModule
{
final public class Weather extends AbstractModule {
/**
* The decimal number format.
*/
@ -67,42 +66,35 @@ final public class Weather extends AbstractModule
/**
* Creates a new {@link Weather} instance.
*/
public Weather()
{
public Weather() {
commands.add(WEATHER_CMD);
}
@Override
public void commandResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate)
{
public void commandResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate) {
new Thread(() -> run(bot, sender, args.toUpperCase(), isPrivate)).start();
}
@Override
public void helpResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate)
{
public void helpResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate) {
bot.send(sender, "To display weather information:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + WEATHER_CMD + " <station id>"));
bot.send(sender, "For a listing of the ICAO station IDs, please visit: " + STATIONS_URL);
}
@Override
public boolean isPrivateMsgEnabled()
{
public boolean isPrivateMsgEnabled() {
return true;
}
/**
* Fetches the weather data from a specific station ID.
*/
private void run(final Mobibot bot, final String sender, final String station, final boolean isPrivate)
{
if (station.length() == 4)
{
private void run(final Mobibot bot, final String sender, final String station, final boolean isPrivate) {
if (station.length() == 4) {
final Metar metar = net.sf.jweather.Weather.getMetar(station);
if (metar != null)
{
if (metar != null) {
Float result;
bot.send(sender, "Station ID: " + metar.getStationID(), isPrivate);
@ -117,8 +109,7 @@ final public class Weather extends AbstractModule
result = metar.getWindSpeedInMPH();
if (result != null)
{
if (result != null) {
bot.send(sender,
"Wind Speed: "
+ result
@ -132,8 +123,7 @@ final public class Weather extends AbstractModule
result = metar.getVisibility();
if (result != null)
{
if (result != null) {
bot.send(sender,
"Visibility: "
+ (metar.getVisibilityLessThan() ? "< " : "")
@ -144,8 +134,7 @@ final public class Weather extends AbstractModule
result = metar.getPressure();
if (result != null)
{
if (result != null) {
bot.send(sender,
"Pressure: " + result + " Hg, " + metar.getPressureInHectoPascals() + " hPa",
isPrivate);
@ -153,33 +142,26 @@ final public class Weather extends AbstractModule
result = metar.getTemperatureInCelsius();
if (result != null)
{
if (result != null) {
bot.send(sender,
"Temperature: " + result + " \u00B0C, " + metar.getTemperatureInFahrenheit() + " \u00B0F",
isPrivate);
}
if (metar.getWeatherConditions() != null)
{
for (final Object weatherCondition : metar.getWeatherConditions())
{
if (metar.getWeatherConditions() != null) {
for (final Object weatherCondition : metar.getWeatherConditions()) {
bot.send(sender, ((WeatherCondition) weatherCondition).getNaturalLanguageString(), isPrivate);
}
}
if (metar.getSkyConditions() != null)
{
for (final Object skyCondition : metar.getSkyConditions())
{
if (metar.getSkyConditions() != null) {
for (final Object skyCondition : metar.getSkyConditions()) {
bot.send(sender, ((SkyCondition) skyCondition).getNaturalLanguageString(), isPrivate);
}
}
return;
}
else
{
} else {
bot.send(sender, "Invalid Station ID. Please try again.", isPrivate);
return;

View file

@ -46,8 +46,7 @@ import java.util.TreeMap;
* @created 2014-04-27
* @since 1.0
*/
final public class WorldTime extends AbstractModule
{
final public class WorldTime extends AbstractModule {
/**
* The beats (Internet Time) keyword.
*/
@ -72,8 +71,7 @@ final public class WorldTime extends AbstractModule
/**
* Creates a new {@link WorldTime} instance.
*/
public WorldTime()
{
public WorldTime() {
commands.add(TIME_CMD);
// Initialize the countries map
@ -137,10 +135,8 @@ final public class WorldTime extends AbstractModule
COUNTRIES_MAP.put("INTERNET", BEATS_KEYWORD);
COUNTRIES_MAP.put("BEATS", BEATS_KEYWORD);
for (final String tz : TimeZone.getAvailableIDs())
{
if (!tz.contains("/") && tz.length() == 3 & !COUNTRIES_MAP.containsKey(tz))
{
for (final String tz : TimeZone.getAvailableIDs()) {
if (!tz.contains("/") && tz.length() == 3 & !COUNTRIES_MAP.containsKey(tz)) {
COUNTRIES_MAP.put(tz, tz);
}
}
@ -155,51 +151,37 @@ final public class WorldTime extends AbstractModule
* @param isPrivate Set to <code>true</code> if the response should be sent as a private message.
*/
@Override
public void commandResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate)
{
public void commandResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate) {
boolean isInvalidTz = false;
final String tz = (COUNTRIES_MAP.get((args.substring(args.indexOf(' ') + 1).trim().toUpperCase())));
final String response;
if (tz != null)
{
if (tz.equals(BEATS_KEYWORD))
{
if (tz != null) {
if (tz.equals(BEATS_KEYWORD)) {
response = ("The current Internet Time is: " + internetTime() + ' ' + BEATS_KEYWORD);
}
else
{
} else {
TIME_SDF.setTimeZone(TimeZone.getTimeZone(tz));
response = TIME_SDF.format(Calendar.getInstance().getTime()) + tz.substring(tz.indexOf('/') + 1)
.replace('_', ' ');
}
}
else
{
} else {
isInvalidTz = true;
response = "The supported time zones are: " + COUNTRIES_MAP.keySet().toString();
}
if (isPrivate)
{
if (isPrivate) {
bot.send(sender, response, true);
}
else
{
if (isInvalidTz)
{
} else {
if (isInvalidTz) {
bot.send(sender, response);
}
else
{
} else {
bot.send(bot.getChannel(), response);
}
}
}
@Override
public void helpResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate)
{
public void helpResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate) {
bot.send(sender, "To display a country's current date/time:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + TIME_CMD) + " [<country code>]");
@ -212,8 +194,7 @@ final public class WorldTime extends AbstractModule
*
* @return The Internet Time string.
*/
private String internetTime()
{
private String internetTime() {
final Calendar gc = Calendar.getInstance();
final int offset = (gc.get(Calendar.ZONE_OFFSET) / (60 * 60 * 1000));
@ -226,21 +207,15 @@ final public class WorldTime extends AbstractModule
long beats = Math.round(Math.floor((double) ((((hh * 3600) + (mm * 60) + ss) * 1000) / 86400)));
if (beats >= 1000)
{
if (beats >= 1000) {
beats -= (long) 1000;
}
else if (beats < 0)
{
} else if (beats < 0) {
beats += (long) 1000;
}
if (beats < 10)
{
if (beats < 10) {
return ("@00" + beats);
}
else if (beats < 100)
{
} else if (beats < 100) {
return ("@0" + beats);
}
@ -248,8 +223,7 @@ final public class WorldTime extends AbstractModule
}
@Override
public boolean isPrivateMsgEnabled()
{
public boolean isPrivateMsgEnabled() {
return true;
}
}

View file

@ -5,4 +5,4 @@ version.major=0
version.minor=7
version.patch=0
version.prerelease=beta
version.buildmeta=007
version.buildmeta=008