/** @param packet */
 public void processPacket(Packet packet) {
   PresenceIndicator.getDefault()
       .label
       .setText(
           KenaiUser.getOnlineUserCount() > 0
               ? KenaiUser.getOnlineUserCount() - 1 + ""
               : ""); // NOI18N
   PresenceIndicator.getDefault()
       .label
       .setToolTipText(
           NbBundle.getMessage(
               PresenceIndicator.class,
               "LBL_LoggedIn_Tooltip",
               KenaiUser.getOnlineUserCount() > 0 ? KenaiUser.getOnlineUserCount() - 1 : ""));
   for (MultiUserChat muc :
       KenaiConnection.getDefault(
               KenaiConnection.getKenai(StringUtils.parseBareAddress(packet.getFrom())))
           .getChats()) {
     String chatName = StringUtils.parseName(muc.getRoom());
     assert chatName != null : "muc.getRoom() = " + muc.getRoom(); // NOI18N
     ChatNotifications.getDefault()
         .getMessagingHandle(KenaiConnection.getKenaiProject(muc))
         .setOnlineCount(muc.getOccupantsCount());
   }
 }
 public void updateUser(Presence presence) {
   boolean newUser = true;
   Contact removeC = null;
   for (Contact c : contactList) {
     if (c.getRosterEntry().getUser().equals(StringUtils.parseBareAddress(presence.getFrom()))) {
       newUser = false;
       if (!(presence.isAvailable() || presence.isAway())) {
         removeC = c;
       }
       break;
     }
   }
   if (removeC != null) {
     contactList.remove(removeC);
   }
   if (newUser) {
     RosterEntry re = roster.getEntry(StringUtils.parseBareAddress(presence.getFrom()));
     Contact c = new Contact();
     if (re.getName() == null || re.getName().trim().equals("")) c.setName(re.getUser());
     else c.setName(re.getName());
     c.setStatus(presence.getStatus());
     c.setRosterEntry(re);
     contactList.add(c);
   }
 }
示例#3
0
 /**
  * Creates a new identity for an XMPP entity. 'category' and 'type' are required by <a
  * href="http://xmpp.org/extensions/xep-0030.html#schemas">XEP-30 XML Schemas</a>
  *
  * @param category the entity's category (required as per XEP-30).
  * @param type the entity's type (required as per XEP-30).
  * @param name the entity's name.
  * @param lang the entity's lang.
  */
 public Identity(String category, String type, String name, String lang) {
   this.category = StringUtils.requireNotNullOrEmpty(category, "category cannot be null");
   this.type = StringUtils.requireNotNullOrEmpty(type, "type cannot be null");
   this.key = XmppStringUtils.generateKey(category, type);
   this.name = name;
   this.lang = lang;
 }
  /**
   * @return String - returns a String XML representation of the packet Builds an XLM-style string
   *     representation of the packet
   */
  public String toXML() {
    StringBuilder buf = new StringBuilder();
    buf.append("<ConferencePacket ");
    if (packetIDSet) { // includes only a set Id - not a default
      buf.append("id=\"" + getPacketID() + "\"");
    }
    if (getTo() != null) {
      buf.append(" to=\"").append(StringUtils.escapeForXML(getTo())).append("\"");
    }
    if (getFrom() != null) {
      buf.append(" from=\"").append(StringUtils.escapeForXML(getFrom())).append("\"");
    }
    buf.append(">");
    Collection<String> propertyNames = this.getPropertyNames();

    // write every property and its value to the xml
    for (String propName : propertyNames) {

      if (propName.length() >= 12 && propName.substring(0, 11).equals("participant")) {

        buf.append("\n\t<participant>" + getProperty(propName) + "</participant>");
      } else {
        buf.append("\n\t<" + propName + ">" + getProperty(propName) + "</" + propName + ">");
      }
    }

    buf.append("\n</ConferencePacket>");
    return buf.toString();
  }
示例#5
0
 public String toXML() {
   StringBuilder buf = new StringBuilder();
   buf.append("<iq ");
   if (getPacketID() != null) {
     buf.append("id=\"" + getPacketID() + "\" ");
   }
   if (getTo() != null) {
     buf.append("to=\"").append(StringUtils.escapeForXML(getTo())).append("\" ");
   }
   if (getFrom() != null) {
     buf.append("from=\"").append(StringUtils.escapeForXML(getFrom())).append("\" ");
   }
   if (type == null) {
     buf.append("type=\"get\">");
   } else {
     buf.append("type=\"").append(getType()).append("\">");
   }
   // Add the query section if there is one.
   String queryXML = getChildElementXML();
   if (queryXML != null) {
     buf.append(queryXML);
   }
   // Add the error sub-packet, if there is one.
   XMPPError error = getError();
   if (error != null) {
     buf.append(error.toXML());
   }
   buf.append("</iq>");
   return buf.toString();
 }
示例#6
0
  private void loadHistory() {
    // Add VCard Panel
    final VCardPanel vcardPanel = new VCardPanel(participantJID);

    vcardPanel.setPreferredSize(new Dimension(10, 71));
    vcardPanel.setMaximumSize(new Dimension(1100, 71));
    vcardPanel.setMinimumSize(new Dimension(1100, 71));

    getToolBar()
        .add(
            vcardPanel,
            new GridBagConstraints(
                0,
                1,
                1,
                1,
                1.0,
                0.0,
                GridBagConstraints.NORTHWEST,
                GridBagConstraints.HORIZONTAL,
                new Insets(0, 2, 0, 2),
                0,
                0));

    final LocalPreferences localPreferences = SettingsManager.getLocalPreferences();
    if (!localPreferences.isChatHistoryEnabled()) {
      return;
    }

    if (!localPreferences.isPrevChatHistoryEnabled()) {
      return;
    }

    final String bareJID = StringUtils.parseBareAddress(getParticipantJID());
    final ChatTranscript chatTranscript = ChatTranscripts.getCurrentChatTranscript(bareJID);
    final String personalNickname = SparkManager.getUserManager().getNickname();

    for (HistoryMessage message : chatTranscript.getMessages()) {
      String nickname = SparkManager.getUserManager().getUserNicknameFromJID(message.getFrom());
      String messageBody = message.getBody();
      if (nickname.equals(message.getFrom())) {
        String otherJID = StringUtils.parseBareAddress(message.getFrom());
        String myJID = SparkManager.getSessionManager().getBareAddress();

        if (otherJID.equals(myJID)) {
          nickname = personalNickname;
        } else {
          nickname = StringUtils.parseName(nickname);
        }
      }

      if (ModelUtil.hasLength(messageBody) && messageBody.startsWith("/me ")) {
        messageBody = messageBody.replaceFirst("/me", nickname);
      }

      final Date messageDate = message.getDate();
      getTranscriptWindow().insertHistoryMessage(nickname, messageBody, messageDate);
    }
  }
 @Override
 public void onAvatarChange(
     String from, String avatarId, List<AvatarMetadataExtension.Info> avatarInfos) {
   String jid = StringUtils.parseBareAddress(mUserInfo.getJid());
   String mfrom = StringUtils.parseBareAddress(from);
   if (jid.equalsIgnoreCase(mfrom)) {
     mUserInfo.setAvatarId(avatarId);
   }
 }
 public void userHasLogged(String user) {
   boolean isAnonymous = "".equals(StringUtils.parseName(user));
   String title =
       "Smack Debug Window -- "
           + (isAnonymous ? "" : StringUtils.parseBareAddress(user))
           + "@"
           + connection.getServiceName()
           + ":"
           + connection.getPort();
   title += "/" + StringUtils.parseResource(user);
   frame.setTitle(title);
 }
示例#9
0
 @Override
 protected IQChildElementXmlStringBuilder getIQHoxtChildElementBuilder(
     IQChildElementXmlStringBuilder builder) {
   builder.append(" ");
   builder.append("version='").append(StringUtils.escapeForXML(version)).append("'");
   builder.append(" ");
   builder.append("statusCode='").append(Integer.toString(statusCode)).append("'");
   if (statusMessage != null) {
     builder.append(" ");
     builder.append("statusMessage='").append(StringUtils.escapeForXML(statusMessage)).append("'");
   }
   builder.append(">");
   return builder;
 }
示例#10
0
  /**
   * Represents this <tt>FileElement</tt> in an XML.
   *
   * @see File#toXML()
   */
  @Override
  public String toXML() {
    StringBuilder buffer = new StringBuilder();

    buffer
        .append("<")
        .append(getElementName())
        .append(" xmlns=\"")
        .append(getNamespace())
        .append("\" ");

    if (getName() != null) {
      buffer.append("name=\"").append(StringUtils.escapeForXML(getName())).append("\" ");
    }

    if (getSize() > 0) {
      buffer.append("size=\"").append(getSize()).append("\" ");
    }

    if (getDate() != null) {
      buffer.append("date=\"").append(StringUtils.formatXEP0082Date(this.getDate())).append("\" ");
    }

    if (getHash() != null) {
      buffer.append("hash=\"").append(getHash()).append("\" ");
    }

    if ((this.getDesc() != null && getDesc().length() > 0) || isRanged() || thumbnail != null) {
      buffer.append(">");

      if (getDesc() != null && getDesc().length() > 0) {
        buffer.append("<desc>").append(StringUtils.escapeForXML(getDesc())).append("</desc>");
      }

      if (isRanged()) {
        buffer.append("<range/>");
      }

      if (thumbnail != null) {
        buffer.append(thumbnail.toXML());
      }

      buffer.append("</").append(getElementName()).append(">");
    } else {
      buffer.append("/>");
    }

    return buffer.toString();
  }
示例#11
0
  /**
   * Updates the displayed name for the contact. This method tries to use an alias first. If that's
   * not set, the nickname will be used instead. If that's not set either, the JID of the user will
   * be used.
   */
  protected void setDisplayName() {
    final String displayName = getDisplayName();

    int nickLength = displayName.length();

    LayoutSettings settings = LayoutSettingsManager.getLayoutSettings();
    int windowWidth = settings.getMainWindowWidth();

    if (nickLength > windowWidth) {
      displayNameLabel.setText(
          StringUtils.unescapeNode(displayName).substring(0, windowWidth) + "...");
    } else {
      displayNameLabel.setText(StringUtils.unescapeNode(displayName));
    }
  }
    @Override
    protected Boolean doInBackground(String... params) {
      Log.d(TAG, "Xmpp login task");
      jid = params[0];
      password = params[1];
      Log.d(TAG, "jid " + jid + " server  " + server);

      int port = -1;
      if (params.length > 2) {
        server = params[2];
      }
      if (params.length > 3) {
        if (!TextUtils.isEmpty(params[3])) {
          port = Integer.parseInt(params[3]);
        }
      }
      Connection connection = prepareConnection(jid, server, port);
      try {
        connection.connect();
        AccountManager accountManager = new AccountManager(connection);
        accountManager.createAccount(StringUtils.parseName(jid), password);
      } catch (XMPPException e) {
        Log.e(TAG, "Unable to create account", e);
        exception = e;
        return false;
      } finally {
        connection.disconnect();
      }
      return true;
    }
示例#13
0
  /**
   * Remove records telling what entity caps node a contact has.
   *
   * @param contact the contact
   */
  public void removeContactCapsNode(Contact contact) {
    Caps caps = null;
    String lastRemovedJid = null;

    Iterator<String> iter = userCaps.keySet().iterator();
    while (iter.hasNext()) {
      String jid = iter.next();

      if (StringUtils.parseBareAddress(jid).equals(contact.getAddress())) {
        caps = userCaps.get(jid);
        lastRemovedJid = jid;
        iter.remove();
      }
    }

    // fire only for the last one, at the end the event out
    // of the protocol will be one and for the contact
    if (caps != null) {
      UserCapsNodeListener[] listeners;
      synchronized (userCapsNodeListeners) {
        listeners = userCapsNodeListeners.toArray(NO_USER_CAPS_NODE_LISTENERS);
      }
      if (listeners.length != 0) {
        String nodeVer = caps.getNodeVer();

        for (UserCapsNodeListener listener : listeners)
          listener.userCapsNodeRemoved(lastRemovedJid, nodeVer, false);
      }
    }
  }
示例#14
0
  public void sendMessage(String text) {
    final Message message = new Message();

    if (threadID == null) {
      threadID = StringUtils.randomString(6);
    }
    message.setThread(threadID);

    // Set the body of the message using typedMessage
    message.setBody(text);

    // IF there is no body, just return and do nothing
    if (!ModelUtil.hasLength(text)) {
      return;
    }

    // Fire Message Filters
    SparkManager.getChatManager().filterOutgoingMessage(this, message);

    // Fire Global Filters
    SparkManager.getChatManager().fireGlobalMessageSentListeners(this, message);

    sendMessage(message);

    sendNotification = true;
  }
示例#15
0
 private OnceForThisStanza(XMPPTCPConnection xMPPTCPConnection, Stanza stanza) {
   this.connection = xMPPTCPConnection;
   this.id = stanza.getStanzaId();
   if (StringUtils.isNullOrEmpty(this.id)) {
     throw new IllegalArgumentException("Stanza ID must be set");
   }
 }
示例#16
0
 public void addFriend(String userID) {
   if (sRoster != null) {
     if (!sRoster.contains(userID)) {
       try {
         sRoster.createEntry(userID, StringUtils.parseBareAddress(userID), null);
         retrieveFriendList();
       } catch (XMPPException e) {
         System.err.println("Error in adding friend " + e.getMessage());
       }
     } else {
       RosterEntry rosterEntry = sRoster.getEntry(userID);
       RosterPacket.ItemType type = rosterEntry.getType();
       switch (type) {
         case from:
           requestSubscription(userID, sConnection);
           break;
         case to:
           grantSubscription(userID, sConnection);
           break;
         case none:
           grantSubscription(userID, sConnection);
           requestSubscription(userID, sConnection);
           break;
         case both:
         default:
           break;
       }
     }
   }
 }
示例#17
0
 /**
  * Calculate the ver attribute.
  *
  * @param info The discover info to calculate the ver.
  * @param hashMethod the hash algorithm to use.
  * @return the value of the ver attribute
  * @throws NoSuchAlgorithmException if the hash algorithm is not supported.
  */
 private String calculateVer(DiscoverInfo info, String hashMethod)
     throws NoSuchAlgorithmException {
   StringBuilder s = new StringBuilder();
   for (DiscoverInfo.Identity identity : getSortedIdentity(info)) {
     String c = identity.getCategory();
     if (c != null) s.append(c);
     s.append('/');
     c = identity.getType();
     if (c != null) s.append(c);
     s.append('/');
     // Should add lang but it is not available
     //             c = identity.getType();
     //             if (c != null)
     //                 S.append(c);
     s.append('/');
     c = identity.getName();
     if (c != null) s.append(c);
     s.append('<');
   }
   for (String f : getSortedFeature(info)) {
     s.append(f);
     s.append('<');
   }
   // Should add data form (XEP 0128) but it is not available
   byte[] hash = getHash(hashMethod, s.toString().getBytes());
   return StringUtils.encodeBase64(hash);
 }
  @Override
  protected void onStart() {
    super.onStart();

    if (mKey == null) {
      PersonalKeyRunnable action =
          new PersonalKeyRunnable() {
            public void run(PersonalKey key) {
              mKey = key;
              if (mValidator != null)
                // this will release the waiting lock
                mValidator.setKey(mKey);
            }
          };

      // random passphrase (40 characters!!!!)
      mPassphrase = StringUtils.randomString(40);

      mKeyReceiver = new KeyGeneratedReceiver(mHandler, action);

      IntentFilter filter = new IntentFilter(KeyPairGeneratorService.ACTION_GENERATE);
      lbm.registerReceiver(mKeyReceiver, filter);

      Toast.makeText(this, R.string.msg_generating_keypair, Toast.LENGTH_LONG).show();

      Intent i = new Intent(this, KeyPairGeneratorService.class);
      i.setAction(KeyPairGeneratorService.ACTION_GENERATE);
      startService(i);
    }
  }
示例#19
0
 /**
  * If the given JID is a full JID, take its resource to be the resource we are currently chatting
  * with.
  */
 public void setUserResource(String jid) {
   String bareJid = StringUtils.parseBareAddress(jid);
   if (!jid.equals(bareJid)) {
     setLastKnownResource(jid);
     mRemoteIdFull = jid;
   }
 }
示例#20
0
 private Presence enter$324fb5b(String nickname, long timeout)
     throws NotConnectedException, NoResponseException, XMPPErrorException {
   if (StringUtils.isNullOrEmpty(nickname)) {
     throw new IllegalArgumentException("Nickname must not be null or blank.");
   }
   Presence joinPresence = new Presence(Type.available);
   joinPresence.to = this.room + MqttTopic.TOPIC_LEVEL_SEPARATOR + nickname;
   joinPresence.addExtension(new MUCInitialPresence());
   for (PacketInterceptor interceptPacket : this.presenceInterceptors) {
     interceptPacket.interceptPacket(joinPresence);
   }
   PacketCollector response =
       this.connection.createPacketCollector(
           new AndFilter(
               FromMatchesFilter.createFull(
                   this.room + MqttTopic.TOPIC_LEVEL_SEPARATOR + nickname),
               new PacketTypeFilter(Presence.class)));
   this.connection.sendPacket(joinPresence);
   Presence presence = (Presence) response.nextResultOrThrow(timeout);
   this.nickname = nickname;
   this.joined = true;
   List<String> rooms = (List) joinedRooms.get(this.connection);
   if (rooms == null) {
     rooms = new ArrayList();
     joinedRooms.put(this.connection, rooms);
   }
   rooms.add(this.room);
   return presence;
 }
 @Override
 public void onClick(View v) {
   if (v == createButton) {
     boolean create = true;
     if (!checkUserName()) {
       username.setError(getString(R.string.create_account_err_username));
       create = false;
     }
     if (TextUtils.isEmpty(serverEdit.getText())) {
       serverEdit.setError("Choose a server");
       create = false;
     }
     if (!checkPasswords()) {
       password.setError(getString(R.string.create_account_err_passwords));
       confirmPassword.setError(getString(R.string.create_account_err_passwords));
       create = false;
     }
     if (create) {
       String jid = String.format("%s@%s", username.getText(), serverEdit.getText());
       jid = StringUtils.parseBareAddress(jid);
       String pass = password.getText().toString();
       task = new CreateAccountTask();
       task.execute(jid, pass);
     }
   }
 }
示例#22
0
  private void processOfflineMessages() {
    Log.i(LOG_TAG, "Begin retrieval of offline messages from server");

    OfflineMessageManager offlineMessageManager = new OfflineMessageManager(con);
    try {
      if (!offlineMessageManager.supportsFlexibleRetrieval()) {
        Log.d(LOG_TAG, "Offline messages not supported");
        return;
      }

      List<Message> msgs = offlineMessageManager.getMessages();
      for (Message msg : msgs) {
        Intent intent =
            new Intent(MessageService.ACTION_MESSAGE_RECEIVED, null, context, MessageService.class);
        intent.putExtra(
            MessageService.EXTRA_DATA_NAME_FROM, StringUtils.parseBareAddress(msg.getFrom()));
        intent.putExtra(MessageService.EXTRA_DATA_NAME_MESSAGE_BODY, msg.getBody());

        context.startService(intent);
      }

      offlineMessageManager.deleteMessages();
    } catch (Exception e) {
      Log.e(LOG_TAG, "handle offline messages error ", e);
    }

    Log.i(LOG_TAG, "End of retrieval of offline messages from server");
  }
 public String getChildElementXML() {
   StringBuilder buf = new StringBuilder();
   buf.append("<query xmlns=\"jabber:iq:auth\">");
   if (username != null) {
     if (username.equals("")) {
       buf.append("<username/>");
     } else {
       buf.append("<username>").append(username).append("</username>");
     }
   }
   if (digest != null) {
     if (digest.equals("")) {
       buf.append("<digest/>");
     } else {
       buf.append("<digest>").append(digest).append("</digest>");
     }
   }
   if (password != null && digest == null) {
     if (password.equals("")) {
       buf.append("<password/>");
     } else {
       buf.append("<password>").append(StringUtils.escapeForXML(password)).append("</password>");
     }
   }
   if (resource != null) {
     if (resource.equals("")) {
       buf.append("<resource/>");
     } else {
       buf.append("<resource>").append(resource).append("</resource>");
     }
   }
   buf.append("</query>");
   return buf.toString();
 }
 /**
  * Parse a properties sub-packet. If any errors occur while de-serializing Java object properties,
  * an exception will be printed and not thrown since a thrown exception will shut down the entire
  * connection. ClassCastExceptions will occur when both the sender and receiver of the packet
  * don't have identical versions of the same class.
  *
  * @param parser the XML parser, positioned at the start of a properties sub-packet.
  * @return a map of the properties.
  * @throws Exception if an error occurs while parsing the properties.
  */
 public static Map<String, Object> parseProperties(XmlPullParser parser) throws Exception {
   Map<String, Object> properties = new HashMap<String, Object>();
   while (true) {
     int eventType = parser.next();
     if (eventType == XmlPullParser.START_TAG && parser.getName().equals("property")) {
       // Parse a property
       boolean done = false;
       String name = null;
       String type = null;
       String valueText = null;
       Object value = null;
       while (!done) {
         eventType = parser.next();
         if (eventType == XmlPullParser.START_TAG) {
           String elementName = parser.getName();
           if (elementName.equals("name")) {
             name = parser.nextText();
           } else if (elementName.equals("value")) {
             type = parser.getAttributeValue("", "type");
             valueText = parser.nextText();
           }
         } else if (eventType == XmlPullParser.END_TAG) {
           if (parser.getName().equals("property")) {
             if ("integer".equals(type)) {
               value = Integer.valueOf(valueText);
             } else if ("long".equals(type)) {
               value = Long.valueOf(valueText);
             } else if ("float".equals(type)) {
               value = Float.valueOf(valueText);
             } else if ("double".equals(type)) {
               value = Double.valueOf(valueText);
             } else if ("boolean".equals(type)) {
               value = Boolean.valueOf(valueText);
             } else if ("string".equals(type)) {
               value = valueText;
             } else if ("java-object".equals(type)) {
               try {
                 byte[] bytes = StringUtils.decodeBase64(valueText);
                 ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
                 value = in.readObject();
               } catch (Exception e) {
                 e.printStackTrace();
               }
             }
             if (name != null && value != null) {
               properties.put(name, value);
             }
             done = true;
           }
         }
       }
     } else if (eventType == XmlPullParser.END_TAG) {
       if (parser.getName().equals("properties")) {
         break;
       }
     }
   }
   return properties;
 }
 /**
  * Gets a friend based on his XMPPAddress.
  *
  * @param xmppAddress For example [email protected]
  * @return The corresponding Friend or null if user is not found or he is not a friend of you.
  */
 public Friend getFriendById(String xmppAddress) {
   final RosterEntry entry =
       connection.getRoster().getEntry(StringUtils.parseBareAddress(xmppAddress));
   if (entry != null) {
     return new Friend(this, connection, entry);
   }
   return null;
 }
示例#26
0
 public boolean accept(Stanza stanza) {
   CharSequence stanzaId = stanza.getStanzaId();
   if (StringUtils.isNullOrEmpty(stanzaId) || !this.id.equals(stanzaId)) {
     return false;
   }
   this.connection.removeRequestAckPredicate(this);
   return true;
 }
示例#27
0
 /**
  * @param jid the jid
  * @param interlocutorList the interlocutors
  * @param groupChatList the group chats
  */
 public Participant(
     String jid, List<InterlocutorImpl> interlocutorList, List<InterlocutorImpl> groupChatList) {
   this.jid = jid;
   this.interlocutorList = interlocutorList;
   this.groupChatList = groupChatList;
   this.username = StringUtils.parseName(jid);
   this.hexName = CodingUtils.encodeToHex(this.username);
 }
示例#28
0
 /** 更改用户状态 */
 public void setPresence(int code) {
   if (connection == null) return;
   Presence presence;
   switch (code) {
     case 0:
       presence = new Presence(Presence.Type.available);
       connection.sendPacket(presence);
       Log.v("state", "设置在线");
       break;
     case 1:
       presence = new Presence(Presence.Type.available);
       presence.setMode(Presence.Mode.chat);
       connection.sendPacket(presence);
       Log.v("state", "设置Q我吧");
       System.out.println(presence.toXML());
       break;
     case 2:
       presence = new Presence(Presence.Type.available);
       presence.setMode(Presence.Mode.dnd);
       connection.sendPacket(presence);
       Log.v("state", "设置忙碌");
       System.out.println(presence.toXML());
       break;
     case 3:
       presence = new Presence(Presence.Type.available);
       presence.setMode(Presence.Mode.away);
       connection.sendPacket(presence);
       Log.v("state", "设置离开");
       System.out.println(presence.toXML());
       break;
     case 4:
       Roster roster = connection.getRoster();
       Collection<RosterEntry> entries = roster.getEntries();
       for (RosterEntry entry : entries) {
         presence = new Presence(Presence.Type.unavailable);
         presence.setPacketID(Packet.ID_NOT_AVAILABLE);
         presence.setFrom(connection.getUser());
         presence.setTo(entry.getUser());
         connection.sendPacket(presence);
         System.out.println(presence.toXML());
       }
       // 向同一用户的其他客户端发送隐身状态
       presence = new Presence(Presence.Type.unavailable);
       presence.setPacketID(Packet.ID_NOT_AVAILABLE);
       presence.setFrom(connection.getUser());
       presence.setTo(StringUtils.parseBareAddress(connection.getUser()));
       connection.sendPacket(presence);
       Log.v("state", "设置隐身");
       break;
     case 5:
       presence = new Presence(Presence.Type.unavailable);
       connection.sendPacket(presence);
       Log.v("state", "设置离线");
       break;
     default:
       break;
   }
 }
示例#29
0
  public UserProfile search(String username) throws SmackInvocationException {
    String name = StringUtils.parseName(username);
    String jid = null;
    if (name == null || name.trim().length() == 0) {
      jid = username + "@" + con.getServiceName();
    } else {
      jid = StringUtils.parseBareAddress(username);
    }

    if (vCardHelper == null) {
      return null;
    }

    VCard vCard = vCardHelper.loadVCard(jid);
    String nickname = vCard.getNickName();

    return nickname == null ? null : new UserProfile(jid, vCard);
  }
示例#30
0
  /**
   * The server is challenging the SASL mechanism for the stanza he just sent. Send a response to
   * the server's challenge.
   *
   * @param challengeString a base64 encoded string representing the challenge.
   * @param finalChallenge true if this is the last challenge send by the server within the success
   *     stanza
   * @throws NotConnectedException
   * @throws SmackException
   */
  public final void challengeReceived(String challengeString, boolean finalChallenge)
      throws SmackException, NotConnectedException {
    byte[] challenge = StringUtils.decodeBase64(challengeString);
    byte response[] = evaluateChallenge(challenge);
    if (finalChallenge) {
      return;
    }

    Response responseStanza;
    if (response == null) {
      responseStanza = new Response();
    } else {
      responseStanza = new Response(StringUtils.encodeBase64(response, false));
    }

    // Send the authentication to the server
    connection.sendPacket(responseStanza);
  }