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 deployDir = 'deploy'
def isRelease = 'release' in gradle.startParameter.taskNames def isRelease = 'release' in gradle.startParameter.taskNames
def getVersion(isIncrement = false) def getVersion(isIncrement = false) {
{
def propsFile = 'version.properties' def propsFile = 'version.properties'
def majorKey = 'version.major' def majorKey = 'version.major'
def minorKey = 'version.minor' def minorKey = 'version.minor'
def patchKey = 'version.patch' def patchKey = 'version.patch'
def metaKey = 'version.buildmeta' def metaKey = 'version.buildmeta'
def preKey = 'version.prerelease' def preKey = 'version.prerelease'
if (isIncrement) if (isIncrement) {
{
ant.propertyfile(file: propsFile) { ant.propertyfile(file: propsFile) {
entry(key: patchKey, entry(key: patchKey,
type: 'int', type: 'int',

View file

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

View file

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

View file

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

View file

@ -48,8 +48,7 @@ import java.util.List;
* @created 2014-04-28 * @created 2014-04-28
* @since 1.0 * @since 1.0
*/ */
final class EntriesMgr final class EntriesMgr {
{
/** /**
* The name of the file containing the current entries. * The name of the file containing the current entries.
*/ */
@ -76,8 +75,7 @@ final class EntriesMgr
* @throws UnsupportedOperationException If the constructor is called. * @throws UnsupportedOperationException If the constructor is called.
*/ */
private EntriesMgr() private EntriesMgr()
throws UnsupportedOperationException throws UnsupportedOperationException {
{
throw new UnsupportedOperationException("Illegal constructor call."); throw new UnsupportedOperationException("Illegal constructor call.");
} }
@ -86,27 +84,23 @@ final class EntriesMgr
* *
* @param file The file containing the backlogs. * @param file The file containing the backlogs.
* @param history The history list. * @param history The history list.
*
* @throws IOException If the file was not found or could not be read. * @throws IOException If the file was not found or could not be read.
* @throws FeedException If an error occurred while reading the feed. * @throws FeedException If an error occurred while reading the feed.
*/ */
public static void loadBacklogs(final String file, final List<String> history) public static void loadBacklogs(final String file, final List<String> history)
throws IOException, FeedException throws IOException, FeedException {
{
history.clear(); history.clear();
final SyndFeedInput input = new SyndFeedInput(); 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 SyndFeed feed = input.build(reader);
final List items = feed.getEntries(); final List items = feed.getEntries();
SyndEntry item; 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); item = (SyndEntryImpl) items.get(i);
history.add(item.getTitle()); history.add(item.getTitle());
} }
@ -119,24 +113,20 @@ final class EntriesMgr
* @param file The file containing the current entries. * @param file The file containing the current entries.
* @param channel The channel * @param channel The channel
* @param entries The entries. * @param entries The entries.
*
* @return The feed's last published date. * @return The feed's last published date.
*
* @throws IOException If the file was not found or could not be read. * @throws IOException If the file was not found or could not be read.
* @throws FeedException If an error occurred while reading the feed. * @throws FeedException If an error occurred while reading the feed.
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static String loadEntries(final String file, final String channel, final List<EntryLink> entries) public static String loadEntries(final String file, final String channel, final List<EntryLink> entries)
throws IOException, FeedException throws IOException, FeedException {
{
entries.clear(); entries.clear();
final SyndFeedInput input = new SyndFeedInput(); final SyndFeedInput input = new SyndFeedInput();
final String today; 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); final SyndFeed feed = input.build(reader);
today = Utils.ISO_SDF.format(feed.getPublishedDate()); today = Utils.ISO_SDF.format(feed.getPublishedDate());
@ -148,8 +138,7 @@ final class EntriesMgr
String author; String author;
EntryLink entry; 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); item = (SyndEntryImpl) items.get(i);
author = item.getAuthor() author = item.getAuthor()
.substring(item.getAuthor().lastIndexOf('(') + 1, item.getAuthor().length() - 1); .substring(item.getAuthor().lastIndexOf('(') + 1, item.getAuthor().length() - 1);
@ -163,12 +152,10 @@ final class EntriesMgr
comments = description.getValue().split("<br/>"); comments = description.getValue().split("<br/>");
int split; int split;
for (final String comment : comments) for (final String comment : comments) {
{
split = comment.indexOf(": "); split = comment.indexOf(": ");
if (split != -1) if (split != -1) {
{
entry.addComment(comment.substring(split + 2).trim(), comment.substring(0, split).trim()); 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. * @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, public static void saveEntries(final Mobibot bot, final List<EntryLink> entries, final List<String> history,
final boolean isDayBackup) final boolean isDayBackup) {
{ if (bot.getLogger().isDebugEnabled()) {
if (bot.getLogger().isDebugEnabled())
{
bot.getLogger().debug("Saving the feeds..."); 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; FileWriter fw = null;
try try {
{
fw = new FileWriter(new File(bot.getLogsDir() + CURRENT_XML)); fw = new FileWriter(new File(bot.getLogsDir() + CURRENT_XML));
SyndFeed rss = new SyndFeedImpl(); SyndFeed rss = new SyndFeedImpl();
@ -219,26 +202,22 @@ final class EntriesMgr
SyndEntry item; SyndEntry item;
SyndContent description; SyndContent description;
for (int i = (entries.size() - 1); i >= 0; --i) for (int i = (entries.size() - 1); i >= 0; --i) {
{
entry = entries.get(i); entry = entries.get(i);
buff = new StringBuffer( buff = new StringBuffer(
"Posted by <b>" + entry.getNick() + "</b> on <a href=\"irc://" + bot.getIrcServer() + '/' "Posted by <b>" + entry.getNick() + "</b> on <a href=\"irc://" + bot.getIrcServer() + '/'
+ entry.getChannel() + "\"><b>" + entry.getChannel() + "</b></a>"); + entry.getChannel() + "\"><b>" + entry.getChannel() + "</b></a>");
if (entry.getCommentsCount() > 0) if (entry.getCommentsCount() > 0) {
{
buff.append(" <br/><br/>"); buff.append(" <br/><br/>");
final EntryComment[] comments = entry.getComments(); final EntryComment[] comments = entry.getComments();
for (int j = 0; j < comments.length; j++) for (int j = 0; j < comments.length; j++) {
{
comment = comments[j]; comment = comments[j];
if (j > 0) if (j > 0) {
{
buff.append(" <br/>"); buff.append(" <br/>");
} }
@ -262,8 +241,7 @@ final class EntriesMgr
rss.setEntries(items); rss.setEntries(items);
if (bot.getLogger().isDebugEnabled()) if (bot.getLogger().isDebugEnabled()) {
{
bot.getLogger().debug("Writing the entries feed."); 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)); fw = new FileWriter(new File(bot.getLogsDir() + bot.getToday() + XML_EXT));
output.output(rss, fw); output.output(rss, fw);
if (isDayBackup) if (isDayBackup) {
{ if (Utils.isValidString(bot.getBacklogsUrl())) {
if (Utils.isValidString(bot.getBacklogsUrl())) if (history.indexOf(bot.getToday()) == -1) {
{
if (history.indexOf(bot.getToday()) == -1)
{
history.add(bot.getToday()); history.add(bot.getToday());
while (history.size() > MAX_BACKLOGS) while (history.size() > MAX_BACKLOGS) {
{
history.remove(0); history.remove(0);
} }
} }
@ -300,8 +274,7 @@ final class EntriesMgr
String date; String date;
items.clear(); items.clear();
for (int i = (history.size() - 1); i >= 0; --i) for (int i = (history.size() - 1); i >= 0; --i) {
{
date = history.get(i); date = history.get(i);
item = new SyndEntryImpl(); item = new SyndEntryImpl();
@ -316,40 +289,27 @@ final class EntriesMgr
rss.setEntries(items); rss.setEntries(items);
if (bot.getLogger().isDebugEnabled()) if (bot.getLogger().isDebugEnabled()) {
{
bot.getLogger().debug("Writing the backlog feed."); bot.getLogger().debug("Writing the backlog feed.");
} }
output.output(rss, fw); output.output(rss, fw);
} } else {
else
{
bot.getLogger().warn("Unable to generate the backlogs feed. No property configured."); 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); bot.getLogger().warn("Unable to generate the entries feed.", e);
} } finally {
finally try {
{ if (fw != null) {
try
{
if (fw != null)
{
fw.close(); fw.close();
} }
} } catch (Exception ignore) {
catch (Exception ignore)
{
; // Do nothing ; // Do nothing
} }
} }
} } else {
else
{
bot.getLogger() bot.getLogger()
.warn("Unable to generate the entries feed. At least one of the required property is missing."); .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 * @created Jan 31, 2004
* @since 1.0 * @since 1.0
*/ */
public class EntryComment implements Serializable public class EntryComment implements Serializable {
{
/** /**
* The serial version UID. * The serial version UID.
*/ */
@ -55,7 +54,6 @@ public class EntryComment implements Serializable
private final Date date = Calendar.getInstance().getTime(); private final Date date = Calendar.getInstance().getTime();
private String comment = ""; private String comment = "";
private String nick = ""; private String nick = "";
/** /**
@ -64,8 +62,7 @@ public class EntryComment implements Serializable
* @param comment The new comment. * @param comment The new comment.
* @param nick The nickname of the comment's author. * @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.comment = comment;
this.nick = nick; this.nick = nick;
} }
@ -74,8 +71,7 @@ public class EntryComment implements Serializable
* Creates a new comment. * Creates a new comment.
*/ */
@SuppressWarnings("UnusedDeclaration") @SuppressWarnings("UnusedDeclaration")
protected EntryComment() protected EntryComment() {
{
; // Required for serialization. ; // Required for serialization.
} }
@ -84,8 +80,7 @@ public class EntryComment implements Serializable
* *
* @return The comment. * @return The comment.
*/ */
public final String getComment() public final String getComment() {
{
return comment; return comment;
} }
@ -95,8 +90,7 @@ public class EntryComment implements Serializable
* @param comment The actual comment. * @param comment The actual comment.
*/ */
@SuppressWarnings("UnusedDeclaration") @SuppressWarnings("UnusedDeclaration")
public final void setComment(final String comment) public final void setComment(final String comment) {
{
this.comment = comment; this.comment = comment;
} }
@ -106,8 +100,7 @@ public class EntryComment implements Serializable
* @return The date. * @return The date.
*/ */
@SuppressWarnings("UnusedDeclaration") @SuppressWarnings("UnusedDeclaration")
public final Date getDate() public final Date getDate() {
{
return date; return date;
} }
@ -116,8 +109,7 @@ public class EntryComment implements Serializable
* *
* @return The nickname. * @return The nickname.
*/ */
public final String getNick() public final String getNick() {
{
return nick; return nick;
} }
@ -126,8 +118,7 @@ public class EntryComment implements Serializable
* *
* @param nick The new nickname. * @param nick The new nickname.
*/ */
public final void setNick(final String nick) public final void setNick(final String nick) {
{
this.nick = nick; this.nick = nick;
} }
} }

View file

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

View file

@ -48,8 +48,7 @@ import java.util.List;
* @created Feb 1, 2004 * @created Feb 1, 2004
* @since 1.0 * @since 1.0
*/ */
class FeedReader implements Runnable class FeedReader implements Runnable {
{
/** /**
* The maximum number of feed items to display. * 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 sender The nick of the person who sent the message.
* @param url The URL to fetch. * @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.bot = bot;
this.sender = sender; this.sender = sender;
this.url = url; this.url = url;
@ -92,30 +90,23 @@ class FeedReader implements Runnable
/** /**
* Fetches the Feed's items. * Fetches the Feed's items.
*/ */
public final void run() public final void run() {
{ try {
try
{
final SyndFeedInput input = new SyndFeedInput(); final SyndFeedInput input = new SyndFeedInput();
final SyndFeed feed = input.build(new XmlReader(new URL(url))); final SyndFeed feed = input.build(new XmlReader(new URL(url)));
SyndEntry item; SyndEntry item;
final List items = feed.getEntries(); 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); item = (SyndEntryImpl) items.get(i);
bot.send(sender, item.getTitle()); bot.send(sender, item.getTitle());
bot.send(sender, TAB_INDENT + Utils.green(item.getLink())); bot.send(sender, TAB_INDENT + Utils.green(item.getLink()));
} }
} } catch (MalformedURLException e) {
catch (MalformedURLException e)
{
bot.getLogger().debug("Invalid feed URL.", e); bot.getLogger().debug("Invalid feed URL.", e);
bot.send(sender, "The feed URL is invalid."); bot.send(sender, "The feed URL is invalid.");
} } catch (Exception e) {
catch (Exception e)
{
bot.getLogger().debug("Unable to fetch the feed.", e); bot.getLogger().debug("Unable to fetch the feed.", e);
bot.send(sender, "An error has occurred while fetching the feed: " + e.getMessage()); 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 * @created 2016-07-02
* @since 1.0 * @since 1.0
*/ */
public class Tell public class Tell {
{
/** /**
* The all keyword. * The all keyword.
*/ */
@ -61,7 +60,6 @@ public class Tell
/** /**
* The default maximum number of days to keep messages. * The default maximum number of days to keep messages.
*/ */
private static final int DEFAULT_TELL_MAX_DAYS = 7; private static final int DEFAULT_TELL_MAX_DAYS = 7;
/** /**
@ -99,8 +97,7 @@ public class Tell
*/ */
private final String serializedObject; 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.bot = bot;
this.maxDays = Utils.getIntProperty(maxDays, DEFAULT_TELL_MAX_DAYS); this.maxDays = Utils.getIntProperty(maxDays, DEFAULT_TELL_MAX_DAYS);
this.maxSize = Utils.getIntProperty(maxSize, DEFAULT_TELL_MAX_SIZE); this.maxSize = Utils.getIntProperty(maxSize, DEFAULT_TELL_MAX_SIZE);
@ -109,8 +106,7 @@ public class Tell
serializedObject = bot.getLogsDir() + bot.getName() + SER_EXT; serializedObject = bot.getLogsDir() + bot.getName() + SER_EXT;
messages.addAll(TellMessagesMgr.load(serializedObject, bot.getLogger())); messages.addAll(TellMessagesMgr.load(serializedObject, bot.getLogger()));
if (clean()) if (clean()) {
{
save(); save();
} }
} }
@ -120,217 +116,20 @@ public class Tell
* *
* @return <code>True</code> if the queue was cleaned. * @return <code>True</code> if the queue was cleaned.
*/ */
private boolean clean() private boolean clean() {
{ if (bot.getLogger().isDebugEnabled()) {
if (bot.getLogger().isDebugEnabled())
{
bot.getLogger().debug("Cleaning the messages."); bot.getLogger().debug("Cleaning the messages.");
} }
return TellMessagesMgr.clean(messages, maxDays); 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. * Responds with help.
* *
* @param sender The sender. * @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, "To send a message to someone when they join the channel:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + TELL_CMD + " <nick> <message>")); 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) public boolean isEnabled() {
{ return maxSize > 0 && maxDays > 0;
send(nickname, false); }
/**
* 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 nickname The user's nickname.
* @param isMessage The message flag. * @param isMessage The message flag.
*/ */
public void send(final String nickname, final boolean isMessage) public void send(final String nickname, final boolean isMessage) {
{ if (!nickname.equals(bot.getNick()) && isEnabled()) {
if (!nickname.equals(bot.getNick()) && isEnabled()) messages.stream().filter(message -> message.isMatch(nickname)).forEach(
{ message -> {
messages.stream().filter(message -> message.isMatch(nickname)).forEach(message -> { if (message.getRecipient().equalsIgnoreCase(nickname) && !message.isReceived()) {
if (message.getRecipient().equalsIgnoreCase(nickname) && !message.isReceived()) if (message.getSender().equals(nickname)) {
{ if (!isMessage) {
if (message.getSender().equals(nickname)) bot.send(nickname, Utils.bold("You") + " wanted me to remind you: "
{ + Utils.reverseColor(message.getMessage()),
if (!isMessage)
{
bot.send(nickname,
Utils.bold("You") + " wanted me to remind you: " + Utils
.reverseColor(message.getMessage()),
true); true);
message.setIsReceived(); message.setIsReceived();
@ -377,26 +311,22 @@ public class Tell
save(); save();
} }
} } else {
else bot.send(nickname, message.getSender() + " wanted me to tell you: "
{ + Utils.reverseColor(message.getMessage()),
bot.send(nickname,
message.getSender() + " wanted me to tell you: " + Utils
.reverseColor(message.getMessage()),
true); true);
message.setIsReceived(); message.setIsReceived();
save(); save();
} }
} } else if (message.getSender().equalsIgnoreCase(nickname) && message.isReceived()
else if (message.getSender().equalsIgnoreCase(nickname) && message.isReceived() && !message && !message.isNotified()) {
.isNotified())
{
bot.send(nickname, bot.send(nickname,
"Your message " + Utils.reverseColor("[ID " + message.getId() + ']') + " was sent to " "Your message "
+ Utils.bold(message.getRecipient()) + " on " + Utils.UTC_SDF + Utils.reverseColor("[ID " + message.getId() + ']') + " was sent to "
.format(message.getReceived()), + Utils.bold(message.getRecipient()) + " on "
+ Utils.UTC_SDF.format(message.getReceived()),
true); true);
message.setIsNotified(); 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() public void send(final String nickname) {
{ send(nickname, false);
return maxSize > 0 && maxDays > 0;
} }
/** /**
@ -422,8 +351,7 @@ public class Tell
* *
* @return The size. * @return The size.
*/ */
public int size() public int size() {
{
return messages.size(); return messages.size();
} }
} }

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -45,8 +45,7 @@ import java.text.DecimalFormat;
* @created 2016-07-01 * @created 2016-07-01
* @since 1.0 * @since 1.0
*/ */
public class Calc extends AbstractModule public class Calc extends AbstractModule {
{
/** /**
* The Calc command. * The Calc command.
*/ */
@ -55,43 +54,33 @@ public class Calc extends AbstractModule
/** /**
* The default constructor. * The default constructor.
*/ */
public Calc() public Calc() {
{
commands.add(CALC_CMD); commands.add(CALC_CMD);
} }
@Override @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) {
{ if (Utils.isValidString(args)) {
if (Utils.isValidString(args))
{
final DecimalFormat decimalFormat = new DecimalFormat("#.##"); final DecimalFormat decimalFormat = new DecimalFormat("#.##");
try try {
{
final Expression calc = new ExpressionBuilder(args).build(); final Expression calc = new ExpressionBuilder(args).build();
bot.send(bot.getChannel(), args.replaceAll(" ", "") + " = " + decimalFormat.format(calc.evaluate())); bot.send(bot.getChannel(), args.replaceAll(" ", "") + " = " + decimalFormat.format(calc.evaluate()));
} } catch (Exception e) {
catch (Exception e) if (bot.getLogger().isDebugEnabled()) {
{
if (bot.getLogger().isDebugEnabled())
{
bot.getLogger().debug("Unable to calculate: " + args, e); bot.getLogger().debug("Unable to calculate: " + args, e);
} }
bot.send(bot.getChannel(), "No idea. This is the kind of math I don't get."); bot.send(bot.getChannel(), "No idea. This is the kind of math I don't get.");
} }
} } else {
else
{
helpResponse(bot, sender, args, isPrivate); helpResponse(bot, sender, args, isPrivate);
} }
} }
@Override @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, "To solve a mathematical calculation:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + CALC_CMD + " <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 * @created Feb 11, 2004
* @since 1.0 * @since 1.0
*/ */
final public class CurrencyConverter extends AbstractModule final public class CurrencyConverter extends AbstractModule {
{
/** /**
* The currency command. * The currency command.
*/ */
@ -79,23 +78,19 @@ final public class CurrencyConverter extends AbstractModule
/** /**
* The last exchange rates table publication date. * The last exchange rates table publication date.
*/ */
private String pubDate = ""; private static String pubDate = "";
/** /**
* Creates a new {@link CurrencyConverter} instance. * Creates a new {@link CurrencyConverter} instance.
*/ */
public CurrencyConverter() public CurrencyConverter() {
{
commands.add(CURRENCY_CMD); commands.add(CURRENCY_CMD);
} }
@Override @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) {
{ synchronized (this) {
synchronized (this) if (!pubDate.equals(Utils.today())) {
{
if (!pubDate.equals(Utils.today()))
{
EXCHANGE_RATES.clear(); EXCHANGE_RATES.clear();
} }
} }
@ -104,13 +99,11 @@ final public class CurrencyConverter extends AbstractModule
} }
@Override @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, "To convert from one currency to another:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + CURRENCY_CMD + " [100 USD to EUR]")); 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, "For a listing of currency rates:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + CURRENCY_CMD) + ' ' + CURRENCY_RATES_KEYWORD); bot.send(sender, bot.helpIndent(bot.getNick() + ": " + CURRENCY_CMD) + ' ' + CURRENCY_RATES_KEYWORD);
bot.send(sender, "For a listing of supported currencies:"); bot.send(sender, "For a listing of supported currencies:");
@ -121,14 +114,10 @@ final public class CurrencyConverter extends AbstractModule
/** /**
* Converts the specified currencies. * Converts the specified currencies.
*/ */
private void run(final Mobibot bot, final String sender, final String query) private void run(final Mobibot bot, final String sender, final String query) {
{ if (Utils.isValidString(sender)) {
if (Utils.isValidString(sender)) if (EXCHANGE_RATES.isEmpty()) {
{ try {
if (EXCHANGE_RATES.isEmpty())
{
try
{
final SAXBuilder builder = new SAXBuilder(); final SAXBuilder builder = new SAXBuilder();
builder.setIgnoringElementContentWhitespace(true); builder.setIgnoringElementContentWhitespace(true);
@ -143,8 +132,7 @@ final public class CurrencyConverter extends AbstractModule
final List cubes = cubeTime.getChildren(); final List cubes = cubeTime.getChildren();
Element cube; Element cube;
for (final Object rawCube : cubes) for (final Object rawCube : cubes) {
{
cube = (Element) rawCube; cube = (Element) rawCube;
EXCHANGE_RATES.put( EXCHANGE_RATES.put(
cube.getAttribute("currency").getValue(), cube.getAttribute("currency").getValue(),
@ -152,43 +140,29 @@ final public class CurrencyConverter extends AbstractModule
} }
EXCHANGE_RATES.put("EUR", "1"); EXCHANGE_RATES.put("EUR", "1");
} } catch (JDOMException e) {
catch (JDOMException e)
{
bot.getLogger().debug("Unable to parse the exchange rates table.", 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."); 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.getLogger().debug("Unable to fetch the exchange rates table.", e);
bot.send(sender, bot.send(sender,
"An error has occurred while fetching the exchange rates table: " + e.getMessage()); "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.getLogger().debug("The exchange rate table is empty.");
bot.send(sender, "Sorry, but the exchange rate table is empty."); bot.send(sender, "Sorry, but the exchange rate table is empty.");
} } else if (Utils.isValidString(query)) {
else if (Utils.isValidString(query)) if (!EXCHANGE_RATES.isEmpty()) {
{ if (query.matches("\\d+([,\\d]+)?(\\.\\d+)? [a-zA-Z]{3}+ to [a-zA-Z]{3}+")) {
if (!EXCHANGE_RATES.isEmpty())
{
if (query.matches("\\d+([,\\d]+)?(\\.\\d+)? [a-zA-Z]{3}+ to [a-zA-Z]{3}+"))
{
final String[] cmds = query.split(" "); final String[] cmds = query.split(" ");
if (cmds.length == 4) if (cmds.length == 4) {
{ if (cmds[3].equals(cmds[1]) || cmds[0].equals("0")) {
if (cmds[3].equals(cmds[1]) || cmds[0].equals("0"))
{
bot.send(sender, "You're kidding, right?"); bot.send(sender, "You're kidding, right?");
} } else {
else try {
{
try
{
final double amt = Double.parseDouble(cmds[0].replaceAll(",", "")); final double amt = Double.parseDouble(cmds[0].replaceAll(",", ""));
final double from = Double.parseDouble(EXCHANGE_RATES.get(cmds[1].toUpperCase())); final double from = Double.parseDouble(EXCHANGE_RATES.get(cmds[1].toUpperCase()));
final double to = Double.parseDouble(EXCHANGE_RATES.get(cmds[3].toUpperCase())); final double to = Double.parseDouble(EXCHANGE_RATES.get(cmds[3].toUpperCase()));
@ -203,25 +177,19 @@ final public class CurrencyConverter extends AbstractModule
.substring(1) .substring(1)
+ ' ' + ' '
+ cmds[3].toUpperCase()); + cmds[3].toUpperCase());
} } catch (NullPointerException ignored) {
catch (NullPointerException ignored)
{
bot.send(sender, bot.send(sender,
"The supported currencies are: " + EXCHANGE_RATES.keySet().toString()); "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); bot.send(sender, "Last Update: " + pubDate);
final StringBuilder buff = new StringBuilder(0); final StringBuilder buff = new StringBuilder(0);
for (final Map.Entry<String, String> rate : EXCHANGE_RATES.entrySet()) for (final Map.Entry<String, String> rate : EXCHANGE_RATES.entrySet()) {
{ if (buff.length() > 0) {
if (buff.length() > 0)
{
buff.append(", "); buff.append(", ");
} }
buff.append(rate.getKey()).append(": ").append(rate.getValue()); buff.append(rate.getKey()).append(": ").append(rate.getValue());
@ -230,9 +198,7 @@ final public class CurrencyConverter extends AbstractModule
bot.send(sender, buff.toString()); bot.send(sender, buff.toString());
} }
} }
} } else {
else
{
helpResponse(bot, sender, CURRENCY_CMD + ' ' + query, true); helpResponse(bot, sender, CURRENCY_CMD + ' ' + query, true);
bot.send(sender, "The supported currencies are: " + EXCHANGE_RATES.keySet().toString()); 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 * @created 2014-04-28
* @since 1.0 * @since 1.0
*/ */
final public class Dice extends AbstractModule final public class Dice extends AbstractModule {
{
/** /**
* The dice command. * The dice command.
*/ */
@ -53,8 +52,7 @@ final public class Dice extends AbstractModule
/** /**
* The default constructor. * The default constructor.
*/ */
public Dice() public Dice() {
{
commands.add(DICE_CMD); 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. * @param isPrivate Set to <code>true</code> if the response should be sent as a private message.
*/ */
@Override @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(); final Random r = new Random();
int i = r.nextInt(6) + 1; int i = r.nextInt(6) + 1;
@ -86,30 +83,23 @@ final public class Dice extends AbstractModule
bot.action( bot.action(
"rolled two dice: " + Utils.bold(i) + " and " + Utils.bold(y) + " for a total of " + Utils.bold(total)); "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."); bot.action("wins.");
} } else if (playerTotal > total) {
else if (playerTotal > total)
{
bot.action("lost."); bot.action("lost.");
} } else {
else
{
bot.action("tied."); bot.action("tied.");
} }
} }
@Override @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, "To roll the dice:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + DICE_CMD)); bot.send(sender, bot.helpIndent(bot.getNick() + ": " + DICE_CMD));
} }
@Override @Override
public boolean isEnabled() public boolean isEnabled() {
{
return true; return true;
} }
} }

View file

@ -49,8 +49,7 @@ import java.net.URLEncoder;
* @created Feb 7, 2004 * @created Feb 7, 2004
* @since 1.0 * @since 1.0
*/ */
final public class GoogleSearch extends AbstractModule final public class GoogleSearch extends AbstractModule {
{
/** /**
* The Google API Key property. * The Google API Key property.
*/ */
@ -74,40 +73,45 @@ final public class GoogleSearch extends AbstractModule
/** /**
* Creates a new {@link GoogleSearch} instance. * Creates a new {@link GoogleSearch} instance.
*/ */
public GoogleSearch() public GoogleSearch() {
{
commands.add(GOOGLE_CMD); commands.add(GOOGLE_CMD);
properties.put(GOOGLE_API_KEY_PROP, ""); properties.put(GOOGLE_API_KEY_PROP, "");
properties.put(GOOGLE_CSE_KEY_PROP, ""); properties.put(GOOGLE_CSE_KEY_PROP, "");
} }
@Override @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) {
{ if (isEnabled() && args.length() > 0) {
if (isEnabled() && args.length() > 0) if (args.length() > 0) {
{
if (args.length() > 0)
{
new Thread(() -> run(bot, sender, args)).start(); new Thread(() -> run(bot, sender, args)).start();
} else {
helpResponse(bot, sender, args, isPrivate);
} }
else } else {
{
helpResponse(bot, sender, args, isPrivate); helpResponse(bot, sender, args, isPrivate);
} }
} }
else
{ @Override
helpResponse(bot, sender, args, isPrivate); 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. * Searches Google.
*/ */
private void run(final Mobibot bot, final String sender, final String query) private void run(final Mobibot bot, final String sender, final String query) {
{ try {
try
{
final String q = URLEncoder.encode(query, "UTF-8"); final String q = URLEncoder.encode(query, "UTF-8");
final URL url = final URL url =
@ -121,49 +125,24 @@ final public class GoogleSearch extends AbstractModule
final URLConnection conn = url.openConnection(); final URLConnection conn = url.openConnection();
final StringBuilder sb = new StringBuilder(); 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; String line;
while ((line = reader.readLine()) != null) while ((line = reader.readLine()) != null) {
{
sb.append(line); sb.append(line);
} }
final JSONObject json = new JSONObject(sb.toString()); final JSONObject json = new JSONObject(sb.toString());
final JSONArray ja = json.getJSONArray("items"); 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); final JSONObject j = ja.getJSONObject(i);
bot.send(sender, Utils.unescapeXml(j.getString("title"))); bot.send(sender, Utils.unescapeXml(j.getString("title")));
bot.send(sender, TAB_INDENT + Utils.green(j.getString("link"))); 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.getLogger().warn("Unable to search in Google for: " + query, e);
bot.send(sender, "An error has occurred searching in Google: " + e.getMessage()); 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 * @created 2014-04-20
* @since 1.0 * @since 1.0
*/ */
final public class Joke extends AbstractModule final public class Joke extends AbstractModule {
{
/** /**
* The joke command. * The joke command.
*/ */
@ -64,20 +62,17 @@ final public class Joke extends AbstractModule
/** /**
* Creates a new {@link Joke} instance. * Creates a new {@link Joke} instance.
*/ */
public Joke() public Joke() {
{
commands.add(JOKE_CMD); commands.add(JOKE_CMD);
} }
@Override @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(); new Thread(() -> run(bot, sender)).start();
} }
@Override @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, "To retrieve a random joke:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + JOKE_CMD)); 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> * 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) private void run(final Mobibot bot, final String sender) {
{ try {
try
{
final URL url = new URL(JOKE_URL); final URL url = new URL(JOKE_URL);
final URLConnection conn = url.openConnection(); final URLConnection conn = url.openConnection();
final StringBuilder sb = new StringBuilder(); 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; String line;
while ((line = reader.readLine()) != null) while ((line = reader.readLine()) != null) {
{
sb.append(line); sb.append(line);
} }
@ -109,9 +100,7 @@ final public class Joke extends AbstractModule
.replaceAll("\\\"", "\"") .replaceAll("\\\"", "\"")
+ Colors.NORMAL); + Colors.NORMAL);
} }
} } catch (Exception e) {
catch (Exception e)
{
bot.getLogger().warn("Unable to retrieve random joke.", e); bot.getLogger().warn("Unable to retrieve random joke.", e);
bot.send(sender, "An error has occurred retrieving a random joke: " + e.getMessage()); 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 * @created 2014-04-26
* @since 1.0 * @since 1.0
*/ */
final public class Lookup extends AbstractModule final public class Lookup extends AbstractModule {
{
/** /**
* THe lookup command. * THe lookup command.
*/ */
@ -60,113 +59,36 @@ final public class Lookup extends AbstractModule
/** /**
* The default constructor * The default constructor
*/ */
public Lookup() public Lookup() {
{
commands.add(LOOKUP_CMD); 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. * Performs a DNS lookup on the specified query.
* *
* @param query The IP address or hostname. * @param query The IP address or hostname.
*
* @return The lookup query result string. * @return The lookup query result string.
*
* @throws java.net.UnknownHostException If the host is unknown. * @throws java.net.UnknownHostException If the host is unknown.
*/ */
private static String lookup(final String query) private static String lookup(final String query)
throws UnknownHostException throws UnknownHostException {
{
final StringBuilder buffer = new StringBuilder(""); final StringBuilder buffer = new StringBuilder("");
final InetAddress[] results = InetAddress.getAllByName(query); final InetAddress[] results = InetAddress.getAllByName(query);
String hostInfo; String hostInfo;
for (final InetAddress result : results) for (final InetAddress result : results) {
{ if (result.getHostAddress().equals(query)) {
if (result.getHostAddress().equals(query))
{
hostInfo = result.getHostName(); hostInfo = result.getHostName();
if (hostInfo.equals(query)) if (hostInfo.equals(query)) {
{
throw new UnknownHostException(); throw new UnknownHostException();
} }
} } else {
else
{
hostInfo = result.getHostAddress(); hostInfo = result.getHostAddress();
} }
if (buffer.length() > 0) if (buffer.length() > 0) {
{
buffer.append(", "); buffer.append(", ");
} }
@ -180,14 +102,11 @@ final public class Lookup extends AbstractModule
* Performs a whois IP query. * Performs a whois IP query.
* *
* @param query The IP address. * @param query The IP address.
*
* @return The IP whois data, if any. * @return The IP whois data, if any.
*
* @throws java.io.IOException If a connection error occurs. * @throws java.io.IOException If a connection error occurs.
*/ */
private static String[] whois(final String query) private static String[] whois(final String query)
throws IOException throws IOException {
{
return whois(query, WHOIS_HOST); return whois(query, WHOIS_HOST);
} }
@ -196,38 +115,80 @@ final public class Lookup extends AbstractModule
* *
* @param query The IP address. * @param query The IP address.
* @param host The whois host. * @param host The whois host.
*
* @return The IP whois data, if any. * @return The IP whois data, if any.
*
* @throws java.io.IOException If a connection error occurs. * @throws java.io.IOException If a connection error occurs.
*/ */
@SuppressWarnings("WeakerAccess, SameParameterValue") @SuppressWarnings("WeakerAccess, SameParameterValue")
public static String[] whois(final String query, final String host) public static String[] whois(final String query, final String host)
throws IOException throws IOException {
{
final WhoisClient whois = new WhoisClient(); final WhoisClient whois = new WhoisClient();
String[] lines; String[] lines;
try try {
{
whois.setDefaultTimeout(Mobibot.CONNECT_TIMEOUT); whois.setDefaultTimeout(Mobibot.CONNECT_TIMEOUT);
whois.connect(host); whois.connect(host);
whois.setSoTimeout(Mobibot.CONNECT_TIMEOUT); whois.setSoTimeout(Mobibot.CONNECT_TIMEOUT);
whois.setSoLinger(false, 0); whois.setSoLinger(false, 0);
lines = whois.query('-' + query).split("\n"); lines = whois.query('-' + query).split("\n");
} } finally {
finally
{
whois.disconnect(); whois.disconnect();
} }
return lines; 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 @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, "To perform a DNS lookup query:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + LOOKUP_CMD + " <ip address or hostname>")); 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 * @created 2016-07-02
* @since 1.0 * @since 1.0
*/ */
public class Ping extends AbstractModule public class Ping extends AbstractModule {
{
/** /**
* The ping responses. * 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.", "is trying to stay awake.",
"has gone fishing.", "has gone fishing.",
"is somewhere over the rainbow.", "is somewhere over the rainbow.",
@ -70,22 +71,19 @@ public class Ping extends AbstractModule
/** /**
* The default constructor. * The default constructor.
*/ */
public Ping() public Ping() {
{
commands.add(PING_CMD); commands.add(PING_CMD);
} }
@Override @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(); final Random r = new Random();
bot.action(PINGS.get(r.nextInt(PINGS.size()))); bot.action(PINGS.get(r.nextInt(PINGS.size())));
} }
@Override @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, "To ping the bot:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + PING_CMD)); bot.send(sender, bot.helpIndent(bot.getNick() + ": " + PING_CMD));
} }

View file

@ -45,8 +45,7 @@ import java.io.IOException;
* @created Feb 7, 2004 * @created Feb 7, 2004
* @since 1.0 * @since 1.0
*/ */
final public class StockQuote extends AbstractModule final public class StockQuote extends AbstractModule {
{
/** /**
* The quote command. * The quote command.
*/ */
@ -60,27 +59,21 @@ final public class StockQuote extends AbstractModule
/** /**
* Creates a new {@link StockQuote} instance. * Creates a new {@link StockQuote} instance.
*/ */
public StockQuote() public StockQuote() {
{
commands.add(STOCK_CMD); commands.add(STOCK_CMD);
} }
@Override @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) {
{ if (args.length() > 0) {
if (args.length() > 0)
{
new Thread(() -> run(bot, sender, args)).start(); new Thread(() -> run(bot, sender, args)).start();
} } else {
else
{
helpResponse(bot, sender, args, isPrivate); helpResponse(bot, sender, args, isPrivate);
} }
} }
@Override @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, "To retrieve a stock quote:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + STOCK_CMD + " <symbol[.country code]>")); 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! * Returns the specified stock quote from Yahoo!
*/ */
private void run(final Mobibot bot, final String sender, final String symbol) private void run(final Mobibot bot, final String sender, final String symbol) {
{ try {
try
{
final HttpClient client = new HttpClient(); final HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(Mobibot.CONNECT_TIMEOUT); client.getHttpConnectionManager().getParams().setConnectionTimeout(Mobibot.CONNECT_TIMEOUT);
client.getHttpConnectionManager().getParams().setSoTimeout(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()); final String[][] lines = CSVParser.parse(getMethod.getResponseBodyAsString());
if (lines.length > 0) if (lines.length > 0) {
{
final String[] quote = lines[0]; final String[] quote = lines[0];
if (quote.length > 0) if (quote.length > 0) {
{ if ((quote.length > 3) && (!"N/A".equalsIgnoreCase(quote[3]))) {
if ((quote.length > 3) && (!"N/A".equalsIgnoreCase(quote[3])))
{
bot.send(bot.getChannel(), "Symbol: " + quote[0] + " [" + quote[1] + ']'); 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] + ')'); bot.send(bot.getChannel(), "Last Trade: " + quote[2] + " (" + quote[5] + ')');
} } else {
else
{
bot.send(bot.getChannel(), "Last Trade: " + quote[2]); bot.send(bot.getChannel(), "Last Trade: " + quote[2]);
} }
if (quote.length > 4) if (quote.length > 4) {
{
bot.send(sender, "Time: " + quote[3] + ' ' + quote[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]); 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]); 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]); bot.send(sender, "Volume: " + quote[9]);
} }
} } else {
else
{
bot.send(sender, "Invalid ticker symbol."); bot.send(sender, "Invalid ticker symbol.");
} }
} } else {
else
{
bot.send(sender, "No values returned."); bot.send(sender, "No values returned.");
} }
} } else {
else
{
bot.send(sender, "No data returned."); bot.send(sender, "No data returned.");
} }
} } catch (IOException e) {
catch (IOException e)
{
bot.getLogger().debug("Unable to retrieve stock quote for: " + symbol, 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()); 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 * @created Sept 10, 2008
* @since 1.0 * @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_KEY_PROP = "twitter-consumerKey";
private final static String CONSUMER_SECRET_PROP = "twitter-consumerSecret"; private final static String CONSUMER_SECRET_PROP = "twitter-consumerSecret";
private final static String TOKEN_PROP = "twitter-token"; private final static String TOKEN_PROP = "twitter-token";
private final static String TOKEN_SECRET_PROP = "twitter-tokenSecret"; 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. * Creates a new {@link Twitter} instance.
*/ */
public Twitter() public Twitter() {
{
commands.add(TWITTER_CMD); commands.add(TWITTER_CMD);
properties.put(CONSUMER_SECRET_PROP, ""); properties.put(CONSUMER_SECRET_PROP, "");
properties.put(CONSUMER_KEY_PROP, ""); properties.put(CONSUMER_KEY_PROP, "");
@ -71,45 +66,34 @@ final public class Twitter extends AbstractModule
} }
@Override @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) {
{ if (isEnabled() && args.length() > 0) {
if (isEnabled() && args.length() > 0)
{
new Thread(() -> run(bot, sender, args)).start(); new Thread(() -> run(bot, sender, args)).start();
} } else {
else
{
helpResponse(bot, sender, args, isPrivate); helpResponse(bot, sender, args, isPrivate);
} }
} }
@Override @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) {
{ if (isEnabled()) {
if (isEnabled())
{
bot.send(sender, "To post to Twitter:"); bot.send(sender, "To post to Twitter:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + TWITTER_CMD + " <message>")); bot.send(sender, bot.helpIndent(bot.getNick() + ": " + TWITTER_CMD + " <message>"));
} } else {
else
{
bot.send(sender, "The Twitter posting facility is disabled."); bot.send(sender, "The Twitter posting facility is disabled.");
} }
} }
@Override @Override
public boolean isEnabled() public boolean isEnabled() {
{
return isValidProperties(); return isValidProperties();
} }
/** /**
* Posts to twitter. * Posts to twitter.
*/ */
private void run(final Mobibot bot, final String sender, final String message) private void run(final Mobibot bot, final String sender, final String message) {
{ try {
try
{
final ConfigurationBuilder cb = new ConfigurationBuilder(); final ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true) cb.setDebugEnabled(true)
.setOAuthConsumerKey(properties.get(CONSUMER_KEY_PROP)) .setOAuthConsumerKey(properties.get(CONSUMER_KEY_PROP))
@ -124,9 +108,7 @@ final public class Twitter extends AbstractModule
bot.send(sender, bot.send(sender,
"You message was posted to http://twitter.com/" + twitter.getScreenName() + "/statuses/" + status "You message was posted to http://twitter.com/" + twitter.getScreenName() + "/statuses/" + status
.getId()); .getId());
} } catch (Exception e) {
catch (Exception e)
{
bot.getLogger().warn("Unable to post to Twitter: " + message, e); bot.getLogger().warn("Unable to post to Twitter: " + message, e);
bot.send(sender, "An error has occurred: " + e.getMessage()); bot.send(sender, "An error has occurred: " + e.getMessage());
} }

View file

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

View file

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

View file

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

View file

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