Project

General

Profile

1
package edu.ucsb.nceas.metacat;
2

    
3

    
4
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

    
35
    static String defaultCatalog = "/home/httpd/html/xmltodb/catalog.txt";   
36
    
37
    Parser parser;
38
    ErrorStorer ef;
39
    String xml_doc; // document to be parsed
40
    
41
    public GenericXMLValidate( Parser parse)  {
42
        parser = parse;
43
        CatalogEntityResolver cer = new CatalogEntityResolver();
44
        try {
45
            Catalog myCatalog = new Catalog();
46
            myCatalog.loadSystemCatalogs();
47
            myCatalog.parseCatalog(defaultCatalog);
48
            cer.setCatalog(myCatalog);
49
        }
50
        catch (Exception e) {System.out.println("Problem creating Catalog!");}
51
        parser.setEntityResolver(cer);
52
/*            Class defaultParserClass = Class.forName(DEFAULT_PARSER_NAME);
53
            Object par = defaultParserClass.newInstance();
54
            Class[] parameterTypes = new Class[] {boolean.class};
55
            Method set_validation;
56
            Object[] arguments = new Object[] {new Boolean(true)};
57
            try {
58
                  set_validation = defaultParserClass.getMethod("setValidationMode", parameterTypes);
59
                  set_validation.invoke(par, arguments);
60
                } catch (NoSuchMethodException e) {
61
                    System.out.println(e);
62
                } catch (IllegalAccessException e) {
63
                    System.out.println(e);
64
                } catch (InvocationTargetException e) {
65
                    System.out.println(e);
66
                }
67
            
68
            
69
            parser = (Parser)par;
70
*/
71
    }
72
    
73
    public boolean validate(String doc) {
74
        xml_doc = doc;    
75
        ef = new ErrorStorer();
76
        ef.resetErrors();
77
        parser.setErrorHandler(ef);
78
        try {
79
            parser.parse((createURL(xml_doc)).toString());
80
        }
81
        catch (IOException e) {
82
            System.out.println("IOException:Could not parse :"+xml_doc);
83
            ParseError eip = null;
84
            eip = new ParseError("",0,0,"","IOException:Could not parse :"+xml_doc);
85
            if (ef.errorNodes == null)  ef.errorNodes = new Vector();
86
            ef.errorNodes.addElement(eip);
87
        
88
        } catch (Exception e) {} // {System.out.println("Exception parsing:Could not parse :"+xml_doc);} 
89
    
90
        if (ef != null && ef.getErrorNodes()!=null && ef.getErrorNodes().size() > 0 ) {
91
            return false; 
92
            
93
        }
94
        else {return true;}
95
        
96
    }
97
    
98
    public boolean validateString(String xmldoc) {
99
    // string is actual XML here, NOT URL or file name    
100
        ef = new ErrorStorer();
101
        ef.resetErrors();
102
        parser.setErrorHandler(ef);
103
        
104
        InputSource is = new InputSource(new StringReader(xmldoc));
105
        try {
106
            parser.parse(is);
107
        }
108
        catch (Exception e) {System.out.println("Error in parsing!");}
109

    
110
    
111
        if (ef != null && ef.getErrorNodes()!=null && ef.getErrorNodes().size() > 0 ) {
112
            return false; 
113
            
114
        }
115
        else {return true;}
116
        
117
    }
118
    
119
    
120
    public String returnErrors() {
121
        String errorstring = "";
122
        if (ef != null && ef.getErrorNodes()!=null && ef.getErrorNodes().size() > 0 ) {
123
            Vector errors = ef.getErrorNodes();
124
            for (Enumeration e = errors.elements() ; e.hasMoreElements() ;) {
125
                errorstring = errorstring +((ParseError)(e.nextElement())).getMsg()+"\n";
126
                errorstring = errorstring + "----\n";
127
            }
128
        }
129
        else {errorstring = "No errors were detected!!!";}
130
        return errorstring;
131
    }
132
              
133
    //
134
    // Create a URL object from either a URL string or a plain file name.
135
    //
136
    private URL createURL(String name) throws Exception {
137
        try {
138
                URL u = new URL(name);
139
                return u;
140
        } catch (MalformedURLException ex) {
141
        }
142
        URL u = new URL("file:" + new File(name).getAbsolutePath());
143
        return u;
144
    }    
145
    
146
    /**
147
     * ErrorStorer has been revised here to simply create a Vector of 
148
     * ParseError objects
149
     *
150
     */
151
    class ErrorStorer 
152
        implements ErrorHandler
153
        
154
    {
155

    
156
        //
157
        // Data
158
        //
159
        Vector errorNodes = null;
160
        
161
        /**
162
         * Constructor
163
         */
164
        public ErrorStorer() {
165
        }
166

    
167
        /**
168
         * The client is is allowed to get a reference to the Hashtable,
169
         * and so could corrupt it, or add to it...
170
         */
171
        public Vector getErrorNodes() {
172
            return errorNodes;
173
        }
174

    
175
        /**
176
         * The ParseError object for the node key is returned.
177
         * If the node doesn't have errors, null is returned.
178
         */
179
        public Object getError() {
180
            if (errorNodes == null)
181
                return null;
182
            return errorNodes;
183
        }
184
        
185
        /**
186
         * Reset the error storage.
187
         */
188
        public void resetErrors() {
189
            if (errorNodes != null)
190
            errorNodes.removeAllElements();
191
        }
192
        
193
        /***/
194
        public void warning(SAXParseException ex) {
195
            handleError(ex, WARNING);
196
        }
197

    
198
        public void error(SAXParseException ex) {
199
            handleError(ex, ERROR);
200
        }
201

    
202
        public void fatalError(SAXParseException ex) throws SAXException {
203
            handleError(ex, FATAL_ERROR);
204
        }
205
        
206
        private void handleError(SAXParseException ex, int type) {
207
   //         System.out.println("!!! handleError: "+ex.getMessage());
208

    
209
            StringBuffer errorString = new StringBuffer();
210
            errorString.append("at line number, ");
211
            errorString.append(ex.getLineNumber());
212
            errorString.append(": ");
213
            errorString.append(ex.getMessage());
214

    
215
            
216
            if (errorNodes == null)  errorNodes = new Vector();
217
            ParseError eip = null;
218
            eip = new ParseError(ex.getSystemId(),ex.getLineNumber(),ex.getColumnNumber(),"",errorString.toString());
219
        
220

    
221
            // put it in the Hashtable.
222
            errorNodes.addElement(eip);
223
        }
224
        
225
    }
226
    
227
    /**
228
     * The ParseError class wraps up all the error info from
229
     * the ErrorStorer's error method.
230
     *
231
     * @see ErrorStorer
232
     */
233
    class ParseError extends Object {
234

    
235
        //
236
        // Data
237
        //
238

    
239
        String fileName;
240
        int lineNo;
241
        int charOffset;
242
        Object key;
243
        String msg;
244

    
245
        /**
246
         * Constructor
247
         */
248
        public ParseError(String fileName, int lineNo, int charOffset,
249
                           Object key, 
250
                           String msg)
251
        {
252
            this. fileName=fileName;
253
            this. lineNo=lineNo;
254
            this. charOffset=charOffset;
255
            this. key=key;
256
            this. msg=msg;
257
        }
258

    
259
        //
260
        // Getters...
261
        //
262
        public String getFileName() { return fileName; }
263
        public int getLineNo() { return lineNo; }
264
        public int getCharOffset() { return charOffset;}
265
        public Object getKey() { return key; }
266
        public String getMsg() { return msg; }
267
        public void setMsg(String s) { msg = s; }
268
    }
269
              
270
              
271
}
(13-13/28)