Link to home
Start Free TrialLog in
Avatar of LeanMoreTryMore
LeanMoreTryMore

asked on

StackOverflowError

Would anyone give me some idea how to tackle the StackOverflowError problem?

The java program I have developed is run as an interface manager. This performs multi-threads operation. Inititally it creates 3 threads and keeps in READY-TO-USE stage. The problem is I keep getting the StackOverflowError error. But I dont have any idea how to resolve this problem.

Does the System.out.println cause this problem as I have already comment out all System.out.println so that this means it wont send any message to the buffer.
Avatar of Mick Barry
Mick Barry
Flag of Australia image

generally its recursion gone wrong
the stacj trace is a good place to start
Avatar of LeanMoreTryMore
LeanMoreTryMore

ASKER

how do i do the stack trace?

Do you mean I put e.printStackTrace() on the recursion function?
Please give me more details
Put e.printStackTrace () in your catch blocks. Post your code.
Notes that this is a multi-thread program.

1. It constantly checks the email account
2. It constantly looks at the table to check if any new user request

See below my codes
==============
public class UTeventScheduler extends MailUtilities implements EvtConfig {

  public static void main(String[] args)  throws Exception {
     userName = args[0];
     pwd      = args[1];
     dbName   = args[2];

     int dbConnOk = Utilities.SQLJdbConnection(userName, pwd, dbName );
     if ( dbConnOk == 0 ) {
        new UTeventScheduler();
     }
     else {
       System.out.println("UTeventScheduler.main: Process is aborted. Failed to establish a database connection");
       System.exit(1);
     }
  } // main



  private UTeventScheduler() throws Exception
  {
    workingDrive    = Utilities.schDrive;
    terminal_no     = Utilities.terminal;
    sessionProgram  = Utilities.sessionProg;
    if (IsRunningOnNetwork(terminal_no).equals("Y")) {
      workingDrive = "N";
    }
    // System.out.println("workingDrive:" + workingDrive);
    int totalSschdRunning = schedulerRunning(sessionProgram);

    // System.out.println("v$session.totalSschdRunning:" + totalSschdRunning);
    if ( totalSschdRunning > 1 )
       System.exit(0);
    //
    try {
       #sql [ new ExecutionContext() ] {
            CALL UT_EVENT_SCHEDULER_PKG.pu_switch_on_schd(:sessionProgram)
       };
    }
    catch (Exception e) {
       System.out.println("UTeventScheduler: Error due to " + e);
    };
    //Start 3 threats that are in READY-TO-USE stage
    exeEvent[ HIGH_PRIORITY_EVENT ] = new executeEvent( HIGH_PRIORITY_EVENT );
    exeEvent[ HIGH_PRIORITY_EVENT ].start();
    exeEvent[ MID_PRIORITY_EVENT ] = new executeEvent( MID_PRIORITY_EVENT );
    exeEvent[ MID_PRIORITY_EVENT ].start();
    exeEvent[ LOW_PRIORITY_EVENT ] = new executeEvent( LOW_PRIORITY_EVENT );
    exeEvent[ LOW_PRIORITY_EVENT ].start();

    updateEvent();
  } // eventScheduler


  private void updateEvent()
  {
    while (true) {
      try {
        getSchSysParams();
        emailRecs emailIter = null;
        #sql emailIter =
        {
          SELECT u.email_user_acct                         email_user_acct
                ,XORBIN(u.email_user_pwd,'ABDEFGHIJKLMN')  email_user_pwd
                ,u.email_subject                           email_subject
                ,up.program_id                             program_id
                ,u.output_filename                         output_filename
          FROM   ut_program up, ut_email_interface_conf u, ut_party_workflow upw
          WHERE  u.email_user_acct IS NOT NULL
          AND    u.email_user_pwd  IS NOT NULL
          AND    u.email_subject   IS NOT NULL
          AND    u.appl_code     = upw.appl_code
          AND    u.process_type  = upw.process_type
          AND    upw.program_id  = up.program_id
        };
        while (emailIter.next()) {
          exchangeData(Utilities.emailHost
                      ,emailIter.email_user_acct()
                      ,emailIter.email_user_pwd()
                      ,emailIter.email_subject()
                      ,applHome);

        }
        // Check any email is due to send out
        SendemailRec SendEmailIter  = null;
        #sql SendEmailIter =
        {
          SELECT uer.email_subject        email_subject
                ,uer.email_address
                ,uer.email_attachment
                ,upw.message              email_content
                ,u.output_filename        output_filename
                ,uer.rowid                email_request_rowid
          FROM   ut_email_request uer
               , ut_party_workflow upw
                ,ut_email_interface_conf u
          WHERE  uer.appl_code    = upw.appl_code
          AND    uer.process_type = upw.process_type
          AND    uer.interface_code = u.interface_code
          AND    uer.status       = 'P'
        };
        while (SendEmailIter.next()) {
          updateEmailReqStatus(SendEmailIter.email_request_rowid(),"I");
          exitCode = MailUtilities.MSoutlookSend(SendEmailIter.email_address()
                                                ,Utilities.emailFrom
                                                ,Utilities.emailHost
                                                ,SendEmailIter.email_subject()
                                                ,adminEmailUser
                                                ,adminEmailPwd
                                                ,SendEmailIter.email_content()
                                                ,"NULL"
                                                ,SendEmailIter.email_attachment()
                                                ,SendEmailIter.output_filename());
          deleteEmailRequest(SendEmailIter.email_request_rowid());
        }
        int totalThreads = maxThreads;
        if ( terminateProcess.equals("Y")) {
          System.exit(0);
        }
        vHighPriorityEvents.trimToSize();
        vMidPriorityEvents.trimToSize();
        vLowPriorityEvents.trimToSize();

        int vTotalHighPriorityElements = vHighPriorityEvents.capacity();
        int vTotalMidPriorityElements  = vMidPriorityEvents.capacity();
        int vTotalLowPriorityElements  = vLowPriorityEvents.capacity();

        int eventRequests = ( vTotalHighPriorityElements +
                              vTotalMidPriorityElements  +
                              vTotalLowPriorityElements == 0 ) ?
        maxThreads : maxThreads - vTotalHighPriorityElements
                                    - vTotalMidPriorityElements
                                    - vTotalLowPriorityElements;
        if ( eventRequests > 0 ) {
           updateEventStatus(0,"P",""); /* (P)ending */
           insertEvent(eventRequests);

          /**
           * Only create a thread as needed.
           * Notes: be aware of that this consumes a lot of memory where creating
           *        a thread or keeping a thread in the READY-TO-USE stage
           **/

           totalThreads = maxThreads -
                             exeEvent[ HIGH_PRIORITY_EVENT ].activeCount() -
                             exeEvent[ MID_PRIORITY_EVENT ].activeCount()  -
                             exeEvent[ LOW_PRIORITY_EVENT ].activeCount();

              // Create a priority with high priority
              if (  ( ! exeEvent[ HIGH_PRIORITY_EVENT ].isAlive())
                 && ( ! vHighPriorityEvents.isEmpty()))  {
                 exeEvent[ HIGH_PRIORITY_EVENT ] = new executeEvent( HIGH_PRIORITY_EVENT );
                 exeEvent[ HIGH_PRIORITY_EVENT ].start();
              }
              else
              {
                 if (  ( ! vHighPriorityEvents.isEmpty()))  {
                   exeEvent[ HIGH_PRIORITY_EVENT ] = new executeEvent( HIGH_PRIORITY_EVENT );
                   exeEvent[ HIGH_PRIORITY_EVENT ].start();
                 }
              }
              // Create a priority with mid priority
              if (  ( ! exeEvent[ MID_PRIORITY_EVENT ].isAlive())
                 && ( ! vMidPriorityEvents.isEmpty())) {
                 exeEvent[ MID_PRIORITY_EVENT ] = new executeEvent( MID_PRIORITY_EVENT );
                 exeEvent[ MID_PRIORITY_EVENT ].start();
              }
              else
              {
                 if (  ( ! vMidPriorityEvents.isEmpty())) {
                   exeEvent[ MID_PRIORITY_EVENT ] = new executeEvent( MID_PRIORITY_EVENT );
                   exeEvent[ MID_PRIORITY_EVENT ].start();
                 }
              }
              // Create a priority with lower priority
              if (  ( ! exeEvent[ LOW_PRIORITY_EVENT ].isAlive())
                 && ( ! vLowPriorityEvents.isEmpty())) {
                 exeEvent[ LOW_PRIORITY_EVENT ] = new executeEvent( LOW_PRIORITY_EVENT );
                 exeEvent[ LOW_PRIORITY_EVENT ].start();
              }
              else
              {
                 if (  ( ! vLowPriorityEvents.isEmpty())) {
                   exeEvent[ LOW_PRIORITY_EVENT ] = new executeEvent( LOW_PRIORITY_EVENT );
                   exeEvent[ LOW_PRIORITY_EVENT ].start();
                 }
              }
          // } // end of for
        } // eventRequests => 0
        Thread.sleep(10000);
      } // End of Try
      catch (InterruptedException ie) {
        ie.printStackTrace();
        System.out.println("UTeventScheduler.updateEvent(): Interrupted Exception error occured due to " + ie);
        System.exit(1);
      }
      catch (Exception e) {
        e.printStackTrace();
        System.out.println("UTeventScheduler.updateEvent(): Exception error occured due to " + e);
        System.exit(1);
      }
    } // End of While loop
   }  // updateEvent



   private void insertEvent(int pEventRequests)
   {
     eventRecs eventIter        = null;
     int       eventPriority    = HIGH_PRIORITY_EVENT;
     try{
       int eventCounter = 0;
       #sql eventIter =
       {
          SELECT ujr.jr_no                                jr_no
                ,DECODE(usc.job_type,'RW',1
                                    ,'D' ,2
                                    ,'J' ,3
                                    ,'F' ,4,0)            program_type
                ,NVL(usc.command_line,'NULL')             command_line
                ,NVL(usc.desname,'NULL')                  desname
                ,NVL(usc.report_param,'NULL')             report_param
                ,NVL(usc.output_filename,'NULL')          output_filename
                ,usc.op_login                             op_login
                ,usc.description                          description
                ,usc.process_id                           process_id
          FROM   ut_schedule_client  usc
                ,ut_job_recurrence   ujr
                ,ut_scheduled_date   usd
          WHERE  usd.job_origin            = 'CLIENT'
          AND    usd.client_process_status = 'P'
          AND    usd.jr_no                 = ujr.jr_no
          AND    ujr.jr_no                 = usc.jr_no
          AND    ujr.selected_scheduler    = DECODE(:workingDrive,'C','PC','NS')
          AND ( (:workingDrive    = 'C'
             AND usc.terminal_no = :terminal_no )
             OR (:workingDrive   <> 'C'
             and usc.terminal_no  = usc.terminal_no ))
          AND    usc.schd_job_status       = 'A'
          AND   ROWNUM BETWEEN 1 AND :maxThreads
          UNION
          SELECT jr_no                                           jr_no
                ,DECODE(job_type,'RW',1
                                    ,'D' ,2
                                    ,'J' ,3
                                    ,'F' ,4,0)                   program_type
                ,NVL(command_line,'NULL')                        command_line
                ,NVL(desname,'NULL')                             desname
                ,NVL(report_param,'NULL')                        report_param
                ,NVL(output_filename,'NULL')                     output_filename
                ,NVL(op_login,'NULL')                            op_login
                ,description                                     description
                ,process_id
          FROM  ut_schedule_client
          WHERE schd_job_status IS NULL
       };
       // Extract event details awaiting to be processed
       while (eventIter.next()) {
          int    jr_no    = eventIter.jr_no();
          int    whichOne = eventIter.program_type();
          // int    processId = eventIter.process_id();
          String commandLine      = "";
          String rptParameter     = "";
          String desname          = "";
          String outfileName      = "";
          String executeCmdString = "";
          eventCounter++;

          if ( eventCounter == 1 )
             eventPriority = 1;

          if ( eventCounter == 2 )
             eventPriority = 2;

          if ( eventCounter == 3 )
             eventPriority = 3;

          switch (whichOne)
          {
            // Oracle Report V.6
            case 1:
               if (eventIter.process_id()>0) {
                 if ( ! eventIter.report_param().equals("NULL") ) {
                    rptParameter = reconsturctParamLine(eventIter.report_param());
                    executeCmdString = eventIter.command_line()  + " " +
                                       "USERID=" + userName + "/" + pwd + "@" + dbName + " " +
                                       eventIter.desname()       + " " +
                                       rptParameter;
                    outfileName = eventIter.output_filename();
                 }
               }
               else {
                    rptParameter = eventIter.report_param();
                    executeCmdString = oracleHome + "rwrun60.exe"              +
                                       "  REPORT=\"" + applHome                +
                                       eventIter.command_line() + "\" "        +
                                       "USERID=" + userName + "/" + pwd + "@"  +
                                       dbName + " " + rptParameter;
               }
              break;
            // Database Package
            case 2:
                  executeCmdString = eventIter.command_line() + eventIter.report_param() + ";";
              break;
            // Java script
            case 3:
                  executeCmdString = Utilities.javaPath + " " + eventIter.command_line() + " " +
                                     Utilities.dbConn   + " " + eventIter.report_param();
              break;
            // Oracle Form
            case 4:
                  executeCmdString = eventIter.command_line() + " " + eventIter.report_param() ;
              break;
            default:
              System.out.println("Cant identify the program type ");
              break;
          }
          Event  evt = new Event(eventIter.jr_no()
                                ,eventIter.program_type()
                                ,executeCmdString
                                ,outfileName
                                ,eventIter.op_login()
                                ,eventIter.description());
           /**
           * Add the event to Event Vector in descending order.
           * The event in the vector is awaiting to be processed.
           * Once the event is added to the vector, its status is set to
           * "PENDING".
           **/
           try {
             switch (eventPriority)
             {
               case 1:
                     vHighPriorityEvents.addElement(evt);
                     break;
               case 2:
                     vMidPriorityEvents.addElement(evt);
                     break;
               case 3:
                     vLowPriorityEvents.addElement(evt);
                     break;
               default:
                     vHighPriorityEvents.addElement(evt);
                     break;
             }
             updateEventStatus(evt._jr_no, PENDING, "");
           }
           catch (Exception e) {
             String ErrorMsg = "Failed to update the event status due to " + e;
             updateEventStatus(evt._jr_no, ERROR, "");
             eventlogRec(evt._jr_no, ErrorMsg);
           }
        }  // End of While loop
      } // End of try
      catch (SQLException e) {
        e.printStackTrace();
        System.out.println("Error occured in the main query due to "+ e);
        System.exit(1);
      }
      finally {
        try {
          if ( eventIter != null ) {
            eventIter.close();
          }

        }
        catch (SQLException e) {
          e.printStackTrace();
          Utilities.emailToOperator(Utilities.emailTo, Utilities.emailFrom,Utilities.emailHost
                                ,"Fatal Error : 2000Plus Scheduler was aborted due to " + e + emailEndMsg
                                ,"NULL");
          System.exit(1);
        }
      } // End of finally
  } // insertEvent



   class executeEvent extends Thread
   {
     int _eventPriority;
     String returnValue = "";
     public executeEvent(int eventPriority ) {
       _eventPriority     = eventPriority;
     }

     public void run()
     {
       System.out.println("executeEvent._eventPriority:" + _eventPriority);
       Enumeration enum = null;
       switch (_eventPriority) {
         case 1:
                 enum = vHighPriorityEvents.elements();
                 break;
         case 2:
                 enum = vMidPriorityEvents.elements();
                 break;
         case 3:
                 enum = vLowPriorityEvents.elements();
                 break;
         default:
                 break;
       }
       while ( enum.hasMoreElements())
       {

          Event eventQueue =  (Event) enum.nextElement();
          updateEventStatus(eventQueue._jr_no,INPROGRESS,"");
          try {
            // Remove the event from the event vector before executing the CmdString
            removeVector(eventQueue, _eventPriority);
            if ( eventQueue._programType == 2 ) {
              try {
                deleteChildProcess(eventQueue._jr_no);
                String dbpk_name = eventQueue._executeCmdString;
                returnValue = "";
                #sql [ new ExecutionContext()]
                {
                   CALL UT_EVENT_SCHEDULER_PKG.pu_exe_dynamic_sql(:IN dbpk_name)
                };
                //System.out.println("RetrunValue => " + returnValue);
              }
              catch (SQLException e) {
                reason   = "Failed to execute the program " + eventQueue._executeCmdString;
                updateEventStatus(eventQueue._jr_no,ERROR,"");
                eventlogRec(eventQueue._jr_no, reason);
              }
            }
            else {
              deleteChildProcess(eventQueue._jr_no);
              eventlogRec(eventQueue._jr_no, "Process Start : "  + processDateTime() + " - " + eventQueue._executeCmdString);
              int returnProcessValue = Runtime.getRuntime().exec(eventQueue._executeCmdString).waitFor();
              if ( returnProcessValue == 0) {
                 //System.out.println("called job completed");
                 updateEventStatus(eventQueue._jr_no ,COMPLETED,eventQueue._outputFileName);
                 eventlogRec(eventQueue._jr_no, "Process Completed : "  + processDateTime());
              }
              else  {
                reason   = "Failed to execute the program " + eventQueue._executeCmdString;
                updateEventStatus(eventQueue._jr_no,ERROR,"");
                eventlogRec(eventQueue._jr_no, reason);
                sendAlertEmail(reason,eventQueue._opLogin, eventQueue._description);
                // removeVector(evt, _eventPriority);
              } // end if Runtime
            }   // End if for checking program Type
          }
          catch (Exception e) {
            System.out.println("executeEvent. Error due to " + e);
            System.exit(1);
            //reason = "Error due to " + e;
            //updateEventStatus(eventQueue._jr_no ,COMPLETED,eventQueue._outputFileName);
            updateEventStatus(eventQueue._jr_no,ERROR,"");
            //eventlogRec(eventQueue._jr_no, "Process Completed : "  + processDateTime());
            eventlogRec(eventQueue._jr_no, reason);
            sendAlertEmail(reason,eventQueue._opLogin, eventQueue._description);
          };
       }  // End of While loop
     } // End or run()
   } // End of executeEvent



   protected void removeVector(Event pEvt, int pEventPriority)
   {
     switch (pEventPriority) {
      case 1:
          vHighPriorityEvents.removeElement(pEvt);
          break;
      case 2:
          vMidPriorityEvents.removeElement(pEvt);
          break;
      case 3:
          vLowPriorityEvents.removeElement(pEvt);
          break;
      default:
             break;
     }
   } // End of removeVector



  protected void getSchSysParams()
  {
    try {
       // System.out.println("getSchSysParams.sessionProgram=>" + sessionProgram);
       #sql [ new ExecutionContext() ]
       {
         CALL UT_EVENT_SCHEDULER_PKG.pu_get_sys_params(:IN  sessionProgram
                                                      ,:OUT schOuputDir
                                                      ,:OUT maxThreads
                                                      ,:OUT terminateProcess
                                                      ,:OUT threadSleepTimes
                                                      ,:OUT adminEmailUser
                                                      ,:OUT adminEmailPwd
                                                      ,:OUT applHome
                                                      ,:OUT oracleHome)
       };
       if (applHome.equalsIgnoreCase("NULL")){
          emailMsg = "UTeventScheduler.getSchSysParams:2000Plus scheduler was aborted.\n Reason: Failed to get 2000Plus application home directory" + emailEndMsg;;
          Utilities.emailToOperator(Utilities.emailTo
                                   ,Utilities.emailFrom
                                   ,Utilities.emailHost
                                   ,emailMsg,"NULL");
       }
    }
    catch (SQLException e) {
      e.printStackTrace();
    }
      // Use the default setting for Event Scheduler if no system record is found
   } // getSchSysParams


   private String processDateTime()
   {
     try {
      #sql {
             SELECT TO_CHAR(SYSDATE,'DD-MON-YYYY HH24:MI')
             INTO :currentDateTime
             FROM dual
         };
       //System.out.println("currentDateTime => " + currentDateTime);
       return (currentDateTime);
     }
     catch (SQLException e) {
       e.printStackTrace();
       return("Error due to " + e);
     }
   }

   private String reconsturctParamLine(String iRptParam)
   {
     String l_rtn_String   = "NULL";
     try  {
       #sql l_rtn_String = { VALUES(UT_EVENT_SCHEDULER_PKG.fu_reconst_client_cmdline(:iRptParam)) };
       return (l_rtn_String);
     }
     catch (SQLException e) {
       e.printStackTrace();
       return ("ERROR");
     }
   }


   protected void eventlogRec(int    iJrNo
                             ,String iReason)
   {
     try  {
       #sql [ new ExecutionContext() ]
       {
         CALL UT_EVENT_SCHEDULER_PKG.create_event_log(:iJrNo,:iReason, 'CLIENT')
       };
     }
     catch (SQLException e) {
     e.printStackTrace();
     }
   }// logErrorRec


   protected void updateEmailReqStatus(String iEmailReqRowId, String iEmailProcessStatus)
   {
     try  {
       #sql [ new ExecutionContext() ]
       {
         CALL UT_EVENT_SCHEDULER_PKG.pu_update_email_request_status(:iEmailReqRowId, :iEmailProcessStatus)
       };
     }
     catch (SQLException e) { e.printStackTrace(); }
   }// updateEmailReqStatus


   protected void deleteEmailRequest(String iEmailReqRowId)
   {
     try  {
       #sql [ new ExecutionContext() ]
       {
         CALL UT_EVENT_SCHEDULER_PKG.pu_delete_email_request(:iEmailReqRowId)
       };
     }
     catch (SQLException e) { e.printStackTrace(); }
   }// deleteEmailRequest


   protected void deleteChildProcess(int iJrNo)
   {
     try  {
       #sql [ new ExecutionContext() ]
       {
         CALL UT_EVENT_SCHEDULER_PKG.pu_delete_child_process(:iJrNo)
       };
     }
     catch (SQLException e) { e.printStackTrace(); }
   }// udpateChildProcessStatus



   protected void updateEventStatus(int    pJrNo
                                   ,String pEventStatus
                                   ,String pOutputFilename)
   {
     //System.out.println("pJrNo =>" + pJrNo + " | terminal =>" + terminal_no + " | workingDrive =>" + workingDrive);
     try {
       #sql [ new ExecutionContext() ]
       {
         CALL UT_EVENT_SCHEDULER_PKG.update_event_status(:pJrNo
                                                        ,:pEventStatus
                                                        ,:pOutputFilename
                                                        ,:terminal_no
                                                        ,:workingDrive)
       };
     }
     catch (SQLException e) {
       /*
       Utilities.emailToOperator(Utilities.emailTo, Utilities.emailFrom,Utilities.emailHost
                                ,"Error : Failed to update event status due to " + e + emailEndMsg
                                ,"NULL");
       */
       try {
          #sql {
              UPDATE ut_system_param set terminate_process = 'Y', scheduler_status = 'S'
              WHERE  sch_location = 'NT' };
          #sql { commit };
       }
       catch (SQLException se) {}
       // System.exit(1);
     }
   } // updateEventStatus



   protected String getOPemailAddr(String opName) {
     // Notify the user by sending an email if it fails to establish a database
     // connection
     try {
       #sql {
           SELECT NVL(email_address,'NULL')
           INTO   :op_emailAddr
           FROM   ut_operator
           WHERE  op_login = :opName
           AND    NVL(instant_email,'N') = 'Y'
         };
       return (op_emailAddr);
     }
     catch (SQLException e) {
       e.printStackTrace();
       return("NULL");
     }
   } // getOPemailAddr



   protected void sendAlertEmail(String ErrorCausedBy
                                ,String operatorName
                                ,String ProcessDescr )
   {
     String emailMsg = "Hi " + operatorName + ","  +
                       "\n\nAn error occured while processing "+ProcessDescr+
                       "\n\nReasons:" + ErrorCausedBy + emailEndMsg;
     try {
       String op_EmailAddr = getOPemailAddr(operatorName);
       //
       if ( adminEmailUser.equals("NULL") || adminEmailPwd.equals("NULL")) {
           Utilities.emailToOperator(Utilities.emailTo
                                    ,Utilities.emailFrom
                                    ,Utilities.emailHost
                                    ,emailMsg
                                    ,"NULL");
       }
       else {
         if ( ! op_EmailAddr.equals("NULL")) {
             exitCode = MailUtilities.MSoutlookSend(op_EmailAddr
                                               ,Utilities.emailFrom
                                               ,Utilities.emailHost
                                               ,"2000Plus Scheduler"
                                               ,adminEmailUser
                                               ,adminEmailPwd
                                               ,emailMsg
                                               ,"NULL"
                                               ,"NULL"
                                               ,"NULL");
         }
       }
     }
     catch (Exception e) {
       e.printStackTrace();
       System.out.println("ut_eventScheduler.sendAlertEmail failed due to " + e);
     }
   } // sendAlertEmail

   // Check if the scheduler is already up and running on that machine.
   // it retuns Y or N
   private int schedulerRunning(String vessionProgram)
   {
     int totalSchedulerUp = 0;
     try {
      #sql {
             SELECT COUNT(*)
             INTO   :totalSchedulerUp
             FROM   v$session
             WHERE  program = :vessionProgram
             AND    status  <> 'KILLED'
           };
       return(totalSchedulerUp);
     }
     catch (SQLException e) {
        return(totalSchedulerUp);
     }
   }

   // Check if the scheduler is running on nomiated server
   private String IsRunningOnNetwork(String terminalNo)
   {
     String runOnServerFlag = "N";
     try {
      #sql {
          SELECT 'Y'
          INTO   :runOnServerFlag
          FROM   ut_system_param
          WHERE  sch_location = 'NS'
          AND    UPPER(terminal_no) = UPPER(:terminalNo)
       };
       return(runOnServerFlag);
     }
     catch (SQLException e) {
        return(runOnServerFlag);
     }
   }


   public static void addClientJob (String iXMLfileLocation
                                   ,int    iXMLid
                                   ,String iEmailSubject
                                   ,String iIncomingEmailSubject) {

     // System.out.println("addClientJob:START");

     int    jrNo = 0;
     String programType = "J";
     String commandLine = null;
     String reqNo       = null;
     String ProcessStep = null;

     // System.out.println("addClientJob:START :iEmailSubject:" + iEmailSubject);
     try {
       ProcessStep = "Get the job recurrence number";
       int programId = 0;
       #sql [ new ExecutionContext() ]
       {
         CALL UT_EVENT_SCHEDULER_PKG.pu_get_next_program(:IN  iEmailSubject
                                                        ,:IN  programId
                                                        ,:OUT commandLine
                                                        ,:OUT programType)
       };

       #sql {
          SELECT SUBSTR(:iIncomingEmailSubject,
                   INSTR(:iIncomingEmailSubject, ' ',-1)+1)
          INTO   :reqNo
          FROM   dual
       };

       String reportParam = jrNo + " " + "\"" + iXMLfileLocation + "\"" + " " + reqNo;
       ProcessStep = "CALL UT_EVENT_SCHEDULER_PKG.add_scheduled_task";
       #sql [ new ExecutionContext() ]        {
           CALL UT_EVENT_SCHEDULER_PKG.pu_create_child_process(:jrNo
                                                              ,:programType
                                                              ,:commandLine
                                                              ,:reportParam)
       };
     }
     catch (SQLException e) {
        e.printStackTrace();
        System.out.println("UTeventScheduler.addClientJob(): Failed to " + ProcessStep + " due to " + e);
        System.exit(1);
     }
   } // addClientJob


  public static  void exchangeData(String mailHost
                                  ,String mailUserName
                                  ,String mailPassword
                                  ,String emailSubject
                                  ,String iApplHomeDir) throws Exception {
    // Get session
    Session session = Session.getInstance(new Properties(), null);

    // Get the store
    Store store = session.getStore("pop3");
    store.connect(mailHost, mailUserName, mailPassword);

    // Get folder
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_WRITE);

    // Get directory
    Message message[]   = folder.getMessages();
    Flags.Flag l_flag=null;

    String firstWordEmailSubject = null;
    for (int i=0, n=message.length; i<n; i++) {
       incomingEmailSubject  = message[i].getSubject();
       try {
         firstWordEmailSubject = incomingEmailSubject.substring(0,incomingEmailSubject.indexOf(" "));
       }  catch (Exception e)  {
         firstWordEmailSubject = incomingEmailSubject;
       }
       //  System.out.println("incomingEmailSubject:"+incomingEmailSubject+" |firstWordEmailSubject:" + firstWordEmailSubject + "|emailSubject:" + emailSubject);
       if (firstWordEmailSubject.equalsIgnoreCase(emailSubject)) {
          Object content = message[i].getContent();
          if (content instanceof Multipart) {
             handleMultipart((Multipart)content, incomingEmailSubject, iApplHomeDir,emailSubject);
          } else {
          handlePart(message[i], incomingEmailSubject, iApplHomeDir,emailSubject);
          }
          message[i].setFlag(l_flag.DELETED,true);
       }
    }
    folder.close(true);
    store.close();
  } // exchangeData


  protected static void handleMultipart(Multipart multipart
                                       ,String    iIncomingEmailSubject
                                       ,String    iApplHomeDir
                                       ,String    iEmailSubject)
      throws MessagingException, IOException {
    for (int i=0, n=multipart.getCount(); i<n; i++) {
      handlePart(multipart.getBodyPart(i), iIncomingEmailSubject, iApplHomeDir,iEmailSubject);
    }
  }

  protected static void handlePart(Part   part
                                  ,String iIncomingEmailSubject
                                  ,String iApplHome
                                  ,String iEmailSubject)
    throws MessagingException, IOException {

    String disposition = part.getDisposition();
    String contentType = part.getContentType();

    if (disposition == null) { // When just body
      if ((contentType.length() >= 10) &&
          (contentType.toLowerCase().substring(0, 10).equals("text/plain"))) {
      } else { // Don't think this will happen
        //System.out.println("Other body: " + contentType);
        // part.writeTo(System.out);
      }
    }
    else if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
      int xmlID = getXMLid();
      //System.out.println("*** xmlID: " + xmlID);
      String XMLfileLocation =  saveFile(part.getFileName(), part.getInputStream(),xmlID, iApplHome, iEmailSubject);
      addClientJob(XMLfileLocation, xmlID, "LANDATA",iIncomingEmailSubject );
    }
    else if (disposition.equalsIgnoreCase(Part.INLINE)) {
      //System.out.println("Inline: " + part.getFileName() + " : " + contentType);
    }
    else {  // Should never happen
      //System.out.println("Other: " + disposition);
    }
  }

  protected static int getXMLid() {

     int    XMLid = 0;

     try {
       ExecutionContext execCtx = new ExecutionContext();
       #sql [execCtx] {
          SELECT UT_XML_SEQ.nextval
          INTO   :XMLid
          FROM   dual
       };
       return(XMLid);
    }
    catch (Exception e) {
       return(XMLid);
    }
  } // getXMLid


  protected static String saveFile(String      ifilename
                                  ,InputStream input
                                  ,int         iXMLid
                                  ,String      iApplHome
                                  ,String      iEmailSubject ) throws IOException {


    PrintWriter  out;
    String targetPath = iApplHome + "Incoming";
    String downLoadFileName = targetPath + File.separator + iEmailSubject + "_" + iXMLid + ".xml";
    File   targetPathDir  = new File(targetPath);
    if(!targetPathDir.exists())  {
       targetPathDir.mkdirs();
    }
    //
    if (!targetPathDir.exists()) {
       throw new IOException("Could not access target dir "+targetPath);
    }
    // Delete the file if already exists
    File   downLoadFile  = new File(downLoadFileName);
    // System.out.println("saveFile.filename: " + ifilename + "download file:" + downLoadFileName);
    if (downLoadFile.exists()) {
        downLoadFile.delete();
    }
    try {
      out = new PrintWriter(new BufferedWriter(new FileWriter(downLoadFile)));
    }
    catch (IOException e) {
      throw e;
    }

    BufferedInputStream bis = new BufferedInputStream(input);
    int aByte;
    while ((aByte = bis.read()) != -1) {
      out.write(aByte);
    }
    bis.close();
    out.close();
    return (downLoadFileName);
  } // saveFile




  // Protected variables
  protected static String adminEmailUser = "";
  protected static String adminEmailPwd  = "";
  protected static String applHome       = "";
  protected static String userName       = "";
  protected static String pwd            = "";
  protected static String dbName         = "";
  protected static String incomingEmailSubject = "";

  // Static System variables
  private String schOuputDir      = "";
  private int    maxThreads       = 3;     // Default maximum threads
  private String terminateProcess = "";
  private int    threadSleepTimes = 100000;  // Default thread sleep time
  private String oracleHome       = "";

  private String currentDateTime  = "";
  private String op_emailAddr     = "";
  private String reason           = "";
  private static int exitCode     = 0;
  private static String emailMsg  = "";
  private String workingDrive     = "";
  private String terminal_no      = "";
  private String sessionProgram   = "";
  private String javaExecutePath  = "";

  // Create array in which holds the Event Class
  private static final executeEvent[] exeEvent    = new executeEvent[ MAX_THREADS ];

  /*****************************************************************************
   * Define the event iterator
  *****************************************************************************/
  #sql iterator eventRecs
  (
     int     jr_no,
     int     program_type,
     String  command_line,
     String  desname,
     String  report_param,
     String  output_filename,
     String  op_login,
     String  description,
     int     process_id
  );

  #sql iterator emailRecs
  (
     String  email_user_acct,
     String  email_user_pwd,
     String  email_subject,
     int     program_id,
     String  output_filename
  );

  #sql iterator SendemailRec
  (
     String email_subject,
     String email_address,
     String email_attachment,
     String email_content,
     String output_filename,
     String email_request_rowid
  );

} // ut_eventScheduler.class
// **** End of Program ****


==========================================================================
The problem seems to be occured in the following function as I comment out this function. The Stackoverfloat problem seems to haven't occured, at least 30 mins already.

The exchangeData function is to constantly check the email account and if found, it open the attachment and create a tempoaray XML files under the specific folder and then load to the database. It thens delete the temporary file which was previously created. Yes, it does involve a lot of IO process. BUT I CAN'T FIND ANY PROBLEM.
PLEASE ADVISE.


 exchangeData(Utilities.emailHost
                      ,emailIter.email_user_acct()
                      ,emailIter.email_user_pwd()
                      ,emailIter.email_subject()
                      ,applHome);
> how do i do the stack trace?

the stack trace for the SOE, see mayank's earlier post.

I use stack trace everywhere like below but i still cannot find the problem.

   catch (Exception e) {
     System.out.println("saveFile(): Errro occured");
     e.printStackTrace();
     System.exit(1);
   }

Fatal error: Cannot find class java/lang/StackOverflowError

Stack only overflows when u r using the stack too much.
Avoid recursion if you can.

if you need to have it then you can Increase the Heap Size of hte JVM
try something like:

java -Xmx32M <your program>

where 32M is 32 Megabytes - you can change that to what ever you want.

Look at the java extensions by typing java -X

regards,

Freedom.
>>The exchangeData function is to constantly check the email account and if found ...

You're opening and closing the store each time through the loop. What you should do is open it once before looping, do the loop, then close it.
> You're opening and closing the store each time through the loop.

And whty would that cause a SOE exactly?
SOE? what does it stand for?
lets say if i change to open the Store session from the very beginning, this means i only open the session once.
 "store = session.getStore("pop3");"
, where do i close the store session

Please advise
> SOE? what does it stand for?

StackOverflowError :)
>>
, where do i close the store session

Please advise
>>

After you finish looping
i basically put printStackTrace in every Catch in the ExchangeData function but it doesn't really tell me where the problem is.

Only if i comment out the ExchangeData function, it seems SOE will no longer appear at least I can say for 30mins.
Before that SOE appears in 10mins after the program is up and running
> i basically put printStackTrace in every Catch in the ExchangeData function but it doesn't really tell me where the problem is.

your not catching SOE so it slips thru, you need to include a catch for SOE


add the following around the code that is causeing the error and let me know the reply

try
{
   ...
}
catch (Throwable e)
{
   e.printStackTrace();
}
I added the code as advised to catch the stackoverflow, but it does not really tell except the following error message

Fatal error: Cannot find class java/lang/StackOverflowError


The error occures in 15mins after I changed the program to call the ExchangeData function

Please advise
could be a bug outside your code, are you using the latest versions available?
What do you mean a bug outside my code?
I dont quite understand what you mean by using the latest versions available? Would you please give me more details about this? Thanks.
what version of java are you running?
Have you been able to track down exactly which line is causing the error?
I'm using JDK1.2
JavaMail (API) 1.2
can you try running it on 1.4
No. I still have a problem to tacke down exactly which line causing the error....
you'll need to add some debug println() statements to determine where it is failing.
No we can't as our client is still using JDK1.2

I do the following to track down the problem but with no success

   catch (Throwable e) {
     System.out.println("saveFile().Throwable: Errro occured");
     e.printStackTrace();
     //System.out.println(e.printStackTrace());
     System.exit(1);
   }
its a fatal error, no error is being thrown from what you have said.
does the app exit when it happens?
> No we can't as our client is still using JDK1.2

can u reproduce the error?
if so, can you test it on 1.4?
Obejct.
Yes. that is a fatal error. It terminates and exits the application when it happened.

I only can replicate this problem by calling the ExchangeData function. I'm wondering because it keeps open and close the mail session whenever it gets called.
OBJECT,

i THINK i can track down the problem in the exchangeData function. As i comment out the function in which exchangedata calls. I still have the same error, Fatal error: Cannot find class java/lang/StackOverflowError

My logic is to every minutest to check the email with the particaular and if found, open the attachment (XML file) and download to the database. Anytime i call this function I need to open and close the session. because after the email is read i need to remove the email by using the folder.close(true);

Please advise and shed the light on this matter. As I have already spent alot of time still can't resolve this problem


See below code..
=====================================================================
  public static  void exchangeData(String mailHost
                                  ,String mailUserName
                                  ,String mailPassword
                                  ,String emailSubject
                                  ,String iApplHomeDir) {
  try {
    // Get session
    Session session = Session.getInstance(new Properties(), null);

    // Get the store
    Store store = session.getStore("pop3");
    store.connect(mailHost, mailUserName, mailPassword);

    // Get folder
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_WRITE);

    // Get directory
    Message message[]   = folder.getMessages();
    Flags.Flag l_flag=null;

    String firstWordEmailSubject = null;
    for (int i=0, n=message.length; i<n; i++) {
       incomingEmailSubject  = message[i].getSubject();
       try {
         firstWordEmailSubject = incomingEmailSubject.substring(0,incomingEmailSubject.indexOf(" "));
       }  catch (Exception e)  {
         firstWordEmailSubject = incomingEmailSubject;
       }
       //  System.out.println("incomingEmailSubject:"+incomingEmailSubject+" |firstWordEmailSubject:" + firstWordEmailSubject + "|emailSubject:" + emailSubject);

/********

       if (firstWordEmailSubject.equalsIgnoreCase(emailSubject)) {
          //System.out.println("*** email subject AR.11 FOUND ****");
          //System.out.println(i + ": "  + message[i].getFrom()[0] + "\t" + "*" + message[i].getSubject() + "*");
          Object content = message[i].getContent();
          if (content instanceof Multipart) {
             handleMultipart((Multipart)content, incomingEmailSubject, iApplHomeDir,emailSubject);
          } else {
          handlePart(message[i], incomingEmailSubject, iApplHomeDir,emailSubject);
          }
          message[i].setFlag(l_flag.DELETED,true);
        //  System.out.println("****** The email has been deleted ****");
       }
**********/

    }
    folder.close(true);
    store.close();
  }
  catch (Exception e) {
    e.printStackTrace();
    System.out.println("exchangeData(): Error occured due to " + e );
    System.exit(1);
  }
   catch (Throwable e) {
     System.out.println("exchangeData().Throwable: Errro occured");
     e.printStackTrace();
     System.exit(1);
   }
  } // exchangeData
uncomment all those println() calls, that should give u a better idea where it is crashing
You don't seem to need to create a new session each time, so you create the session in the ctor and reuse it each call.
sorry i dont quite understand
does that mean

comment out the System.out.println
please give me more details

but the catch(Throwable)  doesn't catch the stackOverfloat error as i think because this is a fatal error it exits the program
the method has a number of println() calls that are currently commented out.
if you uncomment them you'll get a better idea at which point it crashes.
Hi object.

Finally I found the spot which causes the StackOverfloat

In the exchangeData function, the following statement cause the problem. But anytime I open the folder, i close. Why It causes Stack over float.
Please give me some idea how to tackle this problem

Folder folder = store.getFolder("INBOX");
Did you try using a single session?
 public static  void exchangeData(String mailHost
                                  ,String mailUserName
                                  ,String mailPassword
                                  ,String emailSubject
                                  ,String iApplHomeDir
                                  ,Store  iStore
                                  ,Folder iFolder) {
  try {
  Message message[]   = iFolder.getMessages();
    Flags.Flag l_flag=null;
    String firstWordEmailSubject = null;

    for (int i=0, n=message.length; i<n; i++) {
       incomingEmailSubject  = message[i].getSubject();
          Object content = message[i].getContent();
          if (content instanceof Multipart) {
             handleMultipart((Multipart)content, incomingEmailSubject, iApplHomeDir,emailSubject);
          } else {
          handlePart(message[i], incomingEmailSubject, iApplHomeDir,emailSubject);
          }
          message[i].setFlag(l_flag.DELETED,true);
    }
    //iFolder.close(true);               <======== problem here if I comment out, it work. but i cannot delete the email
   // System.out.println("exchangeData: 9");
      //iStore.close();
  //  System.out.println("exchangeData: 10");
  }
  catch (Exception e) {
    e.printStackTrace();
    System.out.println("exchangeData(): Error occured due to " + e );
    System.exit(1);
  }
   catch (Throwable e) {
     System.out.println("exchangeData().Throwable: Errro occured");
     e.printStackTrace();
     System.exit(1);
   }
  } // exchangeData
you can still open and close the folder in the method, I just meant to resuse the session instance.
>>I just meant to resuse the session instance.

I already said this earlier
> I already said this earlier

You said nothing of the sort, you talked about the store which is totally different.
My comments apply to *all* unnecessary fetching of resources made in the loop
"You're opening and closing the store each time through the loop. What you should do is open it once before looping, do the loop, then close it."

Not only do you make no mention of any other resources other than the store, but your suggestion would also change the finctionality. And you fail to give any reason for having to keep the store open.
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I have to say thank first. object. In the past you have been helping me a lot. Most people here just ignore me if something are difficult.

I have tried but not work.
I have also written a simple java program which can replicate this problem. what you need is to subsititue the MailServer Host name, email account and password,

("YOUR_MAIL_SERVER", "YOUR_EMAIL_ACCOUNT", "YOUR_EMAIL_ACC_PWD");
 it will run. Notes it returns an StackOverfloat error after about 12 mins.
TAKE THIS PROGRAM TO RUN ON YOUR ENVIRONMENT. Notes. I use JDK1.2. as our client is using

See my source code below ( Very smaill program but it replicate the problem I have encountered)
===
/*@lineinfo:filename=scheduler*//*@lineinfo:user-code*//*@lineinfo:1^1*/import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.BufferedInputStream;
import java.util.Properties;
import java.text.ParseException;
import java.util.Enumeration;
import oracle.sqlj.runtime.Oracle;
import sqlj.runtime.ExecutionContext;
import java.sql.SQLException;
import javax.mail.*;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import java.util.Properties;
import java.net.InetAddress;

public class scheduler extends Object {

  public static void main(String[] args)  throws Exception {
     new scheduler();
  } // main


  private scheduler() throws Exception   {
    updateEvent();
  } // eventScheduler

  private void updateEvent() throws Exception
  {
    System.out.println("updateEvent");
    Session session = Session.getInstance(new Properties(), null);
    while (true) {
       exchangeData(session, "LANDATA");
       Thread.sleep(10000);
    } // End of While loop

  }  // updateEvent

  public static  void exchangeData(Session iSession
                                  ,String emailSubject) throws Exception {
  try {
      // Get the store
      Store store = iSession.getStore("pop3");
      store.connect("YOUR_MAIL_SERVER", "YOUR_EMAIL_ACCOUNT", "YOUR_EMAIL_ACC_PWD");
      // Get folder
      Folder folder = store.getFolder("INBOX");
      folder.open(Folder.READ_WRITE);

     // Get directory
    Message message[]   = folder.getMessages();
    Flags.Flag l_flag=null;
    String firstWordEmailSubject = null;
    System.out.println("exchangeData: 7  <====== this is a problem - folder.open(Folder.READ_WRITE)");

    for (int i=0, n=message.length; i<n; i++) {
       String incomingEmailSubject  = message[i].getSubject();
       Object content = message[i].getContent();
       if (content instanceof Multipart) {
          handleMultipart((Multipart)content);
       } else {
          handlePart(message[i]);
       }
       message[i].setFlag(l_flag.DELETED,true);
    }
    folder.close(true);
    store.close();
  }
  catch (Exception e) {
    e.printStackTrace();
    System.out.println("exchangeData(): Error occured due to " + e );
    System.exit(1);
  }
   catch (Throwable e) {
     System.out.println("exchangeData().Throwable: Errro occured");
     e.printStackTrace();
     System.exit(1);
   }
  } // exchangeData



  protected static void handleMultipart(Multipart multipart)
      throws MessagingException, IOException {

    for (int i=0, n=multipart.getCount(); i<n; i++) {
      handlePart(multipart.getBodyPart(i));
    }
  } // handleMultipart


  protected static void handlePart(Part   part)
    throws MessagingException, IOException {

    String disposition = part.getDisposition();
    String contentType = part.getContentType();

    if (disposition == null) { // When just body
      if ((contentType.length() >= 10) &&
          (contentType.toLowerCase().substring(0, 10).equals("text/plain"))) {
      } else { // Don't think this will happen
        //System.out.println("Other body: " + contentType);
        // part.writeTo(System.out);
      }
    }
    else if (disposition.equalsIgnoreCase(Part.INLINE)) {
      //System.out.println("Inline: " + part.getFileName() + " : " + contentType);
    }
    else {  // Should never happen
      //System.out.println("Other: " + disposition);
    }
  } // handlePart

}/*@lineinfo:generated-code*/
//====================================================================
Hello object.

See the link
That is exactly what the problem is.
  http://forum.java.sun.com/thread.jspa?threadID=147182&messageID=416035#416035.



But I dont know what does mean by "Polling the mailserver less frequently"

  private void updateEvent() throws Exception
  {
    System.out.println("updateEvent");
    Session session = Session.getInstance(new Properties(), null);
    Store store = session.getStore("pop3");
    while (true) {
       exchangeData(session, "LANDATA", store);
       Thread.sleep(100000);
    } // End of While loop

  }  // updateEvent

I change to Thread.sleep(100000) but it still fails after it opens and closes the folder 50 times. Exactly 50 times



Please give me some hints as this problem become more critical and this time I really rely on you
Yes I'd seen that report, unfortunately it doesn't really give any definitive answers.

Mad monday here, but will hopefully get to running your code tomorrow and see what I can find.
very very thanks for that.
It is not a bug in the open/close method of Store class.  I did this simple test:

public class StoreTest {
      public static void main(String[] args) throws MessagingException {
            Session session = Session.getInstance(new Properties(), null);
            Store store = session.getStore("pop3");
            store.connect("...", "...", "...");

            Folder folder = store.getFolder("INBOX");
            int count = 0;
            while (true) {
                  System.out.println("Open #" + (++count));
                  folder.open(Folder.READ_WRITE);
                  folder.close(true);
            }

      }
}

It opened 241 connections before I got bored.  Therefore you can open and close the same folder as many times as you want.

I noticed in the JavaDoc for Store that the getFolder() method returns a NEW Folder object EVERY time it is called (the Store class does NOT cache Folder objects).  Maybe what is happening is you cannot open 50 Folders or 50 Stores.  As Objects and CEHJ suggested, I factored out the Session/Store/Folder objects outside of the exchangeData() function.  Try this:

public class scheduler extends Object {
      public static void main(String[] args) throws Exception {
            new scheduler();
      } // main

      private scheduler() throws Exception {
            updateEvent();
      } // eventScheduler

      private void updateEvent() throws Exception {
            System.out.println("updateEvent");
            Session iSession = Session.getInstance(new Properties(), null);

            Store store = iSession.getStore("pop3");
            store.connect("mail.comcast.net", "mccardellc", "gilligan");
            // Get folder
            Folder folder = store.getFolder("INBOX");
            boolean done = false;
            while (!done) {
                  exchangeData(folder, "LANDATA");
                  Thread.sleep(10000);
            } // End of While loop
            store.close();

      } // updateEvent

      public static void exchangeData(Folder folder, String emailSubject)
                  throws Exception {
            try {
                  // Get the store
                  folder.open(Folder.READ_WRITE);
...Everything else is the same and continues as normal...
>>I factored out the Session/Store/Folder objects outside of the exchangeData() function.  

Yep. Well done
Hi object, MogalManic and CEHJ.

Thank all your help.

MogalManic, I use your codes as suggested, but still got the same problem, it runs 50times and returns StackOverflowError.

50 | New verion().exchangeData: 7  <====== this is a problem - folder.open(Folder.READ_WRITE)
Fatal error: Cannot find class java/lang/StackOverflowError

See my code below
=============
public class scheduler extends Object {

  public static void main(String[] args)  throws Exception {
     new scheduler();
  } // main


  private scheduler() throws Exception   {
    updateEvent();
  } // eventScheduler

  private void updateEvent() throws Exception
  {
    System.out.println("updateEvent");
    Session session = Session.getInstance(new Properties(), null);
    Store store = session.getStore("pop3");
    store.connect("MEL0689", "laupa", "SPYonme01");
    Folder folder = store.getFolder("INBOX");
    while (true) {
       exchangeData(folder, "LANDATA");
       Thread.sleep(10000);
    } // End of While loop
    //store.close();                               <============== I have to comment out because statement not reachable
  }  // updateEvent

  public static  void exchangeData(Folder iFolder
                                  ,String emailSubject ) throws Exception {
  try {
      // Get the store
      //Store store = iSession.getStore("pop3");
      //iStore.connect("MEL0689", "laupa", "SPYonme01");
      // Get folder
      //Folder folder = iStore.getFolder("INBOX");

      iFolder.open(Folder.READ_WRITE);

     // Get directory
    Message message[]   = iFolder.getMessages();
    Flags.Flag l_flag=null;
    String firstWordEmailSubject = null;
    counter++;
    System.out.println(counter + " | New verion().exchangeData: 7  <====== this is a problem - folder.open(Folder.READ_WRITE)");


    for (int i=0, n=message.length; i<n; i++) {
       String incomingEmailSubject  = message[i].getSubject();
       Object content = message[i].getContent();
       if (content instanceof Multipart) {
          handleMultipart((Multipart)content);
       } else {
          handlePart(message[i]);
       }
       if (incomingEmailSubject.equalsIgnoreCase("LANDATA 1.10 REQ 782761-010-8")) {
         System.out.println("found");
         message[i].setFlag(l_flag.DELETED,true);
       }
    }


    iFolder.close(true);
    //iStore.close();
  }
  catch (Exception e) {
    e.printStackTrace();
    System.out.println("exchangeData(): Error occured due to " + e );
    System.exit(1);
  }
   catch (Throwable e) {
     System.out.println("exchangeData().Throwable: Errro occured");
     e.printStackTrace();
     System.exit(1);
   }
  } // exchangeData



  protected static void handleMultipart(Multipart multipart)
      throws MessagingException, IOException {

    for (int i=0, n=multipart.getCount(); i<n; i++) {
      handlePart(multipart.getBodyPart(i));
    }
  } // handleMultipart


  protected static void handlePart(Part   part)
    throws MessagingException, IOException {

    String disposition = part.getDisposition();
    String contentType = part.getContentType();

    if (disposition == null) { // When just body
      if ((contentType.length() >= 10) &&
          (contentType.toLowerCase().substring(0, 10).equals("text/plain"))) {
      } else { // Don't think this will happen
        //System.out.println("Other body: " + contentType);
        // part.writeTo(System.out);
      }
    }
    else if (disposition.equalsIgnoreCase(Part.INLINE)) {
      //System.out.println("Inline: " + part.getFileName() + " : " + contentType);
    }
    else {  // Should never happen
      //System.out.println("Other: " + disposition);
    }
  } // handlePart
  private static int counter = 0;
}


==================
Please point out the mistake I have made
> Please point out the mistake I have made

As I've mentioned earlier I suspect it is not your mistake and instead a bug in javamail.
What we need to find is a workaround.
thanks. It only works is to only open the folder once. It works. But i cannot delete the email because i need to close the folder and set the true parameter in order to delete the eamil.
We have to delete the email because we expect to recieve hundreds emails a day from our internet web site.

  private void updateEvent() throws Exception
  {
    System.out.println("updateEvent");
    Session session = Session.getInstance(new Properties(), null);
    Store store = session.getStore("pop3");
    store.connect("MEL0689", "laupa", "SPYonme01");
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_WRITE);            <========== only open the folder once
    while (true) {
       exchangeData(folder, "LANDATA");
       //folder.close(true);
       Thread.sleep(10000);
    } // End of While loop
    //store.close();
  }  // updateEvent
Yes I realise that keeping the folder open is not possible for you. Will let you know what I find.

Did you try  my first example program StoreTest?
What version of JavaMail are you using?
Hi MogalManic,

I have just tried your StoreTest, but it fails after it opens and closes 50 times

Open #48
Open #49
Open #50
Fatal error: Cannot find class java/lang/StackOverflowError

I'm using JavaMail (API) 1.2 and JDK1.2

Thanks

Hi MogalManic,

Would you please copy my program from the above and run on your environment to see how it work?
I think maybe your mail server polling or the version is different. i dont know

Notes: I even download the javamail apl 1.3.2, it still got the same problem (JDK1.2)
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I have a feeling it could be an error due to the version. Also - if its loading the other classes, why is it not loading the StackOverflowError class? Can you open rt.jar and verify that it contains the class?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi MogalManic,

I have run your sample Test program, it runs and crashes.

The program is crashed and display the following error

      void Test.crash()
      void Test.main(java.lang.String[])
Exception in thread main


How do i open rt.jar
what does the rt.jar do?

Thanks
> Can you open rt.jar and verify that it contains the class?

99% sure it would contain it.
where do i fnd the rt.jar?


the classpath i use


classpath "c:\corpdev6i\JavaAppl;c:\Java\jdk1.2\jdbc\lib\classes12.zip;c:\Java\jdk1.2\jdbc\lib\nls_charset12.zip;c:\Java\jdk1.2\sqlj\lib\runtime12.zip;c:\Java\jdk1.2\lib\mail.jar;c:\Java\jdk1.2\lib\activation.jar"


no rt.jar attached to my classpath.
i dont find the rt.jar but i found dt.jar?

do i need to attach the rt.jar to the classpath?

what the rt.jar does?
> do i need to attach the rt.jar to the classpath?

No

> what the rt.jar does?

Contains the standard java classes

where is the rt.jar located?
as wat you say i need to open the rt.jar to see the class exist or not
i guess class12.zip contain the rt.jar, right? as you say rt.jar contains the standard java cleasses
>>as wat you say i need to open the rt.jar to see the class exist or not

You don't need to open it. You just need to run

javap java.lang.StackOverflowError
hi object,

i finally find the rt.jar and open it.
The rt.jar contains a heap of classes. i have a very quick search it seems the StackOverflowError not there
If you're determined to 'look inside' rt.jar you can do:

jar tf rt.jar | find "StackOverflowError"

No output means it's not there
Hi CEHJ,

You don't need to open it. You just need to run


javap java.lang.StackOverflowError   <=== is this a command i run on the dos
jar tf rt.jar | find "StackOverflowError"  <== this is a unix command, right. I run the window dos and lists of the classes
Would you tell me where to download JDK1.4? Is it legal to download JDK1.4? Let's say if the problem is related to JDK version we need to force our client to upgrade JDK1.4.
My question from my manager is do our client need to pay for JDK1.4?
> Would you tell me where to download JDK1.4?

http://java.sun.com/j2se/1.4.2/download.html

> Is it legal to download JDK1.4?

yes

> My question from my manager is do our client need to pay for JDK1.4?

no
Hi object, MogalManic and CHEJ

Finially I get this one work. Very thanks for object and MogalManic gave me some ideas, especially the sample program given from MoglManic, giving me some hint that the problem is probably related to version. You know what i did,

I used to use JDeveloper 3.2 and JDK1.2 and javamail 1.2

After that

I donwload JDeveloper 9i and use JDK1.4 and javamail 1.3.2, It works so far as the program already opens and close 8000 times and it's still up and running.

We actually raise a TAR to Oracle and Oracle still can't figure out the problem so that you can see how good you guy are.

Object, i have looked at your EE profile and know you are the freelane Java developer helping people developing the java/web application, I have already mentioned your name to our manager, maybe (NOT promising) we need your help for our next project (Web application). (Of course, the company will pay your consultant fees. because I can see your technical skill also your technical support even better than Oracle. What is your skill rank for JSP )


Thanks all.
>>javap java.lang.StackOverflowError   <=== is this a command i run on the dos

Yes

>>jar tf rt.jar | find "StackOverflowError"  <== this is a unix command, right. I run the window dos and lists of the classes

No, it's a 'DOS' command

> I donwload JDeveloper 9i and use JDK1.4 and javamail 1.3.2

Suspect it was a bug in earlier version of Javamail, good to see you got it working.
(Contact me directly about consulting and we can discuss further)
:-)