org.jivesoftware.smack.chat2.Chat Java Examples

The following examples show how to use org.jivesoftware.smack.chat2.Chat. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MucChatService.java    From xyTalk-pc with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void sendInvitationMessage(List<Jid> users, String roomid, String roomName){
	MucInvitation mi = new MucInvitation(roomid, roomName);

	for (int i = 0; i < users.size(); i++) {
		Jid userJid = users.get(i);
		Chat chat = ChatManager.getInstanceFor(Launcher.connection).chatWith(userJid.asEntityBareJidIfPossible());
		org.jivesoftware.smack.packet.Message message = new org.jivesoftware.smack.packet.Message();
		message.setType(Type.chat);
		message.addExtension(mi);
		message.setBody("请加入会议");
		try {
			chat.send(message);
			DebugUtil.debug("sendOfflineInvitationMessage:" + message.toXML());
		} catch (NotConnectedException | InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
 
Example #2
Source File: SysTrayPlugin.java    From Spark with Apache License 2.0 6 votes vote down vote up
@Override
public void stateChanged(Chat chat, ChatState state, Message message) {
	presence = Workspace.getInstance().getStatusBar().getPresence();
	if (ChatState.composing.equals(state)) {
		changeSysTrayIcon();
	} else {
		if (!newMessage) {
			if (presence.getMode() == Presence.Mode.available) {
				trayIcon.setImage(availableIcon.getImage());
			} else if (presence.getMode() == Presence.Mode.away
					|| presence.getMode() == Presence.Mode.xa) {
				trayIcon.setImage(awayIcon.getImage());
			} else if (presence.getMode() == Presence.Mode.dnd) {
				trayIcon.setImage(dndIcon.getImage());
			} else {
				trayIcon.setImage(newMessageIcon.getImage());
			}
		}
	}
}
 
Example #3
Source File: StanzaThread.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public void run() {
    XMPPTCPConnectionConfiguration config = null;
    try {
        config = XMPPTCPConnectionConfiguration.builder()
                .setUsernameAndPassword("baeldung2","baeldung2")
                .setXmppDomain("jabb3r.org")
                .setHost("jabb3r.org")
                .build();

        AbstractXMPPConnection connection = new XMPPTCPConnection(config);
        connection.connect();
        connection.login();

        ChatManager chatManager = ChatManager.getInstanceFor(connection);

        Chat chat = chatManager.chatWith(JidCreate.from("[email protected]").asEntityBareJidOrThrow());

        chat.send("Hello!");

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}
 
Example #4
Source File: ChatStateIntegrationTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
@SmackIntegrationTest
public void testChatStateListeners() throws Exception {
    ChatStateManager manOne = ChatStateManager.getInstance(conOne);
    ChatStateManager manTwo = ChatStateManager.getInstance(conTwo);

    // Add chatState listeners.
    manTwo.addChatStateListener(this::composingListener);
    manTwo.addChatStateListener(this::activeListener);

    Chat chatOne = ChatManager.getInstanceFor(conOne)
            .chatWith(conTwo.getUser().asEntityBareJid());

    // Test, if setCurrentState works and the chatState arrives
    manOne.setCurrentState(ChatState.composing, chatOne);
    composingSyncPoint.waitForResult(timeout);

    // Test, if the OutgoingMessageInterceptor successfully adds a chatStateExtension of "active" to
    // an outgoing chat message and if it arrives at the other side.
    Chat chat = ChatManager.getInstanceFor(conOne)
            .chatWith(conTwo.getUser().asEntityBareJid());
    chat.send("Hi!");
    activeSyncPoint.waitForResult(timeout);
}
 
Example #5
Source File: XmppConnection.java    From Zom-Android-XMPP with GNU General Public License v3.0 6 votes vote down vote up
private void sendChatState (String to, ChatState currentChatState)
{
    try {
        if (mConnection != null && mConnection.isConnected())
        {
            Chat thisChat = mChatMap.get(to);

            if (thisChat == null) {
                thisChat = mChatManager.chatWith(JidCreate.from(to).asEntityBareJidIfPossible());
                mChatMap.put(to,thisChat);
            }

            if (mChatStateManager != null)
                mChatStateManager.setCurrentState(currentChatState,thisChat);
        }
    }
    catch (Exception e)
    {
        Log.w(ImApp.LOG_TAG,"error sending chat state: " + e.getMessage());
    }
}
 
Example #6
Source File: XmppMessageEngine.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Constructor for the XMPP message engine. It initialises fields and a {@link java.util.Timer Timer} that periodically
 * in interval that is randomly set, executes the {@link #renewPresenceAndRoster() renewPresenceAndRoster} method.
 * 
 * @param objectId String with the object ID that connects via this engine.
 * @param password Password string for authentication.
 * @param config Configuration of the OGWAPI.
 * @param logger Logger of the OGWAPI. 
 * @param connectionDescriptor Connection descriptor that is using this particular instance of engine.
 */
public XmppMessageEngine(String objectId, String password, XMLConfiguration config, Logger logger, 
																	ConnectionDescriptor connectionDescriptor) {
	super(objectId, password, config, logger, connectionDescriptor);
	
	connection = null;
	chatManager = null;
	roster = null;
	
	// initialise map with opened chats
	openedChats = new HashMap<EntityBareJid, Chat>();
	
	// compute the random time in seconds after which a roster will be renewed
	long timeForRosterRenewal = (long) ((Math.random() * ((ROSTER_RELOAD_TIME_MAX - ROSTER_RELOAD_TIME_MIN) + 1)) 
			+ ROSTER_RELOAD_TIME_MIN) * 1000;
	
	logger.finest("The roster for " + objectId + " will be renewed every " 
			+ timeForRosterRenewal + "ms.");
	
	
	// timer for roster renewing
	Timer timerForRosterRenewal = new Timer();
	timerForRosterRenewal.schedule(new TimerTask() {
		@Override
		public void run() {
			renewPresenceAndRoster();
		}
	}, timeForRosterRenewal, timeForRosterRenewal);
	
	// enable debugging if desired
	boolean debuggingEnabled = config.getBoolean(CONFIG_PARAM_XMPPDEBUG, CONFIG_DEF_XMPPDEBUG);
	if (debuggingEnabled) {
		SmackConfiguration.DEBUG = debuggingEnabled;
		logger.config("XMPP debugging enabled.");
	}
}
 
Example #7
Source File: XmppFileService.java    From xyTalk-pc with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void requestOfflineFile(org.jivesoftware.smack.packet.Message message) {
	// TODO 向离线文件机器人发送请求
	// 将接收到的离线文件消息,原封不动的发给离线文件机器人 ,
	//	离线机器人接收后,会立即将已存储的文件发过来,同时会发送一条消息回执,发送成功后,删除文件
	//	用户收到回执后,需要对聊天UI进行处理,注意:此时的fromJid是机器人,应处理为实际发送者,即senderFullJid
	Chat chat;
	try {
		chat = ChatManager.getInstanceFor(Launcher.connection).chatWith(JidCreate.entityBareFrom(Launcher.OFFLINEFILEROBOTJID));
        
		chat.send(message); //发送请求到机器人,然后机器人会把文件发给我
		OfflineFile of = (OfflineFile)message.getExtension(OfflineFile.NAMESPACE);
		offlineFileJidMap.put(of.getFileName(), of.getSenderFullJid());
		DebugUtil.debug( "send offlinefile request:"+ message.toXML());	
		
	} catch (XmppStringprepException |NotConnectedException | InterruptedException e) {
		
	}
}
 
Example #8
Source File: MucChatService.java    From xyTalk-pc with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void sendKickMessage(List<Jid> users, String roomId, String name) {
	MucKick mucKick = new MucKick(roomId, name);

	for (int i = 0; i < users.size(); i++) {
		Jid userJid = users.get(i);
		Chat chat;
		chat = ChatManager.getInstanceFor(Launcher.connection).chatWith(userJid.asEntityBareJidIfPossible());
		org.jivesoftware.smack.packet.Message message = new org.jivesoftware.smack.packet.Message();
		message.setType(Type.chat);
		message.addExtension(mucKick);
		message.setBody("被管理员删除出群:"+name);
		try {
			chat.send(message);
			DebugUtil.debug("sendKickMessage:" + message.toXML());
		} catch (NotConnectedException | InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
 
Example #9
Source File: MucChatService.java    From xyTalk-pc with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void sendOfflineInvitationMessage(List<String> users, String roomid, String roomName)
		throws XmppStringprepException {
	// TODO 对离线用户应发送邀请消息,并让服务器存储离线消息,待用户上线后还应对此类消息进行处理
	MucInvitation mi = new MucInvitation(roomid, roomName);

	for (int i = 0; i < users.size(); i++) {
		String userJid = users.get(i);
		Chat chat = ChatManager.getInstanceFor(Launcher.connection).chatWith(JidCreate.entityBareFrom(userJid));
		org.jivesoftware.smack.packet.Message message = new org.jivesoftware.smack.packet.Message();
		message.setType(Type.chat);
		message.addExtension(mi);
		message.setBody("请加入会议");
		try {
			chat.send(message);
			DebugUtil.debug("sendOfflineInvitationMessage:" + message.toXML());
		} catch (NotConnectedException | InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
 
Example #10
Source File: ChatStateManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the current state of the provided chat. This method will send an empty bodied Message
 * stanza with the state attached as a {@link org.jivesoftware.smack.packet.ExtensionElement}, if
 * and only if the new chat state is different than the last state.
 *
 * @param newState the new state of the chat
 * @param chat the chat.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public void setCurrentState(ChatState newState, Chat chat) throws NotConnectedException, InterruptedException {
    if (chat == null || newState == null) {
        throw new IllegalArgumentException("Arguments cannot be null.");
    }
    if (!updateChatState(chat, newState)) {
        return;
    }
    Message message = StanzaBuilder.buildMessage().build();
    ChatStateExtension extension = new ChatStateExtension(newState);
    message.addExtension(extension);

    chat.send(message);
}
 
Example #11
Source File: ChatStateManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
private synchronized boolean updateChatState(Chat chat, ChatState newState) {
    ChatState lastChatState = chatStates.get(chat);
    if (lastChatState != newState) {
        chatStates.put(chat, newState);
        return true;
    }
    return false;
}
 
Example #12
Source File: ChatManager.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
    * Called by smack when the state of a chat changes.
    *
    * @param chat the chat that is concerned by this event.
    * @param state the new state of the chat.
    */
@Override
   public void stateChanged(Chat chat, ChatState state, Message message) {
    Jid participant = chat.getXmppAddressOfChatPartner();
       if (ChatState.composing.equals(state)) {
           composingNotification(participant);
       } else {
       	cancelledNotification(participant, state);
       }
       
   }
 
Example #13
Source File: XmppEndpoint.java    From EDDI with Apache License 2.0 4 votes vote down vote up
@Override
public void newIncomingMessage(EntityBareJid entityBareJid, Message message, Chat chat) {
    log.info("xmpp incoming: {}", message.getBody());
    String senderId = entityBareJid.asEntityBareJidString();
    say(senderId, message.getBody(), chat);
}
 
Example #14
Source File: ChatMarkersManager.java    From Smack with Apache License 2.0 4 votes vote down vote up
private ChatMarkersManager(XMPPConnection connection) {
    super(connection);

    chatManager = ChatManager.getInstanceFor(connection);

    connection.addMessageInterceptor(mb -> mb.addExtension(ChatMarkersElements.MarkableExtension.INSTANCE),
            m -> {
                return OUTGOING_MESSAGE_FILTER.accept(m);
        });

    connection.addSyncStanzaListener(new StanzaListener() {
        @Override
        public void processStanza(Stanza packet)
                throws
                NotConnectedException,
                InterruptedException,
                SmackException.NotLoggedInException {
            final Message message = (Message) packet;

            // Note that this listener is used together with a PossibleFromTypeFilter.ENTITY_BARE_JID filter, hence
            // every message is guaranteed to have a from address which is representable as bare JID.
            EntityBareJid bareFrom = message.getFrom().asEntityBareJidOrThrow();

            final Chat chat = chatManager.chatWith(bareFrom);

            asyncButOrdered.performAsyncButOrdered(chat, new Runnable() {
                @Override
                public void run() {
                    for (ChatMarkersListener listener : incomingListeners) {
                        if (ChatMarkersElements.MarkableExtension.from(message) != null) {
                            listener.newChatMarkerMessage(ChatMarkersState.markable, message, chat);
                        }
                        else if (ChatMarkersElements.ReceivedExtension.from(message) != null) {
                            listener.newChatMarkerMessage(ChatMarkersState.received, message, chat);
                        }
                        else if (ChatMarkersElements.DisplayedExtension.from(message) != null) {
                            listener.newChatMarkerMessage(ChatMarkersState.displayed, message, chat);
                        }
                        else if (ChatMarkersElements.AcknowledgedExtension.from(message) != null) {
                            listener.newChatMarkerMessage(ChatMarkersState.acknowledged, message, chat);
                        }
                    }
                }
            });

        }
    }, INCOMING_MESSAGE_FILTER);

    serviceDiscoveryManager = ServiceDiscoveryManager.getInstanceFor(connection);
}
 
Example #15
Source File: ChatStateIntegrationTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
private void  composingListener(Chat chat, ChatState state, Message message) {
    if (state.equals(ChatState.composing)) {
        composingSyncPoint.signal();
    }
}
 
Example #16
Source File: ChatStateIntegrationTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
private void activeListener(Chat chat, ChatState state, Message message) {
    if (state.equals(ChatState.active)) {
        activeSyncPoint.signal();
    }
}
 
Example #17
Source File: XmppFileService.java    From xyTalk-pc with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void sendOfflineFileMsg(String fileFullPath, String reciveBareJid,String uuid,boolean toRobot) {
	String fileType;
	String fileName = fileFullPath.substring(fileFullPath.lastIndexOf(System.getProperty("file.separator"))+1);

	boolean isImage;
	if (fileFullPath.lastIndexOf(".")<0){
		isImage = false;
	}else{
		String type = MimeTypeUtil.getMime(fileFullPath.substring(fileFullPath.lastIndexOf(".")));
		isImage = type.startsWith("image/");
	}
	
	if (isImage){
		fileType = "image";
	}
	else{
		fileType = "file";
	}
	
	OfflineFile of = null;
	OfflineFileRobot ofr = null; 
	
	if (toRobot){
		ofr = new OfflineFileRobot(UserCache.CurrentBareJid,reciveBareJid,fileType,uuid,fileName);
	}else{
		of = new OfflineFile(UserCache.CurrentBareJid,reciveBareJid,fileType,uuid,fileName);
	}
		
	
	Chat chat;
	try {
		chat = ChatManager.getInstanceFor(Launcher.connection).chatWith(JidCreate.entityBareFrom(reciveBareJid));
        org.jivesoftware.smack.packet.Message message = new org.jivesoftware.smack.packet.Message();
        message.setType(Type.chat);
        
        if (toRobot){
	        message.addExtension(ofr);	        	
        }else{
	        message.addExtension(of);	        	
        }

        message.setBody(UserCache.CurrentUserRealName + " 发给您离线文件,即将接收:"+fileName);
		chat.send(message);
		DebugUtil.debug( "send offlinefile msg:"+ message.toXML());	
		
	} catch (XmppStringprepException |NotConnectedException | InterruptedException e) {
		
	}
}
 
Example #18
Source File: XmppMessageEngine.java    From vicinity-gateway-api with GNU General Public License v3.0 3 votes vote down vote up
/**
 * This method gets executed when a new message for this object ID arrives. It then gets forwarded to its 
 * {@link eu.bavenir.ogwapi.commons.ConnectionDescriptor ConnectionDescriptor}.
 * 
 * @param from XMPP JID of the originating object (with domain).
 * @param xmppMessage Received XMPP message.
 * @param chat A chat in which the messages were exchanged.
 */
private void processMessage(EntityBareJid from, Message xmppMessage, Chat chat) {
	
	// try to find an opened chat
	Chat openedChat = openedChats.get(from);
	
	if (openedChat == null) {

		openedChats.put(from, chat);
	}

	connectionDescriptor.processIncommingMessage(from.getLocalpart().toString(), xmppMessage.getBody());
}
 
Example #19
Source File: ChatMarkersListener.java    From Smack with Apache License 2.0 2 votes vote down vote up
/**
 * Called in ChatMarkersManager when a new message with a markable tag arrives.
 *
 * @param chatMarkersState the current state of the message.
 * @param message          the new incoming message with a markable XML tag.
 * @param chat             associated to the message. This element can be <code>NULL</code>.
 */
void newChatMarkerMessage(ChatMarkersState chatMarkersState, Message message, Chat chat);
 
Example #20
Source File: ChatStateListener.java    From Smack with Apache License 2.0 2 votes vote down vote up
/**
 * Fired when the state of a chat with another user changes.
 *
 * @param chat the chat in which the state has changed.
 * @param state the new state of the participant.
 * @param message the message carrying the chat state.
 */
void stateChanged(Chat chat, ChatState state, Message message);