public void handleDirections(Update update) throws InvalidObjectException {
    Message message = update.getMessage();
    if (message != null && message.hasText()) {
      if (languageMessages.contains(message.getFrom().getId())) {
        onLanguageSelected(message);
      } else {
        String language =
            DatabaseManager.getInstance().getUserLanguage(update.getMessage().getFrom().getId());
        if (message.getText().startsWith(Commands.setLanguageCommand)) {
          onSetLanguageCommand(message, language);
        } else if (message.getText().startsWith(Commands.startDirectionCommand)) {
          onStartdirectionsCommand(message, language);
        } else if ((message.getText().startsWith(Commands.help)
                || (message.getText().startsWith(Commands.startCommand)
                    || !message.isGroupMessage()))
            && DatabaseManager.getInstance().getUserDestinationStatus(message.getFrom().getId())
                == -1) {
          sendHelpMessage(message, language);
        } else if (!message.getText().startsWith("/")) {
          if (DatabaseManager.getInstance().getUserDestinationStatus(message.getFrom().getId())
                  == WATING_ORIGIN_STATUS
              && message.hasReplayMessage()
              && DatabaseManager.getInstance()
                      .getUserDestinationMessageId(message.getFrom().getId())
                  == message.getReplyToMessage().getMessageId()) {
            onOriginReceived(message, language);

          } else if (DatabaseManager.getInstance()
                      .getUserDestinationStatus(message.getFrom().getId())
                  == WATING_DESTINY_STATUS
              && message.hasReplayMessage()
              && DatabaseManager.getInstance()
                      .getUserDestinationMessageId(message.getFrom().getId())
                  == message.getReplyToMessage().getMessageId()) {
            onDestinationReceived(message, language);
          } else if (!message.hasReplayMessage()) {
            if (DatabaseManager.getInstance().getUserDestinationStatus(message.getFrom().getId())
                == -1) {
              sendHelpMessage(message, language);
            } else {
              SendMessage sendMessageRequest = new SendMessage();
              sendMessageRequest.setText(
                  LocalisationService.getInstance().getString("youNeedReplyDirections", language));
              sendMessageRequest.setChatId(message.getChatId().toString());
              SenderHelper.SendApiMethod(sendMessageRequest, TOKEN);
            }
          }
        }
      }
    }
  }
 public MessagesWrapper print() throws MessagingException {
   logger.info("Found message(s) : " + messages.size());
   for (Message message : messages) {
     logger.info(">>>>>>");
     logger.info("Date    : " + message.getSentDate());
     logger.info("From    : " + (message.getFrom().length > 0 ? message.getFrom()[0] : null));
     logger.info("Subject : " + message.getSubject());
     logger.info("<<<<<<");
   }
   return this;
 }
Esempio n. 3
0
  private void login(String line0) {
    Message m = new Message(line0);

    if (m.getTyp() != Message.TYP_LOGIN) throw new MessageException("Zuerst einloggen!");

    if (server.addUser(m.getFrom())) {
      name = m.getFrom();
      EchoServer.sem.release();
    } else {
      EchoServer.sem.release();
      throw new MessageException("Name schon da!");
    }
  }
Esempio n. 4
0
  private void handlePacket(Packet packet) {
    if (packet instanceof Message) {
      Message msg = (Message) packet;
      // Check to see if the user left the queue.
      PacketExtension pe = msg.getExtension("depart-queue", "http://jabber.org/protocol/workgroup");
      PacketExtension queueStatus =
          msg.getExtension("queue-status", "http://jabber.org/protocol/workgroup");

      if (pe != null) {
        fireQueueDepartedEvent();
      } else if (queueStatus != null) {
        QueueUpdate queueUpdate = (QueueUpdate) queueStatus;
        if (queueUpdate.getPosition() != -1) {
          fireQueuePositionEvent(queueUpdate.getPosition());
        }
        if (queueUpdate.getRemaingTime() != -1) {
          fireQueueTimeEvent(queueUpdate.getRemaingTime());
        }
      } else {
        // Check if a room invitation was sent and if the sender is the workgroup
        MUCUser mucUser = (MUCUser) msg.getExtension("x", "http://jabber.org/protocol/muc#user");
        MUCUser.Invite invite = mucUser != null ? mucUser.getInvite() : null;
        if (invite != null && workgroupJID.equals(invite.getFrom())) {
          String sessionID = null;
          Map<String, List<String>> metaData = null;

          pe = msg.getExtension(SessionID.ELEMENT_NAME, SessionID.NAMESPACE);
          if (pe != null) {
            sessionID = ((SessionID) pe).getSessionID();
          }

          pe = msg.getExtension(MetaData.ELEMENT_NAME, MetaData.NAMESPACE);
          if (pe != null) {
            metaData = ((MetaData) pe).getMetaData();
          }

          WorkgroupInvitation inv =
              new WorkgroupInvitation(
                  connection.getUser(),
                  msg.getFrom(),
                  workgroupJID,
                  sessionID,
                  msg.getBody(),
                  msg.getFrom(),
                  metaData);

          fireInvitationEvent(inv);
        }
      }
    }
  }
Esempio n. 5
0
 public void receiveMsg(Message msg) {
   // System.out.println(msg.getSubject() + " : " + msg.getBody());
   String subject = msg.getSubject();
   if (subject != null) {
     if (subject.equals("online")) {
       onlineUsers.addElement(new HostItem(msg.getBody()));
       displayMessage(msg.getBody() + " : Online", onlineClientAttrSet);
     } else if (subject.equals("offline")) {
       onlineUsers.removeElement(new HostItem(msg.getBody()));
       displayMessage(msg.getBody() + " : Offline", offlineClientAttrSet);
     } else if (subject.equals("eavesdrop enabled")) {
       Object[] values = jListOnlineUsers.getSelectedValues();
       if (values == null) return;
       for (int i = 0; i < values.length; i++) {
         ((HostItem) values[i]).eavesDroppingEnabled = true;
       }
       jListOnlineUsers.updateUI();
     } else if (subject.equals("eavesdrop disabled")) {
       Object[] values = jListOnlineUsers.getSelectedValues();
       if (values == null) return;
       for (int i = 0; i < values.length; i++) {
         ((HostItem) values[i]).eavesDroppingEnabled = false;
       }
       jListOnlineUsers.updateUI();
     } else if (subject.equals("globaleavesdrop enabled")) {
       displayMessage("Global Eavesdropping Enabled", onlineClientAttrSet);
     } else if (subject.equals("globaleavesdrop disabled")) {
       displayMessage("Global Eavesdropping Disabled", offlineClientAttrSet);
     } else {
       String to = msg.getTo();
       String from = msg.getFrom() == null ? "server" : msg.getFrom();
       String body = msg.getBody() != null ? msg.getBody() : "";
       if (jTextFieldUser.getText().equals(to)) { // this message is sent to us
         displayMessage(subject, from, body, incomingMsgAttrSet);
       } else { // this is an eavesdrop message
         displayMessage(subject, to, from, body, eavesdropAttrSet);
       }
     }
   } else {
     subject = "";
     String to = msg.getTo();
     String from = msg.getFrom() == null ? "server" : msg.getFrom();
     String body = msg.getBody() != null ? msg.getBody() : "";
     if (jTextFieldUser.getText().equals(to)) { // this message is sent to us
       displayMessage(subject, from, body, incomingMsgAttrSet);
     } else { // this is an eavesdrop message
       displayMessage(subject, to, from, body, eavesdropAttrSet);
     }
   }
 }
Esempio n. 6
0
  public void route(Message m) {

    if (m.getFrom() == null) {
      // local message

      if (m_lanMessageRemoteOutbox != null) m_lanMessageRemoteOutbox.route(m);

    } else if (m.getTo() == null) {
      // remote message
      if (m_uiMessageRouter != null) m_uiMessageRouter.route(m);
    } else {
      D.out("Could not route message from=" + m.getFrom() + " to=" + m.getTo());
    }
  }
Esempio n. 7
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) {
      }
    }
  }
Esempio n. 8
0
  /**
   * Handles a message received from the remote party.
   *
   * @param msg The Message object that was received.
   */
  private void doMessageReceived(Message msg) {
    assert (SwingUtilities.isEventDispatchThread()) : "not in UI thread";

    if (msg.getType() == Message.Type.ERROR) {
      JOptionPane.showMessageDialog(
          this,
          msg.getError().getMessage(),
          JavolinApp.getAppName() + ": Error",
          JOptionPane.ERROR_MESSAGE);
    } else if (msg.getType() == Message.Type.HEADLINE) {
      // Do nothing
    } else {
      String jid = msg.getFrom();
      if (jid != null) setUserResource(jid);

      Date date = null;
      PacketExtension ext = msg.getExtension("x", "jabber:x:delay");
      if (ext != null && ext instanceof DelayInformation) {
        date = ((DelayInformation) ext).getStamp();
      }

      mLog.message(mRemoteIdFull, mRemoteNick, msg.getBody(), date);
      Audio.playMessage();
    }
  }
 public CustomProperties getMessageProperties(Message message, String prefix, CustomProperties p)
     throws MessagingException, IOException {
   CustomProperties envVars = new CustomProperties();
   String msgSubject = stringify(message.getSubject());
   envVars.put(prefix + "subject", msgSubject);
   envVars.put(prefix + "from", stringify(message.getFrom()));
   envVars.put(prefix + "replyTo", stringify(message.getReplyTo()));
   envVars.put(prefix + "flags", stringify(message.getFlags()));
   envVars.put(prefix + "folder", stringify(message.getFolder()));
   envVars.put(prefix + "messageNumber", stringify(message.getMessageNumber()));
   envVars.put(prefix + "receivedDate", stringify(message.getReceivedDate()));
   envVars.put(prefix + "sentDate", stringify(message.getSentDate()));
   envVars.put(prefix + "headers", stringify(message.getAllHeaders()));
   envVars.put(prefix + "content", stringify(message));
   envVars.put(prefix + "contentType", stringify(message.getContentType()));
   envVars.put(prefix + "recipients", stringify(message.getAllRecipients()));
   // add parameters from email content
   final CustomProperties properties = CustomProperties.read(getText(message));
   envVars.putAll(properties);
   //            envVars.put(prefix + "emailParams", stringify(properties.getMap(), "=", "&"));
   // add "jobTrigger"
   if (p.has(subjectContains)) {
     String subject = p.get(subjectContains);
     // normalise strings, find index, then get text after it
     int idx = msgSubject.toLowerCase().indexOf(subject.toLowerCase());
     int beginIndex = idx + subject.length();
     if (idx > -1 && beginIndex < msgSubject.length()) {
       envVars.put(prefix + "jobTrigger", msgSubject.substring(beginIndex).trim());
     }
   }
   return envVars;
 }
  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();
      }
    }
  }
  private void onDestinationReceived(Message message, String language) {
    String origin = DatabaseManager.getInstance().getUserOrigin(message.getFrom().getId());
    String destiny = message.getText();
    List<String> directions =
        DirectionsService.getInstance().getDirections(origin, destiny, language);
    SendMessage sendMessageRequest = new SendMessage();
    sendMessageRequest.setChatId(message.getChatId().toString());
    ReplyKeyboardHide replyKeyboardHide = new ReplyKeyboardHide();
    replyKeyboardHide.setSelective(true);
    sendMessageRequest.setReplayMarkup(replyKeyboardHide);
    sendMessageRequest.setReplayToMessageId(message.getMessageId());
    Message sentMessage = null;
    for (String direction : directions) {
      sendMessageRequest.setText(direction);
      SenderHelper.SendApiMethodAsync(
          sendMessageRequest,
          TOKEN,
          new SentCallback<Message>() {
            @Override
            public void onResult(BotApiMethod<Message> method, JSONObject jsonObject) {
              Message sentMessage = method.deserializeResponse(jsonObject);
              if (sentMessage != null) {
                DatabaseManager.getInstance().deleteUserForDirections(message.getFrom().getId());
              }
            }

            @Override
            public void onError(BotApiMethod<Message> method, JSONObject jsonObject) {}
          });
    }
  }
Esempio n. 12
0
  @Test
  public void invalidAddressesShouldBeAllowed() throws Exception {
    String headers =
        "From: user <userdomain>\n"
            + "To: user1 <user1domain>, user2 <user2domain>\n"
            + "Cc: usercc <userccdomain>\n"
            + "Bcc: userbcc <userbccdomain>\n"
            + "Subject: test subject\n";
    MetaDataWithContent testMail =
        MetaDataWithContent.builder()
            .uid(MessageUid.of(2))
            .flags(new Flags(Flag.SEEN))
            .size(headers.length())
            .internalDate(INTERNAL_DATE)
            .content(new ByteArrayInputStream(headers.getBytes(Charsets.UTF_8)))
            .attachments(ImmutableList.of())
            .mailboxId(MAILBOX_ID)
            .messageId(MessageId.of("user|box|2"))
            .build();

    Message testee = messageFactory.fromMetaDataWithContent(testMail);

    Emailer user = Emailer.builder().name("user").email("userdomain").allowInvalid().build();
    Emailer user1 = Emailer.builder().name("user1").email("user1domain").allowInvalid().build();
    Emailer user2 = Emailer.builder().name("user2").email("user2domain").allowInvalid().build();
    Emailer usercc = Emailer.builder().name("usercc").email("userccdomain").allowInvalid().build();
    Emailer userbcc =
        Emailer.builder().name("userbcc").email("userbccdomain").allowInvalid().build();

    assertThat(testee.getFrom()).contains(user);
    assertThat(testee.getTo()).contains(user1, user2);
    assertThat(testee.getCc()).contains(usercc);
    assertThat(testee.getBcc()).contains(userbcc);
  }
  /*
   * This method would print FROM,TO and SUBJECT of the message
   */
  public static void writeEnvelope(Message m, MailInfo mail) throws Exception {
    log.info("This is the message envelope");
    log.info("---------------------------");
    Address[] a;

    // FROM
    if ((a = m.getFrom()) != null) {
      for (int j = 0; j < a.length; j++) {
        log.info("FROM: " + a[j].toString());
        InternetAddress adress = (InternetAddress) a[j];
        mail.setFrom(adress.getAddress());
      }
    }

    // TO
    if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
      for (int j = 0; j < a.length; j++) {
        log.info("TO: " + a[j].toString());
        mail.setTo(a[j].toString());
      }
    }

    // SUBJECT
    if (m.getSubject() != null) {
      log.info("SUBJECT: " + m.getSubject());
      mail.setSubject(m.getSubject());
    }
  }
  public void sendUdpOneWay(Message message, EndPoint to) {
    EndPoint from = message.getFrom();
    if (message.getFrom().equals(to)) {
      MessagingService.receive(message);
      return;
    }

    UdpConnection connection = null;
    try {
      connection = new UdpConnection();
      connection.init();
      connection.write(message, to);
    } catch (IOException e) {
      logger_.warn(LogUtil.throwableToString(e));
    } finally {
      if (connection != null) connection.close();
    }
  }
  /*
      Use this version for fire and forget style messaging.
  */
  public void sendOneWay(Message message, EndPoint to) {
    // do local deliveries
    if (message.getFrom().equals(to)) {
      MessagingService.receive(message);
      return;
    }

    Runnable tcpWriteEvent = new MessageSerializationTask(message, to);
    messageSerializerExecutor_.execute(tcpWriteEvent);
  }
 private void onLanguageSelected(Message message) throws InvalidObjectException {
   String[] parts = message.getText().split("-->", 2);
   SendMessage sendMessageRequest = new SendMessage();
   sendMessageRequest.setChatId(message.getChatId().toString());
   if (LocalisationService.getInstance().getSupportedLanguages().containsKey(parts[0].trim())) {
     DatabaseManager.getInstance().putUserLanguage(message.getFrom().getId(), parts[0].trim());
     sendMessageRequest.setText(
         LocalisationService.getInstance().getString("languageModified", parts[0].trim()));
   } else {
     sendMessageRequest.setText(LocalisationService.getInstance().getString("errorLanguage"));
   }
   sendMessageRequest.setReplayToMessageId(message.getMessageId());
   ReplyKeyboardHide replyKeyboardHide = new ReplyKeyboardHide();
   replyKeyboardHide.setHideKeyboard(true);
   replyKeyboardHide.setSelective(true);
   sendMessageRequest.setReplayMarkup(replyKeyboardHide);
   SenderHelper.SendApiMethod(sendMessageRequest, TOKEN);
   languageMessages.remove(message.getFrom().getId());
 }
Esempio n. 17
0
  private void sendMessageTo(ArrayList<String> addresses, Message message)
      throws MessagingException {
    boolean possibleSend = false;

    close();
    open();

    message.setEncoding(m8bitEncodingAllowed ? "8bit" : null);
    // If the message has attachments and our server has told us about a limit on
    // the size of messages, count the message's size before sending it
    if (mLargestAcceptableMessage > 0 && ((LocalMessage) message).hasAttachments()) {
      if (message.calculateSize() > mLargestAcceptableMessage) {
        MessagingException me = new MessagingException("Message too large for server");
        me.setPermanentFailure(possibleSend);
        throw me;
      }
    }

    Address[] from = message.getFrom();
    try {
      // TODO: Add BODY=8BITMIME parameter if appropriate?
      executeSimpleCommand("MAIL FROM:" + "<" + from[0].getAddress() + ">");
      for (String address : addresses) {
        executeSimpleCommand("RCPT TO:" + "<" + address + ">");
      }
      executeSimpleCommand("DATA");

      EOLConvertingOutputStream msgOut =
          new EOLConvertingOutputStream(
              new SmtpDataStuffing(
                  new LineWrapOutputStream(new BufferedOutputStream(mOut, 1024), 1000)));

      message.writeTo(msgOut);

      // We use BufferedOutputStream. So make sure to call flush() !
      msgOut.flush();

      possibleSend = true; // After the "\r\n." is attempted, we may have sent the message
      executeSimpleCommand("\r\n.");
    } catch (Exception e) {
      MessagingException me = new MessagingException("Unable to send message", e);

      // "5xx text" -responses are permanent failures
      String msg = e.getMessage();
      if (msg != null && msg.startsWith("5")) {
        Log.w(K9.LOG_TAG, "handling 5xx SMTP error code as a permanent failure");
        possibleSend = false;
      }

      me.setPermanentFailure(possibleSend);
      throw me;
    } finally {
      close();
    }
  }
  public static void dumpEnvelope(Message m) throws Exception {
    pr("This is the message envelope");
    pr("---------------------------");
    Address[] a;
    // FROM
    if ((a = m.getFrom()) != null) {
      for (int j = 0; j < a.length; j++) pr("FROM: " + a[j].toString());
    }

    // TO
    if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
      for (int j = 0; j < a.length; j++) pr("TO: " + a[j].toString());
    }

    // SUBJECT
    pr("SUBJECT: " + m.getSubject());

    // DATE
    Date d = m.getSentDate();
    pr("SendDate: " + (d != null ? d.toString() : "UNKNOWN"));

    // FLAGS
    Flags flags = m.getFlags();
    StringBuffer sb = new StringBuffer();
    Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags

    boolean first = true;
    for (int i = 0; i < sf.length; i++) {
      String s;
      Flags.Flag f = sf[i];
      if (f == Flags.Flag.ANSWERED) s = "\\Answered";
      else if (f == Flags.Flag.DELETED) s = "\\Deleted";
      else if (f == Flags.Flag.DRAFT) s = "\\Draft";
      else if (f == Flags.Flag.FLAGGED) s = "\\Flagged";
      else if (f == Flags.Flag.RECENT) s = "\\Recent";
      else if (f == Flags.Flag.SEEN) s = "\\Seen";
      else continue; // skip it
      if (first) first = false;
      else sb.append(' ');
      sb.append(s);
    }

    String[] uf = flags.getUserFlags(); // get the user flag strings
    for (int i = 0; i < uf.length; i++) {
      if (first) first = false;
      else sb.append(' ');
      sb.append(uf[i]);
    }
    pr("FLAGS: " + sb.toString());

    // X-MAILER
    String[] hdrs = m.getHeader("X-Mailer");
    if (hdrs != null) pr("X-Mailer: " + hdrs[0]);
    else pr("X-Mailer NOT available");
  }
Esempio n. 19
0
 public void process(Packet packet) {
   // Check that the requested packet can be processed
   if (canProcess(packet)) {
     // Perform the actual processing of the packet. This usually implies sending
     // the packet to the entity
     try {
       // Invoke the interceptors before we send the packet
       InterceptorManager.getInstance().invokeInterceptors(packet, this, false, false);
       deliver(packet);
       // Invoke the interceptors after we have sent the packet
       InterceptorManager.getInstance().invokeInterceptors(packet, this, false, true);
     } catch (PacketRejectedException e) {
       // An interceptor rejected the packet so do nothing
     } catch (Exception e) {
       Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
     }
   } else {
     // http://xmpp.org/extensions/xep-0016.html#protocol-error
     if (packet instanceof Message) {
       // For message stanzas, the server SHOULD return an error, which SHOULD be
       // <service-unavailable/>.
       Message message = (Message) packet;
       Message result = message.createCopy();
       result.setTo(message.getFrom());
       result.setError(PacketError.Condition.service_unavailable);
       XMPPServer.getInstance().getRoutingTable().routePacket(message.getFrom(), result, true);
     } else if (packet instanceof IQ) {
       // For IQ stanzas of type "get" or "set", the server MUST return an error, which SHOULD be
       // <service-unavailable/>.
       // IQ stanzas of other types MUST be silently dropped by the server.
       IQ iq = (IQ) packet;
       if (iq.getType() == IQ.Type.get || iq.getType() == IQ.Type.set) {
         IQ result = IQ.createResultIQ(iq);
         result.setError(PacketError.Condition.service_unavailable);
         XMPPServer.getInstance().getRoutingTable().routePacket(iq.getFrom(), result, true);
       }
     }
   }
 }
Esempio n. 20
0
 /**
  * Puts a message in the database Note: the timestamp will be stored as the current time at which
  * this method is called.
  */
 public void storeMessage(Message message) {
   con.updateDB(
       "INSERT INTO "
           + MESSAGES
           + " VALUES ( \""
           + message.getFrom()
           + "\", \""
           + message.getTo()
           + "\", \""
           + message.getBody()
           + "\", "
           + null
           + ", "
           + message.getType()
           + ")");
 }
 private void onSetLanguageCommand(Message message, String language)
     throws InvalidObjectException {
   SendMessage sendMessageRequest = new SendMessage();
   sendMessageRequest.setChatId(message.getChatId().toString());
   ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup();
   HashMap<String, String> languages = LocalisationService.getInstance().getSupportedLanguages();
   List<List<String>> commands = new ArrayList<>();
   for (Map.Entry<String, String> entry : languages.entrySet()) {
     List<String> commandRow = new ArrayList<>();
     commandRow.add(entry.getKey() + " --> " + entry.getValue());
     commands.add(commandRow);
   }
   replyKeyboardMarkup.setResizeKeyboard(true);
   replyKeyboardMarkup.setOneTimeKeyboad(true);
   replyKeyboardMarkup.setKeyboard(commands);
   replyKeyboardMarkup.setSelective(true);
   sendMessageRequest.setReplayMarkup(replyKeyboardMarkup);
   sendMessageRequest.setText(
       LocalisationService.getInstance().getString("chooselanguage", language));
   SenderHelper.SendApiMethod(sendMessageRequest, TOKEN);
   languageMessages.add(message.getFrom().getId());
 }
Esempio n. 22
0
  public Object getValueAt(int row, int column) {
    try {
      Message message = getMessage(row);
      switch (column) {
        case 0:
          // Answered?
          return (message.isSet(Flags.Flag.ANSWERED) ? "R" : "");

        case 1:
          // From.
          Address[] addresses = message.getFrom();
          if (addresses == null || addresses.length == 0) {
            return "(No sender)";
          }
          // Given "Personal Name <*****@*****.**>", choose "Personal Name" if it's available, and
          // "*****@*****.**" if not.
          InternetAddress address = (InternetAddress) addresses[0];
          String name = address.getPersonal();
          return (name != null) ? name : address.getAddress();

        case 2:
          // Subject.
          String subject = message.getSubject();
          return (subject != null) ? subject : "(No subject)";

        case 3:
          // Date.
          Date date = message.getReceivedDate();
          return (date != null) ? Mailer.dateToIsoString(date) : "Unknown";

        default:
          return "<no-column-" + column + ">";
      }
    } catch (MessagingException ex) {
      ex.printStackTrace();
      return "<error>";
    }
  }
Esempio n. 23
0
 /** Returns the from field. */
 public String getFrom() throws MessagingException {
   return formatAddresses(message.getFrom());
 }
Esempio n. 24
0
 /** Method for checking if the message has a from field. */
 public boolean hasFrom() throws MessagingException {
   return (message.getFrom() != null);
 }
Esempio n. 25
0
  public static void dumpPart(Part p) throws Exception {
    if (p instanceof Message) {
      Message m = (Message) p;
      Address[] a;
      // FROM
      if ((a = m.getFrom()) != null) {
        for (int j = 0; j < a.length; j++) System.out.println("FROM: " + a[j].toString());
      }

      // TO
      if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
        for (int j = 0; j < a.length; j++) System.out.println("TO: " + a[j].toString());
      }

      // SUBJECT
      System.out.println("SUBJECT: " + m.getSubject());

      // DATE
      Date d = m.getSentDate();
      System.out.println("SendDate: " + (d != null ? d.toLocaleString() : "UNKNOWN"));

      // FLAGS:
      Flags flags = m.getFlags();
      StringBuffer sb = new StringBuffer();
      Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags

      boolean first = true;
      for (int i = 0; i < sf.length; i++) {
        String s;
        Flags.Flag f = sf[i];
        if (f == Flags.Flag.ANSWERED) s = "\\Answered";
        else if (f == Flags.Flag.DELETED) s = "\\Deleted";
        else if (f == Flags.Flag.DRAFT) s = "\\Draft";
        else if (f == Flags.Flag.FLAGGED) s = "\\Flagged";
        else if (f == Flags.Flag.RECENT) s = "\\Recent";
        else if (f == Flags.Flag.SEEN) s = "\\Seen";
        else continue; // skip it
        if (first) first = false;
        else sb.append(' ');
        sb.append(s);
      }

      String[] uf = flags.getUserFlags(); // get the user flag strings
      for (int i = 0; i < uf.length; i++) {
        if (first) first = false;
        else sb.append(' ');
        sb.append(uf[i]);
      }
      System.out.println("FLAGS = " + sb.toString());
    }

    System.out.println("CONTENT-TYPE: " + p.getContentType());

    /* Dump input stream
    InputStream is = ((MimeMessage)m).getInputStream();
    int c;
    while ((c = is.read()) != -1)
        System.out.write(c);
    */

    Object o = p.getContent();
    if (o instanceof String) {
      System.out.println("This is a String");
      System.out.println((String) o);
    } else if (o instanceof Multipart) {
      System.out.println("This is a Multipart");
      Multipart mp = (Multipart) o;
      int count = mp.getCount();
      for (int i = 0; i < count; i++) dumpPart(mp.getBodyPart(i));
    } else if (o instanceof InputStream) {
      System.out.println("This is just an input stream");
      InputStream is = (InputStream) o;
      int c;
      while ((c = is.read()) != -1) System.out.write(c);
    }
  }