Updated to new SwingWorker.

More Java 8 optimizations.
This commit is contained in:
Erik C. Thauvin 2016-07-16 00:54:47 -07:00
parent 9e601d45ef
commit 5c8951a0a8
18 changed files with 497 additions and 622 deletions

View file

@ -1,27 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<module external.linked.project.id="mobibot" external.linked.project.path="$MODULE_DIR$/../.." external.root.project.path="$MODULE_DIR$/../.." external.system.id="GRADLE" external.system.module.group="" external.system.module.version="0.6.1-beta+008" type="JAVA_MODULE" version="4">
<module external.linked.project.id="mobibot" external.linked.project.path="$MODULE_DIR$/../.." external.root.project.path="$MODULE_DIR$/../.." external.system.id="GRADLE" external.system.module.group="" external.system.module.version="0.7.0-beta+006" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="false">
<output url="file://$MODULE_DIR$/../../build/classes/main" />
<output-test url="file://$MODULE_DIR$/../../build/classes/test" />
<exclude-output />
<content url="file://$MODULE_DIR$/../..">
<sourceFolder url="file://$MODULE_DIR$/../../src/generated/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/../../src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/../../src/test/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/../../src/annotationProcessor/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/../../src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/../../src/test/resources" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/../../src/generated/java" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/../../.gradle" />
<excludeFolder url="file://$MODULE_DIR$/../../build" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Gradle: log4j:log4j:1.2.17" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Gradle: net.thauvin.erik:semver:0.9.6-beta" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Gradle: commons-lang:commons-lang:2.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Gradle: commons-collections:commons-collections:3.2.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Gradle: org.apache.velocity:velocity:1.7" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Gradle: net.thauvin.erik:semver:0.9.5-beta" level="project" />
<orderEntry type="library" name="Gradle: org.slf4j:slf4j-api:1.7.16" level="project" />
<orderEntry type="library" name="Gradle: org.jdom:jdom2:2.0.6" level="project" />
<orderEntry type="library" name="Gradle: com.rometools:rome-utils:1.6.1" level="project" />
<orderEntry type="library" name="Gradle: net.sf.delicious-java:delicious:1.14" level="project" />
@ -39,5 +38,7 @@
<orderEntry type="library" name="Gradle: commons-logging:commons-logging:1.2" level="project" />
<orderEntry type="library" name="Gradle: commons-codec:commons-codec:1.10" level="project" />
<orderEntry type="library" name="Gradle: pircbot:pircbot:1.5.0" level="project" />
<orderEntry type="library" name="Gradle: org.slf4j:slf4j-log4j12:1.7.21" level="project" />
<orderEntry type="library" name="Gradle: org.slf4j:slf4j-api:1.7.21" level="project" />
</component>
</module>

View file

@ -74,12 +74,12 @@ dependencies {
compile 'org.twitter4j:twitter4j-core:4.0.4'
compile 'net.sf.delicious-java:delicious:1.14'
compileOnly 'net.thauvin.erik:semver:0.9.5-beta'
compileOnly 'net.thauvin.erik:semver:0.9.6-beta'
}
annotationProcessor {
project.version = getVersion(isRelease)
library 'net.thauvin.erik:semver:0.9.5-beta'
library 'net.thauvin.erik:semver:0.9.6-beta'
processor 'net.thauvin.erik.semver.VersionProcessor'
}

View file

@ -70,6 +70,9 @@
<option name="fileTypeOverride" value="3" />
<option name="addBlankAfter" value="false" />
</LanguageOptions>
<LanguageOptions name="__TEMPLATE__">
<option name="addBlankAfter" value="false" />
</LanguageOptions>
</component>
<component name="DependencyValidationManager">
<scope name="Source" pattern="file[mobibot]:src/generated/java//*||file[mobibot]:src/main/java//*" />
@ -183,6 +186,12 @@
</MavenGeneralSettings>
</option>
</component>
<component name="ProjectCodeStyleSettingsManager">
<option name="PER_PROJECT_SETTINGS">
<value />
</option>
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Erik's Code Style" />
</component>
<component name="ProjectInspectionProfilesVisibleTreeState">
<entry key="Project Default">
<profile-state>
@ -440,13 +449,13 @@
<root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/net.sourceforge.jweather/jweather/0.3.0/385ecc27f62f9d7c31de57cee468a8df58cb415e/jweather-0.3.0-sources.jar!/" />
</SOURCES>
</library>
<library name="Gradle: net.thauvin.erik:semver:0.9.5-beta">
<library name="Gradle: net.thauvin.erik:semver:0.9.6-beta">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/net/thauvin/erik/semver/0.9.5-beta/semver-0.9.5-beta.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/net/thauvin/erik/semver/0.9.6-beta/semver-0.9.6-beta.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/net/thauvin/erik/semver/0.9.5-beta/semver-0.9.5-beta-sources.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/net/thauvin/erik/semver/0.9.6-beta/semver-0.9.6-beta-sources.jar!/" />
</SOURCES>
</library>
<library name="Gradle: org.apache.velocity:velocity:1.7">
@ -494,13 +503,22 @@
<root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.ostermiller/utils/1.07.00/586774ee4b8409b6835621bae2186d9b54d1c36a/utils-1.07.00-sources.jar!/" />
</SOURCES>
</library>
<library name="Gradle: org.slf4j:slf4j-api:1.7.16">
<library name="Gradle: org.slf4j:slf4j-api:1.7.21">
<CLASSES>
<root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.slf4j/slf4j-api/1.7.16/3a6274f658487d5bfff9af3862beff6da1e7fd52/slf4j-api-1.7.16.jar!/" />
<root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.slf4j/slf4j-api/1.7.21/139535a69a4239db087de9bab0bee568bf8e0b70/slf4j-api-1.7.21.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.slf4j/slf4j-api/1.7.16/974c5dd98f38036bd98b3a8f7bf00ee0d91adbdd/slf4j-api-1.7.16-sources.jar!/" />
<root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.slf4j/slf4j-api/1.7.21/f285ac123f201fb4b028bac556928d7cf527ef48/slf4j-api-1.7.21-sources.jar!/" />
</SOURCES>
</library>
<library name="Gradle: org.slf4j:slf4j-log4j12:1.7.21">
<CLASSES>
<root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.slf4j/slf4j-log4j12/1.7.21/7238b064d1aba20da2ac03217d700d91e02460fa/slf4j-log4j12-1.7.21.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.slf4j/slf4j-log4j12/1.7.21/16b1333786ea93d16bff6fb0f5e3b82716d1b008/slf4j-log4j12-1.7.21-sources.jar!/" />
</SOURCES>
</library>
<library name="Gradle: org.twitter4j:twitter4j-core:4.0.4">

View file

@ -3,6 +3,8 @@ server=irc.freenode.net
#port=6667
login=mobibot
nick=mobibot
# NickServ password
ident=changepwd
#ident-nick=nickserv
#ident-msg=IDENTIFY changepwd

View file

@ -13,15 +13,15 @@ import java.util.Date;
* Annotation Processor</a>
*/
public final class ReleaseInfo {
private final static String buildmeta = "005";
private final static Date date = new Date(1467669995645L);
private final static int major = 0;
private final static int minor = 7;
private final static int patch = 0;
private final static String prerelease = "beta";
private final static String project = "mobibot";
private final static String buildmeta = "006";
private final static Date date = new Date(1468655027549L);
private final static int major = 0;
private final static int minor = 7;
private final static int patch = 0;
private final static String prerelease = "beta";
private final static String project = "mobibot";
/**
/**
* Disables the default constructor.
*
* @throws UnsupportedOperationException If the constructor is called.
@ -71,7 +71,7 @@ public final class ReleaseInfo {
return Integer.toString(getMajor()) + '.'
+ Integer.toString(getMinor()) + '.'
+ Integer.toString(getPatch())
+ getPreRelease() + getBuildMetadata();
+ getPreRelease(true) + getBuildMetadata(true);
}
/**
@ -101,14 +101,46 @@ public final class ReleaseInfo {
return patch;
}
/**
* Returns the pre-release version.
*
* @param isHyphen Prepend a hyphen, if <code>true</code>.
* @return The pre-release version, if any.
*/
public static String getPreRelease(final boolean isHyphen) {
if (prerelease.length() > 0) {
if (isHyphen) {
return '-' + prerelease;
} else {
return prerelease;
}
}
return "";
}
/**
* Returns the pre-release version.
*
* @return The pre-release version, if any.
*/
public static String getPreRelease() {
if (prerelease.length() > 0) {
return '-' + prerelease;
return getPreRelease(false);
}
/**
* Returns the build metadata.
*
* @param isPlus Prepend a plus sign, if <code>true</code>.
* @return The build metadata, if any.
*/
public static String getBuildMetadata(final boolean isPlus) {
if (buildmeta.length() > 0) {
if (isPlus) {
return '+' + buildmeta;
} else {
return buildmeta;
}
}
return "";
@ -120,10 +152,6 @@ public final class ReleaseInfo {
* @return The build metadata, if any.
*/
public static String getBuildMetadata() {
if (buildmeta.length() > 0) {
return '+' + buildmeta;
}
return "";
return getBuildMetadata(false);
}
}

View file

@ -33,6 +33,8 @@ package net.thauvin.erik.mobibot;
import del.icio.us.Delicious;
import javax.swing.*;
/**
* The class to handle posts to del.icio.us.
*
@ -49,8 +51,8 @@ class DeliciousPoster
/**
* Creates a new {@link DeliciousPoster} instance.
*
* @param username The del.icio.us user name.
* @param password The del.icio.us password.
* @param username The del.icio.us user name.
* @param password The del.icio.us password.
* @param ircServer The IRC server.
*/
public DeliciousPoster(final String username, final String password, final String ircServer)
@ -66,19 +68,21 @@ class DeliciousPoster
*/
public final void addPost(final EntryLink entry)
{
final SwingWorker worker = new SwingWorker()
final SwingWorker<Boolean, Void> worker = new SwingWorker<Boolean, Void>()
{
public Object construct()
@Override
protected Boolean doInBackground()
throws Exception
{
return delicious.addPost(entry.getLink(),
entry.getTitle(),
postedBy(entry),
entry.getDeliciousTags(),
entry.getDate());
entry.getTitle(),
postedBy(entry),
entry.getDeliciousTags(),
entry.getDate());
}
};
worker.start();
worker.execute();
}
/**
@ -102,52 +106,56 @@ class DeliciousPoster
{
final String link = entry.getLink();
final SwingWorker worker = new SwingWorker()
final SwingWorker<Boolean, Void> worker = new SwingWorker<Boolean, Void>()
{
public Object construct()
@Override
protected Boolean doInBackground()
throws Exception
{
return delicious.deletePost(link);
}
};
worker.start();
worker.execute();
}
/**
* Updates a post to del.icio.us.
*
* @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)
{
final SwingWorker worker = new SwingWorker()
final SwingWorker<Boolean, Void> worker = new SwingWorker<Boolean, Void>()
{
public Object construct()
@Override
protected Boolean doInBackground()
throws Exception
{
if (!oldUrl.equals(entry.getLink()))
{
delicious.deletePost(oldUrl);
return delicious.addPost(entry.getLink(),
entry.getTitle(),
postedBy(entry),
entry.getDeliciousTags(),
entry.getDate());
entry.getTitle(),
postedBy(entry),
entry.getDeliciousTags(),
entry.getDate());
}
else
{
return delicious.addPost(entry.getLink(),
entry.getTitle(),
postedBy(entry),
entry.getDeliciousTags(),
entry.getDate(),
true,
true);
entry.getTitle(),
postedBy(entry),
entry.getDeliciousTags(),
entry.getDate(),
true,
true);
}
}
};
worker.start();
worker.execute();
}
}

View file

@ -87,21 +87,18 @@ final class EntriesMgr
* @param file The file containing the backlogs.
* @param history The history list.
*
* @throws FileNotFoundException If the file was not found.
* @throws IOException If the file was not found or could not be read.
* @throws FeedException If an error occurred while reading the feed.
*/
public static void loadBacklogs(final String file, final List<String> history)
throws FileNotFoundException, FeedException
throws IOException, FeedException
{
history.clear();
final SyndFeedInput input = new SyndFeedInput();
InputStreamReader reader = null;
try
try (final InputStreamReader reader = new InputStreamReader(new FileInputStream(new File(file))))
{
reader = new InputStreamReader(new FileInputStream(new File(file)));
final SyndFeed feed = input.build(reader);
@ -114,20 +111,6 @@ final class EntriesMgr
history.add(item.getTitle());
}
}
finally
{
if (reader != null)
{
try
{
reader.close();
}
catch (IOException ignore)
{
; // Do nothing
}
}
}
}
/**
@ -139,24 +122,21 @@ final class EntriesMgr
*
* @return The feed's last published date.
*
* @throws FileNotFoundException If the file was not found.
* @throws IOException If the file was not found or could not be read.
* @throws FeedException If an error occurred while reading the feed.
*/
@SuppressWarnings("unchecked")
public static String loadEntries(final String file, final String channel, final List<EntryLink> entries)
throws FileNotFoundException, FeedException
throws IOException, FeedException
{
entries.clear();
final SyndFeedInput input = new SyndFeedInput();
String today;
InputStreamReader reader = null;
final String today;
try
try (InputStreamReader reader = new InputStreamReader(new FileInputStream(new File(file))))
{
reader = new InputStreamReader(new FileInputStream(new File(file)));
final SyndFeed feed = input.build(reader);
today = Utils.ISO_SDF.format(feed.getPublishedDate());
@ -196,20 +176,6 @@ final class EntriesMgr
entries.add(entry);
}
}
finally
{
if (reader != null)
{
try
{
reader.close();
}
catch (IOException ignore)
{
; // Do nothing
}
}
}
return today;
}

View file

@ -122,13 +122,30 @@ public class Mobibot extends PircBot
* The version strings.
*/
private static final String[] VERSION_STRS = {
"Version: " + ReleaseInfo.getVersion() + " (" + Utils.ISO_SDF.format(ReleaseInfo.getBuildDate()) + ')',
"Platform: " + System.getProperty("os.name") + " (" + System.getProperty("os.version") + ", " + System
.getProperty("os.arch") + ", " + System.getProperty("user.country") + ')',
"Runtime: " + System.getProperty("java.runtime.name") + " (build " + System
.getProperty("java.runtime.version") + ')',
"VM: " + System.getProperty("java.vm.name") + " (build " + System.getProperty("java.vm.version") + ", "
+ System.getProperty("java.vm.info") + ')'
"Version: "
+ ReleaseInfo.getVersion()
+ " ("
+ Utils.ISO_SDF.format(ReleaseInfo.getBuildDate()) + ')',
"Platform: "
+ System.getProperty("os.name")
+ " ("
+ System.getProperty("os.version")
+ ", "
+ System.getProperty("os.arch")
+ ", "
+ System.getProperty("user.country") + ')',
"Runtime: "
+ System.getProperty("java.runtime.name")
+ " (build "
+ System.getProperty("java.runtime.version")
+ ')',
"VM: "
+ System.getProperty("java.vm.name")
+ " (build "
+ System.getProperty("java.vm.version")
+ ", "
+ System.getProperty("java.vm.info")
+ ')'
};
/**
@ -211,11 +228,6 @@ public class Mobibot extends PircBot
*/
private String feedURL = "";
/**
* The NickServ ident password.
*/
private String ident = "";
/**
* The ident message.
*/
@ -226,6 +238,11 @@ public class Mobibot extends PircBot
*/
private String identNick = "";
/**
* The NickServ ident password.
*/
private String identPwd = "";
/**
* Today's date.
*/
@ -239,15 +256,18 @@ public class Mobibot extends PircBot
/**
* Creates a new {@link Mobibot} instance.
*
* @param server The server.
* @param port The port.
* @param server The server.
* @param port The port.
* @param nickname The nickname.
* @param channel The channel.
* @param logsDir The logs directory.
* @param channel The channel.
* @param logsDir The logs directory.
*/
@SuppressWarnings("WeakerAccess")
public Mobibot(final String server, final int port, final String nickname, final String channel,
final String logsDir)
public Mobibot(final String server,
final int port,
final String nickname,
final String channel,
final String logsDir)
{
System.getProperties().setProperty("sun.net.client.defaultConnectTimeout", String.valueOf(CONNECT_TIMEOUT));
System.getProperties().setProperty("sun.net.client.defaultReadTimeout", String.valueOf(CONNECT_TIMEOUT));
@ -281,7 +301,7 @@ public class Mobibot extends PircBot
today = Utils.today();
}
}
catch (FileNotFoundException ignore)
catch (IOException ignore)
{
; // Do nothing.
}
@ -295,7 +315,7 @@ public class Mobibot extends PircBot
{
EntriesMgr.loadBacklogs(this.logsDir + EntriesMgr.NAV_XML, history);
}
catch (FileNotFoundException ignore)
catch (IOException ignore)
{
; // Do nothing.
}
@ -329,12 +349,11 @@ public class Mobibot extends PircBot
// Setup the command line options
final Options options = new Options();
options.addOption(Commands.HELP_ARG.substring(0, 1), Commands.HELP_ARG, false, "print this help message");
options.addOption(Commands.DEBUG_ARG.substring(0, 1),
Commands.DEBUG_ARG,
false,
"print debug & logging data directly to the console");
options.addOption(Option.builder(Commands.PROPS_ARG.substring(0, 1)).hasArg().argName("file")
.desc("use alternate properties file").longOpt(Commands.PROPS_ARG).build());
options.addOption(Commands.DEBUG_ARG.substring(0, 1), Commands.DEBUG_ARG, false,
"print debug & logging data directly to the console");
options.addOption(Option.builder(
Commands.PROPS_ARG.substring(0, 1)).hasArg().argName("file").desc("use " + "alternate properties file")
.longOpt(Commands.PROPS_ARG).build());
options.addOption(Commands.VERSION_ARG.substring(0, 1), Commands.VERSION_ARG, false, "print version info");
// Parse the command line
@ -366,14 +385,11 @@ public class Mobibot extends PircBot
}
else
{
FileInputStream fis = null;
final Properties p = new Properties();
try
try (final FileInputStream fis = new FileInputStream(
new File(line.getOptionValue(Commands.PROPS_ARG.charAt(0), "./mobibot.properties"))))
{
fis = new FileInputStream(new File(line.getOptionValue(Commands.PROPS_ARG.charAt(0),
"./mobibot.properties")));
// Load the properties files
p.load(fis);
}
@ -389,20 +405,6 @@ public class Mobibot extends PircBot
e.printStackTrace(System.err);
System.exit(1);
}
finally
{
if (fis != null)
{
try
{
fis.close();
}
catch (IOException ignore)
{
; // Do nothing
}
}
}
// Get the main properties
final String channel = p.getProperty("channel");
@ -453,7 +455,7 @@ public class Mobibot extends PircBot
final String ignoredNicks = p.getProperty("ignore", "");
final String identNick = p.getProperty("ident-nick", "");
final String identMsg = p.getProperty("ident-msg", "");
final String ident = p.getProperty("ident", "");
final String identPwd = p.getProperty("ident", "");
final String tags = p.getProperty("tags", "");
// Get the del.icio.us properties
@ -472,13 +474,7 @@ public class Mobibot extends PircBot
bot.setLogin(login);
bot.setVersion(weblogURL);
bot.setMessageDelay(MESSAGE_DELAY);
// Set the ident password
bot.setIdent(ident);
// Set the ident nick and message
bot.setIdentNick(identNick);
bot.setIdentMsg(identMsg);
bot.setIdentity(identPwd, identNick, identMsg);
// Set the URLs
bot.setWeblogUrl(weblogURL);
@ -492,12 +488,14 @@ public class Mobibot extends PircBot
}
// Load the modules properties
MODULES.stream().filter(AbstractModule::hasProperties).forEach(module -> {
for (final String s : module.getPropertyKeys())
{
module.setProperty(s, p.getProperty(s, ""));
}
});
MODULES.stream().filter(AbstractModule::hasProperties).forEach(
module ->
{
for (final String s : module.getPropertyKeys())
{
module.setProperty(s, p.getProperty(s, ""));
}
});
// Set the tags
bot.setTags(tags);
@ -540,111 +538,12 @@ public class Mobibot extends PircBot
bot.setVersion(INFO_STRS[0]);
// Identify with NickServ
if (Utils.isValidString(ident))
{
bot.identify(ident);
}
// Identify with a specified nick
if (Utils.isValidString(identNick) && Utils.isValidString(identMsg))
{
bot.sendMessage(identNick, identMsg);
}
bot.identify();
bot.joinChannel(channel);
}
}
/**
* Sets the ident password.
*
* @param pwd The password.
*/
private void setIdent(final String pwd)
{
ident = pwd;
}
/**
* Sets the ident nickname.
*
* @param nick The nickname.
*/
private void setIdentNick(final String nick)
{
identNick = nick;
}
/**
* Sets the ident message.
*
* @param msg The message.
*/
private void setIdentMsg(final String msg)
{
identMsg = msg;
}
/**
* Sets the feed URL.
*
* @param feedURL The feed URL.
*/
private void setFeedURL(final String feedURL)
{
this.feedURL = feedURL;
}
/**
* Sets the del.icio.us authentication.
*
* @param username The del.icio.us user name.
* @param password The del.icio.us password.
*/
private void setDeliciousAuth(final String username, final String password)
{
delicious = new DeliciousPoster(username, password, ircServer);
}
/**
* Sets the default tags/categories.
*
* @param tags The tags.
*/
private void setTags(final String tags)
{
defaultTags = tags;
}
/**
* Sets the Ignored nicks.
*
* @param nicks The nicks to ignore
*/
private void setIgnoredNicks(final String nicks)
{
if (Utils.isValidString(nicks))
{
final StringTokenizer st = new StringTokenizer(nicks, ",");
while (st.hasMoreTokens())
{
ignoredNicks.add(st.nextToken().trim().toLowerCase());
}
}
}
/**
* Saves the entries.
*
* @param isDayBackup Set the true if the daily backup file should also be created.
*/
private void saveEntries(final boolean isDayBackup)
{
EntriesMgr.saveEntries(this, entries, history, isDayBackup);
}
/**
* Sleeps for the specified number of seconds.
*
@ -676,7 +575,7 @@ public class Mobibot extends PircBot
* Sends an action to the channel.
*
* @param channel The channel.
* @param action The action.
* @param action The action.
*/
private void action(final String channel, final String action)
{
@ -807,8 +706,9 @@ public class Mobibot extends PircBot
if (Character.isLetter(c))
{
buff.append('[').append(String.valueOf(c).toLowerCase()).append(String.valueOf(c).toUpperCase())
.append(']');
buff.append('[')
.append(String.valueOf(c).toLowerCase()).append(String.valueOf(c).toUpperCase())
.append(']');
}
else
{
@ -864,7 +764,7 @@ public class Mobibot extends PircBot
/**
* Returns indented help string.
*
* @param help The help string.
* @param help The help string.
* @param isBold The bold flag.
*
* @return The indented help string.
@ -878,7 +778,7 @@ public class Mobibot extends PircBot
* Responds with the bot's help.
*
* @param sender The nick of the person who sent the private message.
* @param topic The help topic, if any.
* @param topic The help topic, if any.
*/
private void helpResponse(final String sender, final String topic)
{
@ -997,8 +897,8 @@ public class Mobibot extends PircBot
commandsList.add(Commands.USERS_CMD);
commandsList.add(Commands.VIEW_CMD);
MODULES.stream().filter(AbstractModule::isEnabled)
.forEach(module -> commandsList.addAll(module.getCommands()));
MODULES.stream().filter(AbstractModule::isEnabled).forEach(
module -> commandsList.addAll(module.getCommands()));
if (tell.isEnabled())
{
@ -1032,18 +932,39 @@ public class Mobibot extends PircBot
if (isOp(sender))
{
send(sender, "The op commands are:");
send(sender,
helpIndent(Commands.CYCLE_CMD + " " + Commands.ME_CMD + " " + Commands.MSG_CMD + " "
+ Commands.SAY_CMD + " " + Commands.VERSION_CMD));
send(sender, helpIndent(
Commands.CYCLE_CMD + " "
+ Commands.ME_CMD + " "
+ Commands.MSG_CMD + " "
+ Commands.SAY_CMD + " "
+ Commands.VERSION_CMD));
}
}
}
/**
* Identifies the bot.
*/
private void identify()
{
// Identify with NickServ
if (Utils.isValidString(identPwd))
{
identify(identPwd);
}
// Identify with a specified nick
if (Utils.isValidString(identNick) && Utils.isValidString(identMsg))
{
sendMessage(identNick, identMsg);
}
}
/**
* Processes the {@link net.thauvin.erik.mobibot.Commands#IGNORE_CMD} command.
*
* @param sender The sender.
* @param args The command arguments.
* @param args The command arguments.
*/
private void ignoreResponse(final String sender, final String args)
{
@ -1110,7 +1031,7 @@ public class Mobibot extends PircBot
/**
* Responds with the bot's information.
*
* @param sender The nick of the person who sent the message.
* @param sender The nick of the person who sent the message.
* @param isPrivate Set to true is the response should be send as a private message.
*/
private void infoResponse(final String sender, final boolean isPrivate)
@ -1213,6 +1134,19 @@ public class Mobibot extends PircBot
return false;
}
@Override
protected final void onAction(final String sender,
final String login,
final String hostname,
final String target,
final String action)
{
if (target.equals(channel))
{
storeRecap(sender, action, true);
}
}
@Override
protected final void onDisconnect()
{
@ -1260,22 +1194,23 @@ public class Mobibot extends PircBot
setVersion(INFO_STRS[0]);
if (Utils.isValidString(ident))
{
identify(ident);
}
if (Utils.isValidString(identNick) && Utils.isValidString(identMsg))
{
sendMessage(identNick, identMsg);
}
identify();
joinChannel(channel);
}
@Override
protected final void onMessage(final String channel, final String sender, final String login, final String hostname,
final String message)
protected void onJoin(final String channel, final String sender, final String login, final String hostname)
{
tell.send(sender);
}
@Override
protected final void onMessage(final String channel,
final String sender,
final String login,
final String hostname,
final String message)
{
if (logger.isDebugEnabled())
{
@ -1690,15 +1625,23 @@ public class Mobibot extends PircBot
if (!isCommand)
{
recap(sender, message, false);
storeRecap(sender, message, false);
}
tell.send(sender, true);
}
@Override
protected final void onPrivateMessage(final String sender, final String login, final String hostname,
final String message)
protected void onNickChange(final String oldNick, final String login, final String hostname, final String newNick)
{
tell.send(newNick);
}
@Override
protected final void onPrivateMessage(final String sender,
final String login,
final String hostname,
final String message)
{
if (logger.isDebugEnabled())
{
@ -1860,50 +1803,10 @@ public class Mobibot extends PircBot
}
}
@Override
protected final void onAction(final String sender, final String login, final String hostname, final String target,
final String action)
{
if (target.equals(channel))
{
recap(sender, action, true);
}
}
/**
* Stores the last 10 public messages and actions.
*
* @param sender The nick of the person who sent the private message.
* @param message The actual message sent.
* @param isAction Set to true if the message is an action.
*/
private void recap(final String sender, final String message, final boolean isAction)
{
recap.add(Utils.UTC_SDF.format(Calendar.getInstance().getTime()) + " -> " + sender + (isAction ? " " : ": ")
+ message);
if (recap.size() > MAX_RECAP)
{
recap.remove(0);
}
}
@Override
protected void onJoin(final String channel, final String sender, final String login, final String hostname)
{
tell.send(sender);
}
@Override
protected void onNickChange(final String oldNick, final String login, final String hostname, final String newNick)
{
tell.send(newNick);
}
/**
* Responds with the last 10 public messages.
*
* @param sender The nick of the person who sent the private message.
* @param sender The nick of the person who sent the private message.
* @param isPrivate Set to true is the response should be send as a private message.
*/
private void recapResponse(final String sender, final boolean isPrivate)
@ -1914,11 +1817,21 @@ public class Mobibot extends PircBot
}
}
/**
* Saves the entries.
*
* @param isDayBackup Set the true if the daily backup file should also be created.
*/
private void saveEntries(final boolean isDayBackup)
{
EntriesMgr.saveEntries(this, entries, history, isDayBackup);
}
/**
* Sends a private message or notice.
*
* @param sender The nick of the person who sent the message.
* @param message The actual message.
* @param sender The nick of the person who sent the message.
* @param message The actual message.
* @param isPrivate Set to true if the response should be a private message, otherwise a notice is sent.
*/
public final void send(final String sender, final String message, final boolean isPrivate)
@ -1949,7 +1862,7 @@ public class Mobibot extends PircBot
/**
* Sends a private notice.
*
* @param sender The nick of the person who sent the message.
* @param sender The nick of the person who sent the message.
* @param message The actual message.
*/
public final void send(final String sender, final String message)
@ -1957,11 +1870,92 @@ public class Mobibot extends PircBot
send(sender, message, false);
}
/**
* Sets the del.icio.us authentication.
*
* @param username The del.icio.us user name.
* @param password The del.icio.us password.
*/
private void setDeliciousAuth(final String username, final String password)
{
delicious = new DeliciousPoster(username, password, ircServer);
}
/**
* Sets the feed URL.
*
* @param feedURL The feed URL.
*/
private void setFeedURL(final String feedURL)
{
this.feedURL = feedURL;
}
/**
* Sets the bot's identification.
*
* @param identPwd The password for NickServ, if any.
* @param identNick The ident nick name.
* @param identMsg The ident message.
*/
private void setIdentity(final String identPwd, final String identNick, final String identMsg)
{
this.identPwd = identPwd;
this.identNick = identNick;
this.identMsg = identMsg;
}
/**
* Sets the Ignored nicks.
*
* @param nicks The nicks to ignore
*/
private void setIgnoredNicks(final String nicks)
{
if (Utils.isValidString(nicks))
{
final StringTokenizer st = new StringTokenizer(nicks, ",");
while (st.hasMoreTokens())
{
ignoredNicks.add(st.nextToken().trim().toLowerCase());
}
}
}
/**
* Sets the default tags/categories.
*
* @param tags The tags.
*/
private void setTags(final String tags)
{
defaultTags = tags;
}
/**
* Stores the last 10 public messages and actions.
*
* @param sender The nick of the person who sent the private message.
* @param message The actual message sent.
* @param isAction Set to <code>true</code> if the message is an action.
*/
private void storeRecap(final String sender, final String message, final boolean isAction)
{
recap.add(Utils.UTC_SDF.format(Calendar.getInstance().getTime()) + " -> " + sender + (isAction ? " " : ": ")
+ message);
if (recap.size() > MAX_RECAP)
{
recap.remove(0);
}
}
/**
* Responds with the users on a channel.
*
* @param sender The nick of the person who sent the message.
* @param isPrivate Set to true is the response should be send as a private message.
* @param sender The nick of the person who sent the message.
* @param isPrivate Set to <code>true</code> if the response should be send as a private message.
*/
private void usersResponse(final String sender, final boolean isPrivate)
{
@ -1993,8 +1987,8 @@ public class Mobibot extends PircBot
/**
* Responds with the bot's version info.
*
* @param sender The nick of the person who sent the message.
* @param isPrivate Set to true is the response should be send as a private message.
* @param sender The nick of the person who sent the message.
* @param isPrivate Set to <code>true</code> if the response should be send as a private message.
*/
private void versionResponse(final String sender, final boolean isPrivate)
{
@ -2010,9 +2004,9 @@ public class Mobibot extends PircBot
/**
* Responds with the stored links.
*
* @param sender The nick of the person who sent the message.
* @param args The view command arguments.
* @param isPrivate Set to true is the response should be send as a private message.
* @param sender The nick of the person who sent the message.
* @param args The view command arguments.
* @param isPrivate Set to <code>true</code> if the response should be send as a private message.
*/
private void viewResponse(final String sender, final String args, final boolean isPrivate)
{
@ -2071,15 +2065,15 @@ public class Mobibot extends PircBot
if (lcArgs.length() > 0)
{
if ((entry.getLink().toLowerCase().contains(lcArgs)) ||
(entry.getTitle().toLowerCase().contains(lcArgs)) ||
(entry.getNick().toLowerCase().contains(lcArgs)))
(entry.getTitle().toLowerCase().contains(lcArgs)) ||
(entry.getNick().toLowerCase().contains(lcArgs)))
{
if (sent > MAX_ENTRIES)
{
send(sender,
"To view more, try: " + Utils
.bold(getNick() + ": " + Commands.VIEW_CMD + ' ' + (i + 1) + ' ' + lcArgs),
isPrivate);
"To view more, try: " + Utils
.bold(getNick() + ": " + Commands.VIEW_CMD + ' ' + (i + 1) + ' ' + lcArgs),
isPrivate);
break;
}
@ -2093,8 +2087,9 @@ public class Mobibot extends PircBot
if (sent > MAX_ENTRIES)
{
send(sender,
"To view more, try: " + Utils.bold(getNick() + ": " + Commands.VIEW_CMD + ' ' + (i + 1)),
isPrivate);
"To view more, try: " + Utils
.bold(getNick() + ": " + Commands.VIEW_CMD + ' ' + (i + 1)),
isPrivate);
break;
}

View file

@ -1,164 +0,0 @@
package net.thauvin.erik.mobibot;
import javax.swing.*;
/**
* This is the 3rd version of SwingWorker (also known as SwingWorker 3), an abstract class that you subclass to perform
* GUI-related work in a dedicated thread. For instructions on and examples of using this class, see:
* <p/>
* http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html
* <p/>
* Note that the API changed slightly in the 3rd version:
* You must now invoke start() on the SwingWorker after creating it.
*/
@SuppressWarnings("ALL")
public abstract class SwingWorker
{
private ThreadVar threadVar;
private Object value; // see getValue(), setValue()
/**
* Start a thread that will call the <code>construct</code> method and then exit.
*/
public SwingWorker()
{
final Runnable doFinished = new Runnable()
{
public void run()
{
finished();
}
};
Runnable doConstruct = new Runnable()
{
public void run()
{
try
{
setValue(construct());
}
finally
{
threadVar.clear();
}
SwingUtilities.invokeLater(doFinished);
}
};
Thread t = new Thread(doConstruct);
threadVar = new ThreadVar(t);
}
/**
* Called on the event dispatching thread (not on the worker thread) after the <code>construct</code> method has
* returned.
*/
public void finished()
{
}
/**
* Compute the value to be returned by the <code>get</code> method.
*
* @return The computed value.
*/
public abstract Object construct();
/**
* Return the value created by the <code>construct</code> method. Returns null if either the constructing thread or
* the current thread was interrupted before a value was produced.
*
* @return the value created by the <code>construct</code> method
*/
public Object get()
{
while (true)
{
Thread t = threadVar.get();
if (t == null)
{
return getValue();
}
try
{
t.join();
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt(); // propagate
return null;
}
}
}
/**
* Get the value produced by the worker thread, or null if it hasn't been constructed yet.
*
* @return The value.
*/
protected synchronized Object getValue()
{
return value;
}
/**
* Set the value produced by worker thread
*
* @param x The object.
*/
private synchronized void setValue(Object x)
{
value = x;
}
/**
* A new method that interrupts the worker thread. Call this method to force the worker to stop what it's doing.
*/
public void interrupt()
{
Thread t = threadVar.get();
if (t != null)
{
t.interrupt();
}
threadVar.clear();
}
/**
* Start the worker thread.
*/
public void start()
{
Thread t = threadVar.get();
if (t != null)
{
t.start();
}
}
/**
* Class to maintain reference to current worker thread under separate synchronization control.
*/
private static class ThreadVar
{
private Thread thread;
ThreadVar(Thread t)
{
thread = t;
}
synchronized void clear()
{
thread = null;
}
synchronized Thread get()
{
return thread;
}
}
}

View file

@ -53,13 +53,15 @@ public abstract class AbstractModule
/**
* Responds to a command.
*
* @param bot The bot's instance.
* @param sender The sender.
* @param args The command arguments.
* @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.
*/
public abstract void commandResponse(final Mobibot bot, final String sender, final String args,
final boolean isPrivate);
public abstract void commandResponse(final Mobibot bot,
final String sender,
final String args,
final boolean isPrivate);
/**
* Returns the module's commands, if any.
@ -94,13 +96,15 @@ public abstract class AbstractModule
/**
* Responds with the module's help.
*
* @param bot The bot's instance.
* @param sender The sender.
* @param args The help arguments.
* @param bot The bot's instance.
* @param sender The sender.
* @param args The help arguments.
* @param isPrivate Set to <code>true</code> if the response should be sent as a private message.
*/
public abstract void helpResponse(final Mobibot bot, final String sender, final String args,
final boolean isPrivate);
public abstract void helpResponse(final Mobibot bot,
final String sender,
final String args,
final boolean isPrivate);
/**
* Returns <code>true</code> if the module is enabled.
@ -122,10 +126,28 @@ public abstract class AbstractModule
return false;
}
/**
* Ensures that all properties have values.
*
* @return <code>true</code> if the properties are valid, <code>false</code> otherwise.
*/
public boolean isValidProperties()
{
for (final String s : getPropertyKeys())
{
if (!Utils.isValidString(properties.get(s)))
{
return false;
}
}
return true;
}
/**
* Sets a property key and value.
*
* @param key The key.
* @param key The key.
* @param value The value.
*/
public void setProperty(final String key, final String value)

View file

@ -100,9 +100,7 @@ final public class CurrencyConverter extends AbstractModule
}
}
new Thread(() -> {
run(bot, sender, args);
}).start();
new Thread(() -> run(bot, sender, args)).start();
}
@Override
@ -148,8 +146,9 @@ final public class CurrencyConverter extends AbstractModule
for (final Object rawCube : cubes)
{
cube = (Element) rawCube;
EXCHANGE_RATES
.put(cube.getAttribute("currency").getValue(), cube.getAttribute("rate").getValue());
EXCHANGE_RATES.put(
cube.getAttribute("currency").getValue(),
cube.getAttribute("rate").getValue());
}
EXCHANGE_RATES.put("EUR", "1");
@ -163,7 +162,7 @@ final public class CurrencyConverter extends AbstractModule
{
bot.getLogger().debug("Unable to fetch the exchange rates table.", e);
bot.send(sender,
"An error has occurred while fetching the exchange rates table: " + e.getMessage());
"An error has occurred while fetching the exchange rates table: " + e.getMessage());
}
}
@ -195,16 +194,20 @@ final public class CurrencyConverter extends AbstractModule
final double to = Double.parseDouble(EXCHANGE_RATES.get(cmds[3].toUpperCase()));
bot.send(bot.getChannel(),
NumberFormat.getCurrencyInstance(Locale.US).format(amt).substring(1) + ' '
+
cmds[1].toUpperCase() + " = " +
NumberFormat.getCurrencyInstance(Locale.US).format((amt * to) / from)
.substring(1) + ' ' + cmds[3].toUpperCase());
NumberFormat.getCurrencyInstance(Locale.US).format(amt).substring(1)
+ ' '
+ cmds[1].toUpperCase()
+ " = "
+ NumberFormat.getCurrencyInstance(Locale.US)
.format((amt * to) / from)
.substring(1)
+ ' '
+ cmds[3].toUpperCase());
}
catch (NullPointerException ignored)
{
bot.send(sender,
"The supported currencies are: " + EXCHANGE_RATES.keySet().toString());
"The supported currencies are: " + EXCHANGE_RATES.keySet().toString());
}
}
}

View file

@ -88,9 +88,7 @@ final public class GoogleSearch extends AbstractModule
{
if (args.length() > 0)
{
new Thread(() -> {
run(bot, sender, args);
}).start();
new Thread(() -> run(bot, sender, args)).start();
}
else
{
@ -113,35 +111,39 @@ final public class GoogleSearch extends AbstractModule
final String q = URLEncoder.encode(query, "UTF-8");
final URL url =
new URL("https://www.googleapis.com/customsearch/v1?key=" + properties.get(GOOGLE_API_KEY_PROP)
+ "&cx=" + properties.get(GOOGLE_CSE_KEY_PROP) + "&q=" + q + "&filter=1&num=5&alt=json");
new URL("https://www.googleapis.com/customsearch/v1?key="
+ properties.get(GOOGLE_API_KEY_PROP)
+ "&cx="
+ properties.get(GOOGLE_CSE_KEY_PROP)
+ "&q="
+ q
+ "&filter=1&num=5&alt=json");
final URLConnection conn = url.openConnection();
final StringBuilder sb = new StringBuilder();
final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null)
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())))
{
sb.append(line);
String line;
while ((line = reader.readLine()) != null)
{
sb.append(line);
}
final JSONObject json = new JSONObject(sb.toString());
final JSONArray ja = json.getJSONArray("items");
for (int i = 0; i < ja.length(); i++)
{
final JSONObject j = ja.getJSONObject(i);
bot.send(sender, Utils.unescapeXml(j.getString("title")));
bot.send(sender, TAB_INDENT + Utils.green(j.getString("link")));
}
}
final JSONObject json = new JSONObject(sb.toString());
final JSONArray ja = json.getJSONArray("items");
for (int i = 0; i < ja.length(); i++)
{
final JSONObject j = ja.getJSONObject(i);
bot.send(sender, Utils.unescapeXml(j.getString("title")));
bot.send(sender, TAB_INDENT + Utils.green(j.getString("link")));
}
reader.close();
}
catch (Exception e)
{
bot.getLogger().warn("Unable to search in Google for: " + query, e);
bot.send(sender, "An error has occurred: " + e.getMessage());
bot.send(sender, "An error has occurred searching in Google: " + e.getMessage());
}
}
@ -162,7 +164,6 @@ final public class GoogleSearch extends AbstractModule
@Override
public boolean isEnabled()
{
return Utils.isValidString(properties.get(GOOGLE_API_KEY_PROP)) && Utils
.isValidString(properties.get(GOOGLE_CSE_KEY_PROP));
return isValidProperties();
}
}

View file

@ -72,9 +72,7 @@ final public class Joke extends AbstractModule
@Override
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
@ -95,26 +93,27 @@ final public class Joke extends AbstractModule
final URLConnection conn = url.openConnection();
final StringBuilder sb = new StringBuilder();
final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null)
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())))
{
sb.append(line);
String line;
while ((line = reader.readLine()) != null)
{
sb.append(line);
}
final JSONObject json = new JSONObject(sb.toString());
bot.send(bot.getChannel(),
Colors.CYAN
+ json.getJSONObject("value").get("joke").toString().replaceAll("\\'", "'")
.replaceAll("\\\"", "\"")
+ Colors.NORMAL);
}
final JSONObject json = new JSONObject(sb.toString());
bot.send(bot.getChannel(),
Colors.CYAN + json.getJSONObject("value").get("joke").toString().replaceAll("\\'", "'")
.replaceAll("\\\"", "\"") + Colors.NORMAL);
reader.close();
}
catch (Exception e)
{
bot.getLogger().warn("Unable to retrieve random joke.", e);
bot.send(sender, "An error has occurred: " + e.getMessage());
bot.send(sender, "An error has occurred retrieving a random joke: " + e.getMessage());
}
}
}

View file

@ -70,9 +70,7 @@ final public class StockQuote extends AbstractModule
{
if (args.length() > 0)
{
new Thread(() -> {
run(bot, sender, args);
}).start();
new Thread(() -> run(bot, sender, args)).start();
}
else
{
@ -160,7 +158,7 @@ final public class StockQuote extends AbstractModule
catch (IOException e)
{
bot.getLogger().debug("Unable to retrieve stock quote for: " + symbol, e);
bot.send(sender, "An error has occurred: " + e.getMessage());
bot.send(sender, "An error has occurred retrieving a stock quote: " + e.getMessage());
}
}
}

View file

@ -32,7 +32,6 @@
package net.thauvin.erik.mobibot.modules;
import net.thauvin.erik.mobibot.Mobibot;
import net.thauvin.erik.mobibot.Utils;
import twitter4j.Status;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;
@ -76,9 +75,7 @@ final public class Twitter extends AbstractModule
{
if (isEnabled() && args.length() > 0)
{
new Thread(() -> {
run(bot, sender, args);
}).start();
new Thread(() -> run(bot, sender, args)).start();
}
else
{
@ -103,15 +100,7 @@ final public class Twitter extends AbstractModule
@Override
public boolean isEnabled()
{
for (final String s : getPropertyKeys())
{
if (!Utils.isValidString(properties.get(s)))
{
return false;
}
}
return true;
return isValidProperties();
}
/**
@ -122,18 +111,19 @@ final public class Twitter extends AbstractModule
try
{
final ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true).setOAuthConsumerKey(properties.get(CONSUMER_KEY_PROP))
.setOAuthConsumerSecret(properties.get(CONSUMER_SECRET_PROP))
.setOAuthAccessToken(properties.get(TOKEN_PROP))
.setOAuthAccessTokenSecret(properties.get(TOKEN_SECRET_PROP));
cb.setDebugEnabled(true)
.setOAuthConsumerKey(properties.get(CONSUMER_KEY_PROP))
.setOAuthConsumerSecret(properties.get(CONSUMER_SECRET_PROP))
.setOAuthAccessToken(properties.get(TOKEN_PROP))
.setOAuthAccessTokenSecret(properties.get(TOKEN_SECRET_PROP));
final TwitterFactory tf = new TwitterFactory(cb.build());
final twitter4j.Twitter twitter = tf.getInstance();
final Status status = twitter.updateStatus(message + " (" + sender + ')');
bot.send(sender,
"You message was posted to http://twitter.com/" + twitter.getScreenName() + "/statuses/" + status
.getId());
"You message was posted to http://twitter.com/" + twitter.getScreenName() + "/statuses/" + status
.getId());
}
catch (Exception e)
{

View file

@ -75,9 +75,7 @@ final public class Weather extends AbstractModule
@Override
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
@ -110,18 +108,26 @@ final public class Weather extends AbstractModule
bot.send(sender, "Station ID: " + metar.getStationID(), isPrivate);
bot.send(sender,
"At: " + Utils.UTC_SDF.format(metar.getDate()) + " UTC (" + (
((new Date()).getTime() - metar.getDate().getTime()) / 1000L / 60L) + " minutes ago)",
isPrivate);
"At: "
+ Utils.UTC_SDF.format(metar.getDate())
+ " UTC ("
+ (((new Date()).getTime() - metar.getDate().getTime()) / 1000L / 60L)
+ " minutes ago)",
isPrivate);
result = metar.getWindSpeedInMPH();
if (result != null)
{
bot.send(sender,
"Wind Speed: " + result + " mph, " + metar.getWindSpeedInKnots() + " knots, " + metar
.getWindSpeedInMPS() + " m/s",
isPrivate);
"Wind Speed: "
+ result
+ " mph, "
+ metar.getWindSpeedInKnots()
+ " knots, "
+ metar.getWindSpeedInMPS()
+ " m/s",
isPrivate);
}
result = metar.getVisibility();
@ -129,9 +135,11 @@ final public class Weather extends AbstractModule
if (result != null)
{
bot.send(sender,
"Visibility: " + (metar.getVisibilityLessThan() ? "< " : "") + NUMBER_FORMAT.format(result)
+ " mi, " + metar.getVisibilityInKilometers() + " km",
isPrivate);
"Visibility: "
+ (metar.getVisibilityLessThan() ? "< " : "")
+ NUMBER_FORMAT.format(result)
+ " mi, " + metar.getVisibilityInKilometers() + " km",
isPrivate);
}
result = metar.getPressure();
@ -139,8 +147,8 @@ final public class Weather extends AbstractModule
if (result != null)
{
bot.send(sender,
"Pressure: " + result + " Hg, " + metar.getPressureInHectoPascals() + " hPa",
isPrivate);
"Pressure: " + result + " Hg, " + metar.getPressureInHectoPascals() + " hPa",
isPrivate);
}
result = metar.getTemperatureInCelsius();
@ -148,8 +156,8 @@ final public class Weather extends AbstractModule
if (result != null)
{
bot.send(sender,
"Temperature: " + result + " \u00B0C, " + metar.getTemperatureInFahrenheit() + " \u00B0F",
isPrivate);
"Temperature: " + result + " \u00B0C, " + metar.getTemperatureInFahrenheit() + " \u00B0F",
isPrivate);
}
if (metar.getWeatherConditions() != null)

View file

@ -149,9 +149,9 @@ final public class WorldTime extends AbstractModule
/**
* Responds with the current time in the specified timezone/country.
*
* @param bot The bot's instance.
* @param sender The sender.
* @param args The command arguments.
* @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
@ -171,7 +171,7 @@ final public class WorldTime extends AbstractModule
{
TIME_SDF.setTimeZone(TimeZone.getTimeZone(tz));
response = TIME_SDF.format(Calendar.getInstance().getTime()) + tz.substring(tz.indexOf('/') + 1)
.replace('_', ' ');
.replace('_', ' ');
}
}
else
@ -197,6 +197,16 @@ final public class WorldTime extends AbstractModule
}
}
@Override
public void helpResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate)
{
bot.send(sender, "To display a country's current date/time:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + TIME_CMD) + " [<country code>]");
bot.send(sender, "For a listing of the supported countries:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + TIME_CMD));
}
/**
* Returns the current Internet (beat) Time.
*
@ -237,16 +247,6 @@ final public class WorldTime extends AbstractModule
return ('@' + String.valueOf(beats));
}
@Override
public void helpResponse(final Mobibot bot, final String sender, final String args, final boolean isPrivate)
{
bot.send(sender, "To display a country's current date/time:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + TIME_CMD) + " [<country code>]");
bot.send(sender, "For a listing of the supported countries:");
bot.send(sender, bot.helpIndent(bot.getNick() + ": " + TIME_CMD));
}
@Override
public boolean isPrivateMsgEnabled()
{

View file

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