KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > ist > coach > coachEmfServicesComponents > BasicLogProviderComposition > basicLogSegImpl


1 /*====================================================================
2
3 This file was produced by the OpenCCM CIF_JIMPL generator.
4
5 OpenCCM: The Open CORBA Component Model Platform
6 Copyright (C) 2000-2003 INRIA - USTL - LIFL - GOAL
7 Contact: openccm@objectweb.org
8
9 This library is free software; you can redistribute it and/or
10 modify it under the terms of the GNU Lesser General Public
11 License as published by the Free Software Foundation; either
12 version 2.1 of the License, or any later version.
13
14 This library is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 Lesser General Public License for more details.
18
19 You should have received a copy of the GNU Lesser General Public
20 License along with this library; if not, write to the Free Software
21 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
22 USA
23
24 Initial developer(s): Christophe Demarey.
25 Contributor(s): ______________________________________.
26
27 ====================================================================*/

28
29 package ist.coach.coachEmfServicesComponents.BasicLogProviderComposition;
30
31 import ist.coach.coachEmfServices.EmfBasicLog.*;
32 import ist.coach.coachEmfCommon.Utils;
33 import ist.coach.coachEmfCommon.LogNewRecordImpl;
34 import org.omg.CORBA.Any JavaDoc;
35 import java.sql.*;
36
37 import java.util.Calendar JavaDoc;
38
39 /**
40  * This is the CIDL-based implementation of the
41  * OMG IDL3 CIDL:coach.ist/coachEmfServicesComponents/BasicLogProviderComposition/BasicLogProviderHome_impl/BasicLogProvider_impl/basicLogSeg:1.0 segment type.
42  *
43  * @author OpenCCM CIF_Jimpl Compiler.
44  */

45 public class basicLogSegImpl
46      extends ist.coach.coachEmfServicesComponents.BasicLogProviderComposition.basicLogSeg
47 {
48     // ==================================================================
49
//
50
// Internal states.
51
//
52
// ==================================================================
53

54     private boolean logOffDuty_ = false;
55     private boolean logLocked_ = false; // administrative state
56
private boolean logDisabled_ = false; // operational state
57
private long dbTableMaxSize_ = -1;
58
59
60
61     // ==================================================================
62
//
63
// Constructors.
64
//
65
// ==================================================================
66

67     public basicLogSegImpl()
68     {
69     }
70
71     // ==================================================================
72
//
73
// Methods.
74
//
75
// ==================================================================
76

77     /**
78      * Implementation of the ::coachEmfServices::EmfBasicLog::BasicLog::destroy operation.
79      */

80     public void
81     destroy()
82     {
83         //
84
// DONE : Implement
85
//
86
try {
87           get_main_segment().ccm_remove();
88         }
89         catch(org.omg.Components.CCMException e) {}
90     }
91
92         /**
93      * Implementation of the ::coachEmfServices::EmfBasicLog::BasicLog::write_record operation.
94      */

95     public long
96     write_record(org.omg.CORBA.Any JavaDoc record, ist.coach.coachEmfServices.EmfBasicLog.NVPair[] nv)
97     throws ist.coach.coachEmfServices.EmfBasicLog.LogFull,
98         ist.coach.coachEmfServices.EmfBasicLog.LogOffDuty,
99         ist.coach.coachEmfServices.EmfBasicLog.LogLocked,
100         ist.coach.coachEmfServices.EmfBasicLog.LogDisabled
101     {
102         //
103
// DONE : Implement
104
//
105
//System.err.println("basicLogSegImpl>write record called!!");
106
long recordId = -1;
107
108         if (record == null)
109             return recordId;
110
111         if ( logOffDuty_ )
112             throw new LogOffDuty();
113
114         if ( logLocked_ )
115             throw new LogLocked();
116
117         if ( logDisabled_ ) {
118             throw new LogDisabled();
119         }
120
121
122         // Connect to JDBC driver
123
try
124         {
125             Class.forName(get_main_segment().databaseDriver()).newInstance();
126             }
127         catch (Exception JavaDoc ex)
128         {
129             System.out.println("** BasicLogImpl: <EXCEPTION> While connecting to jdbx driver");
130             System.out.println(ex.getMessage());
131             return -1;
132         }
133
134         Connection dbConnection = null;
135
136         // Perform test for LogFull
137
String JavaDoc logTableName = get_main_segment().databaseTable() +
138             Integer.toString(get_main_segment().logId());
139         try {
140
141           dbConnection = DriverManager.getConnection(get_main_segment().databaseConnection());
142           Statement dbTestStatement = dbConnection.createStatement();
143           ResultSet dbTestResults = dbTestStatement.executeQuery("SHOW TABLE STATUS");
144
145           while (dbTestResults.next()) {
146                 if ( dbTestResults.getString(1).equalsIgnoreCase(logTableName) ) {
147                     long avgRowLength = dbTestResults.getLong(5);
148                     long dataLength = dbTestResults.getLong(6);
149                     long maxDataLength = dbTestResults.getLong(7);
150                     dbTableMaxSize_ = maxDataLength;
151                     short numOfRows = dbTestResults.getShort(4);
152
153                     if ( maxDataLength <= (dataLength + avgRowLength) ){
154                         LogFull ex_logFull = new LogFull(numOfRows);
155                         throw ex_logFull;
156                     }
157                 }
158             }
159         }
160         catch (Exception JavaDoc ex){
161             System.err.println("** BasicLogImpl: <EXCEPTION> While connecting to jdbx driver");
162             System.err.println(ex.getMessage());
163             return -1;
164         }
165
166         PreparedStatement dbStatement = null;
167
168         try {
169             dbConnection = DriverManager.getConnection(get_main_segment().databaseConnection());
170
171             dbStatement = dbConnection.prepareStatement("INSERT INTO " + logTableName +
172                                         " (logRecordId, timeStamp, logDataType, logData)" +
173                                         " VALUES(? , ?, ?, ?)" );
174         }
175         catch (Exception JavaDoc ex) {
176             System.err.println("** BasicLogImpl: <EXCEPTION> While getting db connection");
177             System.err.println(ex.getMessage());
178             return -1;
179         }
180
181         AnyTypeTrans AT = new AnyTypeTrans();
182
183         // For the received event extract the information based on the
184
// 'LogRecord'(defined in Log.idl) and stored it in the given log
185
// database and table.
186

187         int anyKindInt = -1;
188
189         Any JavaDoc receivedLogInfo = record;
190
191         // Create timestamp
192
java.util.Date JavaDoc currentDateTime = (java.util.Date JavaDoc) Calendar.getInstance().getTime();
193         recordId = currentDateTime.getTime();
194         java.sql.Timestamp JavaDoc logTimestamp = new java.sql.Timestamp JavaDoc(currentDateTime.getTime());
195         String JavaDoc logTimestampStr = logTimestamp.toString();
196
197         try {
198
199             dbStatement.setLong(1, recordId);
200             dbStatement.setString(2, logTimestampStr);
201             anyKindInt = AT.toDB(dbStatement, 4, record);
202
203             dbStatement.setInt(3, anyKindInt);
204
205             int res = dbStatement.executeUpdate();
206         }
207         catch (Exception JavaDoc ex)
208         {
209             System.err.println("** BasicLogImpl: <EXCEPTION> While getting db connection");
210             System.err.println(ex.getMessage());
211             return -1;
212         }
213
214         if ( nv != null && nv.length > 0) {
215             String JavaDoc tblName = logTableName + "NVPairs";
216             boolean tblExists = false;
217
218             try {
219
220                     Statement dbTblCreateStatement = dbConnection.createStatement();
221
222                     ResultSet queryRes = dbTblCreateStatement.executeQuery("SHOW TABLES");
223
224                 while ( queryRes.next() )
225                 {
226                     if ( queryRes.getString(1).equalsIgnoreCase(tblName) ) {
227                         tblExists = true;
228                         break;
229                     }
230                 }
231
232                 if ( ! tblExists ) {
233                     String JavaDoc sqlStr = "CREATE TABLE " + tblName +
234                                 " (logRecordId BIGINT, " +
235                                 "NVPairName VARCHAR(30), " +
236                                 "NVPairValueType TINYINT, " +
237                                 "NVPairValue BLOB)";
238
239                       dbTblCreateStatement.execute(sqlStr);
240                 }
241
242                 dbStatement = dbConnection.prepareStatement(
243                         "INSERT INTO " + tblName +
244                         " (logRecordId, NVPairName, NVPairValueType, NVPairValue)" +
245                         " VALUES(? , ?, ?, ?)" );
246
247                 for(int i = 0; i < nv.length; i++) {
248
249                   dbStatement.setLong(1, recordId);
250
251                   dbStatement.setString(2, nv[i].name);
252                   if ( nv[i].value != null ) {
253                     anyKindInt = AT.toDB(dbStatement, 4, nv[i].value);
254                   }
255                   else {
256                     dbStatement.setString(4, null);
257                   }
258
259                   dbStatement.setInt(3, anyKindInt);
260
261                   int res = dbStatement.executeUpdate();
262                 }
263             }
264             catch (SQLException ex) {
265                     System.err.println("*** basicLogSegImpl : SQLException: " + ex.getMessage());
266                     System.err.println("*** basicLogSegImpl : SQLState: " + ex.getSQLState());
267                     System.err.println("*** basicLogSegImpl : VendorError: " + ex.getErrorCode());
268                     return -1;
269             }
270         }
271         LogNewRecordImpl log_newRecord_event = new LogNewRecordImpl();
272         log_newRecord_event.eventTime = new org.omg.TimeBase.UtcT(System.currentTimeMillis(),
273                     0,(short) 0,(short) 0);
274         try {
275           for(int i = 0; i < nv.length; i++) {
276             if (nv[i].name.equals("Source"))
277               log_newRecord_event.source = Utils.string2name(nv[i].value.extract_string());
278            else
279            if (nv[i].name.equals("SourceClass"))
280               log_newRecord_event.sourceClass = nv[i].value.extract_string();
281            else
282            if (nv[i].name.equals("EventType"))
283               log_newRecord_event.severity = LogSeverity.from_int(nv[i].value.extract_short());
284            else
285               System.err.println("basicLogSegImpl> Unknown NVPair attribute...");
286           }
287           log_newRecord_event.logRecordId = recordId;
288           log_newRecord_event.info = record.extract_string();
289         }
290         catch(Exception JavaDoc e) {
291           System.err.println("basicLogSegImpl>write_record: Problem extracting logRecord data" + e.getMessage());
292           return -1;
293         }
294
295
296         get_context().push_log_newRecord(log_newRecord_event);
297
298         return recordId;
299     }
300
301
302     /**
303      * Implementation of the ::coachEmfServices::EmfBasicLog::Log::id operation.
304      */

305     public int
306     id()
307     {
308         //
309
// DONE : Implement
310
//
311
return get_main_segment().logId();
312     }
313
314    /**
315      * Implementation of the ::coachEmfServices::EmfBasicLog::Log::get_display_name operation.
316      */

317     public String JavaDoc
318     get_display_name() {
319
320       return get_main_segment().display_name();
321     }
322     /**
323      * Implementation of the ::coachEmfServices::EmfBasicLog::Log::get_log_qos operation.
324      */

325     public short[]
326     get_log_qos()
327     {
328         //
329
// TO BE DONE : Implement
330
//
331
return null;
332     }
333
334     /**
335      * Implementation of the ::coachEmfServices::EmfBasicLog::Log::set_log_qos operation.
336      */

337     public void
338     set_log_qos(short[] qos)
339     throws ist.coach.coachEmfServices.EmfBasicLog.UnsupportedQoS
340     {
341         //
342
// TO BE DO : Implement
343
//
344
}
345
346     /**
347      * Implementation of the ::coachEmfServices::EmfBasicLog::Log::get_max_size operation.
348      */

349     public long
350     get_max_size()
351     {
352         //
353
// DONE : Implement
354
//
355
return get_main_segment().logMaxSize();
356     }
357
358     /**
359      * Implementation of the ::coachEmfServices::EmfBasicLog::Log::set_max_size operation.
360      */

361     public void
362     set_max_size(long size)
363     throws ist.coach.coachEmfServices.EmfBasicLog.InvalidParam
364     {
365         //
366
// DONE : Implement
367
//
368
get_main_segment().logMaxSize((int) size);
369     }
370
371     /**
372      * Implementation of the ::coachEmfServices::EmfBasicLog::Log::get_current_size operation.
373      */

374     public long
375     get_current_size()
376     {
377         //
378
// DONE : Implement
379
//
380
long currentSize = 0;
381
382         // Connect to JDBC driver
383
try {
384             Class.forName(get_main_segment().databaseDriver()).newInstance();
385         }
386         catch (Exception JavaDoc ex) {
387             System.err.println("** BasicLogImpl - METHOD 'get_current_size': <EXCEPTION> " +
388                         " While connecting to jdbx driver");
389             System.err.println(ex.getMessage());
390             return currentSize;
391         }
392
393         Connection dbConnection = null;
394         String JavaDoc logTableName = get_main_segment().databaseTable() +
395             Integer.toString(get_main_segment().logId());
396         try {
397                 dbConnection = DriverManager.getConnection(get_main_segment().databaseConnection());
398                 Statement dbTestStatement = dbConnection.createStatement();
399                 ResultSet dbTestResults = dbTestStatement.executeQuery("SHOW TABLE STATUS");
400
401             while (dbTestResults.next()) {
402                 if ( dbTestResults.getString(1).equalsIgnoreCase(logTableName) ) {
403                     currentSize = dbTestResults.getLong(6);
404                     break;
405                 }
406             }
407         }
408         catch (Exception JavaDoc ex) {
409             System.err.println("** BasicLogImpl - METHOD 'get_current_size': <EXCEPTION> " +
410                         " While connecting to jdbx driver");
411             System.err.println(ex.getMessage());
412         }
413
414         return currentSize ;
415     }
416
417     /**
418      * Implementation of the ::coachEmfServices::EmfBasicLog::Log::get_n_records operation.
419      */

420     public long
421     get_n_records()
422     {
423         //
424
// DONE : Implement
425
//
426
long numOfRecords = 0;
427
428         // Connect to JDBC driver
429
try {
430             Class.forName(get_main_segment().databaseDriver()).newInstance();
431         }
432         catch (Exception JavaDoc ex) {
433             System.err.println("** BasicLogImpl - METHOD 'get_current_size': <EXCEPTION> " +
434                         " While connecting to jdbx driver");
435             System.err.println(ex.getMessage());
436             return -1;
437         }
438
439         Connection dbConnection = null;
440         String JavaDoc logTableName = get_main_segment().databaseTable() +
441             Integer.toString(get_main_segment().logId());
442         try {
443             dbConnection = DriverManager.getConnection(get_main_segment().databaseConnection());
444             Statement dbTestStatement = dbConnection.createStatement();
445             ResultSet dbTestResults = dbTestStatement.executeQuery("SHOW TABLE STATUS");
446
447             while (dbTestResults.next()) {
448                 if ( dbTestResults.getString(1).equalsIgnoreCase(logTableName) ) {
449                     numOfRecords = dbTestResults.getLong(4);
450                     break;
451                 }
452             }
453         }
454         catch (Exception JavaDoc ex) {
455             System.err.println("** BasicLogImpl - METHOD 'get_current_size': <EXCEPTION> " +
456                         " While connecting to jdbx driver");
457             System.err.println(ex.getMessage());
458             return -1;
459         }
460
461         return numOfRecords ;
462
463     }
464
465     /**
466      * Implementation of the ::coachEmfServices::EmfBasicLog::Log::get_log_full_action operation.
467      */

468     public short
469     get_log_full_action()
470     {
471         //
472
// DONE : Implement
473
//
474
return get_main_segment().logFullAction();
475     }
476
477     /**
478      * Implementation of the ::coachEmfServices::EmfBasicLog::Log::set_log_full_action operation.
479      */

480     public void
481     set_log_full_action(short action)
482     throws ist.coach.coachEmfServices.EmfBasicLog.InvalidLogFullAction
483     {
484         //
485
// DONE : Implement
486
//
487
if (action > 1)
488           throw new InvalidLogFullAction();
489
490         get_main_segment().logFullAction(action);
491     }
492
493     /**
494      * Implementation of the ::coachEmfServices::EmfBasicLog::Log::get_administrative_state operation.
495      */

496     public ist.coach.coachEmfServices.EmfBasicLog.AdministrativeState
497     get_administrative_state()
498     {
499         //
500
// DONE : Implement
501
//
502
AdministrativeState adState;
503
504         if ( logLocked_ ) {
505             adState = AdministrativeState.locked;
506         }
507         else {
508             adState = AdministrativeState.unlocked;
509         }
510
511         return adState;
512
513     }
514
515     /**
516      * Implementation of the ::coachEmfServices::EmfBasicLog::Log::set_administrative_state operation.
517      */

518     public void
519     set_administrative_state(ist.coach.coachEmfServices.EmfBasicLog.AdministrativeState admin_state)
520     {
521         //
522
// DONE : Implement
523
//
524
if ( admin_state.value() == 0 )
525             logLocked_ = true;
526         else
527             logLocked_ = false;
528       }
529
530     /**
531      * Implementation of the ::coachEmfServices::EmfBasicLog::Log::get_operational_state operation.
532      */

533     public ist.coach.coachEmfServices.EmfBasicLog.OperationalState
534     get_operational_state()
535     {
536         //
537
// DONE : Implement
538
//
539

540         OperationalState opState;
541
542         if ( logDisabled_ ) {
543             opState = OperationalState.disabled;
544         }
545         else {
546             opState= OperationalState.enabled;
547         }
548
549         return opState;
550
551     }
552
553     /**
554      * Implementation of the ::coachEmfServices::EmfBasicLog::Log::get_capacity_alarm_thresholds operation.
555      */

556     public short[]
557     get_capacity_alarm_thresholds()
558     {
559         //
560
// TO BE DO : Implement
561
//
562
return null;
563     }
564
565     /**
566      * Implementation of the ::coachEmfServices::EmfBasicLog::Log::set_capacity_alarm_thresholds operation.
567      */

568     public void
569     set_capacity_alarm_thresholds(short[] threshs)
570     throws ist.coach.coachEmfServices.EmfBasicLog.InvalidThreshold
571     {
572         //
573
// TO BE DO : Implement
574
//
575
}
576
577     /**
578      * Implementation of the ::coachEmfServices::EmfBasicLog::Log::retrieve operation.
579      */

580     public ist.coach.coachEmfServices.EmfBasicLog.LogRecord[]
581     retrieve(long from_time, int how_many, ist.coach.coachEmfServices.EmfBasicLog.IteratorHolder iterRef)
582     {
583         //
584
// DONE : Implement
585
//
586
LogRecord[] logRecords = new LogRecord[0];
587         LogRecord[] tmpLgRecs = new LogRecord[0];
588
589
590         // Extract the timestamp from the time parameter
591
java.sql.Timestamp JavaDoc from_timeTS= new java.sql.Timestamp JavaDoc(from_time);
592         //System.err.println("timestamp = " + from_timeTS + " (" + from_time + ")");
593
String JavaDoc from_timeTSstr = from_timeTS.toString();
594         //System.err.println("timestamp string = " + from_timeTSstr);
595

596         String JavaDoc logTableName = get_main_segment().databaseTable() +
597             Integer.toString(get_main_segment().logId());
598
599         Connection dbConnection = null;
600         String JavaDoc NVPairTableName = logTableName + "NVPairs";
601         NVPair[] tmpAttrList = null;
602         Statement dbStatement = null;
603         boolean tblExists = false;
604         int rowsFetched = 0;
605         String JavaDoc sqlStmnt = "";
606
607         // Connect to JDBC driver and check if there is an associated NVPair table
608
try {
609             // Connect to JDBC driver and to the database
610
Class.forName(get_main_segment().databaseDriver()).newInstance();
611             dbConnection = DriverManager.getConnection(get_main_segment().databaseConnection());
612             dbStatement = dbConnection.createStatement();
613
614             // Check if there is an associated NVPair table
615
ResultSet queryRes = dbStatement.executeQuery("SHOW TABLES");
616
617             while ( queryRes.next() ) {
618                 if ( queryRes.getString(1).equalsIgnoreCase(NVPairTableName) ) {
619                     tblExists = true;
620                     break;
621                 }
622             }
623
624             sqlStmnt = "SELECT * FROM " + logTableName +
625                     " WHERE timeStamp >= '" + from_timeTSstr +"'";
626
627             queryRes = dbStatement.executeQuery(sqlStmnt);
628
629             while ( queryRes.next() ) {
630                   // if clause added by fset
631
if (rowsFetched == how_many)
632                   break;
633                 rowsFetched++;
634             }
635
636             queryRes.beforeFirst();
637
638             AnyTypeTrans AT = new AnyTypeTrans();
639             tmpLgRecs = new LogRecord[rowsFetched];
640
641             int i = 0;
642             String JavaDoc tmpTimeStamp;
643             ResultSet queryResFrmAsTbl;
644
645
646             while ( queryRes.next() && i < rowsFetched ) {
647                 tmpLgRecs[i]= new LogRecord();
648
649                 tmpLgRecs[i].id = queryRes.getLong(1);
650
651                 tmpTimeStamp = queryRes.getString(2);
652                 java.sql.Timestamp JavaDoc tS = java.sql.Timestamp.valueOf(tmpTimeStamp);
653                 long timeLong = tS.getTime();
654                 tmpLgRecs[i].time = timeLong;
655
656                 tmpLgRecs[i].attr_list = null;
657
658                 int anyKindInt = queryRes.getInt(3);
659                 tmpLgRecs[i].info = AT.fromDB(queryRes, anyKindInt, 4);
660
661                 i++;
662             }
663
664             if ( tblExists ) {
665                 for (i=0; i < tmpLgRecs.length; i++) {
666                     // retrieve all NVPairs from associated table
667
sqlStmnt = "SELECT * FROM " + NVPairTableName +
668                             " WHERE logRecordId=" + tmpLgRecs[i].id;
669                     queryResFrmAsTbl = dbStatement.executeQuery(sqlStmnt);
670
671                     int n = 0;
672                     while ( queryResFrmAsTbl.next() ) {
673                         n++;
674                     }
675
676                     queryResFrmAsTbl.beforeFirst();
677                     if ( n != 0 ) {
678                         tmpAttrList = new NVPair[n];
679                     }
680                     n = 0;
681
682                     while ( queryResFrmAsTbl.next() ) {
683
684                         tmpAttrList[n] = new NVPair();
685
686                         tmpAttrList[n].name = queryResFrmAsTbl.getString(2);
687                         int m = queryResFrmAsTbl.getInt(3);
688
689                         tmpAttrList[n].value = AT.fromDB(queryResFrmAsTbl, m, 4);
690                         n++;
691                     }
692
693                     if ( n != 0 ) {
694
695                         tmpLgRecs[i].attr_list = tmpAttrList;
696                     }
697                 }
698             }
699             // If the fetched records from the database is
700
// greater than the indicated threshold then instantiate
701
// an Iterator and assigned all data to be fetched via
702
// the Iterator interface. Otherwise, Iterator interface
703
// will be null and all the records will be returned by
704
// the present method.
705

706             //System.err.println( "*** BasicLogImpl : <1> > rowsFetched= " + rowsFetched);
707
int numOfRecsRorIterator_ = get_main_segment().recordsReadRange();
708             if ( rowsFetched != 0 ) {
709
710                 if (rowsFetched > numOfRecsRorIterator_) {
711                   System.err.println( "*** BasicLogImpl : <2> > Iterator CASE" );
712
713                   IteratorImpl iteratorSrv = null;
714
715                   try {
716                    iteratorSrv = new IteratorImpl();
717                    }
718                    catch ( Exception JavaDoc ex ) {
719                       System.err.println( "*** BasicLogImpl : <EXCEPTION> " +
720                                     " While trying to instantiate IteratorImpl() " +
721                                       ex.getMessage());
722                       ex.printStackTrace();
723                     }
724
725                     iterRef.value = iteratorSrv._this(org.objectweb.ccm.CORBA.TheORB.getORB());
726
727                     iteratorSrv.logRecords(tmpLgRecs);
728
729                     iteratorSrv.logRecordsSize(iteratorSrv.logRecords().length);
730
731                     logRecords = new LogRecord[numOfRecsRorIterator_];
732                     for (int j = 0; j < numOfRecsRorIterator_ ; j++) {
733                         logRecords[j] = tmpLgRecs[j];
734                     }
735                 }
736                 else {
737                     logRecords = new LogRecord[tmpLgRecs.length];
738                     logRecords = tmpLgRecs;
739                     iterRef.value = null;
740                 }
741             }
742         }
743         catch (Exception JavaDoc ex) {
744             System.err.println("** BasicLogImpl - METHOD 'retrieve': <EXCEPTION> ");
745             System.err.println(ex.getMessage());
746         }
747
748         return logRecords;
749
750     }
751
752     /**
753      * Implementation of the ::coachEmfServices::EmfBasicLog::Log::delete_records_by_id operation.
754      */

755     public int
756     delete_records_by_id(long[] ids)
757     {
758         //
759
// DONE : Implement
760
//
761
int numOfRecsDeleted = 0;
762
763         // Connect to JDBC driver
764
try {
765             Class.forName(get_main_segment().databaseDriver()).newInstance();
766             }
767         catch (Exception JavaDoc ex) {
768             System.out.println("** BasicLogImpl - METHOD 'delete_records_by_id': <EXCEPTION> " +
769                         "While connecting to jdbx driver");
770             System.out.println(ex.getMessage());
771             return -1;
772             }
773
774         Connection dbConnection = null;
775         try {
776             dbConnection = DriverManager.getConnection(get_main_segment().databaseConnection());
777             }
778         catch (Exception JavaDoc ex) {
779             System.out.println("** BasicLogImpl - METHOD 'delete_records_by_id': <EXCEPTION> " +
780                         "While getting db connection");
781             System.out.println(ex.getMessage());
782             return -1;
783         }
784         String JavaDoc logTableName = get_main_segment().databaseTable() +
785             Integer.toString(get_main_segment().logId());
786
787         String JavaDoc NVPairTableName = logTableName + "NVPairs";
788         boolean tblExists = false;
789         Statement dbDeleteStatement = null;
790
791         // Check if there is an associated NVPair table
792
try {
793             dbDeleteStatement = dbConnection.createStatement();
794             ResultSet queryRes = dbDeleteStatement.executeQuery("SHOW TABLES");
795             while ( queryRes.next() ) {
796                 if ( queryRes.getString(1).equalsIgnoreCase(NVPairTableName) ) {
797                     tblExists = true;
798                     break;
799                 }
800             }
801         }
802         catch (Exception JavaDoc ex) {
803             System.err.println("** BasicLogImpl - METHOD 'delete_records_by_id': <EXCEPTION> " +
804                         "While getting db connection");
805             System.err.println(ex.getMessage());
806             return -1;
807         }
808
809         // Delete all records specified (by their record id) from the main
810
// table and if there exists an associated NVPair table, delete the
811
// associated records.
812
for (int i = 0; i < ids.length; i++) {
813             try {
814                 String JavaDoc sqlStmnt = "DELETE FROM " + logTableName +
815                             " WHERE logRecordId = " + ids[i];
816                 boolean dbDeleteResults = dbDeleteStatement.execute(sqlStmnt);
817                 numOfRecsDeleted++;
818
819                 if ( tblExists ) {
820
821                     sqlStmnt = "DELETE FROM " + NVPairTableName +
822                             " WHERE logRecordId = " + ids[i];
823                         dbDeleteResults = dbDeleteStatement.execute(sqlStmnt);
824                 }
825
826             }
827             catch (Exception JavaDoc ex) {
828                 System.err.println("** BasicLogImpl - METHOD 'delete_records_by_id': <EXCEPTION> " +
829                             "While deleting record");
830                 System.err.println(ex.getMessage());
831
832             }
833         }
834
835         return numOfRecsDeleted;
836
837     }
838
839     /**
840      * Implementation of the ::coachEmfServices::EmfBasicLog::Log::write_records operation.
841      */

842     public void
843     write_records(org.omg.CORBA.Any JavaDoc[] records)
844     throws ist.coach.coachEmfServices.EmfBasicLog.LogFull,
845            ist.coach.coachEmfServices.EmfBasicLog.LogOffDuty,
846            ist.coach.coachEmfServices.EmfBasicLog.LogLocked,
847            ist.coach.coachEmfServices.EmfBasicLog.LogDisabled
848     {
849         //
850
// DONE : Implement
851
//
852
// Perform tests for empty input, LogOffDuty, LogLocked, LogDisabled
853

854         if (records.length == 0)
855             return;
856
857         if ( logOffDuty_ )
858             throw new LogOffDuty();
859
860         if ( logLocked_ )
861             throw new LogLocked();
862
863         if ( logDisabled_ ) {
864             throw new LogDisabled();
865         }
866
867
868         // Connect to JDBC driver
869
try
870         {
871             Class.forName(get_main_segment().databaseDriver()).newInstance();
872         }
873         catch (Exception JavaDoc ex) {
874             System.err.println("** BasicLogImpl: <EXCEPTION> While connecting to jdbc driver");
875             System.err.println(ex.getMessage());
876             return;
877         }
878
879         Connection dbConnection = null;
880         String JavaDoc logTableName = get_main_segment().databaseTable() +
881             Integer.toString(get_main_segment().logId());
882         // Perform test for LogFull
883

884         try
885         {
886             dbConnection = DriverManager.getConnection(get_main_segment().databaseConnection());
887             Statement dbTestStatement = dbConnection.createStatement();
888             ResultSet dbTestResults = dbTestStatement.executeQuery("SHOW TABLE STATUS");
889
890             while (dbTestResults.next()) {
891                 if ( dbTestResults.getString(1).equalsIgnoreCase(logTableName) ) {
892                     long avgRowLength = dbTestResults.getLong(5);
893                     long dataLength = dbTestResults.getLong(6);
894                     long maxDataLength = dbTestResults.getLong(7);
895                     dbTableMaxSize_ = maxDataLength;
896                     short numOfRows = dbTestResults.getShort(4);
897
898                     if ( maxDataLength <= (dataLength + avgRowLength) )
899                             throw new LogFull(numOfRows);;
900
901                 }
902             }
903         }
904         catch (Exception JavaDoc ex) {
905             System.err.println("** BasicLogImpl: <EXCEPTION> While connecting to jdbx driver");
906             System.err.println(ex.getMessage());
907             return;
908         }
909
910         PreparedStatement dbStatement = null;
911
912         try {
913
914             dbConnection = DriverManager.getConnection(get_main_segment().databaseConnection());
915
916             dbStatement = dbConnection.prepareStatement(
917                           "INSERT INTO " + logTableName +
918                           " (logRecordId, timeStamp, logDataType, logData)" +
919                         " VALUES(? , ?, ?, ?)"
920               );
921       }
922       catch (Exception JavaDoc ex) {
923             System.err.println("** BasicLogImpl: <EXCEPTION> While getting db connection");
924             System.err.println(ex.getMessage());
925             return;
926       }
927
928       AnyTypeTrans AT = new AnyTypeTrans();
929
930         // For all the received events extract the information based on the
931
// 'LogRecord'(defined in Log.idl) and stored it in the given log
932
// database and table.
933

934       int anyKindInt = -1;
935       long prevRecId = 0;
936
937       for (int i = 0; i < records.length; i++) {
938
939             Any JavaDoc receivedLogInfo = records[i];
940
941             // Create timestamp
942
java.util.Date JavaDoc currentDateTime = (java.util.Date JavaDoc) Calendar.getInstance().getTime();
943             long recordId = currentDateTime.getTime();
944             java.sql.Timestamp JavaDoc logTimestamp = new java.sql.Timestamp JavaDoc(currentDateTime.getTime());
945             String JavaDoc logTimestampStr = logTimestamp.toString();
946
947             try {
948                 if ( (new Long JavaDoc(recordId)).compareTo(new Long JavaDoc(prevRecId))== 0 ) {
949                     recordId++;
950                 }
951                 prevRecId = recordId;
952
953                 dbStatement.setLong(1, recordId);
954                 dbStatement.setString(2, logTimestampStr);
955                 if ( records[i] != null ) {
956                     anyKindInt = AT.toDB(dbStatement, 4, records[i]);
957                 }
958                 else {
959                     dbStatement.setString(4, null);
960                 }
961
962                 dbStatement.setInt(3, anyKindInt);
963
964                 int res = dbStatement.executeUpdate();
965             }
966             catch (Exception JavaDoc ex){
967                 System.err.println("** BasicLogImpl: <EXCEPTION> While getting db connection");
968                 System.err.println(ex.getMessage());
969                 return;
970             }
971       } // End of 'loop' For all received events
972

973     }
974
975     /**
976      * Implementation of the ::coachEmfServices::EmfBasicLog::Log::set_record_attribute operation.
977      */

978     public void
979     set_record_attribute(long id, ist.coach.coachEmfServices.EmfBasicLog.NVPair[] attr_list)
980     throws ist.coach.coachEmfServices.EmfBasicLog.InvalidRecordId,
981          ist.coach.coachEmfServices.EmfBasicLog.InvalidAttribute
982     {
983         //
984
// DONE : Implement
985
//
986
// In case the record ID is 0 throw an exception
987
if ( (new Long JavaDoc(id)).compareTo(new Long JavaDoc(0)) == 0 ) {
988             InvalidRecordId ex_InvalidRecordId = new InvalidRecordId();
989             throw ex_InvalidRecordId;
990         }
991
992         // In the case the NVPair list of parameters has no values, or in
993
// the case the values are either null or invalid (for the any case)
994
// throw an exception.
995

996         if ( attr_list.length == 0 ) {
997
998             InvalidAttribute ex_InvalidAttribute = new InvalidAttribute();
999             ex_InvalidAttribute.attr_name = null;
1000            ex_InvalidAttribute.value = null;
1001            throw ex_InvalidAttribute;
1002        }
1003        else {
1004
1005            for (int i = 0; i < attr_list.length; i++) {
1006
1007                if ( (attr_list[i].name).length() == 0 ) {
1008                    InvalidAttribute ex_InvalidAttribute = new InvalidAttribute();
1009                    ex_InvalidAttribute.attr_name = attr_list[i].name;
1010                    ex_InvalidAttribute.value = attr_list[i].value;
1011                    throw ex_InvalidAttribute;
1012                }
1013                else {
1014                    CheckAnyValueValidity chkVal = new CheckAnyValueValidity();
1015                    if ( !chkVal.checkAny(attr_list[i].value) ){
1016                        InvalidAttribute ex_InvalidAttribute = new InvalidAttribute();
1017                        ex_InvalidAttribute.attr_name = attr_list[i].name;
1018                        ex_InvalidAttribute.value = attr_list[i].value;
1019                        throw ex_InvalidAttribute;
1020                    }
1021                }
1022            }
1023        }
1024
1025        Connection dbConnection = null;
1026        String JavaDoc logTableName = get_main_segment().databaseTable() +
1027            Integer.toString(get_main_segment().logId());
1028        String JavaDoc NVPairTableName = logTableName + "NVPairs";
1029        boolean tblExists = false;
1030
1031        Statement dbStatement = null;
1032
1033        // Connect to JDBC driver and check if there is an associated NVPair table
1034
try {
1035            Class.forName(get_main_segment().databaseDriver()).newInstance();
1036            dbConnection = DriverManager.getConnection(get_main_segment().databaseConnection());
1037
1038            dbStatement = dbConnection.createStatement();
1039            ResultSet queryRes = dbStatement.executeQuery("SHOW TABLES");
1040            while ( queryRes.next() ) {
1041                if ( queryRes.getString(1).equalsIgnoreCase(NVPairTableName) ) {
1042                    tblExists = true;
1043                    break;
1044                }
1045            }
1046        }
1047        catch (Exception JavaDoc ex) {
1048            System.err.println("** BasicLogImpl - METHOD 'set_record_attribute': <EXCEPTION> ");
1049            System.err.println(ex.getMessage());
1050            return;
1051        }
1052
1053        // If associated table exists, delete all records associated in NVPair
1054
// with the given rtecord id. If associated table does not exist create one.
1055
if ( tblExists ) {
1056            try {
1057                String JavaDoc sqlStmnt = "DELETE FROM " + NVPairTableName +
1058                            " WHERE logRecordId = " + id;
1059                    boolean dbDeleteResults = dbStatement.execute(sqlStmnt);
1060            }
1061            catch (Exception JavaDoc ex) {
1062                System.err.println("** BasicLogImpl - METHOD 'set_record_attribute': <EXCEPTION> " +
1063                            "While deleting records from the associated NVPair table");
1064
1065                System.err.println(ex.getMessage());
1066                return;
1067            }
1068        }
1069        else {
1070            String JavaDoc sqlStmnt = "CREATE TABLE " + NVPairTableName +
1071                        " (logRecordId BIGINT, " +
1072                        "NVPairName VARCHAR(30), " +
1073                        "NVPairValueType TINYINT, " +
1074                        "NVPairValue BLOB)";
1075            try {
1076                    boolean tblCreatedInDb = dbStatement.execute(sqlStmnt);
1077            }
1078            catch (Exception JavaDoc ex) {
1079                System.err.println("** BasicLogImpl - METHOD 'set_record_attribute': <EXCEPTION> " +
1080                            "While creating associated NVPair table");
1081
1082                System.err.println(ex.getMessage());
1083                return;
1084            }
1085        }
1086
1087
1088            try {
1089                PreparedStatement dbStatement2 = dbConnection.prepareStatement(
1090                            "INSERT INTO " + NVPairTableName +
1091                            " (logRecordId, NVPairName, NVPairValueType, NVPairValue)" +
1092                            " VALUES(? , ?, ?, ?)" );
1093
1094                AnyTypeTrans AT = new AnyTypeTrans();
1095
1096                for (int i = 0; i < attr_list.length; i++) {
1097
1098                    dbStatement2.setLong(1, id);
1099                    dbStatement2.setString(2, attr_list[i].name);
1100                    int anyKindInt = AT.toDB(dbStatement2, 4, attr_list[i].value);
1101                    dbStatement2.setInt(3, anyKindInt);
1102                    int res = dbStatement2.executeUpdate();
1103                }
1104            }
1105            catch (Exception JavaDoc ex) {
1106                System.err.println("** BasicLogImpl - METHOD 'set_record_attribute': <EXCEPTION> " +
1107                            "While setting the attributes in the associated NVPair table");
1108                System.err.println(ex.getMessage());
1109            }
1110
1111
1112    }
1113
1114    /**
1115     * Implementation of the ::coachEmfServices::EmfBasicLog::Log::get_record_attribute operation.
1116     */

1117    public ist.coach.coachEmfServices.EmfBasicLog.NVPair[]
1118    get_record_attribute(long id)
1119    throws ist.coach.coachEmfServices.EmfBasicLog.InvalidRecordId
1120    {
1121        //
1122
// DONE : Implement
1123
//
1124
// In case the record ID is 0 throw an exception
1125
if ( (new Long JavaDoc(id)).compareTo(new Long JavaDoc(0)) == 0 ) {
1126            InvalidRecordId ex_InvalidRecordId = new InvalidRecordId();
1127            throw ex_InvalidRecordId;
1128        }
1129        String JavaDoc logTableName = get_main_segment().databaseTable() +
1130            Integer.toString(get_main_segment().logId());
1131        Connection dbConnection = null;
1132        String JavaDoc NVPairTableName = logTableName + "NVPairs";
1133        NVPair[] attrList = null;
1134        Statement dbStatement = null;
1135        boolean tblExists = false;
1136        String JavaDoc sqlStmnt = "";
1137
1138        // Connect to JDBC driver and check if there is an associated NVPair table
1139
try {
1140            // Connect to JDBC driver and to the database
1141
Class.forName(get_main_segment().databaseDriver()).newInstance();
1142            dbConnection = DriverManager.getConnection(get_main_segment().databaseConnection());
1143            dbStatement = dbConnection.createStatement();
1144
1145            // Check if there is an associated NVPair table
1146
ResultSet queryRes = dbStatement.executeQuery("SHOW TABLES");
1147            while ( queryRes.next() ) {
1148                if ( queryRes.getString(1).equalsIgnoreCase(NVPairTableName) ) {
1149                    tblExists = true;
1150                    break;
1151                }
1152            }
1153
1154            // if there is an associated NVPair table extract all NVPairs
1155
if ( tblExists ) {
1156                sqlStmnt = "SELECT * FROM " + NVPairTableName +
1157                            " WHERE logRecordId=" + id;
1158                queryRes = dbStatement.executeQuery(sqlStmnt);
1159
1160                int rowsFetched = 0;
1161                while ( queryRes.next() ) {
1162                    rowsFetched++;
1163                }
1164
1165                attrList = new NVPair[rowsFetched];
1166
1167                AnyTypeTrans AT = new AnyTypeTrans();
1168                int i = 0;
1169
1170                queryRes.beforeFirst();
1171                while ( queryRes.next() ) {
1172                    attrList[i] = new NVPair();
1173                    attrList[i].name = queryRes.getString(2);
1174                    int anyKindInt = queryRes.getInt(3);
1175                    attrList[i].value = AT.fromDB(queryRes, anyKindInt, 4);
1176                }
1177            }
1178        }
1179        catch (Exception JavaDoc ex) {
1180            System.err.println("** BasicLogImpl - METHOD 'get_record_attribute': <EXCEPTION> ");
1181            System.err.println(ex.getMessage());
1182        }
1183
1184        return attrList;
1185    }
1186
1187    /**
1188     * Implementation of the ::coachEmfServices::EmfBasicLog::Log::flush operation.
1189     */

1190    public void
1191    flush()
1192    throws ist.coach.coachEmfServices.EmfBasicLog.UnsupportedQoS
1193    {
1194        //
1195
// TODO : Implement
1196
//
1197
System.err.println("basicLogSeqImpl> Flush is called!!");
1198    }
1199
1200}
1201
Popular Tags