KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > quikj > server > log > LogProcessor


1 package com.quikj.server.log;
2
3 import com.quikj.server.framework.*;
4
5 import java.net.*;
6 import java.util.*;
7 import java.io.*;
8
9 // JDBC imports
10
import java.sql.*;
11
12 // JAXP packages
13
import javax.xml.parsers.*;
14 import org.xml.sax.*;
15 import org.w3c.dom.*;
16
17
18
19 public class LogProcessor extends AceThread implements AceLoggerInterface
20 {
21     public LogProcessor()
22     throws IOException, AceException, UnknownHostException, ParserConfigurationException
23     {
24         super("LogProcessor");
25         
26         // create the AceTimer and start it
27
timerQ = new AceTimer();
28         timerQ.start();
29         
30         hostName = InetAddress.getLocalHost().getHostName();
31         processName = LogConfiguration.Instance().getProcessName();
32         processInstance = LogConfiguration.Instance().getProcessInstance();
33         processGroupMask = LogConfiguration.Instance().getGroupMask();
34         
35         rxPort = LogConfiguration.Instance().getRxPort();
36         txPort = LogConfiguration.Instance().getTxPort();
37         
38         logGroup = LogConfiguration.Instance().getLogGroup();
39         
40         // create the server socket to listen for log connections
41
txListener = new ConnectionListener("TxConnectionListener",
42         new ServerSocket(txPort),
43         new Integer JavaDoc(0));
44         txListener.start();
45         
46         // create the server socket to listen for log listener connections
47
rxListener = new ConnectionListener("RxConnectionListener",
48         new ServerSocket(rxPort),
49         new Integer JavaDoc(1));
50         rxListener.start();
51         
52         // start the archive timer
53
archiveTimerId = timerQ.startTimer(LogConfiguration.Instance().getNextArchivesInterval(),
54         this,
55         0L);
56         if (archiveTimerId == -1)
57         {
58             throw new AceException("Could not start archive timer");
59         }
60         
61         // open the log files
62
if (LogConfiguration.Instance().saveToFile() == true)
63         {
64             syslogFile = new LogFile(AceLogger.SYSTEM_LOG, hostName);
65             
66             oplogFile = new LogFile(AceLogger.USER_LOG, hostName);
67             
68             sysrepFile = new LogFile(AceLogger.SYSTEM_REPORT, hostName);
69         }
70         
71         // Attempt to start the mail service for the Log email notification
72
// feature :
73
try
74         {
75             // Start mail service only if the mail-service attributes are present :
76
String JavaDoc mailDir = LogConfiguration.Instance().getMailDir();
77             String JavaDoc mailFile = LogConfiguration.Instance().getMailFile();
78             if ((mailDir != null) && (mailFile != null))
79             {
80                 // Attempt to start mail service thread :
81
new AceMailService(mailDir, mailFile, this);
82                 AceMailService.getInstance().start();
83             } // if mail service should be started
84
} // try
85

86         catch (Exception JavaDoc ex)
87         {
88             System.err.println("Error starting AceMailService "
89             + ex.getClass().getName() + ": "
90             + ex.getMessage());
91         } // catch
92

93         // finally, initialize the XML parser
94
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
95         
96         // set various configuration options
97
dbf.setValidating(false);
98         dbf.setIgnoringComments(true);
99         dbf.setIgnoringElementContentWhitespace(true);
100         dbf.setCoalescing(true);
101         dBuilder = dbf.newDocumentBuilder();
102         
103         int command_port = LogConfiguration.Instance().getCommandPort();
104         if (command_port >= 0) // command port specified
105
{
106             AceCommandService service = new AceCommandService("Ace Log Server Management Console",
107             "ALS> ", command_port, 10);
108             
109             // register commands
110
service.registerCommandHandler("shutdown", new LogShutdownCommandHandler());
111         }
112         
113         log(AceLogger.INFORMATIONAL, AceLogger.SYSTEM_LOG,
114         "LogProcessor.LogProcessor() -- Log processor started");
115         instance = this;
116     }
117     
118     public static LogProcessor Instance()
119     {
120         return instance;
121     }
122     
123     public void dispose()
124     {
125         // kill the thread by sending a signal
126
if (interruptWait(AceSignalMessage.SIGNAL_TERM,
127         "Request to kill the thread received") == false)
128         {
129             log(AceLogger.ERROR, AceLogger.SYSTEM_LOG,
130             "LogProcessor.dispose() -- Error occured while sending signal : "
131             + getErrorMessage());
132         }
133         
134         // If mail service is active, shut it down.
135
if (AceMailService.getInstance() != null)
136         {
137             AceMailService.getInstance().dispose();
138         } // aceMailService
139

140         // close the connection listener
141
if (txListener != null)
142         {
143             txListener.dispose();
144         }
145         
146         if (rxListener != null)
147         {
148             rxListener.dispose();
149         }
150         
151         // dispose of all the tx sessions
152
Iterator iter = txList.entrySet().iterator();
153         while (iter.hasNext() == true)
154         {
155             Map.Entry entry = (Map.Entry)iter.next();
156             LogProcessor.SocketInfo info = (LogProcessor.SocketInfo)entry.getValue();
157             
158             info.getStream().dispose();
159         }
160         txList.clear();
161         
162         // dispose of all the rx sessions
163
iter = rxList.entrySet().iterator();
164         while (iter.hasNext() == true)
165         {
166             Map.Entry entry = (Map.Entry)iter.next();
167             LogProcessor.SocketInfo info = (LogProcessor.SocketInfo)entry.getValue();
168             
169             info.getStream().dispose();
170         }
171         rxList.clear();
172         
173         // cancel all timers
174
if (archiveTimerId != -1)
175         {
176             if (timerQ != null)
177             {
178                 timerQ.cancelTimer(archiveTimerId, this);
179             }
180         }
181         
182         if (timerQ != null)
183         {
184             timerQ.dispose();
185             timerQ = null;
186         }
187         
188         // close all the log files
189
if (syslogFile != null)
190         {
191             syslogFile.dispose();
192         }
193         
194         if (oplogFile != null)
195         {
196             oplogFile.dispose();
197         }
198         
199         if (sysrepFile != null)
200         {
201             sysrepFile.dispose();
202         }
203         
204         // close the AceSQL object & database connection, if present
205
if (database != null)
206         {
207             database.dispose();
208             database = null;
209         }
210         
211         if (AceCommandService.getInstance() != null)
212         {
213             AceCommandService.getInstance().dispose();
214         }
215         
216         super.dispose();
217     }
218     
219     public void run()
220     {
221         while (true)
222         {
223             AceMessageInterface message = waitMessage();
224             if (message == null)
225             {
226                 // print error message
227
log(AceLogger.FATAL, AceLogger.SYSTEM_LOG,
228                 "LogProcessor.run() -- An event is received with no event message : "
229                 + getErrorMessage());
230                 dispose();
231                 break;
232             }
233             
234             if ((message instanceof AceTimerMessage) == true)
235             {
236                 AceTimerMessage timer_message = (AceTimerMessage)message;
237                 if (timer_message.getTimerId() == archiveTimerId)
238                 {
239                     processTimerMessage(timer_message);
240                 }
241                 else
242                 {
243                     // print error message and contiue
244
log(AceLogger.WARNING, AceLogger.SYSTEM_LOG,
245                     "LogProcessor.run() -- An unexpected timer event is received");
246                 }
247             }
248             else if ((message instanceof ConnectionEvent) == true)
249             {
250                 ConnectionEvent cevent = (ConnectionEvent)message;
251                 if (((Integer JavaDoc)cevent.getUserParm()).intValue() == 0) // tx connection
252
{
253                     processConnection(cevent, txList);
254                 }
255                 else if (((Integer JavaDoc)cevent.getUserParm()).intValue() == 1) // rx connection
256
{
257                     processConnection(cevent, rxList);
258                 }
259             }
260             else if ((message instanceof AceInputSocketStreamMessage) == true)
261             {
262                 processLogMessage((AceInputSocketStreamMessage)message);
263             }
264             else if ((message instanceof LogProcessor.LogMessageEvent) == true)
265             {
266                 LogProcessor.LogMessageEvent event = (LogProcessor.LogMessageEvent)message;
267                 processLogMessage(event.getMessage(), null, null);
268             }
269             else if ((message instanceof AceSQLMessage) == true)
270             {
271                 AceSQLMessage result_message = (AceSQLMessage)message;
272                 processSqlResult(result_message);
273             }
274             else if ((message instanceof AceSignalMessage) == true)
275             {
276                 // print info message
277
break;
278             }
279             else
280             {
281                 // print error message and contiue
282
log(AceLogger.WARNING, AceLogger.SYSTEM_LOG,
283                 "LogProcessor.run() -- An unexpected event is received : "
284                 + message.messageType());
285                 
286             }
287         }
288     }
289     
290     public boolean log(int severity, int msg_type, String JavaDoc message, int msg_id)
291     {
292         // create the XML message
293
AceLogMessage log_msg = new AceLogMessage(logGroup,
294         hostName,
295         processName,
296         processInstance,
297         severity,
298         msg_type,
299         message,
300         msg_id);
301         
302         LogProcessor.LogMessageEvent event = new LogProcessor.LogMessageEvent(log_msg);
303         return sendMessage(event);
304     }
305     
306     public boolean log(int severity, int msg_type, String JavaDoc message)
307     {
308         return log(severity, msg_type, message, -1);
309     }
310     
311     private void processConnection(ConnectionEvent event, HashMap list)
312     {
313         try
314         {
315             Socket tx_socket = event.getSocket();
316             tx_socket.setKeepAlive(true);
317             tx_socket.setTcpNoDelay(true);
318             
319             int code = tx_socket.hashCode();
320             
321             BufferedWriter tx_writer = new BufferedWriter(new OutputStreamWriter(tx_socket.getOutputStream()));
322             
323             AceInputSocketStream reader_thread = new AceInputSocketStream(code,
324             "AceLogger", tx_socket, true);
325             reader_thread.start();
326             
327             list.put(new Integer JavaDoc(code), new LogProcessor.SocketInfo(tx_writer,
328             reader_thread));
329         }
330         catch (Exception JavaDoc ex)
331         {
332             log(AceLogger.WARNING, AceLogger.SYSTEM_LOG,
333             "LogProcessor.processConnection() -- Error creating socket stream : "
334             + ex.getClass().getName() + ": " + ex.getMessage());
335         }
336     }
337     
338     private void processTimerMessage(AceTimerMessage message)
339     {
340         if (LogConfiguration.Instance().saveToFile() == false)
341         {
342             return;
343         }
344         
345         if (syslogFile.archive() == false)
346         {
347             // print error message
348
log(AceLogger.WARNING, AceLogger.SYSTEM_LOG,
349             "LogProcessor.processTimerMessage() -- Archiving of the SYSLOG file failed : "
350             + syslogFile.getErrorMessage());
351             
352         }
353         
354         if (oplogFile.archive() == false)
355         {
356             // print error message
357
log(AceLogger.WARNING, AceLogger.SYSTEM_LOG,
358             "LogProcessor.processTimerMessage() -- Archiving of the OPLOG file failed : "
359             + oplogFile.getErrorMessage());
360         }
361         
362         if (sysrepFile.archive() == false)
363         {
364             // print error message
365
log(AceLogger.WARNING, AceLogger.SYSTEM_LOG,
366             "LogProcessor.processTimerMessage() -- Archiving of the SYSREP file failed : "
367             + sysrepFile.getErrorMessage());
368         }
369     }
370     
371     private void processLogMessage(AceInputSocketStreamMessage message)
372     {
373         // get the code
374
Integer JavaDoc code = new Integer JavaDoc((int)message.getUserParm());
375         LogProcessor.SocketInfo stream = (LogProcessor.SocketInfo)txList.get(code);
376         HashMap list;
377         
378         if (stream == null)
379         {
380             stream = (LogProcessor.SocketInfo)rxList.get(code);
381             if (stream == null)
382             {
383                 // print error message
384
log(AceLogger.WARNING, AceLogger.SYSTEM_LOG,
385                 "LogProcessor.processLogMessage() -- A log message is received from an unregistered input stream");
386                 return;
387             }
388             else
389             {
390                 list = rxList;
391             }
392         }
393         else
394         {
395             list = txList;
396         }
397         
398         switch (message.getStatus())
399         {
400             case AceInputSocketStreamMessage.EOF_REACHED:
401                 // the connection has been closed
402
stream.getStream().dispose();
403                 list.remove(code);
404                 break;
405                 
406             case AceInputSocketStreamMessage.READ_COMPLETED:
407                 try
408                 {
409                     InputSource is = new InputSource(new StringReader(message.getLines()));
410                     Document doc = dBuilder.parse(is);
411                     
412                     AceLogMessageParser parser = new AceLogMessageParser(processGroupMask, doc);
413                     
414                     AceLogMessageInterface msg_element = parser.getMessageElement();
415                     if ((msg_element instanceof AceTraceReqMessage) == true)
416                     {
417                         processTraceReqMessage((AceTraceReqMessage)msg_element, list, stream);
418                     }
419                     else if ((msg_element instanceof AceLogMessage) == true)
420                     {
421                         processLogMessage((AceLogMessage)msg_element, list, stream);
422                     }
423                     else if ((msg_element instanceof AceTraceInfoMessage) == true)
424                     {
425                         processTraceInfoMessage((AceTraceInfoMessage)msg_element, list, stream);
426                     }
427                     else
428                     {
429                         // print error message about receiving a bad message
430
log(AceLogger.WARNING, AceLogger.SYSTEM_LOG,
431                         "LogProcessor.processLogMessage() -- An unexpected log message is received : "
432                         + msg_element.messageType());
433                     }
434                 }
435                 catch (SAXException ex1)
436                 {
437                     // print error message about receiving a bad message
438

439                     log(AceLogger.WARNING, AceLogger.SYSTEM_LOG,
440                     "LogProcessor.processLogMessage() -- A log message is received with invalid XML syntax : "
441                     + ex1.getMessage());
442                     
443                     return;
444                 }
445                 catch (AceException ex2)
446                 {
447                     // print error message about receiving a bad message
448
log(AceLogger.WARNING, AceLogger.SYSTEM_LOG,
449                     "LogProcessor.processLogMessage() -- A log message is received with invalid syntax : "
450                     + ex2.getMessage());
451                     
452                     return;
453                 }
454                 catch (IOException ex3)
455                 {
456                     // should not happen
457
// print error message about receiving a bad message
458

459                     log(AceLogger.WARNING, AceLogger.SYSTEM_LOG,
460                     "LogProcessor.processLogMessage() -- A log message is received with IO error : "
461                     + ex3.getMessage());
462                     
463                     return;
464                 }
465                 break;
466                 
467             default:
468                 // print error message
469
log(AceLogger.ERROR, AceLogger.SYSTEM_LOG,
470                 "LogProcessor.processLogMessage() -- A log message is received with invalid status : "
471                 + message.getStatus());
472         }
473     }
474     
475     private void processTraceReqMessage(AceTraceReqMessage message,
476     HashMap list, LogProcessor.SocketInfo info)
477     {
478         // send a trace message
479
AceTraceInfoMessage msg = new AceTraceInfoMessage(processGroupMask, traceInfo);
480         sendMessage(formatMessage(msg.getFormattedMessage()), info.getWriter());
481     }
482     
483     private void processTraceInfoMessage(AceTraceInfoMessage message,
484     HashMap list, LogProcessor.SocketInfo info)
485     {
486         Hashtable trace_info = message.getTraceInformation();
487         if (trace_info != null)
488         {
489             traceInfo = trace_info;
490             
491             // broadcast the trace info message
492
AceTraceInfoMessage msg = new AceTraceInfoMessage(processGroupMask, traceInfo);
493             broadcastTraceMessage(msg);
494         }
495     }
496     
497     private String JavaDoc formatMessage(String JavaDoc message)
498     {
499         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
500         StringTokenizer tokens = new StringTokenizer(message, "\n");
501         int count = tokens.countTokens();
502         
503         for (int i = 0; i < count; i++)
504         {
505             String JavaDoc line = tokens.nextToken();
506             if (line.startsWith(".") == true)
507             {
508                 buffer.append(" ." + line + '\n');
509             }
510             else
511             {
512                 buffer.append(line + '\n');
513             }
514         }
515         
516         buffer.append (".\n");
517         return buffer.toString();
518     }
519     
520     private void broadcastTraceMessage(AceTraceInfoMessage message)
521     {
522         String JavaDoc formatted_message = formatMessage(message.getFormattedMessage());
523         Iterator iter = txList.entrySet().iterator();
524         while (iter.hasNext() == true)
525         {
526             Map.Entry entry = (Map.Entry)iter.next();
527             LogProcessor.SocketInfo info = (LogProcessor.SocketInfo)entry.getValue();
528             BufferedWriter writer = info.getWriter();
529             
530             sendMessage(formatted_message, writer);
531         }
532     }
533     
534     private void broadcastMessage(AceLogMessage message)
535     {
536         String JavaDoc formatted_message = formatMessage(message.getFormattedMessage());
537         Iterator iter = rxList.entrySet().iterator();
538         while (iter.hasNext() == true)
539         {
540             Map.Entry entry = (Map.Entry)iter.next();
541             LogProcessor.SocketInfo info = (LogProcessor.SocketInfo)entry.getValue();
542             BufferedWriter writer = info.getWriter();
543             
544             sendMessage(formatted_message, writer);
545         }
546     }
547     
548     /////////////////////////////////////////////////////////////////////
549
/**
550      * processLogMessage - determines if the log message should
551      * be sent to the console or to a file as specified and
552      * determines if an email notification should be sent
553      * @author amit, elizabeth
554      * @version
555      */

556     /////////////////////////////////////////////////////////////////////////
557
private void processLogMessage(AceLogMessage message,
558     HashMap list, LogProcessor.SocketInfo info)
559     {
560         // first, broadcast the message to all parties listeneing on the rx scoket
561
broadcastMessage(message);
562         
563         if (LogConfiguration.Instance().printToConsole() == true)
564         {
565             processPrintToConsole(message);
566         }
567         
568         if (LogConfiguration.Instance().saveToFile() == true)
569         {
570             proccessSaveToFile(message);
571         }
572         // Determine if an error email notification should be sent :
573
if (AceMailService.getInstance() != null)
574         {
575             processEmailNotification(message);
576         } // aceMailService exists
577

578         // Determine if log should be saved to DB :
579
LogDbInfo dbInfoElement = LogConfiguration.Instance().checkLogDbInfo();
580         if (dbInfoElement.isDbExists())
581             processSaveLogToDb(dbInfoElement, message);
582         
583     } // processLogMessage
584

585     private void processSqlResult(AceSQLMessage message)
586     {
587         if (message.getStatus() == AceSQLMessage.SQL_ERROR)
588         {
589             System.err.println("processSqlResult() : Error encountered while storing log message in database");
590             return;
591         }
592         
593         if (message.getAffectedRows() != 1)
594         {
595             System.err.println("processSqlResult() : Error storing log message in database");
596         }
597     }
598     
599     /////////////////////////////////////////////////////////////////////
600
/**
601      * processPrintToConsole - sets up the message and sends it to
602      * the printer
603      * @author amit, elizabeth
604      * @version
605      */

606     /////////////////////////////////////////////////////////////////////////
607
private void processPrintToConsole(AceLogMessage message)
608     {
609         System.out.println(formatForOutputDevice(message.getTimeStamp(),
610         message.getHostName(),
611         message.getProcessName(),
612         message.getProcessInstance(),
613         message.getSeverity(),
614         message.getMessage(),
615         message.getMessageId(),
616         LogConfiguration.Instance().printColor()));
617     } // processPrintToConsole
618

619     /////////////////////////////////////////////////////////////////////
620
/**
621      * proccessSaveToFile - sets up the message and writes it to a file
622      * @author amit, elizabeth
623      * @version
624      */

625     /////////////////////////////////////////////////////////////////////////
626
private void proccessSaveToFile(AceLogMessage message)
627     {
628         int msg_type = message.getMessageType();
629         if ((msg_type == AceLogger.SYSTEM_LOG) ||
630         (msg_type == AceLogger.USER_LOG) ||
631         (msg_type == AceLogger.SYSTEM_REPORT))
632         {
633             LogFile file = null;
634             switch (msg_type)
635             {
636                 case AceLogger.SYSTEM_LOG:
637                     file = syslogFile;
638                     break;
639                     
640                 case AceLogger.USER_LOG:
641                     file = oplogFile;
642                     break;
643                     
644                 case AceLogger.SYSTEM_REPORT:
645                     file = sysrepFile;
646                     break;
647             }
648             
649             if (file.write(format(message.getTimeStamp(),
650             message.getHostName(),
651             message.getProcessName(),
652             message.getProcessInstance(),
653             message.getSeverity(),
654             message.getMessage(),
655             message.getMessageId())) == false)
656             {
657                 // print error message
658
log(AceLogger.ERROR, AceLogger.SYSTEM_LOG,
659                 "LogProcessor.processLogMessage() -- Error writing log message to the file");
660             }
661         }
662     } // processSaveToFile
663

664     /////////////////////////////////////////////////////////////////////
665
/**
666      * processEmailNotification - determines if a log status email
667      * should be sent
668      * @author amit, elizabeth
669      * @version
670      */

671     /////////////////////////////////////////////////////////////////////////
672
private void processEmailNotification(AceLogMessage message)
673     {
674         // If the error found matches the severity in the config file which
675
// indicates a notification email must be sent, try to send the email :
676
LogEmailInfo emailInfoElement;
677         emailInfoElement = new LogEmailInfo();
678         if (LogConfiguration.Instance().checkEmailType(message.getSeverity(), emailInfoElement))
679             // The email notification may be sent if the log mail service is active :
680
sendLogEmailNotification(message, emailInfoElement);
681         
682     } // processEmailNotification
683

684     /////////////////////////////////////////////////////////////////////
685
/**
686      * processSaveLogToDb - saves the log to the DB.
687      * @author amit, elizabeth
688      * @version
689      */

690     /////////////////////////////////////////////////////////////////////////
691
private void processSaveLogToDb(LogDbInfo dbInfo, AceLogMessage message)
692     {
693         
694         // get the current connection, or a new one if the old one has expired
695
if (getDbConnection(dbInfo) == null)
696         {
697             System.err.println("processSaveLogToDB : Failure connecting to database "
698             + dbInfo.getDbmsUrl() + '\n');
699             
700             return;
701         } // no DB connection
702

703         // Insert the data using PreparedStatements :
704
try
705         {
706             processLogDbSqlStmts(dbInfo, message);
707         } // try sql stmt
708

709         catch (SQLException ex)
710         {
711             System.err.println("processSaveLogToDB : An SQL error occurred while trying to update the DB" +
712             '\n' +
713             " Exception processing result : " + ex.getMessage() + '\n');
714             return;
715         } // sql exception
716

717     } // processSaveLogToDb
718

719     /////////////////////////////////////////////////////////////////////
720
/**
721      * getDbConnection - establishes a new connection, if needed.
722      * Makes sure AceSQL database object is in synch w/connection.
723      * If connection is returned, the appropriate database object exists.
724      * There are two parts to establishing a new connection :
725      * 1. Loading the driver
726      * 2. making the connection
727      * @author amit, elizabeth
728      * @version
729      */

730     /////////////////////////////////////////////////////////////////////////
731
private Connection getDbConnection(LogDbInfo dbInfo)
732     {
733         try
734         {
735             boolean new_connection = false;
736             if (connection == null)
737             {
738                 new_connection = true;
739             }
740             else
741             {
742                 if (connection.isClosed() == true)
743                 {
744                     new_connection = true;
745                     database = null;
746                 }
747             }
748             
749             if (new_connection == true)
750             {
751                 // 1. Load the JDBC driver :
752
Class.forName(dbInfo.getDbClass()).newInstance();
753                 
754                 // 2. Make the connection :
755
String JavaDoc urlString = new String JavaDoc(dbInfo.getDbmsUrl() + "://" + dbInfo.getDbHost() +
756                 "/" + dbInfo.getDbName());
757                 
758                 connection = DriverManager.getConnection(urlString, dbInfo.getDbUser(), dbInfo.getDbPassword());
759                 if (connection != null)
760                 {
761                     database = new AceSQL(connection);
762                 }
763                 
764                 return connection;
765             }
766             else
767             {
768                 return connection;
769             }
770         }
771         catch (Exception JavaDoc ex)
772         {
773             System.err.println(" getDbConnection : An error occurred while trying to connect to the database server"
774             + '\n' +
775             " Exception processing result : " + ex.getMessage() + '\n');
776             
777             connection = null;
778             database = null;
779             return null;
780         }
781     }
782     
783     /////////////////////////////////////////////////////////////////////
784
/**
785      * getDateString - converts given timestamp to proper format.
786      *
787      * @author amit, elizabeth
788      * @version
789      */

790     /////////////////////////////////////////////////////////////////////////
791
private String JavaDoc getDateString(java.util.Date JavaDoc timestamp)
792     {
793         Calendar cal = Calendar.getInstance();
794         cal.setTime(timestamp);
795         
796         String JavaDoc date_string = cal.get(Calendar.YEAR) + "-"
797         + (cal.get(Calendar.MONTH) + 1) + "-"
798         + cal.get(Calendar.DAY_OF_MONTH) + " "
799         + cal.get(Calendar.HOUR_OF_DAY) + ":"
800         + cal.get(Calendar.MINUTE) + ":"
801         + cal.get(Calendar.SECOND);
802         
803         return date_string;
804         
805     } // getDateString
806

807     /////////////////////////////////////////////////////////////////////
808
/**
809      * processLogDbSqlStmts - constructs SQL PreparedStatements and
810      * sends them to the log DB.
811      * @author amit, elizabeth
812      * @version
813      */

814     /////////////////////////////////////////////////////////////////////////
815
private void processLogDbSqlStmts(LogDbInfo dbInfo,
816     AceLogMessage message)
817     throws SQLException
818     {
819         // Construct the sql statement using a prepared statment :
820
String JavaDoc sqlStmt = "insert into " + LogDbInfo.getLogTblName()
821         + " values (?, ?, ?, ?, ?, ?);";
822         
823         PreparedStatement pStmt = connection.prepareStatement(sqlStmt);
824         
825         // Fill in the pStmt parameters from the log message - note : the
826
// first value in prepared statement must be converted (caluculated)
827
// using the getDateString so the time is correct in the DB :
828
pStmt.setString (1, getDateString(new java.util.Date JavaDoc(message.getTimeStamp())));
829         pStmt.setInt (2, message.getSeverity());
830         pStmt.setString (3, message.getHostName());
831         pStmt.setString (4, message.getProcessName());
832         pStmt.setString (5, String.valueOf(message.getProcessInstance()));
833         pStmt.setString (6, message.getMessage());
834         
835         if (database.executeSQL(pStmt, (String JavaDoc[]) null, null) == -1)
836         {
837             System.err.println("processLogDbSqlStmts() : Couldn't store log record in the database");
838         }
839         
840     } // processLogDbSqlStmts
841

842     /////////////////////////////////////////////////////////////////////////
843
/**
844      * sendLogMessage - sends the datagram message
845      * @author amit
846      * @version
847      */

848     /////////////////////////////////////////////////////////////////////////
849
private boolean sendMessage(String JavaDoc message, BufferedWriter writer)
850     {
851         try
852         {
853             writer.write(message);
854             writer.flush();
855         }
856         catch (IOException ex)
857         {
858             // print error message
859
log(AceLogger.ERROR, AceLogger.SYSTEM_LOG,
860             "LogProcessor.sendMessage() -- IO Error while sending message : "
861             + ex.getMessage());
862             return false;
863         }
864         return true;
865     } // sendMessage
866

867     /////////////////////////////////////////////////////////////////////////
868
/**
869      * sendLogEmailNotification - the log is sent to the specified
870      * To and CC email addresses (which correspond to the current
871      * error).
872      * @author elizabeth
873      * @version
874      */

875     /////////////////////////////////////////////////////////////////////////
876
private void sendLogEmailNotification(AceLogMessage emailMessage, LogEmailInfo emailInfoElement)
877     {
878         
879         AceMailMessage msg = new AceMailMessage();
880         
881         try
882         {
883             // Add the subject content :
884
msg.setSubject("Ace LOG notification");
885             
886             // Add the Body content :
887
msg.setBody(formatForOutputDevice(emailMessage.getTimeStamp(),
888             emailMessage.getHostName(),
889             emailMessage.getProcessName(),
890             emailMessage.getProcessInstance(),
891             emailMessage.getSeverity(),
892             emailMessage.getMessage(),
893             emailMessage.getMessageId(),
894             false));
895             
896             // Add the "To" mail parameter :
897
if (!emailInfoElement.getEmailToAddress().isEmpty())
898             {
899                 for (int index = 0; index < emailInfoElement.getEmailToAddress().size(); index++)
900                 {
901                     msg.addTo(emailInfoElement.getEmailToAddress(index));
902                 } // for
903

904                 // Add the "CC" mail parameter :
905
if (!emailInfoElement.getEmailCcAddress().isEmpty())
906                 {
907                     for (int index = 0; index < emailInfoElement.getEmailCcAddress().size(); index++)
908                     {
909                         msg.addCc(emailInfoElement.getEmailCcAddress(index));
910                     } // for
911
} // if "CC" found
912
} // if "To" size > 0
913

914             //msg.addBcc("beckymc@mindspring.com");
915
//msg.addCc("beckymc@mindspring.com");
916

917             // Send the message :
918
if (AceMailService.getInstance().addToMailQueue(msg) == false)
919             {
920                 System.err.println("Error adding message to mail service queue");
921             } // add to message queue
922

923         } // try
924

925         catch (Exception JavaDoc ex1)
926         {
927             // print error message
928
log(AceLogger.ERROR, AceLogger.SYSTEM_LOG,
929             "LogProcessor.sendLogEmailNotification() -- IO Error while sending datagram message : "
930             + ex1.getMessage());
931         } // exception
932

933     } // sendLogEmailNotification
934

935     /////////////////////////////////////////////////////////////////////////
936
/**
937      * format
938      * @author amit
939      * @version
940      */

941     /////////////////////////////////////////////////////////////////////////
942

943     private String JavaDoc format(long time_stamp,
944     String JavaDoc host,
945     String JavaDoc process_name,
946     int process_instance,
947     int severity,
948     String JavaDoc message,
949     int msg_id)
950     {
951         return (new AceLogMessage(new java.util.Date JavaDoc(time_stamp),
952         1,
953         host,
954         process_name,
955         process_instance,
956         severity,
957         0,
958         message,
959         msg_id,
960         true)).getFormattedMessage();
961     }
962     
963     /////////////////////////////////////////////////////////////////////////
964
/**
965      * formatForOutputDevice - formats the log data into a string for output
966      * on a console, for the body of an email, etc.
967      * @author amit, elizabeth
968      * @version
969      */

970     /////////////////////////////////////////////////////////////////////////
971
private String JavaDoc formatForOutputDevice(long time_stamp,
972     String JavaDoc host,
973     String JavaDoc process_name,
974     int process_instance,
975     int severity,
976     String JavaDoc message,
977     int msg_id,
978     boolean in_color)
979     {
980         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
981         String JavaDoc escape_char_prefix = null;
982         
983         if (in_color == true)
984         {
985             escape_char_prefix = AceLogger.COLOR_S[severity];
986         }
987         else
988         {
989             escape_char_prefix = "";
990         }
991         
992         java.util.Date JavaDoc date = new java.util.Date JavaDoc(time_stamp);
993         
994         if (msg_id != -1)
995         {
996             buffer.append(pad0(process_instance, MSG_ID_LEN - 1));
997         }
998         pad(buffer, MSG_ID_LEN);
999         
1000        buffer.append(AceLogger.SEVERITY_S[severity]);
1001        pad(buffer, MSG_ID_LEN + AceLogger.MAX_SEVERITY_LENGTH+1);
1002        
1003        buffer.append(host);
1004        pad(buffer, MSG_ID_LEN + AceLogger.MAX_SEVERITY_LENGTH+1 + HOST_NAME_LEN);
1005        
1006        buffer.append(process_name);
1007        pad(buffer, MSG_ID_LEN + AceLogger.MAX_SEVERITY_LENGTH+1 + HOST_NAME_LEN + PROCESS_NAME_LEN);
1008        
1009        buffer.append(pad0(process_instance, PROCESS_INSTANCE_LEN - 1));
1010        pad(buffer, MSG_ID_LEN + AceLogger.MAX_SEVERITY_LENGTH+1 + HOST_NAME_LEN + PROCESS_NAME_LEN + PROCESS_INSTANCE_LEN);
1011        
1012        buffer.append(message);
1013        
1014        return new String JavaDoc(escape_char_prefix
1015        + date.toString()
1016        + ' '
1017        + buffer.toString()
1018        + '\n');
1019        
1020    } // formatForOutputDevice
1021

1022    private void pad(StringBuffer JavaDoc buffer, int length)
1023    {
1024        int num_pad = length - buffer.length();
1025        
1026        if (num_pad > 0)
1027        {
1028            char[] char_pad = new char[num_pad];
1029            for (int i = 0; i < num_pad; i++)
1030            {
1031                char_pad[i] = ' ';
1032            }
1033            buffer.append(char_pad);
1034        }
1035    }
1036    
1037    private String JavaDoc pad0(int num, int size)
1038    {
1039        String JavaDoc pad_str = "";
1040        String JavaDoc num_str = new String JavaDoc((new Integer JavaDoc(num)).toString());
1041        
1042        int num_pad = size - num_str.length();
1043        
1044        if (num_pad > 0)
1045        {
1046            char[] char_pad = new char[num_pad];
1047            for (int i = 0; i < num_pad; i++)
1048            {
1049                char_pad[i] = '0';
1050            }
1051            pad_str = new String JavaDoc(char_pad);
1052        }
1053        
1054        return new String JavaDoc(pad_str + num_str);
1055    }
1056    
1057    public static void main(String JavaDoc[] args)
1058    {
1059        String JavaDoc dir = null;
1060        String JavaDoc file = null;
1061        
1062        // check the arguments
1063
for (int i = 0; i < args.length; i++)
1064        {
1065            if (args[i].startsWith(ARG_DIR) == true)
1066            {
1067                dir = args[i].substring(ARG_DIR.length());
1068            }
1069            else if (args[i].startsWith(ARG_FILE) == true)
1070            {
1071                file = args[i].substring(ARG_FILE.length());
1072            }
1073            else
1074            {
1075                System.err.println("Command line parameter : "
1076                + args[i]
1077                + " unrecognized");
1078                System.exit(1);
1079            }
1080        }
1081        
1082        if ((dir == null) || (file == null))
1083        {
1084            System.err.println(ARG_DIR + " and/or " + ARG_FILE
1085            + " parameter missing in LogProcessor");
1086            System.exit(1);
1087        }
1088        
1089        try
1090        {
1091            new LogConfiguration(dir, file);
1092        }
1093        catch (Exception JavaDoc ex)
1094        {
1095            System.err.println(ex.getClass().getName()
1096            + " while loading configuration file : "
1097            + ex.getMessage());
1098            System.exit(1);
1099        }
1100        
1101        LogProcessor lp = null;
1102        try
1103        {
1104            lp = new LogProcessor();
1105            lp.start();
1106            
1107            Runtime.getRuntime().addShutdownHook(new ShutdownHandlerThread());
1108        }
1109        catch (Exception JavaDoc ex1)
1110        {
1111            System.err.println(ex1.getClass().getName()
1112            + " while loading log processor thread : "
1113            + ex1.getMessage());
1114            System.exit(1);
1115        }
1116        
1117        try
1118        {
1119            lp.join();
1120            System.exit(0);
1121        }
1122        catch (InterruptedException JavaDoc ex2)
1123        {
1124            System.err.println("InterruptedException : " + ex2.getMessage());
1125            System.exit(1);
1126        } // lp exception
1127
} // main
1128

1129    /////////////////////////////////////////////////////////////////////////
1130
/** Getter for property logEmailMessage.
1131     * @return Value of property logEmailMessage.
1132     *
1133     */

1134    /////////////////////////////////////////////////////////////////////////
1135
public java.lang.String JavaDoc getLogEmailMessage()
1136    {
1137        return logEmailMessage;
1138    }
1139    
1140    /////////////////////////////////////////////////////////////////////////
1141
/** Setter for property logEmailMessage.
1142     * @param logEmailMessage New value of property logEmailMessage.
1143     *
1144     */

1145    /////////////////////////////////////////////////////////////////////////
1146
public void setLogEmailMessage(java.lang.String JavaDoc logEmailMessage)
1147    {
1148        this.logEmailMessage = logEmailMessage;
1149    }
1150    
1151    class SocketInfo
1152    {
1153        public SocketInfo(BufferedWriter writer, AceInputSocketStream stream)
1154        {
1155            this.writer = writer;
1156            this.stream = stream;
1157        }
1158        
1159        public BufferedWriter getWriter()
1160        {
1161            return writer;
1162        }
1163        
1164        public AceInputSocketStream getStream()
1165        {
1166            return stream;
1167        }
1168        
1169        private BufferedWriter writer;
1170        private AceInputSocketStream stream;
1171    }
1172    
1173    class LogMessageEvent implements AceMessageInterface
1174    {
1175        public LogMessageEvent(AceLogMessage message)
1176        {
1177            this.message = message;
1178        }
1179        
1180        public String JavaDoc messageType()
1181        {
1182            return "AceLogMessage";
1183        }
1184        
1185        public AceLogMessage getMessage()
1186        {
1187            return message;
1188        }
1189        
1190        private AceLogMessage message;
1191    }
1192    
1193    /////////////////////////////////////////////////////////////////////////
1194
// Attributes
1195
/////////////////////////////////////////////////////////////////////////
1196

1197    private static final String JavaDoc ARG_DIR = "dir=";
1198    private static final String JavaDoc ARG_FILE = "file=";
1199    
1200    private static final int MSG_ID_LEN = 5 + 1; // 5 characters + the space character
1201
private static final int HOST_NAME_LEN = 25 + 1;
1202    private static final int PROCESS_NAME_LEN = 15 + 1;
1203    private static final int PROCESS_INSTANCE_LEN = 3 + 1;
1204    
1205    private String JavaDoc hostName;
1206    private String JavaDoc processName;
1207    private int processInstance;
1208    private int txPort;
1209    private int rxPort;
1210    
1211    private HashMap txList = new HashMap();
1212    private HashMap rxList = new HashMap();
1213    
1214    private ConnectionListener txListener;
1215    private ConnectionListener rxListener;
1216    
1217    private int logGroup;
1218    private LogFile syslogFile = null;
1219    private LogFile oplogFile = null;
1220    private LogFile sysrepFile = null;
1221    
1222    private AceTimer timerQ = null;
1223    private int archiveTimerId = -1;
1224    private DocumentBuilder dBuilder = null;
1225    private int processGroupMask;
1226    
1227    private Hashtable traceInfo = new Hashtable();
1228    
1229    // Log email notification attributes :
1230
private String JavaDoc mailDir;
1231    private String JavaDoc mailFile;
1232    private String JavaDoc logEmailMessage = null;
1233    
1234    // DB connection
1235
private Connection connection = null;
1236    private AceSQL database = null;
1237    
1238    private static LogProcessor instance = null;
1239    
1240} // LogProcessor
Popular Tags