Home » Java » Java method for parsing messages from Main to HttpServlet to display events

Java method for parsing messages from Main to HttpServlet to display events

Posted by: admin May 17, 2018 Leave a comment

Questions:

I have an email monitor processing incoming requests. Emails contain simple IMAP text transactions. After processing each I want to post an event message to a HTTPServlet to display like a syslog monitor. Have played with Server Sent method but have been struggling for days to achieve this. Any advice would be very helpful.

This is a section of the email monitor…

  public void getNewEmails(String protocol, String host, 
  String port, String userName, String password) throws InterruptedException 
   {
  Properties properties = getServerProperties(protocol, host, port);
  Session session = Session.getDefaultInstance(properties);
  try {
    Store store = session.getStore(protocol);
    store.connect(userName, password);
    Folder inbox = store.getFolder("INBOX");
    inbox.open(Folder.READ_WRITE);
    //Folder outputFolder = store.getFolder("INBOX/PROCESSED_GOOD");

    int count = inbox.getMessageCount();
    Message[] messages = inbox.getMessages(1, count);
    System.out.println("About to process... " + messages.length + " messages");

    for (int i = 0, n = messages.length; i < n; i++) {
        Message message = messages[i];
        if (!message.getFlags().contains(Flags.Flag.SEEN)) 
        {
            System.out.println("-------------------------------------");
            System.out.println("Email Number " + (i));
            System.out.println("\t Flag status: >>>>>>> " + message.getFlags().toString());
            try {
                writePart(message);
                //   >>>>>> Post message to HTTPServlet to confirm event <<<<<<<
                //   >>>>>> Post message to HTTPServlet to confirm event <<<<<<<
                //   >>>>>> Post message to HTTPServlet to confirm event <<<<<<<
                }
            catch (Exception e) 
                {
                e.printStackTrace();
                }
            //message.setFlag((Flags.Flag.SEEN),true);//Resetting email use .remove(Flags.Flag.SEEN);
            try {
                System.out.println(message.getContent().toString());
                } 
            catch (Exception ex) 
                {
                System.out.println("Error reading content!!");
                ex.printStackTrace();
            }
            //moveMessage(message, outputFolder);
        }
    }
    inbox.close(false);
    store.close();      
  }
  catch (NoSuchProviderException ex) 
  {
      System.out.println("No provider for protocol: " + protocol);
      ex.printStackTrace();
  } 

catch (MessagingException ex) 
    {
    System.out.println("Could not connect to the message store");
    ex.printStackTrace();
    }
}

This is the Servlet…

    package com.udigital.sse;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Calendar;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

        @WebServlet("/SSEServlet")
        public class SSEServlet extends HttpServlet 
        {
            private static final long serialVersionUID = 1L;
            public String messageFrom;

            protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
                response.setContentType("text/event-stream");
                response.setCharacterEncoding("UTF-8");
                PrintWriter printWriter = null;
                System.out.println("Email monitor up and running...");
                while (true){
                    try {
                        printWriter = response.getWriter();
                        //   >>>>> Echo - waiting for messages from email monitor <<<<<
                        //   >>>>> Echo - waiting for messages from email monitor <<<<<
                        //   >>>>> Echo - waiting for messages from email monitor <<<<<
                         printWriter.print("New Email Received From: " + messageFrom + " : at time:   " + Calendar.getInstance().getTime() + "\n\n");
                        response.flushBuffer();
                        Thread.sleep((long) 1000);//Wait - give email server time to breath  :)
                        }catch (IOException  | InterruptedException e)
                            {
                            printWriter.close();
                            break;
                            }
                }
            }
        }

This is the html page to display the incoming messages…

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Email Processing - Demo</title>
</head>
<body>
  <button id="startButton" onclick="start()">Start</button>
  <button onclick="stop()">Stop</button>
  <button onclick="clearText()">Clear</button>
  <br>
  <textarea id="displayTextArea" readonly="readonly" rows="30" cols="45"></textarea><br/>
  <!-- print("Random number generated") -->
  <script>
    function start() {
      displayTextArea.value = "starting";
      eventSource = new EventSource('http://localhost:8080/ServerSentProject/SSEServlet');
      eventSource.onopen = function() {
        displayTextArea.value += 'Connected ..' + '\n';
      };
      eventSource.onmessage = function(message) {
        displayTextArea.value += message.data + '\n\n';
      };
      eventSource.onerror = function() {
        displayTextArea.value += 'Error Occurred...' + '\n';
      };
    }
    function stop() {
      eventSource.close();
      startButton.disabled = false;
    }
    function clearText() {
      displayTextArea.value = '';
    }
  </script>
</body>
</html>
Answers: