Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that validates XML documents
4
 *             This class is designed to be 'parser independent
5
 *             i.e. it uses only org.xml.sax classes
6
 *             It is tied to SAX 2.0 methods
7
 *  Copyright: 2000 Regents of the University of California and the
8
 *             National Center for Ecological Analysis and Synthesis
9
 *    Authors: Dan Higgins, Matt Jones
10
 *    Release: @release@
11
 * 
12
 *   '$Author: tao $'
13
 *     '$Date: 2002-06-13 11:54:51 -0700 (Thu, 13 Jun 2002) $'
14
 * '$Revision: 1217 $'
15
 *
16
 * This program is free software; you can redistribute it and/or modify
17
 * it under the terms of the GNU General Public License as published by
18
 * the Free Software Foundation; either version 2 of the License, or
19
 * (at your option) any later version.
20
 *
21
 * This program is distributed in the hope that it will be useful,
22
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24
 * GNU General Public License for more details.
25
 *
26
 * You should have received a copy of the GNU General Public License
27
 * along with this program; if not, write to the Free Software
28
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
29
 */
30
package edu.ucsb.nceas.metacat;
31

    
32

    
33
import java.net.URL;
34
import java.net.MalformedURLException;
35
import java.util.*;
36
import java.io.*;
37
import java.lang.reflect.*;
38
import java.sql.*;
39

    
40
import org.w3c.dom.*;
41
import org.xml.sax.*;
42
import org.xml.sax.XMLReader;
43
import org.xml.sax.helpers.XMLReaderFactory;
44

    
45
import com.arbortext.catalog.*;
46

    
47
/**
48
 * Name: DBValidate.java
49
 *       Purpose: A Class that validates XML documents
50
 * 			   This class is designed to be parser independent
51
 *    			   i.e. it uses only org.xml.sax classes
52
 * 			   It is tied to SAX 2.0 methods
53
 *     Copyright: 2000 Regents of the University of California and the
54
 *                National Center for Ecological Analysis and Synthesis
55
 *                April 28, 2000
56
 *    Authors: Dan Higgins, Matt Jones
57
 */
58
public class DBValidate {
59
    
60
  static int WARNING = 0;
61
  static int ERROR=1;
62
  static int FATAL_ERROR=2;
63

    
64
  XMLReader parser;
65
  ErrorStorer ef;
66
  String xml_doc; // document to be parsed
67
    
68
  /** Construct a new validation object */
69
  public DBValidate(String parserName) {
70

    
71
    try {
72
      // Get an instance of the parser
73
      parser = XMLReaderFactory.createXMLReader(parserName);
74
      parser.setFeature("http://xml.org/sax/features/validation",true);
75
      //parser.setValidationMode(true);     // Oracle
76
    } catch (Exception e) {
77
      System.err.println("Could not create parser in DBValidate.DBValidate");
78
    }
79
  }
80
    
81
  /** Construct a new validation object using an OASIS catalog file */
82
  public DBValidate(String parserName, String xmlcatalogfile)  {
83
    this(parserName);
84

    
85
    CatalogEntityResolver cer = new CatalogEntityResolver();
86
    try {
87
      Catalog myCatalog = new Catalog();
88
      myCatalog.loadSystemCatalogs();
89
      myCatalog.parseCatalog(xmlcatalogfile);
90
      cer.setCatalog(myCatalog);
91
    } catch (Exception e) {
92
      System.out.println("Problem creating Catalog in DBValidate.DBValidate");
93
    }
94

    
95
    parser.setEntityResolver(cer);
96
  }
97

    
98
  /** Construct a new validation object using a database entity resolver */
99
  public DBValidate(String parserName, DBConnection conn) {
100
    this(parserName);
101

    
102
    DBEntityResolver dbresolver = new DBEntityResolver(conn);
103
    parser.setEntityResolver(dbresolver);
104
  }
105

    
106
  /** 
107
   * validate an xml document against its DTD
108
   *
109
   * @param doc the filename of the document to validate
110
   */
111
  public boolean validate(String doc) {
112
    xml_doc = doc;    
113
    ef = new ErrorStorer();
114
    ef.resetErrors();
115
    parser.setErrorHandler(ef);
116
    try {
117
      parser.parse((createURL(xml_doc)).toString());
118
    } catch (IOException e) {
119
      System.out.println("IOException:Could not parse :" + xml_doc +
120
                         " from DBValidate.validate");
121
      ParseError eip = null;
122
      eip = new ParseError("",0,0,
123
                "IOException:Could not parse :"+xml_doc);
124
      if (ef.errorNodes == null)  ef.errorNodes = new Vector();
125
      ef.errorNodes.addElement(eip);
126
        
127
    } catch (Exception e) {} 
128

    
129
      // {System.out.println("Exception parsing:Could not parse :"+xml_doc);} 
130
    
131
    if (ef != null && ef.getErrorNodes()!=null && 
132
      ef.getErrorNodes().size() > 0 ) {
133
      return false; 
134
    } else {
135
      return true;
136
    }
137
  }
138
    
139
  /** 
140
   * validate an xml document against its DTD
141
   *
142
   * @param xmldoc the String containing the xml document to validate
143
   */
144
  public boolean validateString(String xmldoc) {
145
    // string is actual XML here, NOT URL or file name    
146
    ef = new ErrorStorer();
147
    ef.resetErrors();
148
    parser.setErrorHandler(ef);
149
      
150
    InputSource is = new InputSource(new StringReader(xmldoc));
151
    try {
152
      parser.parse(is);
153
    }
154
    catch (Exception e) {
155
      System.out.println("Error in parsing in DBValidate.validateString");
156
    }
157

    
158
    if (ef != null && ef.getErrorNodes()!=null && 
159
      ef.getErrorNodes().size() > 0 ) {
160
      return false; 
161
    } else {
162
      return true;
163
    }
164
  }
165
    
166
  /** provide a list of errors from the validation process */
167
  public String returnErrors() {
168
    StringBuffer errorstring = new StringBuffer();
169
    errorstring.append("<?xml version=\"1.0\" ?>\n");
170
    if (ef != null && ef.getErrorNodes()!=null && 
171
        ef.getErrorNodes().size() > 0 ) {
172
      Vector errors = ef.getErrorNodes();
173
      errorstring.append("<validationerrors>\n");
174
      for (Enumeration e = errors.elements() ; e.hasMoreElements() ;) {
175
        errorstring.append(
176
                      ((ParseError)(e.nextElement())).toXML());
177
      }
178
      errorstring.append("</validationerrors>\n");
179
    } else {
180
      errorstring.append("<valid />\n");
181
    }
182
    return errorstring.toString();
183
  }
184
              
185
  /** Create a URL object from either a URL string or a plain file name. */
186
  private URL createURL(String name) throws Exception {
187
    try {
188
      URL u = new URL(name);
189
      return u;
190
    } catch (MalformedURLException ex) {
191
    }
192
    URL u = new URL("file:" + new File(name).getAbsolutePath());
193
    return u;
194
  }    
195

    
196
  /** 
197
   * main method for testing 
198
   * <p>
199
   * Usage: java DBValidate <xmlfile or URL>
200
   */
201
  public static void main(String[] args) {
202

    
203
    if (args.length != 1) {
204
      System.out.println("Usage: java DBValidate <xmlfile or URL>");
205
      System.exit(0);
206
    }
207

    
208
    String doc = args[0];
209

    
210
    MetaCatUtil util = new MetaCatUtil();
211
    DBConnection conn = null;
212
    int serailNumber = -1;
213
    try {
214
      conn = DBConnectionPool.getDBConnection("DBValidate.main");
215
      serailNumber = conn.getCheckOutSerialNumber();
216
  
217
      DBValidate gxv = new DBValidate(util.getOption("saxparser"), conn);
218
      if (gxv.validate(doc)) {
219
        System.out.print(gxv.returnErrors());
220
      } else {
221
        System.out.print(gxv.returnErrors());
222
      }
223
    } catch (SQLException e) {
224
      System.out.println("<error>Couldn't open database connection.</error>");
225
    } 
226
    finally
227
    {
228
      DBConnectionPool.returnDBConnection(conn, serailNumber);
229
    }//finally
230
  }
231

    
232
    
233
  /**
234
   * ErrorStorer has been revised here to simply create a Vector of 
235
   * ParseError objects
236
   *
237
   */
238
  class ErrorStorer implements ErrorHandler {
239

    
240
    //
241
    // Data
242
    //
243
    Vector errorNodes = null;
244
        
245
    /**
246
     * Constructor
247
     */
248
    public ErrorStorer() {
249
    }
250

    
251
    /**
252
     * The client is is allowed to get a reference to the Hashtable,
253
     * and so could corrupt it, or add to it...
254
     */
255
    public Vector getErrorNodes() {
256
        return errorNodes;
257
    }
258

    
259
    /**
260
     * The ParseError object for the node key is returned.
261
     * If the node doesn't have errors, null is returned.
262
     */
263
    public Object getError() {
264
        if (errorNodes == null)
265
            return null;
266
        return errorNodes;
267
    }
268
        
269
    /**
270
     * Reset the error storage.
271
     */
272
    public void resetErrors() {
273
        if (errorNodes != null)
274
        errorNodes.removeAllElements();
275
    }
276
    
277
    /***/
278
    public void warning(SAXParseException ex) {
279
        handleError(ex, WARNING);
280
    }
281

    
282
    public void error(SAXParseException ex) {
283
        handleError(ex, ERROR);
284
    }
285

    
286
    public void fatalError(SAXParseException ex) throws SAXException {
287
        handleError(ex, FATAL_ERROR);
288
    }
289
        
290
    private void handleError(SAXParseException ex, int type) {
291
      // System.out.println("!!! handleError: "+ex.getMessage());
292

    
293
      if (errorNodes == null) {
294
        errorNodes = new Vector();
295
      }
296

    
297
      ParseError eip = null;
298
      eip = new ParseError(ex.getSystemId(), ex.getLineNumber(),
299
                           ex.getColumnNumber(), ex.getMessage());
300
        
301
      // put it in the Hashtable.
302
      errorNodes.addElement(eip);
303
    }
304
        
305
  }
306
    
307
  /**
308
   * The ParseError class wraps up all the error info from
309
   * the ErrorStorer's error method.
310
   *
311
   * @see ErrorStorer
312
   */
313
  class ParseError extends Object {
314

    
315
    //
316
    // Data
317
    //
318

    
319
    String fileName;
320
    int lineNo;
321
    int charOffset;
322
    String msg;
323

    
324
    /**
325
     * Constructor
326
     */
327
    public ParseError(String fileName, int lineNo, int charOffset, String msg) {
328
      this.fileName=fileName;
329
      this.lineNo=lineNo;
330
      this.charOffset=charOffset;
331
      this.msg=msg;
332
    }
333

    
334
    //
335
    // Getters...
336
    //
337
    public String getFileName() { return fileName; }
338
    public int getLineNo() { return lineNo; }
339
    public int getCharOffset() { return charOffset;}
340
    public String getMsg() { return msg; }
341
    public void setMsg(String s) { msg = s; }
342

    
343
    /** Return the error message as an xml fragment */
344
    public String toXML() {
345
      StringBuffer err = new StringBuffer();
346
      err.append("<error>\n");
347
      err.append("<filename>").append(getFileName()).append("</filename>\n");
348
      err.append("<line>").append(getLineNo()).append("</line>\n");
349
      err.append("<offset>").append(getCharOffset()).append("</offset>\n");
350
      err.append("<message>").append(getMsg()).append("</message>\n");
351
      err.append("</error>\n");
352
      return err.toString();
353
    }
354
  }
355
}
(23-23/43)