Example #1
0
  @Override
  public void send(Message message) throws Exception {
    log.info("START");
    try {
      log.info("Message: " + message.getContent());
      log.info("Send To: " + message.getVsdVehOwnConDetail().getMobileNumber());

      String recipient = "";
      if (SystemProperties.get(SystemProperties.ALERT_ENV).toString().equalsIgnoreCase("PROD")
          && SystemProperties.get(SystemProperties.ALERT_ENV_PROP)
              .toString()
              .equalsIgnoreCase("PROD")) {
        recipient = message.getVsdVehOwnConDetail().getMobileNumber();
      } else {
        // recipient = "971504677281";	// Nada
        recipient = "923018564787"; // Zain
      }

      String url =
          "http://www.ducont.ae/smscompanion/smsadmin/rapidegovsmssubmit.asp?uname=rtald&passwd=rtald08&urname=RTA&number="
              + recipient
              + "&udata=";
      String msg = message.getContent();
      if (message.getLanguage().equalsIgnoreCase(Constant.ARABIC)) {
        msg = prepareUnicodeMessage(msg);
      } else {
        msg = msg.replaceAll(" ", "%20");
      }
      log.info(msg);
      url = url + msg + "&drmsgid=1";

      URL urlObject = new URL(url);
      HttpURLConnection UrlConn = (HttpURLConnection) urlObject.openConnection();

      UrlConn.setRequestMethod("GET");
      UrlConn.setAllowUserInteraction(false);
      UrlConn.setDoOutput(true);

      OutputStreamWriter out = new OutputStreamWriter(UrlConn.getOutputStream(), "UCS-2");
      out.flush();
      out.close();
      String response = UrlConn.getResponseMessage();
      log.info("SMS Sent!" + response);
      if (!response.equalsIgnoreCase("OK")) {
        throw new Exception("Error sending SMS: " + response);
      }
    } catch (Exception ex) {
      log.error(ex.getMessage(), ex);
      throw ex;
    }
    log.info("END");
  }
Example #2
0
 protected int getMessageSize(Message message, Account account)
     throws IOException, MessagingException {
   int count = 0;
   if (account.getLoginName().contains("aol.com") && message.getContent() instanceof Multipart) {
     Multipart multipart = (Multipart) message.getContent();
     for (int i = 0; i < multipart.getCount(); i++) {
       count += multipart.getBodyPart(i).getSize();
     }
   } else {
     count = message.getSize();
   }
   return count;
 }
Example #3
0
  @Override
  public void run() {
    try {
      login(scanner.nextLine());

      while (true) {
        Message m = new Message(scanner.nextLine());

        switch (m.getTyp()) {
          case Message.TYP_TO_ALL:
            server.anAlle("2::" + m.getFrom() + ":" + m.getContent() + txt_ende);
            server.liste_senden();
            break;
          case Message.TYP_TO_ONE:
            if (!server.sendAn(
                m.getTo(), "3:" + m.getTo() + ":" + m.getFrom() + ":" + m.getContent()))
              // todo fehlermeldung an sender;
              ;
            break;

          default:
            throw new MessageException("alle blöd");
        }
      }

    } catch (NoSuchElementException e) {

      try {
        client.close();
        server.anAlle("2::SERVER:" + name + " has disconnected." + txt_ende);
        Window.listenModel.removeElement(name);
        System.out.println(name + " entfernt");
        server.liste_senden();

      } catch (IOException e1) {
        e1.printStackTrace();
      }

    } catch (Exception e) {
      try {
        client.close();
        server.anAlle("2::SERVER:" + name + " has disconnected." + txt_ende);
        Window.listenModel.removeElement(name);
        System.out.println(name + " entfernt");
        server.liste_senden();
      } catch (IOException e1) {
      }
    }
  }
Example #4
0
  public void send(Message message, String footer) {
    String msgToSent = message.getContent() + "\n\n" + footer;

    for (Contact contact : message.getDestinations()) {
      send(contact.getNumber(), msgToSent);
    }
  }
  private void addMessageToLayout(Message message) {
    TextView user = new TextView(this);
    TextView messageView = new TextView(this);

    user.setTextColor(getResources().getColor(R.color.messageTitle));
    user.setText(
        "("
            + DateFormat.format("hh:mm aa", message.getTimestamp())
            + ") "
            + message.getUsername()
            + ":");
    user.setTextSize(15);
    user.setPadding(5, 15, 5, 0);
    user.setTypeface(Typeface.DEFAULT_BOLD);

    messageView.setText(message.getContent());
    messageView.setTextColor(getResources().getColor(R.color.textColor));
    messageView.setTextSize(15);
    messageView.setPadding(5, 0, 5, 0);

    View line = new View(this);
    line.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 1));
    line.setBackgroundColor(getResources().getColor(R.color.messageLine));
    line.setPadding(0, 0, 0, 15);

    messages.addView(user);
    messages.addView(messageView);
    messages.addView(line);
  }
  public static void main(String[] args) throws MessagingException, IOException {
    IMAPFolder folder = null;
    Store store = null;
    String subject = null;
    Flag flag = null;
    try {
      Properties props = System.getProperties();
      props.setProperty("mail.store.protocol", "imaps");
      props.setProperty("mail.imap.host", "imap.googlemail.com");
      SimpleAuthenticator authenticator =
          new SimpleAuthenticator("*****@*****.**", "hhy8611hhyy");
      Session session = Session.getDefaultInstance(props, null);
      // Session session = Session.getDefaultInstance(props, authenticator);

      store = session.getStore("imaps");
      //          store.connect("imap.googlemail.com","*****@*****.**", "hhy8611hhyy");
      // store.connect("imap.googlemail.com","*****@*****.**", "hhy8611hhyy");

      store.connect("*****@*****.**", "hhy8611hhy");
      // folder = (IMAPFolder) store.getFolder("[Gmail]/Spam"); // This doesn't work for other email
      // account
      folder = (IMAPFolder) store.getFolder("inbox"); // This works for both email account

      if (!folder.isOpen()) folder.open(Folder.READ_WRITE);
      Message[] messages = messages = folder.getMessages(150, 150); // folder.getMessages();
      System.out.println("No of get Messages : " + messages.length);
      System.out.println("No of Messages : " + folder.getMessageCount());
      System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount());
      System.out.println("No of New Messages : " + folder.getNewMessageCount());
      System.out.println(messages.length);
      for (int i = 0; i < messages.length; i++) {

        System.out.println(
            "*****************************************************************************");
        System.out.println("MESSAGE " + (i + 1) + ":");
        Message msg = messages[i];
        // System.out.println(msg.getMessageNumber());
        // Object String;
        // System.out.println(folder.getUID(msg)

        subject = msg.getSubject();

        System.out.println("Subject: " + subject);
        System.out.println("From: " + msg.getFrom()[0]);
        System.out.println("To: " + msg.getAllRecipients()[0]);
        System.out.println("Date: " + msg.getReceivedDate());
        System.out.println("Size: " + msg.getSize());
        System.out.println(msg.getFlags());
        System.out.println("Body: \n" + msg.getContent());
        System.out.println(msg.getContentType());
      }
    } finally {
      if (folder != null && folder.isOpen()) {
        folder.close(true);
      }
      if (store != null) {
        store.close();
      }
    }
  }
Example #7
0
 public boolean acceptMsg(Message msg) {
   logRecvMsg(msg);
   TestChatServer.logUserMsgRecvd(username, msg.toString(), new Date());
   TransportObject toSend =
       new TransportObject(
           ServerReply.receive,
           msg.getSource(),
           msg.getDest(),
           msg.getContent(),
           msg.getTimestamp(),
           msg.getSQN());
   if (!queueReply(toSend)) return false;
   msgReceived(
       msg.getSource() + "\t" + msg.getDest() + "\t" + msg.getSQN() + "\t" + msg.getContent());
   return true;
 }
  /** Method for checking if the message has attachments. */
  public boolean hasAttachments() throws java.io.IOException, MessagingException {
    boolean hasAttachments = false;
    if (message.isMimeType("multipart/*")) {
      Multipart mp = (Multipart) message.getContent();
      if (mp.getCount() > 1) hasAttachments = true;
    }

    return hasAttachments;
  }
 /** Returns the body of the message (if it's plain text). */
 public String getBody() throws MessagingException, java.io.IOException {
   Object content = message.getContent();
   if (message.isMimeType("text/plain")) {
     return (String) content;
   } else if (message.isMimeType("multipart/alternative")) {
     Multipart mp = (Multipart) message.getContent();
     int numParts = mp.getCount();
     for (int i = 0; i < numParts; ++i) {
       if (mp.getBodyPart(i).isMimeType("text/plain"))
         return (String) mp.getBodyPart(i).getContent();
     }
     return "";
   } else if (message.isMimeType("multipart/*")) {
     Multipart mp = (Multipart) content;
     if (mp.getBodyPart(0).isMimeType("text/plain"))
       return (String) mp.getBodyPart(0).getContent();
     else return "";
   } else return "";
 }
Example #10
0
  /**
   * When a sent message is delivered shows it in the chat conversation panel.
   *
   * @param evt the event containing details on the message delivery
   */
  public void messageDelivered(MessageDeliveredEvent evt) {
    Contact contact = evt.getDestinationContact();
    MetaContact metaContact =
        GuiActivator.getContactListService().findMetaContactByContact(contact);

    if (logger.isTraceEnabled())
      logger.trace("MESSAGE DELIVERED to contact: " + contact.getAddress());

    ChatPanel chatPanel = chatWindowManager.getContactChat(metaContact, false);

    if (chatPanel != null) {
      Message msg = evt.getSourceMessage();
      ProtocolProviderService protocolProvider = contact.getProtocolProvider();

      if (logger.isTraceEnabled())
        logger.trace(
            "MESSAGE DELIVERED: process message to chat for contact: "
                + contact.getAddress()
                + " MESSAGE: "
                + msg.getContent());

      chatPanel.addMessage(
          this.mainFrame.getAccountAddress(protocolProvider),
          this.mainFrame.getAccountDisplayName(protocolProvider),
          evt.getTimestamp(),
          Chat.OUTGOING_MESSAGE,
          msg.getContent(),
          msg.getContentType(),
          msg.getMessageUID(),
          evt.getCorrectedMessageUID());

      if (evt.isSmsMessage() && !ConfigurationUtils.isSmsNotifyTextDisabled()) {
        chatPanel.addMessage(
            contact.getDisplayName(),
            new Date(),
            Chat.ACTION_MESSAGE,
            GuiActivator.getResources().getI18NString("service.gui.SMS_SUCCESSFULLY_SENT"),
            "text");
      }
    }
  }
Example #11
0
  /**
   * Shows a warning message to the user when message delivery has failed.
   *
   * @param evt the event containing details on the message delivery failure
   */
  public void messageDeliveryFailed(MessageDeliveryFailedEvent evt) {
    logger.error(evt.getReason());

    String errorMsg = null;

    Message sourceMessage = (Message) evt.getSource();

    Contact sourceContact = evt.getDestinationContact();

    MetaContact metaContact =
        GuiActivator.getContactListService().findMetaContactByContact(sourceContact);

    if (evt.getErrorCode() == MessageDeliveryFailedEvent.OFFLINE_MESSAGES_NOT_SUPPORTED) {
      errorMsg =
          GuiActivator.getResources()
              .getI18NString(
                  "service.gui.MSG_DELIVERY_NOT_SUPPORTED",
                  new String[] {sourceContact.getDisplayName()});
    } else if (evt.getErrorCode() == MessageDeliveryFailedEvent.NETWORK_FAILURE) {
      errorMsg = GuiActivator.getResources().getI18NString("service.gui.MSG_NOT_DELIVERED");
    } else if (evt.getErrorCode() == MessageDeliveryFailedEvent.PROVIDER_NOT_REGISTERED) {
      errorMsg =
          GuiActivator.getResources().getI18NString("service.gui.MSG_SEND_CONNECTION_PROBLEM");
    } else if (evt.getErrorCode() == MessageDeliveryFailedEvent.INTERNAL_ERROR) {
      errorMsg =
          GuiActivator.getResources().getI18NString("service.gui.MSG_DELIVERY_INTERNAL_ERROR");
    } else {
      errorMsg = GuiActivator.getResources().getI18NString("service.gui.MSG_DELIVERY_ERROR");
    }

    String reason = evt.getReason();
    if (reason != null)
      errorMsg +=
          " "
              + GuiActivator.getResources()
                  .getI18NString("service.gui.ERROR_WAS", new String[] {reason});

    ChatPanel chatPanel = chatWindowManager.getContactChat(metaContact, sourceContact);

    chatPanel.addMessage(
        sourceContact.getAddress(),
        metaContact.getDisplayName(),
        new Date(),
        Chat.OUTGOING_MESSAGE,
        sourceMessage.getContent(),
        sourceMessage.getContentType(),
        sourceMessage.getMessageUID(),
        evt.getCorrectedMessageUID());

    chatPanel.addErrorMessage(metaContact.getDisplayName(), errorMsg);

    chatWindowManager.openChat(chatPanel, false);
  }
    @Override
    public String respond(HttpExchange httpExchange) {
      InputStream body = httpExchange.getRequestBody();

      try {
        Message message = objectMapper.readValue(body, Message.class);
        logger.log(message.getType() + ": " + message.getContent());
      } catch (IOException exception) {
        logger.error(exception.getMessage());
      }

      return NO_CONTENT;
    }
  /**
   * Sends the <tt>message</tt> to the destination indicated by the <tt>to</tt> contact.
   *
   * @param to the <tt>Contact</tt> to send <tt>message</tt> to
   * @param message the <tt>Message</tt> to send.
   * @throws IllegalStateException if the underlying ICQ stack is not registered and initialized.
   * @throws IllegalArgumentException if <tt>to</tt> is not an instance belonging to the underlying
   *     implementation.
   */
  public void sendInstantMessage(Contact to, Message message)
      throws IllegalStateException, IllegalArgumentException {
    if (!(to instanceof ContactDictImpl)) {
      throw new IllegalArgumentException("The specified contact is not a Dict contact." + to);
    }

    // Remove all html tags from the message
    message = createMessage(Html2Text.extractText(message.getContent()));

    // Display the queried word
    fireMessageDelivered(message, to);

    this.submitDictQuery((ContactDictImpl) to, message);
  }
 /**
  * Saves all attachments to a temp directory, and returns the directory path. Null if no
  * attachments.
  */
 public File saveAttachments(Message message) throws IOException, MessagingException {
   File tmpDir = Files.createTempDir();
   boolean foundAttachments = false;
   Object content = message.getContent();
   if (message.isMimeType(MULTIPART_WILDCARD) && content instanceof Multipart) {
     Multipart mp = (Multipart) content;
     for (int i = 0; i < mp.getCount(); i++) {
       BodyPart bodyPart = mp.getBodyPart(i);
       if (bodyPart instanceof MimeBodyPart && isNotBlank(bodyPart.getFileName())) {
         MimeBodyPart mimeBodyPart = (MimeBodyPart) bodyPart;
         mimeBodyPart.saveFile(new File(tmpDir, mimeBodyPart.getFileName()));
         foundAttachments = true;
       }
     }
   }
   return foundAttachments ? tmpDir : null;
 }
  /**
   * get a view that displays the data at the specified position in the data set. This function is
   * called for each rows a bubble contains information loaded thanks to the controller
   *
   * @param position the position of the item in the listview
   * @param convertView the old view to rescue
   * @param parent the parent that this view will eventually be attached to (conversationActivity)
   * @return the view of a bubble. Created view by us
   */
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    View bubbleViewRow = convertView;

    if (convertView == null) {
      // create a new object with the same properties that the buuble_item
      bubbleViewRow = this.mLayoutInflater.inflate(R.layout.bubble_item, null);

      holder = new ViewHolder();
      holder.messageBody = (TextView) bubbleViewRow.findViewById(R.id.b_contenu);
      holder.photo = (ImageView) bubbleViewRow.findViewById(R.id.imageViewPhotoContact);

      bubbleViewRow.setTag(holder);
    } else {
      holder = (ViewHolder) bubbleViewRow.getTag();
    }

    Message item = mBubbles.get(position);

    /**
     * if it's an instance of Message, we create an item with a messageBody, imageBubble etc...
     * Else, We write the date.
     */
    if (item instanceof Message) {
      Message message = (Message) item;
      holder.messageBody.setText(message.getContent());

      RelativeLayout layout = (RelativeLayout) bubbleViewRow.findViewById(R.id.layoutBubble);
      if (message.isSendByMe()) {
        holder.messageBody.setBackgroundResource(R.drawable.bulle_me);
        layout.setGravity(Gravity.RIGHT);
      } else {
        holder.photo.setImageBitmap(message.getContact().getPhoto(contentResolver));
        holder.messageBody.setBackgroundResource(R.drawable.bulle_not_me);
        layout.setGravity(Gravity.LEFT);
      }
      holder.messageBody.setPadding(50, 50, 50, 50);
    } else {
      holder.messageBody.setTextSize(13);
      holder.messageBody.setText(item.getManagedDate());
    }

    return bubbleViewRow;
  }
Example #16
0
File: Queue.java Project: jielen/EB
  public synchronized void produce(Message message) {

    this.notifyAll();
    while (queue.size() == maxMessageNum) {
      System.out.println(Thread.currentThread().getName() + "  队列满!等待中。。。");
      try {
        this.wait();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    queue.add(message);
    System.out.println(
        Thread.currentThread().getName()
            + "正在生产"
            + message.getContent()
            + "。。。  ,当前个数:"
            + getCount());
  }
  /**
   * Create, execute and display a query to a dictionary (ContactDictImpl)
   *
   * @param dictContact the contact containing the database name
   * @param message the message containing the word
   */
  private void submitDictQuery(ContactDictImpl dictContact, Message message) {
    Message msg = this.createMessage("");

    String database = dictContact.getContactID();
    DictConnection conn = this.parentProvider.getConnection();
    boolean doMatch = false;

    String word;

    // Formatting the query message, if the word as one or more spaces we
    // put it between quotes to prevent errors
    word = message.getContent().replace("\"", "").trim();
    if (word.indexOf(' ') > 0) {
      word = "\"" + word + "\"";
    }

    // Try to get the definition of the work
    try {
      List<Definition> definitions = conn.define(database, word);
      msg = this.createMessage(retrieveDefine(definitions, word));
    } catch (DictException dx) {
      if (dx.getErrorCode()
          == DictReturnCode.NO_MATCH) { // No word found, we are going to try the match command
        doMatch = true;
      } else { // Otherwise we display the error returned by the server
        msg = this.createMessage(manageException(dx, database));
      }
    }

    if (doMatch) {
      // Trying the match command
      try {
        List<MatchWord> matchWords = conn.match(database, word, this.accountID.getStrategy());
        msg = this.createMessage(retrieveMatch(matchWords, word));
      } catch (DictException dx) {
        msg = this.createMessage(manageException(dx, database));
      }
    }

    // Send message
    fireMessageReceived(msg, dictContact);
  }
Example #18
0
File: Queue.java Project: jielen/EB
  public synchronized void consume() {

    this.notifyAll();
    while (queue.size() == 0) {
      System.out.println(Thread.currentThread().getName() + "  队列空!等待中。。。");
      try {
        System.out.println("begin!");
        wait();
        System.out.println("end!");
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }

    Message message = queue.get(0);
    queue.remove(0);
    System.out.println(
        Thread.currentThread().getName()
            + "正在消费"
            + message.getContent()
            + "。。。 ,当前个数: "
            + getCount());
  }
Example #19
0
 // affichage a la reception
 private void receive(Message msg) {
   this.log("Received " + msg.getContent());
 }
Example #20
0
  /**
   * When a message is received determines whether to open a new chat window or chat window tab, or
   * to indicate that a message is received from a contact which already has an open chat. When the
   * chat is found checks if in mode "Auto popup enabled" and if this is the case shows the message
   * in the appropriate chat panel.
   *
   * @param protocolContact the source contact of the event
   * @param contactResource the resource from which the contact is writing
   * @param metaContact the metacontact containing <tt>protocolContact</tt>
   * @param message the message to deliver
   * @param eventType the event type
   * @param timestamp the timestamp of the event
   * @param correctedMessageUID the identifier of the corrected message
   * @param isPrivateMessaging if <tt>true</tt> the message is received from private messaging
   *     contact.
   * @param privateContactRoom the chat room associated with the private messaging contact.
   */
  private void messageReceived(
      final Contact protocolContact,
      final ContactResource contactResource,
      final MetaContact metaContact,
      final Message message,
      final int eventType,
      final Date timestamp,
      final String correctedMessageUID,
      final boolean isPrivateMessaging,
      final ChatRoom privateContactRoom) {
    if (!SwingUtilities.isEventDispatchThread()) {
      SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              messageReceived(
                  protocolContact,
                  contactResource,
                  metaContact,
                  message,
                  eventType,
                  timestamp,
                  correctedMessageUID,
                  isPrivateMessaging,
                  privateContactRoom);
            }
          });
      return;
    }

    // Obtain the corresponding chat panel.
    final ChatPanel chatPanel =
        chatWindowManager.getContactChat(
            metaContact, protocolContact, contactResource, message.getMessageUID());

    // Show an envelope on the sender contact in the contact list and
    // in the systray.
    if (!chatPanel.isChatFocused()) contactList.setActiveContact(metaContact, true);

    // Distinguish the message type, depending on the type of event that
    // we have received.
    String messageType = null;

    if (eventType == MessageReceivedEvent.CONVERSATION_MESSAGE_RECEIVED) {
      messageType = Chat.INCOMING_MESSAGE;
    } else if (eventType == MessageReceivedEvent.SYSTEM_MESSAGE_RECEIVED) {
      messageType = Chat.SYSTEM_MESSAGE;
    } else if (eventType == MessageReceivedEvent.SMS_MESSAGE_RECEIVED) {
      messageType = Chat.SMS_MESSAGE;
    }

    String contactAddress =
        (contactResource != null)
            ? protocolContact.getAddress() + " (" + contactResource.getResourceName() + ")"
            : protocolContact.getAddress();

    chatPanel.addMessage(
        contactAddress,
        protocolContact.getDisplayName(),
        timestamp,
        messageType,
        message.getContent(),
        message.getContentType(),
        message.getMessageUID(),
        correctedMessageUID);

    String resourceName = (contactResource != null) ? contactResource.getResourceName() : null;

    if (isPrivateMessaging) {
      chatWindowManager.openPrivateChatForChatRoomMember(privateContactRoom, protocolContact);
    } else {
      chatWindowManager.openChat(chatPanel, false);
    }

    ChatTransport chatTransport =
        chatPanel.getChatSession().findChatTransportForDescriptor(protocolContact, resourceName);

    chatPanel.setSelectedChatTransport(chatTransport, true);
  }
Example #21
0
 // envoi d'un message (l'envoi se fait via la couche transport)
 public void send(Message msg, Node dest) {
   this.log("Send " + msg.getContent() + " to " + dest.getID());
   this.transport.send(getMyNode(), dest, msg, this.mypid);
 }
Example #22
0
 public void send(Message message) {
   for (Contact contact : message.getDestinations()) {
     send(contact.getNumber(), message.getContent());
   }
 }