/**
   * Closes the connection by setting presence to unavailable then closing the stream to the XMPP
   * server. The shutdown logic will be used during a planned disconnection or when dealing with an
   * unexpected disconnection. Unlike {@link #disconnect()} the connection's packet reader, packet
   * writer, and {@link Roster} will not be removed; thus connection's state is kept.
   *
   * @param unavailablePresence the presence packet to send during shutdown.
   */
  protected void shutdown(Presence unavailablePresence) {
    // Set presence to offline.
    PacketWriter packetWriter = this.packetWriter;
    if (packetWriter != null) {
      packetWriter.sendPacket(unavailablePresence);
    }

    this.setWasAuthenticated(authenticated);
    authenticated = false;
    connected = false;

    PacketReader packetReader = this.packetReader;
    if (packetReader != null) {
      packetReader.shutdown();
    }
    packetWriter = this.packetWriter;
    if (packetWriter != null) {
      packetWriter.shutdown();
    }
    // Wait 150 ms for processes to clean-up, then shutdown.
    try {
      Thread.sleep(150);
    } catch (Exception e) {
      // Ignore.
    }

    // Close down the readers and writers.
    Reader reader = this.reader;
    if (reader != null) {
      try {
        reader.close();
      } catch (Throwable ignore) {
        /* ignore */
      }
      this.reader = null;
    }
    Writer writer = this.writer;
    if (writer != null) {
      try {
        writer.close();
      } catch (Throwable ignore) {
        /* ignore */
      }
      this.writer = null;
    }

    try {
      socket.close();
    } catch (Exception e) {
      // Ignore.
    }

    saslAuthentication.init();
  }
  /**
   * Start using stream compression since the server has acknowledged stream compression.
   *
   * @throws Exception if there is an exception starting stream compression.
   */
  void startStreamCompression() throws Exception {
    // Secure the plain connection
    usingCompression = true;
    // Initialize the reader and writer with the new secured version
    initReaderAndWriter();

    // Set the new  writer to use
    packetWriter.setWriter(writer);
    // Send a new opening stream to the server
    packetWriter.openStream();
    // Notify that compression is being used
    synchronized (this) {
      this.notify();
    }
  }
 public void sendPacket(Packet packet) {
   if (!isConnected()) {
     throw new IllegalStateException("Not connected to server.");
   }
   if (packet == null) {
     throw new NullPointerException("Packet is null.");
   }
   packetWriter.sendPacket(packet);
 }
  /**
   * The server has indicated that TLS negotiation can start. We now need to secure the existing
   * plain connection and perform a handshake. This method won't return until the connection has
   * finished the handshake or an error occured while securing the connection.
   *
   * @throws Exception if an exception occurs.
   */
  void proceedTLSReceived() throws Exception {
    enableEncryption(true);
    // Initialize the reader and writer with the new secured version
    initReaderAndWriter();
    // Proceed to do the handshake
    ((SSLSocket) socket).startHandshake();
    // if (((SSLSocket) socket).getWantClientAuth()) {
    //    System.err.println("Connection wants client auth");
    // }
    // else if (((SSLSocket) socket).getNeedClientAuth()) {
    //    System.err.println("Connection needs client auth");
    // }
    // else {
    //    System.err.println("Connection does not require client auth");
    // }
    // Set that TLS was successful
    usingTLS = true;

    // Set the new  writer to use
    packetWriter.setWriter(writer);
    // Send a new opening stream to the server
    packetWriter.openStream();
  }
  public void disconnect(Presence unavailablePresence) {
    // If not connected, ignore this request.
    PacketReader packetReader = this.packetReader;
    PacketWriter packetWriter = this.packetWriter;
    if (packetReader == null || packetWriter == null) {
      return;
    }

    shutdown(unavailablePresence);

    if (roster != null) {
      roster.cleanup();
      roster = null;
    }
    chatManager = null;

    wasAuthenticated = false;

    packetWriter.cleanup();
    this.packetWriter = null;
    packetReader.cleanup();
    this.packetReader = null;
  }
  @Override
  public synchronized void loginAnonymously() throws XMPPException {
    if (!isConnected()) {
      throw new IllegalStateException("Not connected to server.");
    }
    if (authenticated) {
      throw new IllegalStateException("Already logged in to server.");
    }

    String response;
    if (config.isSASLAuthenticationEnabled() && saslAuthentication.hasAnonymousAuthentication()) {
      response = saslAuthentication.authenticateAnonymously();
    } else {
      // Authenticate using Non-SASL
      response = new NonSASLAuthentication(this).authenticateAnonymously();
    }

    // Set the user value.
    this.user = response;
    // Update the serviceName with the one returned by the server
    config.setServiceName(StringUtils.parseServer(response));

    // If compression is enabled then request the server to use stream compression
    if (config.isCompressionEnabled()) {
      useCompression();
    }

    // Set presence to online.
    packetWriter.sendPacket(new Presence(Presence.Type.available));

    // Indicate that we're now authenticated.
    authenticated = true;
    anonymous = true;

    // If debugging is enabled, change the the debug window title to include the
    // name we are now logged-in as.
    // If DEBUG_ENABLED was set to true AFTER the connection was created the debugger
    // will be null
    if (config.isDebuggerEnabled() && debugger != null) {
      debugger.userHasLogged(user);
    }
  }
  /**
   * 0 ushort 28 2 ushort 1010 4 uint Timer 8 uint Entity_ID 12 ushort Value_A 14 ushort Value_B 16
   * ushort Value_C 20 ushort Value_D 22 ushort Value_E 24 uint Data_Type
   *
   * @param id the character id to update
   * @param parm1
   * @param parm2
   * @param parm3
   * @param parm4
   * @param parm5
   * @param parm6
   * @param type the subtype of the packet
   * @see GeneralTypes
   * @return returns a new channel buffer containing the packet
   */
  public static ChannelBuffer build(
      long id, int parm1, int parm2, int parm3, int parm4, int parm5, int parm6, int type) {
    PacketWriter Packet = new PacketWriter(28);

    Packet.writeUnSignedShort(Packet.getBuffer().array().length);
    Packet.writeUnSignedShort(PacketTypes.GENERAL_DATA);
    Packet.writeUnSignedInt(System.currentTimeMillis() / 10000L);
    Packet.writeUnSignedInt(id);
    Packet.writeUnSignedShort(parm1);
    Packet.writeUnSignedShort(parm2);
    Packet.writeUnSignedShort(parm3);
    Packet.writeUnSignedShort(parm4);
    Packet.writeUnSignedShort(parm5);
    Packet.writeUnSignedShort(parm6);
    Packet.writeUnSignedInt(type);

    // spouse goes here
    return Packet.getBuffer();
  }
  @Test
  @Ignore
  public void testOutThreadPerformance() throws IOException, InterruptedException {
    new Thread(
            new Runnable() {
              public void run() {
                ServerSocket serverSocket = null;
                try {
                  serverSocket = new ServerSocket(5799);
                } catch (IOException e) {
                  System.out.println("Could not listen on port: 4444");
                  System.exit(-1);
                }
                Socket clientSocket = null;
                try {
                  clientSocket = serverSocket.accept();
                  byte[] bytes = new byte[1000000];
                  while (true) {
                    clientSocket.getInputStream().read(bytes);
                  }
                } catch (IOException e) {
                  System.out.println("Accept failed: 4444");
                  System.exit(-1);
                }
              }
            })
        .start();
    HazelcastClient client = mock(HazelcastClient.class);
    ConnectionManager connectionManager = mock(ConnectionManager.class);
    when(client.getConnectionManager()).thenReturn(connectionManager);
    Connection connection = new Connection("localhost", 5799, 1);
    when(connectionManager.getConnection()).thenReturn(connection);
    PacketWriter packetWriter = new PacketWriter();
    packetWriter.setConnection(connection);
    final OutRunnable outRunnable =
        new OutRunnable(client, new HashMap<Long, Call>(), packetWriter);
    new Thread(outRunnable).start();
    final AtomicLong callCounter = new AtomicLong();
    final long start = Clock.currentTimeMillis();
    ExecutorService executorService = Executors.newFixedThreadPool(20);
    final BlockingQueue<Object> queue = new LinkedBlockingQueue<Object>();
    final Object object = new Object();
    for (int i = 0; i < 16; i++) {
      executorService.execute(
          new Runnable() {

            public void run() {
              for (; ; ) {
                try {
                  queue.take();
                } catch (InterruptedException e) {
                  e.printStackTrace(); // To change body of catch statement use File | Settings |
                  // File Templates.
                }
                Packet packet = new Packet();
                packet.set("c:default", ClusterOperation.CONCURRENT_MAP_GET, new byte[30], null);
                Call call = new Call(callCounter.incrementAndGet(), packet);
                outRunnable.enQueue(call);
              }
            }
          });
    }
    Executors.newSingleThreadExecutor()
        .submit(
            new Runnable() {
              public void run() {
                int numberOfTasks = 10000;
                //                int numberOfTasks = 11000;
                while (true) {
                  try {
                    for (int i = 0; i < numberOfTasks; i++) {
                      queue.offer(object);
                    }
                    //                        numberOfTasks = numberOfTasks + numberOfTasks/10;
                    Thread.sleep(1 * 1000);
                    System.out.println(
                        "Operations per millisecond : "
                            + callCounter.get() / (Clock.currentTimeMillis() - start));
                    System.out.println("out runnable Queue size: " + outRunnable.getQueueSize());
                  } catch (Exception e) {
                    e.printStackTrace();
                  }
                }
              }
            });
    Thread.sleep(1000000);
  }
  /**
   * Initializes the connection by creating a packet reader and writer and opening a XMPP stream to
   * the server.
   *
   * @throws XMPPException if establishing a connection to the server fails.
   */
  private void initConnection() throws XMPPException {
    PacketReader packetReader = this.packetReader;
    PacketWriter packetWriter = this.packetWriter;
    boolean isFirstInitialization = packetReader == null || packetWriter == null;
    usingCompression = false;

    // Set the reader and writer instance variables
    initReaderAndWriter();

    try {
      if (isFirstInitialization) {
        this.packetWriter = packetWriter = new PacketWriter(this);
        this.packetReader = packetReader = new PacketReader(this);

        // If debugging is enabled, we should start the thread that will listen for
        // all packets and then log them.
        if (config.isDebuggerEnabled()) {
          addPacketListener(debugger.getReaderListener(), null);
          if (debugger.getWriterListener() != null) {
            addPacketSendingListener(debugger.getWriterListener(), null);
          }
        }
      } else {
        packetWriter.init();
        packetReader.init();
      }

      // Start the packet writer. This will open a XMPP stream to the server
      packetWriter.startup();
      // Start the packet reader. The startup() method will block until we
      // get an opening stream packet back from server.
      packetReader.startup();

      // Make note of the fact that we're now connected.
      connected = true;

      // Start keep alive process (after TLS was negotiated - if available)
      packetWriter.startKeepAliveProcess();

      if (isFirstInitialization) {
        // Notify listeners that a new connection has been established
        for (ConnectionCreationListener listener : getConnectionCreationListeners()) {
          listener.connectionCreated(this);
        }
      } else if (!wasAuthenticated) {
        packetReader.notifyReconnection();
      }

    } catch (XMPPException ex) {
      // An exception occurred in setting up the connection. Make sure we shut down the
      // readers and writers and close the socket.

      if (packetWriter != null) {
        try {
          packetWriter.shutdown();
        } catch (Throwable ignore) {
          /* ignore */
        }
        this.packetWriter = null;
      }
      if (packetReader != null) {
        try {
          packetReader.shutdown();
        } catch (Throwable ignore) {
          /* ignore */
        }
        this.packetReader = null;
      }
      if (reader != null) {
        try {
          reader.close();
        } catch (Throwable ignore) {
          /* ignore */
        }
        reader = null;
      }
      if (writer != null) {
        try {
          writer.close();
        } catch (Throwable ignore) {
          /* ignore */
        }
        writer = null;
      }
      if (socket != null) {
        try {
          socket.close();
        } catch (Exception e) {
          /* ignore */
        }
        socket = null;
      }
      this.setWasAuthenticated(authenticated);
      chatManager = null;
      authenticated = false;
      connected = false;

      throw ex; // Everything stoppped. Now throw the exception.
    }
  }
Esempio n. 10
0
  @Override
  public synchronized void login(String username, String password, String resource)
      throws XMPPException {
    if (!isConnected()) {
      throw new IllegalStateException("Not connected to server.");
    }
    if (authenticated) {
      throw new IllegalStateException("Already logged in to server.");
    }
    // Do partial version of nameprep on the username.
    username = username.toLowerCase().trim();

    // Pause keep alive process while authentication and compression is in
    // progress
    packetWriter.stopKeepAliveProcess();

    String response;
    if (config.isSASLAuthenticationEnabled()
        && saslAuthentication.hasNonAnonymousAuthentication()) {
      // Authenticate using SASL
      if (password != null) {
        response = saslAuthentication.authenticate(username, password, resource);
      } else {
        response = saslAuthentication.authenticate(username, resource, config.getCallbackHandler());
      }
    } else {
      // Authenticate using Non-SASL
      response = new NonSASLAuthentication(this).authenticate(username, password, resource);
    }

    // Set the user.
    if (response != null) {
      this.user = response;
      // Update the serviceName with the one returned by the server
      config.setServiceName(StringUtils.parseServer(response));
    } else {
      this.user = username + "@" + getServiceName();
      if (resource != null) {
        this.user += "/" + resource;
      }
    }

    // If compression is enabled then request the server to use stream compression
    if (config.isCompressionEnabled()) {
      useCompression();
    }

    // Resume keep alive process (after authentication and compression was
    // complited)
    packetWriter.resumeKeepAliveProcess();

    // Indicate that we're now authenticated.
    authenticated = true;
    anonymous = false;

    if (config.isRosterLoadedAtLogin()) {
      // Create the roster if it is not a reconnection or roster already
      // created by getRoster()
      if (this.roster == null) {
        if (rosterStorage == null) {
          this.roster = new Roster(this);
        } else {
          this.roster = new Roster(this, rosterStorage);
        }
      }
      this.roster.reload();
    }

    // Set presence to online.
    if (config.isSendPresence()) {
      packetWriter.sendPacket(new Presence(Presence.Type.available));
    }

    // Stores the authentication for future reconnection
    config.setLoginInfo(username, password, resource);

    // If debugging is enabled, change the the debug window title to include the
    // name we are now logged-in as.
    // If DEBUG_ENABLED was set to true AFTER the connection was created the debugger
    // will be null
    if (config.isDebuggerEnabled() && debugger != null) {
      debugger.userHasLogged(user);
    }
  }
Esempio n. 11
0
 /**
  * Returns whether connection with server is alive.
  *
  * @return <code>false</code> if timeout occur.
  */
 @Override
 public boolean isAlive() {
   PacketWriter packetWriter = this.packetWriter;
   return packetWriter == null || packetWriter.isAlive();
 }