Project

General

Profile

« Previous | Next » 

Revision 111

Added by Matt Jones over 24 years ago

moved java files to src directory

View differences:

XMLValidate.java
1
package edu.ucsb.nceas.metacat;
2

  
3
import org.w3c.dom.*;
4
import org.xml.sax.*;
5
import org.xml.sax.Parser;
6
import oracle.xml.parser.v2.*;    //Oracle parser
7
//import org.apache.xerces.parsers.*;  //Apache/IBM/Xerces parser
8

  
9
/**
10
 * XMLValidate.java
11
 *         Purpose: A Class that validates XML documents
12
 *   			   This class is uses a specific parser
13
 * 				and calls the GenericXMLValidate class
14
 *                 to do the actual validation
15
 *       Copyright: 2000 Regents of the University of California and the
16
 *                  National Center for Ecological Analysis and Synthesis
17
 *                  April 28, 2000
18
 * 
19
 * @author Dan Higgins
20
 * @version Version 1.0
21
 */
22
public class XMLValidate
23
{
24
    String doc;
25
    SAXParser par;
26
    public boolean validating = false; 
27
    
28
    public XMLValidate( String docname){
29
        doc = docname;
30
        
31
            par = new SAXParser();           // works for both Xerces and Oracle
32
/*            try {   //Xerces
33
            par.setFeature("http://xml.org/sax/features/validation",true);  
34
            }
35
            catch (Exception e) 
36
                {System.out.println("Could not set Validation!!!");
37
                System.exit(0);}
38
                // Xerces end 
39
*/                
40
                
41
                par = new SAXParser();           // works for both Xerces and Oracle
42
                par.setValidationMode(true);     // Oracle
43
            
44
        
45
            
46
            
47
        GenericXMLValidate gxv = new GenericXMLValidate(par);
48
        if (gxv.validate(doc)) {
49
            System.out.println("XML is validated");
50
        }
51
        else {
52
            System.out.print(gxv.returnErrors());    
53
        }
54
    }
55

  
56
    
57
    public static void main(String[] args) {
58
        
59
        if (args.length!=1) {
60
            System.out.println("Usage: java XMLValidate <xmlfile or URL>");
61
            System.exit(0);
62
        }
63
        String doc = args[0];
64
        
65
        
66
        new XMLValidate(doc);
67
    }
68
   
69
    
70
    
71
}
72 0

  
DBSAXWriter.java
1
/**
2
 *        Name: DBSAXWriter.java
3
 *     Purpose: A Class that reads in an XML text document and
4
 *              write its contents to a database connection using SAX
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
package edu.ucsb.nceas.metacat;
13

  
14
import org.xml.sax.*;
15

  
16
import java.io.*;
17
import java.net.URL;
18
import java.net.MalformedURLException;
19
import java.sql.*;
20
import java.util.Stack;
21

  
22
// Extensions to the SAX Interfaces for Namespace support.
23
import oracle.xml.parser.v2.XMLDocumentHandler;
24
import oracle.xml.parser.v2.DefaultXMLDocumentHandler;
25
import oracle.xml.parser.v2.NSName;
26
import oracle.xml.parser.v2.SAXAttrList;
27

  
28
import oracle.xml.parser.v2.SAXParser;
29

  
30
/**
31
 * A Class that reads in an XML text document and
32
 * write its contents to a database connection using SAX
33
 */
34
public class DBSAXWriter {
35

  
36
  static  String 	defaultDB = "jdbc:oracle:thin:@penelope.nceas.ucsb.edu:1526:DEV8";
37
  private Connection	conn = null;
38

  
39
  /**
40
   * the main routine used to test the DBSAXWriter utility.
41
   *
42
   * Usage: java DBSAXWriter <filename> <user> <password> [dbstring]
43
   *
44
   * @param filename the filename to be loaded into the database
45
   * @param user the username to use for the database connection
46
   * @param password the password to use for the database connection
47
   * @param dbstring the connection info to use for the database connection
48
   */
49
  static public void main(String[] args) {
50
     
51
     if (args.length < 3)
52
     {
53
        System.err.println("Wrong number of arguments!!!");
54
        System.err.println("USAGE: java DBSAXWriter " +
55
                           "<filename> <user> <password> [dbstring]");
56
        return;
57
     } else {
58
        try {
59
                    
60
          String filename = args[0];
61
          String user     = args[1];
62
          String password = args[2];
63
          String dbstring = null;
64

  
65
          if (args.length <= 3) {
66
            dbstring = defaultDB;
67
          } else {
68
            dbstring = args[3];
69
          }
70

  
71
          // Open a connection to the database
72
          Connection dbconn = MetaCatUtil.openDBConnection(
73
                "oracle.jdbc.driver.OracleDriver",
74
                dbstring, user, password);
75

  
76
          new DBSAXWriter(filename, dbconn);
77
          System.out.println("Document processing finished for: " + filename);
78

  
79
        } catch (Exception e) {
80
          System.err.println("EXCEPTION HANDLING REQUIRED");
81
          System.err.println(e.getMessage());
82
          e.printStackTrace(System.err);
83
        }
84
     }
85
  }
86
  
87
  /**
88
   * construct a new instance of the class to write an XML file to the database
89
   *
90
   * @param filename the filename to be loaded into the database
91
   * @param conn the database connection to which to write the XML file
92
   */
93
  public DBSAXWriter( Reader xml, Connection conn)
94
                  throws IOException, 
95
                         SQLException, 
96
                         ClassNotFoundException
97
  {
98
    this.conn = conn;
99

  
100
    try {
101
        SAXParser parser = initializeParser(conn);
102
        parser.parse(xml);
103
      } catch (SAXParseException e) {
104
        System.err.println(e.getMessage());
105
      } catch (SAXException e) {
106
        System.err.println(e.getMessage());
107
      } catch (Exception e) {
108
        System.err.println(e.toString());
109
      }
110
  }
111

  
112
  public DBSAXWriter( String filename, Connection conn)
113
                  throws IOException, 
114
                         SQLException, 
115
                         ClassNotFoundException
116
  {
117
     this.conn = conn;
118
     FileReader xmlfile = new FileReader(new File(filename).toString());
119
     try {
120
       SAXParser parser = initializeParser(conn);
121
       parser.parse(xmlfile);
122
     } catch (SAXParseException e) {
123
       System.err.println(e.getMessage());
124
     } catch (SAXException e) {
125
       System.err.println(e.getMessage());
126
     } catch (Exception e) {
127
       System.err.println(e.toString());
128
     }
129
  }
130
  
131
  private SAXParser initializeParser(Connection conn) {
132
    SAXParser parser = null;
133
    //
134
    // Set up the SAX document handlers for parsing
135
    //
136
    try {
137
      // Use the XMLDocumentHandler interface for namespace support
138
      // instead of org.xml.sax.DocumentHandler
139
      XMLDocumentHandler xmlDocHandler = new DBSAXHandler(conn);
140
      EntityResolver xmlEntityResolver = new DBEntityResolver(conn);
141
      DTDHandler xmlDTDHandler         = new DBDTDHandler(conn);
142

  
143
      // For all the other interface use the default provided by
144
      // Handler base
145
      HandlerBase defHandler = new HandlerBase();
146

  
147
      // Get an instance of the parser
148
      parser = new SAXParser();
149

  
150
      // Set Handlers in the parser
151
      // Set the DocumentHandler to XMLDocumentHandler
152
      parser.setDocumentHandler(xmlDocHandler);
153
      parser.setEntityResolver(xmlEntityResolver);
154
      parser.setDTDHandler(xmlDTDHandler);
155

  
156
      // Set the other Handler to the defHandler
157
      parser.setErrorHandler(defHandler);
158

  
159
    } catch (Exception e) {
160
       System.err.println(e.toString());
161
    }
162

  
163
    return parser;
164
  }
165

  
166
  /** Utility method to convert a file handle into a URL */
167
  static public URL fileToURL(File file) 
168
  {
169
     String path = file.getAbsolutePath();
170
     String fSep = System.getProperty("file.separator");
171
     if (fSep != null && fSep.length() == 1)
172
       path = path.replace(fSep.charAt(0), '/');
173
     if (path.length() > 0 && path.charAt(0) != '/')
174
       path = '/' + path;
175
     try {
176
       return new URL("file", null, path);
177
     }
178
     catch (java.net.MalformedURLException e) {
179
       /* According to the spec this could only happen if the file
180
	  protocol were not recognized. */
181
       throw new Error("unexpected MalformedURLException");
182
     }
183
  }
184
}
185 0

  
DBTransform.java
1
/**
2
 *        Name: DBTransform.java
3
 *     Purpose: A Class that transforms an XML text document
4
 *              into a another type using XSL
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
package edu.ucsb.nceas.metacat;
13

  
14
import java.io.*;
15
import java.net.URL;
16
import java.net.MalformedURLException;
17
import java.sql.*;
18
import java.util.Stack;
19

  
20
import oracle.xml.parser.v2.XSLStylesheet;
21
import oracle.xml.parser.v2.XSLException;
22
import oracle.xml.parser.v2.XSLProcessor;
23
import oracle.xml.parser.v2.XMLDocument;
24
import oracle.xml.parser.v2.DOMParser;
25

  
26
/** 
27
 * A Class that transforms XML documents utitlizing XSL style sheets
28
 */
29
public class DBTransform {
30

  
31
  static  String 	defaultDB = "jdbc:oracle:thin:@localhost:1521:test";
32
  private Connection	conn = null;
33

  
34
  /**
35
   * construct a DBTransform instance.
36
   *
37
   * Generally, one calls transformXMLDocument() after constructing the instance
38
   *
39
   * @param conn the database connection from which to lookup the public ids
40
   */
41
  public DBTransform( Connection conn ) 
42
                  throws IOException, 
43
                         SQLException, 
44
                         ClassNotFoundException
45
  {
46
    this.conn = conn;
47
  }
48
  
49
  /**
50
   * Transform an XML document using the stylesheet reference from the db
51
   *
52
   * @param doc the document to be transformed
53
   * @param sourcetype the document type of the source
54
   * @param targettype the target document type
55
   */
56
  public void transformXMLDocument(String doc, String sourcetype, 
57
                String targettype, PrintWriter pw) {
58
    
59
    // Look up the stylesheet for this type combination
60
    String xsl_system_id = getSystemId("XSL", sourcetype, targettype);
61

  
62
    if (xsl_system_id != null) {
63
      // Create a stylesheet from the system id that was found
64
      try {
65
        XSLStylesheet style = new XSLStylesheet(new URL(xsl_system_id), null);
66
        DOMParser dp = new DOMParser();
67
        dp.setValidationMode(false);
68
        dp.parse((Reader)(new StringReader(doc)));
69
        new XSLProcessor().processXSL(style, dp.getDocument(), pw);
70
      } catch (Exception e) {
71
        pw.println(xsl_system_id + "Error transforming document:\n" + 
72
                   e.getMessage());
73
      }
74
    } else {
75
      // No stylesheet registered form this document type, so just return the 
76
      // XML stream we were passed
77
      pw.print(doc);
78
    }
79
  }
80

  
81
  /**
82
   * Lookup a stylesheet reference from the db catalog
83
   *
84
   * @param objecttype the type of the object we want to retrieve
85
   * @param sourcetype the document type of the source
86
   * @param targettype the document type of the target
87
   */
88
  public String getSystemId(String objecttype, String sourcetype, 
89
                String targettype) {
90

  
91
    // Look up the System ID of a particular object
92
    PreparedStatement pstmt;
93
    String the_system_id = null;
94
    try {
95
      pstmt =
96
        conn.prepareStatement("SELECT system_id " +
97
                "FROM xml_catalog " +
98
                "WHERE entity_type LIKE ? " +
99
                "AND source_doctype LIKE ? " +
100
                "AND target_doctype LIKE ? ");
101
      // Bind the values to the query
102
      pstmt.setString(1, objecttype);
103
      pstmt.setString(2, sourcetype);
104
      pstmt.setString(3, targettype);
105
      pstmt.execute();
106
      try {
107
        ResultSet rs = pstmt.getResultSet();
108
        try {
109
          boolean tableHasRows = rs.next();
110
          if (tableHasRows) {
111
            try {
112
              the_system_id = rs.getString(1);
113
            } catch (SQLException e) {
114
              System.out.println("Error with getString: " + e.getMessage());                }
115
          } else {
116
            the_system_id = null; 
117
          }
118
        } catch (SQLException e) {
119
          System.err.println("Error with next: " + e.getMessage());
120
          return ("Error with next: " + e.getMessage());
121
        }
122
      } catch (SQLException e) {
123
        System.err.println("Error with getrset: " + e.getMessage());
124
        return ("Error with getrset: " + e.getMessage());
125
      }
126
      pstmt.close();
127
    } catch (SQLException e) {
128
      System.err.println("Error getting id: " + e.getMessage());
129
      return ("Error getting id: " + e.getMessage());
130
    }
131
    return the_system_id;
132
  }
133

  
134
  /**
135
   * the main routine used to test the transform utility.
136
   *
137
   * Usage: java transform <user> <password> [dbstring]
138
   *
139
   * @param user the username to use for the database connection
140
   * @param password the password to use for the database connection
141
   * @param dbstring the connection info to use for the database connection
142
   */
143
  static public void main(String[] args) {
144
     
145
     if (args.length < 2)
146
     {
147
        System.err.println("Wrong number of arguments!!!");
148
        System.err.println("USAGE: java transform " +
149
                           "<user> <password> [dbstring]");
150
        return;
151
     } else {
152
        try {
153
                    
154
          String user     = args[0];
155
          String password = args[1];
156
          String dbstring = null;
157

  
158
          if (args.length <= 2) {
159
            dbstring = defaultDB;
160
          } else {
161
            dbstring = args[2];
162
          }
163

  
164
          // Open a connection to the database
165
          Connection dbconn = MetaCatUtil.openDBConnection( 
166
                              "oracle.jdbc.driver.OracleDriver",
167
                              dbstring, user, password);
168

  
169
          // Create a test document
170
          StringBuffer testdoc = new StringBuffer();
171
          testdoc.append("<?xml version=\"1.0\"?>");
172
          testdoc.append("<eml-dataset><metafile_id>NCEAS-0001</metafile_id>");
173
          testdoc.append("<dataset_id>DS001</dataset_id>");
174
          testdoc.append("<title>My test doc</title></eml-dataset>");
175

  
176
          // Transform the document to the new doctype
177
          DBTransform dbt = new DBTransform(dbconn);
178
          dbt.transformXMLDocument(testdoc.toString(), 
179
                                   "-//NCEAS//eml-dataset//EN", 
180
                                   "-//W3C//HTML//EN", 
181
                                   new PrintWriter(System.out));
182

  
183
        } catch (Exception e) {
184
          System.err.println("EXCEPTION HANDLING REQUIRED");
185
          System.err.println(e.getMessage());
186
          e.printStackTrace(System.err);
187
        }
188
     }
189
  }
190
  
191
  public void dbg(int position) {
192
    System.err.println("Debug flag: " + position);
193
  }
194

  
195
}
196 0

  
MetaCatUtil.java
1
/**
2
 *        Name: MetaCatUtil.java
3
 *     Purpose: A Class that implements utility methods for a metadata catalog
4
 *   Copyright: 2000 Regents of the University of California and the
5
 *              National Center for Ecological Analysis and Synthesis
6
 *     Authors: Matt Jones
7
 * 
8
 *     Version: '$Id$'
9
 */
10

  
11
package edu.ucsb.nceas.metacat;
12

  
13
import java.sql.Connection;
14
import java.sql.DriverManager;
15
import java.sql.SQLException;
16

  
17
/**
18
 * A suite of utility classes for the metadata catalog server
19
 */
20
public class MetaCatUtil {
21

  
22
  static  String 	user = "jones";
23
  static  String 	password = "your-pw-goes-here";
24
  static  String 	defaultDB = "jdbc:oracle:thin:@localhost:1521:test";
25

  
26
  /** 
27
   * Utility method to establish a JDBC database connection 
28
   *
29
   * @param dbDriver the string representing the database driver
30
   * @param connection the string representing the database connectin parameters
31
   * @param user name of the user to use for database connection
32
   * @param password password for the user to use for database connection
33
   */
34
  public static Connection openDBConnection(String dbDriver, String connection,
35
                String user, String password)
36
                throws SQLException, ClassNotFoundException {
37

  
38
     // Load the Oracle JDBC driver
39
     Class.forName (dbDriver);
40

  
41
     // Connect to the database
42
     Connection conn = DriverManager.getConnection( connection, user, password);
43
     return conn;
44
  }
45
}
46 0

  
DBSimpleQuery.java
1
/**
2
 *        Name: DBSimpleQuery.java
3
 *     Purpose: A Class that searches a relational DB for elements and 
4
 *              attributes that have free text matches to the query string.  
5
 *              It returns a result set consisting of the root nodeid for 
6
 *              each document that satisfies the query
7
 *   Copyright: 2000 Regents of the University of California and the
8
 *              National Center for Ecological Analysis and Synthesis
9
 *     Authors: Matt Jones
10
 *
11
 *     Version: '$Id$'
12
 */
13

  
14
package edu.ucsb.nceas.metacat;
15

  
16
import java.io.*;
17
import java.net.URL;
18
import java.net.MalformedURLException;
19
import java.sql.*;
20
import java.util.Stack;
21
import java.util.Hashtable;
22
import java.util.Enumeration;
23

  
24
/** 
25
 * A Class that searches a relational DB for elements and attributes that
26
 * have free text matches to the query string.  It returns a result set 
27
 * consisting of the root nodeid for each document that satisfies the query
28
 */
29
public class DBSimpleQuery {
30

  
31
  static  String 	defaultDB = "jdbc:oracle:thin:@localhost:1521:test";
32
  private Connection	conn = null;
33

  
34
  /**
35
   * the main routine used to test the DBSimpleQuery utility.
36
   *
37
   * Usage: java DBSimpleQuery <query> <user> <password> [dbstring]
38
   *
39
   * @param query the text to search for in the element and attribute content
40
   * @param user the username to use for the database connection
41
   * @param password the password to use for the database connection
42
   * @param dbstring the connection info to use for the database connection
43
   */
44
  static public void main(String[] args) {
45
     
46
     if (args.length < 3)
47
     {
48
        System.err.println("Wrong number of arguments!!!");
49
        System.err.println("USAGE: java DBSimpleQuery " +
50
                           "<query> <user> <password> [dbstring]");
51
        return;
52
     } else {
53
        try {
54
                    
55
          String query    = args[0];
56
          String user     = args[1];
57
          String password = args[2];
58
          String dbstring = null;
59

  
60
          if (args.length <= 3) {
61
            dbstring = defaultDB;
62
          } else {
63
            dbstring = args[3];
64
          }
65

  
66
          // Open a connection to the database
67
          Connection dbconn = MetaCatUtil.openDBConnection( 
68
                              "oracle.jdbc.driver.OracleDriver",
69
                              dbstring, user, password);
70
          // Execute the simple query
71
          DBSimpleQuery rd = new DBSimpleQuery(dbconn);
72
          Hashtable nodelist = rd.findDocuments(query);
73

  
74
          // Print the reulting root nodes
75
          StringBuffer result = new StringBuffer();
76
          long docid = 0;
77
          result.append("<?xml version=\"1.0\"?>\n");
78
          result.append("<resultset>\n");
79
          Enumeration doclist = nodelist.keys(); 
80
          while (doclist.hasMoreElements()) {
81
            docid = ((Long)doclist.nextElement()).longValue();
82
            result.append("  <docid>").append(docid).append("</docid>\n");
83
          }
84
          result.append("</resultset>");
85

  
86
          System.out.println(result);
87

  
88
        } catch (Exception e) {
89
          System.err.println("EXCEPTION HANDLING REQUIRED");
90
          System.err.println(e.getMessage());
91
          e.printStackTrace(System.err);
92
        }
93
     }
94
  }
95
  
96
  /**
97
   * construct an instance of the DBSimpleQuery class 
98
   *
99
   * <p>Generally, one would call the findDocuments() routine after creating 
100
   * an instance to specify the search query</p>
101
   *
102
   * @param conn the JDBC connection that we use for the query
103
   */
104
  public DBSimpleQuery( Connection conn ) 
105
                  throws IOException, 
106
                         SQLException, 
107
                         ClassNotFoundException
108
  {
109
    this.conn = conn;
110
  }
111
  
112
  /** 
113
   * routine to search the elements and attributes looking to match query
114
   *
115
   * @param query the text to search for
116
   */
117
  public Hashtable findDocuments(String query) {
118
      Hashtable	nodeListResult = new Hashtable();
119
      Hashtable	rootListResult = new Hashtable();
120
      Hashtable	 docListResult = new Hashtable();
121

  
122
      PreparedStatement pstmt;
123
      long nodeid;
124

  
125
      try {
126
        pstmt =
127
          conn.prepareStatement("SELECT nodeid " +
128
                  "FROM xml_nodes WHERE nodedata LIKE ?");
129
        // Bind the values to the query
130
        pstmt.setString(1, query);
131

  
132
        pstmt.execute();
133
        try {
134
          ResultSet rs = pstmt.getResultSet();
135
          try {
136
            boolean tableHasRows = rs.next();
137
            while (tableHasRows) {
138
              try {
139
                nodeid = rs.getLong(1);
140
                nodeListResult.put(new Long(nodeid),new Long(nodeid));
141

  
142
              } catch (SQLException e) {
143
                System.out.println("Error with getInt: " + e.getMessage());
144
              }
145

  
146
              // Advance to the next record in the cursor
147
              tableHasRows = rs.next();
148
            }
149
          } catch (SQLException e) {
150
            System.out.println("Error with next: " + e.getMessage());
151
          }
152
        } catch (SQLException e) {
153
          System.out.println("Error with getrset: " + e.getMessage());
154
        }
155
        pstmt.close();
156
      } catch (SQLException e) {
157
        System.out.println("Error getting id: " + e.getMessage());
158
      }
159

  
160
      Enumeration nodelist = nodeListResult.keys(); 
161
      while (nodelist.hasMoreElements()) {
162
        nodeid = ((Long)nodelist.nextElement()).longValue();
163

  
164
        try {
165
          pstmt =
166
            conn.prepareStatement("SELECT nodeid " +
167
                    "FROM xml_nodes START WITH nodeid = ? " +
168
                    "CONNECT BY nodeid = PRIOR parentnodeid");
169
          // Bind the values to the query
170
          pstmt.setLong(1, nodeid);
171
  
172
          pstmt.execute();
173
          try {
174
            ResultSet rs = pstmt.getResultSet();
175
            try {
176
              boolean tableHasRows = rs.next();
177
              while (tableHasRows) {
178
                try {
179
                  nodeid = rs.getLong(1);
180
                } catch (SQLException e) {
181
                  System.out.println("Error with getInt: " + e.getMessage());
182
                }
183

  
184
                // Advance to the next record in the cursor
185
                tableHasRows = rs.next();
186
                
187
              }
188
            } catch (SQLException e) {
189
              System.out.println("Error with next: " + e.getMessage());
190
            }
191
          } catch (SQLException e) {
192
            System.out.println("Error with getrset: " + e.getMessage());
193
          }
194
          pstmt.close();
195
        } catch (SQLException e) {
196
          System.out.println("Error getting id: " + e.getMessage());
197
        }
198

  
199
        // Record that the last record should be the root
200
        rootListResult.put(new Long(nodeid),new Long(nodeid));
201
      } 
202

  
203
      // Now look up the document id
204
      long docid = 0;
205
      String docname = null;
206
      String doctype = null;
207
      String doctitle = null;
208
      StringBuffer document = null; 
209
      Enumeration rootlist = rootListResult.keys();
210
      while (rootlist.hasMoreElements()) {
211
        nodeid = ((Long)rootlist.nextElement()).longValue();
212

  
213
        try {
214
          pstmt =
215
            conn.prepareStatement("SELECT docid,docname,doctype,doctitle " +
216
                    "FROM xml_documents " +
217
                    "WHERE rootnodeid = ?");
218
          // Bind the values to the query
219
          pstmt.setLong(1, nodeid);
220
 
221
          pstmt.execute();
222
          try {
223
            ResultSet rs = pstmt.getResultSet();
224
            try {
225
              boolean tableHasRows = rs.next();
226
              while (tableHasRows) {
227
                try {
228
                  docid = rs.getLong(1);
229
                  docname = rs.getString(2);
230
                  doctype = rs.getString(3);
231
                  doctitle = rs.getString(4);
232

  
233
                  document = new StringBuffer();
234
                  document.append("<docid>").append(docid).append("</docid>");
235
                  if (docname != null) {
236
                    document.append("<docname>" + docname + "</docname>");
237
                  }
238
                  if (doctype != null) {
239
                    document.append("<doctype>" + doctype + "</doctype>");
240
                  }
241
                  if (doctitle != null) {
242
                    document.append("<doctitle>" + doctitle + "</doctitle>");
243
                  }
244
                } catch (SQLException e) {
245
                  System.out.println("Error with getLong: " + e.getMessage());
246
                }
247

  
248
                // Advance to the next record in the cursor
249
                tableHasRows = rs.next();
250

  
251
              }
252
            } catch (SQLException e) {
253
              System.out.println("Error with next: " + e.getMessage());
254
            }
255
          } catch (SQLException e) {
256
            System.out.println("Error with getrset: " + e.getMessage());
257
          }
258
          pstmt.close();
259
        } catch (SQLException e) {
260
          System.out.println("Error getting id: " + e.getMessage());
261
        }
262

  
263
        // Store the document id and the root node id
264
        docListResult.put(new Long(docid),(String)document.toString());
265
      }
266

  
267
      return docListResult;
268
  }
269
}
270 0

  
MetaCatServlet.java
1
/**
2
 *        Name: MetaCatServlet.java
3
 *     Purpose: A Class that implements a metadata catalog as a java Servlet
4
 *   Copyright: 2000 Regents of the University of California and the
5
 *              National Center for Ecological Analysis and Synthesis
6
 *     Authors: Matt Jones, Dan Higgins
7
 * 
8
 *     Version: '$Id$'
9
 */
10

  
11
package edu.ucsb.nceas.metacat;
12

  
13
import java.io.PrintWriter;
14
import java.io.IOException;
15
import java.io.Reader;
16
import java.io.StringReader;
17
import java.io.BufferedReader;
18
import java.util.Enumeration;
19
import java.util.Hashtable;
20
import java.util.ResourceBundle;
21
import java.util.PropertyResourceBundle;
22
import java.net.URL;
23
import java.net.MalformedURLException;
24
import java.sql.PreparedStatement;
25
import java.sql.ResultSet;
26
import java.sql.Connection;
27
import java.sql.SQLException;
28

  
29
import javax.servlet.ServletConfig;
30
import javax.servlet.ServletContext;
31
import javax.servlet.ServletException;
32
import javax.servlet.ServletInputStream;
33
import javax.servlet.http.HttpServlet;
34
import javax.servlet.http.HttpServletRequest;
35
import javax.servlet.http.HttpServletResponse;
36
import javax.servlet.http.HttpUtils;
37

  
38
import oracle.xml.parser.v2.XSLStylesheet;
39
import oracle.xml.parser.v2.XSLException;
40
import oracle.xml.parser.v2.XMLDocumentFragment;
41
import oracle.xml.parser.v2.XSLProcessor;
42
import oracle.xml.parser.v2.*;    //Oracle parser - DFH
43
import java.io.File;  //DFH
44
import java.io.FileInputStream; //DFH
45

  
46
/**
47
 * A metadata catalog server implemented as a Java Servlet
48
   *
49
   * <p>Valid parameters are:<br>
50
   * action=query -- query the values of all elements and attributes
51
   *                     and return a result set of nodes<br>
52
   * action=getdocument -- display an XML document in XML or HTML<br>
53
   * qformat=xml -- display resultset from query in XML<br>
54
   * qformat=html -- display resultset from query in HTML<br>
55
   * action=getdocument -- display an XML document in XML or HTML<br>
56
   * docid=34 -- display the document with the document ID number 34<br>
57
   * action=putdocument -- load an XML document into the database store<br>
58
   * doctext -- XML text ofthe document to load into the database<br>
59
   * query -- actual query text (to go with 'action=query')<br>
60
   * action=validate -- vallidate the xml contained in validatetext<br>
61
   * valtext -- XML text to be validated
62
   * action=getdatadoc -- retreive a stored datadocument  //DFH
63
   * datadoc -- data document name (id)                   //DFH
64
 */
65
public class MetaCatServlet extends HttpServlet {
66

  
67
  private ServletConfig		config = null;
68
  private ServletContext	context = null;
69
  Connection 		conn = null;
70
  DBSimpleQuery		queryobj = null;
71
  DBReader		docreader = null;
72
  DBTransform		dbt = null;
73
  String 	user = null;
74
  String 	password = null;
75
  String 	defaultDB = null;
76
  String 	resultStyleURL = null;
77
  String 	xmlcatalogfile = null;
78
  String    defaultdatapath = null;  // path to directory where data files that can be downloaded will be stored
79
  String    executescript  = null;  // script to get data file and put it in defaultdocpath dir
80
  PropertyResourceBundle options = null;
81

  
82
  /**
83
   * Initialize the servlet by creating appropriate database connections
84
   */
85
  public void init( ServletConfig config ) throws ServletException {
86
    try {
87
      super.init( config );
88
      this.config = config;
89
      this.context = config.getServletContext();
90
      System.out.println("Servlet Initialize");
91

  
92
      // Get the configuration file information
93
      options = (PropertyResourceBundle)PropertyResourceBundle.getBundle("edu.ucsb.nceas.metacat.metacat");
94
      user = (String)options.handleGetObject("user");
95
      password = (String)options.handleGetObject("password");
96
      defaultDB = (String)options.handleGetObject("defaultDB");
97
      resultStyleURL = (String)options.handleGetObject("resultStyleURL");
98
      xmlcatalogfile = (String)options.handleGetObject("xmlcatalogfile");
99
      defaultdatapath = (String)options.handleGetObject("defaultdatapath");
100
      executescript = (String)options.handleGetObject("executescript");
101

  
102
      try {
103
        // Open a connection to the database
104
        conn = MetaCatUtil.openDBConnection(
105
                "oracle.jdbc.driver.OracleDriver",
106
                defaultDB, user, password);
107

  
108
        queryobj = new DBSimpleQuery(conn);
109
        docreader = new DBReader(conn);
110
        dbt = new DBTransform(conn);
111

  
112
      } catch (Exception e) {
113
        System.err.println("Error opening database connection");
114
      }
115
    } catch ( ServletException ex ) {
116
      throw ex;
117
    }
118
  }
119

  
120
  /** Handle "GET" method requests from HTTP clients */
121
  public void doGet (HttpServletRequest request, HttpServletResponse response)
122
    throws ServletException, IOException {
123

  
124
    // Process the data and send back the response
125
    handleGetOrPost(request, response);
126
  }
127

  
128
  /** Handle "POST" method requests from HTTP clients */
129
  public void doPost( HttpServletRequest request, HttpServletResponse response)
130
    throws ServletException, IOException {
131

  
132
    // Process the data and send back the response
133
    handleGetOrPost(request, response);
134
  }
135

  
136
  /**
137
   * Control servlet response depending on the action parameter specified
138
   */
139
  private void handleGetOrPost(HttpServletRequest request, 
140
    HttpServletResponse response) 
141
    throws ServletException, IOException {
142

  
143
    if (conn == null) {
144
      System.err.println("Connection to database lost.  Reopening...");
145
      try {
146
        // Open a connection to the database
147
        conn = MetaCatUtil.openDBConnection(
148
                "oracle.jdbc.driver.OracleDriver",
149
                defaultDB, user, password);
150
  
151
        queryobj = new DBSimpleQuery(conn);
152
        docreader = new DBReader(conn);
153
        dbt = new DBTransform(conn);
154
  
155
      } catch (Exception e) {
156
        System.err.println("Error opening database connection");
157
      }
158
    }
159

  
160
    // Get a handle to the output stream back to the client
161
    PrintWriter out = response.getWriter();
162
    //response.setContentType("text/html");
163
  
164
    String name = null;
165
    String[] value = null;
166
    String[] docid = new String[3];
167
    Hashtable params = new Hashtable();
168
    Enumeration paramlist = request.getParameterNames();
169
    while (paramlist.hasMoreElements()) {
170
      name = (String)paramlist.nextElement();
171
      value = request.getParameterValues(name);
172

  
173
      // Decode the docid and mouse click information
174
      if (name.endsWith(".y")) {
175
        docid[0] = name.substring(0,name.length()-2);
176
        //out.println("docid => " + docid[0]);
177
        params.put("docid", docid);
178
        name = "ypos";
179
      }
180
      if (name.endsWith(".x")) {
181
        name = "xpos";
182
      }
183

  
184
      //out.println(name + " => " + value[0]);
185
      params.put(name,value);
186
    }
187

  
188
    // Determine what type of request the user made
189
    // if the action parameter is set, use it as a default
190
    // but if the ypos param is set, calculate the action needed
191
    String action = ((String[])params.get("action"))[0];
192
    long ypos = 0;
193
    try {
194
      ypos = (new Long(((String[])params.get("ypos"))[0]).longValue());
195
      //out.println("<P>YPOS IS " + ypos);
196
      if (ypos <= 13) {
197
        action = "getdocument";
198
      } else if (ypos > 13 && ypos <= 27) {
199
        action = "validate";
200
      } else if (ypos > 27) {
201
        action = "transform";
202
      } else {
203
        action = "";
204
      }
205
    } catch (Exception npe) {
206
      //out.println("<P>Caught exception looking for Y value.");
207
    }
208

  
209
    if (action.equals("query")) {
210
      handleQueryAction(out, params, response);
211
    } else if (action.equals("getdocument")) {
212
      try {
213
        handleGetDocumentAction(out, params, response);
214
      } catch (ClassNotFoundException e) {
215
        out.println(e.getMessage());
216
      } catch (SQLException se) {
217
        out.println(se.getMessage());
218
      }
219
    } else if (action.equals("putdocument")) {
220
      handlePutDocumentAction(out, params, response);
221
    } else if (action.equals("validate")) {
222
      handleValidateAction(out, params, response);  
223
    } else if (action.equals("getdatadoc")) {
224
      handleGetDataDocumentAction(out, params, response);  
225
    } else {
226
      out.println("Error: action not registered.  Please report this error.");
227
    }
228

  
229
    // Close the stream to the client
230
    out.close();
231
  }
232

  
233
  /** 
234
   * Handle the database query request and return a result set, possibly
235
   * transformed from XML into HTML
236
   */
237
  private void handleQueryAction(PrintWriter out, Hashtable params, 
238
               HttpServletResponse response) {
239
      // Run the query
240
      Hashtable nodelist = null;
241
      String query = ((String[])params.get("query"))[0]; 
242
      if (queryobj != null) {
243
        nodelist = queryobj.findDocuments(query);
244
      } else {
245
        out.println("Query Object Init failed.");
246
	/*
247
        out.println(user);
248
        out.println(defaultDB);
249
        out.println(xmlcatalogfile);
250
        */
251
        return;
252
      }
253
 
254
      // Create a buffer to hold the xml result
255
      StringBuffer resultset = new StringBuffer();
256
 
257
      // Print the resulting root nodes
258
      Long nodeid;
259
      String document = null;
260
      resultset.append("<?xml version=\"1.0\"?>\n");
261
      //resultset.append("<!DOCTYPE resultset PUBLIC " +
262
      //               "\"-//NCEAS//resultset//EN\" \"resultset.dtd\">\n");
263
      resultset.append("<resultset>\n");
264
      resultset.append("  <query>" + query + "</query>");
265
      Enumeration rootlist = nodelist.keys(); 
266
      while (rootlist.hasMoreElements()) {
267
        nodeid = (Long)rootlist.nextElement();
268
        document = (String)nodelist.get(nodeid);
269
        resultset.append("  <document>" + document + "</document>");
270
      }
271
      resultset.append("</resultset>");
272

  
273
      String qformat = ((String[])params.get("qformat"))[0]; 
274
      if (qformat.equals("xml")) {
275
        // set content type and other response header fields first
276
        response.setContentType("text/xml");
277
        out.println(resultset.toString());
278
      } else if (qformat.equals("html")) {
279
        // set content type and other response header fields first
280
        response.setContentType("text/html");
281
        //out.println("Converting to HTML...");
282
        XMLDocumentFragment htmldoc = null;
283
        try {
284
          XSLStylesheet style = new XSLStylesheet(new URL(resultStyleURL), null);
285
          htmldoc = (new XSLProcessor()).processXSL(style, 
286
                     (Reader)(new StringReader(resultset.toString())),null);
287
          htmldoc.print(out);
288
        } catch (Exception e) {
289
          out.println("Error transforming document:\n" + e.getMessage());
290
        }
291
      }
292
  }
293

  
294
  /** 
295
   * Handle the database getdocument request and return a XML document, 
296
   * possibly transformed from XML into HTML
297
   */
298
  private void handleGetDocumentAction(PrintWriter out, Hashtable params, 
299
               HttpServletResponse response) 
300
               throws ClassNotFoundException, IOException, SQLException {
301
    String docidstr = null;
302
    long docid = 0;
303
    String doc = null;
304
    try {
305
      // Find the document id number
306
      docidstr = ((String[])params.get("docid"))[0]; 
307
      docid = (new Long(docidstr)).longValue();
308

  
309
      // Get the document indicated fromthe db
310
      doc = docreader.readXMLDocument(docid);
311
    } catch (NullPointerException npe) {
312
      response.setContentType("text/html");
313
      out.println("Error getting document ID: " + docidstr +" (" + docid + ")");
314
    }
315

  
316
      // Return the document in XML or HTML format
317
      String qformat = ((String[])params.get("qformat"))[0]; 
318
      if (qformat.equals("xml")) {
319
        // set content type and other response header fields first
320
        response.setContentType("text/xml");
321
        out.println(doc);
322
      } else if (qformat.equals("html")) {
323
        // set content type and other response header fields first
324
        response.setContentType("text/html");
325

  
326
        // Look up the document type
327
        String sourcetype = docreader.getDoctypeInfo(docid).getDoctype();
328

  
329
        // Transform the document to the new doctype
330
        dbt.transformXMLDocument(doc, sourcetype, "-//W3C//HTML//EN", out);
331
      }
332
  }
333

  
334
  /** 
335
   * Handle the database putdocument request and write an XML document 
336
   * to the database connection
337
   */
338
  private void handlePutDocumentAction(PrintWriter out, Hashtable params, 
339
               HttpServletResponse response) {
340

  
341
      // Get the document indicated
342
      String[] doctext = (String[])params.get("doctext");
343
      StringReader xml = new StringReader(doctext[0]);
344

  
345
      // write the document to the database
346
      try {
347
        DBSAXWriter dbw = new DBSAXWriter(xml, conn);
348
      } catch (SQLException e1) {
349
          out.println("Error 1 loading document:<p>\n" + e1.getMessage());
350
      }catch (IOException e2) {
351
          out.println("Error 2 loading document:<p>\n" + e2.getMessage());
352
      }catch (ClassNotFoundException e3) {
353
          out.println("Error 3 loading document:<p>\n" + e3.getMessage());
354
      }
355

  
356
      // set content type and other response header fields first
357
      response.setContentType("text/xml");
358
  
359
      out.println(doctext[0]);
360
  }
361
  
362
  /** 
363
   * Handle the validtion request and return the results 
364
   * to the requestor - DFH
365
   */
366
  private void handleValidateAction(PrintWriter out, Hashtable params, HttpServletResponse response) {
367

  
368
    // Get the document indicated
369
    String valtext = null;
370
    try {
371
      valtext = ((String[])params.get("valtext"))[0];
372
    } catch (Exception nullpe) {
373

  
374
      String docidstr = null;
375
      long docid = 0;
376
      try {
377
        // Find the document id number
378
        docidstr = ((String[])params.get("docid"))[0]; 
379
        docid = (new Long(docidstr)).longValue();
380
  
381
        // Get the document indicated fromthe db
382
        valtext = docreader.readXMLDocument(docid);
383
      } catch (NullPointerException npe) {
384
        response.setContentType("text/html");
385
        out.println("Error getting document ID: " + 
386
                     docidstr +" (" + docid + ")");
387
      }
388
    }
389

  
390
    SAXParser parser = new SAXParser();  // works for both Xerces and Oracle
391
    parser.setValidationMode(true);      // Oracle
392
    try {
393
      GenericXMLValidate gxv = new GenericXMLValidate(parser, xmlcatalogfile);
394
      boolean valid = gxv.validateString(valtext);
395

  
396
      // set content type and other response header fields first
397
      response.setContentType("text/html");
398
      out.println("<html>");
399
      out.println("<head><link rel=\"stylesheet\" type=\"text/css\" " +
400
                  "href=\"/xmltodb/rowcol.css\" /></head>");
401
      out.println("<body class=\"emlbody\">");
402
  
403
      if (valid) {
404
        out.println("The input XML is VALID!");
405
      } else {
406
        out.println("The input XML is NOT VALID<br />\n<pre>\n" 
407
                    + gxv.returnErrors() + "\n</pre>\n");
408
        //response.setContentType("text/xml");
409
        //out.println(valtext);
410
      } 
411
      out.println("</body></html>");
412
    } catch (NullPointerException npe2) {
413
      // set content type and other response header fields first
414
      response.setContentType("text/html");
415
      //out.println(valtext); 
416
      out.println("Error validating document."); 
417
    }
418
  }
419

  
420
  /** 
421
   * Look up the document type from the database
422
   *
423
   * @param docid the id of the document to look up
424
   */
425
  private String OldgetDoctype(long docid) {
426
    PreparedStatement pstmt;
427
    String doctype = null;
428
 
429
    try {
430
      pstmt =
431
        conn.prepareStatement("SELECT doctype " + 
432
                                "FROM xml_documents " +
433
                               "WHERE docid = ?");
434
      // Bind the values to the query
435
      pstmt.setLong(1, new Long(docid).longValue());
436

  
437
      pstmt.execute();
438
      try {
439
        ResultSet rs = pstmt.getResultSet();
440
        try {
441
          boolean tableHasRows = rs.next();
442
          if (tableHasRows) {
443
            try {
444
              doctype  = rs.getString(1);
445
            } catch (SQLException e) {
446
              System.out.println("Error with getString: " + e.getMessage());
447
            }
448
          }
449
        } catch (SQLException e) {
450
          System.out.println("Error with next: " + e.getMessage());
451
        }
452
      } catch (SQLException e) {
453
        System.out.println("Error with getrset: " + e.getMessage());
454
      }
455
      pstmt.close();
456
    } catch (SQLException e) {
457
      System.out.println("Error getting id: " + e.getMessage());
458
    }
459

  
460
    return doctype;
461
  }
462
    
463
    
464
  /** 
465
   * Handle the document request and return the results 
466
   * to the requestor - DFH
467
   */
468
  private void handleGetDataDocumentAction(PrintWriter out, Hashtable params, HttpServletResponse response) {
469
      boolean error_flag = false;
470
      String error_message = "";
471
      // Get the document indicated
472
      String[] datadoc = (String[])params.get("datadoc");
473
  //    defaultdatapath = "C:\\Temp\\";    // for testing only!!!
474
   //   executescript = "test.bat";        // for testing only!!!
475
      
476
      // set content type and other response header fields first
477
      response.setContentType("application/octet-stream");
478
   if (defaultdatapath!=null) {
479
        if(!defaultdatapath.endsWith(System.getProperty("file.separator"))) defaultdatapath=defaultdatapath+System.getProperty("file.separator");
480
      System.out.println("Path= "+defaultdatapath+datadoc[0]);
481
      if (executescript!=null) {
482
        String command = null;
483
        File scriptfile = new File(executescript);
484
        if (scriptfile.exists()) {
485
            command=executescript+" "+datadoc[0]; }  // execute script includes path
486
        else {     // look in defaultdatapath
487
                command = defaultdatapath+executescript+" "+datadoc[0];  // on Win98 one MUST include the .bat extender
488
        }
489
      System.out.println(command);
490
      try {
491
      Process proc = Runtime.getRuntime().exec(command);
492
      proc.waitFor();
493
      }
494
      catch (Exception eee) {
495
        System.out.println("Error running process!");
496
        error_flag = true;
497
        error_message = "Error running process!";}
498
      } // end executescript not null if
499
      File datafile = new File(defaultdatapath+datadoc[0]);
500
      try {
501
      FileInputStream fw = new FileInputStream(datafile);
502
      int x;
503
     while ((x = fw.read())!=-1) {
504
        out.write(x); }
505
      fw.close();
506
      
507
      }
508
      catch (Exception e) {
509
        System.out.println("Error in returning file\n"+e.getMessage());
510
        error_flag=true;
511
        error_message = error_message+"\nError in returning file\n"+e.getMessage();}
512
   } // end defaultdatapath not null if
513
  }
514
    
515
    
516
}
517 0

  
DBEntityResolver.java
1
/**
2
 *        Name: DBEntityResolver.java
3
 *     Purpose: A Class that implements org.xml.sax.EntityResolver interface
4
 *              for resolving external entities
5
 *   Copyright: 2000 Regents of the University of California and the
6
 *              National Center for Ecological Analysis and Synthesis
7
 *     Authors: Jivka Bojilova
8
 *
9
 *     Version: '$Id$'
10
 */
11

  
12
package edu.ucsb.nceas.metacat;
13

  
14
import org.xml.sax.*;
15

  
16
import java.sql.*;
17
import java.net.URL;
18
import java.net.MalformedURLException;
19
import java.util.Stack;
20
import java.util.EmptyStackException;
21

  
22
/** 
23
 * A database aware Class implementing EntityResolver interface for the SAX parser to
24
 * call when processing the XML stream and intercepting any external entities
25
 * (including the external DTD subset and external parameter entities, if any) before including them.
26
 */
27
public class DBEntityResolver implements EntityResolver
28
{
29

  
30
   static String doctype = null;
31
   private Connection conn = null;
32
   private int pIdCounter = 0;
33
   private long currentElementNo;
34

  
35
   /** Construct an instance of the DBEntityResolver clas
36
    *
37
    * @param conn the JDBC connection to which information is written
38
    */
39
   public DBEntityResolver(Connection conn)
40
   {
41
      this.conn = conn;
42
   }
43
   
44
   
45
   /** The Parser call this method before opening any external entity 
46
     * except the top-level document entity (including the external DTD subset,
47
     * external entities referenced within the DTD, and external entities referenced 
48
     * within the document element)*/
49
   public InputSource resolveEntity (String publicId, String systemId)
50
            throws MalformedURLException
51
   {
52
     String dbSystemId;
53
     
54
     currentElementNo = DBSAXHandler.elementNo;
55
     
56
     if (publicId != null) {
57
        pIdCounter += 1;
58
        System.out.println("from DBEntityResolver: current element is " + DBSAXHandler.elementNo);
59
        System.out.println("from DBEntityResolver: " + pIdCounter + " " + publicId);
60
        // look at the db XML Catalog and get dbSystemId by this publicId
61
        if (currentElementNo == 0) {
62
            doctype = publicId;
63
            dbSystemId = getDTDSystemID (conn, publicId);
64
            if (dbSystemId == "")
65
                // register publicId in db and use the provided systemId
66
                if (systemId != "") {
67
                    new URL(systemId);
68
                    registerDTDSystemID (conn, doctype, publicId, systemId);
69
                    return null;
70
                }
71
            new URL(dbSystemId);
72
            return new InputSource(dbSystemId);
73
        } 
74
        /*else {
75
            // look at the db XML Catalog and get dbSystemId by this publicId for a given doctype
76
            dbSystemId = getEntitySystemID (conn, doctype, publicId);
77
            if (dbSystemId == "")
78
                // register publicId in db for a given doctype and use the provided systemId
79
                if (systemId != "") {
80
                    new URL(systemId);
81
                    registerEntityPublicID (conn, doctype, publicId, systemId);
82
                    return null;
83
                }
84
            new URL(dbSystemId);
85
            return new InputSource(dbSystemId);
86
        }*/  
87
     }
88
     // publicId is null => doctype is null => doctype = docname
89
     if ( systemId != null) {
90
        if (currentElementNo == 0) {
91
            doctype = DBSAXHandler.docname;
92
            dbSystemId = getDTDSystemID (conn, doctype);
93
            if (dbSystemId == "") {
94
                new URL(systemId);
95
                registerDTDSystemID (conn, doctype, doctype, systemId);
96
                return null;
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff