Skip to main content

This CGIT instance is deprecated, and repositories have been moved to Gitlab or Github. See the repository descriptions for specific locations.

summaryrefslogtreecommitdiffstats
blob: acce7775a6aae908f3accbd64892c85249b0d7d0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
/*******************************************************************************
 * Copyright (c) 2001, 2005 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/

package org.eclipse.wst.xml.core.internal.validation;

import java.io.InputStream;
import java.io.Reader;
import java.net.URL;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;

import org.eclipse.wst.common.uriresolver.internal.provisional.URIResolver;
import org.eclipse.wst.common.uriresolver.internal.provisional.URIResolverPlugin;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.ext.LexicalHandler;

/**
 * A helper class for the XML validator.
 * 
 * @author Craig Salter, IBM
 * @author Lawrence Mandel, IBM
 */
public class ValidatorHelper
{                           
  public List namespaceURIList = new Vector();
  public boolean isGrammarEncountered = false;    
  public boolean isDTDEncountered = false;
  public boolean isNamespaceEncountered = false;
  public String schemaLocationString = ""; //$NON-NLS-1$
  public int numDTDElements = 0;

  /**
   * Constructor.
   */
  public ValidatorHelper()
  {
  }
 
  /**
   * Create an XML Reader.
   * 
   * @return An XML Reader if one can be created or null.
   * @throws Exception
   */
  protected XMLReader createXMLReader(String uri) throws Exception
  {     
    XMLReader reader = null;
    
    reader = new org.apache.xerces.parsers.SAXParser();     
    reader.setFeature("http://apache.org/xml/features/continue-after-fatal-error", false); //$NON-NLS-1$
    reader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); //$NON-NLS-1$
    reader.setFeature("http://xml.org/sax/features/namespaces", false); //$NON-NLS-1$
    reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); //$NON-NLS-1$
    reader.setContentHandler(new MyContentHandler(uri));
    reader.setErrorHandler(new InternalErrorHandler()); 

    LexicalHandler lexicalHandler = new LexicalHandler()
    {      
      public void startDTD (String name, String publicId, String systemId)
      {
        isGrammarEncountered = true;   
        isDTDEncountered = true;
      }

      public void endDTD() throws SAXException
      {
      }

      public void startEntity(String name) throws SAXException
      {
      }

      public void endEntity(String name) throws SAXException
      {
      }

      public void startCDATA() throws SAXException
      {
      }

      public void endCDATA() throws SAXException
      {
      }
 
      public void comment (char ch[], int start, int length) throws SAXException
      {
      }
    };
    reader.setProperty("http://xml.org/sax/properties/lexical-handler", lexicalHandler); //$NON-NLS-1$
    
    return reader;
  }  

  /**
   * An error handler to suppress error and warning information.
   */
  private class InternalErrorHandler implements org.xml.sax.ErrorHandler
  {
    public void error(SAXParseException exception) throws SAXException
    {
    }

    public void fatalError(SAXParseException exception) throws SAXException
    {
    }

    public void warning(SAXParseException exception) throws SAXException
    {
    }
  }

 
  /**
   * Figures out the information needed for validation.
   * 
   * @param uri The uri of the file to validate.
   * @param uriResolver A helper to resolve locations.
   */
  public void computeValidationInformation(String uri, Reader characterStream, URIResolver uriResolver)
  {
    try
    {
      XMLReader reader = createXMLReader(uri);  
      InputSource inputSource = new InputSource(uri);
      inputSource.setCharacterStream(characterStream);
      reader.parse(inputSource);
    }
    catch (Exception e)
    {     
      //System.out.println(e);
    }
  }
  
 

  /**
   * Handle the content while parsing the file.
   */
  class MyContentHandler extends org.xml.sax.helpers.DefaultHandler
  {      
    /* (non-Javadoc)
     * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException)
     */
    boolean isRootElement = true;
    String baseURI;
    
    MyContentHandler(String uri)
    {
      this.baseURI = uri;  
    }
    
    public void error(SAXParseException e) throws SAXException
    {
    }
    /* (non-Javadoc)
     * @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException)
     */
    public void fatalError(SAXParseException e) throws SAXException
    {
    }
    /* (non-Javadoc)
     * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException)
     */
    public void warning(SAXParseException e) throws SAXException
    {
    }
    public String getPrefix(String name)
    {
      String prefix = null;
      int index = name.indexOf(":"); //$NON-NLS-1$
      if (index != -1)
      {
        prefix = name.substring(0, index);
      }
      return prefix;
    }    
        
    public String getUnprefixedName(String name)
    {
      int index = name.indexOf(":"); //$NON-NLS-1$
      if (index != -1)
      {
        name = name.substring(index + 1);
      }
      return name;
    }
    
    public String getPrefixedName(String prefix, String localName)
    {
      return prefix != null && prefix.length() > 0 ? prefix + ":" + localName : localName;      //$NON-NLS-1$
    }

    public void startElement(String namespaceURI, String localName, String rawName, Attributes atts)
    {      
      //String explicitLocation = null;
      if (isRootElement)
      {  
        
        isRootElement = false;  
        int nAtts = atts.getLength();    
        String schemaInstancePrefix = null;
        for (int i =0; i < nAtts; i++)
        {              
          String attributeName = atts.getQName(i);       
          if (attributeName.equals("xmlns") || attributeName.startsWith("xmlns:")) //$NON-NLS-1$ //$NON-NLS-2$
          {                                         
            isNamespaceEncountered = true;    
            String value = atts.getValue(i);                 
            if (value.startsWith("http://www.w3.org/") && value.endsWith("/XMLSchema-instance")) //$NON-NLS-1$ //$NON-NLS-2$
            {
              schemaInstancePrefix = attributeName.equals("xmlns") ? "" : getUnprefixedName(attributeName); //$NON-NLS-1$ //$NON-NLS-2$
            }                   
          }                 
        }
        
        String prefix = getPrefix(rawName);
        String rootElementNamespaceDeclarationName = (prefix != null && prefix.length() > 0) ? "xmlns:" + prefix : "xmlns"; //$NON-NLS-1$ //$NON-NLS-2$
        String rootElementNamespace = rootElementNamespaceDeclarationName != null ? atts.getValue(rootElementNamespaceDeclarationName) : null;        
        
        String location = null;
        
        // first we use any 'xsi:schemaLocation' or 'xsi:noNamespaceSchemaLocation' attribute
        // to determine a location
        if (schemaInstancePrefix != null)
        {                     
          location = atts.getValue(getPrefixedName(schemaInstancePrefix, "noNamespaceSchemaLocation")); //$NON-NLS-1$
          if (location == null)
          {            
        	String schemaLoc = atts.getValue(getPrefixedName(schemaInstancePrefix, "schemaLocation"));  //$NON-NLS-1$
            location = getSchemaLocationForNamespace(schemaLoc, rootElementNamespace);
          }  
        }  
        if (rootElementNamespace != null)
        {
          location = URIResolverPlugin.createResolver().resolve(baseURI, rootElementNamespace, location);    
          location = URIResolverPlugin.createResolver().resolvePhysicalLocation(baseURI, rootElementNamespace, location);                                          
        }           
        
        if (location != null)
        {  
          InputStream is = null;
          try
          {
            URL url = new URL(location);
            is = url.openStream();
            isGrammarEncountered = true;
          }
          catch(Exception e)
          {
        	// Do nothing.
          }
          finally
          {
        	if(is != null)
        	{
        	  try
        	  {
        	    is.close();
        	  }
        	  catch(Exception e)
        	  {
        		// Do nothing.
        	  }
        	}
          }
        }        
      }
    }     
    /* (non-Javadoc)
     * @see org.xml.sax.ext.DeclHandler#elementDecl(java.lang.String, java.lang.String)
     */
    public void elementDecl(String name, String model) 
    {
      numDTDElements++;
    }
    
    // The xsiSchemaLocationValue is a list of namespace/location pairs that are separated by whitespace 
    // this method walks the list of pairs looking for the specified namespace and returns the associated
    // location.
    //   
    protected String getSchemaLocationForNamespace(String xsiSchemaLocationValue, String namespace)
    {      
      String result = null;
      if (xsiSchemaLocationValue != null && namespace != null)
      {
        
        StringTokenizer st = new StringTokenizer(xsiSchemaLocationValue);
        while(st.hasMoreTokens())
        {
          if(st.nextToken().equals(namespace))
          {
            if(st.hasMoreTokens())
            {
              result = st.nextToken();
            }
          }
          else
          {
            if(st.hasMoreTokens())
            {
              st.nextToken();
            }
          }
        }
      }
      return result;
    }         
  }   
       
  
  /**
   * Replace all instances in the string of the old pattern with the new pattern.
   * 
   * @param string The string to replace the patterns in.
   * @param oldPattern The old pattern to replace.
   * @param newPattern The pattern used for replacement.
   * @return The modified string with all occurrances of oldPattern replaced by new Pattern.
   */
  protected static String replace(String string, String oldPattern, String newPattern)
  {     
    int index = 0;
    while (index != -1)
    {
      index = string.indexOf(oldPattern, index);
      if (index != -1)
      {
        string = string.substring(0, index) + newPattern + string.substring(index + oldPattern.length());
        index = index + oldPattern.length();
      }
    }
    return string;
  }
}

Back to the top