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