/** @param error null if connection is closed by user */
 void logoutImpl(Exception error) {
   synchronized (this) {
     if (isLoggedIn()) {
       loggedIn.set(false);
       LOG.infof(
           "disconnecting from {0} at {1}:{2} ...",
           connection.getServiceName(), connection.getHost(), connection.getPort());
       connection.disconnect();
       synchronized (friends) {
         friends.clear();
       }
       XMPPConnection.removeConnectionCreationListener(smackConnectionListener);
       connection = null;
       LOG.info("disconnected.");
       connectionMulticaster.broadcast(
           new FriendConnectionEvent(
               XMPPFriendConnectionImpl.this, FriendConnectionEvent.Type.DISCONNECTED, error));
       ChatStateManager.remove(connection);
       if (discoInfoListener != null) {
         discoInfoListener.cleanup();
       }
       if (noSaveFeatureInitializer != null) {
         noSaveFeatureInitializer.cleanup();
       }
       if (idleStatusMonitor != null) {
         idleStatusMonitor.stop();
       }
       if (xmppActivityListener != null) {
         xmppActivitySupport.removeListener(xmppActivityListener);
       }
       featureRegistry.deregisterInitializer(NoSaveFeature.ID);
     }
   }
 }
 private void xmppTalk() {
   System.err.println("INFO: KML-Simulating has started.");
   System.err.println("INFO: Stage 1: Initializing XMPP connection.");
   XMPPConnection connection = this.xmppInitialize();
   if (connection == null) return;
   System.err.println("INFO: Stage 2: Reading and posting roster.");
   this.xmppRosterPost(connection);
   System.err.println("INFO: Stage 3: Walking through coordinates.");
   int interval = 1000;
   try {
     interval = Integer.parseInt(this.interval);
   } catch (NumberFormatException e) {
   }
   for (Coordinate c : this.coordinates) {
     this.xmppLocationUpdate(connection, c.lat, c.lon);
     System.err.println("INFO: Waiting for " + interval + "ms.");
     try {
       LocationJabberer.sleep(interval);
     } catch (InterruptedException e) {
     }
   }
   System.err.println("INFO: Stage 4: Done walking. Shutting down connection.");
   connection.disconnect();
   System.err.println("INFO: Connection closed.");
 }
 void loginImpl() throws FriendException {
   synchronized (this) {
     try {
       loggingIn.set(true);
       connectionMulticaster.broadcast(
           new FriendConnectionEvent(this, FriendConnectionEvent.Type.CONNECTING));
       org.jivesoftware.smack.XMPPConnection.addConnectionCreationListener(
           smackConnectionListener);
       org.jivesoftware.smack.XMPPConnection.DEBUG_ENABLED = configuration.isDebugEnabled();
       connect();
       LOG.infof("connected.");
       LOG.infof(
           "logging in {0} with resource: {1} ...",
           configuration.getUserInputLocalID(), configuration.getResource());
       connection.login(
           configuration.getUserInputLocalID(),
           configuration.getPassword(),
           configuration.getResource());
       LOG.infof("logged in.");
       loggedIn.set(true);
       loggingIn.set(false);
       connectionMulticaster.broadcast(
           new FriendConnectionEvent(this, FriendConnectionEvent.Type.CONNECTED));
     } catch (org.jivesoftware.smack.XMPPException e) {
       handleLoginError(e);
       throw new FriendException(e);
     } catch (RuntimeException e) {
       handleLoginError(e);
       throw e;
     }
   }
 }
Exemple #4
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;
    }
  }
Exemple #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);
  }
Exemple #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();
     }
   }
 }
Exemple #7
0
 /**
  * 注册
  *
  * @param account 注册帐号
  * @param password 注册密码
  * @return 1、注册成功 0、服务器没有返回结果2、这个账号已经存在3、注册失败
  */
 public String regist(String account, String password) {
   if (connection == null) return "0";
   Registration reg = new Registration();
   reg.setType(IQ.Type.SET);
   reg.setTo(connection.getServiceName());
   reg.setUsername(account); // 注意这里createAccount注册时,参数是username,不是jid,是“@”前面的部分。
   reg.setPassword(password);
   reg.addAttribute("android", "geolo_createUser_android"); // 这边addAttribute不能为空,否则出错。
   PacketFilter filter =
       new AndFilter(new PacketIDFilter(reg.getPacketID()), new PacketTypeFilter(IQ.class));
   PacketCollector collector = connection.createPacketCollector(filter);
   connection.sendPacket(reg);
   IQ result = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
   // Stop queuing results
   collector.cancel(); // 停止请求results(是否成功的结果)
   if (result == null) {
     Log.e("Regist", "No response from server.");
     return "0";
   } else if (result.getType() == IQ.Type.RESULT) {
     return "1";
   } else { // if (result.getType() == IQ.Type.ERROR)
     if (result.getError().toString().equalsIgnoreCase("conflict(409)")) {
       Log.e("Regist", "IQ.Type.ERROR: " + result.getError().toString());
       return "2";
     } else {
       Log.e("Regist", "IQ.Type.ERROR: " + result.getError().toString());
       return "3";
     }
   }
 }
  /**
   * 获取服务器上所有会议室
   *
   * @return
   * @throws org.jivesoftware.smack.XMPPException
   */
  public static List<FriendRooms> getConferenceRoom(ImConnection talkConnection)
      throws XMPPException {
    if (talkConnection == null) return null;
    XMPPConnection connection = talkConnection.getXMPPConnection();
    if (connection == null) return null;
    List<FriendRooms> list = new ArrayList<FriendRooms>();
    new ServiceDiscoveryManager(connection);
    if (!MultiUserChat.getHostedRooms(connection, connection.getServiceName()).isEmpty()) {
      for (HostedRoom k : MultiUserChat.getHostedRooms(connection, connection.getServiceName())) {

        for (HostedRoom j : MultiUserChat.getHostedRooms(connection, k.getJid())) {
          RoomInfo info2 = MultiUserChat.getRoomInfo(connection, j.getJid());
          if (j.getJid().indexOf("@") > 0) {
            FriendRooms friendrooms = new FriendRooms();
            friendrooms.setName(j.getName()); // 聊天室的名称
            friendrooms.setJid(j.getJid()); // 聊天室JID
            friendrooms.setOccupants(info2.getOccupantsCount()); // 聊天室中占有者数量
            friendrooms.setDescription(info2.getDescription()); // 聊天室的描述
            friendrooms.setSubject(info2.getSubject()); // 聊天室的主题
            list.add(friendrooms);
          }
        }
      }
    }
    return list;
  }
  /** Creates a destination for a service that receives XMPP messages. */
  public Destination getDestination(EndpointInfo endpointInfo) throws IOException {
    // The node name is the full name of the service.
    String nodeName = endpointInfo.getService().getName().toString();
    pepProvider.registerPEPParserExtension(nodeName, soapProvider);

    PEPDestination dest = new PEPDestination(endpointInfo);

    try {
      XMPPConnection conn = destinationConnectionFactory.login(endpointInfo);

      // Advertise interest in receiving information.
      ServiceDiscoveryManager disco = ServiceDiscoveryManager.getInstanceFor(conn);
      disco.addFeature(nodeName + "+notify");

      // Create destination.
      dest.setXmppConnection(conn);
      conn.addPacketListener(
          dest, new PacketExtensionFilter("event", "http://jabber.org/protocol/pubsub#event"));

    } catch (XMPPException e) {
      throw new IOException(e);
    }

    return dest;
  }
  /**
   * Creates a last activity manager to response last activity requests.
   *
   * @param connection The XMPPConnection that the last activity requests will use.
   */
  private LastActivityManager(XMPPConnection connection) {
    this.connection = connection;

    // Listen to all the sent messages to reset the idle time on each one
    connection.addPacketWriterListener(
        new PacketListener() {
          public void processPacket(Packet packet) {
            resetIdleTime();
          }
        },
        null);

    // Register a listener for a last activity query
    connection.addPacketListener(
        new PacketListener() {

          public void processPacket(Packet packet) {
            LastActivity message = new LastActivity();
            message.setType(IQ.Type.RESULT);
            message.setTo(packet.getFrom());
            message.setFrom(packet.getTo());
            message.setPacketID(packet.getPacketID());
            message.setLastActivity(getIdleTime());

            LastActivityManager.this.connection.sendPacket(message);
          }
        },
        new AndFilter(new IQTypeFilter(IQ.Type.GET), new PacketTypeFilter(LastActivity.class)));
  }
 @Override
 public void run() {
   if (xmppManager.isConnected() && !xmppManager.isAuthenticated() && !xmppManager.isRunning()) {
     XMPPConnection connection = xmppManager.getConnection();
     try {
       xmppManager.setRunning(true);
       xmppManager
           .getConnection()
           .login(xmppManager.getUsername(), xmppManager.getPassword(), XMPP_RESOURCE_NAME);
       Log.d(LOG_TAG, "Loggedn in successfully");
       PacketFilter packetFilter = new PacketTypeFilter(NotificationIQ.class);
       // packet listener
       PacketListener packetListener = xmppManager.getNotificationPacketListener();
       connection.addPacketListener(packetListener, packetFilter);
       callback.onSuccess();
     } catch (Exception e) {
       Log.e(LOG_TAG, "LoginTask.call()... other error");
       Log.e(LOG_TAG, "Failed to login to xmpp server. Caused by: " + e.getMessage(), e);
       callback.onFailed("LoginTask.call()... other error");
     } finally {
       xmppManager.setRunning(false);
     }
   } else {
     Log.w(LOG_TAG, "XMPP is not connected or is running or is authenticated");
     callback.onFailed("XMPP is not connected or is running or is authenticated");
   }
 }
Exemple #12
0
  private void syncUsers() {
    for (RosterEntry entry : conn.getRoster().getEntries()) {
      getBuddyManager()
          .storeBuddy(
              new XMPPBuddy(
                  getBuddyManager(), entry.getUser(), entry.getName(), entry.getGroups(), entry));
      // Facebook does not support presence probes in their XMPP implementation. See
      // http://developers.facebook.com/docs/chat#features
      if (!TransportType.facebook.equals(getTransport().getType())) {
        // ProbePacket probe = new ProbePacket(this.getJID()+"/"+xmppResource, entry.getUser());
        ProbePacket probe = new ProbePacket(null, entry.getUser());
        Log.debug("XMPP: Sending the following probe packet: " + probe.toXML());
        try {
          conn.sendPacket(probe);
        } catch (IllegalStateException e) {
          Log.debug("XMPP: Not connected while trying to send probe.");
        }
      }
    }

    try {
      getTransport().syncLegacyRoster(getJID(), getBuddyManager().getBuddies());
    } catch (UserNotFoundException ex) {
      Log.error("XMPP: User not found while syncing legacy roster: ", ex);
    }

    getBuddyManager().activate();

    // lets repoll the roster since smack seems to get out of sync...
    // we'll let the roster listener take care of this though.
    conn.getRoster().reload();
  }
  @Override
  public void disconnected(boolean onError) {
    final XMPPConnection connection = myFacade.getConnection();

    LOG.info("Jabber disconnected: " + connection.getUser());
    connection.removePacketListener(mySubscribeListener);
    mySubscribeListener = null;
    connection.removePacketListener(myMessageListener);
    myMessageListener = null;

    final Roster roster = connection.getRoster();
    if (roster != null) {
      roster.removeRosterListener(myRosterListener);
    }
    myRosterListener = null;

    myIDEtalkUsers.clear();
    myUser2Presence.clear();
    myUser2Thread.clear();

    if (onError && reconnectEnabledAndNotStarted()) {
      LOG.warn(getMsg("jabber.server.was.disconnected", myReconnectTimeout / 1000));
      myReconnectProcess = myIdeFacade.runOnPooledThread(new MyReconnectRunnable());
    }
  }
  /**
   * Returns an Iterator with all the offline <tt>Messages</tt> of the user. The returned offline
   * messages will not be deleted from the server. Use {@link #deleteMessages(java.util.List)} to
   * delete the messages.
   *
   * @return an Iterator with all the offline <tt>Messages</tt> of the user.
   * @throws XMPPException If the user is not allowed to make this request or the server does not
   *     support offline message retrieval.
   */
  public Iterator getMessages() throws XMPPException {
    List messages = new ArrayList();
    OfflineMessageRequest request = new OfflineMessageRequest();
    request.setFetch(true);
    // Filter packets looking for an answer from the server.
    PacketFilter responseFilter = new PacketIDFilter(request.getPacketID());
    PacketCollector response = connection.createPacketCollector(responseFilter);
    // Filter offline messages that were requested by this request
    PacketCollector messageCollector = connection.createPacketCollector(packetFilter);
    // Send the retrieval request to the server.
    connection.sendPacket(request);
    // Wait up to a certain number of seconds for a reply.
    IQ answer = (IQ) response.nextResult(SmackConfiguration.getPacketReplyTimeout());
    // Stop queuing results
    response.cancel();

    if (answer == null) {
      throw new XMPPException("No response from server.");
    } else if (answer.getError() != null) {
      throw new XMPPException(answer.getError());
    }

    // Collect the received offline messages
    Message message =
        (Message) messageCollector.nextResult(SmackConfiguration.getPacketReplyTimeout());
    while (message != null) {
      messages.add(message);
      message = (Message) messageCollector.nextResult(SmackConfiguration.getPacketReplyTimeout());
    }
    // Stop queuing offline messages
    messageCollector.cancel();
    return messages.iterator();
  }
Exemple #15
0
  /**
   * @see net.sf.kraken.session.TransportSession#sendChatState(org.xmpp.packet.JID,
   *     net.sf.kraken.type.ChatStateType)
   */
  @Override
  public void sendChatState(JID jid, ChatStateType chatState) {
    final Presence presence = conn.getRoster().getPresence(jid.toString());
    if (presence == null || presence.getType().equals(Presence.Type.unavailable)) {
      // don't send chat state to contacts that are offline.
      return;
    }
    Chat chat = conn.getChatManager().createChat(getTransport().convertJIDToID(jid), listener);
    try {
      ChatState state = ChatState.active;
      switch (chatState) {
        case active:
          state = ChatState.active;
          break;
        case composing:
          state = ChatState.composing;
          break;
        case paused:
          state = ChatState.paused;
          break;
        case inactive:
          state = ChatState.inactive;
          break;
        case gone:
          state = ChatState.gone;
          break;
      }

      Message message = new Message();
      message.addExtension(new ChatStateExtension(state));
      chat.sendMessage(message);
    } catch (XMPPException e) {
      // Ignore
    }
  }
Exemple #16
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);
      }
    }
  }
  /** Loads streamhost address and ports from the proxies on the local server. */
  private void initStreamHosts() {
    List<Bytestream.StreamHost> streamHosts = new ArrayList<Bytestream.StreamHost>();
    Iterator it = proxies.iterator();
    IQ query;
    PacketCollector collector;
    Bytestream response;
    while (it.hasNext()) {
      String jid = it.next().toString();
      query =
          new IQ() {
            public String getChildElementXML() {
              return "<query xmlns=\"http://jabber.org/protocol/bytestreams\"/>";
            }
          };
      query.setType(IQ.Type.GET);
      query.setTo(jid);

      collector = connection.createPacketCollector(new PacketIDFilter(query.getPacketID()));
      connection.sendPacket(query);

      response = (Bytestream) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
      if (response != null) {
        streamHosts.addAll(response.getStreamHosts());
      }
      collector.cancel();
    }
    this.streamHosts = streamHosts;
  }
 @Override
 public void run() {
   Log.i(LOGTAG, "ConnectTask.run()...");
   XmppManager xmppManager = getXmppManager();
   if (!xmppManager.isConnected()) {
     ConnectionConfiguration connCfg =
         new ConnectionConfiguration(xmppManager.getXmppHost(), xmppManager.getXmppPort());
     connCfg.setSecurityMode(SecurityMode.required);
     connCfg.setSASLAuthenticationEnabled(false);
     connCfg.setCompressionEnabled(false);
     XMPPConnection connection = new XMPPConnection(connCfg);
     xmppManager.setConnection(connection);
     try {
       connection.connect();
       ProviderManager.getInstance()
           .addIQProvider(
               "notification", Constants.NOTIFICATION_NAMESPACE, new NotificationIQProvider());
       Log.i(LOGTAG, "XMPP connected successfully");
       xmppManager.getContext().sendBroadcast(new Intent(Constants.ACTION_CONNECT_SUCCESS));
     } catch (XMPPException e) {
       Log.e(LOGTAG, "XMPP connection failed", e);
       xmppManager.getContext().sendBroadcast(new Intent(Constants.ACTION_CONNECT_FAIL));
     }
     xmppManager.runTask();
   } else {
     Log.i(LOGTAG, "XMPP connected already");
     xmppManager.runTask();
   }
 }
Exemple #19
0
  public void retrieveVcard() {

    ConnectionConfiguration conf =
        new ConnectionConfiguration(
            ConnectionManager.HOST, ConnectionManager.PORT, ConnectionManager.SERVICE);
    connection = new XMPPConnection(conf);
    ProviderManager.getInstance().addIQProvider("vCard", "vcard-temp", new VCardProvider());

    try {
      connection.connect();

      Log.i("success", "successful connection to server");
    } catch (XMPPException e) {
      Log.e("unable to connect to the server", e.toString());
    }

    try {

      connection.login("admin", "xenomorph");
      gettingCard(connection);

    } catch (XMPPException ex) {
      Log.e("error logging in as user ", ex.toString());
    }
  }
  /**
   * Returns the discovered items of a given XMPP entity addressed by its JID and note attribute.
   * Use this message only when trying to query information which is not directly addressable.
   *
   * @param entityID the address of the XMPP entity.
   * @param node the attribute that supplements the 'jid' attribute.
   * @return the discovered items.
   * @throws XMPPException if the operation failed for some reason.
   */
  public DiscoverItems discoverItems(String entityID, String node) throws XMPPException {
    // Discover the entity's items
    DiscoverItems disco = new DiscoverItems();
    disco.setType(IQ.Type.GET);
    disco.setTo(entityID);
    disco.setNode(node);

    // Create a packet collector to listen for a response.
    PacketCollector collector =
        connection.createPacketCollector(new PacketIDFilter(disco.getPacketID()));

    connection.sendPacket(disco);

    // Wait up to 5 seconds for a result.
    IQ result = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
    // Stop queuing results
    collector.cancel();
    if (result == null) {
      throw new XMPPException("No response from the server.");
    }
    if (result.getType() == IQ.Type.ERROR) {
      throw new XMPPException(result.getError());
    }
    return (DiscoverItems) result;
  }
Exemple #21
0
 /** Template method to perform any work when destroying the connectoe */
 protected void disposeConnector() {
   for (Iterator iterator = connCache.keySet().iterator(); iterator.hasNext(); ) {
     UMOEndpointURI uri = (UMOEndpointURI) iterator.next();
     XMPPConnection conn = (XMPPConnection) connCache.remove(uri);
     conn.close();
   }
 }
 @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;
   }
 }
Exemple #23
0
 public boolean deleteUser(String jid) {
   try {
     connection.getRoster().removeEntry(connection.getRoster().getEntry(jid));
   } catch (XMPPException e) {
     e.printStackTrace();
   }
   return false;
 }
 /**
  * Returns real full jid, that was assigned while login.
  *
  * @return <code>null</code> if connection is not established.
  */
 public String getRealJid() {
   ConnectionThread connectionThread = getConnectionThread();
   if (connectionThread == null) return null;
   XMPPConnection xmppConnection = connectionThread.getXMPPConnection();
   if (xmppConnection == null) return null;
   String user = xmppConnection.getUser();
   if (user == null) return null;
   return user;
 }
 /** Disconnects from chatserver and releases all resources. */
 public void disconnect() {
   connection.getRoster().removeRosterListener(leagueRosterListener);
   try {
     connection.disconnect();
   } catch (final NotConnectedException e) {
     e.printStackTrace();
   }
   stop = true;
 }
 private static MultiUserChat getMultiUserChat(ImConnection talkConnection, String roomName)
     throws XMPPException {
   if (talkConnection == null) return null;
   XMPPConnection connection = talkConnection.getXMPPConnection();
   if (connection == null) return null;
   MultiUserChat muc =
       new MultiUserChat(connection, roomName + "@conference." + connection.getServiceName());
   return muc;
 }
  /**
   * 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;
  }
  @Override
  public void run() {
    Log.i(LOGTAG, "RegisterTask.run()...");
    final XmppManager xmppManager = getXmppManager();
    if (!xmppManager.isRegistered()) {
      String uuid = Util.getDeviceUUID(xmppManager.getContext());
      final String newUsername = uuid;
      final String newPassword = uuid;
      Registration registration = new Registration();
      PacketFilter packetFilter =
          new AndFilter(
              new PacketIDFilter(registration.getPacketID()), new PacketTypeFilter(IQ.class));
      PacketListener packetListener =
          new PacketListener() {
            public void processPacket(Packet packet) {
              Log.d("RegisterTask.PacketListener", "processPacket().....");
              Log.d("RegisterTask.PacketListener", "packet=" + packet.toXML());

              if (packet instanceof IQ) {
                IQ response = (IQ) packet;
                if (response.getType() == IQ.Type.ERROR) {
                  if (!response.getError().toString().contains("409")) {
                    Log.e(
                        LOGTAG,
                        "Unknown error while registering XMPP account! "
                            + response.getError().getCondition());
                  }
                } else if (response.getType() == IQ.Type.RESULT) {
                  xmppManager.setUsername(newUsername);
                  xmppManager.setPassword(newPassword);
                  Log.d(LOGTAG, "username="******"password="******"Account registered successfully");
                  xmppManager.runTask();
                }
              }
            }
          };
      XMPPConnection connection = xmppManager.getConnection();
      connection.addPacketListener(packetListener, packetFilter);
      registration.setType(IQ.Type.SET);
      registration.addAttribute("username", newUsername);
      registration.addAttribute("password", newPassword);
      connection.sendPacket(registration);
    } else {
      Log.i(LOGTAG, "Account registered already");
      xmppManager.runTask();
    }
  }
 public synchronized void enableAutomaticReconnection() {
   if (!this.automaticReconnectEnabled) {
     XMPPConnection xMPPConnection = (XMPPConnection) this.weakRefConnection.get();
     if (xMPPConnection == null) {
       throw new IllegalStateException("Connection instance no longer available");
     }
     xMPPConnection.addConnectionListener(this.connectionListener);
     this.automaticReconnectEnabled = true;
   }
 }
Exemple #30
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;
 }