Browse Source

PMD Fixes for plugins

Change-Id: I16cbfad94712946435c2be40ed0f2d25733bf354
Reviewed-on: http://gerrit.dmdirc.com/1700
Automatic-Compile: DMDirc Local Commits <dmdirc@googlemail.com>
Reviewed-by: Chris Smith <chris@dmdirc.com>
tags/0.6.5
Greg Holmes 13 years ago
parent
commit
b732f4bd16

+ 6
- 5
src/com/dmdirc/addons/calc/CalcCommand.java View File

47
             int offset = 0;
47
             int offset = 0;
48
             boolean showexpr = false;
48
             boolean showexpr = false;
49
 
49
 
50
-            if (args.getArguments().length > 0 && args.getArguments()[0].equals("--showexpr")) {
50
+            if (args.getArguments().length > 0 && args.getArguments()[0]
51
+                    .equals("--showexpr")) {
51
                 showexpr = true;
52
                 showexpr = true;
52
                 offset++;
53
                 offset++;
53
             }
54
             }
60
             sendLine(origin, args.isSilent(), FORMAT_OUTPUT,
61
             sendLine(origin, args.isSilent(), FORMAT_OUTPUT,
61
                     (showexpr ? input + " = " : "") + result);
62
                     (showexpr ? input + " = " : "") + result);
62
         } catch (ParseException ex) {
63
         } catch (ParseException ex) {
63
-            sendLine(origin, args.isSilent(), FORMAT_ERROR, "Unable to parse expression: "
64
-                    + ex.getMessage());
64
+            sendLine(origin, args.isSilent(), FORMAT_ERROR, 
65
+                    "Unable to parse expression: " + ex.getMessage());
65
         } catch (ArithmeticException ex) {
66
         } catch (ArithmeticException ex) {
66
-            sendLine(origin, args.isSilent(), FORMAT_ERROR, "Unable to calculate expression: "
67
-                    + ex.getMessage());
67
+            sendLine(origin, args.isSilent(), FORMAT_ERROR, 
68
+                    "Unable to calculate expression: " + ex.getMessage());
68
         }
69
         }
69
     }
70
     }
70
 
71
 

+ 26
- 13
src/com/dmdirc/addons/calc/Parser.java View File

43
     protected static final List<TokenType> TOKENS_BY_PRECEDENCE;
43
     protected static final List<TokenType> TOKENS_BY_PRECEDENCE;
44
 
44
 
45
     static {
45
     static {
46
-        TOKENS_BY_PRECEDENCE = new ArrayList<TokenType>(Arrays.asList(TokenType.values()));
47
-        Collections.sort(TOKENS_BY_PRECEDENCE, new TokenTypePrecedenceComparator());
46
+        TOKENS_BY_PRECEDENCE = new ArrayList<TokenType>(Arrays.asList(
47
+                TokenType.values()));
48
+        Collections.sort(TOKENS_BY_PRECEDENCE,
49
+                new TokenTypePrecedenceComparator());
48
     }
50
     }
49
 
51
 
50
     /**
52
     /**
82
      * @return A single tree containing all of the specified tokens
84
      * @return A single tree containing all of the specified tokens
83
      * @throws ParseException If the tokens contain mismatched brackets
85
      * @throws ParseException If the tokens contain mismatched brackets
84
      */
86
      */
85
-    protected TreeToken parse(final List<TreeToken> tokens) throws ParseException {
87
+    protected TreeToken parse(final List<TreeToken> tokens)
88
+            throws ParseException {
86
         while (tokens.size() > 1) {
89
         while (tokens.size() > 1) {
87
             for (TokenType type : TOKENS_BY_PRECEDENCE) {
90
             for (TokenType type : TOKENS_BY_PRECEDENCE) {
88
                 final int offset = findTokenType(tokens, type);
91
                 final int offset = findTokenType(tokens, type);
119
      * @throws ParseException If the operator is a bracket and that bracket is
122
      * @throws ParseException If the operator is a bracket and that bracket is
120
      * mismatched
123
      * mismatched
121
      */
124
      */
122
-    protected void parseNullaryOperator(final List<TreeToken> tokens, final int offset)
125
+    protected void parseNullaryOperator(final List<TreeToken> tokens,
126
+            final int offset)
123
             throws ParseException {
127
             throws ParseException {
124
-        if (tokens.get(offset).getToken().getType() == TokenType.BRACKET_CLOSE
125
-                || tokens.get(offset).getToken().getType() == TokenType.BRACKET_OPEN) {
128
+        if (tokens.get(offset).getToken().getType()
129
+                == TokenType.BRACKET_CLOSE
130
+                || tokens.get(offset).getToken().getType()
131
+                == TokenType.BRACKET_OPEN) {
126
             parseBracket(tokens, offset);
132
             parseBracket(tokens, offset);
127
         } else {
133
         } else {
128
             parseNumber(tokens, offset);
134
             parseNumber(tokens, offset);
155
             }
161
             }
156
         }
162
         }
157
 
163
 
158
-        throw new ParseException("Couldn't find matching opening bracket", offset);
164
+        throw new ParseException("Couldn't find matching opening bracket",
165
+                offset);
159
     }
166
     }
160
 
167
 
161
     /**
168
     /**
164
      * @param tokens The supply of tokens from which the operator will be parsed
171
      * @param tokens The supply of tokens from which the operator will be parsed
165
      * @param offset The offset at which the operator occurs
172
      * @param offset The offset at which the operator occurs
166
      */
173
      */
167
-    protected void parseBinaryOperator(final List<TreeToken> tokens, final int offset) {
174
+    protected void parseBinaryOperator(final List<TreeToken> tokens,
175
+            final int offset) {
168
         tokens.get(offset).addChild(tokens.get(offset - 1));
176
         tokens.get(offset).addChild(tokens.get(offset - 1));
169
         tokens.get(offset).addChild(tokens.get(offset + 1));
177
         tokens.get(offset).addChild(tokens.get(offset + 1));
170
         tokens.get(offset).setProcessed();
178
         tokens.get(offset).setProcessed();
179
      * @param tokens The supply of tokens from which the operator will be parsed
187
      * @param tokens The supply of tokens from which the operator will be parsed
180
      * @param offset The offset at which the operator occurs
188
      * @param offset The offset at which the operator occurs
181
      */
189
      */
182
-    protected void parseUnaryOperator(final List<TreeToken> tokens, final int offset) {
190
+    protected void parseUnaryOperator(final List<TreeToken> tokens,
191
+            final int offset) {
183
         tokens.get(offset).addChild(tokens.get(offset + 1));
192
         tokens.get(offset).addChild(tokens.get(offset + 1));
184
         tokens.get(offset).setProcessed();
193
         tokens.get(offset).setProcessed();
185
         tokens.remove(offset + 1);
194
         tokens.remove(offset + 1);
192
      * @param tokens The supply of tokens from which the operator will be parsed
201
      * @param tokens The supply of tokens from which the operator will be parsed
193
      * @param offset The offset at which the operator occurs
202
      * @param offset The offset at which the operator occurs
194
      */
203
      */
195
-    protected void parseHiddenOperator(final List<TreeToken> tokens, final int offset) {
204
+    protected void parseHiddenOperator(final List<TreeToken> tokens,
205
+            final int offset) {
196
         tokens.remove(offset);
206
         tokens.remove(offset);
197
     }
207
     }
198
 
208
 
214
      * @param type The desired token type
224
      * @param type The desired token type
215
      * @return The index of the first token with that type, or -1 if none found
225
      * @return The index of the first token with that type, or -1 if none found
216
      */
226
      */
217
-    protected static int findTokenType(final List<TreeToken> tokens, final TokenType type) {
227
+    protected static int findTokenType(final List<TreeToken> tokens,
228
+            final TokenType type) {
218
         for (int i = 0; i < tokens.size(); i++) {
229
         for (int i = 0; i < tokens.size(); i++) {
219
-            if (tokens.get(i).getToken().getType() == type && !tokens.get(i).isProcessed()) {
230
+            if (tokens.get(i).getToken().getType() == type && !tokens.get(i)
231
+                    .isProcessed()) {
220
                 return i;
232
                 return i;
221
             }
233
             }
222
         }
234
         }
227
     /**
239
     /**
228
      * A class which compares token types based on their precendence.
240
      * A class which compares token types based on their precendence.
229
      */
241
      */
230
-    protected static class TokenTypePrecedenceComparator implements Comparator<TokenType> {
242
+    protected static class TokenTypePrecedenceComparator implements
243
+            Comparator<TokenType> {
231
 
244
 
232
         /** {@inheritDoc} */
245
         /** {@inheritDoc} */
233
         @Override
246
         @Override

+ 16
- 10
src/com/dmdirc/addons/calc/TokenType.java View File

41
     END(TokenTypeArity.HIDDEN, "$", 0),
41
     END(TokenTypeArity.HIDDEN, "$", 0),
42
 
42
 
43
     /** An opening bracket. */
43
     /** An opening bracket. */
44
-    BRACKET_OPEN(TokenTypeArity.NULLARY, "\\(", 0, "NUMBER_*", "MOD_*", "BRACKET_OPEN"),
44
+    BRACKET_OPEN(TokenTypeArity.NULLARY, "\\(", 0, "NUMBER_*", "MOD_*",
45
+                "BRACKET_OPEN"),
45
     /** A closing bracket. */
46
     /** A closing bracket. */
46
-    BRACKET_CLOSE(TokenTypeArity.NULLARY, "\\)", 50, "OP_*", "BRACKET_*", "END"),
47
+    BRACKET_CLOSE(TokenTypeArity.NULLARY, "\\)", 50, "OP_*", "BRACKET_*",
48
+                "END"),
47
 
49
 
48
     /** A floating point number. */
50
     /** A floating point number. */
49
-    NUMBER_FLOAT(TokenTypeArity.NULLARY, "[0-9]+\\.[0-9]+", 1, "OP_*", "BRACKET_*", "END") {
51
+    NUMBER_FLOAT(TokenTypeArity.NULLARY, "[0-9]+\\.[0-9]+", 1, "OP_*",
52
+                "BRACKET_*", "END") {
50
         /** {@inheritDoc} */
53
         /** {@inheritDoc} */
51
         @Override
54
         @Override
52
         public Number evaluate(final TreeToken token) {
55
         public Number evaluate(final TreeToken token) {
55
     },
58
     },
56
 
59
 
57
     /** An integer. */
60
     /** An integer. */
58
-    NUMBER_INT(TokenTypeArity.NULLARY, "[0-9]+", 1, "OP_*", "BRACKET_*", "END") {
61
+    NUMBER_INT(TokenTypeArity.NULLARY, "[0-9]+", 1, "OP_*",
62
+                "BRACKET_*", "END") {
59
         /** {@inheritDoc} */
63
         /** {@inheritDoc} */
60
         @Override
64
         @Override
61
         public Number evaluate(final TreeToken token) {
65
         public Number evaluate(final TreeToken token) {
102
     },
106
     },
103
 
107
 
104
     /** The multiplication operator. */
108
     /** The multiplication operator. */
105
-    OP_MULT(TokenTypeArity.BINARY, "(?=\\()|\\*", 9, "NUMBER_*", "BRACKET_OPEN") {
109
+    OP_MULT(TokenTypeArity.BINARY, "(?=\\()|\\*", 9, "NUMBER_*",
110
+            "BRACKET_OPEN") {
106
         /** {@inheritDoc} */
111
         /** {@inheritDoc} */
107
         @Override
112
         @Override
108
         public Number evaluate(final TreeToken token) {
113
         public Number evaluate(final TreeToken token) {
136
         /** {@inheritDoc} */
141
         /** {@inheritDoc} */
137
         @Override
142
         @Override
138
         public Number evaluate(final TreeToken token) {
143
         public Number evaluate(final TreeToken token) {
139
-            return new Float(Math.pow(token.getChildren().get(0).evaluate().doubleValue(),
144
+            return new Float(Math.pow(token.getChildren().get(0).evaluate()
145
+                    .doubleValue(),
140
                     token.getChildren().get(1).evaluate().doubleValue()));
146
                     token.getChildren().get(1).evaluate().doubleValue()));
141
         }
147
         }
142
     };
148
     };
217
         matcher.useAnchoringBounds(false);
223
         matcher.useAnchoringBounds(false);
218
         matcher.useTransparentBounds(true);
224
         matcher.useTransparentBounds(true);
219
 
225
 
220
-        return matcher.find(offset) && matcher.start() == offset ? matcher.end() : -1;
226
+        return matcher.find(offset) && matcher.start() == offset
227
+                ? matcher.end() : -1;
221
     }
228
     }
222
 
229
 
223
     /**
230
     /**
241
         final List<TokenType> res = new ArrayList<TokenType>();
248
         final List<TokenType> res = new ArrayList<TokenType>();
242
 
249
 
243
         for (TokenType token : values()) {
250
         for (TokenType token : values()) {
244
-            if ((name.endsWith("*")
245
-                    && token.name().startsWith(name.substring(0, name.length() - 1)))
246
-                    || name.equals(token.name())) {
251
+            if ((name.endsWith("*") && token.name().startsWith(name.substring(0,
252
+                    name.length() - 1))) || name.equals(token.name())) {
247
                 res.add(token);
253
                 res.add(token);
248
             }
254
             }
249
         }
255
         }

+ 13
- 16
src/com/dmdirc/addons/dcc/ChatContainer.java View File

30
 
30
 
31
 /**
31
 /**
32
  * This class links DCC Chat objects to a window.
32
  * This class links DCC Chat objects to a window.
33
- *
34
- * @author Shane 'Dataforce' McCormack
35
  */
33
  */
36
 public class ChatContainer extends DCCFrameContainer<InputWindow> implements DCCChatHandler {
34
 public class ChatContainer extends DCCFrameContainer<InputWindow> implements DCCChatHandler {
37
 
35
 
38
-    /** The DCCChat object we are a window for */
39
-    private final DCCChat dcc;
40
-
41
-    /** My Nickname */
36
+    /** The DCCChat object we are a window for. */
37
+    private final DCCChat dccChat;
38
+    /** My Nickname. */
42
     private final String nickname;
39
     private final String nickname;
43
-
44
-    /** Other Nickname */
40
+    /** Other Nickname. */
45
     private final String otherNickname;
41
     private final String otherNickname;
46
 
42
 
47
     /**
43
     /**
55
      */
51
      */
56
     public ChatContainer(final DCCPlugin plugin, final DCCChat dcc,
52
     public ChatContainer(final DCCPlugin plugin, final DCCChat dcc,
57
             final String title, final String nick, final String targetNick) {
53
             final String title, final String nick, final String targetNick) {
58
-        super(plugin, title, "dcc-chat-inactive", InputWindow.class,
54
+        super(title, "dcc-chat-inactive", InputWindow.class,
59
                 DCCCommandParser.getDCCCommandParser());
55
                 DCCCommandParser.getDCCCommandParser());
60
-        this.dcc = dcc;
56
+        this.dccChat = dcc;
61
         dcc.setHandler(this);
57
         dcc.setHandler(this);
62
         nickname = nick;
58
         nickname = nick;
63
         otherNickname = targetNick;
59
         otherNickname = targetNick;
66
     }
62
     }
67
 
63
 
68
     /**
64
     /**
69
-     * Get the DCCChat Object associated with this window
65
+     * Get the DCCChat Object associated with this window.
70
      *
66
      *
71
      * @return The DCCChat Object associated with this window
67
      * @return The DCCChat Object associated with this window
72
      */
68
      */
73
     public DCCChat getDCC() {
69
     public DCCChat getDCC() {
74
-        return dcc;
70
+        return dccChat;
75
     }
71
     }
76
 
72
 
77
     /** {@inheritDoc} */
73
     /** {@inheritDoc} */
78
     @Override
74
     @Override
79
     public void sendLine(final String line) {
75
     public void sendLine(final String line) {
80
-        if (dcc.isWriteable()) {
76
+        if (dccChat.isWriteable()) {
81
             final StringBuffer buff = new StringBuffer("DCCChatSelfMessage");
77
             final StringBuffer buff = new StringBuffer("DCCChatSelfMessage");
82
-            ActionManager.processEvent(DCCActions.DCC_CHAT_SELFMESSAGE, buff, this, line);
78
+            ActionManager.processEvent(DCCActions.DCC_CHAT_SELFMESSAGE, buff,
79
+                    this, line);
83
             addLine(buff, nickname, getTranscoder().encode(line));
80
             addLine(buff, nickname, getTranscoder().encode(line));
84
-            dcc.sendLine(line);
81
+            dccChat.sendLine(line);
85
         } else {
82
         } else {
86
             final StringBuffer buff = new StringBuffer("DCCChatError");
83
             final StringBuffer buff = new StringBuffer("DCCChatError");
87
             addLine(buff, "Socket is closed.", getTranscoder().encode(line));
84
             addLine(buff, "Socket is closed.", getTranscoder().encode(line));
121
     @Override
118
     @Override
122
     public void windowClosing() {
119
     public void windowClosing() {
123
         super.windowClosing();
120
         super.windowClosing();
124
-        dcc.close();
121
+        dccChat.close();
125
     }
122
     }
126
 
123
 
127
 }
124
 }

+ 7
- 9
src/com/dmdirc/addons/dcc/DCCChatHandler.java View File

25
 import com.dmdirc.addons.dcc.io.DCCChat;
25
 import com.dmdirc.addons.dcc.io.DCCChat;
26
 
26
 
27
 /**
27
 /**
28
- * This interfaces allows DCC Chat Windows to receive data from a DCCChat
29
- *
30
- * @author Shane 'Dataforce' McCormack
28
+ * This interfaces allows DCC Chat Windows to receive data from a DCCChat.
31
  */
29
  */
32
 public interface DCCChatHandler {
30
 public interface DCCChatHandler {
33
 
31
 
34
     /**
32
     /**
35
-     * Handle a received message
33
+     * Handle a received message.
36
      *
34
      *
37
      * @param dcc The DCCChat that this message is from
35
      * @param dcc The DCCChat that this message is from
38
      * @param message The message
36
      * @param message The message
39
      */
37
      */
40
-    void handleChatMessage(final DCCChat dcc, final String message);
38
+    void handleChatMessage(DCCChat dcc, String message);
41
 
39
 
42
     /**
40
     /**
43
-     * Called when the socket is closed
41
+     * Called when the socket is closed.
44
      *
42
      *
45
      * @param dcc The DCCChat that this message is from
43
      * @param dcc The DCCChat that this message is from
46
      */
44
      */
47
-    void socketClosed(final DCCChat dcc);
45
+    void socketClosed(DCCChat dcc);
48
 
46
 
49
     /**
47
     /**
50
-     * Called when the socket is opened
48
+     * Called when the socket is opened.
51
      *
49
      *
52
      * @param dcc The DCCChat that this message is from
50
      * @param dcc The DCCChat that this message is from
53
      */
51
      */
54
-    void socketOpened(final DCCChat dcc);
52
+    void socketOpened(DCCChat dcc);
55
 
53
 
56
 }
54
 }

+ 142
- 97
src/com/dmdirc/addons/dcc/DCCCommand.java View File

50
 import javax.swing.JOptionPane;
50
 import javax.swing.JOptionPane;
51
 
51
 
52
 /**
52
 /**
53
- * This command allows starting dcc chats/file transfers
54
- *
55
- * @author Shane "Dataforce" Mc Cormack
53
+ * This command allows starting dcc chats/file transfers.
56
  */
54
  */
57
 public final class DCCCommand extends Command implements IntelligentCommand,
55
 public final class DCCCommand extends Command implements IntelligentCommand,
58
         CommandInfo {
56
         CommandInfo {
59
 
57
 
60
-    /** My Plugin */
58
+    /** My Plugin. */
61
     private final DCCPlugin myPlugin;
59
     private final DCCPlugin myPlugin;
62
 
60
 
63
     /**
61
     /**
74
     @Override
72
     @Override
75
     public void execute(final FrameContainer<?> origin,
73
     public void execute(final FrameContainer<?> origin,
76
             final CommandArguments args, final CommandContext context) {
74
             final CommandArguments args, final CommandContext context) {
77
-        final Server server = ((ServerCommandContext) context).getServer();
78
-        
79
         if (args.getArguments().length > 1) {
75
         if (args.getArguments().length > 1) {
80
-            final String type = args.getArguments()[0];
81
             final String target = args.getArguments()[1];
76
             final String target = args.getArguments()[1];
77
+            final Server server = ((ServerCommandContext) context).getServer();
82
             final Parser parser = server.getParser();
78
             final Parser parser = server.getParser();
83
             final String myNickname = parser.getLocalClient().getNickname();
79
             final String myNickname = parser.getLocalClient().getNickname();
84
 
80
 
85
             if (parser.isValidChannelName(target)
81
             if (parser.isValidChannelName(target)
86
-                    || parser.getStringConverter().equalsIgnoreCase(target, myNickname)) {
87
-                final Thread errorThread = new Thread(new Runnable() {
82
+                    || parser.getStringConverter().equalsIgnoreCase(target,
83
+                    myNickname)) {
84
+                new Thread(new Runnable() {
88
 
85
 
89
                     /** {@inheritDoc} */
86
                     /** {@inheritDoc} */
90
                     @Override
87
                     @Override
91
                     public void run() {
88
                     public void run() {
92
-                        if (parser.getStringConverter().equalsIgnoreCase(target, myNickname)) {
93
-                            JOptionPane.showMessageDialog(null, "You can't DCC yourself.",
94
-                                    "DCC Error", JOptionPane.ERROR_MESSAGE);
89
+                        if (parser.getStringConverter().equalsIgnoreCase(target,
90
+                                myNickname)) {
91
+                            JOptionPane.showMessageDialog(null,
92
+                                    "You can't DCC yourself.", "DCC Error",
93
+                                    JOptionPane.ERROR_MESSAGE);
95
                         } else {
94
                         } else {
96
-                            JOptionPane.showMessageDialog(null, "You can't DCC a channel.",
97
-                                    "DCC Error", JOptionPane.ERROR_MESSAGE);
95
+                            JOptionPane.showMessageDialog(null,
96
+                                    "You can't DCC a channel.", "DCC Error",
97
+                                    JOptionPane.ERROR_MESSAGE);
98
                         }
98
                         }
99
                     }
99
                     }
100
 
100
 
101
-                });
102
-                errorThread.start();
101
+                }).start();
103
                 return;
102
                 return;
104
             }
103
             }
104
+            final String type = args.getArguments()[0];
105
             if (type.equalsIgnoreCase("chat")) {
105
             if (type.equalsIgnoreCase("chat")) {
106
-                final DCCChat chat = new DCCChat();
107
-                if (myPlugin.listen(chat)) {
108
-                    final ChatContainer window = new ChatContainer(myPlugin, chat,
109
-                            "*Chat: " + target, myNickname, target);
110
-
111
-                    parser.sendCTCP(target, "DCC", "CHAT chat "
112
-                            + DCC.ipToLong(myPlugin.getListenIP(parser)) + " "
113
-                            + chat.getPort());
114
-
115
-                    ActionManager.processEvent(DCCActions.DCC_CHAT_REQUEST_SENT,
116
-                            null, server, target);
117
-
118
-                    sendLine(origin, args.isSilent(), "DCCChatStarting", target,
119
-                            chat.getHost(), chat.getPort());
120
-                    window.addLine("DCCChatStarting", target,
121
-                            chat.getHost(), chat.getPort());
122
-                } else {
123
-                    sendLine(origin, args.isSilent(), "DCCChatError",
124
-                            "Unable to start chat with " + target
125
-                            + " - unable to create listen socket");
126
-                }
106
+                startChat(parser, server, origin, myNickname, target, true);
127
             } else if (type.equalsIgnoreCase("send")) {
107
             } else if (type.equalsIgnoreCase("send")) {
128
-                sendFile(target, origin, server, args.isSilent(), args.getArgumentsAsString(2));
108
+                sendFile(target, origin, server, true,
109
+                        args.getArgumentsAsString(2));
129
             } else {
110
             } else {
130
-                sendLine(origin, args.isSilent(), FORMAT_ERROR, "Unknown DCC Type: '" + type + "'");
111
+                sendLine(origin, args.isSilent(), FORMAT_ERROR,
112
+                        "Unknown DCC Type: '" + type + "'");
131
             }
113
             }
132
         } else {
114
         } else {
133
-            sendLine(origin, args.isSilent(), FORMAT_ERROR, "Syntax: dcc <type> <target> [params]");
115
+            showUsage(origin, true, getName(), getHelp());
116
+        }
117
+    }
118
+
119
+    /**
120
+     * Starts a DCC Chat.
121
+     *
122
+     * @param parser Parser from which command originated
123
+     * @param server Server from which command originated
124
+     * @param origin Frame container from which command originated
125
+     * @param myNickname My current nickname
126
+     * @param target Target of the command
127
+     * @param isSilent Is this a silent command
128
+     */
129
+    private void startChat(final Parser parser, final Server server,
130
+            final FrameContainer<?> origin, final String myNickname,
131
+            final String target, final boolean isSilent) {
132
+        final DCCChat chat = new DCCChat();
133
+        if (myPlugin.listen(chat)) {
134
+            final ChatContainer window = new ChatContainer(myPlugin, chat,
135
+                    "*Chat: " + target, myNickname, target);
136
+            parser.sendCTCP(target, "DCC", "CHAT chat " + DCC.ipToLong(
137
+                    myPlugin.getListenIP(parser)) + " " + chat.getPort());
138
+            ActionManager.processEvent(DCCActions.DCC_CHAT_REQUEST_SENT, null,
139
+                    server, target);
140
+            sendLine(origin, isSilent, "DCCChatStarting", target,
141
+                    chat.getHost(), chat.getPort());
142
+            window.addLine("DCCChatStarting", target, chat.getHost(),
143
+                    chat.getPort());
144
+        } else {
145
+            sendLine(origin, isSilent, "DCCChatError",
146
+                    "Unable to start chat with " + target
147
+                    + " - unable to create listen socket");
134
         }
148
         }
135
     }
149
     }
136
 
150
 
148
             final Server server, final boolean isSilent, final String filename) {
162
             final Server server, final boolean isSilent, final String filename) {
149
         // New thread to ask the user what file to send
163
         // New thread to ask the user what file to send
150
         final File givenFile = new File(filename);
164
         final File givenFile = new File(filename);
151
-        final Thread dccThread = new Thread(new Runnable() {
165
+        new Thread(new Runnable() {
152
 
166
 
153
             /** {@inheritDoc} */
167
             /** {@inheritDoc} */
154
             @Override
168
             @Override
156
                 final JFileChooser jc = givenFile.exists()
170
                 final JFileChooser jc = givenFile.exists()
157
                         ? KFileChooser.getFileChooser(myPlugin, givenFile)
171
                         ? KFileChooser.getFileChooser(myPlugin, givenFile)
158
                         : KFileChooser.getFileChooser(myPlugin);
172
                         : KFileChooser.getFileChooser(myPlugin);
159
-                int result;
160
-                if (!givenFile.exists() || !givenFile.isFile()) {
161
-                    jc.setDialogTitle("Send file to " + target + " - DMDirc ");
162
-                    jc.setFileSelectionMode(JFileChooser.FILES_ONLY);
163
-                    jc.setMultiSelectionEnabled(false);
164
-                    result = jc.showOpenDialog(((SwingController) PluginManager
165
-                            .getPluginManager().getPluginInfoByName("ui_swing")
166
-                            .getPlugin()).getMainFrame());
167
-                } else {
168
-                    jc.setSelectedFile(givenFile);
169
-                    result = JFileChooser.APPROVE_OPTION;
173
+                final int result = showFileChooser(givenFile, target, jc);
174
+                if (result != JFileChooser.APPROVE_OPTION
175
+                        || !handleInvalidItems(jc)) {
176
+                    return;
170
                 }
177
                 }
171
-                if (result == JFileChooser.APPROVE_OPTION) {
172
-                    if (jc.getSelectedFile().length() == 0) {
173
-                        JOptionPane.showMessageDialog(null,
174
-                                "You can't send empty files over DCC.", "DCC Error",
175
-                                JOptionPane.ERROR_MESSAGE);
176
-                        return;
177
-                    } else if (!jc.getSelectedFile().exists()) {
178
-                        JOptionPane.showMessageDialog(null,
179
-                                "Invalid file specified", "DCC Error",
180
-                                JOptionPane.ERROR_MESSAGE);
181
-                        return;
182
-                    }
183
-                    final Parser parser = server.getParser();
184
-                    DCCTransfer send = new DCCTransfer(IdentityManager
185
-                            .getGlobalConfig().getOptionInt(myPlugin.getDomain(),
186
-                            "send.blocksize"));
187
-                    send.setTurbo(IdentityManager.getGlobalConfig()
188
-                            .getOptionBool(myPlugin.getDomain(), "send.forceturbo"));
189
-                    send.setType(DCCTransfer.TransferType.SEND);
178
+                final DCCTransfer send = new DCCTransfer(IdentityManager
179
+                        .getGlobalConfig().getOptionInt(myPlugin.getDomain(),
180
+                        "send.blocksize"));
181
+                send.setTurbo(IdentityManager.getGlobalConfig().getOptionBool(
182
+                        myPlugin.getDomain(), "send.forceturbo"));
183
+                send.setType(DCCTransfer.TransferType.SEND);
190
 
184
 
191
-                    ActionManager.processEvent(DCCActions.DCC_SEND_REQUEST_SENT,
192
-                            null, server, target, jc.getSelectedFile());
185
+                ActionManager.processEvent(DCCActions.DCC_SEND_REQUEST_SENT,
186
+                        null, server, target, jc.getSelectedFile());
193
 
187
 
194
-                    sendLine(origin, isSilent, FORMAT_OUTPUT,
195
-                            "Starting DCC Send with: " + target);
188
+                sendLine(origin, isSilent, FORMAT_OUTPUT,
189
+                        "Starting DCC Send with: " + target);
196
 
190
 
197
-                    send.setFileName(jc.getSelectedFile().getAbsolutePath());
198
-                    send.setFileSize(jc.getSelectedFile().length());
191
+                send.setFileName(jc.getSelectedFile().getAbsolutePath());
192
+                send.setFileSize(jc.getSelectedFile().length());
199
 
193
 
200
-                    if (IdentityManager.getGlobalConfig().getOptionBool(
201
-                            myPlugin.getDomain(), "send.reverse")) {
202
-                        new TransferContainer(myPlugin, send, "Send: "
194
+                if (IdentityManager.getGlobalConfig().getOptionBool(
195
+                        myPlugin.getDomain(), "send.reverse")) {
196
+                    final Parser parser = server.getParser();
197
+                    new TransferContainer(myPlugin, send, "Send: " + target,
198
+                            target, server);
199
+                    parser.sendCTCP(target, "DCC", "SEND \""
200
+                            + jc.getSelectedFile().getName() + "\" "
201
+                            + DCC.ipToLong(myPlugin.getListenIP(parser))
202
+                            + " 0 " + send.getFileSize() + " "
203
+                            + send.makeToken()
204
+                            + (send.isTurbo() ? " T" : ""));
205
+                } else {
206
+                    final Parser parser = server.getParser();
207
+                    if (myPlugin.listen(send)) {
208
+                        new TransferContainer(myPlugin, send, "*Send: "
203
                                 + target, target, server);
209
                                 + target, target, server);
204
                         parser.sendCTCP(target, "DCC", "SEND \""
210
                         parser.sendCTCP(target, "DCC", "SEND \""
205
                                 + jc.getSelectedFile().getName() + "\" "
211
                                 + jc.getSelectedFile().getName() + "\" "
206
                                 + DCC.ipToLong(myPlugin.getListenIP(parser))
212
                                 + DCC.ipToLong(myPlugin.getListenIP(parser))
207
-                                + " 0 " + send.getFileSize() + " " + send.makeToken()
213
+                                + " " + send.getPort() + " " + send.getFileSize()
208
                                 + (send.isTurbo() ? " T" : ""));
214
                                 + (send.isTurbo() ? " T" : ""));
209
                     } else {
215
                     } else {
210
-                        if (myPlugin.listen(send)) {
211
-                            new TransferContainer(myPlugin, send, "*Send: "
212
-                                    + target, target, server);
213
-                            parser.sendCTCP(target, "DCC", "SEND \""
214
-                                    + jc.getSelectedFile().getName() + "\" "
215
-                                    + DCC.ipToLong(myPlugin.getListenIP(parser))
216
-                                    + " " + send.getPort() + " " + send.getFileSize()
217
-                                    + (send.isTurbo() ? " T" : ""));
218
-                        } else {
219
-                            sendLine(origin, isSilent, "DCCSendError",
220
-                                    "Unable to start dcc send with " + target
221
-                                    + " - unable to create listen socket");
222
-                        }
216
+                        sendLine(origin, isSilent, "DCCSendError",
217
+                                "Unable to start dcc send with " + target
218
+                                + " - unable to create listen socket");
223
                     }
219
                     }
224
                 }
220
                 }
225
             }
221
             }
226
 
222
 
227
-        }, "openFileThread");
228
-        // Start the thread
229
-        dccThread.start();
223
+        }, "openFileThread").start();
224
+    }
225
+
226
+    /**
227
+     * Checks for invalid items.
228
+     *
229
+     * @param jc File chooser to check
230
+     *
231
+     * @return true iif the selection was valid
232
+     */
233
+    private boolean handleInvalidItems(final JFileChooser jc) {
234
+        if (jc.getSelectedFile().length() == 0) {
235
+            JOptionPane.showMessageDialog(null,
236
+                    "You can't send empty files over DCC.", "DCC Error",
237
+                    JOptionPane.ERROR_MESSAGE);
238
+            return false;
239
+        } else if (!jc.getSelectedFile().exists()) {
240
+            JOptionPane.showMessageDialog(null, "Invalid file specified",
241
+                    "DCC Error", JOptionPane.ERROR_MESSAGE);
242
+            return false;
243
+        }
244
+        return true;
245
+    }
246
+
247
+    /**
248
+     * Sets up and display a file chooser.
249
+     *
250
+     * @param givenFile File to display
251
+     * @param target DCC target
252
+     * @param jc File chooser
253
+     *
254
+     * @return   the return state of the file chooser on popdown:
255
+     * <ul>
256
+     * <li>JFileChooser.CANCEL_OPTION
257
+     * <li>JFileChooser.APPROVE_OPTION
258
+     * <li>JFileChooser.ERROR_OPTION if an error occurs or the
259
+     *                               dialog is dismissed
260
+     * </ul>
261
+     */
262
+    private int showFileChooser(final File givenFile, final String target,
263
+            final JFileChooser jc) {
264
+        if (givenFile.exists() && givenFile.isFile()) {
265
+            jc.setSelectedFile(givenFile);
266
+            return JFileChooser.APPROVE_OPTION;
267
+        } else {
268
+        jc.setDialogTitle("Send file to " + target + " - DMDirc ");
269
+        jc.setFileSelectionMode(JFileChooser.FILES_ONLY);
270
+        jc.setMultiSelectionEnabled(false);
271
+        return jc.showOpenDialog(((SwingController) PluginManager
272
+                .getPluginManager().getPluginInfoByName("ui_swing")
273
+                .getPlugin()).getMainFrame());
274
+        }
230
     }
275
     }
231
 
276
 
232
     /** {@inheritDoc} */
277
     /** {@inheritDoc} */

+ 3
- 2
src/com/dmdirc/addons/dcc/DCCCommandParser.java View File

29
 import com.dmdirc.commandparser.parsers.GlobalCommandParser;
29
 import com.dmdirc.commandparser.parsers.GlobalCommandParser;
30
 
30
 
31
 /**
31
 /**
32
- * DCC CommandParser
32
+ * DCC CommandParser.
33
  */
33
  */
34
 public final class DCCCommandParser extends GlobalCommandParser {
34
 public final class DCCCommandParser extends GlobalCommandParser {
35
 
35
 
74
      * @param line The line input by the user
74
      * @param line The line input by the user
75
      */
75
      */
76
     @Override
76
     @Override
77
-    protected void handleNonCommand(final FrameContainer<?> origin, final String line) {
77
+    protected void handleNonCommand(final FrameContainer<?> origin,
78
+            final String line) {
78
         ((WritableFrameContainer<?>) origin).sendLine(line);
79
         ((WritableFrameContainer<?>) origin).sendLine(line);
79
     }
80
     }
80
 
81
 

+ 6
- 31
src/com/dmdirc/addons/dcc/DCCFrameContainer.java View File

26
 import com.dmdirc.WritableFrameContainer;
26
 import com.dmdirc.WritableFrameContainer;
27
 import com.dmdirc.commandparser.parsers.CommandParser;
27
 import com.dmdirc.commandparser.parsers.CommandParser;
28
 import com.dmdirc.config.IdentityManager;
28
 import com.dmdirc.config.IdentityManager;
29
-import com.dmdirc.ui.WindowManager;
30
 import com.dmdirc.ui.input.TabCompleter;
29
 import com.dmdirc.ui.input.TabCompleter;
31
 import com.dmdirc.ui.interfaces.InputWindow;
30
 import com.dmdirc.ui.interfaces.InputWindow;
32
-import com.dmdirc.ui.interfaces.Window;
33
 
31
 
34
 /**
32
 /**
35
  * This class links DCC objects to a window.
33
  * This class links DCC objects to a window.
36
  *
34
  *
37
  * @param <T> The type of window which corresponds to this DCC frame
35
  * @param <T> The type of window which corresponds to this DCC frame
38
- * @author Shane 'Dataforce' McCormack
39
  */
36
  */
40
 public abstract class DCCFrameContainer<T extends InputWindow> extends WritableFrameContainer<T> {
37
 public abstract class DCCFrameContainer<T extends InputWindow> extends WritableFrameContainer<T> {
41
 
38
 
42
-    /** The dcc plugin that owns this frame */
43
-    protected final DCCPlugin plugin;
44
-
45
     /** The Window we're using. */
39
     /** The Window we're using. */
46
     private boolean windowClosing = false;
40
     private boolean windowClosing = false;
47
 
41
 
48
     /**
42
     /**
49
      * Creates a new instance of DCCFrame.
43
      * Creates a new instance of DCCFrame.
50
      *
44
      *
51
-     * @param plugin The DCCPlugin that owns this frame
52
      * @param title The title of this window
45
      * @param title The title of this window
53
      * @param icon The icon to use
46
      * @param icon The icon to use
54
      * @param windowClass The class of window to use for this container
47
      * @param windowClass The class of window to use for this container
55
      * @param parser Command parser to use for this window
48
      * @param parser Command parser to use for this window
56
      */
49
      */
57
-    public DCCFrameContainer(final DCCPlugin plugin, final String title, final String icon,
50
+    public DCCFrameContainer(final String title, final String icon,
58
             final Class<T> windowClass, final CommandParser parser) {
51
             final Class<T> windowClass, final CommandParser parser) {
59
-        super(icon, title, title, windowClass, IdentityManager.getGlobalConfig(), parser);
60
-        this.plugin = plugin;
61
-    }
62
-
63
-    /**
64
-     * Sends a line of text to this container's source.
65
-     *
66
-     * @param line The line to be sent
67
-     */
68
-    @Override
69
-    public void sendLine(final String line) {
52
+        super(icon, title, title, windowClass,
53
+                IdentityManager.getGlobalConfig(), parser);
70
     }
54
     }
71
 
55
 
72
-    /**
73
-     * Returns the maximum length that a line passed to sendLine() should be,
74
-     * in order to prevent it being truncated or causing protocol violations.
75
-     *
76
-     * @return The maximum line length for this container
77
-     */
56
+    /** {@inheritDoc} */
78
     @Override
57
     @Override
79
     public int getMaxLineLength() {
58
     public int getMaxLineLength() {
80
         return 512;
59
         return 512;
81
     }
60
     }
82
 
61
 
83
-    /**
84
-     * Returns the server instance associated with this container.
85
-     *
86
-     * @return the associated server connection
87
-     */
62
+    /** {@inheritDoc} */
88
     @Override
63
     @Override
89
-    public Server getServer() {
64
+    public Server getServer() { //NOPMD - server will always be null
90
         return null;
65
         return null;
91
     }
66
     }
92
 
67
 

+ 429
- 269
src/com/dmdirc/addons/dcc/DCCPlugin.java View File

60
 
60
 
61
 /**
61
 /**
62
  * This plugin adds DCC to dmdirc.
62
  * This plugin adds DCC to dmdirc.
63
- *
64
- * @author Shane 'Dataforce' McCormack
65
  */
63
  */
66
 public final class DCCPlugin extends Plugin implements ActionListener {
64
 public final class DCCPlugin extends Plugin implements ActionListener {
67
 
65
 
68
     /** The DCCCommand we created. */
66
     /** The DCCCommand we created. */
69
     private DCCCommand command;
67
     private DCCCommand command;
70
-
71
     /** Our DCC Container window. */
68
     /** Our DCC Container window. */
72
     private PlaceholderContainer container;
69
     private PlaceholderContainer container;
73
 
70
 
74
     /**
71
     /**
75
-     * Creates a new instance of the DCC Plugin.
76
-     */
77
-    public DCCPlugin() {
78
-        super();
79
-    }
80
-
81
-    /**
82
-     * Ask a question, if the answer is the answer required, then recall handleProcessEvent.
72
+     * Ask a question, if the answer is the answer required, then recall
73
+     * handleProcessEvent.
83
      *
74
      *
84
      * @param question Question to ask
75
      * @param question Question to ask
85
      * @param title Title of question dialog
76
      * @param title Title of question dialog
88
      * @param format StringBuffer to pass back
79
      * @param format StringBuffer to pass back
89
      * @param arguments arguments to pass back
80
      * @param arguments arguments to pass back
90
      */
81
      */
91
-    public void askQuestion(final String question, final String title, final int desiredAnswer, final ActionType type, final StringBuffer format, final Object... arguments) {
82
+    public void askQuestion(final String question, final String title,
83
+            final int desiredAnswer, final ActionType type,
84
+            final StringBuffer format, final Object... arguments) {
92
         // New thread to ask the question in to stop us locking the UI
85
         // New thread to ask the question in to stop us locking the UI
93
-        final Thread questionThread = new Thread(new Runnable() {
86
+        new Thread(new Runnable() {
94
 
87
 
95
             /** {@inheritDoc} */
88
             /** {@inheritDoc} */
96
             @Override
89
             @Override
97
             public void run() {
90
             public void run() {
98
-                int result = JOptionPane.showConfirmDialog(null, question, title, JOptionPane.YES_NO_OPTION);
91
+                final int result = JOptionPane.showConfirmDialog(null, question,
92
+                        title, JOptionPane.YES_NO_OPTION);
99
                 if (result == desiredAnswer) {
93
                 if (result == desiredAnswer) {
100
                     handleProcessEvent(type, format, true, arguments);
94
                     handleProcessEvent(type, format, true, arguments);
101
                 }
95
                 }
102
             }
96
             }
103
 
97
 
104
-        }, "QuestionThread: " + title);
105
-        // Start the thread
106
-        questionThread.start();
98
+        }, "QuestionThread: " + title).start();
107
     }
99
     }
108
 
100
 
109
     /**
101
     /**
113
      * @param send The DCCSend to save for.
105
      * @param send The DCCSend to save for.
114
      * @param parser The parser this send was received on
106
      * @param parser The parser this send was received on
115
      * @param reverse Is this a reverse dcc?
107
      * @param reverse Is this a reverse dcc?
116
-     * @param sendFilename The name of the file which is being received
117
      * @param token Token used in reverse dcc.
108
      * @param token Token used in reverse dcc.
118
      */
109
      */
119
-    public void saveFile(final String nickname, final DCCTransfer send, final Parser parser, final boolean reverse, final String sendFilename, final String token) {
110
+    public void saveFile(final String nickname, final DCCTransfer send, 
111
+            final Parser parser, final boolean reverse, final String token) {
120
         // New thread to ask the user where to save in to stop us locking the UI
112
         // New thread to ask the user where to save in to stop us locking the UI
121
-        final Thread dccThread = new Thread(new Runnable() {
113
+        new Thread(new Runnable() {
122
 
114
 
123
             /** {@inheritDoc} */
115
             /** {@inheritDoc} */
124
             @Override
116
             @Override
125
             public void run() {
117
             public void run() {
126
-                final JFileChooser jc = KFileChooser.getFileChooser(DCCPlugin.this, IdentityManager.getGlobalConfig().getOption(getDomain(), "receive.savelocation"));
127
-                jc.setDialogTitle("Save " + sendFilename + " As - DMDirc");
128
-                jc.setFileSelectionMode(JFileChooser.FILES_ONLY);
129
-                jc.setMultiSelectionEnabled(false);
130
-                jc.setSelectedFile(new File(send.getFileName()));
118
+                final JFileChooser jc = KFileChooser.getFileChooser(
119
+                        DCCPlugin.this, IdentityManager.getGlobalConfig()
120
+                        .getOption(getDomain(), "receive.savelocation"));
131
                 int result;
121
                 int result;
132
-                if (IdentityManager.getGlobalConfig().getOptionBool(getDomain(), "receive.autoaccept")) {
122
+                if (IdentityManager.getGlobalConfig().getOptionBool(getDomain(),
123
+                        "receive.autoaccept")) {
133
                     result = JFileChooser.APPROVE_OPTION;
124
                     result = JFileChooser.APPROVE_OPTION;
134
                 } else {
125
                 } else {
135
-                    result = jc.showSaveDialog(((SwingController) PluginManager
136
-                            .getPluginManager().getPluginInfoByName("ui_swing")
137
-                            .getPlugin()).getMainFrame());
126
+                    result = showFileChooser(send, jc);
138
                 }
127
                 }
139
-                if (result == JFileChooser.APPROVE_OPTION) {
140
-                    send.setFileName(jc.getSelectedFile().getPath());
141
-                    boolean resume = false;
142
-                    if (jc.getSelectedFile().exists()) {
143
-                        if (send.getFileSize() > -1 && send.getFileSize() <= jc.getSelectedFile().length()) {
144
-                            if (IdentityManager.getGlobalConfig().getOptionBool(getDomain(), "receive.autoaccept")) {
145
-                                return;
146
-                            } else {
147
-                                JOptionPane.showMessageDialog(
148
-                                        ((SwingController) PluginManager
149
-                                        .getPluginManager().getPluginInfoByName("ui_swing")
150
-                                        .getPlugin()).getMainFrame(), "This file has already been completed, or is longer than the file you are receiving.\nPlease choose a different file.", "Problem with selected file", JOptionPane.ERROR_MESSAGE);
151
-                                saveFile(nickname, send, parser, reverse, sendFilename, token);
152
-                                return;
153
-                            }
154
-                        } else {
155
-                            if (IdentityManager.getGlobalConfig().getOptionBool(getDomain(), "receive.autoaccept")) {
156
-                                resume = true;
157
-                            } else {
158
-                                result = JOptionPane.showConfirmDialog(
159
-                                        ((SwingController) PluginManager
160
-                                        .getPluginManager().getPluginInfoByName("ui_swing")
161
-                                        .getPlugin()).getMainFrame(), "This file exists already, do you want to resume an exisiting download?", "Resume Download?", JOptionPane.YES_NO_OPTION);
162
-                                resume = (result == JOptionPane.YES_OPTION);
163
-                            }
164
-                        }
165
-                    }
128
+                if (result != JFileChooser.APPROVE_OPTION) {
129
+                    return;
130
+                }
131
+                send.setFileName(jc.getSelectedFile().getPath());
132
+                if (!handleExists(send, jc, nickname, parser,reverse, token)) {
133
+                    return;
134
+                }
135
+                boolean resume = handleResume(jc);
166
                     if (reverse && !token.isEmpty()) {
136
                     if (reverse && !token.isEmpty()) {
167
-                        new TransferContainer(DCCPlugin.this, send, "*Receive: " + nickname, nickname, null);
137
+                        new TransferContainer(DCCPlugin.this, send,
138
+                                "*Receive: " + nickname, nickname, null);
168
                         send.setToken(token);
139
                         send.setToken(token);
169
                         if (resume) {
140
                         if (resume) {
170
-                            if (IdentityManager.getGlobalConfig().getOptionBool(getDomain(), "receive.reverse.sendtoken")) {
171
-                                parser.sendCTCP(nickname, "DCC", "RESUME " + sendFilename + " 0 " + jc.getSelectedFile().length() + " " + token);
141
+                            if (IdentityManager.getGlobalConfig().getOptionBool(
142
+                                    getDomain(), "receive.reverse.sendtoken")) {
143
+                                parser.sendCTCP(nickname, "DCC", "RESUME "
144
+                                        + send.getShortFileName() + " 0 "
145
+                                        + jc.getSelectedFile().length() + " "
146
+                                        + token);
172
                             } else {
147
                             } else {
173
-                                parser.sendCTCP(nickname, "DCC", "RESUME " + sendFilename + " 0 " + jc.getSelectedFile().length());
148
+                                parser.sendCTCP(nickname, "DCC", "RESUME " 
149
+                                        + send.getShortFileName() + " 0 "
150
+                                        + jc.getSelectedFile().length());
174
                             }
151
                             }
175
                         } else {
152
                         } else {
176
                             if (listen(send)) {
153
                             if (listen(send)) {
177
-                                parser.sendCTCP(nickname, "DCC", "SEND " + sendFilename + " " + DCC.ipToLong(getListenIP(parser)) + " " + send.getPort() + " " + send.getFileSize() + " " + token);
178
-                            } else {
179
-                                // Listen failed.
154
+                                parser.sendCTCP(nickname, "DCC", "SEND " 
155
+                                        + send.getShortFileName() + " "
156
+                                        + DCC.ipToLong(getListenIP(parser))
157
+                                        + " " + send.getPort() + " "
158
+                                        + send.getFileSize() + " " + token);
180
                             }
159
                             }
181
                         }
160
                         }
182
                     } else {
161
                     } else {
183
-                        new TransferContainer(DCCPlugin.this, send, "Receive: " + nickname, nickname, null);
162
+                        new TransferContainer(DCCPlugin.this, send, "Receive: "
163
+                                + nickname, nickname, null);
184
                         if (resume) {
164
                         if (resume) {
185
-                            parser.sendCTCP(nickname, "DCC", "RESUME " + sendFilename + " " + send.getPort() + " " + jc.getSelectedFile().length());
165
+                            parser.sendCTCP(nickname, "DCC", "RESUME "
166
+                                    + send.getShortFileName() + " " 
167
+                                    + send.getPort() + " "
168
+                                    + jc.getSelectedFile().length());
186
                         } else {
169
                         } else {
187
                             send.connect();
170
                             send.connect();
188
                         }
171
                         }
189
                     }
172
                     }
190
                 }
173
                 }
174
+
175
+        }, "saveFileThread: " + send.getShortFileName()).start();
176
+    }
177
+
178
+    /**
179
+     * Checks if the selected file exists and prompts the user as required.
180
+     *
181
+     * @param send DCC Transfer
182
+     * @param jc File chooser
183
+     * @param nickname Remote nickname
184
+     * @param parser Parser
185
+     * @param reverse Reverse DCC?
186
+     * @param token DCC token
187
+     *
188
+     * @return true if the user wants to continue, false if they wish to abort
189
+     */
190
+    private boolean handleExists(final DCCTransfer send, final JFileChooser jc,
191
+            final String nickname, final Parser parser, final boolean reverse,
192
+            final String token) {
193
+        if (jc.getSelectedFile().exists() && send.getFileSize() > -1 
194
+                && send.getFileSize() <= jc.getSelectedFile().length()) {
195
+            if (IdentityManager.getGlobalConfig().getOptionBool(getDomain(),
196
+                    "receive.autoaccept")) {
197
+                return false;
198
+            } else {
199
+                JOptionPane.showMessageDialog(((SwingController) PluginManager
200
+                        .getPluginManager().getPluginInfoByName("ui_swing")
201
+                        .getPlugin()).getMainFrame(), "This file has already "
202
+                        + "been completed, or is longer than the file you are "
203
+                        + "receiving.\nPlease choose a different file.",
204
+                        "Problem with selected file",
205
+                        JOptionPane.ERROR_MESSAGE);
206
+                saveFile(nickname, send, parser, reverse, token);
207
+                return false;
191
             }
208
             }
209
+        }
210
+        return true;
211
+    }
192
 
212
 
193
-        }, "saveFileThread: " + sendFilename);
194
-        // Start the thread
195
-        dccThread.start();
213
+    /**
214
+     * Prompts the user to resume a transfer if required.
215
+     *
216
+     * @param jc File chooser
217
+     *
218
+     * @return true if the user wants to continue the transfer false otherwise
219
+     */
220
+    private boolean handleResume(final JFileChooser jc) {
221
+        if (jc.getSelectedFile().exists()) {
222
+            if (IdentityManager.getGlobalConfig().getOptionBool(getDomain(),
223
+                    "receive.autoaccept")) {
224
+                return true;
225
+            } else {
226
+                final int result = JOptionPane.showConfirmDialog(
227
+                        ((SwingController) PluginManager
228
+                        .getPluginManager().getPluginInfoByName("ui_swing")
229
+                        .getPlugin()).getMainFrame(), "This file exists already"
230
+                        + ", do you want to resume an exisiting download?",
231
+                        "Resume Download?", JOptionPane.YES_NO_OPTION);
232
+                return (result == JOptionPane.YES_OPTION);
233
+            }
234
+        }
235
+        return false;
196
     }
236
     }
197
 
237
 
198
     /**
238
     /**
199
-     * Process an event of the specified type.
239
+     * Sets up and display a file chooser.
200
      *
240
      *
201
-     * @param type The type of the event to process
202
-     * @param format Format of messages that are about to be sent. (May be null)
203
-     * @param arguments The arguments for the event
241
+     * @param send DCCTransfer object sending the file
242
+     * @param jc File chooser
243
+     *
244
+     * @return   the return state of the file chooser on popdown:
245
+     * <ul>
246
+     * <li>JFileChooser.CANCEL_OPTION
247
+     * <li>JFileChooser.APPROVE_OPTION
248
+     * <li>JFileChooser.ERROR_OPTION if an error occurs or the
249
+     *                               dialog is dismissed
250
+     * </ul>
204
      */
251
      */
252
+    private int showFileChooser(final DCCTransfer send, final JFileChooser jc) {
253
+        jc.setDialogTitle("Save " + send.getShortFileName() + " As - DMDirc");
254
+                jc.setFileSelectionMode(JFileChooser.FILES_ONLY);
255
+                jc.setMultiSelectionEnabled(false);
256
+                jc.setSelectedFile(new File(send.getFileName()));
257
+        return jc.showSaveDialog(((SwingController) PluginManager
258
+                .getPluginManager().getPluginInfoByName("ui_swing")
259
+                .getPlugin()).getMainFrame());
260
+    }
261
+
262
+    /** {@inheritDoc} */
205
     @Override
263
     @Override
206
-    public void processEvent(final ActionType type, final StringBuffer format, final Object... arguments) {
264
+    public void processEvent(final ActionType type, final StringBuffer format,
265
+            final Object... arguments) {
207
         handleProcessEvent(type, format, false, arguments);
266
         handleProcessEvent(type, format, false, arguments);
208
     }
267
     }
209
 
268
 
216
      * @return True if Socket was opened.
275
      * @return True if Socket was opened.
217
      */
276
      */
218
     protected boolean listen(final DCC dcc) {
277
     protected boolean listen(final DCC dcc) {
219
-
220
-        final boolean usePortRange = IdentityManager.getGlobalConfig().getOptionBool(getDomain(), "firewall.ports.usePortRange");
221
-        final int startPort = IdentityManager.getGlobalConfig().getOptionInt(getDomain(), "firewall.ports.startPort");
222
-        final int endPort = IdentityManager.getGlobalConfig().getOptionInt(getDomain(), "firewall.ports.endPort");
223
-
278
+        final boolean usePortRange = IdentityManager.getGlobalConfig()
279
+                .getOptionBool(getDomain(), "firewall.ports.usePortRange");
224
         try {
280
         try {
225
             if (usePortRange) {
281
             if (usePortRange) {
282
+                final int startPort = IdentityManager.getGlobalConfig()
283
+                        .getOptionInt(getDomain(), "firewall.ports.startPort");
284
+                final int endPort = IdentityManager.getGlobalConfig()
285
+                        .getOptionInt(getDomain(), "firewall.ports.endPort");
226
                 dcc.listen(startPort, endPort);
286
                 dcc.listen(startPort, endPort);
227
             } else {
287
             } else {
228
                 dcc.listen();
288
                 dcc.listen();
241
      * @param dontAsk Don't ask any questions, assume yes.
301
      * @param dontAsk Don't ask any questions, assume yes.
242
      * @param arguments The arguments for the event
302
      * @param arguments The arguments for the event
243
      */
303
      */
244
-    public void handleProcessEvent(final ActionType type, final StringBuffer format, final boolean dontAsk, final Object... arguments) {
245
-        if (IdentityManager.getGlobalConfig().getOptionBool(getDomain(), "receive.autoaccept") && !dontAsk) {
304
+    public void handleProcessEvent(final ActionType type, 
305
+            final StringBuffer format, final boolean dontAsk,
306
+            final Object... arguments) {
307
+        if (IdentityManager.getGlobalConfig().getOptionBool(getDomain(),
308
+                "receive.autoaccept") && !dontAsk) {
246
             handleProcessEvent(type, format, true, arguments);
309
             handleProcessEvent(type, format, true, arguments);
247
             return;
310
             return;
248
         }
311
         }
249
 
312
 
250
         if (type == CoreActionType.SERVER_CTCP) {
313
         if (type == CoreActionType.SERVER_CTCP) {
251
-            final String ctcpType = (String) arguments[2];
252
             final String[] ctcpData = ((String) arguments[3]).split(" ");
314
             final String[] ctcpData = ((String) arguments[3]).split(" ");
253
-            if (ctcpType.equalsIgnoreCase("DCC")) {
254
-                if (ctcpData[0].equalsIgnoreCase("chat") && ctcpData.length > 3) {
255
-                    final String nickname = ((ClientInfo) arguments[1]).getNickname();
256
-                    if (dontAsk) {
257
-                        final DCCChat chat = new DCCChat();
258
-                        try {
259
-                            chat.setAddress(Long.parseLong(ctcpData[2]), Integer.parseInt(ctcpData[3]));
260
-                        } catch (NumberFormatException nfe) {
261
-                            return;
262
-                        }
263
-                        final String myNickname = ((Server) arguments[0]).getParser().getLocalClient().getNickname();
264
-                        final DCCFrameContainer<?> f = new ChatContainer(this, chat, "Chat: " + nickname, myNickname, nickname);
265
-                        f.addLine("DCCChatStarting", nickname, chat.getHost(), chat.getPort());
266
-                        chat.connect();
267
-                    } else {
268
-                        ActionManager.processEvent(DCCActions.DCC_CHAT_REQUEST, null, ((Server) arguments[0]), nickname);
269
-                        askQuestion("User " + nickname + " on " + ((Server) arguments[0]).toString() + " would like to start a DCC Chat with you.\n\nDo you want to continue?", "DCC Chat Request", JOptionPane.YES_OPTION, type, format, arguments);
270
-                        return;
271
-                    }
272
-                } else if (ctcpData[0].equalsIgnoreCase("send") && ctcpData.length > 3) {
273
-                    final String nickname = ((ClientInfo) arguments[1]).getNickname();
274
-                    final String filename;
275
-                    String tmpFilename;
276
-                    // Clients tend to put files with spaces in the name in "" so lets look for that.
277
-                    final StringBuilder filenameBits = new StringBuilder();
278
-                    int i;
279
-                    final boolean quoted = ctcpData[1].startsWith("\"");
280
-                    if (quoted) {
281
-                        for (i = 1; i < ctcpData.length; i++) {
282
-                            String bit = ctcpData[i];
283
-                            if (i == 1) {
284
-                                bit = bit.substring(1);
285
-                            }
286
-                            if (bit.endsWith("\"")) {
287
-                                filenameBits.append(" " + bit.substring(0, bit.length() - 1));
288
-                                break;
289
-                            } else {
290
-                                filenameBits.append(" " + bit);
291
-                            }
292
-                        }
293
-                        tmpFilename = filenameBits.toString().trim();
294
-                    } else {
295
-                        tmpFilename = ctcpData[1];
296
-                        i = 1;
297
-                    }
315
+            if ("DCC".equalsIgnoreCase((String) arguments[2])) {
316
+                if ("chat".equalsIgnoreCase(ctcpData[0])
317
+                        && ctcpData.length > 3) {
318
+                    handleChat(type, format, dontAsk, ctcpData, arguments);
319
+                } else if ("send".equalsIgnoreCase(ctcpData[0])
320
+                        && ctcpData.length > 3) {
321
+                    handleSend(type, format, dontAsk, ctcpData, arguments);
322
+                } else if (("resume".equalsIgnoreCase(ctcpData[0])
323
+                        || "accept".equalsIgnoreCase(ctcpData[0]))
324
+                        && ctcpData.length > 2) {
325
+                    handleReceive(ctcpData, arguments);
326
+                }
327
+            }
328
+        }
329
+    }
298
 
330
 
299
-                    // Try to remove path names if sent.
300
-                    // Change file separatorChar from other OSs first
301
-                    if (File.separatorChar == '/') {
302
-                        tmpFilename = tmpFilename.replace('\\', File.separatorChar);
303
-                    } else {
304
-                        tmpFilename = tmpFilename.replace('/', File.separatorChar);
305
-                    }
306
-                    // Then get just the name of the file.
307
-                    filename = (new File(tmpFilename)).getName();
308
-
309
-                    final String ip = ctcpData[++i];
310
-                    final String port = ctcpData[++i];
311
-                    long size;
312
-                    if (ctcpData.length + 1 > i) {
313
-                        try {
314
-                            size = Integer.parseInt(ctcpData[++i]);
315
-                        } catch (NumberFormatException nfe) {
316
-                            size = -1;
317
-                        }
318
-                    } else {
319
-                        size = -1;
320
-                    }
321
-                    final String token = (ctcpData.length - 1 > i && !ctcpData[i + 1].equals("T")) ? ctcpData[++i] : "";
331
+    /**
332
+     * Handles a DCC chat request.
333
+     *
334
+     * @param type The type of the event to process
335
+     * @param format Format of messages that are about to be sent. (May be null)
336
+     * @param dontAsk Don't ask any questions, assume yes.
337
+     * @param ctcpData CTCP data bits
338
+     * @param arguments The arguments for the event
339
+     */
340
+    private void handleChat(final ActionType type, final StringBuffer format,
341
+            final boolean dontAsk, final String[] ctcpData,
342
+            final Object... arguments) {
343
+        final String nickname = ((ClientInfo) arguments[1]).getNickname();
344
+        if (dontAsk) {
345
+            final DCCChat chat = new DCCChat();
346
+            try {
347
+                chat.setAddress(Long.parseLong(ctcpData[2]),
348
+                        Integer.parseInt(ctcpData[3]));
349
+            } catch (NumberFormatException nfe) {
350
+                return;
351
+            }
352
+            final String myNickname = ((Server) arguments[0]).getParser()
353
+                    .getLocalClient().getNickname();
354
+            final DCCFrameContainer<?> f = new ChatContainer(this, chat,
355
+                    "Chat: " + nickname, myNickname, nickname);
356
+            f.addLine("DCCChatStarting", nickname, chat.getHost(),
357
+                    chat.getPort());
358
+            chat.connect();
359
+        } else {
360
+            ActionManager.processEvent(DCCActions.DCC_CHAT_REQUEST, null,
361
+                    ((Server) arguments[0]), nickname);
362
+            askQuestion("User " + nickname + " on "
363
+                    + ((Server) arguments[0]).toString()
364
+                    + " would like to start a DCC Chat with you.\n\n"
365
+                    + "Do you want to continue?",
366
+                    "DCC Chat Request", JOptionPane.YES_OPTION,
367
+                    type, format, arguments);
368
+            return;
369
+        }
370
+    }
322
 
371
 
323
-                    // Ignore incorrect ports, or non-numeric IP/Port
324
-                    try {
325
-                        int portInt = Integer.parseInt(port);
326
-                        if (portInt > 65535 || portInt < 0) {
327
-                            return;
328
-                        }
329
-                        Long.parseLong(ip);
330
-                    } catch (NumberFormatException nfe) {
331
-                        return;
332
-                    }
372
+    /**
373
+     * Handles a DCC send request.
374
+     *
375
+     * @param type The type of the event to process
376
+     * @param format Format of messages that are about to be sent. (May be null)
377
+     * @param dontAsk Don't ask any questions, assume yes.
378
+     * @param ctcpData CTCP data bits
379
+     * @param arguments The arguments for the event
380
+     */
381
+    private void handleSend(final ActionType type, final StringBuffer format,
382
+            final boolean dontAsk, final String[] ctcpData,
383
+            final Object... arguments) {
384
+        final String nickname = ((ClientInfo) arguments[1]).getNickname();
385
+        final String filename;
386
+        String tmpFilename;
387
+        // Clients tend to put files with spaces in the name in ""
388
+        final StringBuilder filenameBits = new StringBuilder();
389
+        int i;
390
+        final boolean quoted = ctcpData[1].startsWith("\"");
391
+        if (quoted) {
392
+            for (i = 1; i < ctcpData.length; i++) {
393
+                String bit = ctcpData[i];
394
+                if (i == 1) {
395
+                    bit = bit.substring(1);
396
+                }
397
+                if (bit.endsWith("\"")) {
398
+                    filenameBits.append(" ")
399
+                            .append(bit.substring(0, bit.length() - 1));
400
+                    break;
401
+                } else {
402
+                    filenameBits.append(" ").append(bit);
403
+                }
404
+            }
405
+            tmpFilename = filenameBits.toString().trim();
406
+        } else {
407
+            tmpFilename = ctcpData[1];
408
+            i = 1;
409
+        }
333
 
410
 
334
-                    DCCTransfer send = DCCTransfer.findByToken(token);
411
+        // Try to remove path names if sent.
412
+        // Change file separatorChar from other OSs first
413
+        if (File.separatorChar == '/') {
414
+            tmpFilename = tmpFilename.replace('\\', File.separatorChar);
415
+        } else {
416
+            tmpFilename = tmpFilename.replace('/', File.separatorChar);
417
+        }
418
+        // Then get just the name of the file.
419
+        filename = (new File(tmpFilename)).getName();
335
 
420
 
336
-                    if (send == null && !dontAsk) {
337
-                        if (!token.isEmpty() && !port.equals("0")) {
338
-                            // This is a reverse DCC Send that we no longer care about.
339
-                            return;
340
-                        } else {
341
-                            ActionManager.processEvent(DCCActions.DCC_SEND_REQUEST, null, ((Server) arguments[0]), nickname, filename);
342
-                            askQuestion("User " + nickname + " on " + ((Server) arguments[0]).toString() + " would like to send you a file over DCC.\n\nFile: " + filename + "\n\nDo you want to continue?", "DCC Send Request", JOptionPane.YES_OPTION, type, format, arguments);
343
-                            return;
344
-                        }
345
-                    } else {
346
-                        final boolean newSend = send == null;
347
-                        if (newSend) {
348
-                            send = new DCCTransfer(IdentityManager.getGlobalConfig().getOptionInt(getDomain(), "send.blocksize"));
349
-                            send.setTurbo(IdentityManager.getGlobalConfig().getOptionBool(getDomain(), "send.forceturbo"));
350
-                        }
351
-                        try {
352
-                            send.setAddress(Long.parseLong(ip), Integer.parseInt(port));
353
-                        } catch (NumberFormatException nfe) {
354
-                            return;
355
-                        }
356
-                        if (newSend) {
357
-                            send.setFileName(filename);
358
-                            send.setFileSize(size);
359
-                            saveFile(nickname, send, ((Server) arguments[0]).getParser(), "0".equals(port), (quoted) ? "\"" + filename + "\"" : filename, token);
360
-                        } else {
361
-                            send.connect();
362
-                        }
363
-                    }
364
-                } else if ((ctcpData[0].equalsIgnoreCase("resume") || ctcpData[0].equalsIgnoreCase("accept")) && ctcpData.length > 2) {
365
-
366
-                    final String filename;
367
-                    // Clients tend to put files with spaces in the name in "" so lets look for that.
368
-                    final StringBuilder filenameBits = new StringBuilder();
369
-                    int i;
370
-                    final boolean quoted = ctcpData[1].startsWith("\"");
371
-                    if (quoted) {
372
-                        for (i = 1; i < ctcpData.length; i++) {
373
-                            String bit = ctcpData[i];
374
-                            if (i == 1) {
375
-                                bit = bit.substring(1);
376
-                            }
377
-                            if (bit.endsWith("\"")) {
378
-                                filenameBits.append(" " + bit.substring(0, bit.length() - 1));
379
-                                break;
421
+        final String ip = ctcpData[++i];
422
+        final String port = ctcpData[++i];
423
+        long size;
424
+        if (ctcpData.length + 1 > i) {
425
+            try {
426
+                size = Integer.parseInt(ctcpData[++i]);
427
+            } catch (NumberFormatException nfe) {
428
+                size = -1;
429
+            }
430
+        } else {
431
+            size = -1;
432
+        }
433
+        final String token = (ctcpData.length - 1 > i
434
+                && !ctcpData[i + 1].equals("T")) ? ctcpData[++i] : "";
435
+
436
+        // Ignore incorrect ports, or non-numeric IP/Port
437
+        try {
438
+            int portInt = Integer.parseInt(port);
439
+            if (portInt > 65535 || portInt < 0) {
440
+                return;
441
+            }
442
+            Long.parseLong(ip);
443
+        } catch (NumberFormatException nfe) {
444
+            return;
445
+        }
446
+
447
+        DCCTransfer send = DCCTransfer.findByToken(token);
448
+
449
+        if (send == null && !dontAsk) {
450
+            if (!token.isEmpty() && !port.equals("0")) {
451
+                // This is a reverse DCC Send that we no longer care about.
452
+                return;
453
+            } else {
454
+                ActionManager.processEvent(DCCActions.DCC_SEND_REQUEST, null,
455
+                        ((Server) arguments[0]), nickname, filename);
456
+                askQuestion("User " + nickname + " on "
457
+                        + ((Server) arguments[0]).toString()
458
+                        + " would like to send you a file over DCC.\n\nFile: "
459
+                        + filename + "\n\nDo you want to continue?",
460
+                        "DCC Send Request", JOptionPane.YES_OPTION, type,
461
+                        format, arguments);
462
+                return;
463
+            }
464
+        } else {
465
+            final boolean newSend = send == null;
466
+            if (newSend) {
467
+                send = new DCCTransfer(IdentityManager.getGlobalConfig()
468
+                        .getOptionInt(getDomain(), "send.blocksize"));
469
+                send.setTurbo(IdentityManager.getGlobalConfig().getOptionBool(
470
+                        getDomain(), "send.forceturbo"));
471
+            }
472
+            try {
473
+                send.setAddress(Long.parseLong(ip), Integer.parseInt(port));
474
+            } catch (NumberFormatException nfe) {
475
+                return;
476
+            }
477
+            if (newSend) {
478
+                send.setFileName(filename);
479
+                send.setFileSize(size);
480
+                saveFile(nickname, send, ((Server) arguments[0]).getParser(),
481
+                        "0".equals(port), token);
482
+            } else {
483
+                send.connect();
484
+            }
485
+        }
486
+    }
487
+
488
+    /**
489
+     * Handles a DCC chat request.
490
+     *
491
+     * @param ctcpData CTCP data bits
492
+     * @param arguments The arguments for the event
493
+     */
494
+    private void handleReceive(final String[] ctcpData,
495
+            final Object... arguments) {
496
+        final String filename;
497
+        // Clients tend to put files with spaces in the name in ""
498
+        final StringBuilder filenameBits = new StringBuilder();
499
+        int i;
500
+        final boolean quoted = ctcpData[1].startsWith("\"");
501
+        if (quoted) {
502
+            for (i = 1; i < ctcpData.length; i++) {
503
+                String bit = ctcpData[i];
504
+                if (i == 1) {
505
+                    bit = bit.substring(1);
506
+                }
507
+                if (bit.endsWith("\"")) {
508
+                    filenameBits.append(" ")
509
+                            .append(bit.substring(0, bit.length() - 1));
510
+                    break;
511
+                } else {
512
+                    filenameBits.append(" ").append(bit);
513
+                }
514
+            }
515
+            filename = filenameBits.toString().trim();
516
+        } else {
517
+            filename = ctcpData[1];
518
+            i = 1;
519
+        }
520
+
521
+        final int port;
522
+        final int position;
523
+        try {
524
+            port = Integer.parseInt(ctcpData[++i]);
525
+            position = Integer.parseInt(ctcpData[++i]);
526
+            } catch (NumberFormatException nfe) {
527
+                return;
528
+        }
529
+        final String token = (ctcpData.length - 1 > i) ? " "
530
+                + ctcpData[++i] : "";
531
+
532
+        // Now look for a dcc that matches.
533
+        for (DCCTransfer send : DCCTransfer.getTransfers()) {
534
+            if (send.getPort() == port && (new File(send.getFileName()))
535
+                    .getName().equalsIgnoreCase(filename)) {
536
+                if ((!token.isEmpty() && !send.getToken().isEmpty())
537
+                        && (!token.equals(send.getToken()))) {
538
+                    continue;
539
+                }
540
+                final Parser parser = ((Server) arguments[0]).getParser();
541
+                final String nick = ((ClientInfo) arguments[1]).getNickname();
542
+                if (ctcpData[0].equalsIgnoreCase("resume")) {
543
+                    parser.sendCTCP(nick, "DCC", "ACCEPT "+ ((quoted) ? "\"" 
544
+                            + filename + "\"" : filename) + " " + port + " "
545
+                            + send.setFileStart(position) + token);
546
+                } else {
547
+                    send.setFileStart(position);
548
+                    if (port == 0) {
549
+                        // Reverse dcc
550
+                        if (listen(send)) {
551
+                            if (send.getToken().isEmpty()) {
552
+                                parser.sendCTCP(nick, "DCC", "SEND " 
553
+                                        + ((quoted) ? "\"" + filename
554
+                                        + "\"" : filename) + " " 
555
+                                        + DCC.ipToLong(send.getHost())
556
+                                        + " " + send.getPort()
557
+                                        + " " + send.getFileSize());
380
                             } else {
558
                             } else {
381
-                                filenameBits.append(" " + bit);
559
+                                parser.sendCTCP(nick, "DCC", "SEND "
560
+                                        + ((quoted) ? "\"" + filename
561
+                                        + "\"" : filename) 
562
+                                        + " " + DCC.ipToLong(send.getHost())
563
+                                        + " " + send.getPort()
564
+                                        + " " + send.getFileSize() + " "
565
+                                        + send.getToken());
382
                             }
566
                             }
383
                         }
567
                         }
384
-                        filename = filenameBits.toString().trim();
385
                     } else {
568
                     } else {
386
-                        filename = ctcpData[1];
387
-                        i = 1;
388
-                    }
389
-
390
-                    try {
391
-                        final int port = Integer.parseInt(ctcpData[++i]);
392
-                        final int position = Integer.parseInt(ctcpData[++i]);
393
-                        final String token = (ctcpData.length - 1 > i) ? " " + ctcpData[++i] : "";
394
-
395
-                        // Now look for a dcc that matches.
396
-                        for (DCCTransfer send : DCCTransfer.getTransfers()) {
397
-                            if (send.getPort() == port && (new File(send.getFileName())).getName().equalsIgnoreCase(filename)) {
398
-                                if ((!token.isEmpty() && !send.getToken().isEmpty()) && (!token.equals(send.getToken()))) {
399
-                                    continue;
400
-                                }
401
-                                final Parser parser = ((Server) arguments[0]).getParser();
402
-                                final String nickname = ((ClientInfo) arguments[1]).getNickname();
403
-                                if (ctcpData[0].equalsIgnoreCase("resume")) {
404
-                                    parser.sendCTCP(nickname, "DCC", "ACCEPT " + ((quoted) ? "\"" + filename + "\"" : filename) + " " + port + " " + send.setFileStart(position) + token);
405
-                                } else {
406
-                                    send.setFileStart(position);
407
-                                    if (port == 0) {
408
-                                        // Reverse dcc
409
-                                        if (listen(send)) {
410
-                                            if (send.getToken().isEmpty()) {
411
-                                                parser.sendCTCP(nickname, "DCC", "SEND " + ((quoted) ? "\"" + filename + "\"" : filename) + " " + DCC.ipToLong(send.getHost()) + " " + send.getPort() + " " + send.getFileSize());
412
-                                            } else {
413
-                                                parser.sendCTCP(nickname, "DCC", "SEND " + ((quoted) ? "\"" + filename + "\"" : filename) + " " + DCC.ipToLong(send.getHost()) + " " + send.getPort() + " " + send.getFileSize() + " " + send.getToken());
414
-                                            }
415
-                                        } else {
416
-                                            // Listen failed.
417
-                                        }
418
-                                    } else {
419
-                                        send.connect();
420
-                                    }
421
-                                }
422
-                            }
423
-                        }
424
-                    } catch (NumberFormatException nfe) {
569
+                        send.connect();
425
                     }
570
                     }
426
                 }
571
                 }
427
             }
572
             }
428
         }
573
         }
429
     }
574
     }
430
 
575
 
576
+
577
+
431
     /**
578
     /**
432
      * Retrieves the container for the placeholder.
579
      * Retrieves the container for the placeholder.
433
      *
580
      *
465
         final Identity defaults = IdentityManager.getAddonIdentity();
612
         final Identity defaults = IdentityManager.getAddonIdentity();
466
 
613
 
467
         defaults.setOption(getDomain(), "receive.savelocation",
614
         defaults.setOption(getDomain(), "receive.savelocation",
468
-                Main.getConfigDir() + "downloads" + System.getProperty("file.separator"));
615
+                Main.getConfigDir() + "downloads"
616
+                + System.getProperty("file.separator"));
469
     }
617
     }
470
 
618
 
471
     /**
619
     /**
473
      */
621
      */
474
     @Override
622
     @Override
475
     public void onLoad() {
623
     public void onLoad() {
476
-        final File dir = new File(IdentityManager.getGlobalConfig().getOption(getDomain(), "receive.savelocation"));
624
+        final File dir = new File(IdentityManager.getGlobalConfig()
625
+                .getOption(getDomain(), "receive.savelocation"));
477
         if (dir.exists()) {
626
         if (dir.exists()) {
478
             if (!dir.isDirectory()) {
627
             if (!dir.isDirectory()) {
479
-                Logger.userError(ErrorLevel.LOW, "Unable to create download dir (file exists instead)");
628
+                Logger.userError(ErrorLevel.LOW,
629
+                        "Unable to create download dir (file exists instead)");
480
             }
630
             }
481
         } else {
631
         } else {
482
             try {
632
             try {
483
                 dir.mkdirs();
633
                 dir.mkdirs();
484
                 dir.createNewFile();
634
                 dir.createNewFile();
485
             } catch (IOException ex) {
635
             } catch (IOException ex) {
486
-                Logger.userError(ErrorLevel.LOW, "Unable to create download dir");
636
+                Logger.userError(ErrorLevel.LOW,
637
+                        "Unable to create download dir");
487
             }
638
             }
488
         }
639
         }
489
 
640
 
522
      * @return The IP Address we should send as our listening IP.
673
      * @return The IP Address we should send as our listening IP.
523
      */
674
      */
524
     public String getListenIP(final Parser parser) {
675
     public String getListenIP(final Parser parser) {
525
-        final String configIP = IdentityManager.getGlobalConfig().getOption(getDomain(), "firewall.ip");
676
+        final String configIP = IdentityManager.getGlobalConfig().getOption(
677
+                getDomain(), "firewall.ip");
526
         if (!configIP.isEmpty()) {
678
         if (!configIP.isEmpty()) {
527
             try {
679
             try {
528
                 return InetAddress.getByName(configIP).getHostAddress();
680
                 return InetAddress.getByName(configIP).getHostAddress();
529
-            } catch (UnknownHostException ex) {
530
-                //Fallthrough
681
+            } catch (UnknownHostException ex) { //NOPMD - handled below
682
+                //Continue below
531
             }
683
             }
532
         }
684
         }
533
         if (parser != null) {
685
         if (parser != null) {
535
             if (!myHost.isEmpty()) {
687
             if (!myHost.isEmpty()) {
536
                 try {
688
                 try {
537
                     return InetAddress.getByName(myHost).getHostAddress();
689
                     return InetAddress.getByName(myHost).getHostAddress();
538
-                } catch (UnknownHostException e) { /* Will return default host below */ }
690
+                } catch (UnknownHostException e) { //NOPMD - handled below
691
+                    //Continue below
692
+                }
539
             }
693
             }
540
         }
694
         }
541
         try {
695
         try {
543
         } catch (UnknownHostException e) {
697
         } catch (UnknownHostException e) {
544
             // This is almost certainly not what we want, but we can't work out
698
             // This is almost certainly not what we want, but we can't work out
545
             // the right one.
699
             // the right one.
546
-            return "127.0.0.1";
700
+            return "127.0.0.1"; //NOPMD
547
         }
701
         }
548
     }
702
     }
549
 
703
 
550
     /** {@inheritDoc} */
704
     /** {@inheritDoc} */
551
     @Override
705
     @Override
552
     public void showConfig(final PreferencesDialogModel manager) {
706
     public void showConfig(final PreferencesDialogModel manager) {
553
-        final PreferencesCategory general = new PluginPreferencesCategory(getPluginInfo(), "DCC", "", "category-dcc");
554
-        final PreferencesCategory firewall = new PluginPreferencesCategory(getPluginInfo(), "Firewall", "");
555
-        final PreferencesCategory sending = new PluginPreferencesCategory(getPluginInfo(), "Sending", "");
556
-        final PreferencesCategory receiving = new PluginPreferencesCategory(getPluginInfo(), "Receiving", "");
707
+        final PreferencesCategory general = new PluginPreferencesCategory(
708
+                getPluginInfo(), "DCC", "", "category-dcc");
709
+        final PreferencesCategory firewall = new PluginPreferencesCategory(
710
+                getPluginInfo(), "Firewall", "");
711
+        final PreferencesCategory sending = new PluginPreferencesCategory(
712
+                getPluginInfo(), "Sending", "");
713
+        final PreferencesCategory receiving = new PluginPreferencesCategory(
714
+                getPluginInfo(), "Receiving", "");
557
 
715
 
558
         manager.getCategory("Plugins").addSubCategory(general.setInlineAfter());
716
         manager.getCategory("Plugins").addSubCategory(general.setInlineAfter());
559
         general.addSubCategory(firewall.setInline());
717
         general.addSubCategory(firewall.setInline());
565
                 "What IP should be sent as our IP (Blank = work it out)"));
723
                 "What IP should be sent as our IP (Blank = work it out)"));
566
         firewall.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
724
         firewall.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
567
                 getDomain(), "firewall.ports.usePortRange", "Use Port Range",
725
                 getDomain(), "firewall.ports.usePortRange", "Use Port Range",
568
-                "Useful if you have a firewall that only forwards specific ports"));
726
+                "Useful if you have a firewall that only forwards specific "
727
+                + "ports"));
569
         firewall.addSetting(new PreferencesSetting(PreferencesType.INTEGER,
728
         firewall.addSetting(new PreferencesSetting(PreferencesType.INTEGER,
570
                 getDomain(), "firewall.ports.startPort", "Start Port",
729
                 getDomain(), "firewall.ports.startPort", "Start Port",
571
                 "Port to try to listen on first"));
730
                 "Port to try to listen on first"));
577
                 "Where the save as window defaults to?"));
736
                 "Where the save as window defaults to?"));
578
         sending.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
737
         sending.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
579
                 getDomain(), "send.reverse", "Reverse DCC",
738
                 getDomain(), "send.reverse", "Reverse DCC",
580
-                "With reverse DCC, the sender connects rather than " +
581
-                "listens like normal dcc"));
739
+                "With reverse DCC, the sender connects rather than "
740
+                + "listens like normal dcc"));
582
         sending.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
741
         sending.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
583
                 getDomain(), "send.forceturbo", "Use Turbo DCC",
742
                 getDomain(), "send.forceturbo", "Use Turbo DCC",
584
-                "Turbo DCC doesn't wait for ack packets. this is " +
585
-                "faster but not always supported."));
743
+                "Turbo DCC doesn't wait for ack packets. this is "
744
+                + "faster but not always supported."));
586
         receiving.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
745
         receiving.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
587
                 getDomain(), "receive.reverse.sendtoken",
746
                 getDomain(), "receive.reverse.sendtoken",
588
                 "Send token in reverse receive",
747
                 "Send token in reverse receive",
589
-                "If you have problems with reverse dcc receive resume," +
590
-                " try toggling this."));
748
+                "If you have problems with reverse dcc receive resume,"
749
+                + " try toggling this."));
591
         general.addSetting(new PreferencesSetting(PreferencesType.INTEGER,
750
         general.addSetting(new PreferencesSetting(PreferencesType.INTEGER,
592
                 getDomain(), "send.blocksize", "Blocksize to use for DCC",
751
                 getDomain(), "send.blocksize", "Blocksize to use for DCC",
593
-                "Change the block size for send/receive, this can " +
594
-                "sometimes speed up transfers."));
752
+                "Change the block size for send/receive, this can "
753
+                + "sometimes speed up transfers."));
595
         general.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
754
         general.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
596
                 getDomain(), "general.percentageInTitle",
755
                 getDomain(), "general.percentageInTitle",
597
                 "Show percentage of transfers in the window title",
756
                 "Show percentage of transfers in the window title",
598
-                "Show the current percentage of transfers in the DCC window title"));
757
+                "Show the current percentage of transfers in the DCC window "
758
+                + "title"));
599
     }
759
     }
600
 
760
 
601
-}
761
+}

+ 32
- 19
src/com/dmdirc/addons/dcc/TransferContainer.java View File

34
 import com.dmdirc.parser.interfaces.Parser;
34
 import com.dmdirc.parser.interfaces.Parser;
35
 import com.dmdirc.parser.interfaces.callbacks.SocketCloseListener;
35
 import com.dmdirc.parser.interfaces.callbacks.SocketCloseListener;
36
 import com.dmdirc.ui.WindowManager;
36
 import com.dmdirc.ui.WindowManager;
37
-import com.dmdirc.ui.interfaces.Window;
38
 
37
 
39
 import java.awt.Desktop;
38
 import java.awt.Desktop;
40
 import java.io.File;
39
 import java.io.File;
82
             Desktop.getDesktop().isSupported(Desktop.Action.OPEN);
81
             Desktop.getDesktop().isSupported(Desktop.Action.OPEN);
83
 
82
 
84
     /**
83
     /**
85
-     * Creates a new instance of DCCTransferWindow with a given DCCTransfer object.
84
+     * Creates a new instance of DCCTransferWindow with a given DCCTransfer
85
+     * object.
86
      *
86
      *
87
      * @param plugin the DCC Plugin responsible for this window
87
      * @param plugin the DCC Plugin responsible for this window
88
      * @param dcc The DCCTransfer object this window wraps around
88
      * @param dcc The DCCTransfer object this window wraps around
94
             final String title, final String targetNick, final Server server) {
94
             final String title, final String targetNick, final Server server) {
95
         super(dcc.getType() == DCCTransfer.TransferType.SEND
95
         super(dcc.getType() == DCCTransfer.TransferType.SEND
96
                 ? "dcc-send-inactive" : "dcc-receive-inactive",
96
                 ? "dcc-send-inactive" : "dcc-receive-inactive",
97
-                title, title, TransferWindow.class, IdentityManager.getGlobalConfig());
97
+                title, title, TransferWindow.class,
98
+                IdentityManager.getGlobalConfig());
98
         this.plugin = plugin;
99
         this.plugin = plugin;
99
         this.dcc = dcc;
100
         this.dcc = dcc;
100
         this.server = server;
101
         this.server = server;
102
         this.myPlugin = plugin;
103
         this.myPlugin = plugin;
103
 
104
 
104
         if (parser != null) {
105
         if (parser != null) {
105
-            parser.getCallbackManager().addNonCriticalCallback(SocketCloseListener.class, this);
106
+            parser.getCallbackManager().addNonCriticalCallback(
107
+                    SocketCloseListener.class, this);
106
         }
108
         }
107
         dcc.addHandler(this);
109
         dcc.addHandler(this);
108
 
110
 
152
             percent = getPercent();
154
             percent = getPercent();
153
         }
155
         }
154
 
156
 
155
-        boolean percentageInTitle = IdentityManager.getGlobalConfig().getOptionBool(
156
-                            plugin.getDomain(), "general.percentageInTitle");
157
+        boolean percentageInTitle = IdentityManager.getGlobalConfig()
158
+                .getOptionBool(plugin.getDomain(), "general.percentageInTitle");
157
 
159
 
158
         if (percentageInTitle) {
160
         if (percentageInTitle) {
159
             final StringBuilder title = new StringBuilder();
161
             final StringBuilder title = new StringBuilder();
160
             if (dcc.isListenSocket()) { title.append("*"); }
162
             if (dcc.isListenSocket()) { title.append("*"); }
161
-            title.append(dcc.getType() == DCCTransfer.TransferType.SEND ? "Sending: " : "Recieving: ");
163
+            title.append(dcc.getType() == DCCTransfer.TransferType.SEND
164
+                    ? "Sending: " : "Recieving: ");
162
             title.append(otherNickname);
165
             title.append(otherNickname);
163
-            title.append(" ("+ String.format("%.0f", Math.floor(percent)) +"%)");
166
+            title.append(" (")
167
+                    .append(String.format("%.0f", Math.floor(percent)))
168
+                    .append("%)");
164
             setName(title.toString());
169
             setName(title.toString());
165
             setTitle(title.toString());
170
             setTitle(title.toString());
166
         }
171
         }
167
 
172
 
168
-        ActionManager.processEvent(DCCActions.DCC_SEND_DATATRANSFERED, null, this, bytes);
173
+        ActionManager.processEvent(DCCActions.DCC_SEND_DATATRANSFERED,
174
+                null, this, bytes);
169
     }
175
     }
170
 
176
 
171
     /**
177
     /**
175
      * @return The percentage of this transfer that has been completed
181
      * @return The percentage of this transfer that has been completed
176
      */
182
      */
177
     public double getPercent() {
183
     public double getPercent() {
178
-        return (100.00 / dcc.getFileSize()) * (transferCount + dcc.getFileStart());
184
+        return (100.00 / dcc.getFileSize()) * (transferCount
185
+                + dcc.getFileStart());
179
     }
186
     }
180
 
187
 
181
     /**
188
     /**
203
         final long remaningBytes;
210
         final long remaningBytes;
204
 
211
 
205
         synchronized (this) {
212
         synchronized (this) {
206
-            remaningBytes = dcc.getFileSize() - dcc.getFileStart() - transferCount;
213
+            remaningBytes = dcc.getFileSize() - dcc.getFileStart()
214
+                    - transferCount;
207
         }
215
         }
208
 
216
 
209
         return bytesPerSecond > 0 ? (remaningBytes / bytesPerSecond) : 1;
217
         return bytesPerSecond > 0 ? (remaningBytes / bytesPerSecond) : 1;
213
      * Retrieves the timestamp at which this transfer started.
221
      * Retrieves the timestamp at which this transfer started.
214
      *
222
      *
215
      * @since 0.6.4
223
      * @since 0.6.4
216
-     * @return The timestamp (milliseconds since 01/01/1970) at which this transfer started.
224
+     * @return The timestamp (milliseconds since 01/01/1970) at which this
225
+     * transfer started.
217
      */
226
      */
218
     public long getStartTime() {
227
     public long getStartTime() {
219
         return timeStarted;
228
         return timeStarted;
257
      */
266
      */
258
     @Override
267
     @Override
259
     public void socketClosed(final DCCTransfer dcc) {
268
     public void socketClosed(final DCCTransfer dcc) {
260
-        ActionManager.processEvent(DCCActions.DCC_SEND_SOCKETCLOSED, null, this);
269
+        ActionManager.processEvent(DCCActions.DCC_SEND_SOCKETCLOSED, null,
270
+                this);
261
         if (!windowClosing) {
271
         if (!windowClosing) {
262
             synchronized (this) {
272
             synchronized (this) {
263
                 if (transferCount == dcc.getFileSize() - dcc.getFileStart()) {
273
                 if (transferCount == dcc.getFileSize() - dcc.getFileStart()) {
278
      */
288
      */
279
     @Override
289
     @Override
280
     public void socketOpened(final DCCTransfer dcc) {
290
     public void socketOpened(final DCCTransfer dcc) {
281
-        ActionManager.processEvent(DCCActions.DCC_SEND_SOCKETOPENED, null, this);
291
+        ActionManager.processEvent(DCCActions.DCC_SEND_SOCKETOPENED, null,
292
+                this);
282
         timeStarted = System.currentTimeMillis();
293
         timeStarted = System.currentTimeMillis();
283
         setIcon(dcc.getType() == DCCTransfer.TransferType.SEND
294
         setIcon(dcc.getType() == DCCTransfer.TransferType.SEND
284
                 ? "dcc-send-active" : "dcc-receive-active");
295
                 ? "dcc-send-active" : "dcc-receive-active");
297
         dcc.reset();
308
         dcc.reset();
298
 
309
 
299
         if (server != null && server.getState() == ServerState.CONNECTED) {
310
         if (server != null && server.getState() == ServerState.CONNECTED) {
300
-            final String myNickname = server.getParser().getLocalClient().getNickname();
301
-            // Check again incase we have changed nickname to the same nickname that
302
-            // this send is for.
311
+            final String myNickname = server.getParser().getLocalClient()
312
+                    .getNickname();
313
+            // Check again incase we have changed nickname to the same nickname
314
+            //that this send is for.
303
             if (server.getParser().getStringConverter().equalsIgnoreCase(
315
             if (server.getParser().getStringConverter().equalsIgnoreCase(
304
                     otherNickname, myNickname)) {
316
                     otherNickname, myNickname)) {
305
                 final Thread errorThread = new Thread(new Runnable() {
317
                 final Thread errorThread = new Thread(new Runnable() {
347
         // 2: Remove any callbacks or listeners
359
         // 2: Remove any callbacks or listeners
348
         // 3: Trigger any actions neccessary
360
         // 3: Trigger any actions neccessary
349
         dcc.removeFromTransfers();
361
         dcc.removeFromTransfers();
350
-        
362
+
351
         // 4: Trigger action for the window closing
363
         // 4: Trigger action for the window closing
352
         // 5: Inform any parents that the window is closing
364
         // 5: Inform any parents that the window is closing
353
     }
365
     }
361
     public void addSocketCloseCallback(final SocketCloseListener listener) {
373
     public void addSocketCloseCallback(final SocketCloseListener listener) {
362
         if (server != null && server.getParser() != null) {
374
         if (server != null && server.getParser() != null) {
363
             server.getParser().getCallbackManager()
375
             server.getParser().getCallbackManager()
364
-                    .addNonCriticalCallback(SocketCloseListener.class, listener);
376
+                    .addNonCriticalCallback(SocketCloseListener.class,
377
+                    listener);
365
         }
378
         }
366
     }
379
     }
367
 
380
 

+ 6
- 5
src/com/dmdirc/addons/mediasource_dbus/DBusMediaSource.java View File

24
 
24
 
25
 import com.dmdirc.addons.nowplaying.MediaSource;
25
 import com.dmdirc.addons.nowplaying.MediaSource;
26
 import com.dmdirc.addons.nowplaying.MediaSourceManager;
26
 import com.dmdirc.addons.nowplaying.MediaSourceManager;
27
+import com.dmdirc.logger.ErrorLevel;
28
+import com.dmdirc.logger.Logger;
27
 import com.dmdirc.plugins.Plugin;
29
 import com.dmdirc.plugins.Plugin;
28
 
30
 
29
 import java.io.BufferedReader;
31
 import java.io.BufferedReader;
107
         exeArgs[2] = iface;
109
         exeArgs[2] = iface;
108
         exeArgs[3] = method;
110
         exeArgs[3] = method;
109
 
111
 
110
-        for (int i = 0; i < args.length; i++) {
111
-            exeArgs[4 + i] = args[i]; //NOPMD
112
-        }
112
+        System.arraycopy(args, 0, exeArgs, 4, args.length);
113
 
113
 
114
         return getInfo(exeArgs);
114
         return getInfo(exeArgs);
115
     }
115
     }
143
             input.close();
143
             input.close();
144
             process.destroy();
144
             process.destroy();
145
         } catch (IOException ex) {
145
         } catch (IOException ex) {
146
-            ex.printStackTrace();
146
+            Logger.userError(ErrorLevel.HIGH, "Unable to get dbus info", ex);
147
         }
147
         }
148
 
148
 
149
         return result;
149
         return result;
155
      * @param lines The lines to be parsed as a dictionary
155
      * @param lines The lines to be parsed as a dictionary
156
      * @return A map corresponding to the specified dictionary
156
      * @return A map corresponding to the specified dictionary
157
      */
157
      */
158
-    protected static Map<String, String> parseDictionary(final List<String> lines) {
158
+    protected static Map<String, String> parseDictionary(
159
+            final List<String> lines) {
159
         final Map<String, String> res = new HashMap<String, String>();
160
         final Map<String, String> res = new HashMap<String, String>();
160
 
161
 
161
         for (String line : lines) {
162
         for (String line : lines) {

+ 95
- 80
src/com/dmdirc/addons/ui_swing/Apple.java View File

55
 public final class Apple implements InvocationHandler, ActionListener {
55
 public final class Apple implements InvocationHandler, ActionListener {
56
 
56
 
57
     /**
57
     /**
58
-     * Dummy interface for ApplicationEvent from the Apple UI on non-Apple platforms.
58
+     * Dummy interface for ApplicationEvent from the Apple UI on non-Apple
59
+     * platforms.
59
      * http://developer.apple.com/documentation/Java/Reference/1.5.0/appledoc/api/com/apple/eawt/ApplicationEvent.html
60
      * http://developer.apple.com/documentation/Java/Reference/1.5.0/appledoc/api/com/apple/eawt/ApplicationEvent.html
60
      */
61
      */
61
     public interface ApplicationEvent {
62
     public interface ApplicationEvent {
108
     /** The MenuBar for the application. */
109
     /** The MenuBar for the application. */
109
     private MenuBar menuBar = null;
110
     private MenuBar menuBar = null;
110
     /** Has the CLIENT_OPENED action been called? */
111
     /** Has the CLIENT_OPENED action been called? */
111
-    private volatile boolean clientOpened = false;
112
+    private boolean clientOpened = false;
112
     /** Store any addresses that are opened before CLIENT_OPENED. */
113
     /** Store any addresses that are opened before CLIENT_OPENED. */
113
     private final List<URI> addresses = new ArrayList<URI>();
114
     private final List<URI> addresses = new ArrayList<URI>();
114
 
115
 
118
      * @return Apple instance.
119
      * @return Apple instance.
119
      */
120
      */
120
     public static Apple getApple() {
121
     public static Apple getApple() {
121
-        if (me == null) {
122
-            me = new Apple();
122
+        synchronized (Apple.class) {
123
+            if (me == null) {
124
+                me = new Apple();
125
+            }
126
+            return me;
123
         }
127
         }
124
-        return me;
125
     }
128
     }
126
 
129
 
127
     /**
130
     /**
137
     private Apple() {
140
     private Apple() {
138
         if (isApple()) {
141
         if (isApple()) {
139
             try {
142
             try {
140
-                System.loadLibrary("DMDirc-Apple");
143
+                System.loadLibrary("DMDirc-Apple"); //NOPMD
141
                 registerOpenURLCallback();
144
                 registerOpenURLCallback();
142
                 ActionManager.addListener(this, CoreActionType.CLIENT_OPENED);
145
                 ActionManager.addListener(this, CoreActionType.CLIENT_OPENED);
143
             } catch (UnsatisfiedLinkError ule) {
146
             } catch (UnsatisfiedLinkError ule) {
153
      * @return Object that on OSX will be an "Application"
156
      * @return Object that on OSX will be an "Application"
154
      */
157
      */
155
     public static Object getApplication() {
158
     public static Object getApplication() {
156
-        if (application == null && isApple()) {
157
-            try {
158
-                final Class<?> app = Class.forName("com.apple.eawt.Application");
159
-                final Method method = app.getMethod("getApplication",
160
-                        new Class[0]);
161
-                application = method.invoke(null, new Object[0]);
162
-            } catch (ClassNotFoundException ex) {
163
-                // Probably not on OS X, do nothing.
164
-            } catch (NoSuchMethodException ex) {
165
-                // Probably not on OS X, do nothing.
166
-            } catch (SecurityException ex) {
167
-                // Probably not on OS X, do nothing.
168
-            } catch (IllegalAccessException ex) {
169
-                // Probably not on OS X, do nothing.
170
-            } catch (IllegalArgumentException ex) {
171
-                // Probably not on OS X, do nothing.
172
-            } catch (InvocationTargetException ex) {
173
-                // Probably not on OS X, do nothing.
159
+        synchronized (Apple.class) {
160
+            if (isApple() && application == null) {
161
+                try {
162
+                    final Class<?> app = Class.forName(
163
+                            "com.apple.eawt.Application");
164
+                    final Method method = app.getMethod("getApplication",
165
+                            new Class[0]);
166
+                    application = method.invoke(null, new Object[0]);
167
+                } catch (ClassNotFoundException ex) {
168
+                    application = null;
169
+                } catch (NoSuchMethodException ex) {
170
+                    application = null;
171
+                } catch (SecurityException ex) {
172
+                    application = null;
173
+                } catch (IllegalAccessException ex) {
174
+                    application = null;
175
+                } catch (IllegalArgumentException ex) {
176
+                    application = null;
177
+                } catch (InvocationTargetException ex) {
178
+                    application = null;
179
+                }
174
             }
180
             }
181
+            return application;
175
         }
182
         }
176
-        return application;
177
     }
183
     }
178
 
184
 
179
     /**
185
     /**
182
      * @return Object that on OSX will be an "NSApplication"
188
      * @return Object that on OSX will be an "NSApplication"
183
      */
189
      */
184
     public static Object getNSApplication() {
190
     public static Object getNSApplication() {
185
-        if (nsApplication == null && isApple()) {
186
-            try {
187
-                final Class<?> app = Class.forName(
188
-                        "com.apple.cocoa.application.NSApplication");
189
-                final Method method = app.getMethod("sharedApplication",
190
-                        new Class[0]);
191
-                nsApplication = method.invoke(null, new Object[0]);
192
-            } catch (ClassNotFoundException ex) {
193
-                // Probably not on OS X, do nothing.
194
-            } catch (NoSuchMethodException ex) {
195
-                // Probably not on OS X, do nothing.
196
-            } catch (IllegalAccessException ex) {
197
-                // Probably not on OS X, do nothing.
198
-            } catch (InvocationTargetException ex) {
199
-                // Probably not on OS X, do nothing.
200
-            }
191
+        synchronized (Apple.class) {
192
+           if (isApple() && nsApplication == null) {
193
+               try {
194
+                    final Class<?> app = Class.forName(
195
+                            "com.apple.cocoa.application.NSApplication");
196
+                    final Method method = app.getMethod("sharedApplication",
197
+                            new Class[0]);
198
+                    nsApplication = method.invoke(null, new Object[0]);
199
+               } catch (ClassNotFoundException ex) {
200
+                   nsApplication = null;
201
+               } catch (NoSuchMethodException ex) {
202
+                    nsApplication = null;
203
+                } catch (IllegalAccessException ex) {
204
+                    nsApplication = null;
205
+               } catch (InvocationTargetException ex) {
206
+                  nsApplication = null;
207
+               }
208
+          }
209
+         return nsApplication;
201
         }
210
         }
202
-        return nsApplication;
203
     }
211
     }
204
 
212
 
205
     /**
213
     /**
263
                     "requestUserAttention", new Class[]{Integer.TYPE});
271
                     "requestUserAttention", new Class[]{Integer.TYPE});
264
             method.invoke(getNSApplication(), new Object[]{type.get(null)});
272
             method.invoke(getNSApplication(), new Object[]{type.get(null)});
265
         } catch (NoSuchFieldException ex) {
273
         } catch (NoSuchFieldException ex) {
266
-            // Probably not on OS X, do nothing.
274
+            Logger.userError(ErrorLevel.LOW, "Unable to find OS X classes");
267
         } catch (NoSuchMethodException ex) {
275
         } catch (NoSuchMethodException ex) {
268
-            // Probably not on OS X, do nothing.
276
+            Logger.userError(ErrorLevel.LOW, "Unable to find OS X classes");
269
         } catch (IllegalAccessException ex) {
277
         } catch (IllegalAccessException ex) {
270
-            // Probably not on OS X, do nothing.
278
+            Logger.userError(ErrorLevel.LOW, "Unable to find OS X classes");
271
         } catch (InvocationTargetException ex) {
279
         } catch (InvocationTargetException ex) {
272
-            // Probably not on OS X, do nothing.
280
+            Logger.userError(ErrorLevel.LOW, "Unable to find OS X classes");
273
         }
281
         }
274
     }
282
     }
275
 
283
 
305
             method.invoke(getApplication(), new Object[]{Boolean.TRUE});
313
             method.invoke(getApplication(), new Object[]{Boolean.TRUE});
306
             return true;
314
             return true;
307
         } catch (ClassNotFoundException ex) {
315
         } catch (ClassNotFoundException ex) {
308
-            // Probably not on OS X, do nothing.
316
+            return false;
309
         } catch (NoSuchMethodException ex) {
317
         } catch (NoSuchMethodException ex) {
310
-            // Probably not on OS X, do nothing.
318
+            return false;
311
         } catch (IllegalAccessException ex) {
319
         } catch (IllegalAccessException ex) {
312
-            // Probably not on OS X, do nothing.
320
+            return false;
313
         } catch (InvocationTargetException ex) {
321
         } catch (InvocationTargetException ex) {
314
-            // Probably not on OS X, do nothing.
322
+            return false;
315
         }
323
         }
316
-        return false;
317
     }
324
     }
318
 
325
 
319
     /**
326
     /**
357
      * Set the MenuBar.
364
      * Set the MenuBar.
358
      * This will unset all menu mnemonics aswell if on the OSX ui.
365
      * This will unset all menu mnemonics aswell if on the OSX ui.
359
      *
366
      *
360
-     * @param menuBar MenuBar to use to send events to,
367
+     * @param newMenuBar MenuBar to use to send events to,
361
      */
368
      */
362
-    public void setMenuBar(final MenuBar menuBar) {
363
-        this.menuBar = menuBar;
364
-        if (isAppleUI()) {
365
-            for (int i = 0; i < menuBar.getMenuCount(); i++) {
366
-                final JMenu menu = menuBar.getMenu(i);
367
-                if (menu != null) {
368
-                    menu.setMnemonic(0);
369
-                    for (int j = 0; j < menu.getItemCount(); j++) {
370
-                        final JMenuItem menuItem = menu.getItem(j);
371
-                        if (menuItem != null) {
372
-                            menuItem.setMnemonic(0);
373
-                        }
374
-                    }
369
+    public void setMenuBar(final MenuBar newMenuBar) {
370
+        this.menuBar = newMenuBar;
371
+        if (!isAppleUI()) {
372
+            return;
373
+        }
374
+        for (int i = 0; i < menuBar.getMenuCount(); i++) {
375
+            final JMenu menu = menuBar.getMenu(i);
376
+            if (menu == null) {
377
+                continue;
378
+            }
379
+            menu.setMnemonic(0);
380
+            for (int j = 0; j < menu.getItemCount(); j++) {
381
+                final JMenuItem menuItem = menu.getItem(j);
382
+                if (menuItem != null) {
383
+                    menuItem.setMnemonic(0);
375
                 }
384
                 }
376
             }
385
             }
377
         }
386
         }
429
      * @param event an ApplicationEvent object
438
      * @param event an ApplicationEvent object
430
      */
439
      */
431
     public void handleOpenApplication(final ApplicationEvent event) {
440
     public void handleOpenApplication(final ApplicationEvent event) {
441
+        //We don't currently support this
432
     }
442
     }
433
 
443
 
434
     /**
444
     /**
437
      * @param event an ApplicationEvent object
447
      * @param event an ApplicationEvent object
438
      */
448
      */
439
     public void handleOpenFile(final ApplicationEvent event) {
449
     public void handleOpenFile(final ApplicationEvent event) {
450
+        //We don't currently support this
440
     }
451
     }
441
 
452
 
442
     /**
453
     /**
445
      * @param event an ApplicationEvent object
456
      * @param event an ApplicationEvent object
446
      */
457
      */
447
     public void handlePrintFile(final ApplicationEvent event) {
458
     public void handlePrintFile(final ApplicationEvent event) {
459
+        //We don't currently support this
448
     }
460
     }
449
 
461
 
450
     /**
462
     /**
453
      * @param event an ApplicationEvent object
465
      * @param event an ApplicationEvent object
454
      */
466
      */
455
     public void handleReopenApplication(final ApplicationEvent event) {
467
     public void handleReopenApplication(final ApplicationEvent event) {
468
+        //We don't currently support this
456
     }
469
     }
457
 
470
 
458
     /** {@inheritDoc} */
471
     /** {@inheritDoc} */
479
      * @param url The irc url to connect to.
492
      * @param url The irc url to connect to.
480
      */
493
      */
481
     public void handleOpenURL(final String url) {
494
     public void handleOpenURL(final String url) {
482
-        if (isApple()) {
495
+        if (!isApple()) {
496
+            return;
497
+        }
498
+        synchronized (addresses) {
483
             try {
499
             try {
484
-                synchronized (addresses) {
485
-                    final URI addr = NewServer.getURI(url);
486
-                    if (!clientOpened) {
487
-                        addresses.add(addr);
488
-                    } else {
489
-                        // When the JNI callback is called there is no
490
-                        // ContextClassLoader set, which causes an NPE in
491
-                        // IconManager if no servers have been connected to yet.
492
-                        if (Thread.currentThread().getContextClassLoader() ==
493
-                                null) {
494
-                            Thread.currentThread().setContextClassLoader(ClassLoader.
495
-                                    getSystemClassLoader());
496
-                        }
497
-                        ServerManager.getServerManager().connectToAddress(addr);
500
+                final URI addr = NewServer.getURI(url);
501
+                if (clientOpened) {
502
+                    // When the JNI callback is called there is no
503
+                    // ContextClassLoader set, which causes an NPE in
504
+                    // IconManager if no servers have been connected to yet.
505
+                    if (Thread.currentThread().getContextClassLoader()
506
+                            == null) {
507
+                        Thread.currentThread().setContextClassLoader(
508
+                                ClassLoader.getSystemClassLoader());
498
                     }
509
                     }
510
+                    ServerManager.getServerManager().connectToAddress(addr);
511
+                } else {
512
+                    addresses.add(addr);
499
                 }
513
                 }
500
             } catch (URISyntaxException iae) {
514
             } catch (URISyntaxException iae) {
515
+                //Do nothing
501
             }
516
             }
502
         }
517
         }
503
     }
518
     }

+ 0
- 1
src/com/dmdirc/addons/ui_swing/SwingController.java View File

83
 import java.awt.KeyboardFocusManager;
83
 import java.awt.KeyboardFocusManager;
84
 import java.awt.Toolkit;
84
 import java.awt.Toolkit;
85
 import java.awt.Dialog.ModalityType;
85
 import java.awt.Dialog.ModalityType;
86
-import java.io.Serializable;
87
 import java.net.URI;
86
 import java.net.URI;
88
 import java.util.ArrayList;
87
 import java.util.ArrayList;
89
 import java.util.HashMap;
88
 import java.util.HashMap;

+ 0
- 1
src/com/dmdirc/addons/ui_swing/dialogs/StandardDialog.java View File

22
 
22
 
23
 package com.dmdirc.addons.ui_swing.dialogs;
23
 package com.dmdirc.addons.ui_swing.dialogs;
24
 
24
 
25
-import com.dmdirc.addons.ui_swing.UIUtilities;
26
 import com.dmdirc.ui.CoreUIUtils;
25
 import com.dmdirc.ui.CoreUIUtils;
27
 
26
 
28
 import java.awt.Component;
27
 import java.awt.Component;

+ 0
- 1
src/com/dmdirc/addons/ui_swing/framemanager/tree/NodeLabel.java View File

37
 import javax.swing.BorderFactory;
37
 import javax.swing.BorderFactory;
38
 import javax.swing.JPanel;
38
 import javax.swing.JPanel;
39
 import javax.swing.JTextPane;
39
 import javax.swing.JTextPane;
40
-import javax.swing.SwingUtilities;
41
 import javax.swing.UIManager;
40
 import javax.swing.UIManager;
42
 import javax.swing.text.DefaultStyledDocument;
41
 import javax.swing.text.DefaultStyledDocument;
43
 import javax.swing.text.StyledDocument;
42
 import javax.swing.text.StyledDocument;

+ 1
- 1
src/com/dmdirc/addons/ui_swing/textpane/BackgroundImageLoader.java View File

57
 
57
 
58
     /** {@inheritDoc} */
58
     /** {@inheritDoc} */
59
     @Override
59
     @Override
60
-    protected Image doInBackground() throws Exception {
60
+    protected Image doInBackground() {
61
         try {
61
         try {
62
             if (imageURL != null) {
62
             if (imageURL != null) {
63
                 return ImageIO.read(imageURL);
63
                 return ImageIO.read(imageURL);

Loading…
Cancel
Save