Prevent missing length from throwing an NPE.
[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          *
152          * @return The remote’s hostname
153          */
154         public String hostname() {
155                 return hostname;
156         }
157
158         /**
159          * Returns the port number of the remote end of the connection.
160          *
161          * @return The remote’s port number
162          */
163         public int port() {
164                 return port;
165         }
166
167         /**
168          * Returns whether this connection has already been established.
169          *
170          * @return {@code true} as long as this connection is established, {@code
171          *         false} otherwise
172          */
173         public boolean established() {
174                 return established;
175         }
176
177         /**
178          * Returns the nickname that is currently in use by this connection. The
179          * nickname is only available once the connection has been {@link #start()}ed.
180          *
181          * @return The current nickname
182          */
183         public String nickname() {
184                 return nickname;
185         }
186
187         //
188         // MUTATORS
189         //
190
191         /**
192          * Sets the nickname chooser. The nickname chooser is only used during the
193          * creation of the connection.
194          *
195          * @param nicknameChooser
196          *              The nickname chooser
197          * @return This connection
198          */
199         public Connection nicknameChooser(NicknameChooser nicknameChooser) {
200                 this.nicknameChooser = nicknameChooser;
201                 return this;
202         }
203
204         /**
205          * Sets the username to use.
206          *
207          * @param username
208          *              The username to use
209          * @return This connection
210          */
211         public Connection username(String username) {
212                 this.username = Optional.fromNullable(username);
213                 return this;
214         }
215
216         /**
217          * Sets the real name to use.
218          *
219          * @param realName
220          *              The real name to use
221          * @return This connection
222          */
223         public Connection realName(String realName) {
224                 this.realName = Optional.fromNullable(realName);
225                 return this;
226         }
227
228         /**
229          * Sets the optional password for the connection.
230          *
231          * @param password
232          *              The password for the connection
233          * @return This connection
234          */
235         public Connection password(String password) {
236                 this.password = Optional.fromNullable(password);
237                 return this;
238         }
239
240         //
241         // ACTIONS
242         //
243
244         /**
245          * Returns the current rate of the connection’s incoming side.
246          *
247          * @return The current input rate (in bytes per second)
248          */
249         public long getInputRate() {
250                 return (connectionHandler != null) ? connectionHandler.getInputRate() : 0;
251         }
252
253         /**
254          * Returns the current rate of the connection’s outgoing side.
255          *
256          * @return The current output rate (in bytes per second)
257          */
258         public long getOutputRate() {
259                 return (connectionHandler != null) ? connectionHandler.getOutputRate() : 0;
260         }
261
262         /**
263          * Checks whether the given source is the client represented by this
264          * connection.
265          *
266          * @param source
267          *              The source to check
268          * @return {@code true} if this connection represents the given source, {@code
269          *         false} otherwise
270          */
271         public boolean isSource(Source source) {
272                 return source.nick().isPresent() && source.nick().get().equals(nickname);
273         }
274
275         /**
276          * Joins the given channel.
277          *
278          * @param channel
279          *              The channel to join
280          * @throws IOException
281          *              if an I/O error occurs
282          */
283         public void joinChannel(final String channel) throws IOException {
284                 connectionHandler.sendCommand("JOIN", channel);
285         }
286
287         /**
288          * Sends a message to the given recipient, which may be a channel or another
289          * nickname.
290          *
291          * @param recipient
292          *              The recipient of the message
293          * @param message
294          *              The message
295          * @throws IOException
296          *              if an I/O error occurs
297          */
298         public void sendMessage(String recipient, String message) throws IOException {
299                 connectionHandler.sendCommand("PRIVMSG", recipient, message);
300         }
301
302         /**
303          * Sends a DCC RESUME request to the given recipient.
304          *
305          * @param recipient
306          *              The recipient of the request
307          * @param filename
308          *              The name of the file to resume
309          * @param port
310          *              The port number from the original DCC SEND request
311          * @param position
312          *              The position at which to resume the transfer
313          * @throws IOException
314          *              if an I/O error occurs
315          */
316         public void sendDccResume(String recipient, String filename, int port, long position) throws IOException {
317                 connectionHandler.sendCommand("PRIVMSG", recipient, String.format("\u0001DCC RESUME %s %d %d\u0001", filename, port, position));
318         }
319
320         /**
321          * Closes this connection.
322          *
323          * @throws IOException
324          *              if an I/O error occurs
325          */
326         public void close() throws IOException {
327                 connectionHandler.close();
328         }
329
330         //
331         // ABSTRACTEXECUTIONTHREADSERVICE METHODS
332         //
333
334         @Override
335         protected void startUp() throws IllegalStateException {
336                 checkState(username.isPresent(), "username must be set");
337                 checkState(realName.isPresent(), "realName must be set");
338         }
339
340         @Override
341         protected void run() {
342
343                 /* connect to remote socket. */
344                 try {
345                         Socket socket = socketFactory.createSocket(hostname, port);
346                         connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
347
348                         /* register connection. */
349                         if (password.isPresent()) {
350                                 connectionHandler.sendCommand("PASSWORD", password.get());
351                         }
352                         connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
353                         nickname = nicknameChooser.getNickname();
354                         connectionHandler.sendCommand("NICK", nickname);
355
356                 } catch (IOException ioe1) {
357                         eventBus.post(new ConnectionFailed(this, ioe1));
358                         return;
359                 }
360
361                 /* now read replies and react. */
362                 try {
363                         /* some status variables. */
364                         int oldConnectionStatus = 0;
365                         int connectionStatus = 0;
366                         boolean connected = true;
367                         StringBuilder motd = new StringBuilder();
368                         Set<Nickname> nicks = Sets.newHashSet();
369
370                         /* server modes. */
371                         Map<String, String> nickPrefixes = Maps.newHashMap();
372                         Set<Character> channelTypes = Sets.newHashSet();
373
374                         while (connected) {
375                                 Reply reply = connectionHandler.readReply();
376                                 logger.finest(String.format("<< %s", reply));
377                                 String command = reply.command();
378                                 List<String> parameters = reply.parameters();
379
380                                 /* most common events. */
381                                 if (command.equalsIgnoreCase("PRIVMSG")) {
382                                         String recipient = parameters.get(0);
383                                         String message = parameters.get(1);
384                                         if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
385                                                 /* CTCP! */
386                                                 handleCtcp(reply.source().get(), message);
387                                         } else if (!channelTypes.contains(recipient.charAt(0))) {
388                                                 eventBus.post(new PrivateMessageReceived(this, reply.source().get(), message));
389                                         } else {
390                                                 eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), message));
391                                         }
392
393                                 } else if (command.equalsIgnoreCase("NOTICE")) {
394                                         String recipient = parameters.get(0);
395                                         String message = parameters.get(1);
396                                         if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
397                                                 /* CTCP! */
398                                                 handleCtcp(reply.source().get(), message);
399                                         } else if (!channelTypes.contains(recipient.charAt(0))) {
400                                                 eventBus.post(new PrivateNoticeReceived(this, reply));
401                                         } else {
402                                                 eventBus.post(new ChannelNoticeReceived(this, reply.source().get(), recipient, message));
403                                         }
404
405                                 /* 43x replies are for nick change errors. */
406                                 } else if (command.equals("431")) {
407                                         eventBus.post(new NoNicknameGivenReceived(this, reply));
408                                 } else if (command.equals("433")) {
409                                         if (connectionStatus == 0) {
410                                                 nickname = nicknameChooser.getNickname();
411                                                 connectionHandler.sendCommand("NICK", nickname);
412                                         } else {
413                                                 eventBus.post(new NicknameInUseReceived(this, reply));
414                                         }
415
416                                 /* client stuff. */
417                                 } else if (command.equalsIgnoreCase("NICK")) {
418                                         eventBus.post(new NicknameChanged(this, reply.source().get(), parameters.get(0)));
419
420                                 /* channel stuff. */
421                                 } else if (command.equalsIgnoreCase("JOIN")) {
422                                         eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
423                                 } else if (command.equals("331")) {
424                                         /* no topic is set. */
425                                 } else if (command.equals("332")) {
426                                         eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
427                                 } else if (command.equals("353")) {
428                                         for (String nickname : parameters.get(3).split(" ")) {
429                                                 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
430                                                         nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
431                                                 } else {
432                                                         nicks.add(new Nickname(nickname, ""));
433                                                 }
434                                         }
435                                 } else if (command.equals("366")) {
436                                         eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
437                                         nicks.clear();
438                                 } else if (command.equalsIgnoreCase("PART")) {
439                                         eventBus.post(new ChannelLeft(this, parameters.get(0), reply.source().get(), getOptional(parameters, 1)));
440                                 } else if (command.equalsIgnoreCase("QUIT")) {
441                                         eventBus.post(new ClientQuit(this, reply.source().get(), parameters.get(0)));
442
443                                 /* common channel join errors. */
444                                 } else if (command.equals("474")) {
445                                         eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
446                                 } else if (command.equals("473")) {
447                                         eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
448                                 } else if (command.equals("475")) {
449                                         eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
450
451                                 /* basic connection housekeeping. */
452                                 } else if (command.equalsIgnoreCase("PING")) {
453                                         connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
454
455                                 /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
456                                 } else if (command.equals("001")) {
457                                         connectionStatus |= 0x01;
458                                 } else if (command.equals("002")) {
459                                         connectionStatus |= 0x02;
460                                 } else if (command.equals("003")) {
461                                         connectionStatus |= 0x04;
462                                 } else if (command.equals("004")) {
463                                         connectionStatus |= 0x08;
464
465                                 /* 005 originally was a bounce message, now used to transmit useful information about the server. */
466                                 } else if (command.equals("005")) {
467                                         for (String parameter : parameters) {
468                                                 if (parameter.startsWith("PREFIX=")) {
469                                                         int openParen = parameter.indexOf('(');
470                                                         int closeParen = parameter.indexOf(')');
471                                                         if ((openParen != -1) && (closeParen != -1)) {
472                                                                 for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
473                                                                         char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
474                                                                         char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
475                                                                         nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
476                                                                 }
477                                                                 logger.fine(String.format("Parsed Prefixes: %s", nickPrefixes));
478                                                         }
479                                                 } else if (parameter.startsWith("CHANTYPES=")) {
480                                                         for (int typeIndex = 10; typeIndex < parameter.length(); ++typeIndex) {
481                                                                 channelTypes.add(parameter.charAt(typeIndex));
482                                                         }
483                                                         logger.fine(String.format("Parsed Channel Types: %s", channelTypes));
484                                                 }
485                                         }
486
487                                 /* 375, 372, and 376 handle the server’s MOTD. */
488                                 } else if (command.equals("375")) {
489                                         /* MOTD starts. */
490                                         motd.append(parameters.get(1)).append('\n');
491                                 } else if (command.equals("372")) {
492                                         motd.append(parameters.get(1)).append('\n');
493                                 } else if (command.equals("376")) {
494                                         motd.append(parameters.get(1)).append('\n');
495                                         eventBus.post(new MotdReceived(this, motd.toString()));
496                                         motd.setLength(0);
497
498                                 /* okay, everything else. */
499                                 } else {
500                                         eventBus.post(new UnknownReplyReceived(this, reply));
501                                 }
502
503                                 if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
504                                         /* connection succeeded! */
505                                         established = true;
506                                         eventBus.post(new ConnectionEstablished(this));
507                                 }
508                                 oldConnectionStatus = connectionStatus;
509                         }
510                         eventBus.post(new ConnectionClosed(this));
511                 } catch (IOException ioe1) {
512                         logger.log(Level.WARNING, "I/O error", ioe1);
513                         eventBus.post(new ConnectionClosed(this, ioe1));
514                 } catch (RuntimeException re1) {
515                         logger.log(Level.SEVERE, "Runtime error", re1);
516                         eventBus.post(new ConnectionClosed(this, re1));
517                 } finally {
518                         established = false;
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         //
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.warning(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.warning(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.finest(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                 }
746
747         }
748
749 }