Project

General

Profile

« Previous | Next » 

Revision 106

Added by Matt Jones over 24 years ago

removed files that are no longer needed

View differences:

DBWriter.java
1
/**
2
 *        Name: DBWriter.java
3
 *     Purpose: A Class that reads in an XML text document and
4
 *              write its contents to a database connection
5
 *   Copyright: 2000 Regents of the University of California and the
6
 *              National Center for Ecological Analysis and Synthesis
7
 *     Authors: Matt Jones
8
 *     
9
 *     Version: '$Id$'
10
 */
11

  
12
import java.io.File;
13
import java.io.FileInputStream;
14
import java.io.IOException;
15
import java.io.InputStream;
16
import java.net.URL;
17
import java.util.Properties;
18
import java.sql.*;
19

  
20
import org.xml.sax.ErrorHandler;
21
import org.xml.sax.InputSource;
22
import org.xml.sax.SAXException;
23
import org.xml.sax.SAXParseException;
24

  
25
import org.w3c.dom.Element;
26
import org.w3c.dom.Node;
27
import org.w3c.dom.NodeList;
28

  
29
import com.sun.xml.tree.XmlDocument;
30
import com.sun.xml.tree.XmlDocumentBuilder;
31
import com.sun.xml.tree.SimpleElementFactory;
32
import com.sun.xml.parser.Resolver;
33
import com.sun.xml.parser.ValidatingParser;
34

  
35

  
36
public class DBWriter
37
{
38
    private XmlDocument			doc;
39
    private Connection			conn = null;
40

  
41
    // Constructer to init the class
42
    public DBWriter(String argv[]) 
43
	throws SAXException, SQLException, IOException, ClassNotFoundException {
44

  
45
        // Open a connection to the database
46
        conn = openDBConnection(
47
		"oracle.jdbc.driver.OracleDriver",
48
		"jdbc:oracle:thin:@localhost:test",
49
		argv[2], argv[3]);
50

  
51
	//
52
	// Load the document, using the appropriate custom
53
	// DOM elements.
54
	//
55
	XmlDocument	doc = createDocument (
56
		Resolver.createInputSource (new File (argv [1])),
57
		new FileInputStream (argv [0]),
58
		new ErrorPrinter ()
59
	);
60

  
61
	DBElement		root;
62

  
63
    	root = (DBElement)doc.getDocumentElement();
64
	root.normalize();
65
        root.writeXmlToDB(conn, 0);
66
    }
67

  
68
    public static void main (String argv [])
69
    {
70
	try {
71
	    if (argv.length != 4) {
72
		System.err.println ("usage: java DBWriter "
73
		    + "DBElement.props somefile.xml username password");
74
		System.exit (1);
75
	    }
76

  
77
            new DBWriter(argv);
78

  
79
	} catch (Throwable t) {
80
            t.printStackTrace (System.out);
81
	}
82
    }
83

  
84
    static private XmlDocument createDocument (
85
	InputSource	input,
86
	InputStream	propsStream,
87
	ErrorHandler	errorHandler
88
    ) throws SAXException, IOException
89
    {
90
	try {
91
	    XmlDocumentBuilder		builder = new XmlDocumentBuilder ();
92
	    ValidatingParser		parser = new ValidatingParser ();
93

  
94
	    //
95
	    // Configure the builder to create the right elements.
96
	    //
97
	    {
98
		Properties		props;
99
		SimpleElementFactory	factory;
100

  
101
		props = new Properties ();
102
		props.load (propsStream);
103
		factory = new SimpleElementFactory ();
104
		factory.addMapping (props, DBWriter.class.getClassLoader ());
105
		builder.setElementFactory (factory);
106
	    }
107

  
108
	    //
109
	    // Configure the parser
110
	    //
111
	    parser.setErrorHandler (errorHandler);
112
	    parser.setEntityResolver (new Resolver ());
113
	    parser.setDocumentHandler (builder);
114
	    parser.parse (input);
115

  
116
	    // Look at how the different versions print themselvs...
117
	    if (false) {
118
		builder.getDocument ().write (System.out);
119
		System.exit (0);
120
	    }
121

  
122
	    return builder.getDocument ();
123
	    
124
	} catch (SAXParseException e) {
125
	    // already reported
126
	    throw e;
127

  
128
	} catch (SAXException e) {
129
	    e.printStackTrace (System.out);
130
	    throw e;
131

  
132
	} catch (IOException e) {
133
	    e.printStackTrace (System.out);
134
	    throw e;
135
	}
136
    }
137
    
138
    private Connection openDBConnection(String dbDriver, String connection, 
139
		String user, String password) 
140
		throws SQLException, ClassNotFoundException {
141
      // Load the Oracle JDBC driver
142
      Class.forName (dbDriver);
143

  
144
      // Connect to the database
145
      // You can put a database name after the @ sign in the connection URL.
146
      Connection conn = DriverManager.getConnection(
147
	connection, user, password);
148
      return conn;
149
    }
150

  
151
    static class ErrorPrinter implements ErrorHandler
152
    {
153
	private void message (String level, SAXParseException e)
154
	{
155
	    System.out.print ("** ");
156
	    System.out.println (level);
157
	    System.out.print ("   URI = ");
158
	    System.out.print (e.getSystemId ());
159
	    System.out.print (" Line = ");
160
	    System.out.println (e.getLineNumber ());
161
	    System.out.print ("   Message = ");
162
	    System.out.println (e.getMessage ());
163

  
164
	    /*
165
	    if (e.getException () != null)
166
		e.getException ().printStackTrace (System.out);
167
	    else
168
		e.printStackTrace (System.out);
169
	    */
170
	}
171

  
172
	public void error (SAXParseException e)
173
	{
174
	    // normally a validity error
175
	    message ("Error (recoverable)", e);
176
	}
177

  
178
	public void warning (SAXParseException e)
179
	{
180
	    message ("Warning", e);
181
	}
182

  
183
	public void fatalError (SAXParseException e)
184
	{
185
	    message ("FATAL ERROR", e);
186
	}
187
    }
188

  
189
}
190

  
191 0

  
DBElement.props
1
#
2
#        Name: DBElement.props
3
#     Purpose: A set of properties that map element types to
4
#              the classes that are used to represent that type
5
#   Copyright: 2000 Regents of the University of California and the
6
#              National Center for Ecological Analysis and Synthesis
7
#     Authors: Matt Jones
8
#     
9
#     Version: '$Id$'
10
#
11

  
12
#
13
# NOTE:  Special tag name "*Element" defines the default class to be used,
14
# instead of com.sun.xml.tree.ElementNode, when no explicit entry exists.
15
# The name "*Document" is used similarly for the document itself.
16
#
17

  
18
*Element	= DBElement
19
# *Document	= DBDocument
20

  
21
# Note -- we only use the default tags in this application
22 0

  
DBElement.java
1
/**
2
 *        Name: DBElement.java
3
 *     Purpose: A Class that represents an XML element and can
4
 *		write its contents to a database connection
5
 *   Copyright: 2000 Regents of the University of California and the
6
 *              National Center for Ecological Analysis and Synthesis
7
 *     Authors: Matt Jones
8
 *
9
 *     Version: '$Id$'
10
 */
11

  
12
import com.sun.xml.tree.ElementNode;
13

  
14
import org.w3c.dom.DOMException;
15
import org.w3c.dom.Element;
16
import org.w3c.dom.Attr;
17
import org.w3c.dom.Node;
18
import org.w3c.dom.NodeList;
19
import org.w3c.dom.NamedNodeMap;
20
import org.w3c.dom.ProcessingInstruction;
21
import org.w3c.dom.Text;
22

  
23
import java.sql.*;
24
import java.io.IOException;
25

  
26

  
27
public class DBElement extends ElementNode {
28

  
29
    public DBElement () {
30
      super();
31
    };
32
    
33
    /**
34
     * Writes this element and all of its children out to the 
35
     * given database connection 
36
     */
37
    public void writeXmlToDB(Connection conn, int parentID) 
38
		throws IOException {
39

  
40
        int maxid=0;
41
        int newid=0;
42
        Statement stmt;
43
        try {
44
          stmt = conn.createStatement();
45
          stmt.execute("SELECT MAX(nodeid) FROM xml_elements");
46
          try {
47
            ResultSet rs = stmt.getResultSet();
48
            try {
49
              boolean tableHasRows = rs.next();
50
              if (tableHasRows) {
51
                try {
52
                  maxid = rs.getInt(1);
53
                } catch (SQLException e) {
54
                  System.out.println("Error with getInt: " + e.getMessage());
55
                }
56
              }
57
            } catch (SQLException e) {
58
              System.out.println("Error with next: " + e.getMessage());
59
            }
60
          } catch (SQLException e) {
61
            System.out.println("Error with getrset: " + e.getMessage());
62
          }
63
          stmt.close();
64
        } catch (SQLException e) {
65
          System.out.println("Error getting id: " + e.getMessage());
66
        }
67
        
68
        // assign a new ID number
69
        newid = maxid + 1;
70

  
71
        try {
72
          PreparedStatement pstmt;
73
          if (parentID != 0) {
74
            pstmt = conn.prepareStatement(
75
                "INSERT INTO xml_elements(nodeid, nodename, parentnodeid) " + 
76
		"VALUES (?, ?, ?)");
77
          } else {
78
            pstmt = conn.prepareStatement(
79
                "INSERT INTO xml_elements(nodeid, nodename) " + 
80
		"VALUES (?, ?)");
81
          }
82

  
83
          // Bind the values to the query
84
          pstmt.setInt(1, newid); // The first ? is for NODEID
85
          pstmt.setString(2, getTagName());// The second ? is for NODENAME
86
          if (parentID != 0) {
87
            pstmt.setInt(3, parentID);
88
          }
89
          // Do the insertion
90
          pstmt.execute();
91
          pstmt.close();
92

  
93
        } catch (SQLException e) {
94
          System.out.println(e.getMessage());
95
        }
96

  
97
        System.out.println("ID: " + newid + "\tTag: " + getTagName());
98

  
99
        // Now save this node's attributes
100
	writeAttributesToDB(conn, newid);
101

  
102
        // Now save this node's children
103
	if (hasChildNodes()) {
104
            try {
105
	      writeChildrenXmlToDB(conn, newid);
106
            } catch (SQLException e) {
107
              System.out.println(e.getMessage());
108
            }
109
        }
110

  
111
    }
112

  
113
    public void writeChildrenXmlToDB(Connection conn, int parentID) 
114
		throws IOException, SQLException {
115

  
116
      NodeList children = getChildNodes();
117
      if (children != null) {
118
        for (int i = 0; i < children.getLength(); i++) {
119
          if (children.item(i) instanceof ElementNode) {
120
            ((DBElement)children.item(i)).writeXmlToDB(conn, parentID);
121
          } else if (children.item(i) instanceof Text) {
122
             // Write the text to the now created parent node
123
             PreparedStatement pstmt = conn.prepareStatement(
124
                "UPDATE xml_elements SET nodedata = ? " + 
125
		"WHERE nodeid = ?");
126
             pstmt.setString(1, ((Text)children.item(i)).getNodeValue()); 
127
             pstmt.setInt(2, parentID); 
128
             pstmt.execute();
129
             pstmt.close();
130
          } else {
131
            System.out.println("    Other Node Type skipped.");
132
          }
133
        }
134
      }
135
    }
136

  
137
    /**
138
     * Writes this element's attributes out to the 
139
     * given database connection 
140
     */
141
    public void writeAttributesToDB(Connection conn, int nodeid) 
142
		throws IOException {
143
        NamedNodeMap attributes = getAttributes();
144

  
145
        if (attributes != null) {
146
            for (int i=0; i < attributes.getLength(); i++) {
147
               String name = ((Attr)attributes.item(i)).getName();
148
               String value = ((Attr)attributes.item(i)).getValue();
149
               System.out.println("    Saving attribute: " + name + "=" + value);
150

  
151
               int maxid=0;
152
               int newid=0;
153
               Statement stmt;
154
               try {
155
                 stmt = conn.createStatement();
156
                 stmt.execute("SELECT MAX(attributeid) FROM xml_attributes");
157
                 try {
158
                   ResultSet rs = stmt.getResultSet();
159
                   try {
160
                     boolean tableHasRows = rs.next();
161
                     if (tableHasRows) {
162
                       try {
163
                         maxid = rs.getInt(1);
164
                       } catch (SQLException e) {
165
                         System.out.println("Error with getInt: " + e.getMessage());
166
                       }
167
              }
168
                   } catch (SQLException e) {
169
                     System.out.println("Error with next: " + e.getMessage());
170
                   }
171
                 } catch (SQLException e) {
172
                   System.out.println("Error with getrset: " + e.getMessage());
173
                 }
174
                 stmt.close();
175
               } catch (SQLException e) {
176
                 System.out.println("Error getting id: " + e.getMessage());
177
               }
178
        
179
               // assign a new ID number
180
               newid = maxid + 1;
181
       
182
               try {
183
                 PreparedStatement pstmt;
184
                 pstmt = conn.prepareStatement(
185
                  "INSERT INTO xml_attributes(attributeid, nodeid, " +
186
                  "attributenumber, attributename, attributevalue) " +
187
		   "VALUES (?, ?, ?, ?, ?)");
188
       
189
                 // Bind the values to the query
190
                 pstmt.setInt(1, newid); 		// ATTRIBUTEID
191
                 pstmt.setInt(2, nodeid);		// NODEID
192
                 pstmt.setInt(3, i+1); 			// ATTRIBUTENUMBER
193
                 pstmt.setString(4, name);		// ATTRIBUTENAME
194
                 pstmt.setString(5, value);		// ATTRIBUTEVALUE
195

  
196
                 // Do the insertion
197
                 pstmt.execute();
198
                 pstmt.close();
199
       
200
               } catch (SQLException e) {
201
                 System.out.println(e.getMessage());
202
               }
203
            }
204
        }
205
    }
206

  
207
    // used by JTree to display this node
208
    public String toString ()
209
    {
210
	StringBuffer	value = new StringBuffer ();
211
	value.append ('<');
212
	value.append (getTagName ());
213
	value.append (getAttributes ().toString ());
214
	value.append ('>');
215
	return value.toString ();
216
    }
217
}
218 0

  

Also available in: Unified diff