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