Project

General

Profile

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