1 package net.pterodactylus.irc.connection;
3 import static java.util.Arrays.asList;
5 import net.pterodactylus.irc.Connection;
6 import net.pterodactylus.irc.Reply;
7 import net.pterodactylus.irc.event.ConnectionEstablished;
9 import com.google.common.eventbus.EventBus;
12 * Handles the necessary commands that establish a connection.
14 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
16 public class ConnectionEstablishHandler implements Handler {
18 private static final int FIRST_COMMAND_RECEIVED = 0x01;
19 private static final int SECOND_COMMAND_RECEIVED = 0x02;
20 private static final int THIRD_COMMAND_RECEIVED = 0x04;
21 private static final int FOURTH_COMMAND_RECEIVED = 0x08;
22 private static final int ALL_COMMANDS_RECEIVED = 0x0f;
24 private final EventBus eventBus;
25 private final Connection connection;
26 private int connectionStatus;
27 private int oldConnectionStatus;
29 public ConnectionEstablishHandler(EventBus eventBus,
30 Connection connection) {
31 this.eventBus = eventBus;
32 this.connection = connection;
36 public boolean willHandle(Reply reply) {
37 return !isFinalConnectionStatusReached() &&
38 asList("001", "002", "003", "004").contains(reply.command());
42 public void handleReply(Reply reply) {
43 String command = reply.command();
44 /* replies 001-004 don’t hold information but they
45 * have to be sent on a successful connection. */
46 if (command.equals("001")) {
47 connectionStatus |= FIRST_COMMAND_RECEIVED;
48 } else if (command.equals("002")) {
49 connectionStatus |= SECOND_COMMAND_RECEIVED;
50 } else if (command.equals("003")) {
51 connectionStatus |= THIRD_COMMAND_RECEIVED;
52 } else if (command.equals("004")) {
53 connectionStatus |= FOURTH_COMMAND_RECEIVED;
56 if (hasConnectionStatusChanged()
57 && isFinalConnectionStatusReached()) {
58 eventBus.post(new ConnectionEstablished(connection));
60 oldConnectionStatus = connectionStatus;
63 private boolean hasConnectionStatusChanged() {
64 return connectionStatus != oldConnectionStatus;
67 private boolean isFinalConnectionStatusReached() {
68 return connectionStatus == ALL_COMMANDS_RECEIVED;