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