org.jivesoftware.smack.Chat Java Examples

The following examples show how to use org.jivesoftware.smack.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: XHTMLExtensionTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
    * Low level API test.
    * This is a simple test to use with an XMPP client and check if the client receives the message
    * 1. User_1 will send a message with formatted text (XHTML) to user_2
    */
   public void testSendSimpleXHTMLMessage() {
// User1 creates a chat with user2
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);

// User1 creates a message to send to user2
Message msg = new Message();
msg.setSubject("Any subject you want");
msg.setBody("Hey John, this is my new green!!!!");
// Create a XHTMLExtension Package and add it to the message
XHTMLExtension xhtmlExtension = new XHTMLExtension();
xhtmlExtension.addBody(
"<body><p style='font-size:large'>Hey John, this is my new <span style='color:green'>green</span><em>!!!!</em></p></body>");
msg.addExtension(xhtmlExtension);

// User1 sends the message that contains the XHTML to user2
try {
    chat1.sendMessage(msg);
    Thread.sleep(200);
}
catch (Exception e) {
    fail("An error occurred sending the message with XHTML");
}
   }
 
Example #2
Source File: Friend.java    From League-of-Legends-XMPP-Chat-Library with MIT License 6 votes vote down vote up
private Chat getChat() {
	if (chat == null) {
		chat = ChatManager.getInstanceFor(con).createChat(getUserId(),
				new MessageListener() {

					@Override
					public void processMessage(Chat c, Message m) {
						if (chat != null && listener != null) {
							listener.onMessage(instance, m.getBody());
						}

					}
				});
	}
	return chat;
}
 
Example #3
Source File: ChatActivity.java    From weixin with Apache License 2.0 6 votes vote down vote up
/**
 * 发送消息
 */
private void sendMsg() {
	new Thread(new Runnable() {

		@Override
		public void run() {
			Chat chat = XmppManager.getInstance().getFriendChat(user.getUserAccount(), null);

			//	friend为好友名,不是JID;listener 监听器可以传null,利用聊天窗口对象调用sendMessage发送消息
			//	这里sendMessage我传的是一个JSON字符串,以便更灵活的控制,发送消息完成~
			try {
				// String msgjson = "{\"messageType\":\""+messageType+"\",\"chanId\":\""+chanId+"\",\"chanName\":\""+chanName+"\"}";
				// chat.sendMessage(msgjson);

				chat.sendMessage(msg);
				handler.sendEmptyMessage(HandlerTypeUtils.WX_HANDLER_TYPE_LOAD_DATA_SUCCESS);
			} catch (XMPPException e) {
				handler.sendEmptyMessage(HandlerTypeUtils.WX_HANDLER_TYPE_LOAD_DATA_FAIL);
				e.printStackTrace();
			}
		}
	}).start();
}
 
Example #4
Source File: SmackConnection.java    From SmackAndroidDemo with Apache License 2.0 6 votes vote down vote up
@Override
public void processMessage(Chat chat, Message message) {
    Log.i(TAG, "processMessage()");
    if (message.getType().equals(Message.Type.chat) || message.getType().equals(Message.Type.normal)) {
        if (message.getBody() != null) {
            Intent intent = new Intent(SmackService.NEW_MESSAGE);
            intent.setPackage(mApplicationContext.getPackageName());
            intent.putExtra(SmackService.BUNDLE_MESSAGE_BODY, message.getBody());
            intent.putExtra(SmackService.BUNDLE_FROM_JID, message.getFrom());
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
                intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
            }
            mApplicationContext.sendBroadcast(intent);
            Log.i(TAG, "processMessage() BroadCast send");
        }
    }
}
 
Example #5
Source File: XmppManager.java    From weixin with Apache License 2.0 6 votes vote down vote up
/**
 * 获取或创建聊天窗口
 * 
 * @param friend 好友名
 * @param listenter 聊天監聽器
 * @return
 */
public Chat getFriendChat(String friend, MessageListener listenter) {
	if (getConnection() == null)
		return null;
	/** 判断是否创建聊天窗口 */
	for (String fristr : chatManage.keySet()) {
		if (fristr.equals(friend)) {
			// 存在聊天窗口,则返回对应聊天窗口
			return chatManage.get(fristr);
		}
	}
	/** 创建聊天窗口 */
	Chat chat = getConnection().getChatManager().createChat(friend + "@" + getConnection().getServiceName(), listenter);
	/** 添加聊天窗口到chatManage */
	chatManage.put(friend, chat);
	return chat;
}
 
Example #6
Source File: XMPPService.java    From jolie with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Identifier( "sendMessage" )
@RequestResponse
public void _sendMessage( Value request )
	throws FaultException {
	Chat chat = getChat( request.getFirstChild( "to" ).strValue() );
	try {
		chat.sendMessage( request.strValue() );
	} catch( XMPPException e ) {
		throw new FaultException( e );
	}
}
 
Example #7
Source File: XMPPConsole.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void processMessage(Chat chat, Message msg) {
    logger.debug("Received XMPP message: {} of type {}", msg.getBody(), msg.getType());
    if (msg.getType() == Message.Type.error || msg.getBody() == null) {
        return;
    }
    String cmd = msg.getBody();
    String[] args = cmd.split(" ");
    ConsoleInterpreter.handleRequest(args, new ChatConsole(chat));
}
 
Example #8
Source File: Connection.java    From HippyJava with MIT License 5 votes vote down vote up
public void sendPM(String message, String to) throws XMPPException {
    Chat c;
    if (cache.containsKey(to))
        c = cache.get(to);
    else {
        c = XMPP.getChatManager().createChat(to, this);
        cache.put(to, c);
    }
    c.sendMessage(message);
}
 
Example #9
Source File: SingleUserChat.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void sendMessage(Message message) throws XMPPException {
  Chat currentChat;

  synchronized (SingleUserChat.this) {
    currentChat = chat;

    chat.sendMessage(message);
    message.setFrom(userJID);
  }

  chatStateListener.processMessage(currentChat, message);
}
 
Example #10
Source File: SingleUserChat.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Initializes the chat so that it is possible to exchange messages with the participant.
 *
 * @param userJID {@link JID} of the local user
 * @param chat {@link Chat} object from Smack, contains the recipient
 * @param chatStateManager {@link ChatStateManager} of the current connection
 */
synchronized void initChat(String userJID, Chat chat, ChatStateManager chatStateManager) {
  if (this.chat != null) this.chat.removeMessageListener(chatStateListener);

  this.chat = chat;
  this.chat.addMessageListener(chatStateListener);
  this.chatStateManager = chatStateManager;
  this.userJID = userJID;
}
 
Example #11
Source File: SingleUserChat.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void processMessage(Chat chat, Message message) {
  log.trace(
      this + " : received message from: " + message.getFrom() + " : " + message.getBody());

  if (message.getFrom() == null || message.getBody() == null) return;

  addHistoryEntry(new ChatElement(message, new Date(System.currentTimeMillis())));

  notifyJIDMessageReceived(new JID(message.getFrom()), message.getBody());
}
 
Example #12
Source File: SingleUserChatService.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void processMessage(Chat chat, Message message) {
  if (!message.getBodies().isEmpty()) {

    log.info(
        "chat created between "
            + userJID
            + " <->"
            + chat.getParticipant()
            + ", created local: "
            + false);

    JID jid = new JID(chat.getParticipant());
    SingleUserChat singleUserChat = currentChats.get(jid);

    boolean exists = true;
    if (singleUserChat == null) {
      exists = false;
      singleUserChat = createChat(chat);

      /*
       * The SUC has registered for messages now. As this happened
       * after the notification of listeners started, it won't
       * receive the current, first message. Thus, we have to add
       * it manually.
       */
      singleUserChat.addHistoryEntry(new ChatElement(message, new Date()));
    }

    // do not inform the listener because the chat is reused if
    if (exists) {
      log.info("skipping notification of listeners because the chat already exists");
      return;
    }

    notifyChatCreated(singleUserChat, false);
  }
}
 
Example #13
Source File: MessengerService.java    From KlyphMessenger with MIT License 5 votes vote down vote up
private void onMessageReceived(Chat chat, org.jivesoftware.smack.packet.Message message)
{
	if (message.getBody() != null)
	{
		Log.d(TAG, "processMessage " + chat.getThreadID() + " " + message.getBody() + " " + message.getTo());
		onMessageReceived(message);
		messageEventManager.sendDeliveredNotification(message.getFrom(), message.getPacketID());
	}
}
 
Example #14
Source File: MessengerService.java    From KlyphMessenger with MIT License 5 votes vote down vote up
@Override
public void onCreate()
{
	Log.d(TAG, "onCreate");

	if (instance != null)
		Log.d(TAG, "instance is already defined !");

	instance = this;

	notificationsEnabled = MessengerPreferences.areNotificationsEnabled();
	ringtone = MessengerPreferences.getNotificationRingtone();
	ringtoneUri = MessengerPreferences.getNotificationRingtoneUri();
	vibrateEnabled = MessengerPreferences.isNotificationVibrationEnabled();

	chats = new ArrayList<Chat>();
	roster = new ArrayList<PRosterEntry>();
	savedMessages = new ArrayList<org.jivesoftware.smack.packet.Message>();
	pendingActions = new LinkedHashMap<String, Object>();

	configure(ProviderManager.getInstance());

	Connection.addConnectionCreationListener(new ConnectionCreationListener() {
		public void connectionCreated(Connection connection)
		{
			reconnectionManager = new ReconnectionManager(connection, ConnectionState.getInstance(MessengerService.this).isOnline());
			connection.addConnectionListener(reconnectionManager);
		}
	});

	registerReceiver(new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent)
		{
			Log.i(TAG, "Connection status change to " + ConnectionState.getInstance(MessengerService.this).isOnline());
			onConnectivityChange();
		}
	}, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));

	connect();
}
 
Example #15
Source File: TaxiChatManagerListener.java    From weixin with Apache License 2.0 5 votes vote down vote up
@Override
public void chatCreated(Chat chat, boolean arg1) {
	chat.addMessageListener(new MessageListener() {

		@Override
		public void processMessage(Chat arg0, Message msg) {//登录用户
			StringUtils.parseName(XmppManager.getInstance().getConnection().getUser());
			//发送消息用户
			msg.getFrom();
			//消息内容
			String body = msg.getBody();
			System.out.println("body--->" + body);
			boolean left = body.substring(0, 1).equals("{");
			boolean right = body.substring(body.length() - 1, body.length()).equals("}");
			if (left && right) {
				try {
					JSONObject obj = new JSONObject(body);
					String type = obj.getString("messageType");
					String chanId = obj.getString("chanId");
					String chanName = obj.getString("chanName");

					System.out.println("---body--->" + body);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			
			
			Intent intent = new Intent("net.cgt.weixin.chat");
			intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);// 包含从未启动过的应用
			intent.putExtra("from", msg.getFrom());
			intent.putExtra("body", body);
			GlobalParams.activity.sendBroadcast(intent);
		}
	});
}
 
Example #16
Source File: SmackConnection.java    From SmackAndroidDemo with Apache License 2.0 5 votes vote down vote up
private void sendMessage(String body, String toJid) {
    Log.i(TAG, "sendMessage()");
    Chat chat = ChatManager.getInstanceFor(mConnection).createChat(toJid, this);
    try {
        chat.sendMessage(body);
    } catch (SmackException.NotConnectedException | XMPPException e) {
        e.printStackTrace();
    }
}
 
Example #17
Source File: IMAppender.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Send the contents of the cyclic buffer as an IM message.
 */
protected void sendBuffer() {
    try {
        final StringBuilder buf = new StringBuilder();

        final int len = cb.length();
        for (int i = 0; i < len; i++) {
            final LoggingEvent event = cb.get();
            buf.append(layout.format(event));
            // if layout doesn't handle exception, the appender has to do it
            if (layout.ignoresThrowable()) {
                final String[] s = event.getThrowableStrRep();
                if (s != null) {
                    for (int j = 0; j < s.length; j++) {
                        buf.append(Layout.LINE_SEP);
                        buf.append(s[j]);
                    }
                }
            }
        }

        if (chatroom) {
            groupchat.sendMessage(buf.toString());
        } else {
            final Iterator iter = chats.iterator();
            while (iter.hasNext()) {
                final Chat chat = (Chat) iter.next();
                chat.sendMessage(buf.toString());
            }
        }

    } catch (final Exception e) {
        errorHandler.error("Could not send message in IMAppender [" + name + "]", e, ErrorCode.GENERIC_FAILURE);
    }
}
 
Example #18
Source File: XMPPService.java    From jolie with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Chat getChat( String userJID ) {
	Chat chat = chats.get( userJID );
	if( chat == null ) {
		chat = connection.getChatManager().createChat(
			userJID,
			( chat1, message ) -> {
				// TODO redirect to embedder
			} );
		chats.put( userJID, chat );
	}

	return chat;
}
 
Example #19
Source File: IMAppender.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Send the contents of the cyclic buffer as an IM message.
 */
protected void sendBuffer() {
    try {
        final StringBuilder buf = new StringBuilder();

        final int len = cb.length();
        for (int i = 0; i < len; i++) {
            final LoggingEvent event = cb.get();
            buf.append(layout.format(event));
            // if layout doesn't handle exception, the appender has to do it
            if (layout.ignoresThrowable()) {
                final String[] s = event.getThrowableStrRep();
                if (s != null) {
                    for (int j = 0; j < s.length; j++) {
                        buf.append(Layout.LINE_SEP);
                        buf.append(s[j]);
                    }
                }
            }
        }

        if (chatroom) {
            groupchat.sendMessage(buf.toString());
        } else {
            final Iterator iter = chats.iterator();
            while (iter.hasNext()) {
                final Chat chat = (Chat) iter.next();
                chat.sendMessage(buf.toString());
            }
        }

    } catch (final Exception e) {
        errorHandler.error("Could not send message in IMAppender [" + name + "]", e, ErrorCode.GENERIC_FAILURE);
    }
}
 
Example #20
Source File: XMPPConsole.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
public ChatConsole(Chat chat) {
    this.chat = chat;
    this.sb = new StringBuffer();
}
 
Example #21
Source File: XmppService.java    From yiim_v2 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void onCreate() {
	// TODO Auto-generated method stub
	super.onCreate();
	mHandlerProxy = new YiHandlerProxy(this, this);
	mXmppConnection = null;
	mXmppBinder = new XmppBinder(this);

	NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
	mNotificationManager = new com.ikantech.yiim.common.NotificationManager(
			this, mXmppBinder, notificationManager);
	mKeyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);

	mAVCallManager = new AVCallManager(this);

	mSoundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);
	mSoundIds = new HashMap<String, Integer>();
	mSoundIds.put(MSG_SOUND, mSoundPool.load(this, R.raw.office, 1));

	mVibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);

	mLocker = new Object();
	mMultiUserChats = new HashMap<String, MultiUserChat>();
	mChats = new HashMap<String, Chat>();
	mNeedReInitMultiChatRooms = new ArrayList<String>();

	mMsgReceivedBroadcast = new MsgReceivedBroadcast();
	IntentFilter intentFilter = new IntentFilter();
	intentFilter.addAction(Const.NOTIFY_MSG_RECEIVED_OR_SENT);
	registerReceiver(mMsgReceivedBroadcast, intentFilter);

	mNetworkBroadcastReceiver = new NativeNetworkBroadcastReceiver();
	IntentFilter netIntentFilter = new IntentFilter();
	netIntentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
	registerReceiver(mNetworkBroadcastReceiver, netIntentFilter);

	Connection
			.addConnectionCreationListener(new ConnectionCreationListener() {
				@Override
				public void connectionCreated(Connection connection) {
					// TODO Auto-generated method stub
					initService(connection);
				}
			});

	getHandler().removeMessages(MSG_NETWORK_CONNECTED);
	getHandler().sendEmptyMessageDelayed(MSG_NETWORK_CONNECTED, 1300);
}
 
Example #22
Source File: Connection.java    From HippyJava with MIT License 4 votes vote down vote up
@Override
public void processMessage(Chat arg0, Message arg1) {
    MessageRecivedEvent event = new MessageRecivedEvent(null, arg1);
    HippyJava.events.callEvent(event);
}
 
Example #23
Source File: MPAuthenticationProvider.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Read the PIN number sent by the user as the reply.
 *
 * @param connection
 * @param userName
 * @return
 */
public boolean getUserResponse(XMPPConnection connection, String userName) {

    String response = null;
    Presence presence = connection.getRoster().getPresence(userName);

    if (presence.isAvailable()) {
        try {

            ChatManager chatManager = connection.getChatManager();
            Chat chat = chatManager.createChat(userName, null);
            PacketFilter filter =
                    new AndFilter(new PacketTypeFilter(Message.class), new FromContainsFilter(userName));
            XmppResponseListener chatListener = new XmppResponseListener();
            connection.addPacketListener(chatListener, filter);

            if (isPINEnabled) {

                chat.sendMessage("Please reply with your PIN Number here.");

                if (log.isInfoEnabled()) {
                    log.info("User PIN is sent to the user and awaiting for the response.");
                }

                while (!chatListener.isResponseReceived()) {
                    Thread.sleep(100);
                }

                response = chatListener.getResponse();

                if (response != null) {
                    return userPIN.contentEquals(response.trim());
                }
            } else {
                chat.sendMessage(
                        "You are about to get authenticated for your OpenID. Do you want to continue: [Yes] or [No]");

                if (log.isInfoEnabled()) {
                    log.info("User PIN is sent to the user and awaiting for the response.");
                }

                while (!chatListener.isResponseReceived()) {
                    Thread.sleep(100);
                }

                response = chatListener.getResponse();

                if (response != null) {
                    if ("YES".equalsIgnoreCase(response.trim())) {
                        return true;
                    } else if ("NO".equalsIgnoreCase(response.trim())) {
                        return false;
                    } else {
                        pinDisabledResponse = false;
                        return false;
                    }
                }
            }

        } catch (Exception e) {
            log.error("Error while getting user response", e);
        }
    } else {
        return false;
    }
    return false;

}
 
Example #24
Source File: ChatController.java    From olat with Apache License 2.0 4 votes vote down vote up
protected void setChatManager(final Chat chatManager) {
    this.chatManager = chatManager;
}
 
Example #25
Source File: ChatController.java    From olat with Apache License 2.0 4 votes vote down vote up
protected Chat getChatManager() {
    return chatManager;
}
 
Example #26
Source File: SingleUserChat.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void stateChanged(Chat chat, ChatState state) {
  notifyJIDStateChanged(new JID(chat.getParticipant()), state);
}
 
Example #27
Source File: SingleUserChatService.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Creates a new {@link SingleUserChat} with the given {@link Chat}.
 *
 * @param chat {@link Chat} which specifies the participant
 * @return a new {@link SingleUserChat} if it has not been created yet, otherwise the existing
 *     {@link SingleUserChat} is returned.
 */
public synchronized SingleUserChat createChat(Chat chat) {

  JID jid = new JID(chat.getParticipant());

  SingleUserChat createdChat = currentChats.get(jid);

  if (createdChat == null) {
    log.trace("creating new chat between " + userJID + " <->" + jid);

    createdChat = new SingleUserChat();

    createdChat.initChat(userJID, chat, chatStateManager);
    createdChat.setConnected(true);
    currentChats.put(jid, createdChat);
  }

  return createdChat;
}
 
Example #28
Source File: SingleUserChatService.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void chatCreated(Chat chat, boolean createdLocally) {
  synchronized (SingleUserChatService.this) {
    chat.addMessageListener(messageListener);
  }
}
 
Example #29
Source File: MessengerService.java    From KlyphMessenger with MIT License 4 votes vote down vote up
private void sendMessageTo(Bundle bundle)
{
	if (!connection.isConnected())
	{
		addPendingAction(ACTION_SEND_MSG, bundle);
	}
	else
	{
		String to = bundle.getString("to");
		String message = bundle.getString("message");

		to = "-" + to + "@chat.facebook.com";
		Log.d(TAG, "sendMessage to " + to + " " + message);
		Chat toChat = null;

		for (Chat chat : chats)
		{
			if (chat.getParticipant().equals(to))
			{
				toChat = chat;
			}
		}

		if (toChat == null)
		{
			toChat = createChat(to);
		}
		
		org.jivesoftware.smack.packet.Message msg = new org.jivesoftware.smack.packet.Message();
		msg.setBody(message);
		msg.setTo(to);
		msg.setType(org.jivesoftware.smack.packet.Message.Type.chat);
		msg.setThread(toChat.getThreadID());
		
		// Add to the message all the notifications requests (offline, delivered, displayed, composing)
	    MessageEventManager.addNotificationsRequests(msg, true, true, true, true);
	    DeliveryReceiptManager.addDeliveryReceiptRequest(msg);
	    
		try
		{
			toChat.sendMessage(msg);
		}
		catch (XMPPException e)
		{
			e.printStackTrace();
		}
	}
}
 
Example #30
Source File: ChatController.java    From olat with Apache License 2.0 4 votes vote down vote up
protected void setChatManager(final Chat chatManager) {
    this.chatManager = chatManager;
}