Browse Source

Style/stupidity fixes.

I'm sure I've done some of these before...

Change-Id: Ie41ffe45793e1e54403cc5501df74ad12ce680d7
Reviewed-on: http://gerrit.dmdirc.com/1379
Automatic-Compile: DMDirc Local Commits <dmdirc@googlemail.com>
Reviewed-by: Gregory Holmes <greg@dmdirc.com>
tags/0.6.4
Chris Smith 14 years ago
parent
commit
4251e58915

+ 75
- 90
src/com/dmdirc/addons/parser_twitter/Twitter.java View File

@@ -37,7 +37,6 @@ import com.dmdirc.parser.common.CallbackManager;
37 37
 import com.dmdirc.parser.common.ChannelJoinRequest;
38 38
 import com.dmdirc.parser.common.DefaultStringConverter;
39 39
 import com.dmdirc.parser.common.IgnoreList;
40
-import com.dmdirc.parser.common.MyInfo;
41 40
 import com.dmdirc.parser.common.QueuePriority;
42 41
 import com.dmdirc.parser.interfaces.ChannelClientInfo;
43 42
 import com.dmdirc.parser.interfaces.ChannelInfo;
@@ -90,11 +89,16 @@ import java.util.Map;
90 89
  */
91 90
 public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler, ConfigChangeListener {
92 91
 
92
+    /** Number of loops between clearing of the status cache. */
93
+    private static final long PRUNE_COUNT = 20;
94
+    /** Maximum age of items to leave in the status cache when pruning. */
95
+    private static final long PRUNE_TIME = 3600 * 1000;
96
+
93 97
     /** Are we connected? */
94 98
     private boolean connected = false;
95 99
 
96
-    /** Our owner plugin */
97
-    private TwitterPlugin myPlugin = null;
100
+    /** Our owner plugin. */
101
+    private final TwitterPlugin myPlugin;
98 102
 
99 103
     /** Twitter API. */
100 104
     private TwitterAPI api = new TwitterAPI("", "", "", false, -1, false);
@@ -127,7 +131,7 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
127 131
     private TwitterClientInfo myself = null;
128 132
 
129 133
     /** List of currently active twitter parsers. */
130
-    protected static final List<Twitter> currentParsers = new ArrayList<Twitter>();
134
+    protected static final List<Twitter> PARSERS = new ArrayList<Twitter>();
131 135
 
132 136
     /** Are we waiting for authentication? */
133 137
     private boolean wantAuth = false;
@@ -147,7 +151,7 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
147 151
     /** Address that created us. */
148 152
     private final URI myAddress;
149 153
 
150
-    /** Main Channel Name */
154
+    /** Main Channel Name. */
151 155
     private final String mainChannelName;
152 156
 
153 157
     /** Config Manager for this parser. */
@@ -162,7 +166,7 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
162 166
     /** Automatically leave & channels? */
163 167
     private boolean autoLeaveMessageChannel;
164 168
 
165
-    /** Save last IDs */
169
+    /** Save last IDs. */
166 170
     private boolean saveLastIDs;
167 171
 
168 172
     /** Last Reply ID. */
@@ -175,7 +179,8 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
175 179
     private long lastDirectMessageId = -1;
176 180
 
177 181
     /** Last IDs in searched hashtag channels. */
178
-    private final Map<TwitterChannelInfo, Long> lastSearchIds = new HashMap<TwitterChannelInfo, Long>();
182
+    private final Map<TwitterChannelInfo, Long> lastSearchIds
183
+            = new HashMap<TwitterChannelInfo, Long>();
179 184
 
180 185
     /** Status count. */
181 186
     private int statusCount;
@@ -183,7 +188,7 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
183 188
     /** Get sent messages. */
184 189
     private boolean getSentMessage;
185 190
 
186
-    /** Number of api calls to use. */
191
+    /** Number of API calls to use. */
187 192
     private int apicalls;
188 193
 
189 194
     /** Auto append @ to nicknames. */
@@ -198,11 +203,10 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
198 203
     /**
199 204
      * Create a new Twitter Parser!
200 205
      *
201
-     * @param myInfo The client information to use
202 206
      * @param address The address of the server to connect to
203 207
      * @param myPlugin Plugin that created this parser
204 208
      */
205
-    protected Twitter(final MyInfo myInfo, final URI address, final TwitterPlugin myPlugin) {
209
+    protected Twitter(final URI address, final TwitterPlugin myPlugin) {
206 210
         final String[] bits;
207 211
         if (address.getUserInfo() == null) {
208 212
             bits = new String[]{};
@@ -239,7 +243,7 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
239 243
     @Override
240 244
     public void disconnect(final String message) {
241 245
         connected = false;
242
-        currentParsers.remove(this);
246
+        PARSERS.remove(this);
243 247
         api = new TwitterAPI("", "", "", false, -1, false);
244 248
 
245 249
         getCallbackManager().getCallbackType(SocketCloseListener.class).call();
@@ -270,7 +274,9 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
270 274
                     try {
271 275
                         final long id = Long.parseLong(channel.substring(1));
272 276
                         final TwitterStatus status = api.getStatus(id);
273
-                        if (status != null) {
277
+                        if (status == null) {
278
+                            newChannel.setLocalTopic("Unknown status, or you do not have access to see it.");
279
+                        } else {
274 280
                             if (status.getReplyTo() > 0) {
275 281
                                 newChannel.setLocalTopic(status.getText() + " [Reply to: &" + status.getReplyTo() + "]");
276 282
                             } else {
@@ -284,15 +290,14 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
284 290
                                 clients.put(client.getNickname().toLowerCase(), client);
285 291
                             }
286 292
                             newChannel.addChannelClient(new TwitterChannelClientInfo(newChannel, client));
287
-                        } else {
288
-                            newChannel.setLocalTopic("Unknown status, or you do not have access to see it.");
289 293
                         }
294
+
290 295
                         synchronized (this.channels) {
291 296
                             this.channels.put(channel, newChannel);
292 297
                         }
293 298
                     } catch (final NumberFormatException nfe) {
294 299
                     }
295
-                } else if (channel.startsWith("#")) {
300
+                } else if (channel.charAt(0) == '#') {
296 301
                     newChannel.setLocalTopic("Search results for " + channel);
297 302
                     synchronized (this.channels) {
298 303
                         this.channels.put(channel, newChannel);
@@ -308,8 +313,8 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
308 313
 
309 314
     /**
310 315
      * Remove a channel from the known channels list.
311
-     * 
312
-     * @param channel
316
+     *
317
+     * @param channel The channel to part
313 318
      */
314 319
     protected void partChannel(final ChannelInfo channel) {
315 320
         if (channel == null) { return; }
@@ -339,7 +344,7 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
339 344
     /** {@inheritDoc} */
340 345
     @Override
341 346
     public void setBindIP(final String ip) {
342
-        return;
347
+        // Ignore
343 348
     }
344 349
 
345 350
     /** {@inheritDoc} */
@@ -370,7 +375,7 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
370 375
      */
371 376
     public static String[] tokeniseLine(final String line) {
372 377
         if (line == null) {
373
-            return new String[]{"",}; // Return empty string[]
378
+            return new String[]{""};
374 379
         }
375 380
 
376 381
         final int lastarg = line.indexOf(" :");
@@ -451,7 +456,7 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
451 456
                     getCallbackManager().getCallbackType(NumericListener.class).call(301, new String[]{":" + myServerName, "301", myself.getNickname(), bits[1], "Location: " + user.getLocation()});
452 457
                     getCallbackManager().getCallbackType(NumericListener.class).call(301, new String[]{":" + myServerName, "301", myself.getNickname(), bits[1], "Status: " + user.getStatus().getText()});
453 458
                     if (bits[1].equalsIgnoreCase(myself.getNickname())) {
454
-                        final Long[] apiCalls = api.getRemainingApiCalls();
459
+                        final long[] apiCalls = api.getRemainingApiCalls();
455 460
                         getCallbackManager().getCallbackType(NumericListener.class).call(301, new String[]{":" + myServerName, "301", myself.getNickname(), bits[1], "API Allowance: " + apiCalls[1]});
456 461
                         getCallbackManager().getCallbackType(NumericListener.class).call(301, new String[]{":" + myServerName, "301", myself.getNickname(), bits[1], "API Allowance Remaining: " + apiCalls[0]});
457 462
                         getCallbackManager().getCallbackType(NumericListener.class).call(301, new String[]{":" + myServerName, "301", myself.getNickname(), bits[1], "API Calls Used: " + apiCalls[3]});
@@ -505,7 +510,7 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
505 510
     /** {@inheritDoc} */
506 511
     @Override
507 512
     public boolean isValidChannelName(final String name) {
508
-        return name.matches("^&[0-9]+$") || name.equalsIgnoreCase(mainChannelName) || name.startsWith("#");
513
+        return name.matches("^&[0-9]+$") || name.equalsIgnoreCase(mainChannelName) || name.charAt(0) == '#';
509 514
     }
510 515
 
511 516
     /** {@inheritDoc} */
@@ -638,7 +643,9 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
638 643
                 final long id = Long.parseLong(target.substring(1));
639 644
                 if (type.equalsIgnoreCase("retweet") || type.equalsIgnoreCase("rt")) {
640 645
                     final TwitterStatus status = api.getStatus(id);
641
-                    if (status != null) {
646
+                    if (status == null) {
647
+                        sendPrivateNotice("Invalid Tweet ID.");
648
+                    } else {
642 649
                         sendPrivateNotice("Retweeting: <" + status.getUser().getScreenName() + "> " + status.getText());
643 650
                         if (api.retweetStatus(status)) {
644 651
                             sendPrivateNotice("Retweet was successful.");
@@ -647,12 +654,12 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
647 654
                         } else {
648 655
                             sendPrivateNotice("Retweeting Failed.");
649 656
                         }
650
-                    } else {
651
-                        sendPrivateNotice("Invalid Tweet ID.");
652 657
                     }
653 658
                 } else if (type.equalsIgnoreCase("delete") || type.equalsIgnoreCase("del")) {
654 659
                     final TwitterStatus status = api.getStatus(id);
655
-                    if (status != null) {
660
+                    if (status == null) {
661
+                        sendPrivateNotice("Invalid Tweet ID.");
662
+                    } else {
656 663
                         sendPrivateNotice("Deleting: <" + status.getUser().getScreenName() + "> " + status.getText());
657 664
                         if (api.deleteStatus(status)) {
658 665
                             sendPrivateNotice("Deleting was successful, deleted tweets will still be accessible for some time.");
@@ -661,21 +668,17 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
661 668
                         } else {
662 669
                             sendPrivateNotice("Deleting Failed.");
663 670
                         }
664
-                    } else {
665
-                        sendPrivateNotice("Invalid Tweet ID.");
666 671
                     }
667 672
                 }
668 673
             } catch (final NumberFormatException nfe) {
669 674
                 sendPrivateNotice("Invalid Tweet ID.");
670 675
             }
671
-        } else if (target.equalsIgnoreCase(mainChannelName) || target.startsWith("#")) {
676
+        } else if (target.equalsIgnoreCase(mainChannelName) || target.charAt(0) == '#') {
672 677
             if (type.equalsIgnoreCase("update") || type.equalsIgnoreCase("refresh")) {
673 678
                 final TwitterChannelInfo channel = (TwitterChannelInfo) getChannel(target);
674 679
                 sendChannelNotice(channel, "Refreshing...");
675
-                if (channel != null) {
676
-                    if (!getUpdates(channel)) {
677
-                        sendChannelNotice(channel, "No new items found.");
678
-                    }
680
+                if (channel != null && !getUpdates(channel)) {
681
+                    sendChannelNotice(channel, "No new items found.");
679 682
                 }
680 683
             }
681 684
         } else {
@@ -692,9 +695,9 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
692 695
     /** {@inheritDoc} */
693 696
     @Override
694 697
     public void sendMessage(final String target, final String message) {
695
-        final TwitterChannelInfo channel = (TwitterChannelInfo) getChannel(target);
696 698
         if (target.equalsIgnoreCase(mainChannelName)) {
697 699
             if (wantAuth) {
700
+                final TwitterChannelInfo channel = (TwitterChannelInfo) getChannel(target);
698 701
                 final String[] bits = message.split(" ");
699 702
                 if (bits[0].equalsIgnoreCase("usepw")) {
700 703
                     sendChannelMessage(channel, "Switching to once-off password authentication, please enter your password.");
@@ -739,8 +742,7 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
739 742
             sendPrivateNotice("DMDirc has not been authorised to use this account yet.");
740 743
         } else if (target.matches("^&[0-9]+$")) {
741 744
             try {
742
-                final long id = Long.parseLong(target.substring(1));
743
-                if (setStatus(message, id)) {
745
+                if (setStatus(message, Long.parseLong(target.substring(1)))) {
744 746
                     sendPrivateNotice("Setting status ok.");
745 747
                     if (autoLeaveMessageChannel) {
746 748
                         partChannel(getChannel(target));
@@ -750,14 +752,14 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
750 752
                 }
751 753
             } catch (final NumberFormatException nfe) {
752 754
             }
753
-        } else if (!target.matches("^#.+$")) {
755
+        } else if (target.matches("^#.+$")) {
756
+            sendPrivateNotice("Messages to '" + target + "' are not currently supported.");
757
+        } else {
754 758
             if (api.newDirectMessage(target, message)) {
755 759
                 sendPrivateNotice("Sending Direct Message to '" + target + "' was successful.");
756 760
             } else {
757 761
                 sendPrivateNotice("Sending Direct Message to '" + target + "' failed.");
758 762
             }
759
-        } else {
760
-            sendPrivateNotice("Messages to '" + target + "' are not currently supported.");
761 763
         }
762 764
     }
763 765
 
@@ -799,7 +801,9 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
799 801
 
800 802
     /** {@inheritDoc} */
801 803
     @Override
802
-    public void setPingTimerInterval(final long newValue) { /* Do Nothing. */ }
804
+    public void setPingTimerInterval(final long newValue) {
805
+        /* Do Nothing. */
806
+    }
803 807
 
804 808
     /** {@inheritDoc} */
805 809
     @Override
@@ -809,7 +813,9 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
809 813
 
810 814
     /** {@inheritDoc} */
811 815
     @Override
812
-    public void setPingTimerFraction(final int newValue) { /* Do Nothing. */ }
816
+    public void setPingTimerFraction(final int newValue) {
817
+        /* Do Nothing. */
818
+    }
813 819
 
814 820
     /** {@inheritDoc} */
815 821
     @Override
@@ -826,25 +832,6 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
826 832
         getCallbackManager().getCallbackType(PrivateNoticeListener.class).call(message, myServerName);
827 833
     }
828 834
 
829
-    /**
830
-     * Send a PM to the client.
831
-     *
832
-     * @param message Message to send.
833
-     */
834
-    private void sendPrivateMessage(final String message) {
835
-        sendPrivateMessage(message, myServerName);
836
-    }
837
-
838
-    /**
839
-     * Send a PM to the client.
840
-     *
841
-     * @param message Message to send.
842
-     * @param hostname Who is the message from?
843
-     */
844
-    private void sendPrivateMessage(final String message, final String hostname) {
845
-        sendPrivateMessage(message, hostname, myUsername);
846
-    }
847
-
848 835
     /**
849 836
      * Send a PM to the client.
850 837
      *
@@ -1039,7 +1026,7 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
1039 1026
 
1040 1027
         api = new TwitterAPI(myUsername, myPassword, apiAddress, "", consumerKey, consumerSecret, token, tokenSecret, apiVersioning, apiVersion, getConfigManager().getOptionBool(myPlugin.getDomain(), "autoAt"));
1041 1028
         api.setSource("DMDirc");
1042
-        currentParsers.add(this);
1029
+        PARSERS.add(this);
1043 1030
         api.addErrorHandler(this);
1044 1031
         api.addRawHandler(this);
1045 1032
         api.setDebug(debugEnabled);
@@ -1084,7 +1071,10 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
1084 1071
 
1085 1072
         sendChannelMessage(channel, "Checking to see if we have been authorised to use the account \"" + api.getLoginUsername() + "\"...");
1086 1073
 
1087
-        if (!api.isAllowed(false)) {
1074
+        if (api.isAllowed(false)) {
1075
+            sendChannelMessage(channel, "DMDirc has been authorised to use the account \"" + api.getLoginUsername() + "\"");
1076
+            updateTwitterChannel();
1077
+        } else {
1088 1078
             wantAuth = true;
1089 1079
             if (api.useOAuth()) {
1090 1080
                 sendChannelMessage(channel, "Sorry, DMDirc has not been authorised to use the account \"" + api.getLoginUsername() + "\"");
@@ -1100,9 +1090,6 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
1100 1090
                 sendChannelMessage(channel, "");
1101 1091
                 sendChannelMessage(channel, "To do this, please type the password here, or set it correctly in the URL (twitter://" + myUsername + ":your_password@" + myServerName + myAddress.getPath() + ").");
1102 1092
             }
1103
-        } else {
1104
-            sendChannelMessage(channel, "DMDirc has been authorised to use the account \"" + api.getLoginUsername() + "\"");
1105
-            updateTwitterChannel();
1106 1093
         }
1107 1094
 
1108 1095
         if (saveLastIDs) {
@@ -1120,10 +1107,8 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
1120 1107
         boolean first = true; // Used to let used know if there was no new items.
1121 1108
 
1122 1109
         int count = 0;
1123
-        final long pruneCount = 20; // Every 20 loops, clear the status cache of
1124
-        final long pruneTime = 3600 * 1000; // anything older than 1 hour.
1125 1110
         while (connected) {
1126
-            final int startCalls = (wantAuth) ? 0 : api.getUsedCalls();
1111
+            final int startCalls = wantAuth ? 0 : api.getUsedCalls();
1127 1112
 
1128 1113
             // Get Updates
1129 1114
             final boolean foundUpdates = getUpdates(channel);
@@ -1145,15 +1130,15 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
1145 1130
             }
1146 1131
 
1147 1132
             // Calculate number of calls remaining.
1148
-            final int endCalls = (wantAuth) ? 0 : api.getUsedCalls();
1149
-            final Long[] apiCalls = (wantAuth) ? new Long[]{0L, 0L, System.currentTimeMillis(), (long) api.getUsedCalls()} : api.getRemainingApiCalls();
1133
+            final int endCalls = wantAuth ? 0 : api.getUsedCalls();
1134
+            final long[] apiCalls = wantAuth ? new long[]{0L, 0L, System.currentTimeMillis(), (long) api.getUsedCalls()} : api.getRemainingApiCalls();
1150 1135
             doDebug(Debug.apiCalls, "Twitter calls Remaining: " + apiCalls[0]);
1151 1136
             // laconica doesn't rate limit, so time to reset is always 0, in this case
1152 1137
             // we will assume the time of the next hour.
1153 1138
             final Calendar cal = Calendar.getInstance();
1154 1139
             cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE), cal.get(Calendar.HOUR_OF_DAY) + 1, 0, 0);
1155 1140
 
1156
-            final Long timeLeft = ((apiCalls[2] > 0) ? apiCalls[2] : cal.getTimeInMillis()) - System.currentTimeMillis();
1141
+            final long timeLeft = (apiCalls[2] > 0 ? apiCalls[2] : cal.getTimeInMillis()) - System.currentTimeMillis();
1157 1142
             final long sleepTime;
1158 1143
             if (wantAuth) {
1159 1144
                 // When waiting for auth, sleep for less time so that when the
@@ -1181,7 +1166,7 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
1181 1166
                 // How many calls do we make each time?
1182 1167
                 // If this is less than 0 (If there was a time reset between
1183 1168
                 // calculating the start and end calls used) then assume 3.
1184
-                final long callsPerTime = (endCalls - startCalls) > 0 ? (endCalls - startCalls) : 3;
1169
+                final long callsPerTime = (endCalls - startCalls) > 0 ? endCalls - startCalls : 3;
1185 1170
 
1186 1171
                 doDebug(Debug.apiCalls, "\tCalls Remaining: " + callsLeft);
1187 1172
                 doDebug(Debug.apiCalls, "\tCalls per time: " + callsPerTime);
@@ -1202,12 +1187,12 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
1202 1187
             // Sleep for sleep time,
1203 1188
             // If we have a negative sleep time, use 5 minutes.
1204 1189
             try {
1205
-                Thread.sleep((sleepTime > 0) ? sleepTime : 5 * 60 * 1000);
1190
+                Thread.sleep(sleepTime > 0 ? sleepTime : 5 * 60 * 1000);
1206 1191
             } catch (final InterruptedException ex) {
1207 1192
             }
1208 1193
 
1209
-            if (++count > pruneCount) {
1210
-                api.pruneStatusCache(System.currentTimeMillis() - pruneTime);
1194
+            if (++count > PRUNE_COUNT) {
1195
+                api.pruneStatusCache(System.currentTimeMillis() - PRUNE_TIME);
1211 1196
             }
1212 1197
         }
1213 1198
     }
@@ -1222,7 +1207,6 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
1222 1207
         boolean foundItems = false;
1223 1208
         if (!wantAuth && api.isAllowed()) {
1224 1209
             lastQueryTime = System.currentTimeMillis();
1225
-            final int statusesPerAttempt = Math.min(200, statusCount);
1226 1210
 
1227 1211
             if (channel.getName().startsWith("#")) {
1228 1212
                 long lastId = lastSearchIds.containsKey(channel) ? lastSearchIds.get(channel) : -1;
@@ -1237,6 +1221,7 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
1237 1221
 
1238 1222
                 lastSearchIds.put(channel, lastId);
1239 1223
             } else {
1224
+                final int statusesPerAttempt = Math.min(200, statusCount);
1240 1225
                 final List<TwitterStatus> statuses = new ArrayList<TwitterStatus>();
1241 1226
                 for (final TwitterStatus status : api.getReplies(lastReplyId, statusesPerAttempt)) {
1242 1227
                     statuses.add(status);
@@ -1337,8 +1322,8 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
1337 1322
     }
1338 1323
 
1339 1324
     /**
1340
-     * Get the Twitter API Object
1341
-     * 
1325
+     * Get the Twitter API Object.
1326
+     *
1342 1327
      * @return The Twitter API Object
1343 1328
      */
1344 1329
     public TwitterAPI getApi() {
@@ -1365,7 +1350,7 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
1365 1350
 
1366 1351
     /**
1367 1352
      * Set the twitter status.
1368
-     * 
1353
+     *
1369 1354
      * @param message Status to use.
1370 1355
      * @return True if status was updated, else false.
1371 1356
      */
@@ -1377,10 +1362,10 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
1377 1362
      * Set the twitter status.
1378 1363
      *
1379 1364
      * @param message Status to use.
1380
-     * @param id
1365
+     * @param replyToId The ID this status is in reply to, or -1
1381 1366
      * @return True if status was updated, else false.
1382 1367
      */
1383
-    private boolean setStatus(final String message, final long id) {
1368
+    private boolean setStatus(final String message, final long replyToId) {
1384 1369
         final StringBuffer newStatus = new StringBuffer(message);
1385 1370
         final TwitterChannelInfo channel = (TwitterChannelInfo) getChannel(mainChannelName);
1386 1371
 
@@ -1391,16 +1376,16 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
1391 1376
 
1392 1377
                 final ChannelClientInfo cci = channel.getChannelClient(name);
1393 1378
                 if (cci != null) {
1394
-                    if (cci.getClient().getNickname().charAt(0) != '@') {
1395
-                        bits[0] = "@" + cci.getClient().getNickname();
1396
-                    } else {
1379
+                    if (cci.getClient().getNickname().charAt(0) == '@') {
1397 1380
                         bits[0] = cci.getClient().getNickname();
1381
+                    } else {
1382
+                        bits[0] = "@" + cci.getClient().getNickname();
1398 1383
                     }
1399 1384
 
1400 1385
                     newStatus.setLength(0);
1401 1386
                     for (final String bit : bits) {
1402 1387
                         if (newStatus.length() > 0) {
1403
-                            newStatus.append(" ");
1388
+                            newStatus.append(' ');
1404 1389
                         }
1405 1390
                         newStatus.append(bit);
1406 1391
                     }
@@ -1408,7 +1393,7 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
1408 1393
             }
1409 1394
         }
1410 1395
 
1411
-        if (api.setStatus(newStatus.toString(), id)) {
1396
+        if (api.setStatus(newStatus.toString(), replyToId)) {
1412 1397
             checkTopic(channel, myself.getUser().getStatus());
1413 1398
             return true;
1414 1399
         }
@@ -1501,10 +1486,10 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
1501 1486
             return;
1502 1487
         }
1503 1488
         try {
1504
-            if (!message.isEmpty()) {
1505
-                twitterFail("Recieved an error from twitter: " + message + (debugEnabled ? " [" + source + "]" : ""));
1506
-            } else if (debugEnabled) {
1489
+            if (message.isEmpty()) {
1507 1490
                 twitterFail("Recieved an error: " + source);
1491
+            } else if (debugEnabled) {
1492
+                twitterFail("Recieved an error from twitter: " + message + (debugEnabled ? " [" + source + "]" : ""));
1508 1493
             }
1509 1494
             if (t != null) {
1510 1495
                 doDebug(Debug.twitterError, t.getClass().getSimpleName() + ": " + t + " -> " + t.getMessage());
@@ -1526,7 +1511,7 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
1526 1511
             }
1527 1512
 
1528 1513
             doDebug(Debug.twitterErrorMore, "==================================");
1529
-        } catch (final Throwable t2) {
1514
+        } catch (final Exception t2) {
1530 1515
             doDebug(Debug.twitterError, "wtf? (See Console for stack trace) " + t2);
1531 1516
             t2.printStackTrace();
1532 1517
         }
@@ -1643,7 +1628,7 @@ public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
1643 1628
     /** {@inheritDoc} */
1644 1629
     @Override
1645 1630
     public List<String> getServerInformationLines() {
1646
-        return Arrays.asList(new String[]{"Twitter IRC parser: " + getServerName(),});
1631
+        return Arrays.asList(new String[]{"Twitter IRC parser: " + getServerName()});
1647 1632
     }
1648 1633
 
1649 1634
 }

+ 5
- 9
src/com/dmdirc/addons/parser_twitter/TwitterPlugin.java View File

@@ -33,23 +33,19 @@ import com.dmdirc.parser.common.MyInfo;
33 33
 import com.dmdirc.parser.interfaces.Parser;
34 34
 import com.dmdirc.parser.interfaces.ProtocolDescription;
35 35
 import com.dmdirc.plugins.Plugin;
36
+
36 37
 import java.net.URI;
37 38
 import java.util.ArrayList;
38 39
 
39 40
 /**
41
+ * Facilitates creation of Twitter parsers.
40 42
  *
41 43
  * @author shane
42 44
  */
43 45
 public class TwitterPlugin extends Plugin {
44 46
 
45 47
     /** Are we currently unloading? */
46
-    private static boolean unloading = false;
47
-
48
-    /**
49
-     * Create a TwitterPlugin
50
-     */
51
-    public TwitterPlugin() {
52
-    }
48
+    private volatile boolean unloading = false;
53 49
 
54 50
     /** {@inheritDoc} */
55 51
     @Override
@@ -61,7 +57,7 @@ public class TwitterPlugin extends Plugin {
61 57
     @Override
62 58
     public void onUnload() {
63 59
         unloading = true;
64
-        for (final Twitter parser : new ArrayList<Twitter>(Twitter.currentParsers)) {
60
+        for (final Twitter parser : new ArrayList<Twitter>(Twitter.PARSERS)) {
65 61
             parser.disconnect("");
66 62
         }
67 63
     }
@@ -74,7 +70,7 @@ public class TwitterPlugin extends Plugin {
74 70
      * @return An appropriately configured parser
75 71
      */
76 72
     public Parser getParser(final MyInfo myInfo, final URI address) {
77
-        return (unloading) ? null : new Twitter(myInfo, address, this);
73
+        return unloading ? null : new Twitter(address, this);
78 74
     }
79 75
 
80 76
     /**

+ 48
- 46
src/com/dmdirc/addons/parser_twitter/api/TwitterAPI.java View File

@@ -63,15 +63,19 @@ import org.xml.sax.SAXException;
63 63
 
64 64
 /**
65 65
  * Implementation of the twitter API for DMDirc.
66
- * 
66
+ *
67 67
  * @author shane
68 68
  */
69 69
 public class TwitterAPI {
70 70
 
71
-    /** OAuth Consumer */
71
+    /** Characters used in b64 encoding. */
72
+    private static final String BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcde"
73
+            + "fghijklmnopqrstuvwxyz0123456789+/";
74
+
75
+    /** OAuth Consumer. */
72 76
     private OAuthConsumer consumer;
73 77
 
74
-    /** OAuth Provider */
78
+    /** OAuth Provider. */
75 79
     private OAuthProvider provider;
76 80
 
77 81
     /** Have we signed anything yet? */
@@ -98,7 +102,7 @@ public class TwitterAPI {
98 102
     /** Cache of statuses. */
99 103
     final Map<Long, TwitterStatus> statusCache = new HashMap<Long, TwitterStatus>();
100 104
 
101
-    /** API Allowed status */
105
+    /** API Allowed status. */
102 106
     private APIAllowed allowed = APIAllowed.UNKNOWN;
103 107
 
104 108
     /** How many API calls have we made since the last reset? */
@@ -107,10 +111,10 @@ public class TwitterAPI {
107 111
     /** API reset time. */
108 112
     private long resetTime = 0;
109 113
 
110
-    /** Twitter Token */
114
+    /** Twitter Token. */
111 115
     private String token = "";
112 116
 
113
-    /** Twitter Token Secret */
117
+    /** Twitter Token Secret. */
114 118
     private String tokenSecret = "";
115 119
 
116 120
     /** Last input to the API. */
@@ -119,10 +123,10 @@ public class TwitterAPI {
119 123
     /** Last output from the API. */
120 124
     private String apiOutput = "";
121 125
 
122
-    /** List of TwitterErrorHandlers */
126
+    /** List of TwitterErrorHandlers. */
123 127
     private final List<TwitterErrorHandler> errorHandlers = new LinkedList<TwitterErrorHandler>();
124 128
 
125
-    /** List of TwitterRawHandlers */
129
+    /** List of TwitterRawHandlers. */
126 130
     private final List<TwitterRawHandler> rawHandlers = new LinkedList<TwitterRawHandler>();
127 131
 
128 132
     /** What address should API calls be made to? */
@@ -140,7 +144,7 @@ public class TwitterAPI {
140 144
     /** Should we use the versioned API? */
141 145
     private boolean useAPIVersion = false;
142 146
 
143
-    /** 
147
+    /**
144 148
      * What version of the API should we try to use?
145 149
      * If useAPIVersion is false this is irrelevent, otherwise method calls will
146 150
      * try to use this version of the API, otherwise falling back to any lower
@@ -194,7 +198,9 @@ public class TwitterAPI {
194 198
             return;
195 199
         }
196 200
 
197
-        if (!consumerKey.isEmpty() && !consumerSecret.isEmpty()) {
201
+        if (consumerKey.isEmpty() || consumerSecret.isEmpty()) {
202
+            useOAuth = false;
203
+        } else {
198 204
             consumer = new DefaultOAuthConsumer(consumerKey, consumerSecret, SignatureMethod.HMAC_SHA1);
199 205
             final String thisOauthAddress = ((useSSL) ? "https" : "http") + "://" + ((oauthAddress == null || oauthAddress.isEmpty()) ? apiAddress.replaceAll("/+$", "") + "/oauth" : oauthAddress.replaceAll("/+$", ""));
200 206
 
@@ -204,15 +210,13 @@ public class TwitterAPI {
204 210
             this.tokenSecret = tokenSecret;
205 211
 
206 212
             try {
207
-                useOAuth = !(getOAuthURL().isEmpty());
213
+                useOAuth = !getOAuthURL().isEmpty();
208 214
             } catch (final TwitterRuntimeException tre) {
209 215
                 useOAuth = false;
210 216
             }
211
-        } else {
212
-            useOAuth = false;
213 217
         }
214 218
 
215
-        this.useAPIVersion = useAPIVersion && (apiVersion != 0);
219
+        this.useAPIVersion = useAPIVersion && apiVersion != 0;
216 220
         if (apiVersion > 0) {
217 221
             this.apiVersion = apiVersion;
218 222
         }
@@ -422,9 +426,9 @@ public class TwitterAPI {
422 426
         this.debug = debug;
423 427
     }
424 428
 
425
-    /** 
429
+    /**
426 430
      * Are we using oauth?
427
-     * 
431
+     *
428 432
      * @return are we usin oauth?
429 433
      */
430 434
     public boolean useOAuth() {
@@ -484,15 +488,14 @@ public class TwitterAPI {
484 488
     public void setApiVersion(final int apiVersion) {
485 489
         this.apiVersion = apiVersion;
486 490
 
487
-        if (useAPIVersion) {
491
+        if (useAPIVersion && !isAllowed(true)) {
488 492
             // if we are allowed, isAllowed will automatically call getUser() to
489 493
             // update the cache with our own user object.
490
-            if (!isAllowed(true)) {
491
-                // If not, add a temporary one.
492
-                // It will be replaced as soon as the allowed status is changed to
493
-                // true by isAlowed().
494
-                updateUser(new TwitterUser(this, myLoginUsername));
495
-            }
494
+
495
+            // If not, add a temporary one.
496
+            // It will be replaced as soon as the allowed status is changed to
497
+            // true by isAlowed().
498
+            updateUser(new TwitterUser(this, myLoginUsername));
496 499
         }
497 500
     }
498 501
 
@@ -550,20 +553,19 @@ public class TwitterAPI {
550 553
             // sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
551 554
             // String encodedAuthorization = enc.encode(userpassword.getBytes());
552 555
 
553
-            final String encodedAuthorization = b64encode(myLoginUsername + ":" + myPassword);
554
-            connection.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
556
+            connection.setRequestProperty("Authorization", "Basic "
557
+                    + b64encode(myLoginUsername + ":" + myPassword));
555 558
         }
556 559
     }
557 560
 
558 561
     /**
559
-     * Encode a string to base64,
562
+     * Encode a string to base64.
560 563
      * Based on code from http://www.wikihow.com/Encode-a-String-to-Base64-With-Java
561 564
      *
562 565
      * @param string String to encode
563 566
      * @return Encoded output
564 567
      */
565
-    private String b64encode(final String string) {
566
-        final String base64code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
568
+    private static String b64encode(final String string) {
567 569
         final StringBuilder encoded = new StringBuilder();
568 570
         byte[] stringArray;
569 571
         try {
@@ -581,11 +583,11 @@ public class TwitterAPI {
581 583
 
582 584
         // process 3 bytes at a time, churning out 4 output bytes
583 585
         for (int i = 0; i < padded.length; i += 3) {
584
-            int j = (padded[i] << 16) + (padded[i + 1] << 8) + padded[i + 2];
585
-            encoded.append(base64code.charAt((j >> 18) & 0x3f));
586
-            encoded.append(base64code.charAt((j >> 12) & 0x3f));
587
-            encoded.append(base64code.charAt((j >> 6) & 0x3f));
588
-            encoded.append(base64code.charAt(j & 0x3f));
586
+            final int j = (padded[i] << 16) + (padded[i + 1] << 8) + padded[i + 2];
587
+            encoded.append(BASE64_CHARS.charAt((j >> 18) & 0x3f));
588
+            encoded.append(BASE64_CHARS.charAt((j >> 12) & 0x3f));
589
+            encoded.append(BASE64_CHARS.charAt((j >> 6) & 0x3f));
590
+            encoded.append(BASE64_CHARS.charAt(j & 0x3f));
589 591
         }
590 592
 
591 593
         // replace encoded padding nulls with "="
@@ -618,14 +620,14 @@ public class TwitterAPI {
618 620
      */
619 621
     public static Long timeStringToLong(final String string, final long fallback) {
620 622
         try {
621
-            return (new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy").parse(string)).getTime();
623
+            return new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy").parse(string).getTime();
622 624
         } catch (final ParseException ex) {
623 625
             return fallback;
624 626
         }
625 627
     }
626 628
 
627 629
     /**
628
-     * Parse the given string to a boolean, returns true for "true", "yes" or "1"
630
+     * Parse the given string to a boolean, returns true for "true", "yes" or "1".
629 631
      *
630 632
      * @param string String to parse.
631 633
      * @return Boolean from string
@@ -636,7 +638,7 @@ public class TwitterAPI {
636 638
 
637 639
     /**
638 640
      * Get the contents of the given node from an element.
639
-     * If node doesn't exist, fallbcak will be returned.
641
+     * If node doesn't exist, fallback will be returned.
640 642
      *
641 643
      * @param element Element to look at
642 644
      * @param string Node to get content from.
@@ -793,10 +795,10 @@ public class TwitterAPI {
793 795
             if (isDebug()) {
794 796
                 handleError(ex, "* (4) getXML: " + request.getURL(), apiInput, apiOutput);
795 797
             }
796
-            if (request.getErrorStream() != null) {
797
-                in = new BufferedReader(new InputStreamReader(request.getErrorStream()));
798
-            } else {
798
+            if (request.getErrorStream() == null) {
799 799
                 return new XMLResponse(request, null);
800
+            } else {
801
+                in = new BufferedReader(new InputStreamReader(request.getErrorStream()));
800 802
             }
801 803
         }
802 804
 
@@ -1084,7 +1086,7 @@ public class TwitterAPI {
1084 1086
     }
1085 1087
 
1086 1088
     /**
1087
-     * Send a direct message to the given user
1089
+     * Send a direct message to the given user.
1088 1090
      *
1089 1091
      * @param target Target user.
1090 1092
      * @param message Message to send.
@@ -1440,7 +1442,7 @@ public class TwitterAPI {
1440 1442
     }
1441 1443
 
1442 1444
     /**
1443
-     * Retweet the given status
1445
+     * Retweet the given status.
1444 1446
      *
1445 1447
      * @param status Status to retweet
1446 1448
      * @return True if status was retweeted ok.
@@ -1489,7 +1491,7 @@ public class TwitterAPI {
1489 1491
      *          - 3 is the estimated number of api calls we have made since
1490 1492
      *            the last reset.
1491 1493
      */
1492
-    public Long[] getRemainingApiCalls() {
1494
+    public long[] getRemainingApiCalls() {
1493 1495
         final XMLResponse doc = getXML(getURL("account/rate_limit_status"));
1494 1496
         // The call we just made doesn't count, so remove it from the count.
1495 1497
         usedCalls--;
@@ -1503,9 +1505,9 @@ public class TwitterAPI {
1503 1505
             final String resetTimeString = getElementContents(element, "reset-time-in-seconds", getElementContents(element, "reset_time_in_seconds", "0"));
1504 1506
             resetTime = 1000 * parseLong(resetTimeString, -1);
1505 1507
 
1506
-            return new Long[]{remaining, total, resetTime, (long) usedCalls};
1508
+            return new long[]{remaining, total, resetTime, (long) usedCalls};
1507 1509
         } else {
1508
-            return new Long[]{0L, 0L, System.currentTimeMillis(), (long) usedCalls};
1510
+            return new long[]{0L, 0L, System.currentTimeMillis(), (long) usedCalls};
1509 1511
         }
1510 1512
     }
1511 1513
 
@@ -1712,7 +1714,7 @@ public class TwitterAPI {
1712 1714
 
1713 1715
     /**
1714 1716
      * Block a user on twitter.
1715
-     * 
1717
+     *
1716 1718
      * @param name Username to block.
1717 1719
      * @return The user just blocked.
1718 1720
      */
@@ -1736,7 +1738,7 @@ public class TwitterAPI {
1736 1738
 
1737 1739
     /**
1738 1740
      * Unblock a user on twitter.
1739
-     * 
1741
+     *
1740 1742
      * @param name Username to unblock.
1741 1743
      * @return The user just unblocked.
1742 1744
      */

Loading…
Cancel
Save