/** * Send provided message to provided JID. Message type is always NORMAL. * * @param message * @param jid * @throws NotConnectedException */ public void sendMessage(String message, String jid) throws NotConnectedException { try{ String jidFinal = getFullJid(jid); logger.debug("Sending message: {} to user: {}", new Object[] { message, jidFinal }); Message msg = new Message(jidFinal, Message.Type.normal); msg.setBody(message); connection.sendStanza(msg); logger.debug("Successfully sent message to user: {}", jidFinal);} catch(NotConnectedException ex){ ex.printStackTrace(); try { logger.debug("Tring again to connect.."); init(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
@Override public SendResponse sendMessage(Message message) { org.jivesoftware.smack.packet.Message.Type type = org.jivesoftware.smack.packet.Message.Type.chat; org.jivesoftware.smack.packet.Message msg = new org.jivesoftware.smack.packet.Message(); msg.setFrom(message.getFromJid().getId()); msg.setBody(message.getBody()); msg.setType(type); for (JID to : message.getRecipientJids()) { msg.setTo(to.getId()); session_.getConnection().sendPacket(msg); } return null; }
/** * Returns a (legacy/Smack-based) Presence stanza that represents the * current presence of this session. The Presence includes relevant Mode, * Status and VCardUpdate information. * * This method uses the fields {@link TransportSession#presence} and * {@link TransportSession#verboseStatus} to generate the result. * * @return A Presence packet representing the current presence state of this * session. */ public Presence constructCurrentLegacyPresencePacket() { final org.jivesoftware.smack.packet.Presence presence = new org.jivesoftware.smack.packet.Presence( org.jivesoftware.smack.packet.Presence.Type.available); final Presence.Mode pMode = ((XMPPTransport) getTransport()) .convertGatewayStatusToXMPP(this.presence); if (pMode != null) { presence.setMode(pMode); } if (verboseStatus != null && verboseStatus.trim().length() > 0) { presence.setStatus(verboseStatus); } final Avatar avatar = getAvatar(); if (avatar != null) { final VCardUpdateExtension ext = new VCardUpdateExtension(); ext.setPhotoHash(avatar.getLegacyIdentifier()); presence.addExtension(ext); } return presence; }
public Contact getContact(RosterEntry r) { Contact contact = new Contact(); contact.name = r.getName(); contact.user = r.getUser(); contact.type = r.getType().toString(); Type presenceType = roster.getPresence(r.getUser()).getType(); if (presenceType != null) { contact.presence = presenceType.toString(); } ItemStatus status = r.getStatus(); if (status != null) { contact.status = status.toString(); } // ItemStatus status = r.getStatus(); // null // log.info("roster entry {}", r.toString()); // contact.na= r.getUser(); log.info("getContact {}", contact.toString()); return contact; }
public void updatePresence() { try { Connection connection = XmppConnectionUtils.getInstance() .getConnection(); if (connection != null && connection.isConnected() && connection.isAuthenticated()) { // 在线状态获取 Presence presence = connection.getRoster().getPresence(mUserId); if (presence.getType() != Type.unavailable) { setPresence("online"); } else { setPresence("unavailable"); } saveToDatabase(); } } catch (Exception e) { // TODO: handle exception } }
public byte xmppPresence2UserStatus(Presence presence) { if (presence == null || presence.getType() != Type.available){ return -1; } if (presence.getMode() == null || presence.getMode() == Mode.available){ return 0; } for (byte i=0; i<presenceModes.length; i++) { Mode m = presenceModes[i]; if (m == presence.getMode()){ return i; } } return -1; }
@Override public Presence userStatus2XMPPPresence(Byte status) { Presence presence; if (status < 0 || status >= presenceModes.length) { presence = new Presence(Type.unavailable); } else { presence = new Presence(Type.available); presence.setMode(presenceModes[status]); } if (edProvider != null){ SignedPresence spr = new SignedPresence(); try { spr.signAndSet(presence.getStatus(), edProvider.getMyKey(), edProvider.getMyKeyPw()); presence.addExtension(spr); } catch (XMPPException e) { Logger.log(e); } } return presence; }
@Override public Message textMessage2XMPPMessage(TextMessage textMessage, String thread, String to, Message.Type messageType) throws Exception { Message message = new Message(to, messageType); message.setThread(thread); message.setPacketID(textMessage.getMessageId() + ""); MessageEventManager.addNotificationsRequests(message, true, true, true, true); String buddyKey = null; if (edProvider != null && (buddyKey = edProvider.getKeyStorage().get(textMessage.getContactUid())) != null){ EncryptedMessage ems = new EncryptedMessage(); ems.setAndEncrypt(textMessage.getText(), buddyKey); //TODO message.setBody("Encrypted message"); message.addExtension(ems); } else { message.setBody(textMessage.getText()); } return message; }
@Override protected void doAddContactToListAsync(String address, ContactList list) throws ImException { debug(TAG, "add contact to " + list.getName()); org.jivesoftware.smack.packet.Presence response = new org.jivesoftware.smack.packet.Presence( org.jivesoftware.smack.packet.Presence.Type.subscribed); response.setTo(address); sendPacket(response); Roster roster = mConnection.getRoster(); String[] groups = new String[] { list.getName() }; try { Contact contact = makeContact(address); roster.createEntry(address, contact.getName(), groups); // If contact exists locally, don't create another copy if (!list.containsContact(contact)) notifyContactListUpdated(list, ContactListListener.LIST_CONTACT_ADDED, contact); else debug(TAG, "skip adding existing contact locally " + contact.getName()); } catch (XMPPException e) { throw new RuntimeException(e); } }
@Override public void onClick(View v) { Presence presence = null; switch (v.getId()) { case R.id.SubscriptionAccept: presence = new Presence(Type.subscribed); Toast.makeText(Subscription.this, getString(R.string.SubscriptAccept), Toast.LENGTH_SHORT) .show(); break; case R.id.SubscriptionRefuse: presence = new Presence(Type.unsubscribed); Toast.makeText(Subscription.this, getString(R.string.SubscriptRefused), Toast.LENGTH_SHORT).show(); break; default: Toast.makeText(Subscription.this, getString(R.string.SubscriptError), Toast.LENGTH_SHORT).show(); } if (presence != null) { presence.setTo(mContact); sendPresence(presence); } finish(); }
@Test public void testSetPresence() { XMPPConnection xmppConnection = providerConnection(); assertTrue(XMPPUtil.login(xmppConnection, "ranrandemo", "admin123")); assertTrue(XMPPUtil.setPresence(xmppConnection, Type.error, "I am bad")); XMPPUtil.relaseXMPPConnection(xmppConnection); }
/** * Get online users from roster and store in onlineUsers */ private void getInitialOnlineUsers() { Roster roster = Roster.getInstanceFor(connection); Collection<RosterEntry> entries = roster.getEntries(); if (entries != null && !entries.isEmpty()) { for (RosterEntry entry : entries) { String jid = entry.getUser(); Presence presence = roster.getPresence(jid); if (presence != null) { XMPPError xmppError = presence.getError(); if (xmppError != null) { logger.error(xmppError.getDescriptiveText()); } else { try { if (presence.getType() == Type.available) { onlineUsers.add(jid.substring(0, jid.indexOf('@'))); } else if (presence.getType() == Type.unavailable) { onlineUsers.remove(jid.substring(0, jid.indexOf('@'))); } } catch (Exception e) { logger.error(e.getMessage(), e); } } } } } logger.debug("Online users: {}", onlineUsers.toString()); }
public void setStatus(boolean available, String status) { connect(); if (connection != null && connection.isConnected()) { Presence.Type type = available ? Type.available : Type.unavailable; Presence presence = new Presence(type); presence.setStatus(status); connection.sendPacket(presence); } else { log.error("setStatus not connected"); } }
@Override public void disconnect() { if (this.isConnected()) { org.jivesoftware.smack.packet.Presence unavailable = new org.jivesoftware.smack.packet.Presence(Type.unavailable); unavailable.setFrom(this.session_.getUser().getId().getId()); this.session_.getConnection().disconnect(unavailable); this.eventManager_.stop(); } }
@Override public void sendPresence(JID jabberId, PresenceType type, PresenceShow show, String status, JID fromJid) { checkNotNull(jabberId); final Type presenceType = type == null ? Type.available : Type.valueOf(type.name().toLowerCase()); final Mode presenceMode = show == null ? null : Mode.valueOf(show.name().toLowerCase()); org.jivesoftware.smack.packet.Presence presence = new org.jivesoftware.smack.packet.Presence(presenceType, status, 1, presenceMode); presence.setFrom(fromJid == null ? null : fromJid.getId()); presence.setTo(jabberId.getId()); this.session_.getConnection().sendPacket(presence); }
@Override public void subscribe(JID fromJid, JID toJid) { org.jivesoftware.smack.packet.Presence presence = new org.jivesoftware.smack.packet.Presence(Type.subscribe); presence.setFrom(fromJid == null ? this.session_.getUser().getName() : fromJid.getId()); presence.setTo(toJid.getId()); session_.getConnection().sendPacket(presence); }
/** * @see net.sf.kraken.session.TransportSession#acceptAddContact(JID) */ @Override public void acceptAddContact(JID jid) { final String userID = getTransport().convertJIDToID(jid); Log.debug("XMPP: accept-add contact: " + userID); final Presence accept = new Presence(Type.subscribed); accept.setTo(userID); conn.sendPacket(accept); }
/** * @see net.sf.kraken.session.TransportSession#sendChatState(org.xmpp.packet.JID, net.sf.kraken.type.ChatStateType) */ @Override public void sendChatState(JID jid, ChatStateType chatState) { final Presence presence = conn.getRoster().getPresence(jid.toString()); if (presence == null || presence.getType().equals(Presence.Type.unavailable)) { // don't send chat state to contacts that are offline. return; } Chat chat = conn.getChatManager().createChat(getTransport().convertJIDToID(jid), listener); try { ChatState state = ChatState.active; switch (chatState) { case active: state = ChatState.active; break; case composing: state = ChatState.composing; break; case paused: state = ChatState.paused; break; case inactive: state = ChatState.inactive; break; case gone: state = ChatState.gone; break; } Message message = new Message(); message.addExtension(new ChatStateExtension(state)); chat.sendMessage(message); } catch (XMPPException e) { // Ignore } }
public XmppMsg(Chat chat, Message msg) { this.from = chat.getParticipant(); this.msg = msg.getBody(); Message.Type t = msg.getType(); if (t != null) { this.type = msg.getType().toString(); } stanzaId = msg.getStanzaId(); }
public void setStatus(boolean available, String status) { if (connection != null && connection.isConnected()) { Presence.Type type = available ? Type.available : Type.unavailable; Presence presence = new Presence(type); presence.setStatus(status); // connection.sendPacket(presence); } else { log.error("setStatus not connected"); } }
public Presence userStatus2XMPPPresence(Byte status) { Presence presence; if (status < 0 || status >= presenceModes.length) { presence = new Presence(Type.unavailable); } else { presence = new Presence(Type.available); presence.setMode(presenceModes[status]); } return presence; }
public Message textMessage2XMPPMessage(TextMessage textMessage, String thread, String to, Message.Type messageType) throws Exception { Message message = new Message(to, messageType); message.setThread(thread); message.setPacketID(textMessage.getMessageId() + ""); MessageEventManager.addNotificationsRequests(message, true, true, true, true); message.setBody(textMessage.getText()); return message; }
protected static int parsePresence(org.jivesoftware.smack.packet.Presence presence) { int type = Presence.AVAILABLE; Mode rmode = presence.getMode(); Type rtype = presence.getType(); if (rmode == Mode.away || rmode == Mode.xa) type = Presence.AWAY; else if (rmode == Mode.dnd) type = Presence.DO_NOT_DISTURB; else if (rtype == Type.unavailable || rtype == Type.error) type = Presence.OFFLINE; return type; }
@Override protected void doRemoveContactFromListAsync(Contact contact, ContactList list) { // FIXME synchronize this to executor thread if (mConnection == null) return; Roster roster = mConnection.getRoster(); String address = contact.getAddress().getAddress(); try { RosterGroup group = roster.getGroup(list.getName()); if (group == null) { debug(TAG, "could not find group " + list.getName() + " in roster"); return; } RosterEntry entry = roster.getEntry(address); if (entry == null) { debug(TAG, "could not find entry " + address + " in group " + list.getName()); //just ignore it then } else { // Remove from Roster if this is the last group if (entry.getGroups().size() <= 1) roster.removeEntry(entry); group.removeEntry(entry); } } catch (XMPPException e) { debug(TAG, "remove entry failed: " + e.getMessage()); throw new RuntimeException(e); } //otherwise, send unsub message and delete from local contact database org.jivesoftware.smack.packet.Presence response = new org.jivesoftware.smack.packet.Presence( org.jivesoftware.smack.packet.Presence.Type.unsubscribed); response.setTo(address); sendPacket(response); notifyContactListUpdated(list, ContactListListener.LIST_CONTACT_REMOVED, contact); }
@Override public void declineSubscriptionRequest(String contact) { debug(TAG, "decline subscription"); org.jivesoftware.smack.packet.Presence response = new org.jivesoftware.smack.packet.Presence( org.jivesoftware.smack.packet.Presence.Type.unsubscribed); response.setTo(contact); sendPacket(response); mContactListManager.getSubscriptionRequestListener().onSubscriptionDeclined(contact); }
private void sendPing() { IQ req = new IQ() { public String getChildElementXML() { return "<ping xmlns='urn:xmpp:ping'/>"; } }; req.setType(IQ.Type.GET); PacketFilter filter = new AndFilter(new PacketIDFilter(req.getPacketID()), new PacketTypeFilter(IQ.class)); mPingCollector = mConnection.createPacketCollector(filter); mConnection.sendPacket(req); }
private void sendMessage(String jid, String message) throws NotificationException { BrokerFactory.getLoggingBroker().logDebug( "Sending Jabber message to " + jid + ": " + message); Message msg = new Message(jid, Message.Type.CHAT); msg.setBody(message); getSession().sendPacket(msg); }
@Override public boolean setPresence(Type type, String status) { return XMPPUtil.setPresence(xmppConnection, type, status); }
private PresenceTypeFilter(Presence.Type type) { super(Presence.class); this.type = Objects.requireNonNull(type, "type must not be null"); }