Java 类org.jivesoftware.smack.XMPPException 实例源码

项目:VASSAL-src    文件:JabberClient.java   
public void init() throws XMPPException {
  new TrackRooms().addTo(conn);
  new TrackStatus(getMonitorRoomJID().toLowerCase()).addTo(conn);
  new ListenForChat().addTo(conn);
  monitorRoom = new MultiUserChat(conn, getMonitorRoomJID());
  monitorRoom.addMessageListener(this);
  monitorRoom.addParticipantStatusListener(this);
  monitorRoom.join(StringUtils.parseName(conn.getUser()));
  try {
    // This is necessary to create the room if it doesn't already exist
    monitorRoom.sendConfigurationForm(new Form(Form.TYPE_SUBMIT));
  }
  catch (XMPPException ex) {
    // 403 code means the room already exists and user is not an owner
    if (ex.getXMPPError().getCode() != 403) {
      throw ex;
    }
  }
  sendStatus(me);
}
项目:VASSAL-src    文件:JabberClient.java   
public void process(Packet packet) {
  if (roomResponseFilter.accept(packet)) {
    final DiscoverItems result = (DiscoverItems) packet;
    final JabberPlayer player = playerMgr.getPlayer(packet.getFrom());
    // Collect the entityID for each returned item
    for (Iterator<DiscoverItems.Item> items = result.getItems(); items.hasNext();) {
      final String roomJID = items.next().getEntityID();
      final JabberRoom room = roomMgr.getRoomByJID(JabberClient.this, roomJID);
      try {
       room.setInfo(MultiUserChat.getRoomInfo(JabberClient.this
            .getConnection(), roomJID));
      }
      catch (XMPPException e) {
        // Ignore Error
      }
      if (!roomJID.equals(monitorRoom.getRoom())) {
        player.join(roomMgr.getRoomByJID(JabberClient.this, roomJID));
      }
    }
    fireRoomsUpdated();
  }
  else if (newPlayerFilter.accept(packet)) {
    sendRoomQuery(getAbsolutePlayerJID(packet.getFrom()));
  }
}
项目:VASSAL-src    文件:JabberRoom.java   
public synchronized JabberRoom getRoomByJID(JabberClient client, String jid, String defaultName) {
  if (jid == null) {
    return null;
  }
  JabberRoom newRoom = jidToRoom.get(jid);
  if (newRoom == null) {
    String roomName = defaultName == null ? "" : defaultName; //$NON-NLS-1$
    RoomInfo info = null;
    try {
      info = MultiUserChat.getRoomInfo(client.getConnection(), jid);
    }
    // FIXME: review error message
    catch (XMPPException e) {
      e.printStackTrace();
    }
    newRoom = new JabberRoom(roomName, jid, info, client);
    jidToRoom.put(jid, newRoom);
  }
  return newRoom;
}
项目:SmackStudy    文件:XMPPUtil.java   
/**
 * 注册用户
 * @param xmppConnection
 * @param userName
 * @param password
 * @param attributes
 * @return
 */
public static boolean regist(XMPPConnection xmppConnection,String userName,String password,Map<String,String> attributes){
    AccountManager accountManager=xmppConnection.getAccountManager();
    try {
        if(attributes!=null){
            accountManager.createAccount(userName, password, attributes);
        }
        else{
            accountManager.createAccount(userName, password);
        }
        return true;
    } catch (XMPPException e) {
        e.printStackTrace();
        return false;
    }
}
项目:SmackStudy    文件:XMPPUtil.java   
/**
 * 登录
 * @param userName
 * @param password
 * @return
 */
public static XMPPConnection login(String userName,String password){
    XMPPConnection xmppConnection = createXMPPConnection();
    if (xmppConnection != null) {
        try {
            if (!xmppConnection.isConnected()) {
                xmppConnection.connect();
            }
            xmppConnection.login(userName, password);
        } catch (XMPPException e) {
            e.printStackTrace();
            xmppConnection = null;
        }
    }
    return xmppConnection;
}
项目:SmackStudy    文件:XMPPUtil.java   
/**
 * 查询用户
 * @param xmppConnection
 * @param userName
 * @return
 * @throws XMPPException
 */
public static List<HashMap<String, String>> searchUsers(XMPPConnection xmppConnection,String userName) {
    List<HashMap<String, String>> results = new ArrayList<HashMap<String, String>>();
    try {
        UserSearchManager usm = new UserSearchManager(xmppConnection);
        Form searchForm = usm.getSearchForm(xmppConnection.getServiceName());
        Form answerForm = searchForm.createAnswerForm();
        answerForm.setAnswer("userAccount", true);
        answerForm.setAnswer("userPhote", userName);
        ReportedData data = usm.getSearchResults(answerForm, "search" + xmppConnection.getServiceName());
        Iterator<ReportedData.Row> it = data.getRows();
        while (it.hasNext()) {
            HashMap<String, String> user = new HashMap<String, String>();
            ReportedData.Row row = it.next();
            user.put("userAccount", row.getValues("userAccount").next().toString());
            user.put("userPhote", row.getValues("userPhote").next().toString());
            results.add(user);
        }
    } catch (XMPPException e) {
        e.printStackTrace();
    }
    return results;
}
项目:SmackStudy    文件:XMPPUtil.java   
/**
 * 加入聊天室
 * @param xmppConnection
 * @param roomName
 * @param password
 * @return
 */
public static  MultiUserChat joinMultiUserChat(XMPPConnection xmppConnection,String roomName,String password,PacketListener packetListener){
    try {
        // 使用XMPPConnection创建一个MultiUserChat窗口
        MultiUserChat muc = new MultiUserChat(xmppConnection, roomName+ "@conference." + xmppConnection.getServiceName());
        // 聊天室服务将会决定要接受的历史记录数量
        DiscussionHistory history = new DiscussionHistory();
        history.setMaxChars(0);
        // 用户加入聊天室
        muc.join(xmppConnection.getUser(), password, history, SmackConfiguration.getPacketReplyTimeout());
        if(packetListener!=null){
            muc.addMessageListener(packetListener);
        }
        return muc;
    } catch (XMPPException e) {
        e.printStackTrace();
        return null;
    }
}
项目:SmackStudy    文件:XMPPUtil.java   
/**
 * 注册用户
 * @param xmppConnection
 * @param userName
 * @param password
 * @param attributes
 * @return
 */
public static boolean regist(XMPPConnection xmppConnection, String userName, String password, Map<String, String> attributes) {
    AccountManager accountManager = xmppConnection.getAccountManager();
    try {
        if (attributes != null) {
            accountManager.createAccount(userName, password, attributes);
        } else {
            accountManager.createAccount(userName, password);
        }
        return true;
    } catch (XMPPException e) {
        Log.e("regist", e.getMessage());
        e.printStackTrace();
        return false;
    }
}
项目:SmackStudy    文件:XMPPUtil.java   
/**
 * 查询用户
 * @param xmppConnection
 * @param userName
 * @return
 * @throws XMPPException
 */
public static List<HashMap<String, String>> searchUsers(XMPPConnection xmppConnection, String userName) {
    List<HashMap<String, String>> results = new ArrayList<HashMap<String, String>>();
    try {
        UserSearchManager usm = new UserSearchManager(xmppConnection);
        Form searchForm = usm.getSearchForm(xmppConnection.getServiceName());
        Form answerForm = searchForm.createAnswerForm();
        answerForm.setAnswer("userAccount", true);
        answerForm.setAnswer("userPhote", userName);
        ReportedData data = usm.getSearchResults(answerForm, "search" + xmppConnection.getServiceName());
        Iterator<ReportedData.Row> it = data.getRows();
        while (it.hasNext()) {
            HashMap<String, String> user = new HashMap<String, String>();
            ReportedData.Row row = it.next();
            user.put("userAccount", row.getValues("userAccount").next().toString());
            user.put("userPhote", row.getValues("userPhote").next().toString());
            results.add(user);
        }
    } catch (XMPPException e) {
        Log.e("searchUsers", e.getMessage());
        e.printStackTrace();
    }
    return results;
}
项目:SmackStudy    文件:XMPPUtil.java   
/**
 * 获取用户的所有聊天室
 * @param xmppConnection
 * @return
 */
public static List<HostedRoom>  getHostRooms(XMPPConnection xmppConnection){
    List<HostedRoom> roominfos = new ArrayList<HostedRoom>();
    try {
        new ServiceDiscoveryManager(xmppConnection);
        Collection<HostedRoom> hostrooms = MultiUserChat.getHostedRooms(xmppConnection,xmppConnection.getServiceName());
        for (HostedRoom entry : hostrooms) {
            roominfos.add(entry);
            Log.i("room", "名字:" + entry.getName() + " - ID:" + entry.getJid());
        }
        Log.i("room", "服务会议数量:" + roominfos.size());
    } catch (XMPPException e) {
        Log.e("getHostRooms",e.getMessage());
        e.printStackTrace();
    }
    return roominfos;
}
项目:SmackStudy    文件:XMPPUtil.java   
/**
 * 加入聊天室
 * @param xmppConnection
 * @param roomName
 * @param password
 * @param packetListener 消息监听器
 * @return
 */
public static  MultiUserChat joinMultiUserChat(XMPPConnection xmppConnection,String roomName,String password,PacketListener packetListener){
    try {
        // 使用XMPPConnection创建一个MultiUserChat窗口
        MultiUserChat muc = new MultiUserChat(xmppConnection, roomName+ "@conference." + xmppConnection.getServiceName());
        // 聊天室服务将会决定要接受的历史记录数量
        DiscussionHistory history = new DiscussionHistory();
        history.setMaxChars(0);
        // history.setSince(new Date());
        // 用户加入聊天室
        muc.join(xmppConnection.getUser(), password, history, SmackConfiguration.getPacketReplyTimeout());
        Log.i("MultiUserChat", "会议室【"+roomName+"】加入成功........");
        if(packetListener!=null){
            muc.addMessageListener(packetListener);
        }
        return muc;
    } catch (XMPPException e) {
        Log.e("MultiUserChat", "会议室【"+roomName+"】加入失败........");
        e.printStackTrace();
        return null;
    }
}
项目:xmpp    文件:XmppTool.java   
/**
 * ��¼
 * 
 * @param user
 * @param password
 */
public static void login(String user, String password) {

    if (connection == null) {
        init();
    }
    try {
        /** �û���½���û��������� */
        connection.login(user, password);
    } catch (XMPPException e) {
        e.printStackTrace();
    }
    /** ��ȡ��ǰ��½�û� */
    fail("User:", connection.getUser());
    addGroup(connection.getRoster(), "�ҵĺ���");
    addGroup(connection.getRoster(), "������");
    System.out.println("OK");

}
项目:xmpp    文件:XmppTool.java   
/**
 * 登录
 *
 * @param name
 * @param pwd
 * @return
 */
public boolean login(String name, String pwd, Context context) {

    try {
        this.context = context;
        // SASLAuthentication.supportSASLMechanism("PLAIN", 0);
        con.login(name.toLowerCase(), pwd);
        // getMessage();//获取离线消息
        int status = SharedPreferencesUtil.getInt(context, "status", name + "status");
        setPresence(status);//设置状态,默认为在线状态
        return true;
    } catch (XMPPException e) {
        SLog.e(tag, Log.getStackTraceString(e));
    }
    return false;
}
项目:Smack    文件:OwnerUseCases.java   
public void testPurgeItems() throws XMPPException
{
    LeafNode node = getRandomPubnode(getManager(), true, false);

    node.send(new Item());
    node.send(new Item());
    node.send(new Item());
    node.send(new Item());
    node.send(new Item());

    Collection<? extends Item> items = node.getItems();
    assertTrue(items.size() == 5);

    node.deleteAllItems();
    items = node.getItems();

    // Pubsub service may keep the last notification (in spec), so 0 or 1 may be returned on get items.
    assertTrue(items.size() < 2);
}
项目:xmpp    文件:XmppTool.java   
/**
 * 查找用户
 *
 * @param
 * @param userName
 * @return
 */
public List<XmppUser> searchUsers(String userName) {
    List<XmppUser> list = new ArrayList<XmppUser>();
    UserSearchManager userSearchManager = new UserSearchManager(con);
    try {
        Form searchForm = userSearchManager.getSearchForm("search."
                + con.getServiceName());
        Form answerForm = searchForm.createAnswerForm();
        answerForm.setAnswer("Username", true);
        answerForm.setAnswer("Name", true);
        answerForm.setAnswer("search", userName);
        ReportedData data = userSearchManager.getSearchResults(answerForm,
                "search." + con.getServiceName());
        Iterator<ReportedData.Row> rows = data.getRows();
        while (rows.hasNext()) {
            XmppUser user = new XmppUser(null, null);
            ReportedData.Row row = rows.next();
            user.setUserName(row.getValues("Username").next().toString());
            user.setName(row.getValues("Name").next().toString());
            list.add(user);
        }
    } catch (XMPPException e) {
        SLog.e(tag, Log.getStackTraceString(e));
    }
    return list;
}
项目:mangosta-android    文件:BlogPostDetailsActivity.java   
public BlogPostComment sendBlogPostComment(String content, BlogPost blogPost)
        throws SmackException.NotConnectedException, InterruptedException,
        XMPPException.XMPPErrorException, SmackException.NoResponseException {
    Jid jid = XMPPSession.getInstance().getUser().asEntityBareJid();
    String userName = XMPPUtils.fromJIDToUserName(jid.toString());
    Jid pubSubServiceJid = XMPPSession.getInstance().getPubSubService();

    // create stanza
    PublishCommentExtension publishCommentExtension = new PublishCommentExtension(blogPost.getId(), userName, jid, content, new Date());
    PubSub publishCommentPubSub = PubSub.createPubsubPacket(pubSubServiceJid, IQ.Type.set, publishCommentExtension, null);

    // send stanza
    XMPPSession.getInstance().sendStanza(publishCommentPubSub);

    return new BlogPostComment(publishCommentExtension.getId(),
            blogPost.getId(),
            content,
            userName,
            jid.toString(),
            publishCommentExtension.getPublished());
}
项目:Smack    文件:OutgoingFileTransfer.java   
private OutputStream negotiateStream(String fileName, long fileSize,
        String description) throws SmackException, XMPPException {
    // Negotiate the file transfer profile

       if (!updateStatus(Status.initial, Status.negotiating_transfer)) {
           throw new IllegalStateChangeException();
       }
    StreamNegotiator streamNegotiator = negotiator.negotiateOutgoingTransfer(
            getPeer(), streamID, fileName, fileSize, description,
            RESPONSE_TIMEOUT);

       // Negotiate the stream
       if (!updateStatus(Status.negotiating_transfer, Status.negotiating_stream)) {
           throw new IllegalStateChangeException();
       }
    outputStream = streamNegotiator.createOutgoingStream(streamID,
               initiator, getPeer());

       if (!updateStatus(Status.negotiating_stream, Status.negotiated)) {
           throw new IllegalStateChangeException();
    }
    return outputStream;
}
项目:Smack    文件:MediaNegotiator.java   
/**
  *  The other side has sent us a content-accept.  The payload types in that message may not match with what
  *  we sent, but XEP-167 says that the other side should retain the order of the payload types we first sent.
  *  
  *  This means we can walk through our list, in order, until we find one from their list that matches.  This
  *  will be the best payload type to use.
  *  
  *  @param jingle
  *  @return the iq
 * @throws NotConnectedException 
  */
private IQ receiveContentAcceptAction(Jingle jingle, JingleDescription description) throws XMPPException, NotConnectedException {
    IQ response = null;
    List<PayloadType> offeredPayloads = new ArrayList<PayloadType>();

    offeredPayloads = description.getAudioPayloadTypesList();
    bestCommonAudioPt = calculateBestCommonAudioPt(offeredPayloads);

    if (bestCommonAudioPt == null) {

        setNegotiatorState(JingleNegotiatorState.FAILED);
        response = session.createJingleError(jingle, JingleError.NEGOTIATION_ERROR);

    } else {

        setNegotiatorState(JingleNegotiatorState.SUCCEEDED);
        triggerMediaEstablished(getBestCommonAudioPt());
        LOGGER.severe("Media choice:" + getBestCommonAudioPt().getName());

        response = session.createAck(jingle);
    }

    return response;
}
项目:mangosta-android    文件:RosterManager.java   
public void removeContact(String jidString)
        throws SmackException.NotLoggedInException, InterruptedException,
        SmackException.NotConnectedException, XMPPException.XMPPErrorException,
        SmackException.NoResponseException, XmppStringprepException {
    Roster roster = Roster.getInstanceFor(XMPPSession.getInstance().getXMPPConnection());
    if (!roster.isLoaded()) {
        roster.reloadAndWait();
    }

    BareJid jid = JidCreate.bareFrom(jidString);
    roster.removeEntry(roster.getEntry(jid));

    Presence presence = new Presence(Presence.Type.unsubscribe);
    presence.setTo(JidCreate.from(jidString));
    XMPPSession.getInstance().sendStanza(presence);
}
项目:mangosta-android    文件:RosterManager.java   
public void addContact(String jidString)
        throws SmackException.NotLoggedInException, InterruptedException,
        SmackException.NotConnectedException, XMPPException.XMPPErrorException,
        SmackException.NoResponseException, XmppStringprepException {
    Roster roster = Roster.getInstanceFor(XMPPSession.getInstance().getXMPPConnection());
    if (!roster.isLoaded()) {
        roster.reloadAndWait();
    }

    BareJid jid = JidCreate.bareFrom(jidString);
    String name = XMPPUtils.fromJIDToUserName(jidString);
    String[] groups = new String[]{"Buddies"};

    roster.createEntry(jid, name, groups);
    roster.sendSubscriptionRequest(jid);
}
项目:Smack    文件:MultiUserChat.java   
/**
 * Returns the reserved room nickname for the user in the room. A user may have a reserved
 * nickname, for example through explicit room registration or database integration. In such
 * cases it may be desirable for the user to discover the reserved nickname before attempting
 * to enter the room.
 *
 * @return the reserved room nickname or <tt>null</tt> if none.
 * @throws SmackException if there was no response from the server.
 */
public String getReservedNickname() throws SmackException {
    try {
        DiscoverInfo result =
            ServiceDiscoveryManager.getInstanceFor(connection).discoverInfo(
                room,
                "x-roomuser-item");
        // Look for an Identity that holds the reserved nickname and return its name
        for (DiscoverInfo.Identity identity : result.getIdentities()) {
            return identity.getName();
        }
    }
    catch (XMPPException e) {
        LOGGER.log(Level.SEVERE, "Error retrieving room nickname", e);
    }
    // If no Identity was found then the user does not have a reserved room nickname
    return null;
}
项目:PracticeCode    文件:XSCHelper.java   
/**
 * 建立与服务器的持久连接 (必须仅能被getConnection()直接调用)
 *
 * @return boolean  成功。如成功连接服务器返回true,否则false
 */
private boolean connectToServer() {
    if (connection == null || !connection.isConnected()) {
        try {


            //配置连接
            XMPPConnection.DEBUG_ENABLED = true;
            ConnectionConfiguration config =
                    new ConnectionConfiguration(HOST, PORT, GROUP);
            config.setReconnectionAllowed(true);
            config.setSendPresence(false);

            //创建并连接
            connection = new XMPPConnection(config);
            connection.connect();
            if(!connection.isConnected())
                throw new XMPPException();
            return connection.isConnected();
        } catch (XMPPException e) {
            e.printStackTrace();
            connection = null;
        }
    }
    return false;
}
项目:PracticeCode    文件:XSCHelper.java   
/**
 * 设置用户头像
 *
 * @param bytes 图像。从图像/图像文件获取到的字节集
 * @return tag  标签。如设置成功标签返回修改时间,设置失败返回null
 */
public String setAvatar(byte[] bytes) {
    String tag;

    //确认网络状态
    if(getConnection() == null){
        return null;
    }
    //确认获取名片
    VCard card = getVCard();
    if(card == null){
        return null;
    }
    //开始获取信息
    try {
        //创建图像的唯一标识
        tag = System.currentTimeMillis() + UserInfoBasic.account;
        card.setAvatar(bytes);
        card.setField(AVATAG, tag);
        card.save(getConnection());
    } catch (XMPPException e) {
        tag = null;
    }

    return tag;
}
项目:Smack    文件:LastActivityManagerTest.java   
/**
 * This is a test to check if a LastActivity request for last logged out
 * lapsed time is answered and correct
 */
public void testLastLoggedOut() {
    TCPConnection conn0 = getConnection(0);

    LastActivity lastActivity = null;
    try {
        lastActivity = LastActivityManager.getLastActivity(conn0, getBareJID(1));
    } catch (XMPPException e) {
        e.printStackTrace();
        fail("An error occurred requesting the Last Activity");
    }

    assertNotNull("No last activity packet", lastActivity);
       assertTrue("The last activity idle time should be 0 since the user is logged in: " +
               lastActivity.getIdleTime(), lastActivity.getIdleTime() == 0);
   }
项目:PracticeCode    文件:XSCHelper.java   
/**
 * 设置基础信息
 *
 * @param password 可null。非空则更改登录密码为password
 * @param nickName 可null。非空则更改昵称为nickName
 */
public void setUserBasicData(String password, String nickName) {
    try {
        if(getConnection() == null || !getConnection().isAuthenticated())
            return;

        if (password != null) {
            getConnection().getAccountManager().changePassword(password);
        }

        VCard card = getVCard();
        if(nickName != null && card != null){
            card.setNickName(nickName);
            card.save(getConnection());
        }
    } catch (XMPPException e) {
        e.printStackTrace();
    }
}
项目:PracticeCode    文件:XSCHelper.java   
/**
 * 设置进阶信息
 *
 * @param map 以String为键、String为值存储的键值对
 */
public void setUserEnhancedData(LinkedHashMap<String, String> map) {
    //如果没有网络连接直接返回
    if(getConnection() == null)
        return;

    try {
        VCard card = getVCard();
        if (card != null) {
            for(Map.Entry<String, String> en : map.entrySet())
                card.setField(en.getKey(), en.getValue());
            card.save(getConnection());
        }
    } catch (XMPPException e) {
        e.printStackTrace();
    }
}
项目:lider    文件:XMPPClientImpl.java   
/**
 * Send file to provided JID via a SOCKS5 Bytestream session (XEP-0065).
 * 
 * @param file
 * @param jid
 * @throws SmackException
 * @throws InterruptedException
 * @throws IOException
 * @throws XMPPException
 */
public void sendFile(byte[] file, String jid)
        throws XMPPException, IOException, InterruptedException, SmackException {
    String jidFinal = getFullJid(jid);
    jidFinal += "/receiver";
    Socks5BytestreamManager bytestreamManager = Socks5BytestreamManager.getBytestreamManager(connection);
    OutputStream outputStream = null;
    try {
        Socks5BytestreamSession session = bytestreamManager.establishSession(jidFinal);
        outputStream = session.getOutputStream();
        outputStream.write(file);
        outputStream.flush();
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
}
项目:fcmxmppserver    文件:EntryPoint.java   
public static void main(String[] args) {
    final String fcmProjectSenderId = args[0];
    final String fcmServerKey = args[1];
    final String toRegId = args[2];

    CcsClient ccsClient = CcsClient.prepareClient(fcmProjectSenderId, fcmServerKey, true);

    try {
        ccsClient.connect();
    } catch (XMPPException e) {
        logger.log(Level.SEVERE, "Error trying to connect.", e);
    }

    // Send a sample downstream message to a device
    String messageId = Util.getUniqueMessageId();
    Map<String, String> dataPayload = new HashMap<String, String>();
    dataPayload.put(Util.PAYLOAD_ATTRIBUTE_MESSAGE, "This is the simple sample message");
    CcsOutMessage message = new CcsOutMessage(toRegId, messageId, dataPayload);
    String jsonRequest = MessageHelper.createJsonOutMessage(message);
    ccsClient.send(jsonRequest);
}
项目:Smack    文件:MediaNegotiator.java   
/**
     * Process the ACK of our list of codecs (our offer).
     */
    private Jingle receiveResult(IQ iq) throws XMPPException {
        Jingle response = null;

//        if (!remoteAudioPts.isEmpty()) {
//            // Calculate the best common codec
//            bestCommonAudioPt = calculateBestCommonAudioPt(remoteAudioPts);
//
//            // and send an accept if we havee an agreement...
//            if (bestCommonAudioPt != null) {
//                response = createAcceptMessage();
//            } else {
//                throw new JingleException(JingleError.NO_COMMON_PAYLOAD);
//            }
//        }
        return response;
    }
项目:AyoSunny    文件:AddFriendActivity.java   
void showDialog(final String toUser){
    Builder bd=new Builder(AddFriendActivity.this);
    bd.setItems(new String[] {"添加为好友"}, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface arg0, int arg1) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Roster roster=QQApplication.xmppConnection.getRoster();
                        XmppUtil.addGroup(roster, "我的好友");//先默认创建一个分组
                        XmppUtil.addUsers(roster,toUser+"@"+QQApplication.xmppConnection.getServiceName(), toUser,"我的好友");
                        //注意消息的协议格式 =》接收者卍发送者卍消息类型卍消息内容卍发送时间
                        String message=toUser+Const.SPLIT+I+Const.SPLIT+Const.MSG_TYPE_ADD_FRIEND+Const.SPLIT+"你好"+Const.SPLIT+new SimpleDateFormat("MM-dd HH:mm").format(new Date());
                        XmppUtil.sendMessage(QQApplication.xmppConnection, message,toUser);
                        sendInviteUser=toUser;
                        mHandler.sendEmptyMessage(2);
                    } catch (XMPPException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    });
    bd.create().show();
}
项目:AyoSunny    文件:ChatActivity.java   
/**
 * 执行发送消息 文本类型
 * @param content
 */
void sendMsgLocation(String content){
    Msg msg=getChatInfoTo(content,Const.MSG_TYPE_LOCATION);
    msg.setMsgId(msgDao.insert(msg));
    listMsg.add(msg);
    offset=listMsg.size();
    mLvAdapter.notifyDataSetChanged();
    final String message=YOU+Const.SPLIT+I+Const.SPLIT+Const.MSG_TYPE_LOCATION+Const.SPLIT+content+Const.SPLIT+sd.format(new Date());
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                XmppUtil.sendMessage(QQApplication.xmppConnection, message, YOU);
            } catch (XMPPException e) {
                e.printStackTrace();
                Looper.prepare();
                ToastUtil.showShortToast(ChatActivity.this, "发送失败");
                Looper.loop();
            }
        }
    }).start();
    updateSession(Const.MSG_TYPE_TEXT,"[位置]");
}
项目:Camel    文件:XmppEndpoint.java   
public String resolveRoom(XMPPConnection connection) throws XMPPException, SmackException {
    ObjectHelper.notEmpty(room, "room");

    if (room.indexOf('@', 0) != -1) {
        return room;
    }

    Iterator<String> iterator = MultiUserChat.getServiceNames(connection).iterator();
    if (!iterator.hasNext()) {
        throw new XMPPErrorException("Cannot find Multi User Chat service",
                                     new XMPPError(new XMPPError.Condition("Cannot find Multi User Chat service on connection: " + getConnectionMessage(connection))));
    }

    String chatServer = iterator.next();
    LOG.debug("Detected chat server: {}", chatServer);

    return room + "@" + chatServer;
}
项目:Smack    文件:XMPPTCPConnection.java   
@Override
public synchronized void loginAnonymously() throws XMPPException, SmackException, IOException {
    // Wait with SASL auth until the SASL mechanisms have been received
    saslFeatureReceived.checkIfSuccessOrWaitOrThrow();

    if (saslAuthentication.hasAnonymousAuthentication()) {
        saslAuthentication.authenticateAnonymously();
    }
    else {
        throw new SmackException("No anonymous SASL authentication mechanism available");
    }

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

    bindResourceAndEstablishSession(null);

    afterSuccessfulLogin(false);
}
项目:Smack    文件:ICEResolver.java   
public void initialize() throws XMPPException {
    if (!isResolving() && !isResolved()) {
        LOGGER.fine("Initialized");

        // Negotiation with a STUN server for a set of interfaces is quite slow, but the results
        // never change over then instance of a JVM.  To increase connection performance considerably
        // we now cache established/initialized negotiators for each STUN server, so that subsequent uses
        // of the STUN server are much, much faster.
        if (negociatorsMap.get(server) == null) {
            ICENegociator iceNegociator = new ICENegociator(server, port, (short) 1);
            negociatorsMap.put(server, iceNegociator);

            // gather candidates
            iceNegociator.gatherCandidateAddresses();
            // priorize candidates
            iceNegociator.prioritizeCandidates();
        }

    }
    this.setInitialized();
}
项目:Smack    文件:PrivacyTest.java   
/**
 * Check when a client denies the use of a default list.
 */
public void testDenyDefaultList() {
    try {
        PrivacyListManager privacyManager = PrivacyListManager.getInstanceFor(getConnection(0));
        PrivacyClient client = new PrivacyClient(privacyManager);
        privacyManager.addListener(client);

        privacyManager.declineDefaultList();

        Thread.sleep(500);

        try {
            // The list should not exist and an error will be raised
            privacyManager.getDefaultList();
        } catch (XMPPException xmppException) {
            assertEquals(404, xmppException.getXMPPError().getCode());
        }

    assertEquals(null, null);
     } catch (Exception e) {
         e.printStackTrace();
         fail(e.getMessage());
     }
}
项目:Smack    文件:PrivacyTest.java   
/**
 * Check when a client denies the use of the active list.
 */
public void testDenyActiveList() {
    try {
        PrivacyListManager privacyManager = PrivacyListManager.getInstanceFor(getConnection(0));
        PrivacyClient client = new PrivacyClient(privacyManager);
        privacyManager.addListener(client);

        privacyManager.declineActiveList();

        Thread.sleep(500);

        try {
            // The list should not exist and an error will be raised
            privacyManager.getActiveList();
        } catch (XMPPException xmppException) {
            assertEquals(404, xmppException.getXMPPError().getCode());
        }

        assertEquals(null, null);
        } catch (Exception e) {
            e.printStackTrace();
            fail(e.getMessage());
        }
}
项目:Smack    文件:TestEvents.java   
public void testCreateAndGetNode() throws Exception
{
    String nodeId = "MyTestNode";
    PubSubManager creatorMgr = new PubSubManager(getConnection(0), getService());

    LeafNode creatorNode = null;
    try
    {
        creatorNode = (LeafNode)creatorMgr.getNode(nodeId);
    }
    catch (XMPPException e)
    {
        if (e.getXMPPError().getType() == Type.CANCEL && e.getXMPPError().getCondition().equals("item-not-found"))
            creatorNode = creatorMgr.createNode(nodeId);
        else
            throw e;
    }

    PubSubManager subMgr = new PubSubManager(getConnection(1), getService());
    LeafNode subNode = (LeafNode)subMgr.getNode(nodeId);

    assertNotNull(subNode);
}
项目:Smack    文件:InBandBytestreamTest.java   
/**
 * Target should respond with not-acceptable error if no listeners for incoming In-Band
 * Bytestream requests are registered.
 * 
 * @throws XMPPException should not happen
 */
public void testRespondWithErrorOnInBandBytestreamRequest() throws XMPPException {
    XMPPConnection targetConnection = getConnection(0);

    XMPPConnection initiatorConnection = getConnection(1);

    Open open = new Open("sessionID", 1024);
    open.setFrom(initiatorConnection.getUser());
    open.setTo(targetConnection.getUser());

    PacketCollector collector = initiatorConnection.createPacketCollector(new PacketIDFilter(
                    open.getStanzaId()));
    initiatorConnection.sendStanza(open);
    Packet result = collector.nextResult();

    assertNotNull(result.getError());
    assertEquals(XMPPError.Condition.no_acceptable.toString(), result.getError().getCondition());

}
项目:Smack    文件:InBandBytestreamManagerTest.java   
/**
 * Invoking {@link InBandBytestreamManager#establishSession(String)} should
 * throw an exception if the given target does not support in-band
 * bytestream.
 * @throws SmackException 
 * @throws XMPPException 
 */
@Test
public void shouldFailIfTargetDoesNotSupportIBB() throws SmackException, XMPPException {
    InBandBytestreamManager byteStreamManager = InBandBytestreamManager.getByteStreamManager(connection);

    try {
        XMPPError xmppError = new XMPPError(
                        XMPPError.Condition.feature_not_implemented);
        IQ errorIQ = IBBPacketUtils.createErrorIQ(targetJID, initiatorJID, xmppError);
        protocol.addResponse(errorIQ);

        // start In-Band Bytestream
        byteStreamManager.establishSession(targetJID);

        fail("exception should be thrown");
    }
    catch (XMPPErrorException e) {
        assertEquals(XMPPError.Condition.feature_not_implemented,
                        e.getXMPPError().getCondition());
    }

}
项目:Smack    文件:Socks5ByteStreamTest.java   
/**
 * Target should respond with not-acceptable error if no listeners for incoming Socks5
 * bytestream requests are registered.
 * 
 * @throws XMPPException should not happen
 */
public void testRespondWithErrorOnSocks5BytestreamRequest() throws XMPPException {
    XMPPConnection targetConnection = getConnection(0);

    XMPPConnection initiatorConnection = getConnection(1);

    Bytestream bytestreamInitiation = Socks5PacketUtils.createBytestreamInitiation(
                    initiatorConnection.getUser(), targetConnection.getUser(), "session_id");
    bytestreamInitiation.addStreamHost("proxy.localhost", "127.0.0.1", 7777);

    PacketCollector collector = initiatorConnection.createPacketCollector(new PacketIDFilter(
                    bytestreamInitiation.getStanzaId()));
    initiatorConnection.sendStanza(bytestreamInitiation);
    Packet result = collector.nextResult();

    assertNotNull(result.getError());
    assertEquals(XMPPError.Condition.no_acceptable.toString(), result.getError().getCondition());

}