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