Prevent NPE on closing.
[xudocci.git] / src / main / java / net / pterodactylus / irc / Connection.java
1 /*
2  * XdccDownloader - Connection.java - Copyright © 2013 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.irc;
19
20 import static com.google.common.base.Preconditions.checkState;
21 import static java.util.concurrent.TimeUnit.SECONDS;
22
23 import java.io.BufferedReader;
24 import java.io.Closeable;
25 import java.io.EOFException;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.InputStreamReader;
29 import java.io.OutputStream;
30 import java.io.UnsupportedEncodingException;
31 import java.net.InetAddress;
32 import java.net.Socket;
33 import java.net.UnknownHostException;
34 import java.util.ArrayList;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Set;
38 import java.util.logging.Level;
39 import java.util.logging.Logger;
40 import javax.net.SocketFactory;
41
42 import net.pterodactylus.irc.event.ChannelJoined;
43 import net.pterodactylus.irc.event.ChannelLeft;
44 import net.pterodactylus.irc.event.ChannelMessageReceived;
45 import net.pterodactylus.irc.event.ChannelNicknames;
46 import net.pterodactylus.irc.event.ChannelNotJoined;
47 import net.pterodactylus.irc.event.ChannelNotJoined.Reason;
48 import net.pterodactylus.irc.event.ChannelNoticeReceived;
49 import net.pterodactylus.irc.event.ChannelTopic;
50 import net.pterodactylus.irc.event.ClientQuit;
51 import net.pterodactylus.irc.event.ConnectionClosed;
52 import net.pterodactylus.irc.event.ConnectionEstablished;
53 import net.pterodactylus.irc.event.ConnectionFailed;
54 import net.pterodactylus.irc.event.DccAcceptReceived;
55 import net.pterodactylus.irc.event.DccSendReceived;
56 import net.pterodactylus.irc.event.MotdReceived;
57 import net.pterodactylus.irc.event.NicknameChanged;
58 import net.pterodactylus.irc.event.NicknameInUseReceived;
59 import net.pterodactylus.irc.event.NoNicknameGivenReceived;
60 import net.pterodactylus.irc.event.PrivateMessageReceived;
61 import net.pterodactylus.irc.event.PrivateNoticeReceived;
62 import net.pterodactylus.irc.event.ReplyReceived;
63 import net.pterodactylus.irc.event.UnknownReplyReceived;
64 import net.pterodactylus.irc.util.RandomNickname;
65 import net.pterodactylus.xdcc.util.io.BandwidthCountingInputStream;
66 import net.pterodactylus.xdcc.util.io.BandwidthCountingOutputStream;
67
68 import com.google.common.base.Optional;
69 import com.google.common.collect.Maps;
70 import com.google.common.collect.Sets;
71 import com.google.common.eventbus.EventBus;
72 import com.google.common.io.Closeables;
73 import com.google.common.primitives.Ints;
74 import com.google.common.primitives.Longs;
75 import com.google.common.util.concurrent.AbstractExecutionThreadService;
76 import com.google.common.util.concurrent.Service;
77
78 /**
79  * A connection to an IRC server.
80  *
81  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
82  */
83 public class Connection extends AbstractExecutionThreadService implements Service {
84
85         /* The logger. */
86         private static final Logger logger = Logger.getLogger(Connection.class.getName());
87
88         /** The event bus. */
89         private final EventBus eventBus;
90
91         /** The socket factory. */
92         private final SocketFactory socketFactory;
93
94         /** The hostname to connect to. */
95         private final String hostname;
96
97         /** The port to connect to. */
98         private final int port;
99
100         /** The nickname chooser. */
101         private NicknameChooser nicknameChooser = new NicknameChooser() {
102
103                 @Override
104                 public String getNickname() {
105                         return RandomNickname.get();
106                 }
107         };
108
109         /** The nickname. */
110         private String nickname = null;
111
112         /** The username. */
113         private Optional<String> username = Optional.absent();
114
115         /** The real name. */
116         private Optional<String> realName = Optional.absent();
117
118         /** The optional password for the connection. */
119         private Optional<String> password = Optional.absent();
120
121         /** The connection handler. */
122         private ConnectionHandler connectionHandler;
123
124         /** Whether the connection has already been established. */
125         private boolean established;
126
127         /**
128          * Creates a new connection.
129          *
130          * @param eventBus
131          *              The event bus
132          * @param socketFactory
133          *              The socket factory
134          * @param hostname
135          *              The hostname of the IRC server
136          * @param port
137          *              The port number of the IRC server
138          */
139         public Connection(EventBus eventBus, SocketFactory socketFactory, String hostname, int port) {
140                 this.eventBus = eventBus;
141                 this.socketFactory = socketFactory;
142                 this.hostname = hostname;
143                 this.port = port;
144         }
145
146         //
147         // ACCESSORS
148         //
149
150         /**
151          * Returns the hostname of the remote end of the connection.
152          *
153          * @return The remote’s hostname
154          */
155         public String hostname() {
156                 return hostname;
157         }
158
159         /**
160          * Returns the port number of the remote end of the connection.
161          *
162          * @return The remote’s port number
163          */
164         public int port() {
165                 return port;
166         }
167
168         /**
169          * Returns whether this connection has already been established.
170          *
171          * @return {@code true} as long as this connection is established, {@code
172          *         false} otherwise
173          */
174         public boolean established() {
175                 return established;
176         }
177
178         /**
179          * Returns the nickname that is currently in use by this connection. The
180          * nickname is only available once the connection has been {@link #start()}ed.
181          *
182          * @return The current nickname
183          */
184         public String nickname() {
185                 return nickname;
186         }
187
188         //
189         // MUTATORS
190         //
191
192         /**
193          * Sets the nickname chooser. The nickname chooser is only used during the
194          * creation of the connection.
195          *
196          * @param nicknameChooser
197          *              The nickname chooser
198          * @return This connection
199          */
200         public Connection nicknameChooser(NicknameChooser nicknameChooser) {
201                 this.nicknameChooser = nicknameChooser;
202                 return this;
203         }
204
205         /**
206          * Sets the username to use.
207          *
208          * @param username
209          *              The username to use
210          * @return This connection
211          */
212         public Connection username(String username) {
213                 this.username = Optional.fromNullable(username);
214                 return this;
215         }
216
217         /**
218          * Sets the real name to use.
219          *
220          * @param realName
221          *              The real name to use
222          * @return This connection
223          */
224         public Connection realName(String realName) {
225                 this.realName = Optional.fromNullable(realName);
226                 return this;
227         }
228
229         /**
230          * Sets the optional password for the connection.
231          *
232          * @param password
233          *              The password for the connection
234          * @return This connection
235          */
236         public Connection password(String password) {
237                 this.password = Optional.fromNullable(password);
238                 return this;
239         }
240
241         //
242         // ACTIONS
243         //
244
245         /**
246          * Returns the current rate of the connection’s incoming side.
247          *
248          * @return The current input rate (in bytes per second)
249          */
250         public long getInputRate() {
251                 return (connectionHandler != null) ? connectionHandler.getInputRate() : 0;
252         }
253
254         /**
255          * Returns the current rate of the connection’s outgoing side.
256          *
257          * @return The current output rate (in bytes per second)
258          */
259         public long getOutputRate() {
260                 return (connectionHandler != null) ? connectionHandler.getOutputRate() : 0;
261         }
262
263         /**
264          * Checks whether the given source is the client represented by this
265          * connection.
266          *
267          * @param source
268          *              The source to check
269          * @return {@code true} if this connection represents the given source, {@code
270          *         false} otherwise
271          */
272         public boolean isSource(Source source) {
273                 return source.nick().isPresent() && source.nick().get().equals(nickname);
274         }
275
276         /**
277          * Joins the given channel.
278          *
279          * @param channel
280          *              The channel to join
281          * @throws IOException
282          *              if an I/O error occurs
283          */
284         public void joinChannel(final String channel) throws IOException {
285                 connectionHandler.sendCommand("JOIN", channel);
286         }
287
288         /**
289          * Sends a message to the given recipient, which may be a channel or another
290          * nickname.
291          *
292          * @param recipient
293          *              The recipient of the message
294          * @param message
295          *              The message
296          * @throws IOException
297          *              if an I/O error occurs
298          */
299         public void sendMessage(String recipient, String message) throws IOException {
300                 connectionHandler.sendCommand("PRIVMSG", recipient, message);
301         }
302
303         /**
304          * Sends a DCC RESUME request to the given recipient.
305          *
306          * @param recipient
307          *              The recipient of the request
308          * @param filename
309          *              The name of the file to resume
310          * @param port
311          *              The port number from the original DCC SEND request
312          * @param position
313          *              The position at which to resume the transfer
314          * @throws IOException
315          *              if an I/O error occurs
316          */
317         public void sendDccResume(String recipient, String filename, int port, long position) throws IOException {
318                 connectionHandler.sendCommand("PRIVMSG", recipient, String.format("\u0001DCC RESUME %s %d %d\u0001", filename, port, position));
319         }
320
321         /**
322          * Closes this connection.
323          *
324          * @throws IOException
325          *              if an I/O error occurs
326          */
327         public void close() throws IOException {
328                 if (connectionHandler != null) {
329                         connectionHandler.close();
330                 }
331         }
332
333         //
334         // ABSTRACTEXECUTIONTHREADSERVICE METHODS
335         //
336
337         @Override
338         protected void startUp() throws IllegalStateException {
339                 checkState(username.isPresent(), "username must be set");
340                 checkState(realName.isPresent(), "realName must be set");
341         }
342
343         @Override
344         protected void run() {
345
346                 /* connect to remote socket. */
347                 try {
348                         Socket socket = socketFactory.createSocket(hostname, port);
349                         connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
350
351                         /* register connection. */
352                         if (password.isPresent()) {
353                                 connectionHandler.sendCommand("PASSWORD", password.get());
354                         }
355                         connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
356                         nickname = nicknameChooser.getNickname();
357                         connectionHandler.sendCommand("NICK", nickname);
358
359                 } catch (IOException ioe1) {
360                         eventBus.post(new ConnectionFailed(this, ioe1));
361                         return;
362                 }
363
364                 /* now read replies and react. */
365                 try {
366                         /* some status variables. */
367                         int oldConnectionStatus = 0;
368                         int connectionStatus = 0;
369                         boolean connected = true;
370                         StringBuilder motd = new StringBuilder();
371                         Set<Nickname> nicks = Sets.newHashSet();
372
373                         /* server modes. */
374                         Map<String, String> nickPrefixes = Maps.newHashMap();
375                         Set<Character> channelTypes = Sets.newHashSet();
376
377                         while (connected) {
378                                 Reply reply = connectionHandler.readReply();
379                                 eventBus.post(new ReplyReceived(this, reply));
380                                 logger.finest(String.format("<< %s", reply));
381                                 String command = reply.command();
382                                 List<String> parameters = reply.parameters();
383
384                                 /* most common events. */
385                                 if (command.equalsIgnoreCase("PRIVMSG")) {
386                                         String recipient = parameters.get(0);
387                                         String message = parameters.get(1);
388                                         if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
389                                                 /* CTCP! */
390                                                 handleCtcp(reply.source().get(), message);
391                                         } else if (!channelTypes.contains(recipient.charAt(0))) {
392                                                 eventBus.post(new PrivateMessageReceived(this, reply.source().get(), message));
393                                         } else {
394                                                 eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), message));
395                                         }
396
397                                 } else if (command.equalsIgnoreCase("NOTICE")) {
398                                         String recipient = parameters.get(0);
399                                         String message = parameters.get(1);
400                                         if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
401                                                 /* CTCP! */
402                                                 handleCtcp(reply.source().get(), message);
403                                         } else if (!channelTypes.contains(recipient.charAt(0))) {
404                                                 eventBus.post(new PrivateNoticeReceived(this, reply));
405                                         } else {
406                                                 eventBus.post(new ChannelNoticeReceived(this, reply.source().get(), recipient, message));
407                                         }
408
409                                 /* 43x replies are for nick change errors. */
410                                 } else if (command.equals("431")) {
411                                         eventBus.post(new NoNicknameGivenReceived(this, reply));
412                                 } else if (command.equals("433")) {
413                                         if (connectionStatus == 0) {
414                                                 nickname = nicknameChooser.getNickname();
415                                                 connectionHandler.sendCommand("NICK", nickname);
416                                         } else {
417                                                 eventBus.post(new NicknameInUseReceived(this, reply));
418                                         }
419
420                                 /* client stuff. */
421                                 } else if (command.equalsIgnoreCase("NICK")) {
422                                         eventBus.post(new NicknameChanged(this, reply.source().get(), parameters.get(0)));
423
424                                 /* channel stuff. */
425                                 } else if (command.equalsIgnoreCase("JOIN")) {
426                                         eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
427                                 } else if (command.equals("331")) {
428                                         /* no topic is set. */
429                                 } else if (command.equals("332")) {
430                                         eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
431                                 } else if (command.equals("353")) {
432                                         for (String nickname : parameters.get(3).split(" ")) {
433                                                 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
434                                                         nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
435                                                 } else {
436                                                         nicks.add(new Nickname(nickname, ""));
437                                                 }
438                                         }
439                                 } else if (command.equals("366")) {
440                                         eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
441                                         nicks.clear();
442                                 } else if (command.equalsIgnoreCase("PART")) {
443                                         eventBus.post(new ChannelLeft(this, parameters.get(0), reply.source().get(), getOptional(parameters, 1)));
444                                 } else if (command.equalsIgnoreCase("QUIT")) {
445                                         eventBus.post(new ClientQuit(this, reply.source().get(), parameters.get(0)));
446
447                                 /* common channel join errors. */
448                                 } else if (command.equals("474")) {
449                                         eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
450                                 } else if (command.equals("473")) {
451                                         eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
452                                 } else if (command.equals("475")) {
453                                         eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
454
455                                 /* basic connection housekeeping. */
456                                 } else if (command.equalsIgnoreCase("PING")) {
457                                         connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
458
459                                 /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
460                                 } else if (command.equals("001")) {
461                                         connectionStatus |= 0x01;
462                                 } else if (command.equals("002")) {
463                                         connectionStatus |= 0x02;
464                                 } else if (command.equals("003")) {
465                                         connectionStatus |= 0x04;
466                                 } else if (command.equals("004")) {
467                                         connectionStatus |= 0x08;
468
469                                 /* 005 originally was a bounce message, now used to transmit useful information about the server. */
470                                 } else if (command.equals("005")) {
471                                         for (String parameter : parameters) {
472                                                 if (parameter.startsWith("PREFIX=")) {
473                                                         int openParen = parameter.indexOf('(');
474                                                         int closeParen = parameter.indexOf(')');
475                                                         if ((openParen != -1) && (closeParen != -1)) {
476                                                                 for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
477                                                                         char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
478                                                                         char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
479                                                                         nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
480                                                                 }
481                                                                 logger.fine(String.format("Parsed Prefixes: %s", nickPrefixes));
482                                                         }
483                                                 } else if (parameter.startsWith("CHANTYPES=")) {
484                                                         for (int typeIndex = 10; typeIndex < parameter.length(); ++typeIndex) {
485                                                                 channelTypes.add(parameter.charAt(typeIndex));
486                                                         }
487                                                         logger.fine(String.format("Parsed Channel Types: %s", channelTypes));
488                                                 }
489                                         }
490
491                                 /* 375, 372, and 376 handle the server’s MOTD. */
492                                 } else if (command.equals("375")) {
493                                         /* MOTD starts. */
494                                         motd.append(parameters.get(1)).append('\n');
495                                 } else if (command.equals("372")) {
496                                         motd.append(parameters.get(1)).append('\n');
497                                 } else if (command.equals("376")) {
498                                         motd.append(parameters.get(1)).append('\n');
499                                         eventBus.post(new MotdReceived(this, motd.toString()));
500                                         motd.setLength(0);
501
502                                 /* okay, everything else. */
503                                 } else {
504                                         eventBus.post(new UnknownReplyReceived(this, reply));
505                                 }
506
507                                 if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
508                                         /* connection succeeded! */
509                                         established = true;
510                                         eventBus.post(new ConnectionEstablished(this));
511                                 }
512                                 oldConnectionStatus = connectionStatus;
513                         }
514                         eventBus.post(new ConnectionClosed(this));
515                 } catch (IOException ioe1) {
516                         logger.log(Level.WARNING, "I/O error", ioe1);
517                         eventBus.post(new ConnectionClosed(this, ioe1));
518                 } catch (RuntimeException re1) {
519                         logger.log(Level.SEVERE, "Runtime error", re1);
520                         eventBus.post(new ConnectionClosed(this, re1));
521                 } finally {
522                         established = false;
523                         logger.info("Closing Connection.");
524                         try {
525                                 Closeables.close(connectionHandler, true);
526                         } catch (IOException ioe1) {
527                                 /* will not be thrown. */
528                         }
529                 }
530
531         }
532
533         //
534         // PRIVATE METHODS
535         //
536
537         /**
538          * Handles a CTCP message.
539          *
540          * @param client
541          *              The client sending the message
542          * @param message
543          *              The message
544          */
545         private void handleCtcp(Source client, String message) {
546                 String[] messageWords = message.substring(1, message.length() - 1).split(" +");
547                 String ctcpCommand = messageWords[0];
548                 if (ctcpCommand.equalsIgnoreCase("DCC")) {
549                         if (messageWords[1].equalsIgnoreCase("SEND")) {
550                                 Optional<InetAddress> inetAddress = parseInetAddress(messageWords[3]);
551                                 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[4]));
552                                 long fileSize = Optional.fromNullable(Longs.tryParse(messageWords[5])).or(-1L);
553                                 if (inetAddress.isPresent() && port.isPresent()) {
554                                         eventBus.post(new DccSendReceived(this, client, messageWords[2], inetAddress.get(), port.get(), fileSize));
555                                 } else {
556                                         logger.warning(String.format("Received malformed DCC SEND: “%s”", message));
557                                 }
558                         } else if (messageWords[1].equalsIgnoreCase("ACCEPT")) {
559                                 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[3]));
560                                 long position = (messageWords.length > 4) ? Optional.fromNullable(Longs.tryParse(messageWords[4])).or(-1L) : -1;
561                                 if (port.isPresent()) {
562                                         eventBus.post(new DccAcceptReceived(this, client, messageWords[2], port.get(), position));
563                                 } else {
564                                         logger.warning(String.format("Received malformed DCC ACCEPT: “%s”", message));
565                                 }
566                         }
567                 }
568         }
569
570         /**
571          * Returns an item from the list, or {@link Optional#absent()} if the list is
572          * shorter than required for the given index.
573          *
574          * @param list
575          *              The list to get an item from
576          * @param index
577          *              The index of the item
578          * @param <T>
579          *              The type of the list items
580          * @return This list item wrapped in an {@link Optional}, or {@link
581          *         Optional#absent()} if the list is not long enough
582          */
583         private static <T> Optional<T> getOptional(List<T> list, int index) {
584                 if (index < list.size()) {
585                         return Optional.fromNullable(list.get(index));
586                 }
587                 return Optional.absent();
588         }
589
590         /**
591          * Parses the given {@code ip} and returns an {@link InetAddress} from it.
592          *
593          * @param ip
594          *              The IP to parse
595          * @return The parsed inet address, or {@link Optional#absent()} if no inet
596          *         address could be parsed
597          */
598         private Optional<InetAddress> parseInetAddress(String ip) {
599                 Long ipNumber = Longs.tryParse(ip);
600                 if (ipNumber == null) {
601                         return Optional.absent();
602                 }
603
604                 StringBuilder hostname = new StringBuilder(15);
605                 hostname.append((ipNumber >>> 24) & 0xff).append('.');
606                 hostname.append((ipNumber >>> 16) & 0xff).append('.');
607                 hostname.append((ipNumber >>> 8) & 0xff).append('.');
608                 hostname.append(ipNumber & 0xff);
609                 try {
610                         return Optional.of(InetAddress.getByName(hostname.toString()));
611                 } catch (UnknownHostException uhe1) {
612                         return Optional.absent();
613                 }
614         }
615
616         /** Handles input and output for the connection. */
617         private class ConnectionHandler implements Closeable {
618
619                 /** The output stream of the connection. */
620                 private final BandwidthCountingOutputStream outputStream;
621
622                 /** The input stream. */
623                 private final BandwidthCountingInputStream inputStream;
624
625                 /** The input stream of the connection. */
626                 private final BufferedReader inputStreamReader;
627
628                 /**
629                  * Creates a new connection handler for the given input stream and output
630                  * stream.
631                  *
632                  * @param inputStream
633                  *              The input stream of the connection
634                  * @param outputStream
635                  *              The output stream of the connection
636                  * @throws UnsupportedEncodingException
637                  *              if the encoding (currently “UTF-8”) is not valid
638                  */
639                 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
640                         this.outputStream = new BandwidthCountingOutputStream(outputStream, 5, SECONDS);
641                         this.inputStream = new BandwidthCountingInputStream(inputStream, 5, SECONDS);
642                         inputStreamReader = new BufferedReader(new InputStreamReader(this.inputStream, "UTF-8"));
643                 }
644
645                 //
646                 // ACTIONS
647                 //
648
649                 /**
650                  * Returns the current rate of the connection’s incoming side.
651                  *
652                  * @return The current input rate (in bytes per second)
653                  */
654                 public long getInputRate() {
655                         return inputStream.getCurrentRate();
656                 }
657
658                 /**
659                  * Returns the current rate of the connection’s outgoing side.
660                  *
661                  * @return The current output rate (in bytes per second)
662                  */
663                 public long getOutputRate() {
664                         return outputStream.getCurrentRate();
665                 }
666
667                 /**
668                  * Sends a command with the given parameters, skipping all {@link
669                  * Optional#absent()} optionals.
670                  *
671                  * @param command
672                  *              The command to send
673                  * @param parameters
674                  *              The parameters
675                  * @throws IOException
676                  *              if an I/O error occurs
677                  */
678                 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
679                         List<String> setParameters = new ArrayList<String>();
680                         for (Optional<String> maybeSetParameter : parameters) {
681                                 if (maybeSetParameter.isPresent()) {
682                                         setParameters.add(maybeSetParameter.get());
683                                 }
684                         }
685                         sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
686                 }
687
688                 /**
689                  * Sends a command with the given parameters.
690                  *
691                  * @param command
692                  *              The command to send
693                  * @param parameters
694                  *              The parameters of the command
695                  * @throws IOException
696                  *              if an I/O error occurs
697                  * @throws IllegalArgumentException
698                  *              if any parameter but that last contains a space character
699                  */
700                 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
701                         StringBuilder commandBuilder = new StringBuilder();
702
703                         commandBuilder.append(command);
704                         for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
705                                 String parameter = parameters[parameterIndex];
706                                 /* space is only allowed in the last parameter. */
707                                 commandBuilder.append(' ');
708                                 if (parameter.contains(" ")) {
709                                         if (parameterIndex == (parameters.length - 1)) {
710                                                 commandBuilder.append(':');
711                                         } else {
712                                                 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
713                                         }
714                                 }
715                                 commandBuilder.append(parameter);
716                         }
717
718                         logger.finest(String.format(">> %s", commandBuilder));
719                         outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
720                         outputStream.flush();
721                 }
722
723                 /**
724                  * Reads a line of reply from the connection.
725                  *
726                  * @return The reply
727                  * @throws IOException
728                  *              if an I/O error occurs
729                  * @throws EOFException
730                  *              if EOF was reached
731                  */
732                 public Reply readReply() throws IOException, EOFException {
733                         String line = inputStreamReader.readLine();
734                         if (line == null) {
735                                 throw new EOFException();
736                         }
737
738                         return Reply.parseLine(line);
739                 }
740
741                 //
742                 // CLOSEABLE METHODS
743                 //
744
745                 @Override
746                 public void close() throws IOException {
747                         Closeables.close(outputStream, true);
748                         Closeables.close(inputStreamReader, true);
749                 }
750
751         }
752
753 }