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); }
/** * 查询用户 * @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; }
/** * 查询用户 * @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; }
/** * 查找用户 * * @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; }
/** * 查询用户 * * @param userName * @return * @throws XMPPException */ public static List<Session> searchUsers(XMPPConnection mXMPPConnection,String userName) { List<Session> listUser=new ArrayList<Session>(); try{ UserSearchManager search = new UserSearchManager(mXMPPConnection); //此处一定要加上 search. Form searchForm = search.getSearchForm("search."+mXMPPConnection.getServiceName()); Form answerForm = searchForm.createAnswerForm(); answerForm.setAnswer("Username", true); answerForm.setAnswer("search", userName); ReportedData data = search.getSearchResults(answerForm,"search."+mXMPPConnection.getServiceName()); Iterator<Row> it = data.getRows(); Row row=null; while(it.hasNext()){ row=it.next(); Session session=new Session(); session.setFrom(row.getValues("Username").next().toString()); listUser.add(session); } }catch(Exception e){ } return listUser; }
/** * 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()); } }
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); }
/** * Returns the room's configuration form that the room's owner can use or <tt>null</tt> if * no configuration is possible. The configuration form allows to set the room's language, * enable logging, specify room's type, etc.. * * @return the Form that contains the fields to complete together with the instrucions or * <tt>null</tt> if no configuration is possible. * @throws XMPPException if an error occurs asking the configuration form for the room. */ public Form getConfigurationForm() throws XMPPException { MUCOwner iq = new MUCOwner(); iq.setTo(room); iq.setType(IQ.Type.GET); // Filter packets looking for an answer from the server. PacketFilter responseFilter = new PacketIDFilter(iq.getPacketID()); PacketCollector response = connection.createPacketCollector(responseFilter); // Request the configuration form to the server. connection.sendPacket(iq); // 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()); } return Form.getFormFrom(answer); }
/** * Sends the completed configuration form to the server. The room will be configured * with the new settings defined in the form. If the form is empty then the server * will create an instant room (will use default configuration). * * @param form the form with the new settings. * @throws XMPPException if an error occurs setting the new rooms' configuration. */ public void sendConfigurationForm(Form form) throws XMPPException { MUCOwner iq = new MUCOwner(); iq.setTo(room); iq.setType(IQ.Type.SET); iq.addExtension(form.getDataFormToSend()); // Filter packets looking for an answer from the server. PacketFilter responseFilter = new PacketIDFilter(iq.getPacketID()); PacketCollector response = connection.createPacketCollector(responseFilter); // Send the completed configuration form to the server. connection.sendPacket(iq); // 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()); } }
/** * Returns the room's registration form that an unaffiliated user, can use to become a member * of the room or <tt>null</tt> if no registration is possible. Some rooms may restrict the * privilege to register members and allow only room admins to add new members.<p> * * If the user requesting registration requirements is not allowed to register with the room * (e.g. because that privilege has been restricted), the room will return a "Not Allowed" * error to the user (error code 405). * * @return the registration Form that contains the fields to complete together with the * instrucions or <tt>null</tt> if no registration is possible. * @throws XMPPException if an error occurs asking the registration form for the room or a * 405 error if the user is not allowed to register with the room. */ public Form getRegistrationForm() throws XMPPException { Registration reg = new Registration(); reg.setType(IQ.Type.GET); reg.setTo(room); 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()); collector.cancel(); if (result == null) { throw new XMPPException("No response from server."); } else if (result.getType() == IQ.Type.ERROR) { throw new XMPPException(result.getError()); } return Form.getFormFrom(result); }
/** * Sends the completed registration form to the server. After the user successfully submits * the form, the room may queue the request for review by the room admins or may immediately * add the user to the member list by changing the user's affiliation from "none" to "member.<p> * * If the desired room nickname is already reserved for that room, the room will return a * "Conflict" error to the user (error code 409). If the room does not support registration, * it will return a "Service Unavailable" error to the user (error code 503). * * @param form the completed registration form. * @throws XMPPException if an error occurs submitting the registration form. In particular, a * 409 error can occur if the desired room nickname is already reserved for that room; * or a 503 error can occur if the room does not support registration. */ public void sendRegistrationForm(Form form) throws XMPPException { Registration reg = new Registration(); reg.setType(IQ.Type.SET); reg.setTo(room); reg.addExtension(form.getDataFormToSend()); 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()); collector.cancel(); if (result == null) { throw new XMPPException("No response from server."); } else if (result.getType() == IQ.Type.ERROR) { throw new XMPPException(result.getError()); } }
RoomInfo(DiscoverInfo info) { super(); this.room = info.getFrom(); // Get the information based on the discovered features this.membersOnly = info.containsFeature("muc_membersonly"); this.moderated = info.containsFeature("muc_moderated"); this.nonanonymous = info.containsFeature("muc_nonanonymous"); this.passwordProtected = info.containsFeature("muc_passwordprotected"); this.persistent = info.containsFeature("muc_persistent"); // Get the information based on the discovered extended information Form form = Form.getFormFrom(info); if (form != null) { this.description = form.getField("muc#roominfo_description").getValues().next(); Iterator<String> values = form.getField("muc#roominfo_subject").getValues(); if (values.hasNext()) { this.subject = values.next(); } else { this.subject = ""; } this.occupantsCount = Integer.parseInt(form.getField("muc#roominfo_occupants").getValues() .next()); } }
/** * Creates a node with specified configuration. * * Note: This is the only way to create a collection node. * * @param name The name of the node, which must be unique within the * pubsub service * @param config The configuration for the node * @return The node that was created * @exception XMPPException */ public Node createNode(String name, Form config) throws XMPPException { PubSub request = createPubsubPacket(to, Type.SET, new NodeExtension(PubSubElementType.CREATE, name)); boolean isLeafNode = true; if (config != null) { request.addExtension(new FormNode(FormNodeType.CONFIGURE, config)); FormField nodeTypeField = config.getField(ConfigureNodeFields.node_type.getFieldName()); if (nodeTypeField != null) isLeafNode = nodeTypeField.getValues().next().equals(NodeType.leaf.toString()); } // Errors will cause exceptions in getReply, so it only returns // on success. sendPubsubPacket(con, to, Type.SET, request); Node newNode = isLeafNode ? new LeafNode(con, name) : new CollectionNode(con, name); newNode.setTo(to); nodeMap.put(newNode.getId(), newNode); return newNode; }
/** * Returns the Form to use for searching transcripts. It is unlikely that the server * will change the form (without a restart) so it is safe to keep the returned form * for future submissions. * * @param serviceJID the address of the workgroup service. * @return the Form to use for searching transcripts. * @throws XMPPException if an error occurs while sending the request to the server. */ public Form getSearchForm(String serviceJID) throws XMPPException { TranscriptSearch search = new TranscriptSearch(); search.setType(IQ.Type.GET); search.setTo(serviceJID); PacketCollector collector = connection.createPacketCollector( new PacketIDFilter(search.getPacketID())); connection.sendPacket(search); TranscriptSearch response = (TranscriptSearch) collector.nextResult( SmackConfiguration.getPacketReplyTimeout()); // Cancel the collector. collector.cancel(); if (response == null) { throw new XMPPException("No response from server on status set."); } if (response.getError() != null) { throw new XMPPException(response.getError()); } return Form.getFormFrom(response); }
/** * Submits the completed form and returns the result of the transcript search. The result * will include all the data returned from the server so be careful with the amount of * data that the search may return. * * @param serviceJID the address of the workgroup service. * @param completedForm the filled out search form. * @return the result of the transcript search. * @throws XMPPException if an error occurs while submiting the search to the server. */ public ReportedData submitSearch(String serviceJID, Form completedForm) throws XMPPException { TranscriptSearch search = new TranscriptSearch(); search.setType(IQ.Type.GET); search.setTo(serviceJID); search.addExtension(completedForm.getDataFormToSend()); PacketCollector collector = connection.createPacketCollector(new PacketIDFilter(search.getPacketID())); connection.sendPacket(search); TranscriptSearch response = (TranscriptSearch) collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); // Cancel the collector. collector.cancel(); if (response == null) { throw new XMPPException("No response from server on status set."); } if (response.getError() != null) { throw new XMPPException(response.getError()); } return ReportedData.getReportedDataFrom(response); }
/** * Returns the Form to use for all clients of a workgroup. It is unlikely that the server * will change the form (without a restart) so it is safe to keep the returned form * for future submissions. * * @return the Form to use for searching transcripts. * @throws XMPPException if an error occurs while sending the request to the server. */ public Form getWorkgroupForm() throws XMPPException { WorkgroupForm workgroupForm = new WorkgroupForm(); workgroupForm.setType(IQ.Type.GET); workgroupForm.setTo(workgroupJID); PacketCollector collector = connection.createPacketCollector(new PacketIDFilter(workgroupForm.getPacketID())); connection.sendPacket(workgroupForm); WorkgroupForm response = (WorkgroupForm)collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); // Cancel the collector. collector.cancel(); if (response == null) { throw new XMPPException("No response from server on status set."); } if (response.getError() != null) { throw new XMPPException(response.getError()); } return Form.getFormFrom(response); }
/** * Returns the form for all search fields supported by the search service. * * @param con the current Connection. * @param searchService the search service to use. (ex. search.jivesoftware.com) * @return the search form received by the server. * @throws org.jivesoftware.smack.XMPPException * thrown if a server error has occurred. */ public Form getSearchForm(Connection con, String searchService) throws XMPPException { UserSearch search = new UserSearch(); search.setType(IQ.Type.GET); search.setTo(searchService); PacketCollector collector = con.createPacketCollector(new PacketIDFilter(search.getPacketID())); con.sendPacket(search); IQ response = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); // Cancel the collector. collector.cancel(); if (response == null) { throw new XMPPException("No response from server on status set."); } if (response.getError() != null) { throw new XMPPException(response.getError()); } return Form.getFormFrom(response); }
/** * Sends the filled out answer form to be sent and queried by the search service. * * @param con the current Connection. * @param searchForm the <code>Form</code> to send for querying. * @param searchService the search service to use. (ex. search.jivesoftware.com) * @return ReportedData the data found from the query. * @throws org.jivesoftware.smack.XMPPException * thrown if a server error has occurred. */ public ReportedData sendSearchForm(Connection con, Form searchForm, String searchService) throws XMPPException { UserSearch search = new UserSearch(); search.setType(IQ.Type.SET); search.setTo(searchService); search.addExtension(searchForm.getDataFormToSend()); PacketCollector collector = con.createPacketCollector(new PacketIDFilter(search.getPacketID())); con.sendPacket(search); IQ response = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); // Cancel the collector. collector.cancel(); if (response == null) { throw new XMPPException("No response from server on status set."); } if (response.getError() != null) { return sendSimpleSearchForm(con, searchForm, searchService); } return ReportedData.getReportedDataFrom(response); }
private String getItemsToSearch() { StringBuilder buf = new StringBuilder(); if (form == null) { form = Form.getFormFrom(this); } if (form == null) { return ""; } Iterator<FormField> fields = form.getFields(); while (fields.hasNext()) { FormField field = fields.next(); String name = field.getVariable(); String value = getSingleValue(field); if (value.trim().length() > 0) { buf.append("<").append(name).append(">").append(value).append("</").append(name).append(">"); } } return buf.toString(); }
/** * Creates the initiation acceptance packet to forward to the stream * initiator. * * @param streamInitiationOffer The offer from the stream initiator to connect for a stream. * @param namespaces The namespace that relates to the accepted means of transfer. * @return The response to be forwarded to the initiator. */ public StreamInitiation createInitiationAccept( StreamInitiation streamInitiationOffer, String[] namespaces) { StreamInitiation response = new StreamInitiation(); response.setTo(streamInitiationOffer.getFrom()); response.setFrom(streamInitiationOffer.getTo()); response.setType(IQ.Type.RESULT); response.setPacketID(streamInitiationOffer.getPacketID()); DataForm form = new DataForm(Form.TYPE_SUBMIT); FormField field = new FormField( FileTransferNegotiator.STREAM_DATA_FIELD_NAME); for (String namespace : namespaces) { field.addValue(namespace); } form.addField(field); response.setFeatureNegotiationForm(form); return response; }
RoomInfo(DiscoverInfo info) { super(); this.room = info.getFrom(); // Get the information based on the discovered features this.membersOnly = info.containsFeature("muc_membersonly"); this.moderated = info.containsFeature("muc_moderated"); this.nonanonymous = info.containsFeature("muc_nonanonymous"); this.passwordProtected = info.containsFeature("muc_passwordprotected"); this.persistent = info.containsFeature("muc_persistent"); // Get the information based on the discovered extended information Form form = Form.getFormFrom(info); if (form != null) { FormField descField = form.getField("muc#roominfo_description"); this.description = ( descField == null || !(descField.getValues().hasNext()) )? "" : descField.getValues().next(); FormField subjField = form.getField("muc#roominfo_subject"); this.subject = ( subjField == null || !(subjField.getValues().hasNext()) ) ? "" : subjField.getValues().next(); FormField occCountField = form.getField("muc#roominfo_occupants"); this.occupantsCount = occCountField == null ? -1 : Integer.parseInt(occCountField.getValues() .next()); } }
/** * * @param info * @return true if the packet extensions is ill-formed */ protected static boolean verifyPacketExtensions(DiscoverInfo info) { List<FormField> foundFormTypes = new LinkedList<FormField>(); for (Iterator<PacketExtension> i = info.getExtensions().iterator(); i.hasNext();) { PacketExtension pe = i.next(); if (pe.getNamespace().equals(Form.NAMESPACE)) { DataForm df = (DataForm) pe; for (Iterator<FormField> it = df.getFields(); it.hasNext();) { FormField f = it.next(); if (f.getVariable().equals("FORM_TYPE")) { for (FormField fft : foundFormTypes) { if (f.equals(fft)) return true; } foundFormTypes.add(f); } } } } return false; }
/** * Returns the room's configuration form that the room's owner can use or * <tt>null</tt> if no configuration is possible. The configuration form * allows to set the room's language, enable logging, specify room's type, * etc.. * * @return the Form that contains the fields to complete together with the * instrucions or <tt>null</tt> if no configuration is possible. * @throws XMPPException * if an error occurs asking the configuration form for the * room. */ public Form getConfigurationForm() throws XMPPException { MUCOwner iq = new MUCOwner(); iq.setTo(room); iq.setType(IQ.Type.GET); // Filter packets looking for an answer from the server. PacketFilter responseFilter = new PacketIDFilter(iq.getPacketID()); PacketCollector response = connection .createPacketCollector(responseFilter); // Request the configuration form to the server. connection.sendPacket(iq); // 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()); } return Form.getFormFrom(answer); }
/** * Sends the completed configuration form to the server. The room will be * configured with the new settings defined in the form. If the form is * empty then the server will create an instant room (will use default * configuration). * * @param form * the form with the new settings. * @throws XMPPException * if an error occurs setting the new rooms' configuration. */ public void sendConfigurationForm(Form form) throws XMPPException { MUCOwner iq = new MUCOwner(); iq.setTo(room); iq.setType(IQ.Type.SET); iq.addExtension(form.getDataFormToSend()); // Filter packets looking for an answer from the server. PacketFilter responseFilter = new PacketIDFilter(iq.getPacketID()); PacketCollector response = connection .createPacketCollector(responseFilter); // Send the completed configuration form to the server. connection.sendPacket(iq); // 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()); } }
/** * Returns the room's registration form that an unaffiliated user, can use * to become a member of the room or <tt>null</tt> if no registration is * possible. Some rooms may restrict the privilege to register members and * allow only room admins to add new members. * <p> * * If the user requesting registration requirements is not allowed to * register with the room (e.g. because that privilege has been restricted), * the room will return a "Not Allowed" error to the user (error code 405). * * @return the registration Form that contains the fields to complete * together with the instrucions or <tt>null</tt> if no registration * is possible. * @throws XMPPException * if an error occurs asking the registration form for the room * or a 405 error if the user is not allowed to register with * the room. */ public Form getRegistrationForm() throws XMPPException { Registration reg = new Registration(); reg.setType(IQ.Type.GET); reg.setTo(room); 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()); collector.cancel(); if (result == null) { throw new XMPPException("No response from server."); } else if (result.getType() == IQ.Type.ERROR) { throw new XMPPException(result.getError()); } return Form.getFormFrom(result); }
RoomInfo(DiscoverInfo info) { super(); this.room = info.getFrom(); // Get the information based on the discovered features this.membersOnly = info.containsFeature("muc_membersonly"); this.moderated = info.containsFeature("muc_moderated"); this.nonanonymous = info.containsFeature("muc_nonanonymous"); this.passwordProtected = info.containsFeature("muc_passwordprotected"); this.persistent = info.containsFeature("muc_persistent"); // Get the information based on the discovered extended information Form form = Form.getFormFrom(info); if (form != null) { FormField descField = form.getField("muc#roominfo_description"); this.description = (descField == null || !(descField.getValues() .hasNext())) ? "" : descField.getValues().next(); FormField subjField = form.getField("muc#roominfo_subject"); this.subject = (subjField == null || !(subjField.getValues() .hasNext())) ? "" : subjField.getValues().next(); FormField occCountField = form.getField("muc#roominfo_occupants"); this.occupantsCount = occCountField == null ? -1 : Integer .parseInt(occCountField.getValues().next()); } }