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.
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.
ASKER
how do i do the stack trace?
Do you mean I put e.printStackTrace() on the recursion function?
Please give me more details
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.
ASKER
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("UTeven tScheduler .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(termin al_no).equ als("Y")) {
workingDrive = "N";
}
// System.out.println("workin gDrive:" + workingDrive);
int totalSschdRunning = schedulerRunning(sessionPr ogram);
// System.out.println("v$sess ion.totalS schdRunnin g:" + totalSschdRunning);
if ( totalSschdRunning > 1 )
System.exit(0);
//
try {
#sql [ new ExecutionContext() ] {
CALL UT_EVENT_SCHEDULER_PKG.pu_ switch_on_ schd(:sess ionProgram )
};
}
catch (Exception e) {
System.out.println("UTeven tScheduler : 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,' ABDEFGHIJK LMN') 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.ema ilHost
,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(SendE mailIter.e mail_reque st_rowid() ,"I");
exitCode = MailUtilities.MSoutlookSen d(SendEmai lIter.emai l_address( )
,Utilities.emailFrom
,Utilities.emailHost
,SendEmailIter.email_subje ct()
,adminEmailUser
,adminEmailPwd
,SendEmailIter.email_conte nt()
,"NULL"
,SendEmailIter.email_attac hment()
,SendEmailIter.output_file name());
deleteEmailRequest(SendEma ilIter.ema il_request _rowid());
}
int totalThreads = maxThreads;
if ( terminateProcess.equals("Y ")) {
System.exit(0);
}
vHighPriorityEvents.trimTo Size();
vMidPriorityEvents.trimToS ize();
vLowPriorityEvents.trimToS ize();
int vTotalHighPriorityElements = vHighPriorityEvents.capaci ty();
int vTotalMidPriorityElements = vMidPriorityEvents.capacit y();
int vTotalLowPriorityElements = vLowPriorityEvents.capacit y();
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.isEmpt y())) {
exeEvent[ HIGH_PRIORITY_EVENT ] = new executeEvent( HIGH_PRIORITY_EVENT );
exeEvent[ HIGH_PRIORITY_EVENT ].start();
}
else
{
if ( ( ! vHighPriorityEvents.isEmpt y())) {
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("UTeven tScheduler .updateEve nt(): Interrupted Exception error occured due to " + ie);
System.exit(1);
}
catch (Exception e) {
e.printStackTrace();
System.out.println("UTeven tScheduler .updateEve nt(): 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,'NUL L') command_line
,NVL(usc.desname,'NULL') desname
,NVL(usc.report_param,'NUL L') 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().e quals("NUL L") ) {
rptParameter = reconsturctParamLine(event Iter.repor t_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.addEle ment(evt);
break;
case 2:
vMidPriorityEvents.addElem ent(evt);
break;
case 3:
vLowPriorityEvents.addElem ent(evt);
break;
default:
vHighPriorityEvents.addEle ment(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,Utilit ies.emailH ost
,"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("execut eEvent._ev entPriorit y:" + _eventPriority);
Enumeration enum = null;
switch (_eventPriority) {
case 1:
enum = vHighPriorityEvents.elemen ts();
break;
case 2:
enum = vMidPriorityEvents.element s();
break;
case 3:
enum = vLowPriorityEvents.element s();
break;
default:
break;
}
while ( enum.hasMoreElements())
{
Event eventQueue = (Event) enum.nextElement();
updateEventStatus(eventQue ue._jr_no, INPROGRESS ,"");
try {
// Remove the event from the event vector before executing the CmdString
removeVector(eventQueue, _eventPriority);
if ( eventQueue._programType == 2 ) {
try {
deleteChildProcess(eventQu eue._jr_no );
String dbpk_name = eventQueue._executeCmdStri ng;
returnValue = "";
#sql [ new ExecutionContext()]
{
CALL UT_EVENT_SCHEDULER_PKG.pu_ exe_dynami c_sql(:IN dbpk_name)
};
//System.out.println("Retr unValue => " + returnValue);
}
catch (SQLException e) {
reason = "Failed to execute the program " + eventQueue._executeCmdStri ng;
updateEventStatus(eventQue ue._jr_no, ERROR,"");
eventlogRec(eventQueue._jr _no, reason);
}
}
else {
deleteChildProcess(eventQu eue._jr_no );
eventlogRec(eventQueue._jr _no, "Process Start : " + processDateTime() + " - " + eventQueue._executeCmdStri ng);
int returnProcessValue = Runtime.getRuntime().exec( eventQueue ._executeC mdString). waitFor();
if ( returnProcessValue == 0) {
//System.out.println("call ed job completed");
updateEventStatus(eventQue ue._jr_no ,COMPLETED,eventQueue._out putFileNam e);
eventlogRec(eventQueue._jr _no, "Process Completed : " + processDateTime());
}
else {
reason = "Failed to execute the program " + eventQueue._executeCmdStri ng;
updateEventStatus(eventQue ue._jr_no, ERROR,"");
eventlogRec(eventQueue._jr _no, reason);
sendAlertEmail(reason,even tQueue._op Login, eventQueue._description);
// removeVector(evt, _eventPriority);
} // end if Runtime
} // End if for checking program Type
}
catch (Exception e) {
System.out.println("execut eEvent. Error due to " + e);
System.exit(1);
//reason = "Error due to " + e;
//updateEventStatus(eventQ ueue._jr_n o ,COMPLETED,eventQueue._out putFileNam e);
updateEventStatus(eventQue ue._jr_no, ERROR,"");
//eventlogRec(eventQueue._ jr_no, "Process Completed : " + processDateTime());
eventlogRec(eventQueue._jr _no, reason);
sendAlertEmail(reason,even tQueue._op Login, eventQueue._description);
};
} // End of While loop
} // End or run()
} // End of executeEvent
protected void removeVector(Event pEvt, int pEventPriority)
{
switch (pEventPriority) {
case 1:
vHighPriorityEvents.remove Element(pE vt);
break;
case 2:
vMidPriorityEvents.removeE lement(pEv t);
break;
case 3:
vLowPriorityEvents.removeE lement(pEv t);
break;
default:
break;
}
} // End of removeVector
protected void getSchSysParams()
{
try {
// System.out.println("getSch SysParams. sessionPro gram=>" + sessionProgram);
#sql [ new ExecutionContext() ]
{
CALL UT_EVENT_SCHEDULER_PKG.pu_ get_sys_pa rams(:IN sessionProgram
,:OUT schOuputDir
,:OUT maxThreads
,:OUT terminateProcess
,:OUT threadSleepTimes
,:OUT adminEmailUser
,:OUT adminEmailPwd
,:OUT applHome
,:OUT oracleHome)
};
if (applHome.equalsIgnoreCase ("NULL")){
emailMsg = "UTeventScheduler.getSchSy sParams:20 00Plus 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-YY YY HH24:MI')
INTO :currentDateTime
FROM dual
};
//System.out.println("curr entDateTim e => " + currentDateTime);
return (currentDateTime);
}
catch (SQLException e) {
e.printStackTrace();
return("Error due to " + e);
}
}
private String reconsturctParamLine(Strin g iRptParam)
{
String l_rtn_String = "NULL";
try {
#sql l_rtn_String = { VALUES(UT_EVENT_SCHEDULER_ PKG.fu_rec onst_clien t_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.cre ate_event_ log(:iJrNo ,:iReason, 'CLIENT')
};
}
catch (SQLException e) {
e.printStackTrace();
}
}// logErrorRec
protected void updateEmailReqStatus(Strin g iEmailReqRowId, String iEmailProcessStatus)
{
try {
#sql [ new ExecutionContext() ]
{
CALL UT_EVENT_SCHEDULER_PKG.pu_ update_ema il_request _status(:i EmailReqRo wId, :iEmailProcessStatus)
};
}
catch (SQLException e) { e.printStackTrace(); }
}// updateEmailReqStatus
protected void deleteEmailRequest(String iEmailReqRowId)
{
try {
#sql [ new ExecutionContext() ]
{
CALL UT_EVENT_SCHEDULER_PKG.pu_ delete_ema il_request (:iEmailRe qRowId)
};
}
catch (SQLException e) { e.printStackTrace(); }
}// deleteEmailRequest
protected void deleteChildProcess(int iJrNo)
{
try {
#sql [ new ExecutionContext() ]
{
CALL UT_EVENT_SCHEDULER_PKG.pu_ delete_chi ld_process (:iJrNo)
};
}
catch (SQLException e) { e.printStackTrace(); }
}// udpateChildProcessStatus
protected void updateEventStatus(int pJrNo
,String pEventStatus
,String pOutputFilename)
{
//System.out.println("pJrN o =>" + pJrNo + " | terminal =>" + terminal_no + " | workingDrive =>" + workingDrive);
try {
#sql [ new ExecutionContext() ]
{
CALL UT_EVENT_SCHEDULER_PKG.upd ate_event_ status(:pJ rNo
,:pEventStatus
,:pOutputFilename
,:terminal_no
,:workingDrive)
};
}
catch (SQLException e) {
/*
Utilities.emailToOperator( Utilities. emailTo, Utilities.emailFrom,Utilit ies.emailH ost
,"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(operatorNam e);
//
if ( adminEmailUser.equals("NUL L") || adminEmailPwd.equals("NULL ")) {
Utilities.emailToOperator( Utilities. emailTo
,Utilities.emailFrom
,Utilities.emailHost
,emailMsg
,"NULL");
}
else {
if ( ! op_EmailAddr.equals("NULL" )) {
exitCode = MailUtilities.MSoutlookSen d(op_Email Addr
,Utilities.emailFrom
,Utilities.emailHost
,"2000Plus Scheduler"
,adminEmailUser
,adminEmailPwd
,emailMsg
,"NULL"
,"NULL"
,"NULL");
}
}
}
catch (Exception e) {
e.printStackTrace();
System.out.println("ut_eve ntSchedule r.sendAler tEmail 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("addCli entJob:STA RT");
int jrNo = 0;
String programType = "J";
String commandLine = null;
String reqNo = null;
String ProcessStep = null;
// System.out.println("addCli entJob:STA RT :iEmailSubject:" + iEmailSubject);
try {
ProcessStep = "Get the job recurrence number";
int programId = 0;
#sql [ new ExecutionContext() ]
{
CALL UT_EVENT_SCHEDULER_PKG.pu_ get_next_p rogram(:IN iEmailSubject
,:IN programId
,:OUT commandLine
,:OUT programType)
};
#sql {
SELECT SUBSTR(:iIncomingEmailSubj ect,
INSTR(:iIncomingEmailSubje ct, ' ',-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_chi ld_process (:jrNo
,:programType
,:commandLine
,:reportParam)
};
}
catch (SQLException e) {
e.printStackTrace();
System.out.println("UTeven tScheduler .addClient Job(): 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_WR ITE);
// 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.subst ring(0,inc omingEmail Subject.in dexOf(" "));
} catch (Exception e) {
firstWordEmailSubject = incomingEmailSubject;
}
// System.out.println("incomi ngEmailSub ject:"+inc omingEmail Subject+" |firstWordEmailSubject:" + firstWordEmailSubject + "|emailSubject:" + emailSubject);
if (firstWordEmailSubject.equ alsIgnoreC ase(emailS ubject)) {
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,tr ue);
}
}
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.getBo dyPart(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("Othe r body: " + contentType);
// part.writeTo(System.out);
}
}
else if (disposition.equalsIgnoreC ase(Part.A TTACHMENT) ) {
int xmlID = getXMLid();
//System.out.println("*** xmlID: " + xmlID);
String XMLfileLocation = saveFile(part.getFileName( ), part.getInputStream(),xmlI D, iApplHome, iEmailSubject);
addClientJob(XMLfileLocati on, xmlID, "LANDATA",iIncomingEmailSu bject );
}
else if (disposition.equalsIgnoreC ase(Part.I NLINE)) {
//System.out.println("Inli ne: " + part.getFileName() + " : " + contentType);
}
else { // Should never happen
//System.out.println("Othe r: " + 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("saveFi le.filenam e: " + 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 ****
========================== ========== ========== ========== ========== ========
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
if ( dbConnOk == 0 ) {
new UTeventScheduler();
}
else {
System.out.println("UTeven
System.exit(1);
}
} // main
private UTeventScheduler() throws Exception
{
workingDrive = Utilities.schDrive;
terminal_no = Utilities.terminal;
sessionProgram = Utilities.sessionProg;
if (IsRunningOnNetwork(termin
workingDrive = "N";
}
// System.out.println("workin
int totalSschdRunning = schedulerRunning(sessionPr
// System.out.println("v$sess
if ( totalSschdRunning > 1 )
System.exit(0);
//
try {
#sql [ new ExecutionContext() ] {
CALL UT_EVENT_SCHEDULER_PKG.pu_
};
}
catch (Exception e) {
System.out.println("UTeven
};
//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,'
,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.ema
,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(SendE
exitCode = MailUtilities.MSoutlookSen
,Utilities.emailFrom
,Utilities.emailHost
,SendEmailIter.email_subje
,adminEmailUser
,adminEmailPwd
,SendEmailIter.email_conte
,"NULL"
,SendEmailIter.email_attac
,SendEmailIter.output_file
deleteEmailRequest(SendEma
}
int totalThreads = maxThreads;
if ( terminateProcess.equals("Y
System.exit(0);
}
vHighPriorityEvents.trimTo
vMidPriorityEvents.trimToS
vLowPriorityEvents.trimToS
int vTotalHighPriorityElements
int vTotalMidPriorityElements = vMidPriorityEvents.capacit
int vTotalLowPriorityElements = vLowPriorityEvents.capacit
int eventRequests = ( vTotalHighPriorityElements
vTotalMidPriorityElements +
vTotalLowPriorityElements == 0 ) ?
maxThreads : maxThreads - vTotalHighPriorityElements
- vTotalMidPriorityElements
- vTotalLowPriorityElements;
if ( eventRequests > 0 ) {
updateEventStatus(0,"P",""
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.isEmpt
exeEvent[ HIGH_PRIORITY_EVENT ] = new executeEvent( HIGH_PRIORITY_EVENT );
exeEvent[ HIGH_PRIORITY_EVENT ].start();
}
else
{
if ( ( ! vHighPriorityEvents.isEmpt
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("UTeven
System.exit(1);
}
catch (Exception e) {
e.printStackTrace();
System.out.println("UTeven
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',
,'D' ,2
,'J' ,3
,'F' ,4,0) program_type
,NVL(usc.command_line,'NUL
,NVL(usc.desname,'NULL') desname
,NVL(usc.report_param,'NUL
,NVL(usc.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','
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
,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().e
rptParameter = reconsturctParamLine(event
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.addEle
break;
case 2:
vMidPriorityEvents.addElem
break;
case 3:
vLowPriorityEvents.addElem
break;
default:
vHighPriorityEvents.addEle
break;
}
updateEventStatus(evt._jr_
}
catch (Exception e) {
String ErrorMsg = "Failed to update the event status due to " + e;
updateEventStatus(evt._jr_
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(
,"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("execut
Enumeration enum = null;
switch (_eventPriority) {
case 1:
enum = vHighPriorityEvents.elemen
break;
case 2:
enum = vMidPriorityEvents.element
break;
case 3:
enum = vLowPriorityEvents.element
break;
default:
break;
}
while ( enum.hasMoreElements())
{
Event eventQueue = (Event) enum.nextElement();
updateEventStatus(eventQue
try {
// Remove the event from the event vector before executing the CmdString
removeVector(eventQueue, _eventPriority);
if ( eventQueue._programType == 2 ) {
try {
deleteChildProcess(eventQu
String dbpk_name = eventQueue._executeCmdStri
returnValue = "";
#sql [ new ExecutionContext()]
{
CALL UT_EVENT_SCHEDULER_PKG.pu_
};
//System.out.println("Retr
}
catch (SQLException e) {
reason = "Failed to execute the program " + eventQueue._executeCmdStri
updateEventStatus(eventQue
eventlogRec(eventQueue._jr
}
}
else {
deleteChildProcess(eventQu
eventlogRec(eventQueue._jr
int returnProcessValue = Runtime.getRuntime().exec(
if ( returnProcessValue == 0) {
//System.out.println("call
updateEventStatus(eventQue
eventlogRec(eventQueue._jr
}
else {
reason = "Failed to execute the program " + eventQueue._executeCmdStri
updateEventStatus(eventQue
eventlogRec(eventQueue._jr
sendAlertEmail(reason,even
// removeVector(evt, _eventPriority);
} // end if Runtime
} // End if for checking program Type
}
catch (Exception e) {
System.out.println("execut
System.exit(1);
//reason = "Error due to " + e;
//updateEventStatus(eventQ
updateEventStatus(eventQue
//eventlogRec(eventQueue._
eventlogRec(eventQueue._jr
sendAlertEmail(reason,even
};
} // End of While loop
} // End or run()
} // End of executeEvent
protected void removeVector(Event pEvt, int pEventPriority)
{
switch (pEventPriority) {
case 1:
vHighPriorityEvents.remove
break;
case 2:
vMidPriorityEvents.removeE
break;
case 3:
vLowPriorityEvents.removeE
break;
default:
break;
}
} // End of removeVector
protected void getSchSysParams()
{
try {
// System.out.println("getSch
#sql [ new ExecutionContext() ]
{
CALL UT_EVENT_SCHEDULER_PKG.pu_
,:OUT schOuputDir
,:OUT maxThreads
,:OUT terminateProcess
,:OUT threadSleepTimes
,:OUT adminEmailUser
,:OUT adminEmailPwd
,:OUT applHome
,:OUT oracleHome)
};
if (applHome.equalsIgnoreCase
emailMsg = "UTeventScheduler.getSchSy
Utilities.emailToOperator(
,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-YY
INTO :currentDateTime
FROM dual
};
//System.out.println("curr
return (currentDateTime);
}
catch (SQLException e) {
e.printStackTrace();
return("Error due to " + e);
}
}
private String reconsturctParamLine(Strin
{
String l_rtn_String = "NULL";
try {
#sql l_rtn_String = { VALUES(UT_EVENT_SCHEDULER_
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.cre
};
}
catch (SQLException e) {
e.printStackTrace();
}
}// logErrorRec
protected void updateEmailReqStatus(Strin
{
try {
#sql [ new ExecutionContext() ]
{
CALL UT_EVENT_SCHEDULER_PKG.pu_
};
}
catch (SQLException e) { e.printStackTrace(); }
}// updateEmailReqStatus
protected void deleteEmailRequest(String iEmailReqRowId)
{
try {
#sql [ new ExecutionContext() ]
{
CALL UT_EVENT_SCHEDULER_PKG.pu_
};
}
catch (SQLException e) { e.printStackTrace(); }
}// deleteEmailRequest
protected void deleteChildProcess(int iJrNo)
{
try {
#sql [ new ExecutionContext() ]
{
CALL UT_EVENT_SCHEDULER_PKG.pu_
};
}
catch (SQLException e) { e.printStackTrace(); }
}// udpateChildProcessStatus
protected void updateEventStatus(int pJrNo
,String pEventStatus
,String pOutputFilename)
{
//System.out.println("pJrN
try {
#sql [ new ExecutionContext() ]
{
CALL UT_EVENT_SCHEDULER_PKG.upd
,:pEventStatus
,:pOutputFilename
,:terminal_no
,:workingDrive)
};
}
catch (SQLException e) {
/*
Utilities.emailToOperator(
,"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(operatorNam
//
if ( adminEmailUser.equals("NUL
Utilities.emailToOperator(
,Utilities.emailFrom
,Utilities.emailHost
,emailMsg
,"NULL");
}
else {
if ( ! op_EmailAddr.equals("NULL"
exitCode = MailUtilities.MSoutlookSen
,Utilities.emailFrom
,Utilities.emailHost
,"2000Plus Scheduler"
,adminEmailUser
,adminEmailPwd
,emailMsg
,"NULL"
,"NULL"
,"NULL");
}
}
}
catch (Exception e) {
e.printStackTrace();
System.out.println("ut_eve
}
} // 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("addCli
int jrNo = 0;
String programType = "J";
String commandLine = null;
String reqNo = null;
String ProcessStep = null;
// System.out.println("addCli
try {
ProcessStep = "Get the job recurrence number";
int programId = 0;
#sql [ new ExecutionContext() ]
{
CALL UT_EVENT_SCHEDULER_PKG.pu_
,:IN programId
,:OUT commandLine
,:OUT programType)
};
#sql {
SELECT SUBSTR(:iIncomingEmailSubj
INSTR(:iIncomingEmailSubje
INTO :reqNo
FROM dual
};
String reportParam = jrNo + " " + "\"" + iXMLfileLocation + "\"" + " " + reqNo;
ProcessStep = "CALL UT_EVENT_SCHEDULER_PKG.add
#sql [ new ExecutionContext() ] {
CALL UT_EVENT_SCHEDULER_PKG.pu_
,:programType
,:commandLine
,:reportParam)
};
}
catch (SQLException e) {
e.printStackTrace();
System.out.println("UTeven
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_WR
// 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.subst
} catch (Exception e) {
firstWordEmailSubject = incomingEmailSubject;
}
// System.out.println("incomi
if (firstWordEmailSubject.equ
Object content = message[i].getContent();
if (content instanceof Multipart) {
handleMultipart((Multipart
} else {
handlePart(message[i], incomingEmailSubject, iApplHomeDir,emailSubject)
}
message[i].setFlag(l_flag.
}
}
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.getBo
}
}
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()
} else { // Don't think this will happen
//System.out.println("Othe
// part.writeTo(System.out);
}
}
else if (disposition.equalsIgnoreC
int xmlID = getXMLid();
//System.out.println("*** xmlID: " + xmlID);
String XMLfileLocation = saveFile(part.getFileName(
addClientJob(XMLfileLocati
}
else if (disposition.equalsIgnoreC
//System.out.println("Inli
}
else { // Should never happen
//System.out.println("Othe
}
}
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("saveFi
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 ****
==========================
ASKER
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.ema ilHost
,emailIter.email_user_acct ()
,emailIter.email_user_pwd( )
,emailIter.email_subject()
,applHome);
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.ema
,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.
the stack trace for the SOE, see mayank's earlier post.
ASKER
I use stack trace everywhere like below but i still cannot find the problem.
catch (Exception e) {
System.out.println("saveFi
e.printStackTrace();
System.exit(1);
}
Fatal error: Cannot find class java/lang/StackOverflowErr
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.
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. 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?
And whty would that cause a SOE exactly?
ASKER
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
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 :)
StackOverflowError :)
>>
, where do i close the store session
Please advise
>>
After you finish looping
, where do i close the store session
Please advise
>>
After you finish looping
ASKER
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
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();
}
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();
}
ASKER
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/StackOverflowErr or
The error occures in 15mins after I changed the program to call the ExchangeData function
Please advise
Fatal error: Cannot find class java/lang/StackOverflowErr
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?
ASKER
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.
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?
ASKER
I'm using JDK1.2
JavaMail (API) 1.2
JavaMail (API) 1.2
can you try running it on 1.4
ASKER
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.
ASKER
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("saveFi le().Throw able: Errro occured");
e.printStackTrace();
//System.out.println(e.pri ntStackTra ce());
System.exit(1);
}
I do the following to track down the problem but with no success
catch (Throwable e) {
System.out.println("saveFi
e.printStackTrace();
//System.out.println(e.pri
System.exit(1);
}
its a fatal error, no error is being thrown from what you have said.
does the app exit when it happens?
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?
can u reproduce the error?
if so, can you test it on 1.4?
ASKER
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.
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.
ASKER
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/StackOverflowErr or
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_WR ITE);
// 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.subst ring(0,inc omingEmail Subject.in dexOf(" "));
} catch (Exception e) {
firstWordEmailSubject = incomingEmailSubject;
}
// System.out.println("incomi ngEmailSub ject:"+inc omingEmail Subject+" |firstWordEmailSubject:" + firstWordEmailSubject + "|emailSubject:" + emailSubject);
/********
if (firstWordEmailSubject.equ alsIgnoreC ase(emailS ubject)) {
//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,tr ue);
// System.out.println("****** The email has been deleted ****");
}
**********/
}
folder.close(true);
store.close();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("exchan geData(): Error occured due to " + e );
System.exit(1);
}
catch (Throwable e) {
System.out.println("exchan geData().T hrowable: Errro occured");
e.printStackTrace();
System.exit(1);
}
} // exchangeData
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/StackOverflowErr
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_WR
// 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.subst
} catch (Exception e) {
firstWordEmailSubject = incomingEmailSubject;
}
// System.out.println("incomi
/********
if (firstWordEmailSubject.equ
//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
} else {
handlePart(message[i], incomingEmailSubject, iApplHomeDir,emailSubject)
}
message[i].setFlag(l_flag.
// System.out.println("******
}
**********/
}
folder.close(true);
store.close();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("exchan
System.exit(1);
}
catch (Throwable e) {
System.out.println("exchan
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.
ASKER
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
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.
if you uncomment them you'll get a better idea at which point it crashes.
ASKER
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");
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?
ASKER
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,tr ue);
}
//iFolder.close(true); <======== problem here if I comment out, it work. but i cannot delete the email
// System.out.println("exchan geData: 9");
//iStore.close();
// System.out.println("exchan geData: 10");
}
catch (Exception e) {
e.printStackTrace();
System.out.println("exchan geData(): Error occured due to " + e );
System.exit(1);
}
catch (Throwable e) {
System.out.println("exchan geData().T hrowable: Errro occured");
e.printStackTrace();
System.exit(1);
}
} // exchangeData
,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
} else {
handlePart(message[i], incomingEmailSubject, iApplHomeDir,emailSubject)
}
message[i].setFlag(l_flag.
}
//iFolder.close(true); <======== problem here if I comment out, it work. but i cannot delete the email
// System.out.println("exchan
//iStore.close();
// System.out.println("exchan
}
catch (Exception e) {
e.printStackTrace();
System.out.println("exchan
System.exit(1);
}
catch (Throwable e) {
System.out.println("exchan
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
> I already said this earlier
You said nothing of the sort, you talked about the store which is totally different.
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.
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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=sched uler*//*@l ineinfo:us er-code*// *@lineinfo :1^1*/impo rt 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.BufferedInputStrea m;
import java.util.Properties;
import java.text.ParseException;
import java.util.Enumeration;
import oracle.sqlj.runtime.Oracle ;
import sqlj.runtime.ExecutionCont ext;
import java.sql.SQLException;
import javax.mail.*;
import javax.mail.internet.MimeBo dyPart;
import javax.mail.internet.MimeMu ltipart;
import javax.mail.internet.MimeMe ssage;
import javax.mail.internet.Addres sException ;
import javax.mail.internet.Intern etAddress;
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("update Event");
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_S ERVER", "YOUR_EMAIL_ACCOUNT", "YOUR_EMAIL_ACC_PWD");
// Get folder
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WR ITE);
// Get directory
Message message[] = folder.getMessages();
Flags.Flag l_flag=null;
String firstWordEmailSubject = null;
System.out.println("exchan geData: 7 <====== this is a problem - folder.open(Folder.READ_WR ITE)");
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,tr ue);
}
folder.close(true);
store.close();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("exchan geData(): Error occured due to " + e );
System.exit(1);
}
catch (Throwable e) {
System.out.println("exchan geData().T hrowable: 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.getBo dyPart(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("Othe r body: " + contentType);
// part.writeTo(System.out);
}
}
else if (disposition.equalsIgnoreC ase(Part.I NLINE)) {
//System.out.println("Inli ne: " + part.getFileName() + " : " + contentType);
}
else { // Should never happen
//System.out.println("Othe r: " + disposition);
}
} // handlePart
}/*@lineinfo:generated-cod e*/
//======================== ========== ========== ========== ========== ====
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=sched
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.BufferedInputStrea
import java.util.Properties;
import java.text.ParseException;
import java.util.Enumeration;
import oracle.sqlj.runtime.Oracle
import sqlj.runtime.ExecutionCont
import java.sql.SQLException;
import javax.mail.*;
import javax.mail.internet.MimeBo
import javax.mail.internet.MimeMu
import javax.mail.internet.MimeMe
import javax.mail.internet.Addres
import javax.mail.internet.Intern
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("update
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_S
// Get folder
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WR
// Get directory
Message message[] = folder.getMessages();
Flags.Flag l_flag=null;
String firstWordEmailSubject = null;
System.out.println("exchan
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
} else {
handlePart(message[i]);
}
message[i].setFlag(l_flag.
}
folder.close(true);
store.close();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("exchan
System.exit(1);
}
catch (Throwable e) {
System.out.println("exchan
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.getBo
}
} // 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()
} else { // Don't think this will happen
//System.out.println("Othe
// part.writeTo(System.out);
}
}
else if (disposition.equalsIgnoreC
//System.out.println("Inli
}
else { // Should never happen
//System.out.println("Othe
}
} // handlePart
}/*@lineinfo:generated-cod
//========================
ASKER
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("update Event");
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
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("update
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.
Mad monday here, but will hopefully get to running your code tomorrow and see what I can find.
ASKER
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_WR ITE);
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("update Event");
Session iSession = Session.getInstance(new Properties(), null);
Store store = iSession.getStore("pop3");
store.connect("mail.comcas t.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_WR ITE);
...Everything else is the same and continues as normal...
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_WR
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("update
Session iSession = Session.getInstance(new Properties(), null);
Store store = iSession.getStore("pop3");
store.connect("mail.comcas
// 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_WR
...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
Yep. Well done
ASKER
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_WR ITE)
Fatal error: Cannot find class java/lang/StackOverflowErr or
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("update Event");
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_W RITE);
// 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_WR ITE)");
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.equa lsIgnoreCa se("LANDAT A 1.10 REQ 782761-010-8")) {
System.out.println("found" );
message[i].setFlag(l_flag. DELETED,tr ue);
}
}
iFolder.close(true);
//iStore.close();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("exchan geData(): Error occured due to " + e );
System.exit(1);
}
catch (Throwable e) {
System.out.println("exchan geData().T hrowable: 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.getBo dyPart(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("Othe r body: " + contentType);
// part.writeTo(System.out);
}
}
else if (disposition.equalsIgnoreC ase(Part.I NLINE)) {
//System.out.println("Inli ne: " + part.getFileName() + " : " + contentType);
}
else { // Should never happen
//System.out.println("Othe r: " + disposition);
}
} // handlePart
private static int counter = 0;
}
==================
Please point out the mistake I have made
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_WR
Fatal error: Cannot find class java/lang/StackOverflowErr
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("update
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"
// Get folder
//Folder folder = iStore.getFolder("INBOX");
iFolder.open(Folder.READ_W
// Get directory
Message message[] = iFolder.getMessages();
Flags.Flag l_flag=null;
String firstWordEmailSubject = null;
counter++;
System.out.println(counter
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
} else {
handlePart(message[i]);
}
if (incomingEmailSubject.equa
System.out.println("found"
message[i].setFlag(l_flag.
}
}
iFolder.close(true);
//iStore.close();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("exchan
System.exit(1);
}
catch (Throwable e) {
System.out.println("exchan
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.getBo
}
} // 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()
} else { // Don't think this will happen
//System.out.println("Othe
// part.writeTo(System.out);
}
}
else if (disposition.equalsIgnoreC
//System.out.println("Inli
}
else { // Should never happen
//System.out.println("Othe
}
} // 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.
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.
ASKER
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("update Event");
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_WR ITE); <========== only open the folder once
while (true) {
exchangeData(folder, "LANDATA");
//folder.close(true);
Thread.sleep(10000);
} // End of While loop
//store.close();
} // updateEvent
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("update
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_WR
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?
What version of JavaMail are you using?
ASKER
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/StackOverflowErr or
I'm using JavaMail (API) 1.2 and JDK1.2
Thanks
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/StackOverflowErr
I'm using JavaMail (API) 1.2 and JDK1.2
Thanks
ASKER
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)
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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
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.
99% sure it would contain it.
ASKER
where do i fnd the rt.jar?
the classpath i use
classpath "c:\corpdev6i\JavaAppl;c:\ Java\jdk1. 2\jdbc\lib \classes12 .zip;c:\Ja va\jdk1.2\ jdbc\lib\n ls_charset 12.zip;c:\ Java\jdk1. 2\sqlj\lib \runtime12 .zip;c:\Ja va\jdk1.2\ lib\mail.j ar;c:\Java \jdk1.2\li b\activati on.jar"
no rt.jar attached to my classpath.
the classpath i use
classpath "c:\corpdev6i\JavaAppl;c:\
no rt.jar attached to my classpath.
ASKER
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?
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
No
> what the rt.jar does?
Contains the standard java classes
ASKER
where is the rt.jar located?
as wat you say i need to open the rt.jar to see the class exist or not
as wat you say i need to open the rt.jar to see the class exist or not
ASKER
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.StackOverflowErr or
You don't need to open it. You just need to run
javap java.lang.StackOverflowErr
ASKER
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
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
jar tf rt.jar | find "StackOverflowError"
No output means it's not there
ASKER
Hi CEHJ,
You don't need to open it. You just need to run
javap java.lang.StackOverflowErr or <=== is this a command i run on the dos
You don't need to open it. You just need to run
javap java.lang.StackOverflowErr
ASKER
jar tf rt.jar | find "StackOverflowError" <== this is a unix command, right. I run the window dos and lists of the classes
ASKER
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?
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
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
ASKER
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.
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.StackOverflowErr or <=== 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
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)
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)
:-)
the stacj trace is a good place to start