Example #1
0
  public void sendMessage(String text) {
    final Message message = new Message();

    if (threadID == null) {
      threadID = StringUtils.randomString(6);
    }
    message.setThread(threadID);

    // Set the body of the message using typedMessage
    message.setBody(text);

    // IF there is no body, just return and do nothing
    if (!ModelUtil.hasLength(text)) {
      return;
    }

    // Fire Message Filters
    SparkManager.getChatManager().filterOutgoingMessage(this, message);

    // Fire Global Filters
    SparkManager.getChatManager().fireGlobalMessageSentListeners(this, message);

    sendMessage(message);

    sendNotification = true;
  }
Example #2
0
 @SuppressWarnings("unchecked")
 public void receivesAMessage(Matcher<? super String> messageMatcher)
     throws InterruptedException {
   final Message message = messages.poll(5, TimeUnit.SECONDS);
   assertThat("Message", message, is(notNullValue()));
   assertThat(message.getBody(), messageMatcher);
 }
    @Override
    public void processPacket(final Stanza packet) {
      if (packet instanceof org.jivesoftware.smack.packet.Message) {
        org.jivesoftware.smack.packet.Message xmppMessage =
            (org.jivesoftware.smack.packet.Message) packet;
        Map<String, ?> mappedHeaders = headerMapper.toHeadersFromRequest(xmppMessage);

        String messageBody = xmppMessage.getBody();
        /*
         * Since there are several types of chat messages with different ChatState (e.g., composing, paused etc)
         * we need to perform further validation since for now we only support messages that have
         * content (e.g., Use A says 'Hello' to User B). We don't yet support messages with no
         * content (e.g., User A is typing a message for User B etc.).
         * See https://jira.springsource.org/browse/INT-1728
         * Also see: packet.getExtensions()
         */
        if (StringUtils.hasText(messageBody)) {
          Object payload = (extractPayload ? messageBody : xmppMessage);

          AbstractIntegrationMessageBuilder<?> messageBuilder =
              ChatMessageListeningEndpoint.this
                  .getMessageBuilderFactory()
                  .withPayload(payload)
                  .copyHeaders(mappedHeaders);
          sendMessage(messageBuilder.build());
        }
      }
    }
Example #4
0
  /**
   * @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
    }
  }
Example #5
0
  private void processOfflineMessages() {
    Log.i(LOG_TAG, "Begin retrieval of offline messages from server");

    OfflineMessageManager offlineMessageManager = new OfflineMessageManager(con);
    try {
      if (!offlineMessageManager.supportsFlexibleRetrieval()) {
        Log.d(LOG_TAG, "Offline messages not supported");
        return;
      }

      List<Message> msgs = offlineMessageManager.getMessages();
      for (Message msg : msgs) {
        Intent intent =
            new Intent(MessageService.ACTION_MESSAGE_RECEIVED, null, context, MessageService.class);
        intent.putExtra(
            MessageService.EXTRA_DATA_NAME_FROM, StringUtils.parseBareAddress(msg.getFrom()));
        intent.putExtra(MessageService.EXTRA_DATA_NAME_MESSAGE_BODY, msg.getBody());

        context.startService(intent);
      }

      offlineMessageManager.deleteMessages();
    } catch (Exception e) {
      Log.e(LOG_TAG, "handle offline messages error ", e);
    }

    Log.i(LOG_TAG, "End of retrieval of offline messages from server");
  }
Example #6
0
    @Override
    public void processMessage(Chat chat, org.jivesoftware.smack.packet.Message message) {

      if (message.getBody() == null) {
        // TODO: investigate why some message bodies are null
        return;
      }

      // TODO: implement builder pattern for domain Message and Chat classes
      final Message m = new Message();
      m.setTimestamp(System.currentTimeMillis());
      m.setBody(message.getBody());
      m.setLocal(false);

      Log.d(
          TAG,
          String.format(
              "chatId %s message <%s> received from %s",
              currentChatId, m.getBody(), chat.getParticipant()));

      updateChatTimestamp(pocChat.getId());

      ContentValues values = new ContentValues();
      values.put(SQLiteHelper.COLUMN_BODY, m.getBody());
      values.put(SQLiteHelper.COLUMN_TIMESTAMP, m.getTimestamp()); // current time
      values.put(SQLiteHelper.COLUMN_IS_LOCAL, m.isLocal() ? 1 : 0);
      values.put(SQLiteHelper.COLUMN_CHAT_ID, pocChat.getId());

      // once insert is successful, loader updates the list automatically
      context.getContentResolver().insert(MessageProvider.URI_MESSAGES, values);

      // show the toast regardless if messages UI is opened
      showToast(context, m.getBody());
    }
  public static Map<String, ArrayList<Message>> getOfflineMegs() {

    Map<String, ArrayList<Message>> offlines = new HashMap<String, ArrayList<Message>>();

    try {
      Iterator<Message> ites = MXmppConnManager.getInstance().getOffMsgManager().getMessages();

      while (ites.hasNext()) {

        Message message = ites.next();

        String fromUser = message.getFrom().split("/")[0];

        if (offlines.containsKey(fromUser)) {

          offlines.get(fromUser).add(message);

        } else {

          ArrayList<Message> temp = new ArrayList<Message>();

          temp.add(message);

          offlines.put(fromUser, temp);
        }
      }

    } catch (XMPPException e) {
      e.printStackTrace();
      return null;
    }

    return offlines;
  }
  private static Message rawMessage(MessageContent content, Chat chat, boolean encrypted) {
    Message smackMessage = new Message();

    // text
    String text = content.getPlainText();
    if (!text.isEmpty()) smackMessage.setBody(content.getPlainText());

    // attachment
    MessageContent.Attachment att = content.getAttachment().orElse(null);
    if (att != null) {
      OutOfBandData oobData =
          new OutOfBandData(att.getURL().toString(), att.getMimeType(), att.getLength(), encrypted);
      smackMessage.addExtension(oobData);

      MessageContent.Preview preview = content.getPreview().orElse(null);
      if (preview != null) {
        String data = EncodingUtils.bytesToBase64(preview.getData());
        BitsOfBinary bob = new BitsOfBinary(preview.getMimeType(), data);
        smackMessage.addExtension(bob);
      }
    }

    // group command
    if (chat instanceof KonGroupChat) {
      KonGroupChat groupChat = (KonGroupChat) chat;
      KonGroupData gid = groupChat.getGroupData();
      MessageContent.GroupCommand groupCommand = content.getGroupCommand().orElse(null);
      smackMessage.addExtension(
          groupCommand != null
              ? ClientUtils.groupCommandToGroupExtension(groupChat, groupCommand)
              : new GroupExtension(gid.id, gid.owner.string()));
    }

    return smackMessage;
  }
  @SuppressWarnings("rawtypes")
  @Test
  public void withHeaderMapper() throws Exception {
    Object pollingConsumer = context.getBean("withHeaderMapper");
    assertTrue(pollingConsumer instanceof PollingConsumer);
    assertEquals(headerMapper, TestUtils.getPropertyValue(pollingConsumer, "handler.headerMapper"));
    MessageChannel channel = context.getBean("outboundEventChannel", MessageChannel.class);
    Message<?> message =
        MessageBuilder.withPayload("hello")
            .setHeader(XmppHeaders.TO, "oleg")
            .setHeader("foobar", "foobar")
            .build();
    XMPPConnection connection = context.getBean("testConnection", XMPPConnection.class);

    doAnswer(
            invocation -> {
              Object[] args = invocation.getArguments();
              org.jivesoftware.smack.packet.Message xmppMessage =
                  (org.jivesoftware.smack.packet.Message) args[0];
              assertEquals("oleg", xmppMessage.getTo());
              assertEquals("foobar", JivePropertiesManager.getProperty(xmppMessage, "foobar"));
              return null;
            })
        .when(connection)
        .sendStanza(Mockito.any(org.jivesoftware.smack.packet.Message.class));

    channel.send(message);

    verify(connection, times(1))
        .sendStanza(Mockito.any(org.jivesoftware.smack.packet.Message.class));
    Mockito.reset(connection);
  }
    /**
     * Returns <tt>true</tt> if <tt>packet</tt> is a <tt>Message</tt> and false otherwise.
     *
     * @param packet the packet that we need to check.
     * @return <tt>true</tt> if <tt>packet</tt> is a <tt>Message</tt> and false otherwise.
     */
    public boolean accept(Packet packet) {
      if (!(packet instanceof org.jivesoftware.smack.packet.Message)) return false;

      org.jivesoftware.smack.packet.Message msg = (org.jivesoftware.smack.packet.Message) packet;

      return !msg.getType().equals(org.jivesoftware.smack.packet.Message.Type.groupchat);
    }
Example #11
0
  @Override
  public void processPacket(Packet packet) {
    Session session;

    Message message = (Message) packet;

    if (message.getType() == Message.Type.chat) {
      String sessionId = message.getFrom();
      String text = message.getBody();

      if (!sessionManager.hasSession(sessionId)) {
        session = sessionManager.createSession(sessionId, this);
        session.setProperty("xmppDebugDestination", sessionId);
        session.setProperty("xmppDestination", sessionId);
      } else {
        session = sessionManager.getSession(sessionId);
      }

      if (text.startsWith("d:")) {
        System.out.println(
            "Setting debug for sessionID (" + sessionId + ") to " + text.substring(2));
        session.setProperty("xmppDebugDestination", text.substring(2));
      }
      if (text.startsWith("D:")) {
        session.setProperty("xmppDebugDestination", "*****@*****.**");
        System.out.println(
            "Setting debug for sessionID (" + sessionId + ") to [email protected]");
      } else {
        session.pushInput(text);
      }
    }
  }
Example #12
0
    @Override
    public void processMessage(Chat chat, Message message) {
      String from = message.getFrom();
      String text = message.getBody();
      System.out.printf("From %1$s: %2$s\n", from, text);

      client.notifyMessageRecieved(transform(message));
    }
Example #13
0
 /**
  * Sends a message to the other chat participant. The thread ID, recipient, and message type of
  * the message will automatically set to those of this chat.
  *
  * @param message the message to send.
  * @throws XMPPException if an error occurs sending the message.
  */
 public void sendMessage(Message message) throws XMPPException {
   // Force the recipient, message type, and thread ID since the user elected
   // to send the message through this chat object.
   message.setTo(participant);
   message.setType(Message.Type.chat);
   message.setThread(threadID);
   chatManager.sendMessage(this, message);
 }
Example #14
0
 public final void processPacket(Packet packet) {
   Message msg = (Message) packet;
   MultiUserChat.this.subject = msg.getSubject(null);
   MultiUserChat multiUserChat = MultiUserChat.this;
   msg.getSubject(null);
   String str = msg.from;
   MultiUserChat.access$200$42885ab1(multiUserChat);
 }
Example #15
0
 public void addToTranscript(String to, String from, String body, Date date) {
   final Message newMessage = new Message();
   newMessage.setTo(to);
   newMessage.setFrom(from);
   newMessage.setBody(body);
   newMessage.setProperty("date", date);
   transcript.add(newMessage);
 }
Example #16
0
 private void sendFeature(String account, String user, String session, Feature feature) {
   Message message = new Message(user, Message.Type.normal);
   message.setThread(session);
   message.addExtension(feature);
   try {
     ConnectionManager.getInstance().sendStanza(account, message);
   } catch (NetworkException e) {
   }
 }
Example #17
0
        public void processMessage(Message message)
        {
            for (Chat chat = chatManager.getThreadChat(message.getThread()); chat == null || !updateChatState(chat, ChatState.active);)
            {
                return;
            }

            message.addExtension(new ChatStateExtension(ChatState.active));
        }
Example #18
0
 public void sendChatMessage(String to, String body) throws SmackInvocationException {
   Message message = new Message(to, Message.Type.chat);
   message.setBody(body);
   try {
     con.sendPacket(message);
   } catch (NotConnectedException e) {
     throw new SmackInvocationException(e);
   }
 }
 /**
  * Adds an XHTML body to the message.
  *
  * @param message the message that will receive the XHTML body
  * @param body the string to add as an XHTML body to the message
  */
 public static void addBody(Message message, String body) {
   XHTMLExtension xhtmlExtension = (XHTMLExtension) message.getExtension("html", namespace);
   if (xhtmlExtension == null) {
     // Create an XHTMLExtension and add it to the message
     xhtmlExtension = new XHTMLExtension();
     message.addExtension(xhtmlExtension);
   }
   // Add the required bodies to the message
   xhtmlExtension.addBody(body);
 }
Example #20
0
  public void broadcast() throws XMPPException {

    Message newmsg = new Message();
    newmsg.setTo("*****@*****.**");
    newmsg.setSubject("重要通知");
    newmsg.setBody("今天下午2点60分有会!");
    newmsg.setType(Message.Type.headline); // normal支持离线
    connection.sendPacket(newmsg);
    connection.disconnect();
  }
  /**
   * Sends a roster to userID. All the entries of the roster will be sent to the target user.
   *
   * @param roster the roster to send
   * @param targetUserID the user that will receive the roster entries
   */
  public void send(Roster roster, String targetUserID) {
    // Create a new message to send the roster
    Message msg = new Message(targetUserID);
    // Create a RosterExchange Package and add it to the message
    RosterExchange rosterExchange = new RosterExchange(roster);
    msg.addExtension(rosterExchange);

    // Send the message that contains the roster
    con.sendPacket(msg);
  }
 private void processAndSendResponse(Element element, Message message) {
   Element response = new Element(RESPONSE, Transport.NAMESPACE);
   XmlResponseProvider provider = XmlResponseProvider.getProvider(element, getBroadcaster());
   if (provider.processAndFillResponse(
       response, element, JabberTransport.this, getFrom(message))) {
     Message responseMessage = new Message(getFrom(message));
     responseMessage.addExtension(new JDOMExtension(response));
     responseMessage.setThread(message.getThread());
     myFacade.getConnection().sendPacket(responseMessage);
   }
 }
  private Message doSendMessage(XmlMessage xmlMessage, User user, String threadId) {
    Element element = new Element(xmlMessage.getTagName(), xmlMessage.getTagNamespace());
    xmlMessage.fillRequest(element);

    Message message = createBaseMessage(user, element.getText());
    message.setThread(threadId);
    message.addExtension(new JDOMExtension(element));
    myFacade.getConnection().sendPacket(message);

    return message;
  }
 /**
  * @see org.jivesoftware.smack.PacketListener#processPacket(org.jivesoftware.smack.packet.Packet)
  */
 @Override
 public void processPacket(Packet packet) {
   Message incomingMessage = (Message) packet;
   GcmPacketExtension gcmPacket =
       (GcmPacketExtension) incomingMessage.getExtension(GcmPacketExtension.GCM_NAMESPACE);
   String json = gcmPacket.getJson();
   JsonReader jsonReader = Json.createReader(new StringReader(json));
   JsonObject jsonObject = jsonReader.readObject();
   Object messageType = jsonObject.get("message_type");
   System.out.println(messageType);
 }
 /** {@inheritDoc} */
 public boolean accept(Packet packet) {
   if (!(packet instanceof Message)) {
     return false;
   } else {
     Message m = (Message) packet;
     if (logger.isDebugEnabled()) {
       logger.debug("Got a message in operation filter " + m.toXML());
     }
     return m.getType().equals(Message.Type.chat) && this.isValidOperation(m);
   }
 }
Example #26
0
 @Override
 public void processMessage(Chat arg0, Message message) {
   String result = message.getFrom() + ":" + message.getBody();
   System.out.println(result);
   android.os.Message msg = new android.os.Message();
   msg.what = 0;
   Bundle bd = new Bundle();
   bd.putString("msg", result);
   msg.setData(bd);
   handler.sendMessage(msg);
 }
Example #27
0
 /**
  * @see net.sf.kraken.session.TransportSession#sendBuzzNotification(org.xmpp.packet.JID, String)
  */
 @Override
 public void sendBuzzNotification(JID jid, String message) {
   Chat chat = conn.getChatManager().createChat(getTransport().convertJIDToID(jid), listener);
   try {
     Message m = new Message();
     m.setTo(getTransport().convertJIDToID(jid));
     m.addExtension(new BuzzExtension());
     chat.sendMessage(m);
   } catch (XMPPException e) {
     // Ignore
   }
 }
 @Override
 public boolean accept(Stanza stanza) {
   if (stanza instanceof Message) {
     Message msg = (Message) stanza;
     // All messages from agents are type normal
     if (Message.Type.normal.equals(msg.getType())
         && messagePattern.matcher(msg.getBody()).matches()) {
       return true;
     }
   }
   return false;
 }
 @Override
 public void interceptPacket(Packet packet) {
   System.out.println("Sending message: " + packet.toString());
   Message message = muc2.createMessage();
   message.setBody("Hello from producer, message " + " ");
   try {
     muc2.sendMessage(message);
   } catch (XMPPException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
  /**
   * Sends a roster group to userID. All the entries of the group will be sent to the target user.
   *
   * @param rosterGroup the roster group to send
   * @param targetUserID the user that will receive the roster entries
   */
  public void send(RosterGroup rosterGroup, String targetUserID) {
    // Create a new message to send the roster
    Message msg = new Message(targetUserID);
    // Create a RosterExchange Package and add it to the message
    RosterExchange rosterExchange = new RosterExchange();
    for (RosterEntry entry : rosterGroup.getEntries()) {
      rosterExchange.addRosterEntry(entry);
    }
    msg.addExtension(rosterExchange);

    // Send the message that contains the roster
    con.sendPacket(msg);
  }