@Override
 public boolean connect() throws RemoteException {
   if (mAdaptee.isConnected()) return true;
   else {
     try {
       mAdaptee.connect();
       mAdaptee.addConnectionListener(mConListener);
       return true;
     } catch (XMPPException e) {
       Log.e(TAG, "Error while connecting", e);
       try {
         // TODO NIKITA DOES SOME SHIT !!! Fix this monstruosity
         String str =
             mService
                 .getResources()
                 .getString(
                     mService
                         .getResources()
                         .getIdentifier(
                             e.getXMPPError().getCondition().replace("-", "_"),
                             "string",
                             "com.beem.project.beem"));
         mErrorMsg = str;
       } catch (NullPointerException e2) {
         if (!"".equals(e.getMessage())) mErrorMsg = e.getMessage();
         else mErrorMsg = e.toString();
       }
     }
     return false;
   }
 }
Пример #2
0
  @Test
  public void shouldDisconnectXMPPOnDestroy() {
    startService();
    xmppService.onDestroy();

    assertFalse(xmppConnection.isConnected());
  }
Пример #3
0
  /*
   * (non-Javadoc)
   *
   * @see
   * fr.univartois.ili.fsnet.commons.talk.ITalk#createAccount(java.lang.String
   * , java.lang.String, java.util.Map)
   */
  @Override
  public boolean createAccount(String userName, String password, Map<String, String> map) {
    {
      if (!connection.isConnected()) {
        try {
          connection.connect();
        } catch (XMPPException e3) {

          Logger.getAnonymousLogger().log(Level.SEVERE, "", e3);
        }
      }

      try {
        Map<String, String> finalMap = map;
        if (finalMap == null) {
          finalMap = new HashMap<String, String>();
        }
        accountManager.createAccount(userName, password, finalMap);

        connection.disconnect();
        // Thread.sleep(6000);
        connection.connect();
        connection.login(userName, password);

        return true;
      } catch (XMPPException e2) {
        Logger.getAnonymousLogger().log(Level.SEVERE, "", e2);
      }
      return false;
    }
  }
Пример #4
0
  /**
   * Prepares Spark for shutting down by first calling all {@link MainWindowListener}s and setting
   * the Agent to be offline.
   *
   * @param sendStatus true if Spark should send a presence with a status message.
   */
  public void logout(boolean sendStatus) {
    final XMPPConnection con = SparkManager.getConnection();
    String status = null;

    if (con.isConnected() && sendStatus) {
      final InputTextAreaDialog inputTextDialog = new InputTextAreaDialog();
      status =
          inputTextDialog.getInput(
              Res.getString("title.status.message"),
              Res.getString("message.current.status"),
              SparkRes.getImageIcon(SparkRes.USER1_MESSAGE_24x24),
              this);
    }

    if (status != null || !sendStatus) {
      // Notify all MainWindowListeners
      try {
        // Set auto-login to false;
        SettingsManager.getLocalPreferences().setAutoLogin(false);
        SettingsManager.saveSettings();

        fireWindowShutdown();
        setVisible(false);
      } finally {
        closeConnectionAndInvoke(status);
      }
    }
  }
Пример #5
0
  /*
   * (non-Javadoc)
   *
   * @see
   * fr.univartois.ili.fsnet.commons.talk.ITalk#initConnexion(java.lang.String
   * , int, java.lang.String, java.lang.String, java.util.Map)
   */
  @Override
  public void initConnexion(
      String xmppServer, int port, String login, String pssword, Map<String, String> map)
      throws TalkException {
    config = new ConnectionConfiguration(xmppServer, port);

    connection = new XMPPConnection(config);
    try {
      if (!connection.isConnected()) {
        connection.connect();
      }

      accountManager = connection.getAccountManager();
      connection.login(login, pssword);

    } catch (XMPPException e) {
      if ((e.getLocalizedMessage().contains("authentication failed")
              || e.getLocalizedMessage().contains("SASL authentication"))
          && accountManager.supportsAccountCreation()) {
        createAccount(login, pssword, map);

      } else {
        Logger.getAnonymousLogger().log(Level.SEVERE, "", e);
      }
    }

    /* It is only at that moment where the Listener is correctly initialized */
    ChatStateManager.getInstance(connection);
  }
Пример #6
0
 @Override
 public void run() {
   if (connection != null && connection.isConnected()) {
     disconnect = true;
     Ping ping = new Ping();
     ping.setFrom(ApplicationUtil.getXmppConnectionUserName(PreferencesUtil.getMyId()));
     try {
       connection.sendPacket(ping);
     } catch (Exception e) {
       clearTimer();
       // Application.getNotificationManager().startNotificationService();
     }
     connection.addPacketListener(
         new PacketListener() {
           public void processPacket(Packet packet) {
             disconnect = false;
           }
         },
         new IQTypeFilter(Type.RESULT));
     try {
       Thread.sleep(PERIOD);
     } catch (InterruptedException e) {
     }
     if (disconnect) {
       LaijiaoliuApp.getNotificationManager().startNotificationService();
       clearTimer();
     }
   }
 }
Пример #7
0
 @Test
 public void shouldNotAttemptReconnectionIfHandlerHasQueuedAttempts() {
   Robolectric.pauseMainLooper();
   xmppReconnectionHandler.reconnectAfter(xmppCommunication, 1000);
   startService();
   Robolectric.idleMainLooper(500);
   assertFalse(xmppConnection.isConnected());
 }
  /**
   * Connects to the server and logs you in. If the server is unavailable then it will retry after a
   * certain time period. It will not return unless the connection is successful.
   *
   * <p>Note: add/set all listeners before logging in, otherwise some offline messages can get lost.
   * <br>
   * Note: Garena servers use different credentials to log in. {@link GarenaLogin}
   *
   * @param username Username of your account
   * @param password Password of your account
   * @param replaceLeague True will disconnect you account from the League of Legends client. False
   *     allows you to have another connection open next to the official connection in the League of
   *     Legends client.
   * @return true if login was succesful, false otherwise
   * @see GarenaLogin Logging in on Garena servers
   */
  public boolean login(String username, String password, boolean replaceLeague) {
    int attempt = 0;

    // Wait until connection is stable
    while (!connection.isConnected()) {
      if (attempt > 0) {
        try {
          Thread.sleep(attempt * 10_000);
        } catch (final InterruptedException e) {
        }
      }
      attempt++;
      try {
        connection.connect();
      } catch (SmackException | IOException | XMPPException e) {
        System.err.println(
            "Failed to connect to \""
                + server.host
                + "\". Retrying in "
                + (attempt * 10)
                + " seconds.");
      }
    }

    // Login
    server.loginMethod.login(connection, username, password, replaceLeague);

    // Wait for roster to be loaded
    if (connection.isAuthenticated()) {
      new Thread(
              new Runnable() {

                @Override
                public void run() {
                  while (!stop) {
                    try {
                      Thread.sleep(500);
                    } catch (final InterruptedException ignored) {
                    }
                  }
                }
              })
          .start();
      final long startTime = System.currentTimeMillis();
      while (!leagueRosterListener.isLoaded()
          && (System.currentTimeMillis() - startTime) < 60_000) {
        try {
          Thread.sleep(50);
        } catch (final InterruptedException e) {
        }
      }
      loaded = true;
      return true;
    }
    return false;
  }
 /**
  * Unwind upon login error - broadcast login failed, remove conn creation listener from smack, set
  * conn to null, disconnect if need be, etc
  *
  * @param e Exception which occurred during login
  */
 private synchronized void handleLoginError(Exception e) {
   loggingIn.set(false);
   connectionMulticaster.broadcast(
       new FriendConnectionEvent(this, FriendConnectionEvent.Type.CONNECT_FAILED, e));
   if (connection != null && connection.isConnected()) {
     connection.disconnect();
   }
   org.jivesoftware.smack.XMPPConnection.removeConnectionCreationListener(smackConnectionListener);
   connection = null;
 }
Пример #10
0
 public boolean renameFriend(String userID, String name) {
   if (sConnection != null && sConnection.isConnected()) {
     Roster roster = sConnection.getRoster();
     if (roster.contains(userID)) {
       RosterEntry entry = roster.getEntry(userID);
       entry.setName(name);
     }
   }
   return false;
 }
  @Override
  public boolean login() throws RemoteException {
    if (mAdaptee.isAuthenticated()) return true;
    if (!mAdaptee.isConnected()) return false;
    try {

      this.initFeatures(); // pour declarer les features xmpp qu'on
      // supporte

      PacketFilter filter =
          new PacketFilter() {

            @Override
            public boolean accept(Packet packet) {
              if (packet instanceof Presence) {
                Presence pres = (Presence) packet;
                if (pres.getType() == Presence.Type.subscribe) return true;
              }
              return false;
            }
          };

      mAdaptee.addPacketListener(mSubscribePacketListener, filter);

      filter = new PacketTypeFilter(PingExtension.class);
      mAdaptee.addPacketListener(mPingListener, filter);

      mAdaptee.login(mLogin, mPassword, mResource);
      mUserInfo = new UserInfo(mAdaptee.getUser());

      mChatManager = new BeemChatManager(mAdaptee.getChatManager(), mService, mAdaptee.getRoster());
      // nikita: I commented this line because of the logs provided in
      // http://www.beem-project.com/issues/321
      // Also, since the privacylistmanager isn't finished and used, it will be safer to not
      // initialize it
      // mPrivacyListManager = new
      // PrivacyListManagerAdapter(PrivacyListManager.getInstanceFor(mAdaptee));
      mService.initJingle(mAdaptee);
      discoverServerFeatures();

      mRoster = new RosterAdapter(mAdaptee.getRoster(), mService, mAvatarManager);
      mApplication.setConnected(true);
      int mode = mPref.getInt(BeemApplication.STATUS_KEY, 0);
      String status = mPref.getString(BeemApplication.STATUS_TEXT_KEY, "");
      changeStatus(mode, status);
      return true;
    } catch (XMPPException e) {
      Log.e(TAG, "Error while connecting", e);
      mErrorMsg = mService.getString(R.string.error_login_authentication);
      return false;
    }
  }
Пример #12
0
 /**
  * Check if manager is logged in to xmpp server.
  *
  * @return true if logged in, false otherwise
  */
 private void login() {
   try {
     if (xmpp.isConnected()) {
       LOG.debug("XMPP Manager logging in");
       xmpp.login(xmppUser, xmppPassword, XMPP_RESOURCE);
       rooms.clear();
     } else {
       LOG.debug("XMPP Manager unable to login: Not connected to XMPP server");
     }
   } catch (Throwable e) {
     LOG.error("XMPP Manager unable to login: ", e);
   }
 }
Пример #13
0
 /**
  * Closes the current connection and restarts Spark.
  *
  * @param reason the reason for logging out. This can be if user gave no reason.
  */
 public void closeConnectionAndInvoke(String reason) {
   final XMPPConnection con = SparkManager.getConnection();
   if (con.isConnected()) {
     if (reason != null) {
       Presence byePresence = new Presence(Presence.Type.unavailable, reason, -1, null);
       con.disconnect(byePresence);
     } else {
       con.disconnect();
     }
   }
   if (!restartApplicationWithScript()) {
     restartApplicationWithJava();
   }
 }
Пример #14
0
 public boolean removeFriend(String userID) {
   if (sConnection != null && sConnection.isConnected()) {
     Roster roster = sConnection.getRoster();
     if (roster.contains(userID)) {
       try {
         roster.removeEntry(roster.getEntry(userID));
         return true;
       } catch (XMPPException e) {
         System.err.println("Error in removing friend " + e.getMessage());
       }
     }
   }
   return false;
 }
Пример #15
0
  /**
   * Prepares Spark for shutting down by first calling all {@link MainWindowListener}s and setting
   * the Agent to be offline.
   */
  public void shutdown() {
    final XMPPConnection con = SparkManager.getConnection();

    if (con.isConnected()) {
      // Send disconnect.
      con.disconnect();
    }

    // Notify all MainWindowListeners
    try {
      fireWindowShutdown();
    } catch (Exception ex) {
      Log.error(ex);
    }
    // Close application.
    if (!Default.getBoolean("DISABLE_EXIT")) System.exit(1);
  }
  /** {@inheritDoc} */
  @Override
  public final void connectAsync() throws RemoteException {
    if (mAdaptee.isConnected() || mAdaptee.isAuthenticated()) return;
    Thread t =
        new Thread(
            new Runnable() {

              @Override
              public void run() {
                try {
                  connectSync();
                } catch (RemoteException e) {
                  Log.e(TAG, "Error while connecting asynchronously", e);
                }
              }
            });
    t.start();
  }
Пример #17
0
  /**
   * Deletes the session agent account, frees all resources and disconnects the XMPP connection.
   *
   * @throws org.jivesoftware.smack.XMPPException
   */
  public void shutdown() throws XMPPException {
    ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(mConnection);

    // ServiceDiscovery (feature) http://rn.inf.tu-dresden.de/mobilis
    try {
      sdm.removeFeature(MobilisManager.discoNamespace);
    } catch (Exception e) {
      MobilisManager.getLogger().warning("Problem with ServiceDiscoveryManager: " + e.getMessage());
    }

    // ServiceDiscovery (info+items) http://rn.inf.tu-dresden.de/mobilis#services
    try {
      sdm.removeNodeInformationProvider(MobilisManager.discoServicesNode);
    } catch (Exception e) {
      MobilisManager.getLogger()
          .warning(
              "Problem with NodeInformationProvider: "
                  + MobilisManager.discoServicesNode
                  + " ("
                  + getIdent()
                  + ") "
                  + e.getMessage());
    }

    for (MobilisService service : mServices) {
      try {
        sdm.removeNodeInformationProvider(service.getNode());
        service.shutdown();
      } catch (Exception e) {
        // TODO Auto-generated catch block
      }
    }

    if ((mConnection != null) && mConnection.isConnected()) {
      mConnection.removeConnectionListener(this);
      mConnection.disconnect();
    }
    mConnection = null;

    // logging
    MobilisManager.getLogger().info("Mobilis Agent (" + getIdent() + ") shut down.");
  }
Пример #18
0
 private void connectToServer() {
   try {
     LOG.debug("Attempting vanilla XMPP Connection to {}:{}", xmppServer, xmppPort);
     xmpp.connect();
     if (xmpp.isConnected()) {
       LOG.debug("XMPP Manager successfully connected");
       // Following requires a later version of the library
       if (xmpp.isSecureConnection())
         LOG.debug("XMPP Manager successfully nogotiated a secure connection");
       if (xmpp.isUsingTLS()) LOG.debug("XMPP Manager successfully nogotiated a TLS connection");
       LOG.debug("XMPP Manager Connected");
       login();
       // Add connection listener
       xmpp.addConnectionListener(conlistener);
     } else {
       LOG.debug("XMPP Manager Not Connected");
     }
   } catch (Throwable e) {
     LOG.error("XMPP Manager unable to connect", e);
   }
 }
Пример #19
0
 private static XMPPConnection establishConnection()
     throws CredentialException, XMPPException, IOException {
   // The browser will send a bunch of requests for photos, and we don't
   // want to hammer the Google Talk servers, so we synchronize to
   // create a single connection.
   synchronized (CONNECTION_LOCK) {
     if (conn != null && conn.isConnected()) {
       return conn;
     }
     final String user = LanternHub.xmppHandler().getLastUserName();
     final String pass = LanternHub.xmppHandler().getLastPass();
     if (StringUtils.isBlank(user)) {
       throw new IOException("No user name!!");
     }
     if (StringUtils.isBlank(user)) {
       throw new IOException("No password!!");
     }
     conn = XmppUtils.simpleGoogleTalkConnection(user, pass, "vcard-connection");
     return conn;
   }
 }
Пример #20
0
 /** 建立XMPP连接 */
 public boolean connect() throws RemoteException {
   // 已经连接
   if (connection.isConnected()) {
     return true;
   } else {
     try {
       // 开始连接
       connection.connect();
       if (connectionListener == null) {
         // 添加一个连接监听器
         connectionListener = new IMClientConnectListener();
       }
       connection.addConnectionListener(connectionListener);
       return true;
     } catch (SmackException e) {
       e.printStackTrace();
     } catch (IOException e) {
       e.printStackTrace();
     } catch (XMPPException e) {
       e.printStackTrace();
     }
   }
   return false;
 }
Пример #21
0
 public boolean isAuthenticated() {
   return connection != null && connection.isConnected() && connection.isAuthenticated();
 }
Пример #22
0
 public boolean isConnected() {
   return connection != null && connection.isConnected();
 }
Пример #23
0
 @Test
 public void shouldConnectXMPPOnStartWithCorrectIntent() {
   startService();
   assertTrue(xmppConnection.isConnected());
 }
Пример #24
0
 public void destroy() {
   if (connection != null && connection.isConnected()) {
     connection.disconnect();
   }
 }
Пример #25
0
 private boolean isReconnectionPossible(XMPPConnection xMPPConnection) {
   return (this.done || xMPPConnection.isConnected() || !isAutomaticReconnectEnabled())
       ? false
       : true;
 }
Пример #26
0
 /** 登陆XMPP服务器 */
 public boolean login() throws RemoteException {
   // 未建立XMPP连接
   if (!connection.isConnected()) {
     return false;
   }
   // 应经登陆过
   if (connection.isAuthenticated()) {
     return true;
   } else {
     // 开始登陆
     try {
       connection.login(account, password, imService.getString(R.string.app_name));
       if (messageListener == null) {
         messageListener = new MessageListener();
       }
       // 添加消息监听器
       connection.addPacketListener(messageListener, new PacketTypeFilter(Message.class));
       Roster roster = connection.getRoster();
       if (rosterListener == null) {
         rosterListener = new IMClientRosterListener();
       }
       // 添加花名册监听器
       roster.addRosterListener(rosterListener);
       // 获取花名册
       if (roster != null && roster.getEntries().size() > 0) {
         Uri uri = null;
         for (RosterEntry entry : roster.getEntries()) {
           // 获取联系人名片信息
           VCard vCard = new VCard();
           vCard.load(connection, entry.getUser());
           // 用户名称
           String userName = StringUtils.parseName(entry.getUser());
           // 用户备注
           String remarks = entry.getName();
           // 通讯录的名称
           String name = "";
           // 名称与备注判断
           if (userName.equals(remarks) && vCard != null) {
             // 使用联系人的昵称
             name = vCard.getNickName();
           } else {
             // 使用备注
             name = remarks;
           }
           if (vCard != null) {
             IM.saveAvatar(vCard.getAvatar(), StringUtils.parseName(entry.getUser()));
           }
           ContentValues values = new ContentValues();
           values.put(ContactsProvider.ContactColumns.ACCOUNT, entry.getUser());
           values.put(ContactsProvider.ContactColumns.NAME, name);
           String sortStr = PinYin.getPinYin(name);
           values.put(ContactsProvider.ContactColumns.SORT, sortStr);
           values.put(
               ContactsProvider.ContactColumns.SECTION,
               sortStr.substring(0, 1).toUpperCase(Locale.ENGLISH));
           // 储存联系人
           if (imService
                   .getContentResolver()
                   .update(
                       ContactsProvider.CONTACT_URI,
                       values,
                       ContactsProvider.ContactColumns.ACCOUNT + " = ?",
                       new String[] {entry.getUser()})
               == 0) {
             uri = imService.getContentResolver().insert(ContactsProvider.CONTACT_URI, values);
           }
         }
         // 发生改变,通知刷新
         if (uri != null) {
           imService.getContentResolver().notifyChange(uri, null);
         }
       }
     } catch (XMPPException e) {
       e.printStackTrace();
     } catch (SmackException e) {
       e.printStackTrace();
     } catch (IOException e) {
       e.printStackTrace();
     }
     return true;
   }
 }
Пример #27
0
 /** 关闭XMPP连接 */
 public boolean disconnect() throws RemoteException {
   if (connection != null && connection.isConnected()) {
     connection.disconnect();
   }
   return true;
 }
 /** {@inheritDoc} */
 @Override
 public boolean disconnect() {
   if (mAdaptee != null && mAdaptee.isConnected()) mAdaptee.disconnect();
   return true;
 }
Пример #29
0
 private boolean isConnected() {
   return con != null && con.isConnected();
 }
Пример #30
0
 @Test
 public void shouldAttemptXmppConnectionOnNetworkChange() {
   Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
   Robolectric.getShadowApplication().sendBroadcast(intent);
   assertTrue(xmppConnection.isConnected());
 }