Java源码示例:org.jivesoftware.smackx.Form

示例1
/**
 * 查找用户
 *
 * @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;
}
 
示例2
/**
 * Tests creating a new "Instant Room".
 */
public void testCreateInstantRoom() {
    MultiUserChat muc = new MultiUserChat(getConnection(0), room);

    try {
        // Create the room
        muc.create("testbot");

        // Send an empty room configuration form which indicates that we want
        // an instant room
        muc.sendConfigurationForm(new Form(Form.TYPE_SUBMIT));

        // Destroy the new room
        muc.destroy("The room has almost no activity...", null);
    }
    catch (XMPPException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
 
示例3
private void makeRoomModerated() throws XMPPException {
    // User1 (which is the room owner) converts the instant room into a moderated room
    Form form = muc.getConfigurationForm();
    Form answerForm = form.createAnswerForm();
    answerForm.setAnswer("muc#roomconfig_moderatedroom", true);
    answerForm.setAnswer("muc#roomconfig_whois", Arrays.asList("moderators"));
    // Keep the room owner
    try {
        List<String> owners = new ArrayList<String>();
        owners.add(getBareJID(0));
        answerForm.setAnswer("muc#roomconfig_roomowners", owners);
    }
    catch (IllegalArgumentException e) {
        // Do nothing
    }
    muc.sendConfigurationForm(answerForm);
}
 
示例4
protected void setUp() throws Exception {
    //SmackConfiguration.DEBUG = false;
    super.setUp();
    room = "[email protected]" + getMUCDomain();
    try {
        // User1 creates the room
        muc = new MultiUserChat(getConnection(0), room);
        muc.create("testbot");

        // User1 sends an empty room configuration form which indicates that we want
        // an instant room
        Form form = new Form(Form.TYPE_SUBMIT);
        FormField field = new FormField("muc#roomconfig_whois");
        field.setType("list-single");
        form.addField(field);
        form.setAnswer("muc#roomconfig_whois", Arrays.asList("moderators"));
        muc.sendConfigurationForm(form);
    }
    catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
 
示例5
/**
 * 查询用户
 * 
 * @param userName
 * @return
 * @throws XMPPException
 */
public List<HashMap<String, String>> searchUsers(String userName) {
	if (getConnection() == null)
		return null;
	HashMap<String, String> user = null;
	List<HashMap<String, String>> results = new ArrayList<HashMap<String, String>>();
	try {
		new ServiceDiscoveryManager(getConnection());

		UserSearchManager usm = new UserSearchManager(getConnection());

		Form searchForm = usm.getSearchForm(getConnection().getServiceName());
		Form answerForm = searchForm.createAnswerForm();
		answerForm.setAnswer("userAccount", true);
		answerForm.setAnswer("userPhote", userName);
		ReportedData data = usm.getSearchResults(answerForm, "search" + getConnection().getServiceName());

		Iterator<Row> it = data.getRows();
		Row row = null;
		while (it.hasNext()) {
			user = new HashMap<String, String>();
			row = it.next();
			user.put("userAccount", row.getValues("userAccount").next().toString());
			user.put("userPhote", row.getValues("userPhote").next().toString());
			results.add(user);
			// 若存在,则有返回,UserName一定非空,其他两个若是有设,一定非空
		}
	} catch (XMPPException e) {
		e.printStackTrace();
	}
	return results;
}
 
示例6
/**
 * Tests creating a new "Reserved Room".
 */
public void testCreateReservedRoom() {
    MultiUserChat muc = new MultiUserChat(getConnection(0), room);

    try {
        // Create the room
        muc.create("testbot1");

        // Get the the room's configuration form
        Form form = muc.getConfigurationForm();
        assertNotNull("No room configuration form", form);
        // Create a new form to submit based on the original form
        Form submitForm = form.createAnswerForm();
        // Add default answers to the form to submit
        for (Iterator<FormField> fields = form.getFields(); fields.hasNext();) {
            FormField field = fields.next();
            if (!FormField.TYPE_HIDDEN.equals(field.getType())
                && field.getVariable() != null) {
                // Sets the default value as the answer
                submitForm.setDefaultAnswer(field.getVariable());
            }
        }
        List<String> owners = new ArrayList<String>();
        owners.add(getBareJID(0));
        submitForm.setAnswer("muc#roomconfig_roomowners", owners);

        // Update the new room's configuration
        muc.sendConfigurationForm(submitForm);

        // Destroy the new room
        muc.destroy("The room has almost no activity...", null);

    }
    catch (XMPPException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
 
示例7
/**
 * 创建聊天室
 *
 * @param password 登录密码
 * @param type     登陆类型: 0 - ProjCloud Other - Personal
 * @param roomName 房间名称
 * @param handler  处理信息的Handler
 */
public void createRoom(final String roomName, final int type, final String password, final Handler handler) {
    new Thread(){
        @Override
        public void run() {

            //如果无法连接服务器/超时,Handle Error
            if(getConnection() == null) {
                handler.sendEmptyMessage(ERROR);
                return;
            }

            //如果不是登录状态,Handle Failure
            if (!getConnection().isAuthenticated()) {
                handler.sendEmptyMessage(FAILURE);
                return;
            }

            try {
                String service = type == 0 ? "@cloud." : "@personal.";

                //写清房间地址,房产中心注册,开房,创建房间
                String address = roomName + service + getConnection().getServiceName();
                MultiUserChat room = new MultiUserChat(getConnection(), address);
                room.create(roomName);

                //装修房间配置信息:获取,配置,再提交
                Form originForm = room.getConfigurationForm();
                Form form = originForm.createAnswerForm();

                //---基础:当前域内项非隐藏并且非空(即有实际内容)就设为新表的域
                Iterator<FormField> iterator = originForm.getFields();
                while (iterator.hasNext()) {
                    FormField field = iterator.next();
                    if(!field.getType().equals(FormField.TYPE_HIDDEN)
                            && field.getVariable() != null) {
                        form.setDefaultAnswer(field.getVariable());
                    }
                }

                //---设置当前房间主人
                List<String> ownerList = new ArrayList<>();
                ownerList.add(getConnection().getUser());

                //---杂项
                if(!password.equals("")) {
                    form.setAnswer(ROOM_PSW_REQUIRED, true);  //要求密码
                    form.setAnswer(ROOM_PSW, password);  //设定密码
                }
                form.setAnswer(ROOM_KEEP_ALLOWED, true);  //永久房间
                form.setAnswer(ROOM_MEMBERS_ONLY, false);  //不禁止新入成员
                form.setAnswer(ROOM_INVITE_ALLOWED, true);  //允许邀请
                form.setAnswer(ROOM_LOG_ENABLED, true);  //开启日志
                form.setAnswer(ROOM_NICKNAME_ONLY, true);  //昵称登陆
                form.setAnswer(ROOM_SPECIAL_NICKNAME_ALLOWED, false);  //禁群内昵称
                form.setAnswer(ROOM_REGIST_NEW_ROOM_ALLOWED, false);  //禁开子房

                //发送表单更新房间信息
                room.sendConfigurationForm(form);
                handler.sendEmptyMessage(SUCCESS);
            } catch (XMPPException e) {
                handler.sendEmptyMessage(FAILURE);
                e.printStackTrace();
            }
        }
    }.start();
}
 
示例8
private void searchEjaaberd() {
	// 此处一定要加上 search.
	try {
		Connection connection = getXmppBinder().getXmppConnection();
		UserSearchManager search = new UserSearchManager(connection);
		Form searchForm = search.getSearchForm("vjud."
				+ connection.getServiceName());
		Form answerForm = searchForm.createAnswerForm();
		// answerForm.setAnswer("nick", mSearchEditText.getText()
		// .toString().trim() + "*");
		answerForm.setAnswer("user", mSearchEditText.getText().toString()
				.trim() + "*");
		// answerForm.setAnswer("search", mSearchEditText.getText()
		// .toString().trim());
		ReportedData data = search.getSearchResults(answerForm, "vjud."
				+ connection.getServiceName());
		Iterator<Row> it = data.getRows();
		Row row = null;

		ArrayList<FriendAddModel> list = new ArrayList<FriendAddModel>();
		while (it.hasNext()) {
			row = it.next();
			String userId = StringUtils.escapeUserResource(row
					.getValues("jid").next().toString());
			FriendAddModel model = new FriendAddModel(userId);
			model.setMsg(userId);
			String nick = row.getValues("nick").next().toString();
			if (!YiUtils.isStringInvalid(nick)) {
				model.setName(nick);
			}

			XmppVcard vCard = new XmppVcard(getXmppBinder()
					.getServiceContext());
			vCard.load(connection, model.getMsg());

			// 加载用户的个性签名
			String sign = vCard.getSign();
			if (sign != null && sign.length() > 0) {
				if (model.getSubMsg().length() > 1) {
					sign = ' ' + sign;
				}
				model.setSubMsg(model.getSubMsg() + sign);
			}
			list.add(model);
		}
		Message message = getHandler().obtainMessage(MSG_ON_SEARCH_SUCCESS,
				list);
		message.sendToTarget();
	} catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
	}
}
 
示例9
private void searchOpenfire() {
	// 此处一定要加上 search.
	try {
		Connection connection = getXmppBinder().getXmppConnection();
		UserSearchManager search = new UserSearchManager(connection);
		Form searchForm = search.getSearchForm("search."
				+ connection.getServiceName());
		Form answerForm = searchForm.createAnswerForm();
		answerForm.setAnswer("Username", true);
		answerForm.setAnswer("search", mSearchEditText.getText().toString()
				.trim());
		ReportedData data = search.getSearchResults(answerForm, "search."
				+ connection.getServiceName());
		Iterator<Row> it = data.getRows();
		Row row = null;

		ArrayList<FriendAddModel> list = new ArrayList<FriendAddModel>();
		while (it.hasNext()) {
			row = it.next();
			String userId = row.getValues("Username").next().toString()
					+ "@" + XmppConnectionUtils.getXmppHost();
			FriendAddModel model = new FriendAddModel(userId);
			model.setMsg(userId);
			model.setName(row.getValues("Name").next().toString());

			XmppVcard vCard = new XmppVcard(getXmppBinder()
					.getServiceContext());
			vCard.load(connection, userId);

			// 加载用户的个性签名
			String sign = vCard.getSign();
			if (sign != null && sign.length() > 0) {
				if (model.getSubMsg().length() > 1) {
					sign = ' ' + sign;
				}
				model.setSubMsg(model.getSubMsg() + sign);
			}
			list.add(model);
		}
		Message message = getHandler().obtainMessage(MSG_ON_SEARCH_SUCCESS,
				list);
		message.sendToTarget();
	} catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
	}
}
 
示例10
/**
 * 创建房间
 * 
 * @param roomName 房间名称
 */
public void createRoom(String roomName) {
	if (!isConnected()) {
		return;
	}
	try {
		// 创建一个MultiUserChat  
		MultiUserChat muc = new MultiUserChat(getConnection(), roomName + "@conference." + getConnection().getServiceName());
		// 创建聊天室  
		muc.create(roomName); // roomName房间的名字  
		// 获得聊天室的配置表单  
		Form form = muc.getConfigurationForm();
		// 根据原始表单创建一个要提交的新表单。  
		Form submitForm = form.createAnswerForm();
		// 向要提交的表单添加默认答复  
		for (Iterator<FormField> fields = form.getFields(); fields.hasNext();) {
			FormField field = (FormField) fields.next();
			if (!FormField.TYPE_HIDDEN.equals(field.getType()) && field.getVariable() != null) {
				// 设置默认值作为答复  
				submitForm.setDefaultAnswer(field.getVariable());
			}
		}
		// 设置聊天室的新拥有者  
		List<String> owners = new ArrayList<String>();
		owners.add(getConnection().getUser());// 用户JID  
		submitForm.setAnswer("muc#roomconfig_roomowners", owners);
		// 设置聊天室是持久聊天室,即将要被保存下来  
		submitForm.setAnswer("muc#roomconfig_persistentroom", false);
		// 房间仅对成员开放  
		submitForm.setAnswer("muc#roomconfig_membersonly", false);
		// 允许占有者邀请其他人  
		submitForm.setAnswer("muc#roomconfig_allowinvites", true);
		// 进入是否需要密码  
		//submitForm.setAnswer("muc#roomconfig_passwordprotectedroom", true);  
		// 设置进入密码  
		//submitForm.setAnswer("muc#roomconfig_roomsecret", "password");  
		// 能够发现占有者真实 JID 的角色  
		// submitForm.setAnswer("muc#roomconfig_whois", "anyone");  
		// 登录房间对话  
		submitForm.setAnswer("muc#roomconfig_enablelogging", true);
		// 仅允许注册的昵称登录  
		submitForm.setAnswer("x-muc#roomconfig_reservednick", true);
		// 允许使用者修改昵称  
		submitForm.setAnswer("x-muc#roomconfig_canchangenick", false);
		// 允许用户注册房间  
		submitForm.setAnswer("x-muc#roomconfig_registration", false);
		// 发送已完成的表单(有默认值)到服务器来配置聊天室  
		submitForm.setAnswer("muc#roomconfig_passwordprotectedroom", true);
		// 发送已完成的表单(有默认值)到服务器来配置聊天室  
		muc.sendConfigurationForm(submitForm);
	} catch (XMPPException e) {
		e.printStackTrace();
	}
}
 
示例11
/**
 * Tries to find the user in the user directory of the server. This method may fail for different
 * XMPP Server implementation, because the 'user' variable is not mandatory neither that it must
 * be named 'user'. Currently works with ejabberd XMPP servers.
 */

// TODO: remove this method, add more logic and let the GUI handle search
// stuff

private static boolean isListedInUserDirectory(Connection connection, JID jid) {

  String userDirectoryService = null;

  try {
    userDirectoryService = getUserDirectoryService(connection, connection.getServiceName());

    if (userDirectoryService == null) return false;

    UserSearch search = new UserSearch();

    Form form = search.getSearchForm(connection, userDirectoryService);

    String userFieldVariable = null;

    for (Iterator<FormField> it = form.getFields(); it.hasNext(); ) {
      FormField formField = it.next();

      if ("user".equalsIgnoreCase(formField.getVariable())) {
        userFieldVariable = formField.getVariable();
        break;
      }
    }

    if (userFieldVariable == null) return false;

    Form answerForm = form.createAnswerForm();

    answerForm.setAnswer(userFieldVariable, jid.getName());

    ReportedData data = search.sendSearchForm(connection, answerForm, userDirectoryService);

    for (Iterator<Row> it = data.getRows(); it.hasNext(); ) {

      Row row = it.next();

      Iterator<String> vit = row.getValues("jid");

      if (vit == null) continue;

      while (vit.hasNext()) {
        JID returnedJID = new JID(vit.next());
        if (jid.equals(returnedJID)) return true;
      }
    }

    return false;
  } catch (XMPPException e) {
    log.error("searching in the user directory + '" + userDirectoryService + "' failed", e);
    return false;
  }
}