Report problems to ATLAS LXR Team (with time and IP address indicated)

The LXR Cross Referencer

source navigation ]
diff markup ]
identifier search ]
general search ]
 
 
Architecture: linux ]
Version: head ] [ nightly ] [ GaudiDev ]
  Links to LXR source navigation pages for stable releases [ 12.*.* ]   [ 13.*.* ]   [ 14.*.* ] 

001 package triggertool.Components;
002 
003 import java.io.BufferedReader;
004 import java.io.File;
005 import java.io.FileWriter;
006 import java.io.FileInputStream;
007 import java.io.FileNotFoundException;
008 import java.io.IOException;
009 import java.io.InputStream;
010 import java.io.InputStreamReader;
011 import java.sql.Clob;
012 import java.sql.Connection;
013 import java.sql.DriverManager;
014 import java.sql.PreparedStatement;
015 import java.sql.ResultSet;
016 import java.sql.SQLException;
017 import java.sql.Statement;
018 import java.util.regex.*;
019 import java.util.Collections;
020 import java.util.Iterator;
021 import java.util.TreeMap;
022 import java.util.Vector;
023 import java.util.logging.Logger;
024 import java.net.URL;
025 import javax.swing.JOptionPane;
026 import javax.xml.parsers.DocumentBuilder;
027 import javax.xml.parsers.DocumentBuilderFactory;
028 import oracle.jdbc.OracleConnection;
029 import org.w3c.dom.Document;
030 import org.w3c.dom.Element;
031 import org.w3c.dom.NodeList;
032 
033 ///Handles the connection to the Trigger Database.
034 /**
035  * The new, reduced ConnectionManager class.  Deals with the database connection.
036  * For example the difference between Oracle, MySQL, SQLite.  Also takes care
037  * of the ATONR connection, and the differences between dealing with that and 
038  * a normal conenction.  e.g. user access restrictions.
039  * 
040  * @author Simon Head
041  */
042 public class ConnectionManager {
043 
044     ///Version numbers of the trigger tool.  Major and Minor.
045     public static int TT_MAJOR = 1;
046     /** Minor version number of the trigger tool */
047     public static int TT_MINOR = 34;
048     /** Schema that this version of the TriggerTool requires.  Held in trigger_schema table, as the id */
049     public static int SCHEMA_VERSION = 8;
050     ///Message Log.
051     private static Logger logger = Logger.getLogger(ConnectionManager.class.getName());
052     /** Singleton pointer */
053     private static ConnectionManager connMa = null;
054     ///Login screen.
055     public InitDialog theInitDialog;
056     ///We need to keep a copy of the InitInfo.
057     private InitInfo savedInitInfo;
058     ///Path for logging and TMC files.
059     private String log_path;
060     ///Connection is made when the user logs in, then used whenever we call an SQL command.
061     private Connection conn;
062     ///Statement.
063     private PreparedStatement stmt;
064     ///If we're doing a dbCopy and writing, change this to true.
065     private boolean doDBCopy = false;
066     ///Combined with doDBCopy, this is the connection to write to.
067     ///Not currently used since for DBCopy2 we just change the main connection.
068     private Connection copy_to_connection = null;
069 
070      /**
071      * This registers the additional JAR packages we need to
072      * talk to the database(s) using Oracle, MySQL and SQLite
073      */
074     public ConnectionManager() {
075         try {
076             Class.forName("com.mysql.jdbc.Driver").newInstance();
077         } catch (Exception e) {
078             logger.severe("Error loading MySQL driver");
079             e.printStackTrace();
080         }
081 
082         try {
083             DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
084         } catch (SQLException e) {
085             logger.severe("Error loading Oracle driver");
086             e.printStackTrace();
087         }
088 
089         try {
090             Class.forName("org.sqlite.JDBC").newInstance();
091         } catch (Exception e) {
092             logger.severe("Error loading SQLite driver");
093             e.printStackTrace();
094         }
095 
096         log_path = System.getenv("TRIGGERTOOL_LOGDIRECTORY");
097 
098         if (log_path == null) {
099             log_path = "";
100         } else if (log_path.lastIndexOf("/") != log_path.length() - 1) {
101             log_path += "/";
102         }
103     }
104 
105        /**
106      * Form a connection to the relevant database
107      * At the moment this can connect to MySQL, Oracle and a SQLite file
108      * Also stores a copy of the initialisation information in savedInitInfo
109      * 
110      * Does a lot of tricky things on atonr, including looking up a user's 
111      * access level and signing in as either the read only or write account
112      * based on its findings.
113      *
114      * @param theInitInfo Object that contains the start-up information
115      * @return true if the connection was made ok
116      */
117     public boolean connect(InitInfo theInitInfo) throws SQLException {
118         savedInitInfo = theInitInfo;
119         String username = theInitInfo.getUserName();
120         String password = theInitInfo.getPassWord();
121         String tablename = theInitInfo.getTableName();
122         String hostname = theInitInfo.getdbServer();
123         String dbtechnology = theInitInfo.getdbTechnology();
124         String filename = theInitInfo.getFilename();
125 
126         //System.out.println("filename here is " + filename);
127         
128         // first check if dblookup and authentication have to be used
129         if ((dbtechnology.equals("SQLite")&&filename.equals(""))||              
130             (((dbtechnology.equals("MySQL"))||(dbtechnology.equals("Oracle")))&&(password.equals("") && username.equals("")))) { 
131             // need to authenticate using authentication.xml
132 
133             String svcName = "";
134             File f = null;
135 
136             // first build a xml file parser
137             DocumentBuilder parser = null;
138             try {
139                 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
140                 factory.setIgnoringComments(true);
141                 factory.setCoalescing(true);
142                 factory.setNamespaceAware(false);
143                 factory.setValidating(false);
144                 parser = factory.newDocumentBuilder();
145             } catch (Exception e) {
146                 System.out.println("Problems building document parser " + e.getMessage());
147                 return false;
148             }
149 
150             if (!dbtechnology.equals("Oracle") &&
151                 !dbtechnology.equals("MySQL") &&
152                 !dbtechnology.equals("SQLite")) { // need to lookup using dblookup.xml
153 
154                 String alias = hostname;
155                 logger.fine("TriggerTool is using dblookup on alias " + alias + " to find the connection parameter");
156                 String coral_dblookup_path = System.getenv("CORAL_DBLOOKUP_PATH");
157 
158                 Vector<File> dbLUfiles = new Vector<File>();
159 
160                 f = new File("./dblookup.xml");
161                 if (f.exists()) {
162                     dbLUfiles.addElement(f);
163                 }
164                 f = new File(coral_dblookup_path + "/dblookup.xml");
165                 if (f.exists()) {
166                     dbLUfiles.addElement(f);
167                 }
168                 if (dbLUfiles.isEmpty()) {
169                     System.out.println("No dblookup file, neither locally nor in '" + coral_dblookup_path + "'");
170                     return false;
171                 }
172 
173                 // look in each file (one or two) to find the first
174                 // occurance of the alias and take the first instance of
175                 // service (this is also the behavior of CORAL, so we do
176                 // the same here)
177                 Element lookedUp = null;
178                 Iterator<File> fIt = dbLUfiles.iterator();
179                 while (fIt.hasNext()) {
180                     f = fIt.next();
181                     try {
182                         // first get the xml document from the file
183                         Document document = parser.parse(f);
184                         // then get all the locical services
185                         NodeList lservices = document.getElementsByTagName("logicalservice");
186                         // and find ours
187                         for (int i = 0; i < lservices.getLength(); i++) {
188                             if (((Element) lservices.item(i)).getAttribute("name").equals(alias)) {
189                                 Element lservice = (Element) lservices.item(i);
190                                 lookedUp = (Element) lservice.getElementsByTagName("service").item(0);
191                                 break;
192                             }
193                         }
194                     } catch (Exception e) {
195                         System.out.println("Problems in file " + f.getPath() + "/" + f.getName() + ": " + e.getMessage());
196                     }
197                     if (lookedUp != null) {
198                         break;
199                     }
200                 }
201                 if (lookedUp == null) {
202                     System.out.println("Could not find alias " + alias + " in any of the dblookup files!");
203                     return false;
204                 }
205                 svcName = lookedUp.getAttribute("name");
206                 String connectionSt = lookedUp.getAttribute("name");
207                 Pattern p = Pattern.compile("(\\w+)://(\\w+?)/(\\w+)");
208                 Matcher m = p.matcher(connectionSt);
209                 if (m.find()) {
210                     dbtechnology = m.group(1);
211                     hostname = m.group(2).toLowerCase();
212                     tablename = m.group(3);
213                     if (dbtechnology.toLowerCase().equals("oracle")) {
214                         dbtechnology = "Oracle";
215                     }
216                     if (dbtechnology.toLowerCase().equals("mysql")) {
217                         dbtechnology = "MySQL";
218                     }
219                     if (dbtechnology.toLowerCase().equals("sqlite")) {
220                         dbtechnology = "SQLite";
221                     }
222                 } else {
223                     System.out.println("Connection " + svcName + " does not match pattern 'techno://server/schema'");
224                 }
225             } else {
226                 // a technology is given, put the connection together for authentication
227                 svcName = dbtechnology.toLowerCase() + "://" + hostname + "/" + tablename;
228             }
229 
230             logger.fine("TriggerTool is using authentication on connection " + svcName + " to find account name and password");
231             String coral_auth_path = System.getenv("CORAL_AUTH_PATH");
232             Vector<File> dbAuthfiles = new Vector<File>();
233             f = new File("./authentication.xml");
234             if (f.exists()) {
235                 dbAuthfiles.addElement(f);
236             }
237             f = new File(coral_auth_path + "/authentication.xml");
238             if (f.exists()) {
239                 dbAuthfiles.addElement(f);
240             }
241             if (dbAuthfiles.isEmpty()) {
242                 System.out.println("No authentication file, neither locally nor in '" + coral_auth_path + "'");
243                 return false;
244             }
245 
246 
247             // look in each file (one or two) to find the first
248             // occurance of the alias and take the first instance of
249             // service (this is also the behavior of CORAL, so we do
250             // the same here)
251             Element authConn = null;
252             Iterator<File> fIt = dbAuthfiles.iterator();
253             while (fIt.hasNext()) {
254                 f = fIt.next();
255                 try {
256                     // first get the xml document from the file
257                     Document document = parser.parse(f);
258                     // then get all the connections
259                     NodeList connections = document.getElementsByTagName("connection");
260                     // and find ours
261                     for (int i = 0; i < connections.getLength(); i++) {
262                         if (!((Element) connections.item(i)).getAttribute("name").equals(svcName)) {
263                             continue;
264                         }
265                         logger.fine("Found connection for " + svcName);
266                         authConn = (Element) connections.item(i);
267                         NodeList params = authConn.getElementsByTagName("parameter");
268                         for (int j = 0; j < params.getLength(); j++) {
269                             Element param = (Element) params.item(j);
270                             if (param.getAttribute("name").equals("user")) {
271                                 username = param.getAttribute("value");
272                             }
273                             if (param.getAttribute("name").equals("password")) {
274                                 password = param.getAttribute("value");
275                             }
276                         }
277                         if (username == null || password == null) {
278                             System.out.println("In authentication file " + f.getPath() + "/" + f.getName());
279                             System.out.print("connection " + svcName);
280                             System.out.println(" has no user or no password");
281                             return false;
282                         }
283                         break;
284                     }
285                 } catch (Exception e) {
286                     System.out.println("Problems in file " + f.getPath() + "/" + f.getName() + ": " + e.getMessage());
287                 }
288                 if (authConn != null) {
289                     break;
290                 }
291             }
292             if (authConn == null) {
293                 System.out.println("Could not find connection " + svcName + " in any of the authentication files!");
294                 return false;
295             }
296             logger.fine("Found user " + username + "on host " + hostname);
297         //hostname might be intr, which is ok, but atlas_config means atonr! confusing
298         if(hostname.toLowerCase().equals("atlas_config")) hostname = "atonr";
299             theInitInfo.setdbServer(hostname);
300             theInitInfo.setUserName(username);
301             theInitInfo.setPassWord(password);
302             theInitInfo.setTableName(tablename);
303             theInitInfo.setdbTechnology(dbtechnology);
304             theInitInfo.setFilename(filename);
305             if (dbtechnology.equals("Oracle")) {
306                 hostname = theInitInfo.getdbServer(); // the translation from server name to server connection is in InitInfo
307             }
308 
309         }//end of dblookup/authentication style connection
310         ////////////////////////////////////////////////////////////////////////
311         
312         String url = "";
313         boolean ok = true;
314 
315         if (dbtechnology.equals("Oracle")) {
316             url = hostname;
317         } else if (dbtechnology.equals("MySQL")) {
318             //url = "jdbc:mysql://" + hostname + ":3306/" + tablename + "?zeroDateTimeBehavior=convertToNull";
319             url = "jdbc:mysql://" + hostname + ":3306/" + tablename;
320         } else if (dbtechnology.equals("SQLite")) {
321             url = "jdbc:sqlite:" + filename;
322         }
323 
324         logger.info("url: " + url);
325 
326         String r_username = "atlas_conf_trigger_v2_r";
327         String atonrR_password = theInitInfo.getAtonrRPassword();
328 
329         //writer account on atonr
330         if (theInitInfo.getUserName().contains("atlas_conf_trigger_v2_w") && theInitInfo.getdbServer().contains("atonr")) { // || theInitInfo.getdbServer().contains("devdb10")) {
331 
332             //log on first as reader to check if privilege ok to log on as writer!
333             logger.fine("Attempting to log on to atlas_conf_trigger_v2_w@atonr");
334             conn = DriverManager.getConnection(url, r_username, atonrR_password);
335 
336             //System.out.println("Attempting to log on to atlas_conf_trigger_v2_w@atonr");
337             //System.out.println("User level requested: " + theInitInfo.getMode());
338             
339             boolean pw_ok = checkPassword(getInitInfo().getSystemUsername(), getInitInfo().encryptAtonrPassword());
340 
341             if (!pw_ok) {
342                 throw new SQLException("Incorrect password or user level for user " + getInitInfo().getSystemUsername(), "Error");
343             }
344         }
345 
346         //reader account on atlr
347         if (theInitInfo.getUserName().contains("atlas_conf_trigger_v2_r") && theInitInfo.getdbServer().contains("atlr")) { // || theInitInfo.getdbServer().contains("devdb10")) {
348             username = r_username;
349             getInitInfo().setUserName(r_username);
350             //password is set in the box - users must know it!
351             getInitInfo().setTableName("atlas_conf_trigger_v2");
352         }
353 
354         logger.fine(url);
355         logger.fine(username);
356         conn = DriverManager.getConnection(url, username, password);
357 
358         if (dbtechnology.equals("Oracle")) {
359             ((OracleConnection) conn).setStatementCacheSize(100);
360             ((OracleConnection) conn).setImplicitCachingEnabled(true);
361         }
362 
363         //if (dbtechnology.equals("SQLite") && theInitInfo.getInsertSchema()) {
364         if (dbtechnology.equals("SQLite")) {
365             logger.info("Selected SQLite...");
366         }
367 
368         //check the schema version matches the trigger tool
369         int version = -1;
370 
371         try {
372             version = getSchemaVersion();
373         } catch (SQLException ex) {
374             //CASE WHERE NO SCHEMA VERSION FOUND
375             //*** Used to offer a chance to INSTALL the schema - don't do this anymore!
376             JOptionPane.showMessageDialog(null, "I think you have no schema installed, or a very old one!", "Error", JOptionPane.ERROR_MESSAGE);
377             throw new SQLException("I think you have no schema installed, or a very old one!" + ex);
378             //if (!theInitInfo.getdbServer().contains("atonr")) {
379             //    Object[] options = {"Yes, please", "No, thanks"};
380             //    int n = JOptionPane.showOptionDialog(null,
381             //            "I think you have no schema installed, or a very out of date one. Would you like me to make one? All existing data will be lost.",
382             //            "Populate Schema?",
383             //            JOptionPane.YES_NO_CANCEL_OPTION,
384             //            JOptionPane.QUESTION_MESSAGE,
385             //            null,
386             //            options,
387             //            options[1]);
388 
389             //    if (n == 0) {
390             //        new ResetSchema();
391             //        version = getSchemaVersion();
392             //    } else {
393             //        ok = false;
394             //        return ok;
395             //    }
396             //} else {
397             //    throw new SQLException("No schema version found on ATONR!", "Error, atonr schema out of date.");
398             //}
399             
400         }
401 
402         if (version == SCHEMA_VERSION) {
403             ok = true;
404         } else {
405             //CASE WHERE OLD SCHEMA VERSION FOUND
406             //*** Used to offer a chance to REGEN the schema - don't do this anymore!
407             JOptionPane.showMessageDialog(null, "I think you have an out of data schema installed!", "Error", JOptionPane.ERROR_MESSAGE);
408             //if (!theInitInfo.getdbServer().contains("atonr")) {
409             //    Object[] options = {"Yes, please", "No, thanks"};
410             //    int n = JOptionPane.showOptionDialog(null,
411             //            "This TriggerTool needs schema version " + SCHEMA_VERSION + ".\n" +
412             //            "This Database has schema version " + version + "\n" +
413             //            "Would you like to replace the Schema in the Database?  All existing data will be lost.",
414             //            "Replace Schema?",
415             //            JOptionPane.YES_NO_CANCEL_OPTION,
416             //            JOptionPane.QUESTION_MESSAGE,
417             //            null,
418             //            options,
419             //            options[1]);
420 
421             //    if (n == 0) {
422             //        new ResetSchema();
423             //        version = getSchemaVersion();
424             //    } else {
425             //        ok = false;
426             //        return ok;
427             //    }
428 
429             //    if (version != SCHEMA_VERSION) {
430             //        throw new SQLException("Even after replacing the Schema it still didn't work", "Very Bad Error indeed");
431             //    }
432             //}
433         }
434         logger.fine("Connection made " + ok);
435         return ok;
436     }
437 
438     public void changeUser(String user, String pwd, int mode) {
439         //System.out.println("Changing connection parameters");
440         boolean good = false;
441 
442         if (mode == InitInfo.USER) {
443             good = true;
444         } else {
445             try {
446                 good = checkPassword(user, getInitInfo().encrypt(pwd));
447             } catch (SQLException ex) {
448                 System.out.println(ex.getMessage());
449                 ex.printStackTrace();
450             }
451         }
452 
453         if (good) {
454             try {
455                 conn.close();
456 
457                 if (mode == InitInfo.USER) {
458                     getInitInfo().setUserName("atlas_conf_trigger_v2_r");
459                     getInitInfo().setMode(mode);
460                 } else {
461                     getInitInfo().setUserName("atlas_conf_trigger_v2_w");
462                     getInitInfo().setSystemUsername(user);
463                     getInitInfo().setPassWord(getInitInfo().getAtonrWPassword());
464                     getInitInfo().setOnlineUserPassword(pwd);
465                     getInitInfo().setMode(mode);
466                 }
467 
468                 connect(getInitInfo());
469             } catch (SQLException ex) {
470                 System.out.println(ex.getMessage());
471                 ex.printStackTrace();
472             }
473         }
474 
475         //System.out.println("Done with change");
476     }
477 
478     private boolean checkPassword(String user, String pwd) throws SQLException {
479         boolean pw_ok = false;
480         try {
481             
482             String query = "SELECT TT_LEVEL, TT_PASSWORD FROM ATLAS_CONF_TRIGGER_V2.TT_USERS WHERE TT_USER=?";
483             PreparedStatement ps = getConnection().prepareStatement(query);
484             ps.setString(1, user);
485             ResultSet rset = ps.executeQuery();
486 
487             //System.out.println("Setting to shift mode for some reason... will override with correct privilege");
488             //getInitInfo().setMode(InitInfo.SHIFTER);
489 
490             //System.out.println("User level query: " + query);
491             
492             while (rset.next()) {
493                 
494                 //ugly
495                 int allowedmode = -1;
496                 if(rset.getString(1).equals("Shifter")) allowedmode = 2;
497                 if(rset.getString(1).equals("TriggerMenuMeister")) allowedmode = 5;
498                 if(rset.getString(1).equals("TriggerMeister")) allowedmode = 6;
499                 //System.out.println("PJB trying to connect in mode " + getInitInfo().getMode());
500                 //System.out.println("PJB user " + user + " has access " + rset.getString(1) + " = " + allowedmode);
501                 
502                 if (rset.getString(2).equals(pwd) && allowedmode>=getInitInfo().getMode()) {
503                     //System.out.println("The passwords match and the level is OK");
504                     pw_ok = true;
505                 } else {
506                     pw_ok = false;
507                 }
508             }
509 
510             rset.close();
511             ps.close();
512             getConnection().close();
513         } catch (SQLException ex) {
514             throw new SQLException("Table containing access levels is missing in atonr", "Error");
515         }
516         return pw_ok;
517     }
518 
519     public int countSuperMasterTables(String query, int id) {
520         int count = -10;
521         try {
522             query = fix_schema_name(query);
523             PreparedStatement ps = getConnection().prepareStatement(query);
524 
525             ps.setInt(1, id);
526             ResultSet rs = ps.executeQuery();
527 
528             while (rs.next()) {
529                 count = rs.getInt(1);
530             }
531 
532             ps.close();
533         } catch (SQLException ex) {
534             logger.warning("SQL Ex: " + ex.getMessage());
535         }
536 
537         return count;
538     }
539 
540     public boolean doingDBCopy() {
541         return doDBCopy;
542     }
543     
544     ///Reload a row from the database.
545     /**
546      * Cause a single row to be reloaded from the database.  This is ok for a 
547      * small number of rows, but is far too slow to be used in general.
548      * 
549      * @param aThis The record that we want reloading.
550      */
551     public void forceLoad(AbstractTable aThis) {
552         try {
553             String query = aThis.getQueryString();
554             query += " WHERE " + aThis.tablePrefix + "ID=?";
555             query = fix_schema_name(query);
556 
557             PreparedStatement ps = ConnectionManager.getInstance().getConnection().prepareStatement(query);
558             ps.setInt(1, aThis.get_id());
559             ResultSet rset = ps.executeQuery();
560 
561             while (rset.next()) {
562                 aThis.loadFromRset(rset);
563             }
564 
565             rset.close();
566             ps.close();
567         } catch (SQLException ex) {
568             ex.printStackTrace();
569         }
570     }
571 
572     ///Get the connection information.
573     /**
574      * Get the init info, which contains important information about the user
575      * and the database connection parameters.
576      * 
577      * @return The Init Info object.
578      */
579     public InitInfo getInitInfo() {
580         return savedInitInfo;
581     }
582 
583     ///Return the connection. Must be used.
584     /**
585      * Use this method when referring to the connection, so that we can swap
586      * between the conncetion to read from and the conncetion to write to.
587      * 
588      * @return The connection.  If doDBCopy return the connection to write to.
589      */
590     public Connection getConnection() {
591         Connection connection = conn;
592 
593         //if (doDBCopy) {
594         //    connection = copy_to_connection;
595         //}
596 
597         return connection;
598     }
599 
600     ///Set another connection  for the write account.
601     /**
602      * The user wants to switch from the reading account, to the connection to 
603      * write to.  For now this is hard coded but will change.
604      * 
605      * @param string Null for now.
606      * @param string0 Null for now.
607      * @throws java.sql.SQLException Quit when we have a problem.
608      */
609     public void setWriteDB(String url, String userName, String userPassword) throws SQLException {
610         //System.out.println("Setting Write DB");
611         doDBCopy = true;
612         if (userName.equals("")){
613             userName = getInitInfo().getUserName();
614         }
615         copy_to_connection = DriverManager.getConnection(url, userName, userPassword);
616         //System.out.println("Opened write to account");
617     }
618 
619     /**
620      * Swap back to the reading database, and kill the copy to database.
621      */
622     public void cancelWriteDB() throws SQLException {
623         doDBCopy = false;
624         //copy_to_connection.close();
625         //copy_to_connection = null;
626     }
627 
628     /**
629      * Save a clob to the database
630      *
631      * @param tableName Name of the table to insert the clob into
632      * @param fieldName Field for the clob
633      * @param filename Text file to insert
634      * @param tablePrefix Used to concatenate a string prefix_id
635      * @param id integer id of the record we want to replace (insert not yet supported)
636      */
637     public void set_clob(String tableName, String fieldName, String filename, String tablePrefix, int id) {
638         logger.fine("Ready to insert clob");
639 
640         try {
641             if (getInitInfo().getdbTechnology().contains("Oracle") && getInitInfo().getTableName().length() > 2) {
642                 tableName = getInitInfo().getTableName() + "." + tableName;
643             }
644 
645             String query = "UPDATE " + tableName + " SET " + fieldName + "=? WHERE " + tablePrefix + "ID=" + id;
646 
647             query = fix_schema_name(query);
648             logger.fine("Query: " + query);
649             PreparedStatement pstmt = getConnection().prepareStatement(query);
650 
651             logger.fine("Opening " + filename);
652 
653             File fFile = new File(filename);
654             FileInputStream fis = new FileInputStream(fFile);
655 
656             if (getInitInfo().getdbTechnology().contains("Oracle")) {
657                 InputStreamReader irdr = new InputStreamReader(fis);
658                 BufferedReader brdr = new BufferedReader(irdr, 8192);
659 
660                 String str = "";
661                 String line;
662                 int nlines = 0;
663                 StringBuffer buffer = new StringBuffer();
664                 logger.fine("going to read file");
665                 try {
666                     while ((line = brdr.readLine()) != null) {
667                         nlines++;
668                         buffer.append(line + "\n");
669                     }
670                     logger.fine("read lines:  " + nlines);
671                     brdr.close();
672                 } catch (IOException e) {
673                     logger.warning("File reading failed");
674                     logger.warning("Sometimes this is ok");
675                 }
676                 logger.fine("going to save clob:");
677                 str = buffer.toString();
678                 oracle.sql.CLOB newClob = oracle.sql.CLOB.createTemporary(conn, false, oracle.sql.CLOB.DURATION_CALL);
679 
680                 newClob.putString(1, str);
681                 pstmt.setClob(1, newClob);
682             } else {
683                 //MySQL / SQLite
684                 if (fis != null) {
685                     pstmt.setAsciiStream(1, fis, (int) fFile.length());
686                 } else {
687                     logger.warning("Null fis");
688                 }
689             }
690             pstmt.executeUpdate();
691 
692             pstmt.close();
693             logger.finer("Clob insert ok");
694         } catch (FileNotFoundException e) {
695             logger.warning("CLOB FILE ERROR");
696             logger.warning(e.getMessage());
697             e.printStackTrace();
698         } catch (SQLException e) {
699             logger.warning("CLOB SQL ERROR!");
700             logger.warning(e.getMessage());
701             e.printStackTrace();
702         }
703     }
704 
705     /**
706      * Get a clob from the database
707      * 
708      * @param tableName
709      * @param tablePrefix
710      * @param id
711      * @param field
712      * @return String representation of the clob
713      */
714     public String get_clob(String tableName, String tablePrefix, int id, String field) {
715         StringBuffer strOut = new StringBuffer();
716         String query = "SELECT " + tablePrefix + field + " FROM " + tableName + " WHERE " + tablePrefix + "ID=?";
717         query = fix_schema_name(query);
718         try {
719             PreparedStatement ps = getConnection().prepareStatement(query);
720             ps.setInt(1, id);
721             ResultSet rset = ps.executeQuery();
722             while (rset.next()) {
723                 Clob out = rset.getClob(tablePrefix + field);
724                 if (out != null) {
725 
726                     String aux;
727                     BufferedReader br = new BufferedReader(out.getCharacterStream());
728 
729                     try {
730                         while ((aux = br.readLine()) != null) {
731                             strOut.append(aux).append("\n");
732                         }
733                     } catch (IOException e) {
734                         logger.warning("problem converting clob to string");
735                         e.printStackTrace();
736                     }
737                 }
738             }
739             rset.close();
740             ps.close();
741         } catch (Exception e) {
742             logger.warning("Error reading clob");
743         }
744 
745         return strOut.toString();
746     }
747 
748     /**
749      * Get the log path.
750      * 
751      * @return The log path.
752      */
753     public String get_log_path() {
754         return log_path;
755     }
756 
757     /**
758      * This needs to be a singleton so we can manage the connection
759      * to the database properly
760      *
761      * @return Instance of the singleton
762      */
763     public static synchronized ConnectionManager getInstance() {
764         if (connMa == null) {
765             connMa = new ConnectionManager();
766         }
767         return connMa;
768     }
769 
770     /**
771      * Function to connect towrite db, uses connect(..) function - see below.
772      * @param ii - the InitInfo object
773      * @return true if successful
774      * @throws java.sql.SQLException
775      */
776     public boolean connect_towritedb(InitInfo ii) throws SQLException {
777         doDBCopy=true;
778         return connect(ii);
779     }
780     
781     
782     /**
783      * Converts a java Boolean type to a string (as used in the
784      * database schema)
785      *
786      * @param used True or false
787      * @return 0 or 1 as a string
788      */
789     private String format_bool(Boolean used) {
790         String used_str = "0";
791         if (used) {
792             used_str = "1";
793         }
794         return used_str;
795     }
796 
797     /**
798      * When doing a SQL statement that doesn't have a return
799      * for example removing a record use this
800      *
801      * @param query The SQL code to be executed
802      * @throws SQLException
803      */
804     public void executeStatement(String query) throws SQLException {
805         query = fix_schema_name(query);
806         try {
807             if (stmt != null) {
808                 stmt.close();
809             }
810         } catch (Exception ex) {
811             logger.warning("can't close stmt");
812             String exceptionMessage = "DB Error: ";
813             exceptionMessage += ex.getMessage();
814             exceptionMessage += "Query:\t" + query;
815             throw new SQLException(exceptionMessage);
816         }
817 
818         stmt = getConnection().prepareStatement(query);
819 
820         try {
821             stmt.execute();
822         } catch (SQLException ex) {
823             String exceptionMessage = "DB Error ";
824             exceptionMessage += ex.getMessage();
825             exceptionMessage += "Query:\t" + query;
826             throw new SQLException(exceptionMessage, ex.getSQLState());
827         }
828 
829         if (!getInitInfo().getdbTechnology().contains("SQLite")) {
830             try {
831                 stmt.executeUpdate("COMMIT");
832             } catch (SQLException ex) {
833                 String exceptionMessage = "DB Error ";
834                 exceptionMessage += ex.getMessage();
835                 exceptionMessage += "Query:\t" + query;
836                 throw new SQLException(exceptionMessage, ex.getSQLState());
837             }
838         }
839     }
840 
841     public int save(String tableName, String tablePrefix, Integer id, TreeMap<String, Object> fields_values) throws SQLException {
842         if (id > 0) {
843             //logger.info("Will not save");
844             return id;
845         }
846 
847         //logger.info("Will save");
848 
849         //versioning for comp depends on name and alias
850         if(!tableName.equals("HLT_COMPONENT")){
851             if (fields_values.containsKey("VERSION")) {
852                 fields_values.put("VERSION", new Integer(1 + getMaxVersion(tableName, tablePrefix, (String) fields_values.get("NAME"))));
853             }
854         }else{
855             if (fields_values.containsKey("VERSION")) {
856                 fields_values.put("VERSION", new Integer(1 + getMaxCompVersion((String) fields_values.get("NAME"), (String) fields_values.get("ALIAS"))));
857             }
858         }
859         
860 
861         //for 
862         StringBuffer sb = new StringBuffer();
863         StringBuffer sb2 = new StringBuffer();
864         StringBuffer sb3 = new StringBuffer();
865 
866         //code to save a new record
867         sb.append("INSERT INTO ");
868         sb.append(tableName);
869         sb.append(" (" + tablePrefix + "ID," + tablePrefix + "MODIFIED_TIME," + tablePrefix + "USERNAME,");
870 
871         for (String key : fields_values.keySet()) {
872 
873             if (key.equals("MODIFIED_TIME") || key.equals("USERNAME") || key.equals("ID")) {
874                 continue;
875             }
876             sb.append(tablePrefix);
877             sb.append(key);
878             sb.append(",");
879             sb2.append("?,");
880         }
881 
882         sb.deleteCharAt(sb.length() - 1);
883         sb2.deleteCharAt(sb2.length() - 1);
884 
885         sb.append(") VALUES (");
886 
887         if (getInitInfo().getdbTechnology().contains("MySQL") ||
888                 getInitInfo().getdbTechnology().contains("SQLite")) {
889             sb.append("?,NULL,?,");
890         } else {
891             sb.append("?,sysdate,?,");
892         }
893         sb.append(sb2);
894         sb.append(")");
895 
896         //System.out.println("Insert Query : " + sb.toString());
897 
898         String query = "SELECT MAX(" + tablePrefix + "ID) FROM " + tableName;
899         query = fix_schema_name(query);
900         PreparedStatement s = getConnection().prepareStatement(query);
901 
902         ResultSet r = s.executeQuery();
903         while (r.next()) {
904             id = r.getInt(1) + 1;
905         }
906 
907         s.close();
908 
909         s = getConnection().prepareStatement(fix_schema_name(sb.toString()));
910 
911         String humanQuery = fix_schema_name(sb.toString());
912         humanQuery = humanQuery.replaceFirst("\\?", "" + id);
913         humanQuery = humanQuery.replaceFirst("\\?", getInitInfo().getSystemUsername());
914 
915         s.setInt(1, id);
916 
917         s.setString(2, getInitInfo().getSystemUsername());
918         sb3.append(getInitInfo().getSystemUsername());
919         sb3.append(" ");
920 
921         int i = 3;
922 
923         for (String key : fields_values.keySet()) {
924             if (key.equals("MODIFIED_TIME") || key.equals("USERNAME") || key.equals("ID")) {
925                 continue;
926             }
927 
928             Object obj = fields_values.get(key);
929 
930             if (obj instanceof String) {
931                 String str = (String) obj;
932                 if (str == null || str.equals("")) {
933                     str = "~";
934                 }
935 
936                 s.setString(i, str);
937                 sb3.append(str);
938                 sb3.append(" ");
939             }
940 
941             if (obj instanceof Integer) {
942                 s.setInt(i, (Integer) obj);
943                 sb3.append((Integer) obj);
944                 sb3.append(" ");
945             }
946 
947             if (obj instanceof Boolean) {
948                 s.setString(i, format_bool((Boolean) obj));
949                 sb3.append(format_bool((Boolean) obj));
950                 sb3.append(" ");
951             }
952 
953             if (obj instanceof Double) {
954                 s.setDouble(i, (Double) obj);
955                 sb3.append((Double) obj);
956                 sb3.append(" ");
957             }
958 
959             if (obj instanceof Float) {
960                 s.setDouble(i, (Float) obj);
961                 sb3.append((Float) obj);
962                 sb3.append(" ");
963             }
964 
965             humanQuery = humanQuery.replaceFirst("\\?", obj.toString());
966 
967             ++i;
968         }
969 
970         //logger.info("Insert Params 1: " + sb3.toString());
971 
972         //System.out.println("INSERT: " + humanQuery);
973 
974         try {
975             s.executeUpdate();
976         } catch (SQLException ex) {
977             String errMsg = "Caught SQL error: " + ex.getMessage();
978             errMsg += "query: " + sb.toString() + "\n";
979             errMsg += "params: " + sb3.toString() + "\n";
980             logger.severe(errMsg);
981             ex.printStackTrace();
982             throw ex;
983         }
984 
985         s.close();
986 
987         return id;
988     }
989 
990     /**
991      * @brief Get the version.
992      * 
993      * When we do a copy we need to increment the version.  This returns the max
994      * version that exists in the database.  Also used in the XML reading in to
995      * database.
996      *
997      * @param tableName Name of the table we're searching.
998      * @param tablePrefix Prefix for the table.
999      * @param name The name of the row.
1000      * 
1001      * @return the max version, if you're writing a new record add one to this
1002      */
1003     public int getMaxVersion(String tableName, String tablePrefix, String name) {
1004         StringBuffer query = new StringBuffer();
1005 
1006         if (tableName.equals("HLTTriggerSignature") || tableName.equals("HLTRelease")) {
1007             query.append("SELECT MAX(");
1008             query.append(tableName);
1009             query.append(") FROM ");
1010             query.append(tableName);
1011             query.append(" WHERE ");
1012             query.append(tableName);
1013             query.append("=?");
1014         } else {
1015             query.append("SELECT MAX(");
1016             query.append(tablePrefix);
1017             query.append("VERSION) FROM ");
1018             query.append(tableName);
1019             query.append(" WHERE ");
1020             query.append(tablePrefix);
1021             query.append("NAME=?");
1022         }
1023 
1024         int max = 0;
1025         try {
1026             String q = fix_schema_name(query.toString());
1027             PreparedStatement ps = getConnection().prepareStatement(q);
1028             ps.setString(1, name);
1029             ResultSet rset = ps.executeQuery();
1030 
1031             while (rset.next()) {
1032                 max = rset.getInt(1);
1033             }
1034 
1035             rset.close();
1036             ps.close();
1037         } catch (SQLException e) {
1038             e.printStackTrace();
1039         }
1040         return max;
1041     }
1042 
1043     /**
1044      * Special adaptation of getMaxVersion for compt, which needs name and alias
1045      */ 
1046     
1047     public int getMaxCompVersion(String name, String alias) {
1048 
1049         String query = "SELECT MAX(HCP_VERSION) FROM HLT_COMPONENT WHERE HCP_NAME=? AND HCP_ALIAS=?";
1050 
1051         int max = 0;
1052         try {
1053             query = fix_schema_name(query);
1054             PreparedStatement ps = getConnection().prepareStatement(query);
1055             ps.setString(1, name);
1056             ps.setString(2, alias);
1057             ResultSet rset = ps.executeQuery();
1058 
1059             while (rset.next()) {
1060                 max = rset.getInt(1);
1061             }
1062 
1063             rset.close();
1064             ps.close();
1065         } catch (SQLException e) {
1066             e.printStackTrace();
1067         }
1068         return max;
1069     }
1070 
1071     /**
1072      * For HLT XML upload.  Need to link elements to a component
1073      *
1074      * @param setupID id for the setup record
1075      * @param alias
1076      * @return id of the hlt component
1077      */
1078     public int findComponent(int setupID, String alias) {
1079         int hcp_id = -1;
1080 
1081         StringBuffer buffer = new StringBuffer();
1082         buffer.append("SELECT HCP_ID FROM HLT_COMPONENT, HLT_ST_TO_CP");
1083         buffer.append(" WHERE HLT_COMPONENT.HCP_ALIAS=\'?\'");
1084         buffer.append(" AND HLT_ST_TO_CP.HST2CP_COMPONENT_ID=HLT_COMPONENT.HCP_ID");
1085         buffer.append(" AND HLT_ST_TO_CP.HST2CP_SETUP_ID=?");
1086 
1087         String query = fix_schema_name(buffer.toString());
1088 
1089         try {
1090             logger.finer("findcom " + query);
1091             PreparedStatement ps = getConnection().prepareStatement(query);
1092             ps.setString(1, alias);
1093             ps.setInt(1, setupID);
1094 
1095             ResultSet rset = ps.executeQuery();
1096             while (rset.next()) {
1097                 hcp_id = rset.getInt(1);
1098             }
1099             rset.close();
1100             ps.close();
1101         } catch (SQLException e) {
1102             e.printStackTrace();
1103         }
1104 
1105         return hcp_id;
1106     }
1107 
1108     public Vector<Integer> get_IDs(String table_name, String table_prefix, TreeMap<String, Object> fields_values, String order, String ignore) throws SQLException {
1109         Vector<String> ignoreList = new Vector<String>();
1110         ignoreList.add(ignore);
1111         return get_IDs(table_name, table_prefix, fields_values, order, ignoreList);
1112     }
1113 
1114     ///Get the rows from the database that have columns matching those in fields_values.
1115     /**
1116      * Note you can pass keyValues for a class and specify those to be ignore.
1117      * By default USERNAME, MODIFIED_TIME, USED and VERSION are ignore by the
1118      * seach.  ID is not, since you might not always want to!
1119      * 
1120      * @param table_name Database name of table.
1121      * @param table_prefix Database prefix including underscore, SMT_
1122      * @param fields_values Criteria to match in search.
1123      * @param order NULL?
1124      * @param ignoreList Vector of fields to ignore in the match.
1125      * @return Vector of all the matching IDs in ascending order.
1126      * @throws java.sql.SQLException
1127      */
1128     public Vector<Integer> get_IDs(String table_name, String table_prefix, TreeMap<String, Object> fields_values, String order, Vector<String> ignoreList) throws SQLException {
1129         if (ignoreList == null || ignoreList.size() == 0) {
1130             ignoreList = new Vector<String>();
1131         }
1132 
1133         ignoreList.add("USERNAME");
1134         ignoreList.add("MODIFIED_TIME");
1135         ignoreList.add("VERSION");
1136         ignoreList.add("USED");
1137 
1138         if (order == null) {
1139             order = "";
1140         }
1141 
1142         Vector<Integer> ids_vec = new Vector<Integer>();
1143 
1144         StringBuffer sb = new StringBuffer();
1145         sb.append("SELECT ");
1146         sb.append(table_prefix);
1147         sb.append("ID FROM ");
1148         sb.append(table_name);
1149         sb.append(" WHERE ");
1150 
1151         int i = 1;
1152         StringBuffer sb3 = new StringBuffer();
1153 
1154         try {
1155             for (String key : fields_values.keySet()) {
1156                 boolean skipField = false;
1157                 for (String ignore : ignoreList) {
1158                     if (key.equals(ignore)) {
1159                         skipField = true;
1160                     }
1161                 }
1162 
1163                 if (skipField) {
1164                     continue;
1165                 }
1166                 sb.append(table_prefix);
1167                 sb.append(key);
1168                 sb.append("=? AND ");
1169             }
1170 
1171             sb.delete(sb.length() - 5, sb.length());
1172 
1173             sb.append(" ORDER BY " + table_prefix + "ID ASC");
1174 
1175             //logger.info("query:  " + sb.toString());
1176 
1177             String q = fix_schema_name(sb.toString());
1178             PreparedStatement s = getConnection().prepareStatement(q);
1179 
1180             for (String key : fields_values.keySet()) {
1181                 boolean skipField = false;
1182                 for (String ignore : ignoreList) {
1183                     if (key.equals(ignore)) {
1184                         skipField = true;
1185                     }
1186                 }
1187 
1188                 if (skipField) {
1189                     continue;
1190                 }
1191 
1192                 Object obj = fields_values.get(key);
1193 
1194                 if (obj instanceof String) {
1195                     String str = (String) obj;
1196                     if (str == null || str.equals("")) {
1197                         str = "~";
1198                     }
1199 
1200                     s.setString(i, str);
1201                     sb3.append(str);
1202                     sb3.append(" ");
1203                 }
1204 
1205                 if (obj instanceof Integer) {
1206                     s.setInt(i, (Integer) obj);
1207                     sb3.append((Integer) obj);
1208                     sb3.append(" ");
1209                 }
1210 
1211                 if (obj instanceof Boolean) {
1212                     s.setString(i, format_bool((Boolean) obj));
1213                     sb3.append(format_bool((Boolean) obj));
1214                     sb3.append(" ");
1215                 }
1216 
1217                 if (obj instanceof Double) {
1218                     s.setDouble(i, (Double) obj);
1219                     sb3.append((Double) obj);
1220                     sb3.append(" ");
1221                 }
1222 
1223                 if (obj instanceof Float) {
1224                     s.setDouble(i, (Float) obj);
1225                     sb3.append((Float) obj);
1226                     sb3.append(" ");
1227                 }
1228 
1229                 ++i;
1230             }
1231 
1232             //logger.info("values: " + sb3.toString());
1233 
1234             ResultSet rset = s.executeQuery();
1235 
1236             while (rset.next()) {
1237                 ids_vec.addElement(rset.getInt(1));
1238             }
1239 
1240             rset.close();
1241             s.close();
1242 
1243         } catch (SQLException ex) {
1244             logger.severe("SQL error with following query " + ex.getMessage());
1245             logger.severe("query:  " + sb.toString());
1246             logger.severe("warning: " + sb3.toString());
1247             throw ex;
1248         }
1249 
1250         return ids_vec;
1251     }
1252 
1253     /**
1254      * For HLT XML upload.  Need to link elements to a component
1255      *
1256      * @param setupID id for the setup record
1257      * @param alias
1258      * @param name
1259      * @return id of the hlt component
1260      */
1261     public int findComponent(int setupID, String alias, String name) {
1262         int hcp_id = -1;
1263 
1264         String query = "SELECT HCP_ID FROM HLT_COMPONENT, HLT_ST_TO_CP ";
1265         query += "WHERE HLT_COMPONENT.HCP_ALIAS=? ";
1266         if (name != null) {
1267             query += " AND HLT_ST_TO_CP.HST2CP_COMPONENT_ID=HLT_COMPONENT.HCP_ID AND HLT_ST_TO_CP.HST2CP_SETUP_ID=?";
1268         }
1269 
1270         try {
1271             logger.finer("findcom " + query);
1272             PreparedStatement ps = getConnection().prepareStatement(query);
1273             ps.setString(1, alias);
1274             if (name != null) {
1275                 ps.setInt(2, setupID);
1276             }
1277             ResultSet rset = ps.executeQuery();
1278             while (rset.next()) {
1279                 hcp_id = rset.getInt(1);
1280             }
1281             rset.close();
1282             ps.close();
1283         } catch (SQLException e) {
1284             e.printStackTrace();
1285         }
1286         logger.finer("-------------- found comp " + hcp_id);
1287         return hcp_id;
1288     }
1289 
1290     /**
1291      * For HLT XML upload.  Need to link elements to a component
1292      *
1293      * @param setupID id for the setup record
1294      * @param aliases Aliases of the HLT_COMPONENT
1295      * @param names Names of the HLT_COMPONENT
1296      * @return id of the hlt component
1297      */
1298     public Vector<Integer> findComponents(int setupID, Vector<String> aliases, Vector<String> names) throws SQLException {
1299         Vector<Integer> hcp_ids = new Vector<Integer>();
1300 
1301         int nAliases = aliases.size();
1302         int nNames = names.size();
1303         int nMaxNA = (nNames > nAliases) ? nNames : nAliases;
1304         // Test the input variables
1305         // Mirek: make simpler condition
1306         if (!(nNames == nAliases || nNames == 0 || nAliases == 0)) {
1307             return hcp_ids;
1308         }
1309         // Go through components one by one to have the name and aliases id's sorted
1310         for (int iComponent = 0; iComponent < nMaxNA; iComponent++) {
1311             String query = "SELECT DISTINCT HLT_COMPONENT.HCP_ID FROM HLT_SETUP ";
1312             query += "JOIN HLT_ST_TO_CP ON (HLT_ST_TO_CP.HST2CP_SETUP_ID = HLT_SETUP.HST_ID) ";
1313             query += "JOIN HLT_COMPONENT ON (HLT_ST_TO_CP.HST2CP_COMPONENT_ID = HLT_COMPONENT.HCP_ID) ";
1314             query += "WHERE HLT_SETUP.HST_ID=? ";
1315             query += " AND ";
1316 
1317             if (iComponent < nAliases) {
1318                 query += " HLT_COMPONENT.HCP_ALIAS=? ";
1319             }
1320 
1321             if (iComponent < nAliases && iComponent < nNames) {
1322                 query += " AND ";
1323             }
1324             if (iComponent < nNames) {
1325                 query += " HLT_COMPONENT.HCP_NAME=? ";
1326             }
1327 
1328             int hcp_id = -1;
1329             int nhcp_ids = 0;
1330 
1331             logger.finer("findComponents " + query);
1332             query = fix_schema_name(query);
1333             PreparedStatement ps = getConnection().prepareStatement(query);
1334 
1335             ps.setInt(1, setupID);
1336             int count = 2;
1337 
1338             if (iComponent < nAliases) {
1339                 ps.setString(count, aliases.get(iComponent));
1340                 ++count;
1341             }
1342 
1343             if (iComponent < nNames) {
1344                 ps.setString(count, names.get(iComponent));
1345             }
1346 
1347             ResultSet rset = ps.executeQuery();
1348             nhcp_ids = 0;
1349             while (rset.next()) {
1350                 hcp_id = rset.getInt(1);
1351                 nhcp_ids++;
1352             }
1353 
1354             rset.close();
1355             ps.close();
1356 
1357 
1358             if (nhcp_ids != 1) {
1359                 if (nhcp_ids == 0) {
1360                     // No Component found
1361                     logger.finer("No Matching Component found");
1362                     hcp_ids.addElement(-1);
1363                 } else {
1364                     // Multiple Components found - that should not happen
1365                     logger.finer("Multiple Components found:\t" + nhcp_ids);
1366                     hcp_ids.addElement(-2);
1367                 }
1368             } else {
1369                 // everything OK
1370                 hcp_ids.add(hcp_id);
1371             }
1372         }
1373 
1374         if (hcp_ids.size() != nMaxNA) {
1375             logger.finer("Output not matching the input:\t" + "Size of Input: " + nMaxNA + "\tSize of Output: " + hcp_ids.size());
1376         }
1377 
1378         return hcp_ids;
1379     }
1380 
1381     public TreeMap<Integer, Integer> getConstrainedItemList(String query, int id) {
1382         TreeMap<Integer, Integer> results = new TreeMap<Integer, Integer>();
1383         query = ConnectionManager.getInstance().fix_schema_name(query);
1384 
1385         try {
1386             PreparedStatement ps = getConnection().prepareStatement(query);
1387             ps.setInt(1, id);
1388             ResultSet rset = ps.executeQuery();
1389 
1390             while (rset.next()) {
1391                 results.put(rset.getInt(1), rset.getInt(2));
1392             }
1393 
1394             rset.close();
1395             ps.close();
1396         } catch (SQLException e) {
1397             e.printStackTrace();
1398         }
1399 
1400         return results;
1401     }
1402 
1403     /**
1404      * Get all Items used
1405      *
1406      * @param table_name
1407      * @param table_prefix
1408      * @param base_name
1409      * @param reference_name
1410      * @return Vector of Item's ID's
1411      */
1412     public Vector<Integer> get_ItemList(String table_name, String table_prefix, String base_name, String reference_name, int baseID) {
1413         // Don't use distinct there can be multiple relations
1414 
1415         Connection connection = conn;
1416         
1417         StringBuffer query = new StringBuffer();
1418         query.append("SELECT ");
1419         query.append(reference_name);
1420         query.append("_ID FROM ");
1421         query.append(table_name);
1422         query.append(" WHERE ");
1423         query.append(base_name);
1424         query.append("_ID =?");
1425         query.append(" ORDER BY ");
1426         query.append(reference_name + "_ID ASC");
1427 
1428         //         if (query.toString().contains("HLT_TC_TO_TS")) {
1429         //             System.out.println("ConnectionManager.get_ItemList: " + query);
1430         //         }
1431 
1432         Vector<Integer> ids_vec = new Vector<Integer>();
1433 
1434         String query2 = fix_schema_name(query.toString());
1435 
1436         try {
1437             PreparedStatement ps = connection.prepareStatement(query2);
1438             ps.setInt(1, baseID);
1439             ResultSet rset = ps.executeQuery();
1440 
1441             while (rset.next()) {
1442                 ids_vec.add(rset.getInt(1));
1443             }
1444 
1445             rset.close();
1446             ps.close();
1447         } catch (SQLException e) {
1448             e.printStackTrace();
1449         }
1450         return ids_vec;
1451     }
1452 
1453     public void dblog(String message) {
1454         String values = "";
1455         if (getInitInfo().getdbTechnology().contains("MySQL") ||
1456                 getInitInfo().getdbTechnology().contains("SQLite")) {
1457             values = "?,?,NULL";
1458         } else {
1459             values = "?,?,sysdate";
1460         }
1461 
1462         String query = "INSERT INTO TRIGGER_LOG (TLOG_USERNAME, TLOG_MESSAGE, TLOG_MODIFIED_TIME) VALUES (" + values + ")";
1463         query = fix_schema_name(query);
1464         try {
1465             PreparedStatement ps = getConnection().prepareStatement(query);
1466             ps.setString(1, getInitInfo().getSystemUsername());
1467             ps.setString(2, message);
1468             ps.executeUpdate();
1469             ps.close();
1470         } catch (SQLException e) {
1471             e.printStackTrace();
1472         }
1473     }
1474 
1475     /**
1476      * Here we look into a connection table for an existing mapping
1477      * for instance:
1478      * If there is a trigger_menu with exactly the chains (a,b,c) and we
1479      * want to add a trigger_menu with exactly those three
1480      * chains (meaning exactly the same chain_IDs), then we don't have to
1481      * add a new trigger_menu
1482      * Since in the 'connection tables' the mapping (e.g.
1483      *
1484      * @param id_vec
1485      * @param id2_vec 
1486      * @return Vector of matching ID's of the base name, Remember there can be more things referring to same Items with different own parameters
1487      */
1488     public Vector<Integer> matchingConnectionSignatureIDs(Vector<Integer> id_vec, Vector<Integer> id2_vec) throws SQLException {
1489 
1490         Collections.sort(id2_vec);
1491 
1492         String table_name = "HLT_TS_TO_TE";
1493         String base_name = "HTS2TE_TRIGGER_SIGNATURE";
1494         String reference_name = "HTS2TE_TRIGGER_ELEMENT";
1495 
1496         Vector<Integer> baseIDs = new Vector<Integer>(); // Output vector with base ID with matching references
1497 
1498         if (id_vec == null || id_vec.size() == 0) {
1499             return baseIDs;
1500         }
1501         Vector<Integer> idV = new Vector<Integer>();
1502         Vector<Integer> ecV = new Vector<Integer>();
1503 
1504         Integer ec = 0;
1505         for (Integer id : id_vec) {
1506             idV.addElement(id);
1507             ecV.addElement(ec++);
1508         }
1509         for (Integer id : id2_vec) {
1510             idV.addElement(id);
1511             ecV.addElement(-1);
1512         }
1513 
1514         StringBuffer buffer = new StringBuffer();
1515         buffer.append("SELECT DISTINCT HTS2TE_TRIGGER_SIGNATURE_ID FROM HLT_TS_TO_TE WHERE ");
1516         Integer nRef = idV.size();
1517         for (int i = 0; i < nRef; i++) {
1518             buffer.append("(HTS2TE_TRIGGER_ELEMENT_ID=? AND HTS2TE_ELEMENT_COUNTER=?)");
1519             if (i < nRef - 1) {
1520                 buffer.append(" OR ");
1521             }
1522         }
1523 
1524 
1525         String query = fix_schema_name(buffer.toString());
1526 
1527         logger.finer("MCL: " + query);
1528 
1529         Vector<Integer> base_ids = new Vector<Integer>();
1530         try {
1531             PreparedStatement ps = getConnection().prepareStatement(query);
1532             for (int i = 0; i < nRef; i++) {
1533                 ps.setInt(2 * i + 1, idV.get(i));
1534                 ps.setInt(2 * i + 2, ecV.get(i));
1535             }
1536             ResultSet rset = ps.executeQuery();
1537 
1538             while (rset.next()) {
1539                 base_ids.add(rset.getInt(1));
1540             }
1541             rset.close();
1542             ps.close();
1543         } catch (SQLException e) {
1544             logger.warning("Error finding base ID's");
1545             e.printStackTrace();
1546         }
1547 
1548         int nbase_ids = base_ids.size();
1549         if (nbase_ids == 0) {
1550             // Base ID's is still empty and there was no result searching reference ID's
1551             return baseIDs;
1552         }
1553         //      Now loop over found base ID's and compare found references with the sorted input sorted_ref_vec
1554         Collections.sort(base_ids);
1555 
1556         // Do not use DISTINCT we need all the ID some of them can be doubled
1557         buffer = new StringBuffer();
1558         buffer.append("SELECT HTS2TE_TRIGGER_ELEMENT_ID, HTS2TE_ELEMENT_COUNTER FROM ");
1559         buffer.append(table_name);
1560         buffer.append(" WHERE ");
1561         buffer.append(base_name);
1562         buffer.append("_ID=?");
1563         //buffer.append(base_ids.get(ibase_id));
1564         buffer.append(" ORDER BY HTS2TE_ELEMENT_COUNTER, HTS2TE_TRIGGER_ELEMENT_ID");
1565 
1566         query = fix_schema_name(buffer.toString());
1567 
1568 
1569         logger.fine("   MCL 2: " + query);
1570 
1571         PreparedStatement ps = null;
1572 
1573         try {
1574             ps = getConnection().prepareStatement(query);
1575             for (int ibase_id = 0; ibase_id < nbase_ids; ibase_id++) {
1576 
1577                 Vector<Integer> refIDs = new Vector<Integer>();
1578                 Vector<Integer> refIDsNoEC = new Vector<Integer>();
1579                 // Address the database
1580 
1581                 ps.setInt(1, base_ids.get(ibase_id));
1582                 ResultSet rset = ps.executeQuery();
1583 
1584                 while (rset.next()) {
1585                     if (rset.getInt(2) < 0 || rset.getInt(2) > 99) {
1586                         refIDsNoEC.add(rset.getInt(1)); // the floating TE's
1587 
1588                     } else {
1589                         refIDs.add(rset.getInt(1)); // the TE's that are listed in the signature
1590 
1591                     }
1592                 }
1593 
1594                 // In case of matching references add base id into the output list
1595                 if (refIDs.equals(id_vec) && refIDsNoEC.equals(id2_vec)) {
1596                     baseIDs.add(base_ids.get(ibase_id));
1597                 }
1598                 rset.close();
1599             }
1600             ps.close();
1601         } catch (SQLException e) {
1602             logger.warning("Error preparing statement");
1603             e.printStackTrace();
1604         }
1605 
1606         return baseIDs;
1607     }
1608 
1609     /**
1610      * Here we look into a connection table for an existing mapping
1611      * for instance:
1612      * If there is a trigger_menu with exactly the chains (a,b,c) and we
1613      * want to add a trigger_menu with exactly those three
1614      * chains (meaning exactly the same chain_IDs), then we don't have to
1615      * add a new trigger_menu
1616      * Since in the 'connection tables' the mapping (e.g.
1617      *
1618      * @param componentIDs Vector of component IDs sorted accordingly to the algorithm counter
1619      * @return Vector of matching ID's of the base name, Remember there can be more things referring to same Items with different own parameters
1620      */
1621     public Vector<Integer> matchingElementIDs(Vector<Integer> componentIDs) {
1622 
1623         String table_name = "HLT_TE_TO_CP";
1624         String base_name = "HTE2CP_TRIGGER_ELEMENT";
1625         String reference_name = "HTE2CP_COMPONENT";
1626 
1627         Vector<Integer> baseIDs = new Vector<Integer>(); // Output vector with base ID with matching references
1628 
1629         if (componentIDs == null || componentIDs.size() == 0) {
1630             return baseIDs;
1631         }
1632 
1633 
1634         StringBuffer queryList = new StringBuffer();
1635 
1636         int nReferences = componentIDs.size();
1637 
1638         for (int i = 0; i < nReferences; i++) {
1639             queryList.append("(HTE2CP_COMPONENT_ID=" + componentIDs.get(i) + " AND HTE2CP_ALGORITHM_COUNTER=" + i + ")");
1640             if (i < nReferences - 1) {
1641                 queryList.append(" OR ");
1642             }
1643         }
1644 
1645         String query = "SELECT DISTINCT " + base_name + "_ID FROM " + table_name + " WHERE " + queryList.toString();
1646 
1647         Vector<Integer> base_ids = new Vector<Integer>();
1648 
1649         try {
1650             //    System.out.println("MCL : " + query);
1651             Statement stmt2 = getConnection().createStatement();
1652             ResultSet rset = stmt2.executeQuery(query);
1653 
1654             while (rset.next()) {
1655                 base_ids.add(rset.getInt(1));
1656             }
1657             rset.close();
1658             stmt2.close();
1659         } catch (SQLException e) {
1660             logger.finer("Error finding base ID's");
1661             e.printStackTrace();
1662         }
1663 
1664         int nbase_ids = base_ids.size();
1665         if (nbase_ids <= 0) {
1666             // Base ID's is still empty and there was no result searching reference ID's
1667             return baseIDs;
1668         }
1669         Collections.sort(base_ids);
1670         // Do not use DISTINCT we need all the ID some of them can be doubled
1671         query = "SELECT " + reference_name + "_ID FROM " + table_name;
1672         query += " WHERE " + base_name + "_ID=? ORDER BY HTE2CP_ALGORITHM_COUNTER";
1673 
1674         try {
1675             PreparedStatement ps = getConnection().prepareStatement(query);
1676             // Now loop over found base ID's and compare found references
1677             for (int ibase_id = 0; ibase_id < nbase_ids; ibase_id++) {
1678 
1679                 // Address the database
1680                 ps.setInt(1, base_ids.get(ibase_id));
1681                 ResultSet rset = ps.executeQuery();
1682 
1683                 Vector<Integer> refIDs = new Vector<Integer>();
1684                 while (rset.next()) {
1685                     refIDs.add(rset.getInt(1));
1686                 }
1687 
1688                 // In case of matching references add base id into the output list
1689                 if (refIDs.equals(componentIDs)) {
1690                     baseIDs.add(base_ids.get(ibase_id));
1691                 }
1692                 rset.close();
1693             }
1694             ps.close();
1695         } catch (SQLException e) {
1696             logger.finer("Error finding children");
1697             e.printStackTrace();
1698         }
1699 
1700         return baseIDs;
1701     }
1702 
1703     public String fix_schema_name(String query) {
1704 
1705         String[] tableNames = TableNames.allTableName;
1706 
1707         if (getInitInfo().getdbTechnology().equals("MySQL") || getInitInfo().getTableName().equals("")) {
1708             return query;
1709         }
1710 
1711         String prefix = getInitInfo().getTableName().toUpperCase() + ".";
1712         
1713         for (int i = 0; i < tableNames.length; ++i) {
1714             query = query.replace(" " + tableNames[i], " " + prefix + tableNames[i]);
1715         }
1716 
1717         return query;
1718     }
1719 
1720     private int getSchemaVersion() throws SQLException {
1721         int version = -1;
1722         String query = "SELECT MAX(TS_ID) FROM TRIGGER_SCHEMA";
1723         query = fix_schema_name(query);
1724 
1725         //System.out.println(query);
1726 
1727         PreparedStatement ps = getConnection().prepareStatement(query);
1728         ResultSet rset = ps.executeQuery();
1729 
1730         while (rset.next()) {
1731             version = rset.getInt(1);
1732         }
1733 
1734         rset.close();
1735         ps.close();
1736         return version;
1737     }
1738     
1739     static boolean loadSchema2SqliteFile( String fname, ConnectionManager instance ) throws Exception {
1740         
1741         //see if the schema is in the jar file
1742         URL url1 = null;
1743         URL url2 = null;
1744         try{
1745             url1 = instance.getClass().getClassLoader().getResource("DBstartup");
1746             url1.getPath();
1747             url2 = instance.getClass().getClassLoader().getResource("sql/combined_schema.sql");
1748             url2.getPath();
1749         }catch(Exception ex){
1750             JOptionPane.showMessageDialog(null,"The jar file does not contain the schema.\n" +
1751                                                  "You need to make the TriggerTool in cmt",
1752                                                  "Schema missing", JOptionPane.ERROR_MESSAGE);
1753             return false;
1754         }
1755         
1756         //make DBStartup in the directory if not there already
1757         boolean DBsu_exists = (new File("DBstartup")).exists();
1758         if(!DBsu_exists){
1759             File DBstartup_file = new File("DBstartup");
1760             FileWriter os_DBstartup  = new FileWriter(DBstartup_file);
1761             InputStream is_DBstartup  = instance.getClass().getClassLoader().getResourceAsStream("DBstartup");
1762             BufferedReader in_DBstartup  = new BufferedReader(new InputStreamReader(is_DBstartup));
1763             String line_DB="";
1764             while((line_DB=in_DBstartup.readLine())!=null){
1765                 os_DBstartup.write(line_DB+"\n");
1766             }
1767             os_DBstartup.close();
1768             //DBstartup_file.setExecutable(true); 1.6 only!
1769         }
1770         
1771         //make combined_schema.sql in the directory
1772         boolean CS_exists = (new File("sql/combined_schema.sql")).exists();
1773         boolean dir_exists = (new File("sql")).exists();
1774         if(!CS_exists&&!dir_exists){
1775             (new File("sql")).mkdir();
1776             File CombSchema_file = new File("sql/combined_schema.sql");
1777             FileWriter os_CombSchema = new FileWriter(CombSchema_file);
1778             InputStream is_CombSchema = instance.getClass().getClassLoader().getResourceAsStream("sql/combined_schema.sql");
1779             BufferedReader in_CombSchema = new BufferedReader(new InputStreamReader(is_CombSchema));
1780             String line_CS="";
1781             while((line_CS=in_CombSchema.readLine())!=null){
1782                 os_CombSchema.write(line_CS+"\n");
1783             }
1784             os_CombSchema.close();
1785             //CombSchema_file.setExecutable(true); 1.6 only!
1786         }
1787         
1788         //now run dbstartup script which must now exist
1789         Runtime rt = Runtime.getRuntime();
1790         String args = "-t sqlite -f " + fname;
1791         //logger.info("DBStartUp args are: " + args);
1792         rt.exec("chmod 777 DBstartup");
1793         rt.exec("chmod 777 sql/combined_schema.sql");
1794         Process pr = rt.exec("./DBstartup " + args);
1795         
1796         pr.waitFor();
1797     
1798         return true;
1799     }
1800 }

source navigation ] diff markup ] identifier search ] general search ]

Due to the LXR bug, the updates fail sometimes to remove references to deleted files. The Saturday's full rebuilds fix these problems
This page was automatically generated by the LXR engine. Valid HTML 4.01!