File:  [Repository] / FM2SQL / Attic / Convert.java
Revision 1.30: download - view: text, annotated - select for diffs - revision graph
Wed Feb 11 12:07:26 2004 UTC (20 years, 4 months ago) by rogo
Branches: MAIN
CVS tags: HEAD
new incremental try

    1: 
    2: import java.util.*;
    3: import java.sql.*;
    4: import java.awt.Cursor;
    5: import java.io.BufferedReader;
    6: import java.io.BufferedWriter;
    7: import java.io.File;
    8: import java.io.FileInputStream;
    9: import java.io.FileNotFoundException;
   10: import java.io.FileOutputStream;
   11: import java.io.InputStreamReader;
   12: import java.io.OutputStreamWriter;
   13: import java.io.PrintStream;
   14: import java.io.UnsupportedEncodingException;
   15: 
   16: import com.exploringxml.xml.Node;
   17: import com.exploringxml.xml.Xparse;
   18: 
   19: class Convert 
   20: {
   21: 	static DBBean bean = new DBBean();
   22: 	static DBBean beanDest = new DBBean();
   23: 
   24:   static String user ="",passwd="e1nste1n";
   25:   static String userDest="postgres",passwdDest="rogo";
   26:   static boolean batchRun=false;
   27:   static Vector databases = new Vector();
   28:   final static int numHits = 5000;
   29:   final static int numIntervalls = 2;
   30:   public static void main(String args[])
   31:   {
   32: /*    try
   33:     {
   34:       //byte[] b = "ö".getBytes("UTF-8");
   35:     //  System.out.println("QueryString " +b[0]+" "+b[1]+(new String(b).getBytes()[0])+" "+new String(b).getBytes()[1]);
   36:     //System.out.println(new String(b,"UTF-8"));
   37:     } catch (UnsupportedEncodingException e)
   38:     {
   39:       e.printStackTrace();
   40:     }*/
   41:     FileOutputStream file = null;
   42:     if(args.length!=1)
   43:     {
   44:      System.out.println("Usage: java Convert <xml config file>");
   45:      System.exit(-1);
   46:     }
   47:     if(!(new File(args[0]).exists())) System.exit(0);
   48:     try
   49:     {
   50:       file = new FileOutputStream("./log.txt");
   51:     } catch (FileNotFoundException e1)
   52:     {
   53:       e1.printStackTrace();
   54:     } 
   55:    PrintStream stream= new PrintStream(file);
   56:    System.setOut(stream);
   57:    System.setErr(stream);
   58:    readXMLFile(args[0]);
   59:    System.out.println("Finished!");
   60:     //convert("jdbc:fmpro:http://141.14.237.74:8050","jdbc:postgresql://erebos/test",null,null);
   61:   }
   62:   public static void convertBatch(DBBean source,DBBean destination,Vector names,Vector layouts,Vector selects,Vector creates,int mode) throws Exception
   63:   {
   64:    /*FM2SQL.ProgressDialog dialog = new  FM2SQL.ProgressDialog(FM2SQL.fmInstance);
   65:    dialog.setTitle("Conversion running ...");
   66:    dialog.title.setText("Getting table data ...");
   67:    dialog.setLocation(500,500); 
   68:    dialog.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
   69:   */
   70:   // FM2SQL.fmInstance.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
   71:    //dialog.thread=Thread.currentThread();
   72:    bean = source;
   73:    beanDest = destination;
   74:  /*  // setting user and passwd 
   75:    bean.setUserAndPasswd(user,passwd);
   76:   // setting user and passwd 
   77:   beanDest.setUserAndPasswd(userDest,passwdDest);
   78:   */
   79:   //dialog.setSize(400,250);
   80:    StringBuffer command= null;
   81:     try
   82:     {
   83:       //bean.setConnection("jdbc:fmpro:http://141.14.237.74:8050");    
   84:     //bean.setConnection("jdbc:postgresql://erebos/test","postgres","rogo");
   85:       bean.setConnection(source.url);
   86:       if(names==null)
   87:        names=bean.getTableNames();
   88:       //Collections.sort(names);
   89:         int tbIndex = 1;
   90:      
   91:      // System.out.println("Start at "+names.indexOf("archimedes_facsimiles"));
   92:       for(tbIndex=0;tbIndex<names.size();++tbIndex)
   93:       {
   94:         Vector[] result = null;
   95:        try {
   96:      String query = "select * from " + bean.getQC() +names.get(tbIndex).toString() + bean.getQC();
   97:      String layout=(layouts.isEmpty()) ? "":layouts.get(tbIndex).toString(); 
   98:      query = (selects!=null) ? selects.get(tbIndex).toString():query;
   99:         //if  vectors[1].get(i) != null)
  100:         if (!layout.equals(""))
  101:         {
  102:           System.out.println("before "+query+" table"+names.get(tbIndex));
  103:           layout = " layout " + bean.getQC() + layout + bean.getQC();
  104:           String name = names.get(tbIndex).toString();
  105:           StringBuffer queryLayout = new StringBuffer(query);
  106:           queryLayout.insert(queryLayout.indexOf(name) + name.length() + 1, " " + layout);
  107:           query = queryLayout.toString();
  108:           System.out.println("added layout " + query);
  109:         
  110:         }
  111:         //  if ( layout!= "")
  112:         //   query += " layout " + bean.getQC() + layout + bean.getQC();
  113:      /*   dialog.title.setText("Getting table data ...");
  114:         dialog.table.setText(names.get(tbIndex).toString());
  115:         dialog.status.setText("Table " + (tbIndex + 1) + " of " + names.size());
  116:         dialog.show();
  117:       */
  118:           System.out.println(" performing query "+query);
  119:           //result = bean.getQueryData(query, null, 0);
  120:         bean.getConnection();
  121:         bean.makeQuery(query,0);
  122:       } catch (Exception e)
  123:         {
  124:           System.out.println(e.getMessage());
  125:           e.printStackTrace();
  126:           continue;
  127:         }
  128:         //beanDest.setConnection("jdbc:postgresql://erebos/test3");
  129:         beanDest.setConnection(destination.url);
  130: 
  131:         Statement stm = beanDest.getConnection().createStatement();
  132: 
  133:         Vector tables = beanDest.getTableNames();
  134:      //   Collections.sort(tables);
  135:         System.out.println("converting table "+names.get(tbIndex) + " " + tables.indexOf(convertText((String) names.get(tbIndex)))); // "//beanDest.getTypeNames()); 
  136:         tables = beanDest.getTableNames();
  137:         // System.out.println(beanDest.getTableNames(beanDest.getCatalogs().get(2).toString()));
  138:         stm = beanDest.getConnection().createStatement();
  139:         // System.exit(0);
  140:       if(mode==Convert.DataBase.CONVERT_MODE) 
  141:       {
  142:         if(tables.indexOf(names.get(tbIndex))>=0) 
  143:         {
  144:          stm.executeUpdate("drop table "+beanDest.getQC()+names.get(tbIndex)+beanDest.getQC());
  145:         tables.remove((String)names.get(tbIndex));
  146:         System.out.println("dropped table "+ names.get(tbIndex));
  147:         }
  148:         else
  149:         if(tables.indexOf(convertText(names.get(tbIndex).toString()))>=0) 
  150:         {
  151:          stm.executeUpdate("drop table "+beanDest.getQC()+convertText((String)names.get(tbIndex))+beanDest.getQC());
  152:         tables.remove(convertText((String)names.get(tbIndex)));
  153:         System.out.println("dropped table "+ names.get(tbIndex));
  154:         }
  155:  
  156:         if(tables.indexOf(names.get(tbIndex))<0&&tables.indexOf(convertText(names.get(tbIndex).toString()))<0) 
  157:         {
  158:           if(creates.get(tbIndex).equals("")||creates.get(tbIndex).toString().toLowerCase().indexOf("create")<0)
  159:           {
  160:             System.out.println("Warning empty or invalid create statement - creating one for you\n");
  161:         
  162:           command = new StringBuffer(50);
  163:           command.append("CREATE TABLE ");
  164:           command.append(beanDest.getQC());
  165:           command.append(convertText((String)names.get(tbIndex)));
  166:           command.append(beanDest.getQC());
  167:           command.append("(");
  168:            String type = null;
  169:            Vector columnNames=bean.getColumnNames();
  170:           for(int i=0;i<columnNames.size()-1;++i)
  171:           {
  172:            type = bean.metaData.getColumnTypeName(i+1);
  173:          //   System.out.println(i+" "+result[1].get(i)+" "+type);
  174:           type = (type.equals("NUMBER")) ?"INT4":type;
  175:           type = (type.equals("CONTAINER")) ?"TEXT":type;
  176: 
  177:           command.append(beanDest.getQC() + convertText((String) columnNames.get(i)) + beanDest.getQC() + " " + type + ", ");
  178:         }
  179:           type = bean.metaData.getColumnTypeName(columnNames.size());
  180:           type = (type.equals("NUMBER")) ? "INT4" : type;
  181:           type = (type.equals("CONTAINER")) ? "TEXT" : type;
  182:           command.append(beanDest.getQC() + convertText((String) columnNames.get(columnNames.size() - 1)) + beanDest.getQC() + " " + type);
  183:           command.append(" )");
  184:         }
  185:          else
  186:          command=new StringBuffer().append(creates.get(tbIndex).toString());
  187:          
  188:            System.out.println(command);
  189:           //  System.exit(0);
  190:           //command.append(DBBean.getQC());   
  191:           stm.executeUpdate(command.toString());
  192:         
  193:       }
  194:     }
  195:     // System.out.println(names);
  196:     /*    
  197:     if (idVal == "")
  198:           stm.executeUpdate("INSERT  INTO " + DBBean.getQC() + box.getSelectedItem() + DBBean.getQC() + " (" + DBBean.getQC() + columnName + DBBean.getQC() + ")  VALUES ('" + value + "') ");
  199:         else
  200:           stm.executeUpdate("UPDATE   " + DBBean.getQC() + box.getSelectedItem() + DBBean.getQC() + " SET  " + DBBean.getQC() + columnName + DBBean.getQC() + "='" + value + "' WHERE ID='" + idVal + "' ");
  201:       */
  202: 
  203:     // Vector[] result2=beanDest.getQueryData(names.get(tbIndex).toString());
  204:     // print results to screen
  205:   /*  for (int i = 0; i < result[1].size(); ++i)
  206:     {
  207:       //print Header
  208:       // System.out.println(" "+result[1].get(i)+" "+result2[1].get(i)+" "+i);
  209:     }*/
  210:     // System.out.println();
  211:     //dialog.title.setText("Writing table data ...");
  212:     Vector row = null;
  213:     //for (int j = 0; j < result[0].size(); ++j)
  214:     command = new StringBuffer();
  215: 
  216:     command.append("INSERT  INTO ");
  217:     command.append(beanDest.getQC());
  218:     command.append(convertText((String) names.get(tbIndex)));
  219:     command.append(beanDest.getQC());
  220:     command.append(" values ( ");
  221: 
  222:     for (int i = 0; i < bean.getColumnNames().size() - 1; ++i)
  223:       command.append("?,");
  224:     command.append("?)");
  225:     PreparedStatement pstm = beanDest.getConnection().prepareStatement(command.toString());
  226:     System.out.println(command);
  227:     while((row=bean.getNextRow())!=null)
  228:     {
  229: /*      //Vector row = (Vector) result[0].get(j);
  230:       command = new StringBuffer();
  231: 
  232:         command.append("INSERT  INTO ");
  233:         command.append(beanDest.getQC());
  234:         command.append(convertText((String) names.get(tbIndex)));
  235:         command.append(beanDest.getQC());
  236:         command.append(" values ( ");
  237:    */
  238:              //print rows
  239:      Object obj = null;
  240:      /*
  241:      for(int k=0;k<row.size()-1;++k)
  242:      {
  243:         obj = row.get(k);
  244:         //System.out.println("row "+obj+" "+k);
  245:        if(obj!=null&&!(obj instanceof ArrayList))
  246:        command.append("'"+convertUml(new String(obj.toString().getBytes("UTF-8"),"UTF-8"))+"',"); 
  247:        else if(obj!=null&&   obj instanceof ArrayList)
  248:        command.append("'"+convertUml(((ArrayList)obj).get(0).toString())+"',"); 
  249:        else command.append("NULL,");
  250:      }
  251:      obj = row.get(row.size() - 1);
  252:      if (obj != null && !(obj instanceof ArrayList))
  253:      command.append("'"+convertUml(new String(obj.toString().getBytes("UTF-8"),"UTF-8"))+"')"); 
  254:       else
  255:       if(obj!=null&&   obj instanceof ArrayList)
  256:        command.append("'"+convertUml(((ArrayList)obj).get(0).toString())+"')");         //command.append(obj.toString()+")");
  257:        else command.append("NULL)");
  258:        //command.append("'"+row.get(row.size()-1)+"')"); 
  259:      //command.append(" )");
  260:      //  for(int k=0;k<row.size();++k)
  261:         
  262:     // System.out.println();
  263:        //   System.out.println(command+" "+j+" "+row.size()+" "+  ((Vector)result2[0].get(j)).size());
  264:            // System.out.println(command);
  265:             stm.executeUpdate(command.toString());
  266:   // dialog.progress.setValue((int)(((double)(j+1)/(double)result[0].size())*100.0));
  267:   // System.out.println( (int)(((double)(j+1)/(double)result[0].size())*100.0)+" "+result[0].size()+" "+j);
  268:    command = null;
  269: */
  270:     for (int k = 0; k < row.size(); ++k)
  271:     {
  272:       obj = row.get(k);
  273:       if (obj instanceof ArrayList)
  274:         obj = ((List) obj).get(0);
  275:       String str = (obj == null) ? "NULL" : obj.toString();
  276:       if (!str.equals("NULL"))
  277:         pstm.setString(k + 1, str);
  278:       else
  279:         pstm.setNull(k + 1, Types.NULL);
  280:     }
  281:     pstm.execute();
  282: 
  283: }// to for loop    
  284:    
  285:     }
  286:  } catch(Exception e) 
  287:    {
  288:      System.out.println("Error while connecting to database "+ e);
  289:      //dialog.setVisible(false);
  290:      //dialog.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
  291:      //FM2SQL.fmInstance.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
  292:      java.io.ByteArrayOutputStream b = new java.io.ByteArrayOutputStream();
  293:      java.io.PrintStream stream = new java.io.PrintStream(b);
  294:      stream.print(command+"\n\n");
  295:      e.printStackTrace(stream);
  296:      System.err.println(b);
  297:      //FM2SQL.showErrorDialog(b.toString(), "Error occured !");
  298:    
  299:    }
  300:  //  dialog.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
  301:    //FM2SQL.fmInstance.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
  302: 
  303:  //  dialog.setVisible(false); 
  304:   }
  305: 
  306: 
  307:   public static void update(String source, String destination, Vector names, Vector layouts, Vector selects, Vector creates, Vector ids,int mode) throws Exception
  308:   {
  309:     FM2SQL.ProgressDialog dialog = null;
  310:     if (FM2SQL.fmInstance != null)
  311:     {
  312:       dialog = new FM2SQL.ProgressDialog(FM2SQL.fmInstance);
  313:       dialog.setTitle("Conversion running ...");
  314:       dialog.title.setText("Getting table data ...");
  315:       dialog.setLocation(FM2SQL.fmInstance.getLocationOnScreen().x + (FM2SQL.fmInstance.getWidth() - 400) / 2, FM2SQL.fmInstance.getLocationOnScreen().y + (FM2SQL.fmInstance.getHeight() - 250) / 2);
  316:       dialog.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
  317:       FM2SQL.fmInstance.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
  318:       dialog.thread = Thread.currentThread();
  319:     }
  320:     // setting user and passwd 
  321:     bean.setUserAndPasswd(user, passwd);
  322:     // setting user and passwd 
  323:     beanDest.setUserAndPasswd(userDest, passwdDest);
  324:     if (dialog != null)
  325:       dialog.setSize(400, 250);
  326:     StringBuffer command = null;
  327:     String query = null;
  328:     try
  329:     {
  330:       //bean.setConnection("jdbc:fmpro:http://141.14.237.74:8050");    
  331:       //bean.setConnection("jdbc:postgresql://erebos/test","postgres","rogo");
  332:       bean.setConnection(source);
  333:       if (names == null)
  334:         names = bean.getTableNames();
  335:       // Collections.sort(names);
  336:       int tbIndex = 1;
  337: 
  338:       // System.out.println("Start at "+names.indexOf("archimedes_facsimiles"));
  339:       for (tbIndex = 0; tbIndex < names.size(); ++tbIndex)
  340:       {
  341:         Vector[] result = null;
  342:         try
  343:         {
  344:           query = "select * from " + bean.getQC() + names.get(tbIndex).toString() + bean.getQC();
  345:           String layout = (layouts.isEmpty()) ? "" : layouts.get(tbIndex).toString();
  346:           query = (selects != null) ? selects.get(tbIndex).toString() : query;
  347:           //if  vectors[1].get(i) != null)
  348:           if (layout != "")
  349:           {
  350:             layout = " layout " + bean.getQC() + layout + bean.getQC();
  351:             String name = names.get(tbIndex).toString();
  352:             StringBuffer queryLayout = new StringBuffer(query);
  353:             queryLayout.insert(queryLayout.indexOf(name) + name.length() + 1, " " + layout);
  354:             query = queryLayout.toString();
  355:             System.out.println("added layout  " + query);
  356: 
  357:           }
  358:           dialog.title.setText("Getting table data ...");
  359:           dialog.table.setText(names.get(tbIndex).toString());
  360:           dialog.status.setText("Table " + (tbIndex + 1) + " of " + names.size());
  361:           dialog.show();
  362:           bean.getConnection();
  363:           bean.makeQuery(query, 0);
  364:         } catch (Exception e)
  365:         {
  366:           continue;
  367:         }
  368:         //beanDest.setConnection("jdbc:postgresql://erebos/test3");
  369:         beanDest.setConnection(destination);
  370: 
  371:         Statement stm = beanDest.getConnection().createStatement();
  372: 
  373:         Vector tables = beanDest.getTableNames();
  374:         // Collections.sort(tables);
  375:         System.out.println(names.get(tbIndex) + " " + tables.indexOf(convertText((String) names.get(tbIndex)))); // "//beanDest.getTypeNames()); 
  376:         tables = beanDest.getTableNames();
  377:         // System.out.println(beanDest.getTableNames(beanDest.getCatalogs().get(2).toString()));
  378:         stm = beanDest.getConnection().createStatement();
  379:         // System.exit(0);
  380:     
  381:         if (dialog != null)
  382:           dialog.title.setText("Writing table data ...");
  383: 
  384:         int j = -1;
  385:     
  386:         Vector row = null;
  387:         command = new StringBuffer();
  388: 
  389:         command.append("UPDATE ");
  390:         command.append(beanDest.getQC());
  391:         command.append(convertText((String) names.get(tbIndex)));
  392:         command.append(beanDest.getQC());
  393:         command.append(" SET  ");
  394: 
  395:         int size = bean.getColumnNames().size();
  396:         for (int i = 0; i < size - 1; ++i)
  397:           command.append(beanDest.getQC()+convertText((String)bean.getColumnNames().get(i))+beanDest.getQC()+" = ? ,");
  398:         command.append(convertText((String)bean.getColumnNames().get(size-1))+" = ? ");
  399:         command.append("WHERE "+convertText(ids.get(tbIndex).toString())+ " =  ?");
  400:         PreparedStatement pstm = beanDest.getConnection().prepareStatement(command.toString());
  401:         System.out.println(command+" "+tbIndex);
  402: 		    int rowCount = bean.getRowCount(query);
  403:         int idIndex = bean.getColumnNames().indexOf(ids.get(tbIndex) );
  404:         while ((row = bean.getNextRow()) != null)
  405:         {
  406:           j++;
  407:           //print rows
  408:           Object obj = null;
  409:           /* for(int k=0;k<row.size()-1;++k)
  410:            {
  411:           		obj = row.get(k);
  412:           		//System.out.println("row "+obj+" "+k);
  413:           	 if(obj!=null&&!(obj instanceof ArrayList))
  414:           	 command.append("'"+convertUml(obj.toString())+"',"); 
  415:           	 else if(obj!=null&&   obj instanceof ArrayList)
  416:           	 command.append("'"+convertUml(((ArrayList)obj).get(0).toString())+"',"); 
  417:           	 else command.append("NULL,");
  418:            }
  419:            obj = row.get(row.size() - 1);
  420:            if (obj != null && !(obj instanceof ArrayList))
  421:            command.append("'"+convertUml(obj.toString())+"')"); 
  422:           	else
  423:           	if(obj!=null&&   obj instanceof ArrayList)
  424:           	 command.append("'"+convertUml(((ArrayList)obj).get(0).toString())+"')");         //command.append(obj.toString()+")");
  425:           	 else command.append("NULL)");
  426:           	*/
  427:           //command.append("'"+row.get(row.size()-1)+"')"); 
  428:           //command.append(" )");
  429:           //  for(int k=0;k<row.size();++k)
  430: 
  431:           // System.out.println();
  432:           //   System.out.println(command+" "+j+" "+row.size()+" "+  ((Vector)result2[0].get(j)).size());
  433:           // System.out.println(command);
  434:           for (int k = 0; k < row.size(); ++k)
  435:           {
  436:             obj = row.get(k);
  437:             if (obj instanceof ArrayList)
  438:               obj = ((List) obj).get(0);
  439:             String str = (obj == null) ? "NULL" : obj.toString();
  440:             if (!str.equals("NULL"))
  441:               pstm.setString(k + 1, str);
  442:             else
  443:               pstm.setNull(k + 1, Types.NULL);
  444:           }
  445:          pstm.setString(row.size()+1,row.get(idIndex).toString());
  446: 				 //System.out.println(pstm.toString());
  447: 				// System.exit(0);
  448:           pstm.execute();
  449:           //stm.executeUpdate(command.toString());
  450:           if(dialog!=null)
  451:           dialog.progress.setValue((int) (((double) (j + 1) / (double) rowCount) * 100.0));
  452:           // System.out.println( (int)(((double)(j+1)/(double)result[0].size())*100.0)+" "+result[0].size()+" "+j);
  453:           command = null;
  454:         } // to for loop    
  455: 
  456:       }
  457:     } catch (Exception e)
  458:     {
  459:       System.out.println("Error while connecting to database " + e);
  460:       if (dialog != null)
  461:       {
  462:         dialog.setVisible(false);
  463:         dialog.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
  464:         FM2SQL.fmInstance.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
  465:       }
  466:       java.io.ByteArrayOutputStream b = new java.io.ByteArrayOutputStream();
  467:       java.io.PrintStream stream = new java.io.PrintStream(b);
  468:       stream.print(command + "\n\n");
  469:       e.printStackTrace(stream);
  470:       FM2SQL.showErrorDialog(b.toString(), "Error occured !");
  471: 
  472:     }
  473:     if (dialog != null)
  474:     {
  475:       dialog.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
  476:       FM2SQL.fmInstance.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
  477: 
  478:       dialog.setVisible(false);
  479:     }
  480: 
  481:   }
  482: 
  483: 
  484: 
  485:   public static void  convert(String source,String destination,Vector names,Vector layouts,Vector selects,Vector creates,Vector ids,int mode) throws Exception
  486:   {
  487:    FM2SQL.ProgressDialog dialog = new  FM2SQL.ProgressDialog(FM2SQL.fmInstance);
  488:    dialog.setTitle("Conversion running ...");
  489:    dialog.title.setText("Getting table data ...");
  490:    dialog.setLocation(FM2SQL.fmInstance.getLocationOnScreen().x+(FM2SQL.fmInstance.getWidth()-400)/2,FM2SQL.fmInstance.getLocationOnScreen().y+(FM2SQL.fmInstance.getHeight()-250)/2); 
  491: 	 dialog.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
  492: 	 FM2SQL.fmInstance.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
  493: 	 java.util.TreeSet myIds = new TreeSet();
  494:    int deltaID = 1;
  495:    String idField = "";
  496:    dialog.thread=Thread.currentThread();
  497:    // setting user and passwd 
  498:    bean.setUserAndPasswd(user,passwd);
  499:   // setting user and passwd 
  500:   beanDest.setUserAndPasswd(userDest,passwdDest);
  501:   dialog.setSize(400,250);
  502:    StringBuffer command= null;
  503:    String query = null;
  504:     try
  505:     {
  506:       //bean.setConnection("jdbc:fmpro:http://141.14.237.74:8050");    
  507: 	  //bean.setConnection("jdbc:postgresql://erebos/test","postgres","rogo");
  508:       bean.setConnection(source);
  509:       if(names==null)
  510:        names=bean.getTableNames();
  511:      // Collections.sort(names);
  512:         int tbIndex = 1;
  513:      
  514:      // System.out.println("Start at "+names.indexOf("archimedes_facsimiles"));
  515:       for(tbIndex=0;tbIndex<names.size();++tbIndex)
  516:       {
  517:         Vector[] result = null;
  518:       try
  519:       {
  520:         query = "select * from " + bean.getQC() + names.get(tbIndex).toString() + bean.getQC();
  521:         String layout = (layouts.isEmpty()) ? "" : layouts.get(tbIndex).toString();
  522:         query = (selects != null) ? selects.get(tbIndex).toString() : query;
  523:         //if  vectors[1].get(i) != null)
  524:         if (layout != "")
  525:         {
  526:           layout = " layout " + bean.getQC() + layout + bean.getQC();
  527:           String name = names.get(tbIndex).toString();
  528:           StringBuffer queryLayout = new StringBuffer(query);
  529:           queryLayout.insert(queryLayout.indexOf(name) + name.length() + 1, " " + layout);
  530:           query = queryLayout.toString();
  531:           System.out.println("added layout  " + query);
  532: 
  533:         }
  534:         //  if ( layout!= "")
  535:         //	 query += " layout " + bean.getQC() + layout + bean.getQC();
  536:         dialog.title.setText("Getting table data ...");
  537:         dialog.table.setText(names.get(tbIndex).toString());
  538:         dialog.status.setText("Table " + (tbIndex + 1) + " of " + names.size());
  539:         dialog.show();
  540:         //result = bean.getQueryData(query, dialog, 0);
  541:         bean.getConnection();
  542:         bean.makeQuery(query, 50);
  543:        // @TODO id Vector must be used in querys while loop over id ranges where id>=start and id<=end
  544:        idField = ids.get(tbIndex).toString();
  545:         /*if (idField != "")
  546:         {
  547:           myIds = bean.getIDVector(ids.get(tbIndex).toString(), (String) names.get(tbIndex), query,1000);
  548:           System.out.println("ID LIST SIZE " + Math.round((double) myIds.size() / (double) numIntervalls) + " " + myIds.size());
  549:          deltaID = (int) Math.round((double) myIds.size() / (double) numIntervalls);
  550:         
  551:         }*/
  552:         
  553:       } catch (Exception e)
  554:       {
  555:         System.out.println(e);
  556:         continue;
  557:       }
  558:         //beanDest.setConnection("jdbc:postgresql://erebos/test3");
  559:         beanDest.setConnection(destination);
  560: 
  561:         Statement stm = beanDest.getConnection().createStatement();
  562: 
  563:         Vector tables = beanDest.getTableNames();
  564:        // Collections.sort(tables);
  565:         System.out.println(names.get(tbIndex) + " " + tables.indexOf(convertText((String) names.get(tbIndex)))); // "//beanDest.getTypeNames()); 
  566:         tables = beanDest.getTableNames();
  567:         // System.out.println(beanDest.getTableNames(beanDest.getCatalogs().get(2).toString()));
  568:         stm = beanDest.getConnection().createStatement();
  569:         // System.exit(0);
  570:       if(mode==Convert.DataBase.CONVERT_MODE) 
  571:       {
  572:         if(tables.indexOf(names.get(tbIndex))>=0) 
  573:         {
  574:          stm.executeUpdate("drop table "+beanDest.getQC()+names.get(tbIndex)+beanDest.getQC());
  575:         tables.remove((String)names.get(tbIndex));
  576:         System.out.println("dropped table"+ names.get(tbIndex));
  577:         }
  578:         else
  579:         if(tables.indexOf(convertText(names.get(tbIndex).toString()))>=0) 
  580:         {
  581:          stm.executeUpdate("drop table "+beanDest.getQC()+convertText((String)names.get(tbIndex))+beanDest.getQC());
  582:         tables.remove(convertText((String)names.get(tbIndex)));
  583:         System.out.println("dropped table"+ names.get(tbIndex));
  584:         }
  585:  
  586: 				if(tables.indexOf(names.get(tbIndex))<0&&tables.indexOf(convertText(names.get(tbIndex).toString()))<0) 
  587:         {
  588:           if(creates.get(tbIndex).equals("")||creates.get(tbIndex).toString().toLowerCase().indexOf("create")<0)
  589:           {
  590:             System.out.println("Warning empty or invalid create statement - creating one for you\n");
  591:         
  592:           command = new StringBuffer(50);
  593:           command.append("CREATE TABLE ");
  594:           command.append(beanDest.getQC());
  595:           command.append(convertText((String)names.get(tbIndex)));
  596:           command.append(beanDest.getQC());
  597:           command.append("(");
  598:            String type = null;
  599:           Vector columnNames = bean.getColumnNames();
  600:           for(int i=0;i<columnNames.size()-1;++i)
  601:           {
  602:            type = bean.metaData.getColumnTypeName(i+1);
  603:          //   System.out.println(i+" "+result[1].get(i)+" "+type);
  604:           type = (type.equals("NUMBER")) ?"INT4":type;
  605:           type = (type.equals("CONTAINER")) ?"TEXT":type;
  606: 
  607:           command.append(beanDest.getQC() + convertText((String) columnNames.get(i)) + beanDest.getQC() + " " + type + ", ");
  608:         }
  609:           type = bean.metaData.getColumnTypeName(columnNames.size());
  610:           type = (type.equals("NUMBER")) ? "INT4" : type;
  611:           type = (type.equals("CONTAINER")) ? "TEXT" : type;
  612:           command.append(beanDest.getQC() + convertText((String) columnNames.get(columnNames.size() - 1)) + beanDest.getQC() + " " + type);
  613:           command.append(" )");
  614: 
  615:           // System.out.println(command);
  616:           //  System.exit(0);
  617:           //command.append(DBBean.getQC());   
  618:           } else
  619:           command=new StringBuffer().append(creates.get(tbIndex).toString());
  620:           stm.executeUpdate(command.toString());
  621:         
  622:       }
  623:     }
  624:     // System.out.println(names);
  625:     /*    
  626:     if (idVal == "")
  627:           stm.executeUpdate("INSERT  INTO " + DBBean.getQC() + box.getSelectedItem() + DBBean.getQC() + " (" + DBBean.getQC() + columnName + DBBean.getQC() + ")  VALUES ('" + value + "') ");
  628:         else
  629:           stm.executeUpdate("UPDATE   " + DBBean.getQC() + box.getSelectedItem() + DBBean.getQC() + " SET  " + DBBean.getQC() + columnName + DBBean.getQC() + "='" + value + "' WHERE ID='" + idVal + "' ");
  630:       */
  631: 
  632:     // Vector[] result2=beanDest.getQueryData(names.get(tbIndex).toString());
  633:     // print results to screen
  634:    /* for (int i = 0; i < result[1].size(); ++i)
  635:     {
  636:       //print Header
  637:       // System.out.println(" "+result[1].get(i)+" "+result2[1].get(i)+" "+i);
  638:     }*/
  639:     // System.out.println();
  640:     dialog.title.setText("Writing table data ...");
  641:     
  642:     //for (int j = 0; j < result[0].size(); ++j)
  643:     int j=-1;
  644:     Vector row = null;
  645:     command = new StringBuffer();
  646: 
  647:     command.append("INSERT  INTO ");
  648:     command.append(beanDest.getQC());
  649:     command.append(convertText((String) names.get(tbIndex)));
  650:     command.append(beanDest.getQC());
  651:     command.append(" values ( ");
  652:     
  653:     for(int i=0;i<bean.getColumnNames().size()-1;++i) command.append("?,");
  654:     command.append("?)");
  655:     PreparedStatement pstm = beanDest.getConnection().prepareStatement(command.toString());
  656:     System.out.println(command);
  657:     int rowCount= (idField!="") ? myIds.size():bean.getRowCount(query);
  658:     Vector vec = new Vector(myIds);
  659:     int endIndex = -1;
  660:     String tempQuery=query;String tempID = bean.getQC()+idField+bean.getQC();
  661:     if (!idField.equals(""))
  662:     {
  663:       while (true)
  664:       {
  665:         dialog.title.setText("Getting next ID Vector");
  666:         myIds = bean.getIDVector(ids.get(tbIndex).toString(), (String) names.get(tbIndex), tempQuery, numHits);
  667:         if(myIds.isEmpty()) break;
  668:         vec = new Vector(myIds);
  669:         rowCount = vec.size();
  670:         System.out.println("ID LIST SIZE " + Math.round((double) myIds.size() / (double) numIntervalls) + " " + myIds.size());
  671:         deltaID = (int) Math.round((double) myIds.size() / (double) numIntervalls);
  672: 
  673:         for (int k = 0; k < vec.size() - deltaID; k = k + deltaID)
  674:         {
  675:           System.out.println(vec.get(k) + " " + vec.get(k + deltaID) + " " + vec.lastElement());
  676:           if (query.indexOf("where") > 0)
  677:             tempQuery = query + " and " + tempID + ">=" + vec.get(k) + " and " + tempID + "<=" + vec.get(k + deltaID);
  678:           else
  679:             tempQuery = query + "where " + tempID + ">=" + vec.get(k) + " and " + tempID + "<=" + vec.get(k + deltaID);
  680:           System.out.println(tempQuery);
  681:           dialog.title.setText("Reading table data ...");
  682: 
  683:           bean.makeQuery(tempQuery, deltaID);
  684:           dialog.title.setText("Writing table data ...");
  685: 
  686:           command = writeDatainDestTable(dialog, command, k, pstm, rowCount);
  687:           endIndex = k + deltaID;
  688:         }
  689:         if ((vec.size() - 1) % numIntervalls == 0)
  690:           System.out.println("fits");
  691:         else
  692:         {
  693:           if (query.indexOf("where") > 0)
  694:             tempQuery = query + " and " + tempID + ">=" + vec.get(endIndex) + " and " + tempID + "<=" + vec.lastElement();
  695:           else
  696:             tempQuery = query + "where " + tempID + ">=" + vec.get(endIndex) + " and " + tempID + "<=" + vec.lastElement();
  697:           System.out.println(tempQuery);
  698:           dialog.title.setText("Reading table data ...");
  699:           bean.makeQuery(tempQuery, 0);
  700:           dialog.title.setText("Writing table data ...");
  701:           command = writeDatainDestTable(dialog, command, j, pstm, rowCount);
  702: 
  703:           System.out.println(" last intervall from " + vec.get(endIndex) + " " + vec.lastElement());
  704:           command = writeDatainDestTable(dialog, command, endIndex, pstm, rowCount);
  705:         }
  706:         if (query.indexOf("where") > 0)
  707:           tempQuery = query + " and " + tempID + ">" + vec.lastElement();
  708:         else
  709:         tempQuery = query + " where " + tempID + ">" + vec.lastElement();
  710:       
  711:       }
  712:     } else
  713:     {
  714:       bean.makeQuery(query, 0);
  715:       command = writeDatainDestTable(dialog, command, j, pstm, rowCount);
  716:     }
  717:   }
  718:  } catch(Exception e) 
  719:    {
  720:      System.out.println("Error while connecting to database "+ e);
  721:      dialog.setVisible(false);
  722: 	   dialog.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
  723: 		 FM2SQL.fmInstance.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
  724: 		 java.io.ByteArrayOutputStream b = new java.io.ByteArrayOutputStream();
  725: 		 java.io.PrintStream stream = new java.io.PrintStream(b);
  726: 		 stream.print(command+"\n\n");
  727: 		 e.printStackTrace(stream);
  728: 		 FM2SQL.showErrorDialog(b.toString(), "Error occured !");
  729: 	 
  730:    }
  731: 	 dialog.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
  732: 	 FM2SQL.fmInstance.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
  733: 
  734: 	 dialog.setVisible(false); 
  735:   }
  736:   private static StringBuffer writeDatainDestTable(FM2SQL.ProgressDialog dialog, StringBuffer command, int j, PreparedStatement pstm, int rowCount) throws Exception, SQLException
  737:   {
  738:     Vector row;
  739:         while((row=bean.getNextRow())!=null)
  740:         {
  741:           j++;
  742:           // row = (Vector) result[0].get(j);
  743:        /*   command = new StringBuffer();
  744:     
  745:             command.append("INSERT  INTO ");
  746:             command.append(beanDest.getQC());
  747:             command.append(convertText((String) names.get(tbIndex)));
  748:             command.append(beanDest.getQC());
  749:             command.append(" values ( ");
  750:          */
  751:                //print rows
  752:          Object obj = null;
  753:         /* for(int k=0;k<row.size()-1;++k)
  754:          {
  755:             obj = row.get(k);
  756:             //System.out.println("row "+obj+" "+k);
  757:            if(obj!=null&&!(obj instanceof ArrayList))
  758:            command.append("'"+convertUml(obj.toString())+"',"); 
  759:            else if(obj!=null&&   obj instanceof ArrayList)
  760:            command.append("'"+convertUml(((ArrayList)obj).get(0).toString())+"',"); 
  761:            else command.append("NULL,");
  762:          }
  763:          obj = row.get(row.size() - 1);
  764:          if (obj != null && !(obj instanceof ArrayList))
  765:          command.append("'"+convertUml(obj.toString())+"')"); 
  766:           else
  767:           if(obj!=null&&   obj instanceof ArrayList)
  768:            command.append("'"+convertUml(((ArrayList)obj).get(0).toString())+"')");         //command.append(obj.toString()+")");
  769:            else command.append("NULL)");
  770:           */
  771:           //command.append("'"+row.get(row.size()-1)+"')"); 
  772:           //command.append(" )");
  773:           //  for(int k=0;k<row.size();++k)
  774:     
  775:           // System.out.println();
  776:           //   System.out.println(command+" "+j+" "+row.size()+" "+  ((Vector)result2[0].get(j)).size());
  777:           // System.out.println(command);
  778:           for(int k=0;k<row.size();++k) 
  779:           {
  780:             obj = row.get(k);
  781:             if(obj instanceof ArrayList) obj=((List)obj).get(0);
  782:             String str =(obj==null) ? "NULL":obj.toString();
  783:             if(!str.equals("NULL"))
  784:             pstm.setString(k+1,str); 
  785:             else pstm.setNull(k+1,Types.NULL);
  786:           }
  787:           pstm.execute();
  788:           //stm.executeUpdate(command.toString());
  789:           dialog.progress.setValue((int) (((double) (j + 1) / (double) rowCount) * 100.0));
  790:     	// System.out.println( (int)(((double)(j+1)/(double)result[0].size())*100.0)+" "+result[0].size()+" "+j);
  791:        command = null;
  792:     }// to while loop    
  793:     return command;
  794:   }
  795: 
  796:  public static String convertText(String newName)
  797:   {
  798:     StringBuffer alterMe = new StringBuffer(newName.trim().toLowerCase());
  799:     int length = alterMe.length();
  800:     int j = 0;
  801:     int index=alterMe.indexOf(".fp5");
  802:     if ( index >= 0 )
  803:      {
  804:        alterMe.delete(index, index + 4);
  805:        length = length - 4;
  806:      }
  807:  
  808:     while (j < length)
  809:     { 
  810:       if (alterMe.charAt(j) == ' ')
  811:       {
  812:         alterMe.setCharAt(j, '_');
  813:     //    if(j<length-1) j=j+1;
  814:       }
  815:       else
  816:       if (alterMe.charAt(j) == '_')
  817:       {
  818: 		
  819: 		if(alterMe.charAt(j+1)=='_')
  820: 		alterMe.deleteCharAt(j);
  821:         length = length-1;
  822:       //  if(j<length-1) j=j+1;
  823:       }
  824:      else
  825: 	 if (alterMe.charAt(j) == 'ä')
  826: 		  {
  827: 			alterMe.setCharAt(j, 'a');
  828: 			alterMe.insert(j+1,"e");
  829: 			length=length+1;
  830: 			if(j<length-1) j=j+1;
  831: 		  }
  832: 		else
  833: 		 if (alterMe.charAt(j) == 'ö')
  834: 			  {
  835: 				alterMe.setCharAt(j, 'o');
  836: 				alterMe.insert(j+1,"e");
  837: 				length=length+1;
  838: 				if(j<length-1) j=j+1;
  839: 			  }
  840: 		else
  841: 		 if (alterMe.charAt(j) == 'ü')
  842: 			  {
  843: 				alterMe.setCharAt(j, 'u');
  844: 				alterMe.insert(j+1,"e");
  845: 				length=length+1;
  846: 				if(j<length-1) j=j+1;
  847: 			  }
  848: 		else
  849:     if (alterMe.charAt(j) == 'ß')
  850:     {
  851:       alterMe.setCharAt(j, 's');
  852:       alterMe.insert(j + 1, "s");
  853:       length = length + 1;
  854:       if (j < length - 1)
  855:         j = j + 1;
  856:     } else if (alterMe.charAt(j) == ':')
  857:     {
  858:       if(j<length-1)
  859:       {
  860:       if (alterMe.charAt(j + 1) == ':')
  861:       {
  862:         alterMe.setCharAt(j,'_');
  863:         alterMe.delete(j+1,j+2);
  864:       length = length - 1;
  865:    
  866:       }
  867:  
  868:       if (j < length - 1)
  869:         j = j + 1;
  870:       }
  871:     } else if (alterMe.charAt(j) == '-')
  872:     {
  873:       alterMe.setCharAt(j, '_');
  874: 
  875:     } else if (alterMe.charAt(j) == '?')
  876: 			{
  877: 				// changed ? to _ because of update statement
  878: 		    alterMe.setCharAt(j,'_');
  879:        // length = length + 1;
  880: 			 // j=j+1;
  881: 			System.out.println(alterMe);
  882: 			}
  883: 
  884:     else if (alterMe.charAt(j) == '.')
  885:     {
  886:       if(j==length-1)
  887:       {
  888:         alterMe.delete(j, j); 
  889:         length--;
  890:       }
  891: 			else
  892: 			alterMe.setCharAt(j,'_');
  893:     }
  894: 
  895:     ++j;
  896:   }
  897:     return alterMe.toString();
  898:   }
  899:   public static String convertToEntities(String newName)
  900:   {
  901:     StringBuffer alterMe = new StringBuffer(newName.trim());
  902:     int length = alterMe.length();
  903:     int j = 0;
  904: 
  905:     while (j < length)
  906:     {
  907: 
  908:       if (alterMe.charAt(j) == '>')
  909:       {
  910:         alterMe.setCharAt(j, '&');
  911:         alterMe.insert(j + 1, "gt;");
  912:         length = length + 2;
  913:         if (j < length - 1)
  914:           j = j + 1;
  915: 
  916:       } else if (alterMe.charAt(j) == '<')
  917:       {
  918:         alterMe.setCharAt(j, '&');
  919:         alterMe.insert(j + 1, "lt;");
  920:         length = length + 2;
  921:         if (j < length - 1)
  922:           j = j + 1;
  923: 
  924:       }
  925:       ++j;
  926:     }
  927:     return alterMe.toString();
  928:   }
  929:   public static String convertUml(String newName)
  930:    {
  931: 	 StringBuffer alterMe = new StringBuffer(newName.trim());
  932: 	 int length = alterMe.length();
  933: 	 int j = 0;
  934: 	
  935: 	
  936: 	 while (j < length)
  937: 	 { 
  938: 	
  939: 	   if (alterMe.charAt(j) == '\'')
  940: 	   {
  941: 		 alterMe.setCharAt(j, '\\');
  942: 		 alterMe.insert(j + 1, "'");
  943: 		 length = length + 1;
  944: 		 if(j<length-1) j=j+1;
  945: 	   }
  946: 	/*   else
  947: 	   if (alterMe.charAt(j) == '"')
  948: 	   {
  949: 		 alterMe.setCharAt(j, '\\');
  950: 		 alterMe.insert(j + 1, "\"");
  951: 		 length = length + 1;
  952: 		 if(j<length-1) j=j+1;
  953: 	   }
  954: 	  else
  955: 	  if (alterMe.charAt(j) == '>')
  956: 	   {
  957: 		 alterMe.setCharAt(j, '\\');
  958: 		 alterMe.insert(j + 1, ">");
  959: 		 length = length + 1;
  960: 		 if(j<length-1) j=j+1;
  961: 	   }
  962: 	  else
  963: 	  if (alterMe.charAt(j) == '<')
  964: 	   {
  965: 		 alterMe.setCharAt(j, '\\');
  966: 		 alterMe.insert(j + 1, "<");
  967: 		 length = length + 1;
  968: 		 if(j<length-1) j=j+1;
  969: 	   }
  970: 	 else
  971: 	 if (alterMe.charAt(j) == '?')
  972: 	   {
  973: 		 alterMe.setCharAt(j, '\\');
  974: 		 alterMe.insert(j + 1, "?");
  975: 		 length = length + 1;
  976: 		 if(j<length-1) j=j+1;
  977: 	   }
  978: 	 else
  979: 	 if (alterMe.charAt(j) == '&')
  980: 	   {
  981: 		 alterMe.setCharAt(j, '\\');
  982: 		 alterMe.insert(j + 1, "&");
  983: 		 length = length + 1;
  984: 		 if(j<length-1) j=j+1;
  985: 	   }
  986: 	 else
  987: 	 if (alterMe.charAt(j) == '=')
  988: 	   {
  989: 		 alterMe.setCharAt(j, '\\');
  990: 		 alterMe.insert(j + 1, "=");
  991: 		 length = length + 1;
  992: 		 if(j<length-1) j=j+1;
  993: 	   }
  994: 	 else
  995: 	 if (alterMe.charAt(j) == ',')
  996: 	   {
  997: 		 alterMe.setCharAt(j, '\\');
  998: 		 alterMe.insert(j + 1, ",");
  999: 		 length = length + 1;
 1000: 		 if(j<length-1) j=j+1;
 1001: 	   }
 1002: 	 else
 1003: 	 if (alterMe.charAt(j) == '.')
 1004: 	   {
 1005: 		 alterMe.setCharAt(j, '\\');
 1006: 		 alterMe.insert(j + 1, ".");
 1007: 		 length = length + 1;
 1008: 		 if(j<length-1) j=j+1;
 1009: 	   }
 1010: 	 else
 1011: 	 if (alterMe.charAt(j) == '[')
 1012: 	   {
 1013: 		 alterMe.setCharAt(j, '\\');
 1014: 		 alterMe.insert(j + 1, ".");
 1015: 		 length = length + 1;
 1016: 		 if(j<length-1) j=j+1;
 1017: 	   }
 1018: 	else
 1019: 	 if (alterMe.charAt(j) == ']')
 1020: 	   {
 1021: 		 alterMe.setCharAt(j, '\\');
 1022: 		 alterMe.insert(j + 1, ".");
 1023: 		 length = length + 1;
 1024: 		 if(j<length-1) j=j+1;
 1025: 	   }
 1026: 	else
 1027: 	 if (alterMe.charAt(j) == '%')
 1028: 	   {
 1029: 		 alterMe.setCharAt(j, '\\');
 1030: 		 alterMe.insert(j + 1, "%");
 1031: 		 length = length + 1;
 1032: 		 if(j<length-1) j=j+1;
 1033: 	   }*/
 1034: 		++j;
 1035: 	 }
 1036: 	 return alterMe.toString();
 1037:    }
 1038:    
 1039:    public static void parseXMLConfig(StringBuffer sb)
 1040:     {
 1041:       boolean finished = false;
 1042:       // parse string and build document tree
 1043:       Xparse parser =new Xparse();
 1044:       parser.changeEntities = true;
 1045:       Node  root = parser.parse(sb.toString());
 1046:        // printContents(root);
 1047:       Vector databases= new Vector();
 1048:       Vector tables = new Vector();
 1049:       Vector layouts = new Vector();
 1050:       Vector selects = new Vector();
 1051:       Vector creates = new Vector();
 1052: 			Vector ids     = new Vector();
 1053:       int mode = -1;
 1054:    
 1055:       try
 1056:       {
 1057:         Node tempNode = root.find("convert/source", new int[] { 1, 1 });
 1058:         if(tempNode==null) throw new Error("parse error source tag missing");
 1059:         System.out.println(tempNode.name);
 1060:         int length =countNodes(tempNode);
 1061:         for (int i = 1; i <= length; i++)
 1062:         {
 1063:           
 1064:           DBBean database = new DBBean();
 1065:           tables = new Vector();
 1066:           layouts = new Vector();
 1067:           selects = new Vector();
 1068:           creates = new Vector();
 1069:           ids     = new Vector();
 1070:          // parse dataBase
 1071:           Node node = root.find("convert/source/database/url", new int[] { 1, 1, i, 1 });
 1072:           Node node1 = root.find("convert/source/database/user", new int[] { 1, 1, i, 1, 1 });
 1073:           Node node2 = root.find("convert/source/database/password", new int[] { 1, 1, i, 1, 1 });
 1074:           Node node3 = root.find("convert/source/database", new int[] { 1, 1, i});
 1075:     			Node nodeMode = root.find("convert/source/database/mode", new int[] {1, 1, i, 1,1});
 1076: 
 1077:           if(node3== null) throw new Error("parse error database tag missing");
 1078:           if(node==null) throw new Error("parse error url tag missing");
 1079:           if(node1==null) throw new Error("parse error user tag missing");
 1080:           if(node2==null) throw new Error("parse error password tag missing");
 1081:           String url=node.getCharacters();
 1082:           String user=node1.getCharacters();
 1083:           String password=node2.getCharacters();
 1084:           database.setURL(url.trim());
 1085:           database.setUserAndPasswd(user.trim(),password.trim());
 1086:           System.out.println(node.name + " " + node.getCharacters());
 1087:           System.out.println(node1.name + " " + node1.getCharacters());
 1088:           System.out.println(node2.name + " " + node2.getCharacters());
 1089:           String modeString = "";
 1090:           if (nodeMode == null)
 1091:             modeString = "convert";
 1092:           else
 1093:             modeString = nodeMode.getCharacters();
 1094:           if (modeString.equals("convert"))
 1095:             mode = DataBase.CONVERT_MODE;
 1096:           else
 1097:             if (modeString.equals("append"))
 1098:               mode = DataBase.APPEND_MODE;
 1099:             else
 1100:               if (modeString.equals("update"))
 1101:                 mode = DataBase.UPDATE_MODE;
 1102:        //   if(node3!=null)
 1103:          // System.out.println(node3.name);
 1104:           
 1105:           int length2= countNodes(node3);
 1106:     
 1107:          System.out.println("number of tables " +length2);
 1108:     
 1109:           for(int j=1;j<=length2;++j)
 1110:           {
 1111:             Node node4 = root.find("convert/source/database/table", new int[] { 1, 1, i, j });
 1112:             Node node5 = root.find("convert/source/database/table/select", new int[] { 1, 1, i, j, 1 });
 1113:             Node node6 = root.find("convert/source/database/table/create", new int[] { 1, 1, i, j, 1 });
 1114:             if(node4!=null)
 1115:             System.out.println(node4.name + " " + node4.attributes.get("layout").equals(""));
 1116:             if(node5!=null)
 1117:             System.out.println(node5.name + " " + node5.getCharacters());
 1118:             if(node6!=null)
 1119:             System.out.println(node6.name + " " + node6.getCharacters());
 1120:             if(node4==null) throw new Error("parse error table tag missing");
 1121:             // if(node5==null) throw new Error("parse error select tag missing");
 1122:             // if(node6==null) throw new Error("parse error create tag missing");
 1123:             String name = (String)node4.attributes.get("name");
 1124:             String layout = (String)node4.attributes.get("layout");
 1125:             String id = (String)node4.attributes.get("id");
 1126:             System.out.println("id was "+id);
 1127:             if(name==null) throw new Error("parse error required table tag attribute name missing");
 1128:             if(layout==null) layout ="";
 1129:             if(id==null)  id = "";
 1130:             if(name.equals("")) throw new Error("parse error table tag attribute must not be empty");
 1131:             tables.add(name);
 1132:             layouts.add(layout);
 1133:             ids.add(id);
 1134:             String query = (node5==null) ? "":node5.getCharacters(); 
 1135:             if(query.equals("")) System.err.println("Warning empty select tag or  select tag missing !!");
 1136:             query = (query.equals("")) ? "select * from "+database.getQC()+name+database.getQC():query;
 1137:             selects.add(query);
 1138:             if(node6!=null) creates.add(node6.getCharacters().trim());
 1139:              else
 1140:               creates.add("");
 1141:             
 1142:           }
 1143:           databases.add(new DataBase(database, tables, layouts, selects,creates,ids,mode));
 1144:         }
 1145:         DBBean database = new DBBean();
 1146:         // parse dataBase
 1147:         Node node = root.find("convert/destination/database/url", new int[] { 1, 1, 1, 1 });
 1148:         Node node1 = root.find("convert/destination/database/user", new int[] { 1, 1, 1, 1, 1 });
 1149:         Node node2 = root.find("convert/destination/database/password", new int[] { 1, 1, 1, 1, 1 });
 1150:         String url = node.getCharacters();
 1151:         String user = node1.getCharacters();
 1152:         String password = node2.getCharacters();
 1153:         System.out.println(url);
 1154:         database.setURL(url.trim());
 1155:         database.setUserAndPasswd(user.trim(), password.trim());
 1156:         //databases.add(database);
 1157:        for (Iterator iter = databases.iterator(); iter.hasNext();)
 1158:       {
 1159:         DataBase db = (DataBase) iter.next();
 1160:         if(mode!=DataBase.UPDATE_MODE)
 1161:         convertBatch(db.bean,database,db.tables,db.layouts,db.selects,db.creates,mode);
 1162:         else
 1163:         update(db.bean.url,database.url,db.tables,db.layouts,db.selects,db.creates,db.ids,mode);
 1164: 
 1165:       }
 1166:         // printContents(node3);
 1167:         //   FM2SQL.fmInstance=new FM2SQL();
 1168:       } catch (Exception e)
 1169:       {
 1170:         // TODO Auto-generated catch block
 1171:         e.printStackTrace();
 1172:       }
 1173:       /*
 1174:       Node tempNode=root.find(rootNode,new int[] {1});
 1175:       if(tempNode==null) return rtTag;
 1176:       int count=1;
 1177:       /* 
 1178:       for(int i=0;i<tempNode.contents.v.size();++i)
 1179:       {
 1180:         // System.out.println(((Node)tempNode.contents.v.elementAt(i)).attributes+" "+i);
 1181:       }*/
 1182:    /*
 1183:       if(tempNode.contents.v.size()==0) return rtTag;
 1184:       Node notNull=null;
 1185:       Node rtNode=root.find(rootNode+"/rt",new int[] {1,1});
 1186:       rtTag=(rtNode==null) ? "finished":rtNode.getCharacters();
 1187:       System.out.println("rt tag is "+ rtTag);
 1188:       int length=0;//(tempNode.contents.length()-1)/2;
 1189:       for(int i=0;i<tempNode.contents.v.size();++i)    {
 1190:         Node node=(Node)tempNode.contents.v.elementAt(i);
 1191:         if(node.type.equals("element"))
 1192:         if(node.name.equals("doc"))length++;
 1193:         // System.out.println(((Node)tempNode.contents.v.elementAt(i)).attributes+" "+i);
 1194:       }
 1195:      if(length==0) rtTag="finished";        
 1196:       while(count<=length)
 1197:       {
 1198:          //System.out.println(count+" "+length);
 1199:         tempNode=root.find(rootNode+"/doc",new int[] {1,count});
 1200:         if(tempNode==null)
 1201:         {
 1202:           rtTag="finished";
 1203:           break;
 1204:         }    
 1205:         Bundle.Document doc = new Bundle.Document();
 1206:         Hashtable attributes=tempNode.attributes;
 1207:         int docID=0;
 1208:         int ver=0;
 1209:          if(attributes != null)
 1210:         {
 1211:           docID=Integer.parseInt((String)attributes.get("id"));
 1212:           ver=Integer.parseInt((String)attributes.get("ver"));
 1213:           doc.addData("docID",(String)attributes.get("id"));
 1214:           doc.addData("ver",(String)attributes.get("ver"));
 1215:         }
 1216:         bundle.docs.put(new Integer(docID),doc);
 1217:         bundle.documents.addElement(doc);
 1218:         // System.out.println("id " +docID+" ver "+ver);
 1219:         Node fileNode=root.find(rootNode+"/doc/file",new int[] {1,count,1});
 1220:         attributes=(fileNode==null)? null:fileNode.attributes;
 1221:         int fileID=0;
 1222:         int fileVer=0;
 1223:         if(attributes != null)
 1224:         {
 1225:           fileID=Integer.parseInt((String)attributes.get("id"));
 1226:           fileVer=Integer.parseInt((String)attributes.get("ver"));
 1227:           doc.addData("fileID",(String)attributes.get("id"));
 1228:           doc.addData("fileVer",(String)attributes.get("ver"));
 1229:           // System.out.println("fileid " +fileID+" ver "+fileVer);
 1230:         }
 1231:      // add all Document tags to actual Document
 1232:         for(int i=0;i<tempNode.contents.v.size();++i)
 1233:         {   
 1234:           Node node=(Node)tempNode.contents.v.elementAt(i);
 1235:           if(node.type.equals("element"))
 1236:            {
 1237:              //System.out.println(node.name+" "+node.getCharacters()+" "+node.contents.v.size());
 1238:              if(node.contents.v.size()>1) 
 1239:              {
 1240:                for(int j=0;j<node.contents.v.size();++j)
 1241:                {  
 1242:                  Node node2=(Node)node.contents.v.elementAt(j);
 1243:                  if(node2.type.equals("element"))
 1244:                   {
 1245:                     doc.addData(node2.name,node2.getCharacters());
 1246:                     //System.out.println(node2.name+" "+node2.getCharacters()+" "+node2.contents.v.size());
 1247:                   }
 1248:                }
 1249:              } else doc.addData(node.name,node.getCharacters());
 1250:           }
 1251:         }
 1252:         bundle.docsLocator.put(doc.locator,doc); 
 1253:    
 1254:       bundle.documents.addElement(doc);
 1255:         count++;
 1256:       }      */
 1257:   
 1258:       // System.out.println(bundle.docs.size());
 1259:    // return rtTag;
 1260:     }
 1261:     public static Vector getXMLConfig(String xmlFile)
 1262:      {
 1263:        StringBuffer sb=null;
 1264:        try 
 1265:              {
 1266:                 // read XML Metadata from a file
 1267:                 FileInputStream fi= new FileInputStream(xmlFile);
 1268:                 InputStreamReader isr= new InputStreamReader(fi,"UTF-8");
 1269:                 BufferedReader buffr = new BufferedReader(isr);
 1270:                 sb=new StringBuffer();
 1271:                 int c=0;
 1272:                 while ((c = buffr.read()) != -1) 
 1273:                 {
 1274:                   char ch=(char)c;
 1275:                   sb.append(ch);
 1276:                   // System.out.print((char)c);
 1277:                 }
 1278:                
 1279:             } catch(Exception e) { e.printStackTrace();} 
 1280:   
 1281:        boolean finished = false;
 1282:        // parse string and build document tree
 1283:        Xparse parser =new Xparse();
 1284:        parser.changeEntities = true;
 1285:        Node  root = parser.parse(sb.toString());
 1286:    // printContents(root);
 1287:        Vector databases= new Vector();
 1288:        Vector tables = new Vector();
 1289:        Vector layouts = new Vector();
 1290:        Vector selects = new Vector();
 1291:        Vector creates = new Vector();
 1292:        Vector ids     = new Vector();
 1293:        
 1294:        int mode = -1;
 1295:        try
 1296:        {
 1297:          Node tempNode = root.find("convert/source", new int[] { 1, 1 });
 1298:          if(tempNode==null) throw new Error("parse error source tag missing");
 1299:          System.out.println(tempNode.name);
 1300:          int length =countNodes(tempNode);
 1301:          for (int i = 1; i <= length; i++)
 1302:          {
 1303:           
 1304:            DBBean database = new DBBean();
 1305:            tables = new Vector();
 1306:            layouts = new Vector();
 1307:            selects = new Vector();
 1308:            creates = new Vector();
 1309:            ids     = new Vector();
 1310:           // parse dataBase
 1311:            Node node = root.find("convert/source/database/url", new int[] { 1, 1, i, 1 });
 1312:            Node node1 = root.find("convert/source/database/user", new int[] { 1, 1, i, 1, 1 });
 1313:            Node node2 = root.find("convert/source/database/password", new int[] { 1, 1, i, 1, 1 });
 1314:            Node node3 = root.find("convert/source/database", new int[] { 1, 1, i});
 1315:            Node nodeMode = root.find("convert/source/database/mode", new int[] { 1, 1, i, 1, 1 });
 1316:            
 1317:            if(node3== null) throw new Error("parse error database tag missing");
 1318:            if(node==null) throw new Error("parse error url tag missing");
 1319:            if(node1==null) throw new Error("parse error user tag missing");
 1320:            if(node2==null) throw new Error("parse error password tag missing");
 1321:            String url=node.getCharacters();
 1322:            String user=node1.getCharacters();
 1323:            String password=node2.getCharacters();
 1324:            database.setURL(url.trim());
 1325:            database.setUserAndPasswd(user.trim(),password.trim());
 1326:            System.out.println(node.name + " " + node.getCharacters());
 1327:            System.out.println(node1.name + " " + node1.getCharacters());
 1328:            System.out.println(node2.name + " " + node2.getCharacters());
 1329:            String modeString = "";  
 1330:           if (nodeMode == null)
 1331:             modeString = "convert";
 1332:           else
 1333:             modeString = nodeMode.getCharacters();
 1334:           if (modeString.equals("convert"))
 1335:             mode = DataBase.CONVERT_MODE;
 1336:           else
 1337:             if (modeString.equals("append"))
 1338:               mode = DataBase.APPEND_MODE;
 1339:             else
 1340:               if (modeString.equals("update"))
 1341:                 mode = DataBase.UPDATE_MODE;
 1342: 			 
 1343:         
 1344:         //   if(node3!=null)
 1345:           // System.out.println(node3.name);
 1346:           
 1347:            int length2= countNodes(node3);
 1348:     
 1349:           System.out.println("number of tables " +length2);
 1350:     
 1351:            for(int j=1;j<=length2;++j)
 1352:            {
 1353:              Node node4 = root.find("convert/source/database/table", new int[] { 1, 1, i, j });
 1354:              Node node5 = root.find("convert/source/database/table/select", new int[] { 1, 1, i, j, 1 });
 1355:              Node node6 = root.find("convert/source/database/table/create", new int[] { 1, 1, i, j, 1 });
 1356:              if(node4!=null)
 1357:              System.out.println(node4.name + " " + node4.attributes.get("layout").equals(""));
 1358:              if(node5!=null)
 1359:              System.out.println(node5.name + " " + node5.getCharacters());
 1360:              if(node6!=null)
 1361:              System.out.println(node6.name + " " + node6.getCharacters());
 1362:              if(node4==null) throw new Error("parse error table tag missing");
 1363:              // if(node5==null) throw new Error("parse error select tag missing");
 1364:              // if(node6==null) throw new Error("parse error create tag missing");
 1365:              String name = (String)node4.attributes.get("name");
 1366:              String layout = (String)node4.attributes.get("layout");
 1367:              String id = (String)node4.attributes.get("id");
 1368:              System.out.println("id was "+id);
 1369:          
 1370:              if(name==null) throw new Error("parse error required table tag attribute name missing");
 1371:              if(layout==null) layout ="";
 1372:              if(id == null)  id="";
 1373:              if(name.equals("")) throw new Error("parse error table tag attribute must not be empty");
 1374:              tables.add(name);
 1375:              layouts.add(layout);
 1376:              ids.add(id);
 1377:              String query = (node5==null) ? "":node5.getCharacters(); 
 1378:              if(query.equals("")) System.err.println("Warning empty select tag or  select tag missing !!");
 1379:              query = (query.equals("")) ? "select * from "+database.getQC()+name+database.getQC():query;
 1380:              selects.add(query);
 1381:              if(node6!=null) creates.add(node6.getCharacters().trim());
 1382:               else
 1383:                creates.add("");
 1384:             
 1385:            }
 1386:            databases.add(new DataBase(database, tables, layouts, selects,creates,ids,mode));
 1387:          }
 1388:          DBBean database = new DBBean();
 1389:          // parse dataBase
 1390:          Node node = root.find("convert/destination/database/url", new int[] { 1, 1, 1, 1 });
 1391:          Node node1 = root.find("convert/destination/database/user", new int[] { 1, 1, 1, 1, 1 });
 1392:          Node node2 = root.find("convert/destination/database/password", new int[] { 1, 1, 1, 1, 1 });
 1393:          String url = node.getCharacters();
 1394:          String user = node1.getCharacters();
 1395:          String password = node2.getCharacters();
 1396:          System.out.println(url);
 1397:          database.setURL(url.trim());
 1398:          database.setUserAndPasswd(user.trim(), password.trim());
 1399:          databases.add(new DataBase(database,null,null,null,null,null,0));
 1400:          //databases.add(database);
 1401:     /*    for (Iterator iter = databases.iterator(); iter.hasNext();)
 1402:        {
 1403:          DataBase db = (DataBase) iter.next();
 1404:          convertBatch(db.bean,database,db.tables,db.layouts,db.selects,db.creates);
 1405:         
 1406:        }*/
 1407:          // printContents(node3);
 1408:          //   FM2SQL.fmInstance=new FM2SQL();
 1409:        } catch (Exception e)
 1410:        {
 1411:          // TODO Auto-generated catch block
 1412:          e.printStackTrace();
 1413:        }
 1414:        return databases;
 1415:       }
 1416: 
 1417: 
 1418:     private static int countNodes(Node tempNode)
 1419:     {
 1420:       int length = 0;
 1421:       for(int i=0;i<tempNode.contents.v.size();++i)    {
 1422:       Node node=(Node)tempNode.contents.v.elementAt(i);
 1423:       if(node.type.equals("element"))
 1424:       {
 1425:         if(node.name.equals("database"))length++;
 1426:         if(node.name.equals("table"))length++;
 1427:       }
 1428:       
 1429:             // System.out.println(((Node)tempNode.contents.v.elementAt(i)).attributes+" "+i);
 1430:        }
 1431:      return length;
 1432:     }
 1433:     private static void printContents(Node root)
 1434:     {
 1435:         
 1436:       
 1437:       Vector contents=(root.index==null)? root.contents.v:root.index.v;
 1438:       for (int i=0;i<contents.size();++i)
 1439:       {
 1440:         Node n=(Node)contents.elementAt(i);
 1441:         if(n.type.equals("element"))
 1442:         {
 1443:            System.out.println("tag "+n.name);
 1444:            System.out.println(n.getCharacters());
 1445:           //contents=n.contents.v i=0;
 1446:         }
 1447:         // System.out.println(n.type);
 1448:       
 1449:         
 1450:       
 1451:       }
 1452:     }
 1453:     public static void readXMLFile(String xmlFile)
 1454:     {
 1455:     try 
 1456:         {
 1457:            // read XML Metadata from a file
 1458:            FileInputStream fi= new FileInputStream(xmlFile);
 1459:            InputStreamReader isr= new InputStreamReader(fi,"UTF-8");
 1460:            BufferedReader buffr = new BufferedReader(isr);
 1461:            StringBuffer sb=new StringBuffer();
 1462:            int c=0;
 1463:            while ((c = buffr.read()) != -1) 
 1464:            {
 1465:              char ch=(char)c;
 1466:              sb.append(ch);
 1467:              // System.out.print((char)c);
 1468:            }
 1469:            parseXMLConfig(sb);
 1470:        } catch(Exception e) { e.printStackTrace();} 
 1471:     }
 1472: public static class DataBase 
 1473: {
 1474:   DBBean bean;
 1475:   Vector creates;
 1476:   Vector selects;
 1477:   Vector layouts;
 1478:   Vector tables;
 1479:   Vector ids;
 1480:   final static int CONVERT_MODE = 1;
 1481: 	final static int APPEND_MODE  = 2;
 1482: 	final static int UPDATE_MODE  = 3;
 1483:   int mode = -1;
 1484:   
 1485:   public DataBase(DBBean bean,Vector tables,Vector layouts,Vector selects,Vector creates,Vector ids,int mode)
 1486:   {
 1487:     this.bean = bean;
 1488:     this.tables = tables;
 1489:     this.layouts = layouts;
 1490:     this.selects = selects;
 1491:     this.creates = creates;
 1492:     this.ids     = ids;
 1493:     this.mode = mode;
 1494:     this.bean.setIDVector(ids);
 1495:   }
 1496:   public void exportToXML(BufferedWriter buffr) throws Exception
 1497:    {
 1498:     // ids=bean.getIDVector();
 1499:      buffr.write("    <database>\n");
 1500:      buffr.write("      <url>"+bean.url+"</url>\n");
 1501:      buffr.write("      <user>"+bean.user+"</user>\n");
 1502:      buffr.write("      <password>"+bean.passwd+"</password>\n");
 1503:      String modeString ="";
 1504:     if (mode == CONVERT_MODE)
 1505:       modeString = "convert";
 1506:     else
 1507:       if (mode == APPEND_MODE)
 1508:         modeString = "append";
 1509:       else
 1510:         if (mode == UPDATE_MODE)
 1511:           modeString = "update";
 1512:   
 1513:      buffr.write("      <mode>"+ modeString+"</mode>\n");
 1514:      int index = 0;
 1515:      while(index<tables.size())
 1516:      {
 1517:        String table=(String)tables.get(index);
 1518:        String layout=(String)layouts.get(index);
 1519:        String select=(String)selects.get(index);
 1520:        String create=(String)creates.get(index);
 1521:        String id=(String)ids.get(index);
 1522:    
 1523:        buffr.write("      <table name = \""+table+"\" layout = \""+layout+"\" id = \""+id+"\" >\n");
 1524:        buffr.write("         <select>"+ convertToEntities(select)+"</select>\n");
 1525:        if(!create.equals(""))
 1526:        buffr.write("         <create>"+create+"         </create>\n"); 
 1527:        buffr.write("      </table>\n");
 1528:        index++;
 1529:      }
 1530:      buffr.write("    </database>\n"); 
 1531:    }
 1532: public String toString() {return bean.url+" "+tables;}
 1533: 
 1534: }
 1535: public static String convertToUTF8(Object command)
 1536: {
 1537:   String str = null;
 1538:   try
 1539:   {
 1540:     str = new String(command.toString().getBytes("UTF-8"));
 1541:   } catch (UnsupportedEncodingException e)
 1542:   {
 1543:     // TODO Auto-generated catch block
 1544:     e.printStackTrace();
 1545:   }
 1546:   return str;
 1547: }
 1548:   public static void writeConfig(String file, DataBase source, DataBase destination) throws Exception
 1549:   {
 1550:     if(!file.toLowerCase().endsWith(".xml")) file+=".xml"; 
 1551:     File f = new File(file);
 1552:   
 1553:     FileOutputStream fout= new FileOutputStream(f);
 1554:     OutputStreamWriter outsw = new OutputStreamWriter(fout,"UTF-8");
 1555:     BufferedWriter buffw = new BufferedWriter(outsw);
 1556:     buffw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
 1557:     buffw.newLine();
 1558:     buffw.write("<convert>\n");
 1559:     buffw.write("  <source>\n");
 1560:     source.exportToXML(buffw);
 1561:     buffw.write("  </source>\n");
 1562:     buffw.write("\n  <destination>\n");
 1563:     destination.exportToXML(buffw);
 1564:     buffw.write("  </destination>\n");
 1565:     buffw.write("</convert>\n");
 1566:     buffw.close();
 1567:   } 
 1568: }  

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