Diff for /FM2SQL/src/Convert.java between versions 1.3 and 1.10

version 1.3, 2005/02/16 13:00:48 version 1.10, 2005/04/19 10:49:05
Line 23  import java.io.InputStream; Line 23  import java.io.InputStream;
 import java.io.InputStreamReader;  import java.io.InputStreamReader;
 import java.io.OutputStreamWriter;  import java.io.OutputStreamWriter;
 import java.io.PrintStream;  import java.io.PrintStream;
 import java.io.UnsupportedEncodingException;  
 import java.net.URL;  import java.net.URL;
 import java.sql.PreparedStatement;  import java.sql.PreparedStatement;
 import java.sql.ResultSet;  import java.sql.ResultSet;
Line 67  class Convert Line 66  class Convert
                 {                  {
                     buff.append(element).append(", ");                      buff.append(element).append(", ");
                     count++;                      count++;
                 }          } else
                 else  
                     buff.append(element);                      buff.append(element);
   
             }              }
Line 77  class Convert Line 75  class Convert
         }          }
     }      }
   
     /**
      * Helper class for pre/or post execution of SQLCommands
      * @author rogo
      *
      */
     public static class SQLCommand
     {
       private DBBean bean;
       private String command;
   
       public SQLCommand(DBBean bean, String command)
       {
         this.bean = bean;
         this.command = command;
       }
   
       public void executeCommand() throws SQLException, Exception
       {
         System.out.println("Executing command: \n");
         System.out.println(command);
   
         java.sql.Connection con = bean.getConnection();
         Statement stm = con.createStatement();
         stm.execute(command);
         stm.close();
       }
     }
   
     static DBBean bean = new DBBean();      static DBBean bean = new DBBean();
   
     static DBBean beanDest = new DBBean();      static DBBean beanDest = new DBBean();
Line 93  class Convert Line 119  class Convert
   
     final static int numIntervalls = 4;      final static int numIntervalls = 4;
   
     static boolean debug = false;    static boolean debug = !false;
   
     static boolean isGUI = true;      static boolean isGUI = true;
   
     /**
      * Vector for all SQLCommands to executed before any conversion action is performed
      */
     static Vector preSQLCommands = new Vector();
     /**
      * Vector for all SQLCommands to executed after any conversion action has been performed
      */
   
     static Vector postSQLCommands = new Vector();
   
     static final String versionID = new String("FM2SQL Version 0.9.1b\n");
   
     private static boolean noError = false;
   
     public static void main(String args[]) throws IOException      public static void main(String args[]) throws IOException
     {      {
         /*          /*
          * try { //byte[] b = "ö".getBytes("UTF-8"); //       * try { //byte[] b = "�".getBytes("UTF-8"); //
          * System.out.println("QueryString " +b[0]+" "+b[1]+(new           * System.out.println("QueryString " +b[0]+" "+b[1]+(new
          * String(b).getBytes()[0])+" "+new String(b).getBytes()[1]);           * String(b).getBytes()[0])+" "+new String(b).getBytes()[1]);
          * //System.out.println(new String(b,"UTF-8")); } catch           * //System.out.println(new String(b,"UTF-8")); } catch
          * (UnsupportedEncodingException e) { e.printStackTrace(); }           * (UnsupportedEncodingException e) { e.printStackTrace(); }
          */           */
       File tmpPath = new File(System.getProperty("java.io.tmpdir"));
         isGUI = false;          isGUI = false;
         FileOutputStream file = null;          FileOutputStream file = null;
         if (args.length != 1)          if (args.length != 1)
         {          {
         System.out.println(versionID);
             System.out.println("Usage: java Convert <xml config file>");              System.out.println("Usage: java Convert <xml config file>");
             System.exit(-1);              System.exit(-1);
         }          }
       File temp = null;
         try          try
         {          {
             File temp = File.createTempFile("fm2sql", ".txt");        temp = new File(tmpPath, "fm2sql.txt");
             file = new FileOutputStream(temp);        int count = 1;
         while (temp.exists())
         {
           temp = new File(tmpPath, "fm2sql" + generateSuffix(count++) + ".txt");
         }          }
         catch (FileNotFoundException e1)        file = new FileOutputStream(temp);
       } catch (FileNotFoundException e1)
         {          {
             e1.printStackTrace();              e1.printStackTrace();
         }          }
         PrintStream stream = new PrintStream(file, true);          PrintStream stream = new PrintStream(file, true);
       // write info for user to stdout
       System.out.println(versionID);
       System.out.println("Loading " + args[0] + "....");
       System.out.println("Log  will be written to " + temp.getCanonicalPath());
   
         if (!debug)          if (!debug)
         {          {
             System.setOut(stream);              System.setOut(stream);
             System.setErr(stream);              System.setErr(stream);
         }          }
       System.out.println(versionID);
       System.out.println("Using config file : " + args[0] + "....");
   
         StringBuffer sb = readXMLFile(args[0]);          StringBuffer sb = readXMLFile(args[0]);
         parseXMLConfig(sb);          parseXMLConfig(sb);
         if (!(new File(args[0]).exists()))          if (!(new File(args[0]).exists()))
             System.exit(0);      {
   
         System.exit(0);
       }
         System.out.println("Finished!");          System.out.println("Finished!");
         // convert("jdbc:fmpro:http://141.14.237.74:8050","jdbc:postgresql://erebos/test",null,null);          // convert("jdbc:fmpro:http://141.14.237.74:8050","jdbc:postgresql://erebos/test",null,null);
     }      }
   
     public static void convertBatch(DBBean source, DBBean destination, Vector names, Vector layouts, Vector selects, Vector creates, Vector ids, int mode, String delimiter) throws Exception    public static void convertBatch(DBBean source, DBBean destination, Vector names, Vector layouts,
         Vector selects, Vector creates, Vector ids, int mode, String delimiter) throws Exception
     {      {
         bean = source;          bean = source;
         beanDest = destination;          beanDest = destination;
Line 168  class Convert Line 227  class Convert
      * @param mode       * @param mode
      * @throws Exception       * @throws Exception
      */       */
     public static void update(String source, String destination, Vector names, Vector layouts, Vector selects, Vector creates, Vector ids, int mode) throws Exception    public static void update(String source, String destination, Vector names, Vector layouts,
         Vector selects, Vector creates, Vector ids, int mode) throws Exception
     {      {
   
         FM2SQL.ProgressDialog dialog = null;          FM2SQL.ProgressDialog dialog = null;
Line 204  class Convert Line 264  class Convert
                     String layout = (layouts.isEmpty()) ? "" : layouts.get(tbIndex).toString();                      String layout = (layouts.isEmpty()) ? "" : layouts.get(tbIndex).toString();
                     query = (selects != null) ? selects.get(tbIndex).toString() : query;                      query = (selects != null) ? selects.get(tbIndex).toString() : query;
                     // if vectors[1].get(i) != null)                      // if vectors[1].get(i) != null)
                     if (layout != "")            if (!layout.equals(""))
                     {                      {
               
                         query = addLayoutToQuery(names, query, tbIndex, layout);                          query = addLayoutToQuery(names, query, tbIndex, layout);
   
                     }                      }
Line 216  class Convert Line 277  class Convert
                     bean.getConnection();                      bean.getConnection();
                     bean.makeQuery(query, 0);                      bean.makeQuery(query, 0);
   
                 }          } catch (Exception e)
                 catch (Exception e)  
                 {                  {
                     System.out.println("Warning exception occured \n " + e);                      System.out.println("Warning exception occured \n " + e);
   
Line 230  class Convert Line 290  class Convert
                     String create = creates.get(tbIndex).toString().toLowerCase();                      String create = creates.get(tbIndex).toString().toLowerCase();
                     int fromIndex = create.indexOf("table") + 5;                      int fromIndex = create.indexOf("table") + 5;
                     int toIndex = create.indexOf("(");                      int toIndex = create.indexOf("(");
                     destTableName = create.substring(fromIndex, toIndex).replaceAll(beanDest.getQC(), "").trim();            destTableName = create.substring(fromIndex, toIndex).replaceAll(beanDest.getQC(), "")
                 .trim();
                     System.out.println("destTable " + destTableName);                      System.out.println("destTable " + destTableName);
   
                 }          } else
                 else  
                     destTableName = convertText(names.get(tbIndex).toString());                      destTableName = convertText(names.get(tbIndex).toString());
   
                 beanDest.setConnection(destination);                  beanDest.setConnection(destination);
Line 243  class Convert Line 303  class Convert
   
                 Vector tables = beanDest.getTableNames();                  Vector tables = beanDest.getTableNames();
   
                 System.out.println(names.get(tbIndex) + " " + tables.indexOf(convertText((String) names.get(tbIndex)))); // "//beanDest.getTypeNames());          System.out.println(names.get(tbIndex) + " "
               + tables.indexOf(convertText((String) names.get(tbIndex)))); // "//beanDest.getTypeNames());
                 tables = beanDest.getTableNames();                  tables = beanDest.getTableNames();
                 stm = beanDest.getConnection().createStatement();                  stm = beanDest.getConnection().createStatement();
   
Line 265  class Convert Line 326  class Convert
   
                 int size = bean.getColumnNames().size();                  int size = bean.getColumnNames().size();
                 for (int i = 0; i < size - 1; ++i)                  for (int i = 0; i < size - 1; ++i)
                     command.append(beanDest.getQC() + convertText((String) bean.getColumnNames().get(i)) + beanDest.getQC() + " = ? ,");            command.append(beanDest.getQC() + convertText((String) bean.getColumnNames().get(i))
                 + beanDest.getQC() + " = ? ,");
                 command.append(convertText((String) bean.getColumnNames().get(size - 1)) + " = ? ");                  command.append(convertText((String) bean.getColumnNames().get(size - 1)) + " = ? ");
                 command.append("WHERE " + convertText(ids.get(tbIndex).toString()) + " =  ?");                  command.append("WHERE " + convertText(ids.get(tbIndex).toString()) + " =  ?");
                 PreparedStatement pstm = beanDest.getConnection().prepareStatement(command.toString());                  PreparedStatement pstm = beanDest.getConnection().prepareStatement(command.toString());
Line 296  class Convert Line 358  class Convert
                 } // to for loop                  } // to for loop
   
             }              }
         }      } catch (Exception e)
         catch (Exception e)  
         {          {
             System.out.println("Error while connecting to database " + e);              System.out.println("Error while connecting to database " + e);
             if (isGUI)              if (isGUI)
             {              {
                 showExceptionDialog(dialog, command, e);                  showExceptionDialog(dialog, command, e);
             }        } else
             else  
             {              {
                 e.printStackTrace();                  e.printStackTrace();
   
Line 333  class Convert Line 393  class Convert
      * @param command       * @param command
      * @param e       * @param e
      */       */
     private static void showExceptionDialog(FM2SQL.ProgressDialog dialog, StringBuffer command, Exception e)    private static void showExceptionDialog(FM2SQL.ProgressDialog dialog, StringBuffer command,
         Exception e)
     {      {
         dialog.setVisible(false);          dialog.setVisible(false);
         dialog.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));          dialog.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
Line 354  class Convert Line 415  class Convert
         dialog = new FM2SQL.ProgressDialog(FM2SQL.fmInstance, bean);          dialog = new FM2SQL.ProgressDialog(FM2SQL.fmInstance, bean);
         dialog.setTitle("Conversion running ...");          dialog.setTitle("Conversion running ...");
         dialog.title.setText("Getting table data ...");          dialog.title.setText("Getting table data ...");
         dialog.setLocation(FM2SQL.fmInstance.getLocationOnScreen().x + (FM2SQL.fmInstance.getWidth() - 400) / 2, FM2SQL.fmInstance.getLocationOnScreen().y + (FM2SQL.fmInstance.getHeight() - 250) / 2);      dialog.setLocation(FM2SQL.fmInstance.getLocationOnScreen().x
           + (FM2SQL.fmInstance.getWidth() - 400) / 2, FM2SQL.fmInstance.getLocationOnScreen().y
           + (FM2SQL.fmInstance.getHeight() - 250) / 2);
         dialog.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));          dialog.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
         FM2SQL.fmInstance.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));          FM2SQL.fmInstance.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
         dialog.thread = Thread.currentThread();          dialog.thread = Thread.currentThread();
Line 378  class Convert Line 441  class Convert
      * @throws Exception       * @throws Exception
      */       */
   
     public static void convert(String source, String destination, Vector names, Vector layouts, Vector selects, Vector creates, Vector ids, int mode, String delimiter) throws Exception    public static void convert(String source, String destination, Vector names, Vector layouts,
         Vector selects, Vector creates, Vector ids, int mode, String delimiter) throws Exception
     {      {
       // TODO implement convert_temp mode!!! 
         FM2SQL.ProgressDialog dialog = null;          FM2SQL.ProgressDialog dialog = null;
   
         if (isGUI)          if (isGUI)
Line 423  class Convert Line 487  class Convert
                 try                  try
                 {                  {
                     String layout = (layouts.isEmpty()) ? "" : layouts.get(tbIndex).toString();                      String layout = (layouts.isEmpty()) ? "" : layouts.get(tbIndex).toString();
                     query = (selects != null) ? selects.get(tbIndex).toString() : "select * from " + bean.getQC() + names.get(tbIndex).toString() + bean.getQC();            query = (selects != null) ? selects.get(tbIndex).toString() : "select * from "
                     if (layout != "")                + bean.getQC() + names.get(tbIndex).toString() + bean.getQC();
             if (layout.intern() != "")
                     {                      {
                         query = addLayoutToQuery(names, query, tbIndex, layout);                          query = addLayoutToQuery(names, query, tbIndex, layout);
   
Line 438  class Convert Line 503  class Convert
                     bean.makeQuery(query, 50);                      bean.makeQuery(query, 50);
                     idField = ids.get(tbIndex).toString();                      idField = ids.get(tbIndex).toString();
   
                 }          } catch (Exception e)
                 catch (Exception e)  
                 {                  {
                     System.out.println("Warning exception occured \n " + e);                      System.out.println("Warning exception occured \n " + e);
   
Line 453  class Convert Line 517  class Convert
   
                 Vector tables = beanDest.getTableNames();                  Vector tables = beanDest.getTableNames();
                 // Collections.sort(tables);                  // Collections.sort(tables);
                 System.out.println(names.get(tbIndex) + " " + tables.indexOf(convertText((String) names.get(tbIndex)))); // "//beanDest.getTypeNames());          System.out.println(names.get(tbIndex) + " "
               + tables.indexOf(convertText((String) names.get(tbIndex)))); // "//beanDest.getTypeNames());
                 tables = beanDest.getTableNames();                  tables = beanDest.getTableNames();
                 // System.out.println(beanDest.getTableNames(beanDest.getCatalogs().get(2).toString()));                  // System.out.println(beanDest.getTableNames(beanDest.getCatalogs().get(2).toString()));
                 stm = beanDest.getConnection().createStatement();                  stm = beanDest.getConnection().createStatement();
Line 461  class Convert Line 526  class Convert
   
                 // determine destTableName from createStatement or from source                  // determine destTableName from createStatement or from source
                 // table name                  // table name
                 ConversionProperties prop = getFieldNamesAndDestTableName(creates.get(tbIndex).toString(), query, names.get(tbIndex).toString());          ConversionProperties prop = getFieldNamesAndDestTableName(creates.get(tbIndex).toString(),
               query, names.get(tbIndex).toString());
                 destTableName = prop.destTableName;                  destTableName = prop.destTableName;
           if (mode == Convert.DataBase.CONVERT_TEMP_MODE)
           {
             destTableName += "_temp";
           }
                 fieldNames = prop.fieldNames;                  fieldNames = prop.fieldNames;
                 if (mode == Convert.DataBase.CONVERT_MODE)          if (mode == Convert.DataBase.CONVERT_MODE || mode == Convert.DataBase.CONVERT_TEMP_MODE)
                 {                  {
   
                     if (tables.indexOf(destTableName) >= 0)                      if (tables.indexOf(destTableName) >= 0)
Line 472  class Convert Line 542  class Convert
                         stm.executeUpdate("drop table " + beanDest.getQC() + destTableName + beanDest.getQC());                          stm.executeUpdate("drop table " + beanDest.getQC() + destTableName + beanDest.getQC());
                         tables.remove(destTableName);                          tables.remove(destTableName);
                         System.out.println("dropped table" + destTableName);                          System.out.println("dropped table" + destTableName);
   
                     }                      }
                     if ((tables.indexOf(destTableName) < 0))                      if ((tables.indexOf(destTableName) < 0))
                     {                      {
   
                         if (creates.get(tbIndex).equals("") || creates.get(tbIndex).toString().toLowerCase().indexOf("create") < 0)              if (creates.get(tbIndex).equals("")
                   || creates.get(tbIndex).toString().toLowerCase().indexOf("create") < 0)
                         {                          {
                             System.out.println("Warning empty or invalid create statement - creating one for you\n");                System.out
                     .println("Warning empty or invalid create statement - creating one for you\n");
   
                             command = new StringBuffer(50);                              command = new StringBuffer(50);
                             command.append("CREATE TABLE ");                              command.append("CREATE TABLE ");
                             command.append(beanDest.getQC());                              command.append(beanDest.getQC());
                             command.append(convertText((String) names.get(tbIndex)));                command.append(destTableName);//convertText((String) names.get(tbIndex)));
                             command.append(beanDest.getQC());                              command.append(beanDest.getQC());
                             command.append("(");                              command.append("(");
                             String type = null;                              String type = null;
Line 497  class Convert Line 568  class Convert
                                 type = (type.equals("NUMBER")) ? "INT4" : type;                                  type = (type.equals("NUMBER")) ? "INT4" : type;
                                 type = (type.equals("CONTAINER")) ? "TEXT" : type;                                  type = (type.equals("CONTAINER")) ? "TEXT" : type;
   
                                 command.append(beanDest.getQC() + convertText((String) columnNames.get(i)) + beanDest.getQC() + " " + type + ", ");                  command.append(beanDest.getQC() + convertText((String) columnNames.get(i))
                       + beanDest.getQC() + " " + type + ", ");
                             }                              }
                             type = bean.metaData.getColumnTypeName(columnNames.size());                              type = bean.metaData.getColumnTypeName(columnNames.size());
                             type = (type.equals("NUMBER")) ? "INT4" : type;                              type = (type.equals("NUMBER")) ? "INT4" : type;
                             type = (type.equals("CONTAINER")) ? "TEXT" : type;                              type = (type.equals("CONTAINER")) ? "TEXT" : type;
                             command.append(beanDest.getQC() + convertText((String) columnNames.get(columnNames.size() - 1)) + beanDest.getQC() + " " + type);                command.append(beanDest.getQC()
                     + convertText((String) columnNames.get(columnNames.size() - 1))
                     + beanDest.getQC() + " " + type);
                             command.append(" )");                              command.append(" )");
   
                         }              } else
                         else  
                             command = new StringBuffer().append(creates.get(tbIndex).toString().toLowerCase());                              command = new StringBuffer().append(creates.get(tbIndex).toString().toLowerCase());
                         stm.executeUpdate(command.toString());                          stm.executeUpdate(command.toString());
   
Line 534  class Convert Line 607  class Convert
                 command.append(") ");                  command.append(") ");
   
                 command.append(" values ( ");                  command.append(" values ( ");
   
                 // add a question marks for every field                  // add a question marks for every field
                 for (int i = 0; i < bean.getColumnNames().size() - 1; ++i)                  for (int i = 0; i < bean.getColumnNames().size() - 1; ++i)
                     command.append("?,");                      command.append("?,");
Line 559  class Convert Line 631  class Convert
                             dialog.title.setText("Check if data  is available");                              dialog.title.setText("Check if data  is available");
                         else if (dialog != null)                          else if (dialog != null)
                             dialog.title.setText("Check if more  data  is available");                              dialog.title.setText("Check if more  data  is available");
                         myIds = bean.getIDVector(ids.get(tbIndex).toString(), (String) names.get(tbIndex), tempQuery, numHits);              myIds = bean.getIDVector(ids.get(tbIndex).toString(), (String) names.get(tbIndex),
                   tempQuery, numHits);
                         if (myIds.isEmpty())                          if (myIds.isEmpty())
                             break;                              break;
                         vec = new Vector(myIds);                          vec = new Vector(myIds);
                         rowCount = vec.size();                          rowCount = vec.size();
                         System.out.println("ID LIST SIZE " + Math.round((double) myIds.size() / (double) numIntervalls) + " " + myIds.size());              System.out.println("ID LIST SIZE "
                   + Math.round((double) myIds.size() / (double) numIntervalls) + " " + myIds.size());
                         deltaID = (int) Math.round((double) myIds.size() / (double) numIntervalls);                          deltaID = (int) Math.round((double) myIds.size() / (double) numIntervalls);
                         if (vec.size() <= numIntervalls)                          if (vec.size() <= numIntervalls)
                         {                          {
Line 575  class Convert Line 649  class Convert
                         {                          {
                             System.out.println(vec.get(k) + " " + vec.get(k + deltaID) + " " + vec.lastElement());                              System.out.println(vec.get(k) + " " + vec.get(k + deltaID) + " " + vec.lastElement());
                             if (query.indexOf("where") > 0)                              if (query.indexOf("where") > 0)
                                 tempQuery = query + " and " + tempID + ">='" + vec.get(k) + "' and " + tempID + "<='" + vec.get(k + deltaID) + "'";                  tempQuery = query + " and " + tempID + ">='" + vec.get(k) + "' and " + tempID
                       + "<='" + vec.get(k + deltaID) + "'";
                             else                              else
                                 tempQuery = query + " where " + tempID + ">='" + vec.get(k) + "' and " + tempID + "<='" + vec.get(k + deltaID) + "'";                  tempQuery = query + " where " + tempID + ">='" + vec.get(k) + "' and " + tempID
                       + "<='" + vec.get(k + deltaID) + "'";
                             System.out.println(tempQuery);                              System.out.println(tempQuery);
                             if (dialog != null)                              if (dialog != null)
                                 dialog.title.setText("Reading table data ...");                                  dialog.title.setText("Reading table data ...");
Line 595  class Convert Line 671  class Convert
                             System.out.println("fits");                              System.out.println("fits");
                         else                          else
                         {                          {
                             System.out.println(" last intervall from " + vec.get(endIndex) + " " + vec.lastElement());                System.out.println(" last intervall from " + vec.get(endIndex) + " "
                     + vec.lastElement());
   
                             if (query.indexOf("where") > 0)                              if (query.indexOf("where") > 0)
                                 tempQuery = query + " and " + tempID + ">='" + vec.get(endIndex) + "' and " + tempID + "<='" + vec.lastElement() + "'";                  tempQuery = query + " and " + tempID + ">='" + vec.get(endIndex) + "' and "
                       + tempID + "<='" + vec.lastElement() + "'";
                             else                              else
                                 tempQuery = query + " where " + tempID + ">='" + vec.get(endIndex) + "' and " + tempID + "<='" + vec.lastElement() + "'";                  tempQuery = query + " where " + tempID + ">='" + vec.get(endIndex) + "' and "
                       + tempID + "<='" + vec.lastElement() + "'";
                             System.out.println(tempQuery);                              System.out.println(tempQuery);
                             if (dialog != null)                              if (dialog != null)
                                 dialog.title.setText("Reading table data ...");                                  dialog.title.setText("Reading table data ...");
Line 618  class Convert Line 697  class Convert
                     }                      }
                     long endTime = System.currentTimeMillis();                      long endTime = System.currentTimeMillis();
                     System.out.println("Time for incremental convert elapsed " + (endTime - startTime));                      System.out.println("Time for incremental convert elapsed " + (endTime - startTime));
                 }          } else
                 else  
                 {                  {
                     // read and write all in one big chunk                      // read and write all in one big chunk
                     long startTime = System.currentTimeMillis();                      long startTime = System.currentTimeMillis();
   
                     bean.makeQuery(query, 0);                      bean.makeQuery(query, 0);
             System.err.println("query for whole table done");
                     command = writeDatainDestTable(dialog, command, j, pstm, rowCount, delimiter);                      command = writeDatainDestTable(dialog, command, j, pstm, rowCount, delimiter);
                     long endTime = System.currentTimeMillis();                      long endTime = System.currentTimeMillis();
                     System.out.println("Time for old convert elapsed " + (endTime - startTime));                      System.out.println("Time for old convert elapsed " + (endTime - startTime));
Line 632  class Convert Line 711  class Convert
                 }                  }
                 if (isGUI)                  if (isGUI)
                     resetGUI(dialog);                      resetGUI(dialog);
           noError = true;
             }              }
         }      } catch (Exception e)
         catch (Exception e)  
         {          {
             System.out.println("Error while connecting to database " + e);        System.out.println("Error while connecting to database " + e.getMessage());
         noError = false;
             if (isGUI)              if (isGUI)
             {              {
                 showExceptionDialog(dialog, command, e);                  showExceptionDialog(dialog, command, e);
                 resetGUI(dialog);                  resetGUI(dialog);
             }        } else
             else  
             {              {
                 e.printStackTrace();                  e.printStackTrace();
   
             }              }
       } catch (Error e)
       {
         System.out.println(e);
         e.printStackTrace();
         }          }
   
     }      }
Line 698  class Convert Line 781  class Convert
      * @throws Exception       * @throws Exception
      * @throws SQLException       * @throws SQLException
      */       */
     private static StringBuffer writeDatainDestTable(FM2SQL.ProgressDialog dialog, StringBuffer command, int j, PreparedStatement pstm, int rowCount, String delimiter) throws Exception, SQLException    private static StringBuffer writeDatainDestTable(FM2SQL.ProgressDialog dialog,
         StringBuffer command, int j, PreparedStatement pstm, int rowCount, String delimiter)
         throws Exception, SQLException
     {      {
         Vector row;          Vector row;
         while ((row = bean.getNextRow()) != null)          while ((row = bean.getNextRow()) != null)
Line 716  class Convert Line 801  class Convert
                 if (obj instanceof Double)                  if (obj instanceof Double)
                 {                  {
                     pstm.setDouble(k + 1, ((Double) obj).doubleValue());                      pstm.setDouble(k + 1, ((Double) obj).doubleValue());
                 }          } else if (!str.equals("NULL"))
                 else if (!str.equals("NULL"))  
                     pstm.setString(k + 1, str);                      pstm.setString(k + 1, str);
                 else                  else
                     pstm.setNull(k + 1, Types.NULL);                      pstm.setNull(k + 1, Types.NULL);
Line 755  class Convert Line 839  class Convert
             {              {
                 alterMe.setCharAt(j, '_');                  alterMe.setCharAt(j, '_');
                 // if(j<length-1) j=j+1;                  // if(j<length-1) j=j+1;
             }        } else if (alterMe.charAt(j) == '_')
             else if (alterMe.charAt(j) == '_')  
             {              {
   
                 if (alterMe.charAt(j + 1) == '_')                  if (alterMe.charAt(j + 1) == '_')
                     alterMe.deleteCharAt(j);                      alterMe.deleteCharAt(j);
                 length = length - 1;                  length = length - 1;
                 // if(j<length-1) j=j+1;                  // if(j<length-1) j=j+1;
             }        } else if (alterMe.charAt(j) == 'ä')
             else if (alterMe.charAt(j) == 'ä')  
             {              {
                 alterMe.setCharAt(j, 'a');                  alterMe.setCharAt(j, 'a');
                 alterMe.insert(j + 1, "e");                  alterMe.insert(j + 1, "e");
                 length = length + 1;                  length = length + 1;
                 if (j < length - 1)                  if (j < length - 1)
                     j = j + 1;                      j = j + 1;
             }        } else if (alterMe.charAt(j) == 'ö')
             else if (alterMe.charAt(j) == 'ö')  
             {              {
                 alterMe.setCharAt(j, 'o');                  alterMe.setCharAt(j, 'o');
                 alterMe.insert(j + 1, "e");                  alterMe.insert(j + 1, "e");
                 length = length + 1;                  length = length + 1;
                 if (j < length - 1)                  if (j < length - 1)
                     j = j + 1;                      j = j + 1;
             }        } else if (alterMe.charAt(j) == 'ü')
             else if (alterMe.charAt(j) == 'ü')  
             {              {
                 alterMe.setCharAt(j, 'u');                  alterMe.setCharAt(j, 'u');
                 alterMe.insert(j + 1, "e");                  alterMe.insert(j + 1, "e");
                 length = length + 1;                  length = length + 1;
                 if (j < length - 1)                  if (j < length - 1)
                     j = j + 1;                      j = j + 1;
             }        } else if (alterMe.charAt(j) == 'ß')
             else if (alterMe.charAt(j) == 'ß')  
             {              {
                 alterMe.setCharAt(j, 's');                  alterMe.setCharAt(j, 's');
                 alterMe.insert(j + 1, "s");                  alterMe.insert(j + 1, "s");
                 length = length + 1;                  length = length + 1;
                 if (j < length - 1)                  if (j < length - 1)
                     j = j + 1;                      j = j + 1;
             }        } else if (alterMe.charAt(j) == ':')
             else if (alterMe.charAt(j) == ':')  
             {              {
                 if (j < length - 1)                  if (j < length - 1)
                 {                  {
Line 811  class Convert Line 889  class Convert
                     if (j < length - 1)                      if (j < length - 1)
                         j = j + 1;                          j = j + 1;
                 }                  }
             }        } else if (alterMe.charAt(j) == '-')
             else if (alterMe.charAt(j) == '-')  
             {              {
                 alterMe.setCharAt(j, '_');                  alterMe.setCharAt(j, '_');
   
             }        } else if (alterMe.charAt(j) == '?')
             else if (alterMe.charAt(j) == '?')  
             {              {
                 // changed ? to _ because of update statement                  // changed ? to _ because of update statement
                 alterMe.setCharAt(j, '_');                  alterMe.setCharAt(j, '_');
                 // length = length + 1;                  // length = length + 1;
                 // j=j+1;                  // j=j+1;
                 System.out.println(alterMe);                  System.out.println(alterMe);
             }        } else if (alterMe.charAt(j) == '.')
             else if (alterMe.charAt(j) == '.')  
             {              {
                 if (j == length - 1)                  if (j == length - 1)
                 {                  {
                     alterMe.delete(j, j);                      alterMe.delete(j, j);
                     length--;                      length--;
                 }          } else
                 else  
                     alterMe.setCharAt(j, '_');                      alterMe.setCharAt(j, '_');
             }              }
   
Line 864  class Convert Line 938  class Convert
                 if (j < length - 1)                  if (j < length - 1)
                     j = j + 1;                      j = j + 1;
   
             }        } else if (alterMe.charAt(j) == '<')
             else if (alterMe.charAt(j) == '<')  
             {              {
                 alterMe.setCharAt(j, '&');                  alterMe.setCharAt(j, '&');
                 alterMe.insert(j + 1, "lt;");                  alterMe.insert(j + 1, "lt;");
Line 944  class Convert Line 1017  class Convert
         try          try
         {          {
             databases = getXMLConfig(sb);              databases = getXMLConfig(sb);
   
         // destination DataBase object
         DataBase dbDest = ((DataBase) databases.lastElement());
   
             DBBean database = ((DataBase) databases.lastElement()).bean;              DBBean database = ((DataBase) databases.lastElement()).bean;
             databases.remove(databases.size() - 1);              databases.remove(databases.size() - 1);
   
         for (Iterator iterator = dbDest.preCommands.iterator(); iterator.hasNext();)
         {
           SQLCommand sqlCommand = (SQLCommand) iterator.next();
           sqlCommand.executeCommand();
         }
   
             // databases.add(database);              // databases.add(database);
             for (Iterator iter = databases.iterator(); iter.hasNext();)              for (Iterator iter = databases.iterator(); iter.hasNext();)
             {              {
                 DataBase db = (DataBase) iter.next();                  DataBase db = (DataBase) iter.next();
           for (Iterator iterator = db.preCommands.iterator(); iterator.hasNext();)
           {
             SQLCommand sqlCommand = (SQLCommand) iterator.next();
             sqlCommand.executeCommand();
           }
                 int mode = db.mode;                  int mode = db.mode;
           if (mode == DataBase.CONVERT_TEMP_MODE)
           {
             convertBatch(db.bean, database, db.tables, db.layouts, db.selects, db.creates, db.ids,
                 mode, db.delimiter);
             if (noError)
             {
               System.out.println("no Error occured ");
               //                db.bean.setURL(database.url);
               //                db.bean.setUserAndPasswd(database.user,database.passwd);
               //
               //                Convert.user = db.bean.user;
               //                Convert.passwd = db.bean.passwd;
               //                userDest = database.user;
               //                passwdDest = database.passwd;
               //                synchronize(db.bean.url, database.url, db.tables, db.layouts, db.selects, db.creates,
               //                    db.ids, mode, db.delimiter, new Vector(db.htIndex.values()));
             }
           }
                 if (mode == DataBase.CONVERT_MODE || mode == DataBase.APPEND_MODE)                  if (mode == DataBase.CONVERT_MODE || mode == DataBase.APPEND_MODE)
                     convertBatch(db.bean, database, db.tables, db.layouts, db.selects, db.creates, db.ids, mode, db.delimiter);            convertBatch(db.bean, database, db.tables, db.layouts, db.selects, db.creates, db.ids,
                 mode, db.delimiter);
                 else if (mode == DataBase.UPDATE_MODE)                  else if (mode == DataBase.UPDATE_MODE)
                 {                  {
   
Line 961  class Convert Line 1069  class Convert
                     userDest = database.user;                      userDest = database.user;
                     passwdDest = database.passwd;                      passwdDest = database.passwd;
   
                     update(db.bean.url, database.url, db.tables, db.layouts, db.selects, db.creates, db.ids, mode);            update(db.bean.url, database.url, db.tables, db.layouts, db.selects, db.creates, db.ids,
                 }                mode);
                 else if (mode == DataBase.SYNCHRONIZE_MODE)          } else if (mode == DataBase.SYNCHRONIZE_MODE)
                 {                  {
                     Convert.user = db.bean.user;                      Convert.user = db.bean.user;
                     Convert.passwd = db.bean.passwd;                      Convert.passwd = db.bean.passwd;
                     userDest = database.user;                      userDest = database.user;
                     passwdDest = database.passwd;                      passwdDest = database.passwd;
   
                     synchronize(db.bean.url, database.url, db.tables, db.layouts, db.selects, db.creates, db.ids, mode, db.delimiter, new Vector(db.htIndex.values()));            synchronize(db.bean.url, database.url, db.tables, db.layouts, db.selects, db.creates,
                 db.ids, mode, db.delimiter, new Vector(db.htIndex.values()));
                 }                  }
           for (Iterator iterator = db.postCommands.iterator(); iterator.hasNext();)
           {
             SQLCommand sqlCommand = (SQLCommand) iterator.next();
             sqlCommand.executeCommand();
             }              }
   
         }          }
         catch (Exception e)        for (Iterator iterator = dbDest.postCommands.iterator(); iterator.hasNext();)
         {
           SQLCommand sqlCommand = (SQLCommand) iterator.next();
           sqlCommand.executeCommand();
         }
   
       } catch (Exception e)
         {          {
   
             e.printStackTrace();              e.printStackTrace();
Line 1002  class Convert Line 1121  class Convert
         Vector selects = new Vector();          Vector selects = new Vector();
         Vector creates = new Vector();          Vector creates = new Vector();
         Vector ids = new Vector();          Vector ids = new Vector();
       Vector preSQLCommands = new Vector();
       Vector postSQLCommands = new Vector();
   
         String delimiter = "|";          String delimiter = "|";
         int mode = -1;          int mode = -1;
         try          try
Line 1021  class Convert Line 1143  class Convert
                 selects = new Vector();                  selects = new Vector();
                 creates = new Vector();                  creates = new Vector();
                 ids = new Vector();                  ids = new Vector();
           preSQLCommands = new Vector();
           postSQLCommands = new Vector();
   
                 // parse dataBase                  // parse dataBase
                 Node node = root.find("convert/source/database/url", new int[]                  Node node = root.find("convert/source/database/url", new int[]
                 {1, 1, i, 1});                  {1, 1, i, 1});
Line 1034  class Convert Line 1159  class Convert
                 {1, 1, i, 1, 1});                  {1, 1, i, 1, 1});
                 Node delimiterNode = root.find("convert/source/database/delimiter", new int[]                  Node delimiterNode = root.find("convert/source/database/delimiter", new int[]
                 {1, 1, i, 1, 1});                  {1, 1, i, 1, 1});
                 Node useNormanToUnicodeMapper = root.find("convert/source/database/usenormantounicodemapper", new int[]  
           Node commandNodes = root.find("convert/source/database/sqlcommands", new int[]
           { 1, 1, i, 1, 1 });
           if (commandNodes != null)
           {
             parseCommandNode(commandNodes, database, preSQLCommands, postSQLCommands);
           }
           Node useNormanToUnicodeMapper = root.find(
               "convert/source/database/usenormantounicodemapper", new int[]
                 {1, 1, i, 1, 1});                  {1, 1, i, 1, 1});
   
                 if (delimiterNode != null)                  if (delimiterNode != null)
                     delimiter = delimiterNode.getCharacters();                      delimiter = delimiterNode.getCharacters();
                 if (useNormanToUnicodeMapper != null)                  if (useNormanToUnicodeMapper != null)
                 {                  {
                     database.setUseNormanToUnicodeMapper(Boolean.valueOf(useNormanToUnicodeMapper.getCharacters()).booleanValue());            database.setUseNormanToUnicodeMapper(Boolean.valueOf(
                     System.out.println("useMapper " + Boolean.valueOf(useNormanToUnicodeMapper.getCharacters().trim()).booleanValue());                useNormanToUnicodeMapper.getCharacters()).booleanValue());
             System.out.println("useMapper "
                 + Boolean.valueOf(useNormanToUnicodeMapper.getCharacters().trim()).booleanValue());
                 }                  }
   
                 if (node3 == null)                  if (node3 == null)
Line 1077  class Convert Line 1212  class Convert
   
                 else if (modeString.equals("synchronize"))                  else if (modeString.equals("synchronize"))
                     mode = DataBase.SYNCHRONIZE_MODE;                      mode = DataBase.SYNCHRONIZE_MODE;
           else if (modeString.equals("convert_temp"))
             mode = DataBase.CONVERT_TEMP_MODE;
   
                 // if(node3!=null)                  // if(node3!=null)
                 // System.out.println(node3.name);                  // System.out.println(node3.name);
   
Line 1092  class Convert Line 1230  class Convert
                     {1, 1, i, j, 1});                      {1, 1, i, j, 1});
                     Node node6 = root.find("convert/source/database/table/create", new int[]                      Node node6 = root.find("convert/source/database/table/create", new int[]
                     {1, 1, i, j, 1});                      {1, 1, i, j, 1});
   
                     if (node4 != null)                      if (node4 != null)
                         System.out.println(node4.name + " " + node4.attributes.get("layout").equals(""));                          System.out.println(node4.name + " " + node4.attributes.get("layout").equals(""));
                     if (node5 != null)                      if (node5 != null)
Line 1117  class Convert Line 1256  class Convert
                         id = "";                          id = "";
                     if (name.equals(""))                      if (name.equals(""))
                         throw new Error("parse error table tag attribute must not be empty");                          throw new Error("parse error table tag attribute must not be empty");
                     tables.add(name);            tables.add(name.intern());
                     layouts.add(layout);            layouts.add(layout.intern());
                     ids.add(id);            ids.add(id.intern());
                     String query = (node5 == null) ? "" : node5.getCharacters();                      String query = (node5 == null) ? "" : node5.getCharacters();
                     if (query.equals(""))                      if (query.equals(""))
                         System.err.println("Warning empty select tag or  select tag missing !!");                          System.err.println("Warning empty select tag or  select tag missing !!");
                     query = (query.equals("")) ? "select * from " + database.getQC() + name + database.getQC() : query;            query = (query.equals("")) ? "select * from " + database.getQC() + name
                 + database.getQC() : query;
                     selects.add(query);                      selects.add(query);
                     if (node6 != null)                      if (node6 != null)
                         creates.add(node6.getCharacters().trim());                          creates.add(node6.getCharacters().trim());
Line 1133  class Convert Line 1273  class Convert
                 }                  }
                 DataBase dataBase = new DataBase(database, tables, layouts, selects, creates, ids, mode);                  DataBase dataBase = new DataBase(database, tables, layouts, selects, creates, ids, mode);
                 dataBase.delimiter = delimiter;                  dataBase.delimiter = delimiter;
           dataBase.preCommands = new Vector(preSQLCommands);
           dataBase.postCommands = new Vector(postSQLCommands);
                 databases.add(dataBase);                  databases.add(dataBase);
             }              }
             DBBean database = new DBBean();              DBBean database = new DBBean();
   
         preSQLCommands.clear();
         postSQLCommands.clear();
   
             // parse dataBase              // parse dataBase
             Node node = root.find("convert/destination/database/url", new int[]              Node node = root.find("convert/destination/database/url", new int[]
             {1, 1, 1, 1});              {1, 1, 1, 1});
Line 1143  class Convert Line 1289  class Convert
             {1, 1, 1, 1, 1});              {1, 1, 1, 1, 1});
             Node node2 = root.find("convert/destination/database/password", new int[]              Node node2 = root.find("convert/destination/database/password", new int[]
             {1, 1, 1, 1, 1});              {1, 1, 1, 1, 1});
         Node commandNodes = root.find("convert/destination/database/sqlcommands", new int[]
         { 1, 1, 1, 1, 1 });
         if (commandNodes != null)
         {
           parseCommandNode(commandNodes, database, preSQLCommands, postSQLCommands);
         }
   
             String url = node.getCharacters();              String url = node.getCharacters();
             String user = node1.getCharacters();              String user = node1.getCharacters();
             String password = node2.getCharacters();              String password = node2.getCharacters();
             System.out.println(url);              System.out.println(url);
             database.setURL(url.trim());              database.setURL(url.trim());
             database.setUserAndPasswd(user.trim(), password.trim());              database.setUserAndPasswd(user.trim(), password.trim());
             databases.add(new DataBase(database, null, null, null, null, null, 0));        DataBase db = new DataBase(database, new Vector(), null, null, null, null, 0);
         }        databases.add(db);
         catch (Exception e)        db.preCommands = new Vector(preSQLCommands);
         db.postCommands = new Vector(postSQLCommands);
   
       } catch (Exception e)
         {          {
             // TODO Auto-generated catch block  
             e.printStackTrace();              e.printStackTrace();
         }          }
         return databases;          return databases;
     }      }
   
     /**
      *
      * @param commandNode
      * @param database
      * @param preSQLCommands 
      * @param postSQLCommand 
      */
     private static void parseCommandNode(Node commandNode, DBBean database,
         java.util.Vector preSQLCommands, java.util.Vector postSQLCommands)
     {
       // System.out.println(commandNode.name + " " + countNodes(commandNode));
       int numCommands = commandNode.contents.length();
       for (int j = 0; j < numCommands; ++j)
       {
         Node node = (Node) commandNode.contents.v.elementAt(j);
         if (node.type.equals("element"))
         {
           // System.out.println(node.name + " " + node.getCharacters() + database);
           String execute = node.attributes.get("execute").toString();
           if (execute.equals("before"))
           {
             preSQLCommands.add(new SQLCommand(database, node.getCharacters()));
           }
           if (execute.equals("after"))
           {
             postSQLCommands.add(new SQLCommand(database, node.getCharacters()));
           }
   
         }
   
       }
     }
   
     private static int countNodes(Node tempNode)      private static int countNodes(Node tempNode)
     {      {
         int length = 0;          int length = 0;
Line 1171  class Convert Line 1359  class Convert
                     length++;                      length++;
                 if (node.name.equals("table"))                  if (node.name.equals("table"))
                     length++;                      length++;
           if (node.name.equals("sqlcommand"))
             length++;
   
             }              }
   
             // System.out.println(((Node)tempNode.contents.v.elementAt(i)).attributes+"              // System.out.println(((Node)tempNode.contents.v.elementAt(i)).attributes+"
Line 1213  class Convert Line 1404  class Convert
             {              {
                 URL url = new URL(xmlFile);                  URL url = new URL(xmlFile);
                 stream = url.openStream();                  stream = url.openStream();
             }        } else
             else  
                 // read XML Metadata from a file                  // read XML Metadata from a file
                 stream = new FileInputStream(xmlFile);                  stream = new FileInputStream(xmlFile);
             InputStreamReader isr = new InputStreamReader(stream, "UTF-8");              InputStreamReader isr = new InputStreamReader(stream, "UTF-8");
Line 1226  class Convert Line 1416  class Convert
                 sb.append(ch);                  sb.append(ch);
                 // System.out.print((char)c);                  // System.out.print((char)c);
             }              }
         }      } catch (Exception e)
         catch (Exception e)  
         {          {
             e.printStackTrace();              e.printStackTrace();
         } finally          } finally
Line 1236  class Convert Line 1425  class Convert
             try              try
             {              {
                 stream.close();                  stream.close();
             }        } catch (IOException e1)
             catch (IOException e1)  
             {              {
                 // TODO Auto-generated catch block                  // TODO Auto-generated catch block
                 e1.printStackTrace();                  e1.printStackTrace();
Line 1288  class Convert Line 1476  class Convert
   
         Vector layouts;          Vector layouts;
   
         Vector tables;      Vector tables = new Vector();
   
         Vector ids;          Vector ids;
   
         String delimiter = "//";          String delimiter = "//";
   
       Vector preCommands;
       Vector postCommands;
   
         /**          /**
          * maps table name to index fields           * maps table name to index fields
          */           */
Line 1311  class Convert Line 1502  class Convert
   
         final static int SYNCHRONIZE_MODE = 5;          final static int SYNCHRONIZE_MODE = 5;
   
       final static int CONVERT_TEMP_MODE = 6;
   
         int mode = -1;          int mode = -1;
   
         public DataBase(DBBean bean, Vector tables, Vector layouts, Vector selects, Vector creates, Vector ids, int mode)      public DataBase(DBBean bean, Vector tables, Vector layouts, Vector selects, Vector creates,
           Vector ids, int mode)
         {          {
             this.bean = bean;              this.bean = bean;
             this.tables = tables;              this.tables = tables;
Line 1363  class Convert Line 1557  class Convert
                 modeString = "synchronize";                  modeString = "synchronize";
   
             buffr.write("      <mode>" + modeString + "</mode>\n");              buffr.write("      <mode>" + modeString + "</mode>\n");
             buffr.write("      <usenormantounicodemapper>" + useNormanToUnicodeMapper + "</usenormantounicodemapper>\n");        buffr.write("      <usenormantounicodemapper>" + useNormanToUnicodeMapper
             + "</usenormantounicodemapper>\n");
         if (preCommands != null || postCommands != null)
         {
           int count = 0;
   
           buffr.write("      <sqlcommands> \n");
   
           if (preCommands != null)
           {
             while (count < preCommands.size())
             {
               SQLCommand sqlcommand = (SQLCommand) preCommands.get(count);
               buffr.write("        <sqlcommand execute=\"before\">" + sqlcommand.command
                   + "</sqlcommand>\n");
               count++;
             }
           }
           if (postCommands != null)
           {
             count = 0;
             while (count < postCommands.size())
             {
               SQLCommand sqlcommand = (SQLCommand) postCommands.get(count);
   
               buffr.write("        <sqlcommand execute=\"after\">" + sqlcommand.command
                   + "</sqlcommand>\n");
               count++;
             }
           }
           buffr.write("      </sqlcommands> \n");
   
         }
             int index = 0;              int index = 0;
             while (index < tables.size())              while (index < tables.size())
             {              {
Line 1376  class Convert Line 1601  class Convert
                 IndexList indexList = (IndexList) htIndex.get(table);                  IndexList indexList = (IndexList) htIndex.get(table);
                 if (indexList == null)                  if (indexList == null)
                     indexList = new IndexList();                      indexList = new IndexList();
                 buffr.write("      <table name = \"" + table + "\" layout = \"" + layout + "\" id = \"" + id + "\" indexList =\"" + indexList + "\">\n");          buffr.write("      <table name = \"" + table + "\" layout = \"" + layout + "\" id = \""
               + id + "\" indexList =\"" + indexList + "\">\n");
                 buffr.write("         <select>" + convertToEntities(select) + "</select>\n");                  buffr.write("         <select>" + convertToEntities(select) + "</select>\n");
                 if (!create.equals(""))                  if (!create.equals(""))
                     buffr.write("         <create>" + create + "         </create>\n");                      buffr.write("         <create>" + create + "         </create>\n");
Line 1406  class Convert Line 1632  class Convert
   
     }      }
   
     public static String convertToUTF8(Object command)    public static void writeConfig(String file, DataBase source, DataBase destination)
     {        throws Exception
         String str = null;  
         try  
         {  
             str = new String(command.toString().getBytes("UTF-8"));  
         }  
         catch (UnsupportedEncodingException e)  
         {  
             // TODO Auto-generated catch block  
             e.printStackTrace();  
         }  
         return str;  
     }  
   
     public static void writeConfig(String file, DataBase source, DataBase destination) throws Exception  
     {      {
         if (!file.toLowerCase().endsWith(".xml"))          if (!file.toLowerCase().endsWith(".xml"))
             file += ".xml";              file += ".xml";
Line 1443  class Convert Line 1655  class Convert
         buffw.close();          buffw.close();
     }      }
   
     public static void delete(String source, String destination, Vector names, Vector layouts, Vector selects, Vector creates, Vector ids, int mode) throws Exception    public static void delete(String source, String destination, Vector names, Vector layouts,
         Vector selects, Vector creates, Vector ids, int mode) throws Exception
     {      {
         FM2SQL.ProgressDialog dialog = null;          FM2SQL.ProgressDialog dialog = null;
         if (isGUI)          if (isGUI)
Line 1501  class Convert Line 1714  class Convert
                     bean.makeQuery(query, 50);                      bean.makeQuery(query, 50);
                     idField = ids.get(tbIndex).toString();                      idField = ids.get(tbIndex).toString();
   
                 }          } catch (Exception e)
                 catch (Exception e)  
                 {                  {
                     continue;                      continue;
                 }                  }
Line 1513  class Convert Line 1725  class Convert
                     String create = creates.get(tbIndex).toString().toLowerCase();                      String create = creates.get(tbIndex).toString().toLowerCase();
                     int fromIndex = create.indexOf("table") + 5;                      int fromIndex = create.indexOf("table") + 5;
                     int toIndex = create.indexOf("(");                      int toIndex = create.indexOf("(");
                     destTableName = create.substring(fromIndex, toIndex).replaceAll(beanDest.getQC(), "").trim();            destTableName = create.substring(fromIndex, toIndex).replaceAll(beanDest.getQC(), "")
                 .trim();
                     System.out.println("destTable " + destTableName);                      System.out.println("destTable " + destTableName);
   
                 }          } else
                 else  
                     destTableName = convertText(names.get(tbIndex).toString());                      destTableName = convertText(names.get(tbIndex).toString());
   
                 // for id kram                  // for id kram
Line 1547  class Convert Line 1759  class Convert
                             dialog.title.setText("Check if data  is available");                              dialog.title.setText("Check if data  is available");
                         else if (dialog != null)                          else if (dialog != null)
                             dialog.title.setText("Check if more  data  is available");                              dialog.title.setText("Check if more  data  is available");
                         myIds = bean.getIDVector(ids.get(tbIndex).toString(), (String) names.get(tbIndex), tempQuery, numHits);              myIds = bean.getIDVector(ids.get(tbIndex).toString(), (String) names.get(tbIndex),
                         myIdsDest = beanDest.getIDVector(convertText(idField), destTableName, tempQueryDest, numHits);                  tempQuery, numHits);
               myIdsDest = beanDest.getIDVector(convertText(idField), destTableName, tempQueryDest,
                   numHits);
                         if (myIds.isEmpty())                          if (myIds.isEmpty())
                             break;                              break;
                         vec = new Vector(myIds);                          vec = new Vector(myIds);
Line 1572  class Convert Line 1786  class Convert
   
                         Vector tables = beanDest.getTableNames();                          Vector tables = beanDest.getTableNames();
                         // Collections.sort(tables);                          // Collections.sort(tables);
                         System.out.println(names.get(tbIndex) + " " + tables.indexOf(convertText((String) names.get(tbIndex)))); // "//beanDest.getTypeNames());              System.out.println(names.get(tbIndex) + " "
                   + tables.indexOf(convertText((String) names.get(tbIndex)))); // "//beanDest.getTypeNames());
                         tables = beanDest.getTableNames();                          tables = beanDest.getTableNames();
                         // System.out.println(beanDest.getTableNames(beanDest.getCatalogs().get(2).toString()));                          // System.out.println(beanDest.getTableNames(beanDest.getCatalogs().get(2).toString()));
                         stm = beanDest.getConnection().createStatement();                          stm = beanDest.getConnection().createStatement();
Line 1617  class Convert Line 1832  class Convert
                 } // to idfield if                  } // to idfield if
             } // table loop              } // table loop
   
         }      } catch (Exception e)
         catch (Exception e)  
         {          {
             System.out.println("Error while connecting to database " + e);              System.out.println("Error while connecting to database " + e);
             if (isGUI)              if (isGUI)
             {              {
                 showExceptionDialog(dialog, command, e);                  showExceptionDialog(dialog, command, e);
                 resetGUI(dialog);                  resetGUI(dialog);
             }        } else
             else  
             {              {
                 e.printStackTrace();                  e.printStackTrace();
             }              }
Line 1648  class Convert Line 1861  class Convert
      */       */
     // TODO implement append,update and delete in one method      // TODO implement append,update and delete in one method
     // TODO using id based algorithm      // TODO using id based algorithm
     public static void synchronize(String source, String destination, Vector names, Vector layouts, Vector selects, Vector creates, Vector ids, int mode, String delimiter, Vector indexList)    public static void synchronize(String source, String destination, Vector names, Vector layouts,
         Vector selects, Vector creates, Vector ids, int mode, String delimiter, Vector indexList)
             throws Exception              throws Exception
     {      {
         System.out.println(" bin in synchronize!!!");          System.out.println(" bin in synchronize!!!");
Line 1700  class Convert Line 1914  class Convert
                     bean.makeQuery(query, 50);                      bean.makeQuery(query, 50);
                     idField = ids.get(tbIndex).toString();                      idField = ids.get(tbIndex).toString();
   
                 }          } catch (Exception e)
                 catch (Exception e)  
                 {                  {
                     System.out.println("Warning exception occured \n " + e);                      System.out.println("Warning exception occured \n " + e);
   
Line 1714  class Convert Line 1927  class Convert
                     String create = creates.get(tbIndex).toString().toLowerCase();                      String create = creates.get(tbIndex).toString().toLowerCase();
                     int fromIndex = create.indexOf("table") + 5;                      int fromIndex = create.indexOf("table") + 5;
                     int toIndex = create.indexOf("(");                      int toIndex = create.indexOf("(");
                     destTableName = create.substring(fromIndex, toIndex).replaceAll(beanDest.getQC(), "").trim();            destTableName = create.substring(fromIndex, toIndex).replaceAll(beanDest.getQC(), "")
                 .trim();
                     System.out.println("destTable " + destTableName);                      System.out.println("destTable " + destTableName);
   
                 }          } else
                 else  
                     destTableName = convertText(names.get(tbIndex).toString());                      destTableName = convertText(names.get(tbIndex).toString());
   
                 // for id kram                  // for id kram
Line 1755  class Convert Line 1968  class Convert
                         else if (dialog != null)                          else if (dialog != null)
                             dialog.title.setText("Check if more  data  is available");                              dialog.title.setText("Check if more  data  is available");
   
                         myIds = bean.getIDVector(ids.get(tbIndex).toString(), (String) names.get(tbIndex), tempQuery, 0);              myIds = bean.getIDVector(ids.get(tbIndex).toString(), (String) names.get(tbIndex),
                   tempQuery, 0);
                         myIdsDest = beanDest.getIDVector(convertText(idField), destTableName, tempQueryDest, 0);                          myIdsDest = beanDest.getIDVector(convertText(idField), destTableName, tempQueryDest, 0);
                         // System.out.println("status of remove                          // System.out.println("status of remove
                         // "+myIds.remove("b015892"));                          // "+myIds.remove("b015892"));
Line 1777  class Convert Line 1991  class Convert
                         linesToDelete.removeAll(deleted);                          linesToDelete.removeAll(deleted);
                         System.out.println("linesToAppend " + linesToAppend.size() + " " + destTableName);                          System.out.println("linesToAppend " + linesToAppend.size() + " " + destTableName);
                         System.out.println("linesToDelete " + linesToDelete.size() + " " + destTableName);                          System.out.println("linesToDelete " + linesToDelete.size() + " " + destTableName);
                         System.out.println("ID LIST SIZE " + Math.round((double) myIds.size() / (double) numIntervalls) + " " + myIds.size());              System.out.println("ID LIST SIZE "
                   + Math.round((double) myIds.size() / (double) numIntervalls) + " " + myIds.size());
                         deltaID = (int) Math.round((double) myIds.size() / (double) numIntervalls);                          deltaID = (int) Math.round((double) myIds.size() / (double) numIntervalls);
                         ConversionProperties prop = getFieldNamesAndDestTableName(creates.get(tbIndex).toString(), query, names.get(tbIndex).toString());              ConversionProperties prop = getFieldNamesAndDestTableName(creates.get(tbIndex)
                   .toString(), query, names.get(tbIndex).toString());
                         StringBuffer insCommand = createInsertCommand(prop.destTableName, prop.fieldNames);                          StringBuffer insCommand = createInsertCommand(prop.destTableName, prop.fieldNames);
                         StringBuffer updCommand = createUpdateCommand(prop.destTableName, prop.fieldNames, tempIDdest);              StringBuffer updCommand = createUpdateCommand(prop.destTableName, prop.fieldNames,
                   tempIDdest);
                         StringBuffer delCommand = createDeleteCommand(destTableName, tempIDdest);                          StringBuffer delCommand = createDeleteCommand(destTableName, tempIDdest);
                         PreparedStatement insPst = beanDest.getConnection().prepareStatement(insCommand.toString());              PreparedStatement insPst = beanDest.getConnection().prepareStatement(
                         PreparedStatement updPst = beanDest.getConnection().prepareStatement(updCommand.toString());                  insCommand.toString());
               PreparedStatement updPst = beanDest.getConnection().prepareStatement(
                   updCommand.toString());
                         delPSt = beanDest.getConnection().prepareStatement(delCommand.toString());                          delPSt = beanDest.getConnection().prepareStatement(delCommand.toString());
                         // delPSt.setString(1,"b015892");                          // delPSt.setString(1,"b015892");
                         // delPSt.execute();                          // delPSt.execute();
Line 1799  class Convert Line 2018  class Convert
                         {                          {
                             System.out.println(vec.get(k) + " " + vec.get(k + deltaID) + " " + vec.lastElement());                              System.out.println(vec.get(k) + " " + vec.get(k + deltaID) + " " + vec.lastElement());
                             if (query.indexOf("where") > 0)                              if (query.indexOf("where") > 0)
                                 tempQuery = query + " and " + tempID + ">='" + vec.get(k) + "' and " + tempID + "<='" + vec.get(k + deltaID) + "'";                  tempQuery = query + " and " + tempID + ">='" + vec.get(k) + "' and " + tempID
                       + "<='" + vec.get(k + deltaID) + "'";
                             else                              else
                                 tempQuery = query + " where " + tempID + ">='" + vec.get(k) + "' and " + tempID + "<='" + vec.get(k + deltaID) + "'";                  tempQuery = query + " where " + tempID + ">='" + vec.get(k) + "' and " + tempID
                       + "<='" + vec.get(k + deltaID) + "'";
                             System.out.println(tempQuery);                              System.out.println(tempQuery);
                             if (dialog != null)                              if (dialog != null)
                                 dialog.title.setText("Reading table data ...");                                  dialog.title.setText("Reading table data ...");
Line 1810  class Convert Line 2031  class Convert
                             if (dialog != null)                              if (dialog != null)
                                 dialog.title.setText("Writing table data ...");                                  dialog.title.setText("Writing table data ...");
   
                             performSynchronize(idField, vec, tempQuery, linesToDelete, linesToAppend, insPst, updPst, delPSt, deltaID, delimiter, dialog);                performSynchronize(idField, vec, tempQuery, linesToDelete, linesToAppend, insPst,
                     updPst, delPSt, deltaID, delimiter, dialog);
                             // System.out.println("ID LIST SIZE " +                              // System.out.println("ID LIST SIZE " +
                             // Math.round((double) myIds.size() / (double)                              // Math.round((double) myIds.size() / (double)
                             // numIntervalls) + " " + myIdsDest.size());                              // numIntervalls) + " " + myIdsDest.size());
Line 1822  class Convert Line 2044  class Convert
                             System.out.println("fits");                              System.out.println("fits");
                         else                          else
                         {                          {
                             System.out.println(" last intervall from " + vec.get(endIndex) + " " + vec.lastElement());                System.out.println(" last intervall from " + vec.get(endIndex) + " "
                     + vec.lastElement());
   
                             if (query.indexOf("where") > 0)                              if (query.indexOf("where") > 0)
                                 tempQuery = query + " and " + tempID + ">='" + vec.get(endIndex) + "' and " + tempID + "<='" + vec.lastElement() + "'";                  tempQuery = query + " and " + tempID + ">='" + vec.get(endIndex) + "' and "
                       + tempID + "<='" + vec.lastElement() + "'";
                             else                              else
                                 tempQuery = query + " where " + tempID + ">='" + vec.get(endIndex) + "' and " + tempID + "<='" + vec.lastElement() + "'";                  tempQuery = query + " where " + tempID + ">='" + vec.get(endIndex) + "' and "
                       + tempID + "<='" + vec.lastElement() + "'";
                             System.out.println(tempQuery);                              System.out.println(tempQuery);
                             if (dialog != null)                              if (dialog != null)
                                 dialog.title.setText("Reading table data ...");                                  dialog.title.setText("Reading table data ...");
                             // bean.makeQuery(tempQuery, 0);                              // bean.makeQuery(tempQuery, 0);
                             if (dialog != null)                              if (dialog != null)
                                 dialog.title.setText("Writing table data ...");                                  dialog.title.setText("Writing table data ...");
                             performSynchronize(idField, vec, tempQuery, linesToDelete, linesToAppend, insPst, updPst, delPSt, deltaID, delimiter, dialog);                performSynchronize(idField, vec, tempQuery, linesToDelete, linesToAppend, insPst,
                     updPst, delPSt, deltaID, delimiter, dialog);
                             // System.out.println("ID LIST SIZE " +                              // System.out.println("ID LIST SIZE " +
                             // Math.round((double) myIds.size() / (double)                              // Math.round((double) myIds.size() / (double)
                             // numIntervalls) + " " + myIdsDest.size());                              // numIntervalls) + " " + myIdsDest.size());
Line 1873  class Convert Line 2099  class Convert
                             // "+(type.indexOf("text") >= 0 ||                              // "+(type.indexOf("text") >= 0 ||
                             // type.indexOf("varchar") >= 0 || type.indexOf("char")                              // type.indexOf("varchar") >= 0 || type.indexOf("char")
                             // >= 0));                              // >= 0));
                             if (type.indexOf("text") >= 0 || type.indexOf("varchar") >= 0 || type.indexOf("char") >= 0)                if (type.indexOf("text") >= 0 || type.indexOf("varchar") >= 0
                     || type.indexOf("char") >= 0)
                             {                              {
                                 if (beanDest.url.indexOf("mysql") >= 0)                                  if (beanDest.url.indexOf("mysql") >= 0)
                                 {                                  {
Line 1881  class Convert Line 2108  class Convert
                                     // indexName + " ON " + destTableName + " (" +                                      // indexName + " ON " + destTableName + " (" +
                                     // indexField + "(10))");                                      // indexField + "(10))");
                                     // TODO problem if index exist !!!                                      // TODO problem if index exist !!!
                                     stm.execute("CREATE  INDEX " + indexName + " ON " + destTableName + " (" + indexField + "(10))");                    stm.execute("CREATE  INDEX " + indexName + " ON " + destTableName + " ("
                                 }                        + indexField + "(10))");
                                 else                  } else
                                 {                                  {
                                     stm.execute("CREATE  INDEX " + indexName + " ON " + destTableName + " (lower( " + indexField + "))");                    stm.execute("CREATE  INDEX " + indexName + " ON " + destTableName + " (lower( "
                         + indexField + "))");
   
                                 }                                  }
   
                             }                } else
                             else  
                             {                              {
                                 stm.execute("CREATE  INDEX " + destTableName + "_" + indexField + " ON " + destTableName + "(" + indexField + ")");                  stm.execute("CREATE  INDEX " + destTableName + "_" + indexField + " ON "
                       + destTableName + "(" + indexField + ")");
   
                             }                              }
   
Line 1915  class Convert Line 2143  class Convert
                 } // to idfield if                  } // to idfield if
             } // table loop              } // table loop
   
         }      } catch (Exception e)
         catch (Exception e)  
         {          {
             System.out.println("Error while connecting to database " + e);              System.out.println("Error while connecting to database " + e);
             e.printStackTrace();              e.printStackTrace();
Line 1942  class Convert Line 2169  class Convert
         return destQuery;          return destQuery;
     }      }
   
     private static void performSynchronize(String idField, Vector vec, String tempQuery, TreeSet linesToDelete, TreeSet linesToAppend, PreparedStatement insPst, PreparedStatement updPst,    private static void performSynchronize(String idField, Vector vec, String tempQuery,
             PreparedStatement delPSt, int deltaID, String delimiter, FM2SQL.ProgressDialog dialog) throws SQLException, ParseException, Exception        TreeSet linesToDelete, TreeSet linesToAppend, PreparedStatement insPst,
         PreparedStatement updPst, PreparedStatement delPSt, int deltaID, String delimiter,
         FM2SQL.ProgressDialog dialog) throws SQLException, ParseException, Exception
     {      {
         if (dialog != null)          if (dialog != null)
         {          {
Line 1979  class Convert Line 2208  class Convert
                 }                  }
                 insPst.execute();                  insPst.execute();
   
             }        } else
             else  
             // update              // update
             {              {
                 for (int l = 0; l < line.size(); ++l)                  for (int l = 0; l < line.size(); ++l)
Line 3468  class Convert Line 3696  class Convert
         return buf.toString();          return buf.toString();
     }      }
   
     public static ConversionProperties getFieldNamesAndDestTableName(String create, String query, String tableName)    public static ConversionProperties getFieldNamesAndDestTableName(String create, String query,
         String tableName)
     {      {
         String[] fieldNames = null;          String[] fieldNames = null;
         String destTableName = null;          String destTableName = null;
Line 3485  class Convert Line 3714  class Convert
             // retrieve field_names from select statement              // retrieve field_names from select statement
             // TODO problem with different fieldNames in create statement will              // TODO problem with different fieldNames in create statement will
             // overwrite them              // overwrite them
             if (query.indexOf("*") < 0)        if (query.indexOf("*") < 0 && create.equals(""))// quick hack for hartmut
             {              {
                 int selectEndIndex = query.indexOf("from");                  int selectEndIndex = query.indexOf("from");
                 StringTokenizer tokenizer = new StringTokenizer(query.substring(6, selectEndIndex), ",");                  StringTokenizer tokenizer = new StringTokenizer(query.substring(6, selectEndIndex), ",");
Line 3500  class Convert Line 3729  class Convert
                     fieldIndex++;                      fieldIndex++;
                 }                  }
   
             }        } else
             else  
             {              {
                 // use create statement for field names                  // use create statement for field names
                 StringTokenizer tokenizer = new StringTokenizer(create.substring(toIndex + 1, endIndex), ",");          StringTokenizer tokenizer = new StringTokenizer(create.substring(toIndex + 1, endIndex),
               ",");
                 int numFields = tokenizer.countTokens();                  int numFields = tokenizer.countTokens();
                 fieldNames = new String[numFields];                  fieldNames = new String[numFields];
                 int fieldIndex = 0;                  int fieldIndex = 0;
Line 3517  class Convert Line 3746  class Convert
                     fieldIndex++;                      fieldIndex++;
                 }                  }
             }              }
         }      } else
         else  
         {          {
             destTableName = convertText(tableName);              destTableName = convertText(tableName);
   
             // retrieve field_names from select statement              // retrieve field_names from select statement
             if (query.indexOf("*") < 0)              if (query.indexOf("*") < 0)
             {              {
                 int selectEndIndex = query.indexOf("from");          int selectEndIndex = query.lastIndexOf("from");
                 StringTokenizer tokenizer = new StringTokenizer(query.substring(6, selectEndIndex), ",");                  StringTokenizer tokenizer = new StringTokenizer(query.substring(6, selectEndIndex), ",");
                 int numFields = tokenizer.countTokens();                  int numFields = tokenizer.countTokens();
                 fieldNames = new String[numFields];                  fieldNames = new String[numFields];
Line 3533  class Convert Line 3761  class Convert
                 while (tokenizer.hasMoreTokens())                  while (tokenizer.hasMoreTokens())
                 {                  {
                     String fieldName = tokenizer.nextToken().trim();                      String fieldName = tokenizer.nextToken().trim();
             String text = convertText(fieldName);
             if (text.indexOf("\"") >= 0)
               fieldNames[fieldIndex] = convertText(fieldName);
             else
                     fieldNames[fieldIndex] = beanDest.getQC() + convertText(fieldName) + beanDest.getQC();                      fieldNames[fieldIndex] = beanDest.getQC() + convertText(fieldName) + beanDest.getQC();
                     // System.out.println("field "+ fieldNames[fieldIndex]);                      // System.out.println("field "+ fieldNames[fieldIndex]);
                     fieldIndex++;                      fieldIndex++;
                 }                  }
   
             }        } else
             else  
             {              {
                 Vector fieldNamesVec = bean.getColumnNames();                  Vector fieldNamesVec = bean.getColumnNames();
                 fieldNames = new String[fieldNamesVec.size()];                  fieldNames = new String[fieldNamesVec.size()];
Line 3588  class Convert Line 3819  class Convert
         return command;          return command;
     }      }
   
     public static StringBuffer createUpdateCommand(String destTableName, String[] fieldNames, String id)    public static StringBuffer createUpdateCommand(String destTableName, String[] fieldNames,
         String id)
     {      {
         StringBuffer command = new StringBuffer();          StringBuffer command = new StringBuffer();
   
Line 3628  class Convert Line 3860  class Convert
         bean.getConnection();          bean.getConnection();
         ResultSet resultSet = null;          ResultSet resultSet = null;
         String lastResult = "P227634.11";// "P227625.79554";//"P227625.77391";//"P116034.970998";          String lastResult = "P227634.11";// "P227625.79554";//"P227625.77391";//"P116034.970998";
         String myQuery = "select " + bean.getQC() + idField + bean.getQC() + ",serial " + " from " + bean.getQC() + table + bean.getQC();      String myQuery = "select " + bean.getQC() + idField + bean.getQC() + ",serial " + " from "
           + bean.getQC() + table + bean.getQC();
         System.out.println("Query is now " + myQuery);          System.out.println("Query is now " + myQuery);
         JDialog statusDialog = new JDialog();          JDialog statusDialog = new JDialog();
         statusDialog.setTitle("Status Information");          statusDialog.setTitle("Status Information");
Line 3650  class Convert Line 3883  class Convert
         {          {
             if (!statusDialog.isVisible())              if (!statusDialog.isVisible())
                 statusDialog.setVisible(true);                  statusDialog.setVisible(true);
             tempQuery = myQuery + " where " + bean.getQC() + idField + bean.getQC() + ">'" + lastResult + "'";        tempQuery = myQuery + " where " + bean.getQC() + idField + bean.getQC() + ">'" + lastResult
             + "'";
             resultSet = bean.makeQuery(tempQuery, 1);              resultSet = bean.makeQuery(tempQuery, 1);
             if (resultSet == null)              if (resultSet == null)
             {              {
                 System.out.println("lastResult was " + lastResult + " counter was " + counter);                  System.out.println("lastResult was " + lastResult + " counter was " + counter);
                 break;                  break;
             }        } else
             else  
             {              {
                 resultSet.next();                  resultSet.next();
                 lastResult = resultSet.getString(1);                  lastResult = resultSet.getString(1);
Line 3677  class Convert Line 3910  class Convert
         // ****** end Test ******          // ****** end Test ******
   
     }      }
   
     public final static String generateSuffix(final int step)
     {
       String fileString = null;
       if (step < 10)
         fileString = "00" + step;
       else if (step < 100)
         fileString = "0" + step;
       else
         fileString = step + "";
       return fileString;
     }
   
 }  }
   

Removed from v.1.3  
changed lines
  Added in v.1.10


FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>