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