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
 import com.dmdirc.parser.common.ChannelJoinRequest;
37
 import com.dmdirc.parser.common.ChannelJoinRequest;
38
 import com.dmdirc.parser.common.DefaultStringConverter;
38
 import com.dmdirc.parser.common.DefaultStringConverter;
39
 import com.dmdirc.parser.common.IgnoreList;
39
 import com.dmdirc.parser.common.IgnoreList;
40
-import com.dmdirc.parser.common.MyInfo;
41
 import com.dmdirc.parser.common.QueuePriority;
40
 import com.dmdirc.parser.common.QueuePriority;
42
 import com.dmdirc.parser.interfaces.ChannelClientInfo;
41
 import com.dmdirc.parser.interfaces.ChannelClientInfo;
43
 import com.dmdirc.parser.interfaces.ChannelInfo;
42
 import com.dmdirc.parser.interfaces.ChannelInfo;
90
  */
89
  */
91
 public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler, ConfigChangeListener {
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
     /** Are we connected? */
97
     /** Are we connected? */
94
     private boolean connected = false;
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
     /** Twitter API. */
103
     /** Twitter API. */
100
     private TwitterAPI api = new TwitterAPI("", "", "", false, -1, false);
104
     private TwitterAPI api = new TwitterAPI("", "", "", false, -1, false);
127
     private TwitterClientInfo myself = null;
131
     private TwitterClientInfo myself = null;
128
 
132
 
129
     /** List of currently active twitter parsers. */
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
     /** Are we waiting for authentication? */
136
     /** Are we waiting for authentication? */
133
     private boolean wantAuth = false;
137
     private boolean wantAuth = false;
147
     /** Address that created us. */
151
     /** Address that created us. */
148
     private final URI myAddress;
152
     private final URI myAddress;
149
 
153
 
150
-    /** Main Channel Name */
154
+    /** Main Channel Name. */
151
     private final String mainChannelName;
155
     private final String mainChannelName;
152
 
156
 
153
     /** Config Manager for this parser. */
157
     /** Config Manager for this parser. */
162
     /** Automatically leave & channels? */
166
     /** Automatically leave & channels? */
163
     private boolean autoLeaveMessageChannel;
167
     private boolean autoLeaveMessageChannel;
164
 
168
 
165
-    /** Save last IDs */
169
+    /** Save last IDs. */
166
     private boolean saveLastIDs;
170
     private boolean saveLastIDs;
167
 
171
 
168
     /** Last Reply ID. */
172
     /** Last Reply ID. */
175
     private long lastDirectMessageId = -1;
179
     private long lastDirectMessageId = -1;
176
 
180
 
177
     /** Last IDs in searched hashtag channels. */
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
     /** Status count. */
185
     /** Status count. */
181
     private int statusCount;
186
     private int statusCount;
183
     /** Get sent messages. */
188
     /** Get sent messages. */
184
     private boolean getSentMessage;
189
     private boolean getSentMessage;
185
 
190
 
186
-    /** Number of api calls to use. */
191
+    /** Number of API calls to use. */
187
     private int apicalls;
192
     private int apicalls;
188
 
193
 
189
     /** Auto append @ to nicknames. */
194
     /** Auto append @ to nicknames. */
198
     /**
203
     /**
199
      * Create a new Twitter Parser!
204
      * Create a new Twitter Parser!
200
      *
205
      *
201
-     * @param myInfo The client information to use
202
      * @param address The address of the server to connect to
206
      * @param address The address of the server to connect to
203
      * @param myPlugin Plugin that created this parser
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
         final String[] bits;
210
         final String[] bits;
207
         if (address.getUserInfo() == null) {
211
         if (address.getUserInfo() == null) {
208
             bits = new String[]{};
212
             bits = new String[]{};
239
     @Override
243
     @Override
240
     public void disconnect(final String message) {
244
     public void disconnect(final String message) {
241
         connected = false;
245
         connected = false;
242
-        currentParsers.remove(this);
246
+        PARSERS.remove(this);
243
         api = new TwitterAPI("", "", "", false, -1, false);
247
         api = new TwitterAPI("", "", "", false, -1, false);
244
 
248
 
245
         getCallbackManager().getCallbackType(SocketCloseListener.class).call();
249
         getCallbackManager().getCallbackType(SocketCloseListener.class).call();
270
                     try {
274
                     try {
271
                         final long id = Long.parseLong(channel.substring(1));
275
                         final long id = Long.parseLong(channel.substring(1));
272
                         final TwitterStatus status = api.getStatus(id);
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
                             if (status.getReplyTo() > 0) {
280
                             if (status.getReplyTo() > 0) {
275
                                 newChannel.setLocalTopic(status.getText() + " [Reply to: &" + status.getReplyTo() + "]");
281
                                 newChannel.setLocalTopic(status.getText() + " [Reply to: &" + status.getReplyTo() + "]");
276
                             } else {
282
                             } else {
284
                                 clients.put(client.getNickname().toLowerCase(), client);
290
                                 clients.put(client.getNickname().toLowerCase(), client);
285
                             }
291
                             }
286
                             newChannel.addChannelClient(new TwitterChannelClientInfo(newChannel, client));
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
                         synchronized (this.channels) {
295
                         synchronized (this.channels) {
291
                             this.channels.put(channel, newChannel);
296
                             this.channels.put(channel, newChannel);
292
                         }
297
                         }
293
                     } catch (final NumberFormatException nfe) {
298
                     } catch (final NumberFormatException nfe) {
294
                     }
299
                     }
295
-                } else if (channel.startsWith("#")) {
300
+                } else if (channel.charAt(0) == '#') {
296
                     newChannel.setLocalTopic("Search results for " + channel);
301
                     newChannel.setLocalTopic("Search results for " + channel);
297
                     synchronized (this.channels) {
302
                     synchronized (this.channels) {
298
                         this.channels.put(channel, newChannel);
303
                         this.channels.put(channel, newChannel);
308
 
313
 
309
     /**
314
     /**
310
      * Remove a channel from the known channels list.
315
      * Remove a channel from the known channels list.
311
-     * 
312
-     * @param channel
316
+     *
317
+     * @param channel The channel to part
313
      */
318
      */
314
     protected void partChannel(final ChannelInfo channel) {
319
     protected void partChannel(final ChannelInfo channel) {
315
         if (channel == null) { return; }
320
         if (channel == null) { return; }
339
     /** {@inheritDoc} */
344
     /** {@inheritDoc} */
340
     @Override
345
     @Override
341
     public void setBindIP(final String ip) {
346
     public void setBindIP(final String ip) {
342
-        return;
347
+        // Ignore
343
     }
348
     }
344
 
349
 
345
     /** {@inheritDoc} */
350
     /** {@inheritDoc} */
370
      */
375
      */
371
     public static String[] tokeniseLine(final String line) {
376
     public static String[] tokeniseLine(final String line) {
372
         if (line == null) {
377
         if (line == null) {
373
-            return new String[]{"",}; // Return empty string[]
378
+            return new String[]{""};
374
         }
379
         }
375
 
380
 
376
         final int lastarg = line.indexOf(" :");
381
         final int lastarg = line.indexOf(" :");
451
                     getCallbackManager().getCallbackType(NumericListener.class).call(301, new String[]{":" + myServerName, "301", myself.getNickname(), bits[1], "Location: " + user.getLocation()});
456
                     getCallbackManager().getCallbackType(NumericListener.class).call(301, new String[]{":" + myServerName, "301", myself.getNickname(), bits[1], "Location: " + user.getLocation()});
452
                     getCallbackManager().getCallbackType(NumericListener.class).call(301, new String[]{":" + myServerName, "301", myself.getNickname(), bits[1], "Status: " + user.getStatus().getText()});
457
                     getCallbackManager().getCallbackType(NumericListener.class).call(301, new String[]{":" + myServerName, "301", myself.getNickname(), bits[1], "Status: " + user.getStatus().getText()});
453
                     if (bits[1].equalsIgnoreCase(myself.getNickname())) {
458
                     if (bits[1].equalsIgnoreCase(myself.getNickname())) {
454
-                        final Long[] apiCalls = api.getRemainingApiCalls();
459
+                        final long[] apiCalls = api.getRemainingApiCalls();
455
                         getCallbackManager().getCallbackType(NumericListener.class).call(301, new String[]{":" + myServerName, "301", myself.getNickname(), bits[1], "API Allowance: " + apiCalls[1]});
460
                         getCallbackManager().getCallbackType(NumericListener.class).call(301, new String[]{":" + myServerName, "301", myself.getNickname(), bits[1], "API Allowance: " + apiCalls[1]});
456
                         getCallbackManager().getCallbackType(NumericListener.class).call(301, new String[]{":" + myServerName, "301", myself.getNickname(), bits[1], "API Allowance Remaining: " + apiCalls[0]});
461
                         getCallbackManager().getCallbackType(NumericListener.class).call(301, new String[]{":" + myServerName, "301", myself.getNickname(), bits[1], "API Allowance Remaining: " + apiCalls[0]});
457
                         getCallbackManager().getCallbackType(NumericListener.class).call(301, new String[]{":" + myServerName, "301", myself.getNickname(), bits[1], "API Calls Used: " + apiCalls[3]});
462
                         getCallbackManager().getCallbackType(NumericListener.class).call(301, new String[]{":" + myServerName, "301", myself.getNickname(), bits[1], "API Calls Used: " + apiCalls[3]});
505
     /** {@inheritDoc} */
510
     /** {@inheritDoc} */
506
     @Override
511
     @Override
507
     public boolean isValidChannelName(final String name) {
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
     /** {@inheritDoc} */
516
     /** {@inheritDoc} */
638
                 final long id = Long.parseLong(target.substring(1));
643
                 final long id = Long.parseLong(target.substring(1));
639
                 if (type.equalsIgnoreCase("retweet") || type.equalsIgnoreCase("rt")) {
644
                 if (type.equalsIgnoreCase("retweet") || type.equalsIgnoreCase("rt")) {
640
                     final TwitterStatus status = api.getStatus(id);
645
                     final TwitterStatus status = api.getStatus(id);
641
-                    if (status != null) {
646
+                    if (status == null) {
647
+                        sendPrivateNotice("Invalid Tweet ID.");
648
+                    } else {
642
                         sendPrivateNotice("Retweeting: <" + status.getUser().getScreenName() + "> " + status.getText());
649
                         sendPrivateNotice("Retweeting: <" + status.getUser().getScreenName() + "> " + status.getText());
643
                         if (api.retweetStatus(status)) {
650
                         if (api.retweetStatus(status)) {
644
                             sendPrivateNotice("Retweet was successful.");
651
                             sendPrivateNotice("Retweet was successful.");
647
                         } else {
654
                         } else {
648
                             sendPrivateNotice("Retweeting Failed.");
655
                             sendPrivateNotice("Retweeting Failed.");
649
                         }
656
                         }
650
-                    } else {
651
-                        sendPrivateNotice("Invalid Tweet ID.");
652
                     }
657
                     }
653
                 } else if (type.equalsIgnoreCase("delete") || type.equalsIgnoreCase("del")) {
658
                 } else if (type.equalsIgnoreCase("delete") || type.equalsIgnoreCase("del")) {
654
                     final TwitterStatus status = api.getStatus(id);
659
                     final TwitterStatus status = api.getStatus(id);
655
-                    if (status != null) {
660
+                    if (status == null) {
661
+                        sendPrivateNotice("Invalid Tweet ID.");
662
+                    } else {
656
                         sendPrivateNotice("Deleting: <" + status.getUser().getScreenName() + "> " + status.getText());
663
                         sendPrivateNotice("Deleting: <" + status.getUser().getScreenName() + "> " + status.getText());
657
                         if (api.deleteStatus(status)) {
664
                         if (api.deleteStatus(status)) {
658
                             sendPrivateNotice("Deleting was successful, deleted tweets will still be accessible for some time.");
665
                             sendPrivateNotice("Deleting was successful, deleted tweets will still be accessible for some time.");
661
                         } else {
668
                         } else {
662
                             sendPrivateNotice("Deleting Failed.");
669
                             sendPrivateNotice("Deleting Failed.");
663
                         }
670
                         }
664
-                    } else {
665
-                        sendPrivateNotice("Invalid Tweet ID.");
666
                     }
671
                     }
667
                 }
672
                 }
668
             } catch (final NumberFormatException nfe) {
673
             } catch (final NumberFormatException nfe) {
669
                 sendPrivateNotice("Invalid Tweet ID.");
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
             if (type.equalsIgnoreCase("update") || type.equalsIgnoreCase("refresh")) {
677
             if (type.equalsIgnoreCase("update") || type.equalsIgnoreCase("refresh")) {
673
                 final TwitterChannelInfo channel = (TwitterChannelInfo) getChannel(target);
678
                 final TwitterChannelInfo channel = (TwitterChannelInfo) getChannel(target);
674
                 sendChannelNotice(channel, "Refreshing...");
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
         } else {
684
         } else {
692
     /** {@inheritDoc} */
695
     /** {@inheritDoc} */
693
     @Override
696
     @Override
694
     public void sendMessage(final String target, final String message) {
697
     public void sendMessage(final String target, final String message) {
695
-        final TwitterChannelInfo channel = (TwitterChannelInfo) getChannel(target);
696
         if (target.equalsIgnoreCase(mainChannelName)) {
698
         if (target.equalsIgnoreCase(mainChannelName)) {
697
             if (wantAuth) {
699
             if (wantAuth) {
700
+                final TwitterChannelInfo channel = (TwitterChannelInfo) getChannel(target);
698
                 final String[] bits = message.split(" ");
701
                 final String[] bits = message.split(" ");
699
                 if (bits[0].equalsIgnoreCase("usepw")) {
702
                 if (bits[0].equalsIgnoreCase("usepw")) {
700
                     sendChannelMessage(channel, "Switching to once-off password authentication, please enter your password.");
703
                     sendChannelMessage(channel, "Switching to once-off password authentication, please enter your password.");
739
             sendPrivateNotice("DMDirc has not been authorised to use this account yet.");
742
             sendPrivateNotice("DMDirc has not been authorised to use this account yet.");
740
         } else if (target.matches("^&[0-9]+$")) {
743
         } else if (target.matches("^&[0-9]+$")) {
741
             try {
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
                     sendPrivateNotice("Setting status ok.");
746
                     sendPrivateNotice("Setting status ok.");
745
                     if (autoLeaveMessageChannel) {
747
                     if (autoLeaveMessageChannel) {
746
                         partChannel(getChannel(target));
748
                         partChannel(getChannel(target));
750
                 }
752
                 }
751
             } catch (final NumberFormatException nfe) {
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
             if (api.newDirectMessage(target, message)) {
758
             if (api.newDirectMessage(target, message)) {
755
                 sendPrivateNotice("Sending Direct Message to '" + target + "' was successful.");
759
                 sendPrivateNotice("Sending Direct Message to '" + target + "' was successful.");
756
             } else {
760
             } else {
757
                 sendPrivateNotice("Sending Direct Message to '" + target + "' failed.");
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
 
801
 
800
     /** {@inheritDoc} */
802
     /** {@inheritDoc} */
801
     @Override
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
     /** {@inheritDoc} */
808
     /** {@inheritDoc} */
805
     @Override
809
     @Override
809
 
813
 
810
     /** {@inheritDoc} */
814
     /** {@inheritDoc} */
811
     @Override
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
     /** {@inheritDoc} */
820
     /** {@inheritDoc} */
815
     @Override
821
     @Override
826
         getCallbackManager().getCallbackType(PrivateNoticeListener.class).call(message, myServerName);
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
      * Send a PM to the client.
836
      * Send a PM to the client.
850
      *
837
      *
1039
 
1026
 
1040
         api = new TwitterAPI(myUsername, myPassword, apiAddress, "", consumerKey, consumerSecret, token, tokenSecret, apiVersioning, apiVersion, getConfigManager().getOptionBool(myPlugin.getDomain(), "autoAt"));
1027
         api = new TwitterAPI(myUsername, myPassword, apiAddress, "", consumerKey, consumerSecret, token, tokenSecret, apiVersioning, apiVersion, getConfigManager().getOptionBool(myPlugin.getDomain(), "autoAt"));
1041
         api.setSource("DMDirc");
1028
         api.setSource("DMDirc");
1042
-        currentParsers.add(this);
1029
+        PARSERS.add(this);
1043
         api.addErrorHandler(this);
1030
         api.addErrorHandler(this);
1044
         api.addRawHandler(this);
1031
         api.addRawHandler(this);
1045
         api.setDebug(debugEnabled);
1032
         api.setDebug(debugEnabled);
1084
 
1071
 
1085
         sendChannelMessage(channel, "Checking to see if we have been authorised to use the account \"" + api.getLoginUsername() + "\"...");
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
             wantAuth = true;
1078
             wantAuth = true;
1089
             if (api.useOAuth()) {
1079
             if (api.useOAuth()) {
1090
                 sendChannelMessage(channel, "Sorry, DMDirc has not been authorised to use the account \"" + api.getLoginUsername() + "\"");
1080
                 sendChannelMessage(channel, "Sorry, DMDirc has not been authorised to use the account \"" + api.getLoginUsername() + "\"");
1100
                 sendChannelMessage(channel, "");
1090
                 sendChannelMessage(channel, "");
1101
                 sendChannelMessage(channel, "To do this, please type the password here, or set it correctly in the URL (twitter://" + myUsername + ":your_password@" + myServerName + myAddress.getPath() + ").");
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
         if (saveLastIDs) {
1095
         if (saveLastIDs) {
1120
         boolean first = true; // Used to let used know if there was no new items.
1107
         boolean first = true; // Used to let used know if there was no new items.
1121
 
1108
 
1122
         int count = 0;
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
         while (connected) {
1110
         while (connected) {
1126
-            final int startCalls = (wantAuth) ? 0 : api.getUsedCalls();
1111
+            final int startCalls = wantAuth ? 0 : api.getUsedCalls();
1127
 
1112
 
1128
             // Get Updates
1113
             // Get Updates
1129
             final boolean foundUpdates = getUpdates(channel);
1114
             final boolean foundUpdates = getUpdates(channel);
1145
             }
1130
             }
1146
 
1131
 
1147
             // Calculate number of calls remaining.
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
             doDebug(Debug.apiCalls, "Twitter calls Remaining: " + apiCalls[0]);
1135
             doDebug(Debug.apiCalls, "Twitter calls Remaining: " + apiCalls[0]);
1151
             // laconica doesn't rate limit, so time to reset is always 0, in this case
1136
             // laconica doesn't rate limit, so time to reset is always 0, in this case
1152
             // we will assume the time of the next hour.
1137
             // we will assume the time of the next hour.
1153
             final Calendar cal = Calendar.getInstance();
1138
             final Calendar cal = Calendar.getInstance();
1154
             cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE), cal.get(Calendar.HOUR_OF_DAY) + 1, 0, 0);
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
             final long sleepTime;
1142
             final long sleepTime;
1158
             if (wantAuth) {
1143
             if (wantAuth) {
1159
                 // When waiting for auth, sleep for less time so that when the
1144
                 // When waiting for auth, sleep for less time so that when the
1181
                 // How many calls do we make each time?
1166
                 // How many calls do we make each time?
1182
                 // If this is less than 0 (If there was a time reset between
1167
                 // If this is less than 0 (If there was a time reset between
1183
                 // calculating the start and end calls used) then assume 3.
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
                 doDebug(Debug.apiCalls, "\tCalls Remaining: " + callsLeft);
1171
                 doDebug(Debug.apiCalls, "\tCalls Remaining: " + callsLeft);
1187
                 doDebug(Debug.apiCalls, "\tCalls per time: " + callsPerTime);
1172
                 doDebug(Debug.apiCalls, "\tCalls per time: " + callsPerTime);
1202
             // Sleep for sleep time,
1187
             // Sleep for sleep time,
1203
             // If we have a negative sleep time, use 5 minutes.
1188
             // If we have a negative sleep time, use 5 minutes.
1204
             try {
1189
             try {
1205
-                Thread.sleep((sleepTime > 0) ? sleepTime : 5 * 60 * 1000);
1190
+                Thread.sleep(sleepTime > 0 ? sleepTime : 5 * 60 * 1000);
1206
             } catch (final InterruptedException ex) {
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
         boolean foundItems = false;
1207
         boolean foundItems = false;
1223
         if (!wantAuth && api.isAllowed()) {
1208
         if (!wantAuth && api.isAllowed()) {
1224
             lastQueryTime = System.currentTimeMillis();
1209
             lastQueryTime = System.currentTimeMillis();
1225
-            final int statusesPerAttempt = Math.min(200, statusCount);
1226
 
1210
 
1227
             if (channel.getName().startsWith("#")) {
1211
             if (channel.getName().startsWith("#")) {
1228
                 long lastId = lastSearchIds.containsKey(channel) ? lastSearchIds.get(channel) : -1;
1212
                 long lastId = lastSearchIds.containsKey(channel) ? lastSearchIds.get(channel) : -1;
1237
 
1221
 
1238
                 lastSearchIds.put(channel, lastId);
1222
                 lastSearchIds.put(channel, lastId);
1239
             } else {
1223
             } else {
1224
+                final int statusesPerAttempt = Math.min(200, statusCount);
1240
                 final List<TwitterStatus> statuses = new ArrayList<TwitterStatus>();
1225
                 final List<TwitterStatus> statuses = new ArrayList<TwitterStatus>();
1241
                 for (final TwitterStatus status : api.getReplies(lastReplyId, statusesPerAttempt)) {
1226
                 for (final TwitterStatus status : api.getReplies(lastReplyId, statusesPerAttempt)) {
1242
                     statuses.add(status);
1227
                     statuses.add(status);
1337
     }
1322
     }
1338
 
1323
 
1339
     /**
1324
     /**
1340
-     * Get the Twitter API Object
1341
-     * 
1325
+     * Get the Twitter API Object.
1326
+     *
1342
      * @return The Twitter API Object
1327
      * @return The Twitter API Object
1343
      */
1328
      */
1344
     public TwitterAPI getApi() {
1329
     public TwitterAPI getApi() {
1365
 
1350
 
1366
     /**
1351
     /**
1367
      * Set the twitter status.
1352
      * Set the twitter status.
1368
-     * 
1353
+     *
1369
      * @param message Status to use.
1354
      * @param message Status to use.
1370
      * @return True if status was updated, else false.
1355
      * @return True if status was updated, else false.
1371
      */
1356
      */
1377
      * Set the twitter status.
1362
      * Set the twitter status.
1378
      *
1363
      *
1379
      * @param message Status to use.
1364
      * @param message Status to use.
1380
-     * @param id
1365
+     * @param replyToId The ID this status is in reply to, or -1
1381
      * @return True if status was updated, else false.
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
         final StringBuffer newStatus = new StringBuffer(message);
1369
         final StringBuffer newStatus = new StringBuffer(message);
1385
         final TwitterChannelInfo channel = (TwitterChannelInfo) getChannel(mainChannelName);
1370
         final TwitterChannelInfo channel = (TwitterChannelInfo) getChannel(mainChannelName);
1386
 
1371
 
1391
 
1376
 
1392
                 final ChannelClientInfo cci = channel.getChannelClient(name);
1377
                 final ChannelClientInfo cci = channel.getChannelClient(name);
1393
                 if (cci != null) {
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
                         bits[0] = cci.getClient().getNickname();
1380
                         bits[0] = cci.getClient().getNickname();
1381
+                    } else {
1382
+                        bits[0] = "@" + cci.getClient().getNickname();
1398
                     }
1383
                     }
1399
 
1384
 
1400
                     newStatus.setLength(0);
1385
                     newStatus.setLength(0);
1401
                     for (final String bit : bits) {
1386
                     for (final String bit : bits) {
1402
                         if (newStatus.length() > 0) {
1387
                         if (newStatus.length() > 0) {
1403
-                            newStatus.append(" ");
1388
+                            newStatus.append(' ');
1404
                         }
1389
                         }
1405
                         newStatus.append(bit);
1390
                         newStatus.append(bit);
1406
                     }
1391
                     }
1408
             }
1393
             }
1409
         }
1394
         }
1410
 
1395
 
1411
-        if (api.setStatus(newStatus.toString(), id)) {
1396
+        if (api.setStatus(newStatus.toString(), replyToId)) {
1412
             checkTopic(channel, myself.getUser().getStatus());
1397
             checkTopic(channel, myself.getUser().getStatus());
1413
             return true;
1398
             return true;
1414
         }
1399
         }
1501
             return;
1486
             return;
1502
         }
1487
         }
1503
         try {
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
                 twitterFail("Recieved an error: " + source);
1490
                 twitterFail("Recieved an error: " + source);
1491
+            } else if (debugEnabled) {
1492
+                twitterFail("Recieved an error from twitter: " + message + (debugEnabled ? " [" + source + "]" : ""));
1508
             }
1493
             }
1509
             if (t != null) {
1494
             if (t != null) {
1510
                 doDebug(Debug.twitterError, t.getClass().getSimpleName() + ": " + t + " -> " + t.getMessage());
1495
                 doDebug(Debug.twitterError, t.getClass().getSimpleName() + ": " + t + " -> " + t.getMessage());
1526
             }
1511
             }
1527
 
1512
 
1528
             doDebug(Debug.twitterErrorMore, "==================================");
1513
             doDebug(Debug.twitterErrorMore, "==================================");
1529
-        } catch (final Throwable t2) {
1514
+        } catch (final Exception t2) {
1530
             doDebug(Debug.twitterError, "wtf? (See Console for stack trace) " + t2);
1515
             doDebug(Debug.twitterError, "wtf? (See Console for stack trace) " + t2);
1531
             t2.printStackTrace();
1516
             t2.printStackTrace();
1532
         }
1517
         }
1643
     /** {@inheritDoc} */
1628
     /** {@inheritDoc} */
1644
     @Override
1629
     @Override
1645
     public List<String> getServerInformationLines() {
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
 import com.dmdirc.parser.interfaces.Parser;
33
 import com.dmdirc.parser.interfaces.Parser;
34
 import com.dmdirc.parser.interfaces.ProtocolDescription;
34
 import com.dmdirc.parser.interfaces.ProtocolDescription;
35
 import com.dmdirc.plugins.Plugin;
35
 import com.dmdirc.plugins.Plugin;
36
+
36
 import java.net.URI;
37
 import java.net.URI;
37
 import java.util.ArrayList;
38
 import java.util.ArrayList;
38
 
39
 
39
 /**
40
 /**
41
+ * Facilitates creation of Twitter parsers.
40
  *
42
  *
41
  * @author shane
43
  * @author shane
42
  */
44
  */
43
 public class TwitterPlugin extends Plugin {
45
 public class TwitterPlugin extends Plugin {
44
 
46
 
45
     /** Are we currently unloading? */
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
     /** {@inheritDoc} */
50
     /** {@inheritDoc} */
55
     @Override
51
     @Override
61
     @Override
57
     @Override
62
     public void onUnload() {
58
     public void onUnload() {
63
         unloading = true;
59
         unloading = true;
64
-        for (final Twitter parser : new ArrayList<Twitter>(Twitter.currentParsers)) {
60
+        for (final Twitter parser : new ArrayList<Twitter>(Twitter.PARSERS)) {
65
             parser.disconnect("");
61
             parser.disconnect("");
66
         }
62
         }
67
     }
63
     }
74
      * @return An appropriately configured parser
70
      * @return An appropriately configured parser
75
      */
71
      */
76
     public Parser getParser(final MyInfo myInfo, final URI address) {
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
 
63
 
64
 /**
64
 /**
65
  * Implementation of the twitter API for DMDirc.
65
  * Implementation of the twitter API for DMDirc.
66
- * 
66
+ *
67
  * @author shane
67
  * @author shane
68
  */
68
  */
69
 public class TwitterAPI {
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
     private OAuthConsumer consumer;
76
     private OAuthConsumer consumer;
73
 
77
 
74
-    /** OAuth Provider */
78
+    /** OAuth Provider. */
75
     private OAuthProvider provider;
79
     private OAuthProvider provider;
76
 
80
 
77
     /** Have we signed anything yet? */
81
     /** Have we signed anything yet? */
98
     /** Cache of statuses. */
102
     /** Cache of statuses. */
99
     final Map<Long, TwitterStatus> statusCache = new HashMap<Long, TwitterStatus>();
103
     final Map<Long, TwitterStatus> statusCache = new HashMap<Long, TwitterStatus>();
100
 
104
 
101
-    /** API Allowed status */
105
+    /** API Allowed status. */
102
     private APIAllowed allowed = APIAllowed.UNKNOWN;
106
     private APIAllowed allowed = APIAllowed.UNKNOWN;
103
 
107
 
104
     /** How many API calls have we made since the last reset? */
108
     /** How many API calls have we made since the last reset? */
107
     /** API reset time. */
111
     /** API reset time. */
108
     private long resetTime = 0;
112
     private long resetTime = 0;
109
 
113
 
110
-    /** Twitter Token */
114
+    /** Twitter Token. */
111
     private String token = "";
115
     private String token = "";
112
 
116
 
113
-    /** Twitter Token Secret */
117
+    /** Twitter Token Secret. */
114
     private String tokenSecret = "";
118
     private String tokenSecret = "";
115
 
119
 
116
     /** Last input to the API. */
120
     /** Last input to the API. */
119
     /** Last output from the API. */
123
     /** Last output from the API. */
120
     private String apiOutput = "";
124
     private String apiOutput = "";
121
 
125
 
122
-    /** List of TwitterErrorHandlers */
126
+    /** List of TwitterErrorHandlers. */
123
     private final List<TwitterErrorHandler> errorHandlers = new LinkedList<TwitterErrorHandler>();
127
     private final List<TwitterErrorHandler> errorHandlers = new LinkedList<TwitterErrorHandler>();
124
 
128
 
125
-    /** List of TwitterRawHandlers */
129
+    /** List of TwitterRawHandlers. */
126
     private final List<TwitterRawHandler> rawHandlers = new LinkedList<TwitterRawHandler>();
130
     private final List<TwitterRawHandler> rawHandlers = new LinkedList<TwitterRawHandler>();
127
 
131
 
128
     /** What address should API calls be made to? */
132
     /** What address should API calls be made to? */
140
     /** Should we use the versioned API? */
144
     /** Should we use the versioned API? */
141
     private boolean useAPIVersion = false;
145
     private boolean useAPIVersion = false;
142
 
146
 
143
-    /** 
147
+    /**
144
      * What version of the API should we try to use?
148
      * What version of the API should we try to use?
145
      * If useAPIVersion is false this is irrelevent, otherwise method calls will
149
      * If useAPIVersion is false this is irrelevent, otherwise method calls will
146
      * try to use this version of the API, otherwise falling back to any lower
150
      * try to use this version of the API, otherwise falling back to any lower
194
             return;
198
             return;
195
         }
199
         }
196
 
200
 
197
-        if (!consumerKey.isEmpty() && !consumerSecret.isEmpty()) {
201
+        if (consumerKey.isEmpty() || consumerSecret.isEmpty()) {
202
+            useOAuth = false;
203
+        } else {
198
             consumer = new DefaultOAuthConsumer(consumerKey, consumerSecret, SignatureMethod.HMAC_SHA1);
204
             consumer = new DefaultOAuthConsumer(consumerKey, consumerSecret, SignatureMethod.HMAC_SHA1);
199
             final String thisOauthAddress = ((useSSL) ? "https" : "http") + "://" + ((oauthAddress == null || oauthAddress.isEmpty()) ? apiAddress.replaceAll("/+$", "") + "/oauth" : oauthAddress.replaceAll("/+$", ""));
205
             final String thisOauthAddress = ((useSSL) ? "https" : "http") + "://" + ((oauthAddress == null || oauthAddress.isEmpty()) ? apiAddress.replaceAll("/+$", "") + "/oauth" : oauthAddress.replaceAll("/+$", ""));
200
 
206
 
204
             this.tokenSecret = tokenSecret;
210
             this.tokenSecret = tokenSecret;
205
 
211
 
206
             try {
212
             try {
207
-                useOAuth = !(getOAuthURL().isEmpty());
213
+                useOAuth = !getOAuthURL().isEmpty();
208
             } catch (final TwitterRuntimeException tre) {
214
             } catch (final TwitterRuntimeException tre) {
209
                 useOAuth = false;
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
         if (apiVersion > 0) {
220
         if (apiVersion > 0) {
217
             this.apiVersion = apiVersion;
221
             this.apiVersion = apiVersion;
218
         }
222
         }
422
         this.debug = debug;
426
         this.debug = debug;
423
     }
427
     }
424
 
428
 
425
-    /** 
429
+    /**
426
      * Are we using oauth?
430
      * Are we using oauth?
427
-     * 
431
+     *
428
      * @return are we usin oauth?
432
      * @return are we usin oauth?
429
      */
433
      */
430
     public boolean useOAuth() {
434
     public boolean useOAuth() {
484
     public void setApiVersion(final int apiVersion) {
488
     public void setApiVersion(final int apiVersion) {
485
         this.apiVersion = apiVersion;
489
         this.apiVersion = apiVersion;
486
 
490
 
487
-        if (useAPIVersion) {
491
+        if (useAPIVersion && !isAllowed(true)) {
488
             // if we are allowed, isAllowed will automatically call getUser() to
492
             // if we are allowed, isAllowed will automatically call getUser() to
489
             // update the cache with our own user object.
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
             // sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
553
             // sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
551
             // String encodedAuthorization = enc.encode(userpassword.getBytes());
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
      * Based on code from http://www.wikihow.com/Encode-a-String-to-Base64-With-Java
563
      * Based on code from http://www.wikihow.com/Encode-a-String-to-Base64-With-Java
561
      *
564
      *
562
      * @param string String to encode
565
      * @param string String to encode
563
      * @return Encoded output
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
         final StringBuilder encoded = new StringBuilder();
569
         final StringBuilder encoded = new StringBuilder();
568
         byte[] stringArray;
570
         byte[] stringArray;
569
         try {
571
         try {
581
 
583
 
582
         // process 3 bytes at a time, churning out 4 output bytes
584
         // process 3 bytes at a time, churning out 4 output bytes
583
         for (int i = 0; i < padded.length; i += 3) {
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
         // replace encoded padding nulls with "="
593
         // replace encoded padding nulls with "="
618
      */
620
      */
619
     public static Long timeStringToLong(final String string, final long fallback) {
621
     public static Long timeStringToLong(final String string, final long fallback) {
620
         try {
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
         } catch (final ParseException ex) {
624
         } catch (final ParseException ex) {
623
             return fallback;
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
      * @param string String to parse.
632
      * @param string String to parse.
631
      * @return Boolean from string
633
      * @return Boolean from string
636
 
638
 
637
     /**
639
     /**
638
      * Get the contents of the given node from an element.
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
      * @param element Element to look at
643
      * @param element Element to look at
642
      * @param string Node to get content from.
644
      * @param string Node to get content from.
793
             if (isDebug()) {
795
             if (isDebug()) {
794
                 handleError(ex, "* (4) getXML: " + request.getURL(), apiInput, apiOutput);
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
                 return new XMLResponse(request, null);
799
                 return new XMLResponse(request, null);
800
+            } else {
801
+                in = new BufferedReader(new InputStreamReader(request.getErrorStream()));
800
             }
802
             }
801
         }
803
         }
802
 
804
 
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
      * @param target Target user.
1091
      * @param target Target user.
1090
      * @param message Message to send.
1092
      * @param message Message to send.
1440
     }
1442
     }
1441
 
1443
 
1442
     /**
1444
     /**
1443
-     * Retweet the given status
1445
+     * Retweet the given status.
1444
      *
1446
      *
1445
      * @param status Status to retweet
1447
      * @param status Status to retweet
1446
      * @return True if status was retweeted ok.
1448
      * @return True if status was retweeted ok.
1489
      *          - 3 is the estimated number of api calls we have made since
1491
      *          - 3 is the estimated number of api calls we have made since
1490
      *            the last reset.
1492
      *            the last reset.
1491
      */
1493
      */
1492
-    public Long[] getRemainingApiCalls() {
1494
+    public long[] getRemainingApiCalls() {
1493
         final XMLResponse doc = getXML(getURL("account/rate_limit_status"));
1495
         final XMLResponse doc = getXML(getURL("account/rate_limit_status"));
1494
         // The call we just made doesn't count, so remove it from the count.
1496
         // The call we just made doesn't count, so remove it from the count.
1495
         usedCalls--;
1497
         usedCalls--;
1503
             final String resetTimeString = getElementContents(element, "reset-time-in-seconds", getElementContents(element, "reset_time_in_seconds", "0"));
1505
             final String resetTimeString = getElementContents(element, "reset-time-in-seconds", getElementContents(element, "reset_time_in_seconds", "0"));
1504
             resetTime = 1000 * parseLong(resetTimeString, -1);
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
         } else {
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
 
1714
 
1713
     /**
1715
     /**
1714
      * Block a user on twitter.
1716
      * Block a user on twitter.
1715
-     * 
1717
+     *
1716
      * @param name Username to block.
1718
      * @param name Username to block.
1717
      * @return The user just blocked.
1719
      * @return The user just blocked.
1718
      */
1720
      */
1736
 
1738
 
1737
     /**
1739
     /**
1738
      * Unblock a user on twitter.
1740
      * Unblock a user on twitter.
1739
-     * 
1741
+     *
1740
      * @param name Username to unblock.
1742
      * @param name Username to unblock.
1741
      * @return The user just unblocked.
1743
      * @return The user just unblocked.
1742
      */
1744
      */

Loading…
Cancel
Save