Project

General

Profile

1
/**
2
 *      Name: GenericXMLValidate.java
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 1.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
10
 * 
11
 *   Version: '$Id: GenericXMLValidate.java 168 2000-06-16 03:20:41Z jones $'
12
 */
13
package edu.ucsb.nceas.metacat;
14

    
15

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

    
22
import org.w3c.dom.*;
23
import org.xml.sax.*;
24
import org.xml.sax.Parser;
25

    
26
import com.arbortext.catalog.*;
27

    
28
/**
29
 * Name: GenericXMLValidate.java
30
 *       Purpose: A Class that validates XML documents
31
 * 			   This class is designed to be 'parser independent
32
 *    			   i.e. it uses only org.xml.sax classes
33
 * 			   It is tied to SAX 1.0 methods
34
 *     Copyright: 2000 Regents of the University of California and the
35
 *                National Center for Ecological Analysis and Synthesis
36
 *                April 28, 2000
37
 * 
38
 * @author Dan Higgins
39
 * @version 1.0
40
 */
41
public class GenericXMLValidate{
42
    
43
    static int WARNING = 0;
44
    static int ERROR=1;
45
    static int FATAL_ERROR=2;
46

    
47
    Parser parser;
48
    ErrorStorer ef;
49
    String xml_doc; // document to be parsed
50
    
51
    public GenericXMLValidate(Parser parse)  {
52
        parser = parse;
53
        CatalogEntityResolver cer = new CatalogEntityResolver();
54
        try {
55
            Catalog myCatalog = new Catalog();
56
            myCatalog.loadSystemCatalogs();
57
            cer.setCatalog(myCatalog);
58
        }
59
        catch (Exception e) {System.out.println("Problem creating Catalog!");}
60
        parser.setEntityResolver(cer);
61
/*            Class defaultParserClass = Class.forName(DEFAULT_PARSER_NAME);
62
            Object par = defaultParserClass.newInstance();
63
            Class[] parameterTypes = new Class[] {boolean.class};
64
            Method set_validation;
65
            Object[] arguments = new Object[] {new Boolean(true)};
66
            try {
67
                  set_validation = defaultParserClass.getMethod("setValidationMode", parameterTypes);
68
                  set_validation.invoke(par, arguments);
69
                } catch (NoSuchMethodException e) {
70
                    System.out.println(e);
71
                } catch (IllegalAccessException e) {
72
                    System.out.println(e);
73
                } catch (InvocationTargetException e) {
74
                    System.out.println(e);
75
                }
76
            
77
            
78
            parser = (Parser)par;
79
*/
80
    }
81
    
82
    public GenericXMLValidate(Parser parse, String xmlcatalogfile)  {
83
        parser = parse;
84
        CatalogEntityResolver cer = new CatalogEntityResolver();
85
        try {
86
            Catalog myCatalog = new Catalog();
87
            myCatalog.loadSystemCatalogs();
88
            myCatalog.parseCatalog(xmlcatalogfile);
89
            cer.setCatalog(myCatalog);
90
        }
91
        catch (Exception e) {System.out.println("Problem creating Catalog!");}
92
        parser.setEntityResolver(cer);
93
    }
94

    
95
    public boolean validate(String doc) {
96
        xml_doc = doc;    
97
        ef = new ErrorStorer();
98
        ef.resetErrors();
99
        parser.setErrorHandler(ef);
100
        try {
101
            parser.parse((createURL(xml_doc)).toString());
102
        }
103
        catch (IOException e) {
104
            System.out.println("IOException:Could not parse :"+xml_doc);
105
            ParseError eip = null;
106
            eip = new ParseError("",0,0,"","IOException:Could not parse :"+xml_doc);
107
            if (ef.errorNodes == null)  ef.errorNodes = new Vector();
108
            ef.errorNodes.addElement(eip);
109
        
110
        } catch (Exception e) {} // {System.out.println("Exception parsing:Could not parse :"+xml_doc);} 
111
    
112
        if (ef != null && ef.getErrorNodes()!=null && ef.getErrorNodes().size() > 0 ) {
113
            return false; 
114
            
115
        }
116
        else {return true;}
117
        
118
    }
119
    
120
    public boolean validateString(String xmldoc) {
121
    // string is actual XML here, NOT URL or file name    
122
        ef = new ErrorStorer();
123
        ef.resetErrors();
124
        parser.setErrorHandler(ef);
125
        
126
        InputSource is = new InputSource(new StringReader(xmldoc));
127
        try {
128
            parser.parse(is);
129
        }
130
        catch (Exception e) {System.out.println("Error in parsing!");}
131

    
132
    
133
        if (ef != null && ef.getErrorNodes()!=null && ef.getErrorNodes().size() > 0 ) {
134
            return false; 
135
            
136
        }
137
        else {return true;}
138
        
139
    }
140
    
141
    
142
    public String returnErrors() {
143
        String errorstring = "";
144
        if (ef != null && ef.getErrorNodes()!=null && ef.getErrorNodes().size() > 0 ) {
145
            Vector errors = ef.getErrorNodes();
146
            for (Enumeration e = errors.elements() ; e.hasMoreElements() ;) {
147
                errorstring = errorstring +((ParseError)(e.nextElement())).getMsg()+"\n";
148
                errorstring = errorstring + "----\n";
149
            }
150
        }
151
        else {errorstring = "No errors were detected!!!";}
152
        return errorstring;
153
    }
154
              
155
    //
156
    // Create a URL object from either a URL string or a plain file name.
157
    //
158
    private URL createURL(String name) throws Exception {
159
        try {
160
                URL u = new URL(name);
161
                return u;
162
        } catch (MalformedURLException ex) {
163
        }
164
        URL u = new URL("file:" + new File(name).getAbsolutePath());
165
        return u;
166
    }    
167
    
168
    /**
169
     * ErrorStorer has been revised here to simply create a Vector of 
170
     * ParseError objects
171
     *
172
     */
173
    class ErrorStorer 
174
        implements ErrorHandler
175
        
176
    {
177

    
178
        //
179
        // Data
180
        //
181
        Vector errorNodes = null;
182
        
183
        /**
184
         * Constructor
185
         */
186
        public ErrorStorer() {
187
        }
188

    
189
        /**
190
         * The client is is allowed to get a reference to the Hashtable,
191
         * and so could corrupt it, or add to it...
192
         */
193
        public Vector getErrorNodes() {
194
            return errorNodes;
195
        }
196

    
197
        /**
198
         * The ParseError object for the node key is returned.
199
         * If the node doesn't have errors, null is returned.
200
         */
201
        public Object getError() {
202
            if (errorNodes == null)
203
                return null;
204
            return errorNodes;
205
        }
206
        
207
        /**
208
         * Reset the error storage.
209
         */
210
        public void resetErrors() {
211
            if (errorNodes != null)
212
            errorNodes.removeAllElements();
213
        }
214
        
215
        /***/
216
        public void warning(SAXParseException ex) {
217
            handleError(ex, WARNING);
218
        }
219

    
220
        public void error(SAXParseException ex) {
221
            handleError(ex, ERROR);
222
        }
223

    
224
        public void fatalError(SAXParseException ex) throws SAXException {
225
            handleError(ex, FATAL_ERROR);
226
        }
227
        
228
        private void handleError(SAXParseException ex, int type) {
229
   //         System.out.println("!!! handleError: "+ex.getMessage());
230

    
231
            StringBuffer errorString = new StringBuffer();
232
            errorString.append("at line number, ");
233
            errorString.append(ex.getLineNumber());
234
            errorString.append(": ");
235
            errorString.append(ex.getMessage());
236

    
237
            
238
            if (errorNodes == null)  errorNodes = new Vector();
239
            ParseError eip = null;
240
            eip = new ParseError(ex.getSystemId(),ex.getLineNumber(),ex.getColumnNumber(),"",errorString.toString());
241
        
242

    
243
            // put it in the Hashtable.
244
            errorNodes.addElement(eip);
245
        }
246
        
247
    }
248
    
249
    /**
250
     * The ParseError class wraps up all the error info from
251
     * the ErrorStorer's error method.
252
     *
253
     * @see ErrorStorer
254
     */
255
    class ParseError extends Object {
256

    
257
        //
258
        // Data
259
        //
260

    
261
        String fileName;
262
        int lineNo;
263
        int charOffset;
264
        Object key;
265
        String msg;
266

    
267
        /**
268
         * Constructor
269
         */
270
        public ParseError(String fileName, int lineNo, int charOffset,
271
                           Object key, 
272
                           String msg)
273
        {
274
            this. fileName=fileName;
275
            this. lineNo=lineNo;
276
            this. charOffset=charOffset;
277
            this. key=key;
278
            this. msg=msg;
279
        }
280

    
281
        //
282
        // Getters...
283
        //
284
        public String getFileName() { return fileName; }
285
        public int getLineNo() { return lineNo; }
286
        public int getCharOffset() { return charOffset;}
287
        public Object getKey() { return key; }
288
        public String getMsg() { return msg; }
289
        public void setMsg(String s) { msg = s; }
290
    }
291
              
292
              
293
}
(15-15/20)