File:  [Repository] / FM2SQL / Attic / Convert.java
Revision 1.14: download - view: text, annotated - select for diffs - revision graph
Mon Jan 19 08:24:37 2004 UTC (20 years, 5 months ago) by rogo
Branches: MAIN
CVS tags: HEAD
update mode implemented

    1: 
    2: 
    3: import java.util.*;
    4: import java.sql.*;
    5: import java.awt.Cursor;
    6: import java.io.BufferedReader;
    7: import java.io.BufferedWriter;
    8: import java.io.File;
    9: import java.io.FileInputStream;
   10: import java.io.FileNotFoundException;
   11: import java.io.FileOutputStream;
   12: import java.io.InputStreamReader;
   13: import java.io.OutputStreamWriter;
   14: import java.io.PrintStream;
   15: import java.io.UnsupportedEncodingException;
   16: 
   17: import com.exploringxml.xml.Node;
   18: import com.exploringxml.xml.Xparse;
   19: 
   20: class Convert 
   21: {
   22: 	static DBBean bean = new DBBean();
   23: 	static DBBean beanDest = new DBBean();
   24: 
   25:   static String user ="",passwd="e1nste1n";
   26:   static String userDest="postgres",passwdDest="rogo";
   27:   static boolean batchRun=false;
   28:   static Vector databases = new Vector();
   29:   
   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:         Vector row = null;
  386:         command = new StringBuffer();
  387: 
  388:         command.append("UPDATE ");
  389:         command.append(beanDest.getQC());
  390:         command.append(convertText((String) names.get(tbIndex)));
  391:         command.append(beanDest.getQC());
  392:         command.append(" SET  ");
  393: 
  394:         int size = bean.getColumnNames().size();
  395:         for (int i = 0; i < size - 1; ++i)
  396:           command.append(convertText((String)bean.getColumnNames().get(i))+" = ? ,");
  397:         command.append(convertText((String)bean.getColumnNames().get(size-1))+" = ? ");
  398:         command.append("WHERE "+ids.get(tbIndex)+ " =  ?");
  399:         PreparedStatement pstm = beanDest.getConnection().prepareStatement(command.toString());
  400:         System.out.println(command+" "+tbIndex);
  401:         int rowCount = bean.getRowCount(query);
  402:         int idIndex = bean.getColumnNames().indexOf(ids.get(tbIndex) );
  403:         while ((row = bean.getNextRow()) != null)
  404:         {
  405:           j++;
  406:           //print rows
  407:           Object obj = null;
  408:           /* for(int k=0;k<row.size()-1;++k)
  409:            {
  410:           		obj = row.get(k);
  411:           		//System.out.println("row "+obj+" "+k);
  412:           	 if(obj!=null&&!(obj instanceof ArrayList))
  413:           	 command.append("'"+convertUml(obj.toString())+"',"); 
  414:           	 else if(obj!=null&&   obj instanceof ArrayList)
  415:           	 command.append("'"+convertUml(((ArrayList)obj).get(0).toString())+"',"); 
  416:           	 else command.append("NULL,");
  417:            }
  418:            obj = row.get(row.size() - 1);
  419:            if (obj != null && !(obj instanceof ArrayList))
  420:            command.append("'"+convertUml(obj.toString())+"')"); 
  421:           	else
  422:           	if(obj!=null&&   obj instanceof ArrayList)
  423:           	 command.append("'"+convertUml(((ArrayList)obj).get(0).toString())+"')");         //command.append(obj.toString()+")");
  424:           	 else command.append("NULL)");
  425:           	*/
  426:           //command.append("'"+row.get(row.size()-1)+"')"); 
  427:           //command.append(" )");
  428:           //  for(int k=0;k<row.size();++k)
  429: 
  430:           // System.out.println();
  431:           //   System.out.println(command+" "+j+" "+row.size()+" "+  ((Vector)result2[0].get(j)).size());
  432:           // System.out.println(command);
  433:           for (int k = 0; k < row.size(); ++k)
  434:           {
  435:             obj = row.get(k);
  436:             if (obj instanceof ArrayList)
  437:               obj = ((List) obj).get(0);
  438:             String str = (obj == null) ? "NULL" : obj.toString();
  439:             if (!str.equals("NULL"))
  440:               pstm.setString(k + 1, str);
  441:             else
  442:               pstm.setNull(k + 1, Types.NULL);
  443:           }
  444:          pstm.setString(row.size()+1,row.get(idIndex).toString());
  445: 				 System.out.println(pstm.toString());
  446: 				// System.exit(0);
  447:           pstm.execute();
  448:           //stm.executeUpdate(command.toString());
  449:           if(dialog!=null)
  450:           dialog.progress.setValue((int) (((double) (j + 1) / (double) rowCount) * 100.0));
  451:           // System.out.println( (int)(((double)(j+1)/(double)result[0].size())*100.0)+" "+result[0].size()+" "+j);
  452:           command = null;
  453:         } // to for loop    
  454: 
  455:       }
  456:     } catch (Exception e)
  457:     {
  458:       System.out.println("Error while connecting to database " + e);
  459:       dialog.setVisible(false);
  460:       dialog.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
  461:       FM2SQL.fmInstance.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
  462:       java.io.ByteArrayOutputStream b = new java.io.ByteArrayOutputStream();
  463:       java.io.PrintStream stream = new java.io.PrintStream(b);
  464:       stream.print(command + "\n\n");
  465:       e.printStackTrace(stream);
  466:       FM2SQL.showErrorDialog(b.toString(), "Error occured !");
  467: 
  468:     }
  469:     dialog.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
  470:     FM2SQL.fmInstance.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
  471: 
  472:     dialog.setVisible(false);
  473:   }
  474: 
  475: 
  476: 
  477:   public static void  convert(String source,String destination,Vector names,Vector layouts,Vector selects,Vector creates,int mode) throws Exception
  478:   {
  479:    FM2SQL.ProgressDialog dialog = new  FM2SQL.ProgressDialog(FM2SQL.fmInstance);
  480:    dialog.setTitle("Conversion running ...");
  481:    dialog.title.setText("Getting table data ...");
  482:    dialog.setLocation(FM2SQL.fmInstance.getLocationOnScreen().x+(FM2SQL.fmInstance.getWidth()-400)/2,FM2SQL.fmInstance.getLocationOnScreen().y+(FM2SQL.fmInstance.getHeight()-250)/2); 
  483: 	 dialog.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
  484: 	 FM2SQL.fmInstance.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
  485:    dialog.thread=Thread.currentThread();
  486:    // setting user and passwd 
  487:    bean.setUserAndPasswd(user,passwd);
  488:   // setting user and passwd 
  489:   beanDest.setUserAndPasswd(userDest,passwdDest);
  490:   dialog.setSize(400,250);
  491:    StringBuffer command= null;
  492:    String query = null;
  493:     try
  494:     {
  495:       //bean.setConnection("jdbc:fmpro:http://141.14.237.74:8050");    
  496: 	  //bean.setConnection("jdbc:postgresql://erebos/test","postgres","rogo");
  497:       bean.setConnection(source);
  498:       if(names==null)
  499:        names=bean.getTableNames();
  500:      // Collections.sort(names);
  501:         int tbIndex = 1;
  502:      
  503:      // System.out.println("Start at "+names.indexOf("archimedes_facsimiles"));
  504:       for(tbIndex=0;tbIndex<names.size();++tbIndex)
  505:       {
  506:         Vector[] result = null;
  507:        try {
  508: 	    query = "select * from " + bean.getQC() +names.get(tbIndex).toString() + bean.getQC();
  509: 	   String layout=(layouts.isEmpty()) ? "":layouts.get(tbIndex).toString(); 
  510:      query = (selects!=null) ? selects.get(tbIndex).toString():query;
  511:         //if  vectors[1].get(i) != null)
  512:         if (layout != "")
  513:         {
  514:           layout = " layout " + bean.getQC() + layout + bean.getQC();
  515:           String name = names.get(tbIndex).toString();
  516:           StringBuffer queryLayout = new StringBuffer(query);
  517:           queryLayout.insert(queryLayout.indexOf(name) + name.length() + 1, " " + layout);
  518:           query = queryLayout.toString();
  519:           System.out.println("added layout  "+ query);
  520:         
  521:         }
  522:         //  if ( layout!= "")
  523:         //	 query += " layout " + bean.getQC() + layout + bean.getQC();
  524:         dialog.title.setText("Getting table data ...");
  525:         dialog.table.setText(names.get(tbIndex).toString());
  526:         dialog.status.setText("Table " + (tbIndex + 1) + " of " + names.size());
  527:         dialog.show();
  528:         //result = bean.getQueryData(query, dialog, 0);
  529:         bean.getConnection();
  530:         bean.makeQuery(query,0);
  531:       } catch (Exception e)
  532:         {
  533:           continue;
  534:         }
  535:         //beanDest.setConnection("jdbc:postgresql://erebos/test3");
  536:         beanDest.setConnection(destination);
  537: 
  538:         Statement stm = beanDest.getConnection().createStatement();
  539: 
  540:         Vector tables = beanDest.getTableNames();
  541:        // Collections.sort(tables);
  542:         System.out.println(names.get(tbIndex) + " " + tables.indexOf(convertText((String) names.get(tbIndex)))); // "//beanDest.getTypeNames()); 
  543:         tables = beanDest.getTableNames();
  544:         // System.out.println(beanDest.getTableNames(beanDest.getCatalogs().get(2).toString()));
  545:         stm = beanDest.getConnection().createStatement();
  546:         // System.exit(0);
  547:       if(mode==Convert.DataBase.CONVERT_MODE) 
  548:       {
  549:         if(tables.indexOf(names.get(tbIndex))>=0) 
  550:         {
  551:          stm.executeUpdate("drop table "+beanDest.getQC()+names.get(tbIndex)+beanDest.getQC());
  552:         tables.remove((String)names.get(tbIndex));
  553:         System.out.println("dropped table"+ names.get(tbIndex));
  554:         }
  555:         else
  556:         if(tables.indexOf(convertText(names.get(tbIndex).toString()))>=0) 
  557:         {
  558:          stm.executeUpdate("drop table "+beanDest.getQC()+convertText((String)names.get(tbIndex))+beanDest.getQC());
  559:         tables.remove(convertText((String)names.get(tbIndex)));
  560:         System.out.println("dropped table"+ names.get(tbIndex));
  561:         }
  562:  
  563: 				if(tables.indexOf(names.get(tbIndex))<0&&tables.indexOf(convertText(names.get(tbIndex).toString()))<0) 
  564:         {
  565:           if(creates.get(tbIndex).equals("")||creates.get(tbIndex).toString().toLowerCase().indexOf("create")<0)
  566:           {
  567:             System.out.println("Warning empty or invalid create statement - creating one for you\n");
  568:         
  569:           command = new StringBuffer(50);
  570:           command.append("CREATE TABLE ");
  571:           command.append(beanDest.getQC());
  572:           command.append(convertText((String)names.get(tbIndex)));
  573:           command.append(beanDest.getQC());
  574:           command.append("(");
  575:            String type = null;
  576:           Vector columnNames = bean.getColumnNames();
  577:           for(int i=0;i<columnNames.size()-1;++i)
  578:           {
  579:            type = bean.metaData.getColumnTypeName(i+1);
  580:          //   System.out.println(i+" "+result[1].get(i)+" "+type);
  581:           type = (type.equals("NUMBER")) ?"INT4":type;
  582:           type = (type.equals("CONTAINER")) ?"TEXT":type;
  583: 
  584:           command.append(beanDest.getQC() + convertText((String) columnNames.get(i)) + beanDest.getQC() + " " + type + ", ");
  585:         }
  586:           type = bean.metaData.getColumnTypeName(columnNames.size());
  587:           type = (type.equals("NUMBER")) ? "INT4" : type;
  588:           type = (type.equals("CONTAINER")) ? "TEXT" : type;
  589:           command.append(beanDest.getQC() + convertText((String) columnNames.get(columnNames.size() - 1)) + beanDest.getQC() + " " + type);
  590:           command.append(" )");
  591: 
  592:           // System.out.println(command);
  593:           //  System.exit(0);
  594:           //command.append(DBBean.getQC());   
  595:           } else
  596:           command=new StringBuffer().append(creates.get(tbIndex).toString());
  597:           stm.executeUpdate(command.toString());
  598:         
  599:       }
  600:     }
  601:     // System.out.println(names);
  602:     /*    
  603:     if (idVal == "")
  604:           stm.executeUpdate("INSERT  INTO " + DBBean.getQC() + box.getSelectedItem() + DBBean.getQC() + " (" + DBBean.getQC() + columnName + DBBean.getQC() + ")  VALUES ('" + value + "') ");
  605:         else
  606:           stm.executeUpdate("UPDATE   " + DBBean.getQC() + box.getSelectedItem() + DBBean.getQC() + " SET  " + DBBean.getQC() + columnName + DBBean.getQC() + "='" + value + "' WHERE ID='" + idVal + "' ");
  607:       */
  608: 
  609:     // Vector[] result2=beanDest.getQueryData(names.get(tbIndex).toString());
  610:     // print results to screen
  611:    /* for (int i = 0; i < result[1].size(); ++i)
  612:     {
  613:       //print Header
  614:       // System.out.println(" "+result[1].get(i)+" "+result2[1].get(i)+" "+i);
  615:     }*/
  616:     // System.out.println();
  617:     dialog.title.setText("Writing table data ...");
  618:     
  619:     //for (int j = 0; j < result[0].size(); ++j)
  620:     int j=-1;
  621:     Vector row = null;
  622:     command = new StringBuffer();
  623: 
  624:     command.append("INSERT  INTO ");
  625:     command.append(beanDest.getQC());
  626:     command.append(convertText((String) names.get(tbIndex)));
  627:     command.append(beanDest.getQC());
  628:     command.append(" values ( ");
  629:     
  630:     for(int i=0;i<bean.getColumnNames().size()-1;++i) command.append("?,");
  631:     command.append("?)");
  632:     PreparedStatement pstm = beanDest.getConnection().prepareStatement(command.toString());
  633:     System.out.println(command);
  634:     int rowCount= bean.getRowCount(query);
  635:     while((row=bean.getNextRow())!=null)
  636:     {
  637:       j++;
  638:       // row = (Vector) result[0].get(j);
  639:    /*   command = new StringBuffer();
  640: 
  641:         command.append("INSERT  INTO ");
  642:         command.append(beanDest.getQC());
  643:         command.append(convertText((String) names.get(tbIndex)));
  644:         command.append(beanDest.getQC());
  645:         command.append(" values ( ");
  646:      */
  647:            //print rows
  648:      Object obj = null;
  649:     /* for(int k=0;k<row.size()-1;++k)
  650:      {
  651:         obj = row.get(k);
  652:         //System.out.println("row "+obj+" "+k);
  653:        if(obj!=null&&!(obj instanceof ArrayList))
  654:        command.append("'"+convertUml(obj.toString())+"',"); 
  655:        else if(obj!=null&&   obj instanceof ArrayList)
  656:        command.append("'"+convertUml(((ArrayList)obj).get(0).toString())+"',"); 
  657:        else command.append("NULL,");
  658:      }
  659:      obj = row.get(row.size() - 1);
  660:      if (obj != null && !(obj instanceof ArrayList))
  661:      command.append("'"+convertUml(obj.toString())+"')"); 
  662:       else
  663:       if(obj!=null&&   obj instanceof ArrayList)
  664:        command.append("'"+convertUml(((ArrayList)obj).get(0).toString())+"')");         //command.append(obj.toString()+")");
  665:        else command.append("NULL)");
  666:       */
  667:       //command.append("'"+row.get(row.size()-1)+"')"); 
  668:       //command.append(" )");
  669:       //  for(int k=0;k<row.size();++k)
  670: 
  671:       // System.out.println();
  672:       //   System.out.println(command+" "+j+" "+row.size()+" "+  ((Vector)result2[0].get(j)).size());
  673:       // System.out.println(command);
  674:       for(int k=0;k<row.size();++k) 
  675:       {
  676:         obj = row.get(k);
  677:         if(obj instanceof ArrayList) obj=((List)obj).get(0);
  678:         String str =(obj==null) ? "NULL":obj.toString();
  679:         if(!str.equals("NULL"))
  680:         pstm.setString(k+1,str); 
  681:         else pstm.setNull(k+1,Types.NULL);
  682:       }
  683:       pstm.execute();
  684:       //stm.executeUpdate(command.toString());
  685:       dialog.progress.setValue((int) (((double) (j + 1) / (double) rowCount) * 100.0));
  686: 	// System.out.println( (int)(((double)(j+1)/(double)result[0].size())*100.0)+" "+result[0].size()+" "+j);
  687:    command = null;
  688: }// to for loop    
  689:    
  690:     }
  691:  } catch(Exception e) 
  692:    {
  693:      System.out.println("Error while connecting to database "+ e);
  694:      dialog.setVisible(false);
  695: 	   dialog.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
  696: 		 FM2SQL.fmInstance.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
  697: 		 java.io.ByteArrayOutputStream b = new java.io.ByteArrayOutputStream();
  698: 		 java.io.PrintStream stream = new java.io.PrintStream(b);
  699: 		 stream.print(command+"\n\n");
  700: 		 e.printStackTrace(stream);
  701: 		 FM2SQL.showErrorDialog(b.toString(), "Error occured !");
  702: 	 
  703:    }
  704: 	 dialog.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
  705: 	 FM2SQL.fmInstance.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
  706: 
  707: 	 dialog.setVisible(false); 
  708:   }
  709: 
  710:  public static String convertText(String newName)
  711:   {
  712:     StringBuffer alterMe = new StringBuffer(newName.trim().toLowerCase());
  713:     int length = alterMe.length();
  714:     int j = 0;
  715:     int index=alterMe.indexOf(".fp5");
  716:     if ( index >= 0 )
  717:      {
  718:        alterMe.delete(index, index + 4);
  719:        length = length - 4;
  720:      }
  721:  
  722:     while (j < length)
  723:     { 
  724:       if (alterMe.charAt(j) == ' ')
  725:       {
  726:         alterMe.setCharAt(j, '_');
  727:     //    if(j<length-1) j=j+1;
  728:       }
  729:       else
  730:       if (alterMe.charAt(j) == '_')
  731:       {
  732: 		
  733: 		if(alterMe.charAt(j+1)=='_')
  734: 		alterMe.deleteCharAt(j);
  735:         length = length-1;
  736:       //  if(j<length-1) j=j+1;
  737:       }
  738:      else
  739: 	 if (alterMe.charAt(j) == 'ä')
  740: 		  {
  741: 			alterMe.setCharAt(j, 'a');
  742: 			alterMe.insert(j+1,"e");
  743: 			length=length+1;
  744: 			if(j<length-1) j=j+1;
  745: 		  }
  746: 		else
  747: 		 if (alterMe.charAt(j) == 'ö')
  748: 			  {
  749: 				alterMe.setCharAt(j, 'o');
  750: 				alterMe.insert(j+1,"e");
  751: 				length=length+1;
  752: 				if(j<length-1) j=j+1;
  753: 			  }
  754: 		else
  755: 		 if (alterMe.charAt(j) == 'ü')
  756: 			  {
  757: 				alterMe.setCharAt(j, 'u');
  758: 				alterMe.insert(j+1,"e");
  759: 				length=length+1;
  760: 				if(j<length-1) j=j+1;
  761: 			  }
  762: 		else
  763:     if (alterMe.charAt(j) == 'ß')
  764:     {
  765:       alterMe.setCharAt(j, 's');
  766:       alterMe.insert(j + 1, "s");
  767:       length = length + 1;
  768:       if (j < length - 1)
  769:         j = j + 1;
  770:     } else if (alterMe.charAt(j) == ':')
  771:     {
  772:       if(j<length-1)
  773:       {
  774:       if (alterMe.charAt(j + 1) == ':')
  775:       {
  776:         alterMe.setCharAt(j,'_');
  777:         alterMe.delete(j+1,j+2);
  778:       length = length - 1;
  779:    
  780:       }
  781:  
  782:       if (j < length - 1)
  783:         j = j + 1;
  784:       }
  785:     } else if (alterMe.charAt(j) == '-')
  786:     {
  787:       alterMe.setCharAt(j, '_');
  788: 
  789:     }
  790:     else if (alterMe.charAt(j) == '.')
  791:     {
  792:       if(j==length-1)
  793:       {
  794:         alterMe.delete(j, j); 
  795:         length--;
  796:       }
  797: 			else
  798: 			alterMe.setCharAt(j,'_');
  799:     }
  800: 
  801:     ++j;
  802:   }
  803:     return alterMe.toString();
  804:   }
  805:   public static String convertToEntities(String newName)
  806:   {
  807:     StringBuffer alterMe = new StringBuffer(newName.trim());
  808:     int length = alterMe.length();
  809:     int j = 0;
  810: 
  811:     while (j < length)
  812:     {
  813: 
  814:       if (alterMe.charAt(j) == '>')
  815:       {
  816:         alterMe.setCharAt(j, '&');
  817:         alterMe.insert(j + 1, "gt;");
  818:         length = length + 2;
  819:         if (j < length - 1)
  820:           j = j + 1;
  821: 
  822:       } else if (alterMe.charAt(j) == '<')
  823:       {
  824:         alterMe.setCharAt(j, '&');
  825:         alterMe.insert(j + 1, "lt;");
  826:         length = length + 2;
  827:         if (j < length - 1)
  828:           j = j + 1;
  829: 
  830:       }
  831:       ++j;
  832:     }
  833:     return alterMe.toString();
  834:   }
  835:   public static String convertUml(String newName)
  836:    {
  837: 	 StringBuffer alterMe = new StringBuffer(newName.trim());
  838: 	 int length = alterMe.length();
  839: 	 int j = 0;
  840: 	
  841: 	
  842: 	 while (j < length)
  843: 	 { 
  844: 	
  845: 	   if (alterMe.charAt(j) == '\'')
  846: 	   {
  847: 		 alterMe.setCharAt(j, '\\');
  848: 		 alterMe.insert(j + 1, "'");
  849: 		 length = length + 1;
  850: 		 if(j<length-1) j=j+1;
  851: 	   }
  852: 	/*   else
  853: 	   if (alterMe.charAt(j) == '"')
  854: 	   {
  855: 		 alterMe.setCharAt(j, '\\');
  856: 		 alterMe.insert(j + 1, "\"");
  857: 		 length = length + 1;
  858: 		 if(j<length-1) j=j+1;
  859: 	   }
  860: 	  else
  861: 	  if (alterMe.charAt(j) == '>')
  862: 	   {
  863: 		 alterMe.setCharAt(j, '\\');
  864: 		 alterMe.insert(j + 1, ">");
  865: 		 length = length + 1;
  866: 		 if(j<length-1) j=j+1;
  867: 	   }
  868: 	  else
  869: 	  if (alterMe.charAt(j) == '<')
  870: 	   {
  871: 		 alterMe.setCharAt(j, '\\');
  872: 		 alterMe.insert(j + 1, "<");
  873: 		 length = length + 1;
  874: 		 if(j<length-1) j=j+1;
  875: 	   }
  876: 	 else
  877: 	 if (alterMe.charAt(j) == '?')
  878: 	   {
  879: 		 alterMe.setCharAt(j, '\\');
  880: 		 alterMe.insert(j + 1, "?");
  881: 		 length = length + 1;
  882: 		 if(j<length-1) j=j+1;
  883: 	   }
  884: 	 else
  885: 	 if (alterMe.charAt(j) == '&')
  886: 	   {
  887: 		 alterMe.setCharAt(j, '\\');
  888: 		 alterMe.insert(j + 1, "&");
  889: 		 length = length + 1;
  890: 		 if(j<length-1) j=j+1;
  891: 	   }
  892: 	 else
  893: 	 if (alterMe.charAt(j) == '=')
  894: 	   {
  895: 		 alterMe.setCharAt(j, '\\');
  896: 		 alterMe.insert(j + 1, "=");
  897: 		 length = length + 1;
  898: 		 if(j<length-1) j=j+1;
  899: 	   }
  900: 	 else
  901: 	 if (alterMe.charAt(j) == ',')
  902: 	   {
  903: 		 alterMe.setCharAt(j, '\\');
  904: 		 alterMe.insert(j + 1, ",");
  905: 		 length = length + 1;
  906: 		 if(j<length-1) j=j+1;
  907: 	   }
  908: 	 else
  909: 	 if (alterMe.charAt(j) == '.')
  910: 	   {
  911: 		 alterMe.setCharAt(j, '\\');
  912: 		 alterMe.insert(j + 1, ".");
  913: 		 length = length + 1;
  914: 		 if(j<length-1) j=j+1;
  915: 	   }
  916: 	 else
  917: 	 if (alterMe.charAt(j) == '[')
  918: 	   {
  919: 		 alterMe.setCharAt(j, '\\');
  920: 		 alterMe.insert(j + 1, ".");
  921: 		 length = length + 1;
  922: 		 if(j<length-1) j=j+1;
  923: 	   }
  924: 	else
  925: 	 if (alterMe.charAt(j) == ']')
  926: 	   {
  927: 		 alterMe.setCharAt(j, '\\');
  928: 		 alterMe.insert(j + 1, ".");
  929: 		 length = length + 1;
  930: 		 if(j<length-1) j=j+1;
  931: 	   }
  932: 	else
  933: 	 if (alterMe.charAt(j) == '%')
  934: 	   {
  935: 		 alterMe.setCharAt(j, '\\');
  936: 		 alterMe.insert(j + 1, "%");
  937: 		 length = length + 1;
  938: 		 if(j<length-1) j=j+1;
  939: 	   }*/
  940: 		++j;
  941: 	 }
  942: 	 return alterMe.toString();
  943:    }
  944:    
  945:    public static void parseXMLConfig(StringBuffer sb)
  946:     {
  947:       boolean finished = false;
  948:       // parse string and build document tree
  949:       Xparse parser =new Xparse();
  950:       parser.changeEntities = true;
  951:       Node  root = parser.parse(sb.toString());
  952:        // printContents(root);
  953:       Vector databases= new Vector();
  954:       Vector tables = new Vector();
  955:       Vector layouts = new Vector();
  956:       Vector selects = new Vector();
  957:       Vector creates = new Vector();
  958: 			Vector ids     = new Vector();
  959:       int mode = -1;
  960:    
  961:       try
  962:       {
  963:         Node tempNode = root.find("convert/source", new int[] { 1, 1 });
  964:         if(tempNode==null) throw new Error("parse error source tag missing");
  965:         System.out.println(tempNode.name);
  966:         int length =countNodes(tempNode);
  967:         for (int i = 1; i <= length; i++)
  968:         {
  969:           
  970:           DBBean database = new DBBean();
  971:           tables = new Vector();
  972:           layouts = new Vector();
  973:           selects = new Vector();
  974:           creates = new Vector();
  975:           ids     = new Vector();
  976:          // parse dataBase
  977:           Node node = root.find("convert/source/database/url", new int[] { 1, 1, i, 1 });
  978:           Node node1 = root.find("convert/source/database/user", new int[] { 1, 1, i, 1, 1 });
  979:           Node node2 = root.find("convert/source/database/password", new int[] { 1, 1, i, 1, 1 });
  980:           Node node3 = root.find("convert/source/database", new int[] { 1, 1, i});
  981:     			Node nodeMode = root.find("convert/source/database/mode/", new int[] {1, 1, i, 1,1});
  982: 
  983:           if(node3== null) throw new Error("parse error database tag missing");
  984:           if(node==null) throw new Error("parse error url tag missing");
  985:           if(node1==null) throw new Error("parse error user tag missing");
  986:           if(node2==null) throw new Error("parse error password tag missing");
  987:           String url=node.getCharacters();
  988:           String user=node1.getCharacters();
  989:           String password=node2.getCharacters();
  990:           database.setURL(url.trim());
  991:           database.setUserAndPasswd(user.trim(),password.trim());
  992:           System.out.println(node.name + " " + node.getCharacters());
  993:           System.out.println(node1.name + " " + node1.getCharacters());
  994:           System.out.println(node2.name + " " + node2.getCharacters());
  995:           String modeString = "";
  996:           if (nodeMode == null)
  997:             modeString = "convert";
  998:           else
  999:             modeString = nodeMode.getCharacters();
 1000:           if (modeString.equals("convert"))
 1001:             mode = DataBase.CONVERT_MODE;
 1002:           else
 1003:             if (modeString.equals("append"))
 1004:               mode = DataBase.APPEND_MODE;
 1005:             else
 1006:               if (modeString.equals("update"))
 1007:                 mode = DataBase.UPDATE_MODE;
 1008:        //   if(node3!=null)
 1009:          // System.out.println(node3.name);
 1010:           
 1011:           int length2= countNodes(node3);
 1012:     
 1013:          System.out.println("number of tables " +length2);
 1014:     
 1015:           for(int j=1;j<=length2;++j)
 1016:           {
 1017:             Node node4 = root.find("convert/source/database/table", new int[] { 1, 1, i, j });
 1018:             Node node5 = root.find("convert/source/database/table/select", new int[] { 1, 1, i, j, 1 });
 1019:             Node node6 = root.find("convert/source/database/table/create", new int[] { 1, 1, i, j, 1 });
 1020:             if(node4!=null)
 1021:             System.out.println(node4.name + " " + node4.attributes.get("layout").equals(""));
 1022:             if(node5!=null)
 1023:             System.out.println(node5.name + " " + node5.getCharacters());
 1024:             if(node6!=null)
 1025:             System.out.println(node6.name + " " + node6.getCharacters());
 1026:             if(node4==null) throw new Error("parse error table tag missing");
 1027:             // if(node5==null) throw new Error("parse error select tag missing");
 1028:             // if(node6==null) throw new Error("parse error create tag missing");
 1029:             String name = (String)node4.attributes.get("name");
 1030:             String layout = (String)node4.attributes.get("layout");
 1031:             String id = (String)node4.attributes.get("id");
 1032:             System.out.println("id was "+id);
 1033:             if(name==null) throw new Error("parse error required table tag attribute name missing");
 1034:             if(layout==null) layout ="";
 1035:             if(id==null)  id = "";
 1036:             if(name.equals("")) throw new Error("parse error table tag attribute must not be empty");
 1037:             tables.add(name);
 1038:             layouts.add(layout);
 1039:             ids.add(id);
 1040:             String query = (node5==null) ? "":node5.getCharacters(); 
 1041:             if(query.equals("")) System.err.println("Warning empty select tag or  select tag missing !!");
 1042:             query = (query.equals("")) ? "select * from "+database.getQC()+name+database.getQC():query;
 1043:             selects.add(query);
 1044:             if(node6!=null) creates.add(node6.getCharacters().trim());
 1045:              else
 1046:               creates.add("");
 1047:             
 1048:           }
 1049:           databases.add(new DataBase(database, tables, layouts, selects,creates,ids,mode));
 1050:         }
 1051:         DBBean database = new DBBean();
 1052:         // parse dataBase
 1053:         Node node = root.find("convert/destination/database/url", new int[] { 1, 1, 1, 1 });
 1054:         Node node1 = root.find("convert/destination/database/user", new int[] { 1, 1, 1, 1, 1 });
 1055:         Node node2 = root.find("convert/destination/database/password", new int[] { 1, 1, 1, 1, 1 });
 1056:         String url = node.getCharacters();
 1057:         String user = node1.getCharacters();
 1058:         String password = node2.getCharacters();
 1059:         System.out.println(url);
 1060:         database.setURL(url.trim());
 1061:         database.setUserAndPasswd(user.trim(), password.trim());
 1062:         //databases.add(database);
 1063:        for (Iterator iter = databases.iterator(); iter.hasNext();)
 1064:       {
 1065:         DataBase db = (DataBase) iter.next();
 1066:         convertBatch(db.bean,database,db.tables,db.layouts,db.selects,db.creates,mode);
 1067:         
 1068:       }
 1069:         // printContents(node3);
 1070:         //   FM2SQL.fmInstance=new FM2SQL();
 1071:       } catch (Exception e)
 1072:       {
 1073:         // TODO Auto-generated catch block
 1074:         e.printStackTrace();
 1075:       }
 1076:       /*
 1077:       Node tempNode=root.find(rootNode,new int[] {1});
 1078:       if(tempNode==null) return rtTag;
 1079:       int count=1;
 1080:       /* 
 1081:       for(int i=0;i<tempNode.contents.v.size();++i)
 1082:       {
 1083:         // System.out.println(((Node)tempNode.contents.v.elementAt(i)).attributes+" "+i);
 1084:       }*/
 1085:    /*
 1086:       if(tempNode.contents.v.size()==0) return rtTag;
 1087:       Node notNull=null;
 1088:       Node rtNode=root.find(rootNode+"/rt",new int[] {1,1});
 1089:       rtTag=(rtNode==null) ? "finished":rtNode.getCharacters();
 1090:       System.out.println("rt tag is "+ rtTag);
 1091:       int length=0;//(tempNode.contents.length()-1)/2;
 1092:       for(int i=0;i<tempNode.contents.v.size();++i)    {
 1093:         Node node=(Node)tempNode.contents.v.elementAt(i);
 1094:         if(node.type.equals("element"))
 1095:         if(node.name.equals("doc"))length++;
 1096:         // System.out.println(((Node)tempNode.contents.v.elementAt(i)).attributes+" "+i);
 1097:       }
 1098:      if(length==0) rtTag="finished";        
 1099:       while(count<=length)
 1100:       {
 1101:          //System.out.println(count+" "+length);
 1102:         tempNode=root.find(rootNode+"/doc",new int[] {1,count});
 1103:         if(tempNode==null)
 1104:         {
 1105:           rtTag="finished";
 1106:           break;
 1107:         }    
 1108:         Bundle.Document doc = new Bundle.Document();
 1109:         Hashtable attributes=tempNode.attributes;
 1110:         int docID=0;
 1111:         int ver=0;
 1112:          if(attributes != null)
 1113:         {
 1114:           docID=Integer.parseInt((String)attributes.get("id"));
 1115:           ver=Integer.parseInt((String)attributes.get("ver"));
 1116:           doc.addData("docID",(String)attributes.get("id"));
 1117:           doc.addData("ver",(String)attributes.get("ver"));
 1118:         }
 1119:         bundle.docs.put(new Integer(docID),doc);
 1120:         bundle.documents.addElement(doc);
 1121:         // System.out.println("id " +docID+" ver "+ver);
 1122:         Node fileNode=root.find(rootNode+"/doc/file",new int[] {1,count,1});
 1123:         attributes=(fileNode==null)? null:fileNode.attributes;
 1124:         int fileID=0;
 1125:         int fileVer=0;
 1126:         if(attributes != null)
 1127:         {
 1128:           fileID=Integer.parseInt((String)attributes.get("id"));
 1129:           fileVer=Integer.parseInt((String)attributes.get("ver"));
 1130:           doc.addData("fileID",(String)attributes.get("id"));
 1131:           doc.addData("fileVer",(String)attributes.get("ver"));
 1132:           // System.out.println("fileid " +fileID+" ver "+fileVer);
 1133:         }
 1134:      // add all Document tags to actual Document
 1135:         for(int i=0;i<tempNode.contents.v.size();++i)
 1136:         {   
 1137:           Node node=(Node)tempNode.contents.v.elementAt(i);
 1138:           if(node.type.equals("element"))
 1139:            {
 1140:              //System.out.println(node.name+" "+node.getCharacters()+" "+node.contents.v.size());
 1141:              if(node.contents.v.size()>1) 
 1142:              {
 1143:                for(int j=0;j<node.contents.v.size();++j)
 1144:                {  
 1145:                  Node node2=(Node)node.contents.v.elementAt(j);
 1146:                  if(node2.type.equals("element"))
 1147:                   {
 1148:                     doc.addData(node2.name,node2.getCharacters());
 1149:                     //System.out.println(node2.name+" "+node2.getCharacters()+" "+node2.contents.v.size());
 1150:                   }
 1151:                }
 1152:              } else doc.addData(node.name,node.getCharacters());
 1153:           }
 1154:         }
 1155:         bundle.docsLocator.put(doc.locator,doc); 
 1156:    
 1157:       bundle.documents.addElement(doc);
 1158:         count++;
 1159:       }      */
 1160:   
 1161:       // System.out.println(bundle.docs.size());
 1162:    // return rtTag;
 1163:     }
 1164:     public static Vector getXMLConfig(String xmlFile)
 1165:      {
 1166:        StringBuffer sb=null;
 1167:        try 
 1168:              {
 1169:                 // read XML Metadata from a file
 1170:                 FileInputStream fi= new FileInputStream(xmlFile);
 1171:                 InputStreamReader isr= new InputStreamReader(fi,"UTF-8");
 1172:                 BufferedReader buffr = new BufferedReader(isr);
 1173:                 sb=new StringBuffer();
 1174:                 int c=0;
 1175:                 while ((c = buffr.read()) != -1) 
 1176:                 {
 1177:                   char ch=(char)c;
 1178:                   sb.append(ch);
 1179:                   // System.out.print((char)c);
 1180:                 }
 1181:                
 1182:             } catch(Exception e) { e.printStackTrace();} 
 1183:   
 1184:        boolean finished = false;
 1185:        // parse string and build document tree
 1186:        Xparse parser =new Xparse();
 1187:        parser.changeEntities = true;
 1188:        Node  root = parser.parse(sb.toString());
 1189:    // printContents(root);
 1190:        Vector databases= new Vector();
 1191:        Vector tables = new Vector();
 1192:        Vector layouts = new Vector();
 1193:        Vector selects = new Vector();
 1194:        Vector creates = new Vector();
 1195:        Vector ids     = new Vector();
 1196:        
 1197:        int mode = -1;
 1198:        try
 1199:        {
 1200:          Node tempNode = root.find("convert/source", new int[] { 1, 1 });
 1201:          if(tempNode==null) throw new Error("parse error source tag missing");
 1202:          System.out.println(tempNode.name);
 1203:          int length =countNodes(tempNode);
 1204:          for (int i = 1; i <= length; i++)
 1205:          {
 1206:           
 1207:            DBBean database = new DBBean();
 1208:            tables = new Vector();
 1209:            layouts = new Vector();
 1210:            selects = new Vector();
 1211:            creates = new Vector();
 1212:            ids     = new Vector();
 1213:           // parse dataBase
 1214:            Node node = root.find("convert/source/database/url", new int[] { 1, 1, i, 1 });
 1215:            Node node1 = root.find("convert/source/database/user", new int[] { 1, 1, i, 1, 1 });
 1216:            Node node2 = root.find("convert/source/database/password", new int[] { 1, 1, i, 1, 1 });
 1217:            Node node3 = root.find("convert/source/database", new int[] { 1, 1, i});
 1218:            Node nodeMode = root.find("convert/source/database/mode", new int[] { 1, 1, i, 1, 1 });
 1219:            
 1220:            if(node3== null) throw new Error("parse error database tag missing");
 1221:            if(node==null) throw new Error("parse error url tag missing");
 1222:            if(node1==null) throw new Error("parse error user tag missing");
 1223:            if(node2==null) throw new Error("parse error password tag missing");
 1224:            String url=node.getCharacters();
 1225:            String user=node1.getCharacters();
 1226:            String password=node2.getCharacters();
 1227:            database.setURL(url.trim());
 1228:            database.setUserAndPasswd(user.trim(),password.trim());
 1229:            System.out.println(node.name + " " + node.getCharacters());
 1230:            System.out.println(node1.name + " " + node1.getCharacters());
 1231:            System.out.println(node2.name + " " + node2.getCharacters());
 1232:            String modeString = "";  
 1233:           if (nodeMode == null)
 1234:             modeString = "convert";
 1235:           else
 1236:             modeString = nodeMode.getCharacters();
 1237:           if (modeString.equals("convert"))
 1238:             mode = DataBase.CONVERT_MODE;
 1239:           else
 1240:             if (modeString.equals("append"))
 1241:               mode = DataBase.APPEND_MODE;
 1242:             else
 1243:               if (modeString.equals("update"))
 1244:                 mode = DataBase.UPDATE_MODE;
 1245: 			 
 1246:         
 1247:         //   if(node3!=null)
 1248:           // System.out.println(node3.name);
 1249:           
 1250:            int length2= countNodes(node3);
 1251:     
 1252:           System.out.println("number of tables " +length2);
 1253:     
 1254:            for(int j=1;j<=length2;++j)
 1255:            {
 1256:              Node node4 = root.find("convert/source/database/table", new int[] { 1, 1, i, j });
 1257:              Node node5 = root.find("convert/source/database/table/select", new int[] { 1, 1, i, j, 1 });
 1258:              Node node6 = root.find("convert/source/database/table/create", new int[] { 1, 1, i, j, 1 });
 1259:              if(node4!=null)
 1260:              System.out.println(node4.name + " " + node4.attributes.get("layout").equals(""));
 1261:              if(node5!=null)
 1262:              System.out.println(node5.name + " " + node5.getCharacters());
 1263:              if(node6!=null)
 1264:              System.out.println(node6.name + " " + node6.getCharacters());
 1265:              if(node4==null) throw new Error("parse error table tag missing");
 1266:              // if(node5==null) throw new Error("parse error select tag missing");
 1267:              // if(node6==null) throw new Error("parse error create tag missing");
 1268:              String name = (String)node4.attributes.get("name");
 1269:              String layout = (String)node4.attributes.get("layout");
 1270:              String id = (String)node4.attributes.get("id");
 1271:              System.out.println("id was "+id);
 1272:          
 1273:              if(name==null) throw new Error("parse error required table tag attribute name missing");
 1274:              if(layout==null) layout ="";
 1275:              if(id == null)  id="";
 1276:              if(name.equals("")) throw new Error("parse error table tag attribute must not be empty");
 1277:              tables.add(name);
 1278:              layouts.add(layout);
 1279:              ids.add(id);
 1280:              String query = (node5==null) ? "":node5.getCharacters(); 
 1281:              if(query.equals("")) System.err.println("Warning empty select tag or  select tag missing !!");
 1282:              query = (query.equals("")) ? "select * from "+database.getQC()+name+database.getQC():query;
 1283:              selects.add(query);
 1284:              if(node6!=null) creates.add(node6.getCharacters().trim());
 1285:               else
 1286:                creates.add("");
 1287:             
 1288:            }
 1289:            databases.add(new DataBase(database, tables, layouts, selects,creates,ids,mode));
 1290:          }
 1291:          DBBean database = new DBBean();
 1292:          // parse dataBase
 1293:          Node node = root.find("convert/destination/database/url", new int[] { 1, 1, 1, 1 });
 1294:          Node node1 = root.find("convert/destination/database/user", new int[] { 1, 1, 1, 1, 1 });
 1295:          Node node2 = root.find("convert/destination/database/password", new int[] { 1, 1, 1, 1, 1 });
 1296:          String url = node.getCharacters();
 1297:          String user = node1.getCharacters();
 1298:          String password = node2.getCharacters();
 1299:          System.out.println(url);
 1300:          database.setURL(url.trim());
 1301:          database.setUserAndPasswd(user.trim(), password.trim());
 1302:          databases.add(new DataBase(database,null,null,null,null,null,0));
 1303:          //databases.add(database);
 1304:     /*    for (Iterator iter = databases.iterator(); iter.hasNext();)
 1305:        {
 1306:          DataBase db = (DataBase) iter.next();
 1307:          convertBatch(db.bean,database,db.tables,db.layouts,db.selects,db.creates);
 1308:         
 1309:        }*/
 1310:          // printContents(node3);
 1311:          //   FM2SQL.fmInstance=new FM2SQL();
 1312:        } catch (Exception e)
 1313:        {
 1314:          // TODO Auto-generated catch block
 1315:          e.printStackTrace();
 1316:        }
 1317:        return databases;
 1318:       }
 1319: 
 1320: 
 1321:     private static int countNodes(Node tempNode)
 1322:     {
 1323:       int length = 0;
 1324:       for(int i=0;i<tempNode.contents.v.size();++i)    {
 1325:       Node node=(Node)tempNode.contents.v.elementAt(i);
 1326:       if(node.type.equals("element"))
 1327:       {
 1328:         if(node.name.equals("database"))length++;
 1329:         if(node.name.equals("table"))length++;
 1330:       }
 1331:       
 1332:             // System.out.println(((Node)tempNode.contents.v.elementAt(i)).attributes+" "+i);
 1333:        }
 1334:      return length;
 1335:     }
 1336:     private static void printContents(Node root)
 1337:     {
 1338:         
 1339:       
 1340:       Vector contents=(root.index==null)? root.contents.v:root.index.v;
 1341:       for (int i=0;i<contents.size();++i)
 1342:       {
 1343:         Node n=(Node)contents.elementAt(i);
 1344:         if(n.type.equals("element"))
 1345:         {
 1346:            System.out.println("tag "+n.name);
 1347:            System.out.println(n.getCharacters());
 1348:           //contents=n.contents.v i=0;
 1349:         }
 1350:         // System.out.println(n.type);
 1351:       
 1352:         
 1353:       
 1354:       }
 1355:     }
 1356:     public static void readXMLFile(String xmlFile)
 1357:     {
 1358:     try 
 1359:         {
 1360:            // read XML Metadata from a file
 1361:            FileInputStream fi= new FileInputStream(xmlFile);
 1362:            InputStreamReader isr= new InputStreamReader(fi,"UTF-8");
 1363:            BufferedReader buffr = new BufferedReader(isr);
 1364:            StringBuffer sb=new StringBuffer();
 1365:            int c=0;
 1366:            while ((c = buffr.read()) != -1) 
 1367:            {
 1368:              char ch=(char)c;
 1369:              sb.append(ch);
 1370:              // System.out.print((char)c);
 1371:            }
 1372:            parseXMLConfig(sb);
 1373:        } catch(Exception e) { e.printStackTrace();} 
 1374:     }
 1375: public static class DataBase 
 1376: {
 1377:   DBBean bean;
 1378:   Vector creates;
 1379:   Vector selects;
 1380:   Vector layouts;
 1381:   Vector tables;
 1382:   Vector ids;
 1383:   final static int CONVERT_MODE = 1;
 1384: 	final static int APPEND_MODE  = 2;
 1385: 	final static int UPDATE_MODE  = 3;
 1386:   int mode = -1;
 1387:   
 1388:   public DataBase(DBBean bean,Vector tables,Vector layouts,Vector selects,Vector creates,Vector ids,int mode)
 1389:   {
 1390:     this.bean = bean;
 1391:     this.tables = tables;
 1392:     this.layouts = layouts;
 1393:     this.selects = selects;
 1394:     this.creates = creates;
 1395:     this.ids     = ids;
 1396:     this.mode = mode;
 1397:     this.bean.setIDVector(ids);
 1398:   }
 1399:   public void exportToXML(BufferedWriter buffr) throws Exception
 1400:    {
 1401:     // ids=bean.getIDVector();
 1402:      buffr.write("    <database>\n");
 1403:      buffr.write("      <url>"+bean.url+"</url>\n");
 1404:      buffr.write("      <user>"+bean.user+"</user>\n");
 1405:      buffr.write("      <password>"+bean.passwd+"</password>\n");
 1406:      String modeString ="";
 1407:     if (mode == CONVERT_MODE)
 1408:       modeString = "convert";
 1409:     else
 1410:       if (mode == APPEND_MODE)
 1411:         modeString = "append";
 1412:       else
 1413:         if (mode == UPDATE_MODE)
 1414:           modeString = "update";
 1415:   
 1416:      buffr.write("      <mode>"+ modeString+"</mode>\n");
 1417:      int index = 0;
 1418:      while(index<tables.size())
 1419:      {
 1420:        String table=(String)tables.get(index);
 1421:        String layout=(String)layouts.get(index);
 1422:        String select=(String)selects.get(index);
 1423:        String create=(String)creates.get(index);
 1424:        String id=(String)ids.get(index);
 1425:    
 1426:        buffr.write("      <table name = \""+table+"\" layout = \""+layout+"\" id = \""+id+"\" >\n");
 1427:        buffr.write("         <select>"+ convertToEntities(select)+"</select>\n");
 1428:        if(!create.equals(""))
 1429:        buffr.write("         <create>"+create+"         </create>\n"); 
 1430:        buffr.write("      </table>\n");
 1431:        index++;
 1432:      }
 1433:      buffr.write("    </database>\n"); 
 1434:    }
 1435: public String toString() {return bean.url+" "+tables;}
 1436: 
 1437: }
 1438: public static String convertToUTF8(Object command)
 1439: {
 1440:   String str = null;
 1441:   try
 1442:   {
 1443:     str = new String(command.toString().getBytes("UTF-8"));
 1444:   } catch (UnsupportedEncodingException e)
 1445:   {
 1446:     // TODO Auto-generated catch block
 1447:     e.printStackTrace();
 1448:   }
 1449:   return str;
 1450: }
 1451:   public static void writeConfig(String file, DataBase source, DataBase destination) throws Exception
 1452:   {
 1453:     if(!file.toLowerCase().endsWith(".xml")) file+=".xml"; 
 1454:     File f = new File(file);
 1455:   
 1456:     FileOutputStream fout= new FileOutputStream(f);
 1457:     OutputStreamWriter outsw = new OutputStreamWriter(fout,"UTF-8");
 1458:     BufferedWriter buffw = new BufferedWriter(outsw);
 1459:     buffw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
 1460:     buffw.newLine();
 1461:     buffw.write("<convert>\n");
 1462:     buffw.write("  <source>\n");
 1463:     source.exportToXML(buffw);
 1464:     buffw.write("  </source>\n");
 1465:     buffw.write("\n  <destination>\n");
 1466:     destination.exportToXML(buffw);
 1467:     buffw.write("  </destination>\n");
 1468:     buffw.write("</convert>\n");
 1469:     buffw.close();
 1470:   } 
 1471: }  

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