示例#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;
  }
示例#2
0
        public void processMessage(Chat chat, Message message) {
          if ((message.getBody() != null) && (!message.getType().equals(Message.Type.error))) {
            if (!cipher) {

              Log.i(TAG, "Recibido mensaje plano: " + message.getBody());
              listMessages.add(message);
              refreshAdapter();
              myListView.smoothScrollToPosition(adapter.getCount() - 1);
            } else {

              try {
                PrivateKey pk =
                    RSA.getPrivateKeyDecryted(KeyStore.getInstance().getPk(), passPhrase);
                String decodedMessage = RSA.decipher(message.getBody(), pk);
                Log.i(TAG, "Recibido mensaje cifrado: " + decodedMessage);

                Message m = new Message();
                m.setFrom(message.getFrom());
                m.setTo(message.getTo());

                m.setBody(decodedMessage);
                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                m.setSubject(sdf.format(new Date()));
                listMessages.add(m);
                refreshAdapter();
                myListView.smoothScrollToPosition(adapter.getCount() - 1);

              } catch (Exception e) {
                Log.d(TAG, "PETO AL DESCIFRAR");
                e.printStackTrace();
              }
            }
          }
        }
  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;
  }
示例#4
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);
 }
示例#5
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);
   }
 }
示例#6
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();
  }
 @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();
   }
 }
示例#8
0
  public void send(View view) {
    Message message = new Message(destJid);
    EditText editText = (EditText) findViewById(R.id.textInput);
    String plainText = editText.getText().toString();
    editText.setText("");

    message.setFrom(myJid);
    message.setTo(destJid);

    Message m = new Message();
    m.setFrom(myJid);
    m.setBody(plainText);
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    m.setSubject(sdf.format(new Date()));
    listMessages.add(m);
    refreshAdapter();
    myListView.smoothScrollToPosition(adapter.getCount() - 1);

    if (!cipher) {
      try {
        message.setBody(plainText);
        chatMan.getChat().sendMessage(message);
        Log.d(TAG, "Enviando: " + message.getBody());

      } catch (XMPPException e) {
        Log.d(TAG, "ERROR al enviar mensaje");
      }
    } else {
      try {
        String encodedMessage = RSA.cipher(plainText, cert.getPublicKey());
        message.setBody(encodedMessage);
        chatMan.getChat().sendMessage(message);
        Log.d(TAG, "Enviando cifrado: " + message.getBody() + " " + plainText);

      } catch (Exception e) {
        Log.d(TAG, "PETO ENVIANDO CIFRADOOOO");
        e.printStackTrace();
      }
    }
  }
示例#9
0
 public void addToTranscript(Message message, boolean updateDate) {
   final Message newMessage = new Message();
   newMessage.setTo(message.getTo());
   newMessage.setFrom(message.getFrom());
   newMessage.setBody(message.getBody());
   newMessage.setProperty("date", new Date());
   transcript.add(newMessage);
   if (updateDate && transcriptWindow.getLastUpdated() != null)
     notificationLabel.setText(
         "las msg received at "
             + ChatsyManager.DATE_SECOND_FORMATTER.format(transcriptWindow.getLastUpdated()));
   scrollToBottom();
 }
  public void sendQuery(View v) {

    showMessage = new Builder(this);

    try {
      List<JSONObject> query = generatePayload();
      if (fromDt.getTime() > System.currentTimeMillis()) {
        if (validity) {
          // PubSubManager mgr = new
          // PubSubManager(RegisterMe.conn);
          Iterator<JSONObject> traverse = query.iterator();
          while (traverse.hasNext()) {
            Message query2 = new Message("[email protected]", Message.Type.chat);
            query2.setSubject("Query");
            query2.setBody(traverse.next().toString());
            // System.out.println(query2.getBody());
            RegisterMe.conn.sendPacket(query2);
          }
          showMessage.setTitle("Query Submission").setMessage("Successful").create().show();
          // System.out.println("Sensors selected:"+
          // query.size());
          /*try {
          			Message query2 = new Message("[email protected]",
          			Message.Type.chat);
          	query2.setSubject("Query");
          	query2.setBody(query.toString());
          //	RegisterMe.conn.sendPacket(query2);
          	showMessage.setTitle("Query Submission")
          			.setMessage("Successful").create().show();

          } catch (Exception e) {
          	// TODO Auto-generated catch block
          	e.printStackTrace();
          }*/
        } else {
          showMessage.setTitle("Error!").setMessage("Invalid fields!").create().show();
        }
      } else {
        showMessage.setTitle("Error!").setMessage("Starting Time already passed!").create().show();
      }
    } catch (Exception e) {
      showMessage
          .setTitle("Error!")
          .setMessage("Please ensure that data entered is valid")
          .create()
          .show();
    }
  }
示例#11
0
 /** {@inheritDoc} */
 @Override
 public void sendMessage(com.rei.lolchat.service.Message message) throws RemoteException {
   org.jivesoftware.smack.packet.Message send = new org.jivesoftware.smack.packet.Message();
   send.setTo(message.getTo());
   Log.w(TAG, "message to " + message.getTo());
   send.setBody(message.getBody());
   send.setType(org.jivesoftware.smack.packet.Message.Type.groupchat);
   // TODO gerer les messages contenant des XMPPError
   // send.set
   try {
     mAdaptee.sendMessage(send);
   } catch (XMPPException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
示例#12
0
 /**
  * Writes a formatted message to a room and creates the room if necessary, followed by an invite
  * to the default notification address to join the room
  *
  * @param number
  * @param contact
  * @param message
  * @throws XMPPException
  */
 public void writeRoom(String number, String contact, XmppMsg message, int mode) throws Exception {
   MultiUserChat muc;
   muc = inviteRoom(number, contact, mode);
   if (muc != null) {
     try {
       Message msg = new Message(muc.getRoom());
       msg.setBody(message.generateFmtTxt());
       if (mode == MODE_SHELL) {
         XHTMLManager.addBody(msg, message.generateXHTMLText().toString());
       }
       msg.setType(Message.Type.groupchat);
       muc.sendMessage(msg);
     } catch (Exception e) {
       muc.sendMessage(message.generateTxt());
     }
   }
 }
示例#13
0
  /**
   * Sends a broadcast message to all users selected.
   *
   * @param dlg
   */
  private boolean sendBroadcasts(JDialog dlg) {
    final Set<String> jids = new HashSet<String>();

    for (CheckNode node : nodes) {
      if (node.isSelected()) {
        String jid = (String) node.getAssociatedObject();
        jids.add(jid);
      }
    }

    if (jids.size() == 0) {
      JOptionPane.showMessageDialog(
          dlg,
          Res.getString("message.broadcast.no.user.selected"),
          Res.getString("title.error"),
          JOptionPane.ERROR_MESSAGE);
      return false;
    }

    String text = messageBox.getText();
    if (!ModelUtil.hasLength(text)) {
      JOptionPane.showMessageDialog(
          dlg,
          Res.getString("message.broadcast.no.text"),
          Res.getString("title.error"),
          JOptionPane.ERROR_MESSAGE);
      return false;
    }

    for (String jid : jids) {
      final Message message = new Message();
      message.setTo(jid);
      message.setBody(text);

      if (normalMessageButton.isSelected()) {
        message.setType(Message.Type.normal);
      } else {
        message.setType(Message.Type.headline);
      }
      SparkManager.getConnection().sendPacket(message);
    }

    return true;
  }
示例#14
0
  public void sendOfflineMessages() {
    Cursor cursor =
        contentResolver.query(
            ChatProvider.CONTENT_URI, SEND_OFFLINE_PROJECTION, SEND_OFFLINE_SELECTION, null, null);
    final int ID = cursor.getColumnIndexOrThrow(ChatConstants._ID);
    final int JABBER_ID = cursor.getColumnIndexOrThrow(ChatConstants.JID);
    final int MESSAGE = cursor.getColumnIndexOrThrow(ChatConstants.MESSAGE);
    final int DATE = cursor.getColumnIndexOrThrow(ChatConstants.DATE);
    final int PACKET_ID = cursor.getColumnIndexOrThrow(ChatConstants.PACKET_ID);

    ContentValues mark_sent = new ContentValues();
    mark_sent.put(ChatConstants.DELIVERY_STATUS, ChatConstants.DS_SENT_OR_READ);
    while (cursor.moveToNext()) {
      int id = cursor.getInt(ID);
      String toJID = cursor.getString(JABBER_ID);
      String message = cursor.getString(MESSAGE);
      String packetID = cursor.getString(PACKET_ID);
      long dateTs = cursor.getLong(DATE);
      final Message newMsg = new Message(toJID, Message.Type.chat);
      newMsg.setBody(message);
      DelayInformation delay = new DelayInformation(new Date(dateTs));
      newMsg.addExtension(delay);
      newMsg.addExtension(new DelayInfo(delay));
      newMsg.addExtension(new DeliveryReceiptRequest());
      if ((packetID != null) && (packetID.length() > 0)) {
        newMsg.setPacketID(packetID);
      } else {
        packetID = newMsg.getPacketID();
        mark_sent.put(ChatConstants.PACKET_ID, packetID);
      }
      Uri rowuri =
          Uri.parse(
              Constant.CONTENT_PATH
                  + ChatProvider.AUTHORITY
                  + "/"
                  + ChatProvider.TABLE_NAME
                  + "/"
                  + id);
      contentResolver.update(rowuri, mark_sent, null, null);
      extXMPPConnection.sendPacket(newMsg);
    }
    cursor.close();
  }
示例#15
0
 public void sendMessage(String to, String message) {
   Log.e(TAG, "To:" + to + ", Message:" + message);
   if (to == null) {
     return;
   }
   int index = to.indexOf('/');
   to = index >= 0 ? to.substring(0, index) : to;
   if (mConnection == null) {
     return;
   }
   Message msg = new Message(to, Message.Type.chat);
   msg.setBody(message);
   try {
     mConnection.sendPacket(msg);
   } catch (IllegalStateException e) {
     // Got disconnected.
     Log.e(TAG, "Disconnected. Failed to send: " + message);
   }
 }
示例#16
0
 public void sendOfflineMessages() {
   Cursor cursor =
       mContentResolver.query(
           ChatProvider.CONTENT_URI, SEND_OFFLINE_PROJECTION, SEND_OFFLINE_SELECTION, null, null);
   final int _ID_COL = cursor.getColumnIndexOrThrow(ChatConstants._ID);
   final int JID_COL = cursor.getColumnIndexOrThrow(ChatConstants.JID);
   final int MSG_COL = cursor.getColumnIndexOrThrow(ChatConstants.MESSAGE);
   final int TS_COL = cursor.getColumnIndexOrThrow(ChatConstants.DATE);
   final int PACKETID_COL = cursor.getColumnIndexOrThrow(ChatConstants.PACKET_ID);
   ContentValues mark_sent = new ContentValues();
   mark_sent.put(ChatConstants.DELIVERY_STATUS, ChatConstants.DS_SENT_OR_READ);
   while (cursor.moveToNext()) {
     int _id = cursor.getInt(_ID_COL);
     String toJID = cursor.getString(JID_COL);
     String message = cursor.getString(MSG_COL);
     String packetID = cursor.getString(PACKETID_COL);
     long ts = cursor.getLong(TS_COL);
     Log.d(TAG, "sendOfflineMessages: " + toJID + " > " + message);
     final Message newMessage = new Message(toJID, Message.Type.chat);
     newMessage.setBody(message);
     DelayInformation delay = new DelayInformation(new Date(ts));
     newMessage.addExtension(delay);
     newMessage.addExtension(new DelayInfo(delay));
     newMessage.addExtension(new DeliveryReceiptRequest());
     if ((packetID != null) && (packetID.length() > 0)) {
       newMessage.setPacketID(packetID);
     } else {
       packetID = newMessage.getPacketID();
       mark_sent.put(ChatConstants.PACKET_ID, packetID);
     }
     Uri rowuri =
         Uri.parse(
             "content://" + ChatProvider.AUTHORITY + "/" + ChatProvider.TABLE_NAME + "/" + _id);
     mContentResolver.update(rowuri, mark_sent, null, null);
     mXMPPConnection.sendPacket(
         newMessage); // must be after marking delivered, otherwise it may override the
     // SendFailListener
   }
   cursor.close();
 }
示例#17
0
 public void sendMessage(String toJID, String message) {
   final Message newMessage = new Message(toJID, Message.Type.chat);
   newMessage.setBody(message);
   newMessage.addExtension(new DeliveryReceiptRequest());
   if (isAuthenticated()) {
     addChatMessageToDB(
         ChatConstants.OUTGOING,
         toJID,
         message,
         ChatConstants.DS_SENT_OR_READ,
         System.currentTimeMillis(),
         newMessage.getPacketID());
     extXMPPConnection.sendPacket(newMessage);
   } else {
     addChatMessageToDB(
         ChatConstants.OUTGOING,
         toJID,
         message,
         ChatConstants.DS_NEW,
         System.currentTimeMillis(),
         newMessage.getPacketID());
   }
 }
示例#18
0
  public void send(String destination, String text) {
    Message response = new Message(destination, Message.Type.chat);
    response.setBody("*" + text);

    connection.sendPacket(response);
  }
  /**
   * Helper function used to send a message to a contact, with the given extensions attached.
   *
   * @param to The contact to send the message to.
   * @param toResource The resource to send the message to or null if no resource has been specified
   * @param message The message to send.
   * @param extensions The XMPP extensions that should be attached to the message before sending.
   * @return The MessageDeliveryEvent that resulted after attempting to send this message, so the
   *     calling function can modify it if needed.
   */
  private MessageDeliveredEvent sendMessage(
      Contact to, ContactResource toResource, Message message, PacketExtension[] extensions) {
    if (!(to instanceof ContactJabberImpl))
      throw new IllegalArgumentException("The specified contact is not a Jabber contact." + to);

    assertConnected();

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

    String toJID = null;

    if (toResource != null) {
      if (toResource.equals(ContactResource.BASE_RESOURCE)) {
        toJID = to.getAddress();
      } else toJID = ((ContactResourceJabberImpl) toResource).getFullJid();
    }

    if (toJID == null) {
      toJID = to.getAddress();
    }

    msg.setPacketID(message.getMessageUID());
    msg.setTo(toJID);

    for (PacketExtension ext : extensions) {
      msg.addExtension(ext);
    }

    if (logger.isTraceEnabled())
      logger.trace("Will send a message to:" + toJID + " chat.jid=" + toJID);

    MessageDeliveredEvent msgDeliveryPendingEvt =
        new MessageDeliveredEvent(message, to, toResource);

    MessageDeliveredEvent[] transformedEvents =
        messageDeliveryPendingTransform(msgDeliveryPendingEvt);

    if (transformedEvents == null || transformedEvents.length == 0) return null;

    for (MessageDeliveredEvent event : transformedEvents) {
      String content = event.getSourceMessage().getContent();

      if (message.getContentType().equals(HTML_MIME_TYPE)) {
        msg.setBody(Html2Text.extractText(content));

        // Check if the other user supports XHTML messages
        // make sure we use our discovery manager as it caches calls
        if (jabberProvider.isFeatureListSupported(toJID, HTML_NAMESPACE)) {
          // Add the XHTML text to the message
          XHTMLManager.addBody(msg, OPEN_BODY_TAG + content + CLOSE_BODY_TAG);
        }
      } else {
        // this is plain text so keep it as it is.
        msg.setBody(content);
      }

      // msg.addExtension(new Version());

      if (event.isMessageEncrypted() && isCarbonEnabled) {
        msg.addExtension(new CarbonPacketExtension.PrivateExtension());
      }

      MessageEventManager.addNotificationsRequests(msg, true, false, false, true);

      String threadID = getThreadIDForAddress(toJID);
      if (threadID == null) threadID = nextThreadID();

      msg.setThread(threadID);
      msg.setType(org.jivesoftware.smack.packet.Message.Type.chat);
      msg.setFrom(jabberProvider.getConnection().getUser());

      jabberProvider.getConnection().sendPacket(msg);

      putJidForAddress(toJID, threadID);
    }

    return new MessageDeliveredEvent(message, to, toResource);
  }
示例#20
0
 /**
  * Sends the specified text as a message to the other chat participant. This is a convenience
  * method for:
  *
  * <pre>
  *     Message message = chat.createMessage();
  *     message.setBody(messageText);
  *     chat.sendMessage(message);
  * </pre>
  *
  * @param text the text to send.
  * @throws XMPPException if sending the message fails.
  */
 public void sendMessage(String text) throws XMPPException {
   Message message = new Message(participant, Message.Type.chat);
   message.setThread(threadID);
   message.setBody(text);
   chatManager.sendMessage(this, message);
 }
 static Message createBaseMessage(User user, String message) {
   Message msg = new Message(user.getName(), Message.Type.CHAT);
   msg.setBody(message);
   return msg;
 }