Project

General

Profile

1 69 higgins
package edu.ucsb.nceas.metacat;
2
3
4 66 higgins
import java.net.URL;
5
import java.net.MalformedURLException;
6
import java.util.*;
7
import java.io.*;
8
import java.lang.reflect.*;
9
10
import org.w3c.dom.*;
11
import org.xml.sax.*;
12
import org.xml.sax.Parser;
13
14
import com.arbortext.catalog.*;
15
16
/**
17
 * Name: GenericXMLValidate.java
18
 *       Purpose: A Class that validates XML documents
19
 * 			   This class is designed to be 'parser independent
20
 *    			   i.e. it uses only org.xml.sax classes
21
 * 			   It is tied to SAX 1.0 methods
22
 *     Copyright: 2000 Regents of the University of California and the
23
 *                National Center for Ecological Analysis and Synthesis
24
 *                April 28, 2000
25
 *
26
 * @author Dan Higgins
27
 * @version 1.0
28
 */
29
public class GenericXMLValidate{
30
31
    static int WARNING = 0;
32
    static int ERROR=1;
33
    static int FATAL_ERROR=2;
34 80 jones
35 66 higgins
    Parser parser;
36
    ErrorStorer ef;
37
    String xml_doc; // document to be parsed
38
39 83 jones
    public GenericXMLValidate(Parser parse)  {
40 66 higgins
        parser = parse;
41
        CatalogEntityResolver cer = new CatalogEntityResolver();
42
        try {
43
            Catalog myCatalog = new Catalog();
44
            myCatalog.loadSystemCatalogs();
45
            cer.setCatalog(myCatalog);
46
        }
47
        catch (Exception e) {System.out.println("Problem creating Catalog!");}
48
        parser.setEntityResolver(cer);
49
/*            Class defaultParserClass = Class.forName(DEFAULT_PARSER_NAME);
50
            Object par = defaultParserClass.newInstance();
51
            Class[] parameterTypes = new Class[] {boolean.class};
52
            Method set_validation;
53
            Object[] arguments = new Object[] {new Boolean(true)};
54
            try {
55
                  set_validation = defaultParserClass.getMethod("setValidationMode", parameterTypes);
56
                  set_validation.invoke(par, arguments);
57
                } catch (NoSuchMethodException e) {
58
                    System.out.println(e);
59
                } catch (IllegalAccessException e) {
60
                    System.out.println(e);
61
                } catch (InvocationTargetException e) {
62
                    System.out.println(e);
63
                }
64
65
66
            parser = (Parser)par;
67
*/
68
    }
69
70 83 jones
    public GenericXMLValidate(Parser parse, String xmlcatalogfile)  {
71
        parser = parse;
72
        CatalogEntityResolver cer = new CatalogEntityResolver();
73
        try {
74
            Catalog myCatalog = new Catalog();
75
            myCatalog.loadSystemCatalogs();
76
            myCatalog.parseCatalog(xmlcatalogfile);
77
            cer.setCatalog(myCatalog);
78
        }
79
        catch (Exception e) {System.out.println("Problem creating Catalog!");}
80
        parser.setEntityResolver(cer);
81
    }
82
83 66 higgins
    public boolean validate(String doc) {
84
        xml_doc = doc;
85
        ef = new ErrorStorer();
86
        ef.resetErrors();
87
        parser.setErrorHandler(ef);
88
        try {
89
            parser.parse((createURL(xml_doc)).toString());
90
        }
91
        catch (IOException e) {
92
            System.out.println("IOException:Could not parse :"+xml_doc);
93
            ParseError eip = null;
94
            eip = new ParseError("",0,0,"","IOException:Could not parse :"+xml_doc);
95
            if (ef.errorNodes == null)  ef.errorNodes = new Vector();
96
            ef.errorNodes.addElement(eip);
97
98
        } catch (Exception e) {} // {System.out.println("Exception parsing:Could not parse :"+xml_doc);}
99
100
        if (ef != null && ef.getErrorNodes()!=null && ef.getErrorNodes().size() > 0 ) {
101
            return false;
102
103
        }
104
        else {return true;}
105
106
    }
107
108
    public boolean validateString(String xmldoc) {
109
    // string is actual XML here, NOT URL or file name
110
        ef = new ErrorStorer();
111
        ef.resetErrors();
112
        parser.setErrorHandler(ef);
113
114
        InputSource is = new InputSource(new StringReader(xmldoc));
115
        try {
116
            parser.parse(is);
117
        }
118
        catch (Exception e) {System.out.println("Error in parsing!");}
119
120
121
        if (ef != null && ef.getErrorNodes()!=null && ef.getErrorNodes().size() > 0 ) {
122
            return false;
123
124
        }
125
        else {return true;}
126
127
    }
128
129
130
    public String returnErrors() {
131
        String errorstring = "";
132
        if (ef != null && ef.getErrorNodes()!=null && ef.getErrorNodes().size() > 0 ) {
133
            Vector errors = ef.getErrorNodes();
134
            for (Enumeration e = errors.elements() ; e.hasMoreElements() ;) {
135
                errorstring = errorstring +((ParseError)(e.nextElement())).getMsg()+"\n";
136
                errorstring = errorstring + "----\n";
137
            }
138
        }
139
        else {errorstring = "No errors were detected!!!";}
140
        return errorstring;
141
    }
142
143
    //
144
    // Create a URL object from either a URL string or a plain file name.
145
    //
146
    private URL createURL(String name) throws Exception {
147
        try {
148
                URL u = new URL(name);
149
                return u;
150
        } catch (MalformedURLException ex) {
151
        }
152
        URL u = new URL("file:" + new File(name).getAbsolutePath());
153
        return u;
154
    }
155
156
    /**
157
     * ErrorStorer has been revised here to simply create a Vector of
158
     * ParseError objects
159
     *
160
     */
161
    class ErrorStorer
162
        implements ErrorHandler
163
164
    {
165
166
        //
167
        // Data
168
        //
169
        Vector errorNodes = null;
170
171
        /**
172
         * Constructor
173
         */
174
        public ErrorStorer() {
175
        }
176
177
        /**
178
         * The client is is allowed to get a reference to the Hashtable,
179
         * and so could corrupt it, or add to it...
180
         */
181
        public Vector getErrorNodes() {
182
            return errorNodes;
183
        }
184
185
        /**
186
         * The ParseError object for the node key is returned.
187
         * If the node doesn't have errors, null is returned.
188
         */
189
        public Object getError() {
190
            if (errorNodes == null)
191
                return null;
192
            return errorNodes;
193
        }
194
195
        /**
196
         * Reset the error storage.
197
         */
198
        public void resetErrors() {
199
            if (errorNodes != null)
200
            errorNodes.removeAllElements();
201
        }
202
203
        /***/
204
        public void warning(SAXParseException ex) {
205
            handleError(ex, WARNING);
206
        }
207
208
        public void error(SAXParseException ex) {
209
            handleError(ex, ERROR);
210
        }
211
212
        public void fatalError(SAXParseException ex) throws SAXException {
213
            handleError(ex, FATAL_ERROR);
214
        }
215
216
        private void handleError(SAXParseException ex, int type) {
217
   //         System.out.println("!!! handleError: "+ex.getMessage());
218
219
            StringBuffer errorString = new StringBuffer();
220
            errorString.append("at line number, ");
221
            errorString.append(ex.getLineNumber());
222
            errorString.append(": ");
223
            errorString.append(ex.getMessage());
224
225
226
            if (errorNodes == null)  errorNodes = new Vector();
227
            ParseError eip = null;
228
            eip = new ParseError(ex.getSystemId(),ex.getLineNumber(),ex.getColumnNumber(),"",errorString.toString());
229
230
231
            // put it in the Hashtable.
232
            errorNodes.addElement(eip);
233
        }
234
235
    }
236
237
    /**
238
     * The ParseError class wraps up all the error info from
239
     * the ErrorStorer's error method.
240
     *
241
     * @see ErrorStorer
242
     */
243
    class ParseError extends Object {
244
245
        //
246
        // Data
247
        //
248
249
        String fileName;
250
        int lineNo;
251
        int charOffset;
252
        Object key;
253
        String msg;
254
255
        /**
256
         * Constructor
257
         */
258
        public ParseError(String fileName, int lineNo, int charOffset,
259
                           Object key,
260
                           String msg)
261
        {
262
            this. fileName=fileName;
263
            this. lineNo=lineNo;
264
            this. charOffset=charOffset;
265
            this. key=key;
266
            this. msg=msg;
267
        }
268
269
        //
270
        // Getters...
271
        //
272
        public String getFileName() { return fileName; }
273
        public int getLineNo() { return lineNo; }
274
        public int getCharOffset() { return charOffset;}
275
        public Object getKey() { return key; }
276
        public String getMsg() { return msg; }
277
        public void setMsg(String s) { msg = s; }
278
    }
279
280
281 80 jones
}