⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 echoxmlfiletodbtables.java

📁 java web 开发,Java Xml 编程指南书籍源码
💻 JAVA
字号:
package MyNa.xml;
import MyNa.utils.Env;
import MyNa.utils.Logger;

import java.io.*;
import java.util.Stack;
import java.util.Hashtable;
import java.util.Enumeration;

import org.xml.sax.*;
import org.xml.sax.helpers.ParserFactory;
import com.sun.xml.parser.Resolver;


import java.sql.*;   // communicate with database


public class EchoXmlFileToDBTables extends HandlerBase {
   // by construction, this will echo a File to a database,
   // assuming the myna:simpledb.dtd in which the xml itself
   // specifies the target database and provides user/pwd
   private PrintWriter out; 
   Stack theCallStack=null; 
   Stack theValStack=null;

   Env theEnv=null;
   HandlerSet theHandlerSet; // keeps track of end-handlers for tagnames.

   Connection theDBConnection=null; 
   Statement theCreateTableStatement;
   PreparedStatement theInsertPreparedStatement;
//   String driverName=null; // ="sun.jdbc.odbc.JdbcOdbcDriver";
//   String dbUrl=null;  // ="jdbc:odbc:PHONEBOOK";
//   String theUser=null; // ="usr"; 
//   String thePwd=null; // ="pwd";
   Logger lg;


public EchoXmlFileToDBTables (String fileName){
   lg=new Logger(); lg.logIt("inside EchoXmlFileToDBTables with "+fileName);
   theCallStack=new Stack(); theValStack=new Stack();
   Hashtable H=new Hashtable();
   lg.logIt("hashtable okay");
   theEnv=new Env(); // out=new PrintWriter(outW); 
   lg.logIt("new env okay");
   theEnv.put("garbagein","garbageout");
   lg.logIt("theEnv garbagein="+theEnv.getStr("garbagein"));
   theHandlerSet=new HandlerSet();
   lg.logIt("new handlerset okay");
    try{
   File inFile=new File(fileName);
    lg.logIt("got file");
     InputSource in=Resolver.createInputSource(inFile);
     lg.logIt("got inputSource");
     Parser parser=ParserFactory.makeParser("com.sun.xml.parser.Parser");
     parser.setDocumentHandler(this);
     parser.parse(in);
   }catch (SAXParseException t){lg.logIt("saxparserr ",t);
       lg.logIt("error at "+t.getLineNumber ());
       t.printStackTrace();}
    catch (Throwable t){lg.logIt("initerr ",t); 
       t.printStackTrace();}
}




public void startDocument ()throws SAXException {
  lg.logIt("startDocument");
  }

public void endDocument () throws SAXException {
  lg.logIt("endDocument");
}

public void startElement (String tag, AttributeList attrs)
     throws SAXException {
  lg.logIt("startElement "+tag+": "+attrs.getLength()+" attrs");
  theCallStack.push(new CallStackItem(tag,attrs));
}

public void endElement (String tag) throws SAXException {
  lg.logIt("endElement "+tag);
  theHandlerSet.get(tag).doIt();
}


public void characters (char buf [], int offset, int len)
    throws SAXException {
  String s = new String(buf, offset, len);
  lg.logIt("chars: "+s);
  theValStack.push(s);
  CallStackItem cSI=(CallStackItem)(theCallStack.peek());
  cSI.kidNum+=1;
}


    // Wrap I/O exceptions in SAX exceptions, to
    // suit handler signature requirements
/*
private void emit (String s) throws SAXException {
  try {
        out.write (s); out.flush ();
      } catch (IOException e) {
          throw new SAXException ("I/O error", e);
        }
    }
private void nl () throws SAXException {
  try {out.write (lineEnd);
      } catch (IOException e) {
         throw new SAXException ("I/O error", e);
         }
  }
*/

public class CallStackItem{ // helper/holder class, conceals nothing
  public String tagName; // the <tagname> for the xml item
  public String name;    // its name="nameAttr" if present, else tagName
  public int kidNum;     // number of children on valStack
  public Hashtable attrs; // attributes, not including name

  public CallStackItem(String tag,AttributeList aL){
    kidNum=0; tagName=tag; attrs=null;
    int N=aL.getLength(); int nonName = N;
    name=aL.getValue("name");
    if(name==null)name=tag; else nonName--; 
    if(nonName==0)return;
    attrs=new Hashtable(nonName);
    for(int i=0;i<N;i++){
      String key=aL.getName(i); if("name".equals(key))continue;
      String val=aL.getValue(i);
      attrs.put(key,val);
      }
  }
   
} // end CallStackItem helper class

class HandlerSet{
  Hashtable table; EndHandler defaultHandler;
  public HandlerSet(){
    lg.logIt("in handlerset");
    defaultHandler=new EndHandler();
    table=new Hashtable();
    table.put("row",new EndRowHandler());
    table.put("user-info",new EndUser_Info());
    table.put("header",new EndHeaderHandler());
    lg.logIt("got through end, row, userinfo, header");
    table.put("dbdata",new EnddbDataHandler());
    table.put("table",new EndTableHandler());
    table.put("headers",new EndHeadersHandler());
    lg.logIt("handlerset finished");
    }
  public EndHandler get(String tagName){
    EndHandler eH=(EndHandler)table.get(tagName);
    if(eH==null)return defaultHandler;
    return eH;    
  }
}
public class EndHandler {
  // an object which will handle a /tagname, popping off stacks.
  // the default is to add attrs to theEnv except for name;
  // name is associated with value, i.e. item from theValStack,
  // if exactly one. override doIt() for each special /tagname.

  public EndHandler(){}  // nothing to do in initialization
  public void popAll(CallStackItem cSI){
    lg.logIt("popping "+cSI.kidNum+" from valstack");
    for(int N=cSI.kidNum;N>0;N--)theValStack.pop();
  }
  public void pushVal(Object v){
   theValStack.push(v); 
    ((CallStackItem)theCallStack.peek()).kidNum++;
   }
  public void assocVal(CallStackItem cSI){
    theEnv.put(cSI.name,(String)theValStack.peek());
    lg.logIt("theEnv."+cSI.name+"=="+((String)theValStack.peek()));
  }

  public void addAttrsToEnv(CallStackItem cSI){
    Hashtable H=cSI.attrs;
    lg.logIt("addAttrsToEnv: "+((H==null)?"null":(""+(H.size()))));
    if(H!=null) theEnv.addHashtable(H);
    lg.logIt("added hashtable");
    lg.logIt("Env=["+theEnv.toString()+"]");
  }

  public void doIt() throws SAXException { // default;
       // does not leave any result on the valStack.
    CallStackItem cSI=(CallStackItem)theCallStack.pop();
    lg.logIt("EndHandler doIt on "+cSI.name+"; kidnum="+cSI.kidNum);
    if(cSI.kidNum==1)assocVal(cSI);
    addAttrsToEnv(cSI);
    popAll(cSI);
    lg.logIt("ended endHandler on "+cSI.name);
  }

}
 class EndUser_Info extends EndHandler{
/*
the /user_info function,will open theDBConnection to
E.db_url with E.driver for E.uname with E.upass;
it will create theCreateTableStatement; these will be class vars rather than
in the environment. theCreateTableStatement will be used to create tables.
*/
  public EndUser_Info(){}
  public void doIt() throws SAXException {
    CallStackItem cSI=(CallStackItem)theCallStack.pop();
     lg.logIt("EndUserInfo doIt on "+cSI.name+"; kidnum="+cSI.kidNum);
    String driver=theEnv.getStr("driver");
    String db_url=theEnv.getStr("db_url");
    String uname=theEnv.getStr("uname");
    String upass=theEnv.getStr("upass");
  lg.logIt("driver="+driver+";db_url="+db_url+";uname="+uname+";upass="+upass);
   try{
      Class.forName(theEnv.getStr("driver"));
      theDBConnection= DriverManager.getConnection(
         theEnv.getStr("db_url"),theEnv.getStr("uname"),theEnv.getStr("upass"));
      theCreateTableStatement=theDBConnection.createStatement();
    }catch(ClassNotFoundException e)
      {throw new SAXException ("driver not found error", e);}
    catch(SQLException e)
      {throw new SAXException ("SQL error", e);}
  }
}
 class EndHeaderHandler extends EndHandler{
  public EndHeaderHandler(){} // leaves 
  public void doIt() throws SAXException {
    CallStackItem cSI=(CallStackItem)theCallStack.pop();
    lg.logIt("EndHeaderHandler doIt on "+cSI.name+"; kidnum="+cSI.kidNum);
    cSI.attrs.put("name",cSI.name);  // attrs never null for header
    pushVal(cSI.attrs);
  }
}
 class EndTableHandler extends EndHandler{
  public EndTableHandler(){}
  public void doIt() throws SAXException {
    try{
    CallStackItem cSI=(CallStackItem)theCallStack.pop();
    lg.logIt("EndTableHandler doIt on "+cSI.name+"; kidnum="+cSI.kidNum);
    theInsertPreparedStatement.close();
    }catch(SQLException e)
      {throw new SAXException ("SQL error", e);}
  }
}
 class EnddbDataHandler extends EndHandler{
  public EnddbDataHandler(){}
  public void doIt() throws SAXException {
    try{
    CallStackItem cSI=(CallStackItem)theCallStack.pop();
    lg.logIt("EnddbDataHandler doIt on "+cSI.name+"; kidnum="+cSI.kidNum);
    theCreateTableStatement.close();
    theDBConnection.close();
    }catch(SQLException e)
      {throw new SAXException ("SQL error", e);}
  }
}
 class EndRowHandler extends EndHandler{
  public EndRowHandler(){}
  public void doIt() throws SAXException {
    CallStackItem cSI=(CallStackItem)theCallStack.pop();
    lg.logIt("EndRowHandler doIt on "+cSI.name+"; kidnum="+cSI.kidNum);
    try{
    String [] names=(String[])theEnv.get("header_names");
    String [] types=(String[])theEnv.get("header_types");
    for(int i=1;i<=names.length;i++)
      theInsertPreparedStatement.setString(i,
                       (String)theEnv.get(names[i-1]));
    lg.logIt("strings all set");
    theInsertPreparedStatement.executeUpdate();
    theInsertPreparedStatement.clearParameters();
    }catch(SQLException e)
      {throw new SAXException ("SQL error", e);}
  }
}
 class EndHeadersHandler extends EndHandler{
/*
the /headers function picks up the attrlists; creates the table
if needed with theCreateTableStatement; it also opens 
theInsertPreparedStatement to insert new rows into the current
statement. This will be closed by /table.
 Notice that if there are five headers, then the valstack
consists of five attrlists  /headers uses them and pops them off,
but E.header_names becomes the list of names as an array of strings,
and E.header_types becomes the list of types as an array of strings,
while E.tableName becomes the table name itself.
Meanwhile, <table name="thetablename"> is on the stack, right under
the <headers> which we pop off on the first line.

*/ 

public void createTable(String name,String[]fldnames,String[]fldtypes){
//String createQ="CREATE TABLE COURSEBOOKS (SectionID TEXT, ItemCode TEXT);
  try{
    lg.logIt("createTable "+name+" with "+fldnames.length+" fields");
    int N=fldnames.length;
    String createQ="CREATE TABLE "+name+" (";
    if(N>0)createQ+=fldnames[0]+" "+fldtypes[0];
    for(int i=1;i<N;i++)createQ+=", "+fldnames[i]+" "+fldtypes[i];
    createQ+=");";
    lg.logIt("createQ="+createQ);
    theCreateTableStatement.execute(createQ);
   }catch(SQLException e){lg.logIt("createTable exception: "+e);}
    // this table may well already exist; don't throw the error
}
public void createInserter(String name,String[]fldnames,String[]fldtypes)
    throws SAXException {
//String insertQ="INSERT INTO COURSEBOOKS VALUES (?,?);"
  try{
    lg.logIt("createInserter "+name+" with "+fldnames.length+" fields");
    int N=fldnames.length;
    String insertQ="INSERT INTO "+name+" VALUES (";
    if(N>0)insertQ+="?";
    for(int i=1;i<N;i++)insertQ+=", ?";
    insertQ+=");";
    lg.logIt("insertQ="+insertQ);
    theInsertPreparedStatement=theDBConnection.prepareStatement(insertQ);
   }catch(SQLException e){lg.logIt("createInserter exception: "+e);
     throw new SAXException("createInserter error",e);}
    // this table may well already exist.
}

  public EndHeadersHandler(){}
  public void doIt() throws SAXException {
    CallStackItem cSI=(CallStackItem)theCallStack.pop();
    lg.logIt("EndHeadersHandler doIt on "+cSI.name+"; kidnum="+cSI.kidNum);
    int N=cSI.kidNum;
    lg.logIt(""+N+" fields");
    String[]header_names=new String[N];
    String[]header_types=new String[N];
    for(int i=N-1;i>=0;i--){
      Hashtable aL=(Hashtable)theValStack.pop();
      lg.logIt("field table "+i+" is "+
                (aL==null?"null":"nonnull") );
      header_names[i]=(String)aL.get("name");
      header_types[i]=(String)aL.get("fieldType");
      lg.logIt("name="+header_names[i]+"; type="+header_types[i]);
      }
    String tableName=((CallStackItem)(theCallStack.peek())).name;
    createTable(tableName,header_names,header_types);
    createInserter(tableName,header_names,header_types);
    theEnv.put("header_names",header_names);
    theEnv.put("header_types",header_types);
    theEnv.put("tableName",tableName);
   }
}

} // end EchoXmlFileToWriter class

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -