msv-2009.1/0000755000175000017500000000000011622453141012617 5ustar giovannigiovannimsv-2009.1/testharness/0000755000175000017500000000000011622453066015170 5ustar giovannigiovannimsv-2009.1/testharness/pom.xml0000644000175000017500000000232211213776216016505 0ustar giovannigiovanni 4.0.0 net.java.dev.msv msv-testharness 2009.1 MSV Test Harness net.java.dev.msv msv-parent 2009.1 ../parent/pom.xml scm:svn:http://msv.dev.java.net/svn/msv/tags/msv-2009.1/testharness scm:svn:https://msv.dev.java.net/svn/msv/tags/msv-2009.1/testharness xerces xercesImpl junit junit test org.apache.ant ant msv-2009.1/testharness/build.xml0000644000175000017500000000073510470130726017011 0ustar giovannigiovanni msv-2009.1/testharness/examples/0000755000175000017500000000000011622453066017006 5ustar giovannigiovannimsv-2009.1/testharness/examples/example.rts0000644000175000017500000000360007327417373021202 0ustar giovannigiovanni
Sun Microsystems Sample test suite to test the harness code Kohsuke KAWAGUCHI $Id: example.rts 954 2001-07-25 01:20:59Z Bear $
Does the processor support W3C XML Schema as a datatype library?
5 -52 abc
msv-2009.1/testharness/doc/0000755000175000017500000000000011622453066015735 5ustar giovannigiovannimsv-2009.1/testharness/doc/testSuite.rng0000644000175000017500000001011207365140104020424 0ustar giovannigiovanni ok ng [-A-Za-z0-9:@&=+$,_.!~*'()]+ msv-2009.1/testharness/doc/BSD License.txt0000644000175000017500000000274507327415040020456 0ustar giovannigiovanniCopyright (c) 2001, Sun Microsystems, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Sun Microsystems, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. msv-2009.1/testharness/doc/readme.txt0000644000175000017500000000435707331355534017747 0ustar giovannigiovanni====================================================================== README FILE FOR RELAX NG CONFORMANCE TEST HARNESS FOR JAVA Copyright (c) Sun Microsystems, 2001 Document by Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) $Revision: 987 $ ====================================================================== RELAX NG Conformance Test Harness for Java is an Open-source Java framework to test the conformance of RELAX NG processors. ---------------------------------------------------------------------- OVERVIEW ---------------------------------------------------------------------- This framework parses the test suite files and then use JUnit to test RELAX NG processor. So first you need a test suite file. See the examples folder of the distribution and "testSuite.rng" file for how to write a test suite file. Then, you need a RELAX NG processor and a driver implementation for that processor. The driver impl for Sun Multi-Schema Validator is included as "msvDriver.jar" in the distribution. See javadoc for how to implement a driver for arbitrary RELAX NG processors. To run a test, enter the following command: $ java -jar rngtsth.jar ... For example, to test the conformance of MSV with foo.rts and bar.rts, $ java -jar rngtsth.jar jing.IValidatorImpl foo.rts bar.rts Your classpath must include junit.jar, msv.jar and msvDriver.jar. ---------------------------------------------------------------------- WRITING AN ADAPTOR ---------------------------------------------------------------------- This framework provides the core functionality to parse test suite files and perform tests by them. However, to use this framework with your own RELAX NG processor, you need to write an "driver", which bridges the framework and the processor. To implement a driver, you need to write two classes that implements the org.relaxng.testharness.validator.IValidator interface and the org.relaxng.testharness.validator.ISchema interface. See msvDriver-src.zip for an example. It should be easy if the processor supports SAX or DOM based input. ====================================================================== END OF README msv-2009.1/testharness/MANIFEST.MF0000644000175000017500000000016607327415311016623 0ustar giovannigiovanniManifest-Version: 1.0 Main-Class: org.relaxng.testharness.junit.TestRunner Created-By: 1.2.2 (Sun Microsystems Inc.) msv-2009.1/testharness/src/0000755000175000017500000000000011622453066015757 5ustar giovannigiovannimsv-2009.1/testharness/src/SAXONLiaison.java0000644000175000017500000000726611156723336021046 0ustar giovannigiovanni/* * @(#)$Id: SAXONLiaison.java 1741 2009-03-14 12:45:18Z bimargulies $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ import javax.xml.transform.*; import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamResult; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; /** * XSLTLiaison implementation for SAXON. * * This doesn't use Saxon any longer. It uses the JDK TraX. * *

* This class */ public class SAXONLiaison implements org.apache.tools.ant.taskdefs.XSLTLiaison { /** The trax TransformerFactory */ private TransformerFactory tfactory = null; /** stylesheet stream, close it asap */ private FileInputStream xslStream = null; /** Stylesheet template */ private Templates templates = null; /** transformer */ private Transformer transformer = null; public SAXONLiaison() throws Exception { tfactory = TransformerFactory.newInstance(); } //------------------- IMPORTANT // 1) Don't use the StreamSource(File) ctor. It won't work with // xalan prior to 2.2 because of systemid bugs. // 2) Use a stream so that you can close it yourself quickly // and avoid keeping the handle until the object is garbaged. // (always keep control), otherwise you won't be able to delete // the file quickly on windows. // 3) Always set the systemid to the source for imports, includes... // in xsl and xml... public void setStylesheet(File stylesheet) throws Exception { xslStream = new FileInputStream(stylesheet); StreamSource src = new StreamSource(xslStream); src.setSystemId(getSystemId(stylesheet)); templates = tfactory.newTemplates(src); transformer = templates.newTransformer(); } public void transform(File infile, File outfile) throws Exception { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(infile); fos = new FileOutputStream(outfile); StreamSource src = new StreamSource(fis); src.setSystemId(getSystemId(infile)); StreamResult res = new StreamResult(fos); // not sure what could be the need of this... res.setSystemId(getSystemId(outfile)); transformer.transform(src, res); } finally { // make sure to close all handles, otherwise the garbage // collector will close them...whenever possible and // Windows may complain about not being able to delete files. try { if (xslStream != null){ xslStream.close(); } } catch (IOException ignored){} try { if (fis != null){ fis.close(); } } catch (IOException ignored){} try { if (fos != null){ fos.close(); } } catch (IOException ignored){} } } // make sure that the systemid is made of '/' and not '\' otherwise // crimson will complain that it cannot resolve relative entities // because it grabs the base uri via lastIndexOf('/') without // making sure it is really a /'ed path protected String getSystemId(File file){ String path = file.getAbsolutePath(); path = path.replace('\\','/'); return FILE_PROTOCOL_PREFIX + path; } public void addParam(String name, String value){ transformer.setParameter(name, value); } }msv-2009.1/testharness/src/PathExtractor.java0000644000175000017500000000111307410436423021404 0ustar giovannigiovanniimport java.io.File; /** * Extracts the path part from "file://" URL. * * For example, extract("file://home/abc/def/ghi.xml") * returns "/home/abc/def/ghi" */ public class PathExtractor { public static String extract( String uri ) { String path = uri.substring(5); // file: int idx = path.lastIndexOf('.'); path = path.substring(0,idx); if (File.separatorChar == '\\') { path = path.replace('/', '\\'); while(path.charAt(0)=='\\') path = path.substring(1); } else { while(path.startsWith("//")) path = path.substring(1); } return path; } }msv-2009.1/pom.xml0000644000175000017500000002251611213776216014151 0ustar giovannigiovanni 4.0.0 net.java.dev.msv msv 2009.1 msv http://msv.java.net pom scm:svn:http://msv.dev.java.net/svn/msv/tags/msv-2009.1 scm:svn:https://msv.dev.java.net/svn/msv/tags/msv-2009.1 2.0.8 false BSD repo parent xsdlib testharness msv generator rngconverter deploy deploy org.apache.maven.plugins maven-source-plugin 2.0.4 attach-sources jar org.apache.maven.plugins maven-javadoc-plugin attach-javadocs jar install org.codehaus.mojo build-helper-maven-plugin 1.2 org.apache.felix maven-bundle-plugin 1.4.3 org.apache.maven.plugins maven-release-plugin 2.0-beta-9 https://msv.dev.java.net/svn/msv/tags false clean install deploy -Pdeploy true org.apache.maven.plugins maven-javadoc-plugin 2.5 true 1.5 true MSV 1.5 UTF-8 org.apache.maven.plugins maven-surefire-plugin 2.4.3 org.apache.maven.plugins maven-compiler-plugin 2.0.2 1.5 1.5 256M ${compiler.fork} org.apache.maven.plugins maven-antrun-plugin 1.2 org.apache.maven.plugins maven-jar-plugin 2.2 org.apache.maven.plugins maven-resources-plugin 2.2 org.apache.maven.plugins maven-assembly-plugin 2.2-beta-2 org.apache.maven.plugins maven-dependency-plugin 2.0 org.apache.maven.plugins maven-eclipse-plugin 2.5.1 org.jvnet.wagon-svn wagon-svn 1.8 org.apache.maven.plugins maven-project-info-reports-plugin org.apache.maven.plugins maven-javadoc-plugin 2.2 true true maven2-repository.dev.java.net Java.net Repository for Maven http://download.java.net/maven/2/ false java.net-maven2-repository java-net:/maven2-repository/trunk/repository/ msv-2009.1/www/0000755000175000017500000000000011622453065013450 5ustar giovannigiovannimsv-2009.1/www/alm-process/0000755000175000017500000000000011622453065015675 5ustar giovannigiovannimsv-2009.1/www/alm-process/snippets/0000755000175000017500000000000011622453065017542 5ustar giovannigiovannimsv-2009.1/www/alm-process/snippets/page.xml0000644000175000017500000000066511156245242021205 0ustar giovannigiovanni index.htmlSubprojects msv-2009.1/www/xss.html0000644000175000017500000000017007676612160015160 0ustar giovannigiovanni XSS vulnerability test. msv-2009.1/www/index.html0000644000175000017500000000235410736744756015470 0ustar giovannigiovanni

The Sun Multi-Schema XML Validator (MSV) is a Java technology tool to validate XML documents against several kinds of XML schemata. It supports RELAX NG, RELAX Namespace, RELAX Core, TREX, XML DTDs, and a subset of XML Schema Part 1. This latest (version 1.2) release includes several bug fixes and adds better conformance to RELAX NG/W3C XML standards and JAXP masquerading. This download package includes binaries, source code, and detailed documentation. The project is licensed under the BSD license.

This tool is:

See the included commandline.html file for details on how to use MSV from the command line. See the included developer.html file for details on how to use it as a library.

TODO: add descriptions for other four tools

Downloads

Nightly builds
MSV is usually stable enough that you can safely use any nighlt build.
msv-2009.1/parent/0000755000175000017500000000000011622453066014116 5ustar giovannigiovannimsv-2009.1/parent/pom.xml0000644000175000017500000002055511213776216015443 0ustar giovannigiovanni net.java.dev.msv msv 2009.1 ../pom.xml 4.0.0 net.java.dev.msv msv-parent 2009.1 MSV Parent http://msv.java.net pom scm:svn:http://msv.dev.java.net/svn/msv/tags/msv-2009.1/parent scm:svn:https://msv.dev.java.net/svn/msv/tags/msv-2009.1/parent once brief false -ea ${basedir}/target/classes true ${basedir}/src ${basedir}/test src **/*.java **/*.properties resource **/* test **/*.java org.apache.maven.plugins maven-eclipse-plugin ${eclipse.outputDirectory} org.apache.maven.plugins maven-surefire-plugin **/*Test.java **/*TestCase.java **/*TestCases.java **/*$* ${surefire.format} ${surefire.usefile} ${surefire.fork.mode} false ${surefire.fork.vmargs} java.awt.headless ${java.awt.headless} surefire.fork.vmargs ${surefire.fork.vmargs} install maven2-repository.dev.java.net Java.net Repository for Maven http://download.java.net/maven/2/ junit junit 4.4 test xml-resolver xml-resolver 1.2 xerces xercesImpl 2.9.1 xalan xalan 2.7.1 crimson crimson 1.1.3 isorelax isorelax 20030108 relaxngDatatype relaxngDatatype 20020414 jdom jdom 1.0 net.sf.saxon saxon 8.7 org.apache.ant ant 1.7.1 org.apache.maven.plugins maven-project-info-reports-plugin org.apache.maven.plugins maven-surefire-report-plugin org.apache.maven.plugins maven-javadoc-plugin fastinstall true sourcecheck true org.apache.maven.plugins maven-compiler-plugin true ${compile.flags} set.eclipse.output ${basedir}/eclipse-classes msv-2009.1/tahiti/0000755000175000017500000000000011622453065014106 5ustar giovannigiovannimsv-2009.1/tahiti/build.xml0000644000175000017500000000725307365417216015745 0ustar giovannigiovanni
Schmit: SCHema In Transformation
By Kohsuke Kawaguchi
$Id: readme.html 1551 2003-04-30 00:03:46Z kk122374 $

Table of Contents

  1. Introduction
  2. Getting Started
  3. XML Schema
  4. Reference
  5. Contact

Introduction

Schmit is an XSLT extension that allows you to access schema annotation information from within the stylesheet. This functionality can be used to write more generic stylesheet that isn't tied to any particular XML vocabulary. The current release works for Apache Xalan.

Getting Started

To use Schmit, you first prepare a schema that validates the input of the transformation. For example, if you are converting a DocBook to XHTML, you need a schema for DocBook. Schmit supports
RELAX NG and W3C XML Schema.

Assume you have the following schema:


<?xml version="1.0"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0"
         xmlns:a="test">
  <start>
    <element name="root">
      <element name="child" a:note="1st">
        <empty/>
      </element>
      <element name="child" a:note="2nd">
        <empty/>
      </element>
    </element>
  </start>
</grammar>
</grammar>

Note that this schema contains attributes from namespace "test". Schmit treats all the non-RELAX NG namespaces in a grammar as "annotations". For XML Schema, elements and attributes inside <xs:annotation> are considered as "annotations".

Inside your stylesheet, you first declare Schmit as an XSLT extension:


<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
	xmlns:sc="xalan://com.sun.msv.schmit.XalanExtension"
	extension-element-prefixes="sc">

As usual, you can use any prefix instead of "sc". But in this document, we assume that the prefix "sc" is used for the extension declaration.

Next, you need to tell the processor to apply the above schema to the input. This will be done by using the sc:useSchema extension element. This can be done at the very beginning of the stylesheet:


<xsl:template match="/">
  <sc:useSchema href="myschema.rng" />
  ...
</xsl:template>

The href attribute points to the location of the schema. When this instruction is executed, the schema is loaded.

Once you load a schema, you can use another extension function sc:annotation to obtain the annotation.


<xsl:template match="/">
  <result>
    <sc:useSchema href="myschema.rng" />
    <xsl:for-each select="root/child">
      <note>
        <xsl:value-of select="sc:annotation(.)/@a:note" />
      </note>
    </xsl:for-each>
  </result>
</xsl:template>

The sc:annotation function takes a node set, and returns a node set that contains all the annotation elemetns/attributes attached to it. In the above example, we are retriving the value of the a:note attribute attached to each child element.

If an input looks like:


<?xml version="1.0"?>
<root>
  <child/>
  <child/>
</root>

Then the result will look like:


<?xml version="1.0"?>
<result>
	<note>1st</note>
	<note>2nd</note>
</result>

The use of sc:annotation is not limited to xsl:value-of; it can be used anywhere where you can write XPath functions. For example, you can write a template matching rule like this:


<xsl:template match="*[sc:annotation(.)/@a:visible]">

which will match any element whose definition have a:visible attribute, or you can write:


<xsl:copy-of select="sc:annotation(.)/a:htmldoc/*" />

which copies HTML documentation of the current element (assuming that you've written one inside schema) into the current location.

XML Schema

When you choose W3C XML Schemas as your schema language, you need to use the sc:annotation like this:


<xsl:copy-of select="sc:annotation(.)/xs:appinfo/foo:myAnnotation" />

In other words, you can assume that this method returns xs:annotation element itself --- therefore you need to be prepared to see elements like xs:appinfo or xs:documentation before you get to your own annotation.

Reference

Schmit has one extension element and one extension function. This section defines the syntax of those extensions.

useSchema extension element


<sc:useSchema href="[attribute value template]" />

Loads a schema from the specified location and annotate the current input document (the document that includes the context node) with it.

The href attribute takes an attribute value template, meaning that you can write things like this:


<sc:useSchema href="foo.rng" />
<sc:useSchema href="${myVariable}" />

annotation extension function


sc:annotation()
sc:annotation([node-set])

Looks up the annotation attached to the specified nodes, and returns them as a node set. sc:annotation() is equivalent of sc:annotation(.).

Contact

If you have any comment or suggestion to this technology, please feel free to drop a note to Kohsuke Kawaguchi.

msv-2009.1/schmit/MANIFEST.MF0000644000175000017500000000027107660274614015555 0ustar giovannigiovanniManifest-Version: 1.0 Created-By: 1.2.2 (Sun Microsystems Inc.) Class-Path: msv.jar xercesImpl.jar isorelax.jar relaxngDatatype.jar xsdlib.jar Main-Class: org.apache.xalan.xslt.Process msv-2009.1/schmit/src/0000755000175000017500000000000011622453066014703 5ustar giovannigiovannimsv-2009.1/schmit/src/com/0000755000175000017500000000000011622453066015461 5ustar giovannigiovannimsv-2009.1/schmit/src/com/sun/0000755000175000017500000000000011622453066016266 5ustar giovannigiovannimsv-2009.1/schmit/src/com/sun/msv/0000755000175000017500000000000011622453066017073 5ustar giovannigiovannimsv-2009.1/schmit/src/com/sun/msv/schmit/0000755000175000017500000000000011622453066020362 5ustar giovannigiovannimsv-2009.1/schmit/src/com/sun/msv/schmit/DOMScanner.java0000644000175000017500000001214707635414443023170 0ustar giovannigiovanni/* * @(#)$Id: DOMScanner.java 1531 2003-03-17 18:51:15Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.schmit; import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.ProcessingInstruction; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * Visits a W3C DOM tree and generates SAX2 events from it. * * @author
  • Kohsuke Kawaguchi, Sun Microsystems, Inc.
* @version $Revision: 1531 $ $Date: 2003-03-17 19:51:15 +0100(lun, 17 mar 2003) $ */ public class DOMScanner { /** reference to the current node being scanned - used for determining * location info for validation events */ private Node currentNode = null; /** To save memory, only one instance of AttributesImpl will be used. */ private final AttributesImpl atts = new AttributesImpl(); /** This handler will receive SAX2 events. */ private ContentHandler receiver=null; public DOMScanner() { } /** * A dummy locator that doesn't provide any information - required * by SAX, but not actually used for JAXB's location requirements. */ private static Locator dummyLocator = new Locator() { public int getLineNumber() { return -1; } public int getColumnNumber() { return -1; } public String getSystemId() { return null; } public String getPublicId() { return null; } }; /** * Parses a subtree starting from the element e and * reports SAX2 events to the specified handler. */ public void parse( Element e, ContentHandler handler ) throws SAXException { // it might be better to set receiver at the constructor. receiver = handler; setCurrentLocation( (Node)e ); handler.startDocument(); handler.setDocumentLocator(dummyLocator); visit(e); setCurrentLocation( (Node)e ); handler.endDocument(); } /** * Visits an element and its subtree. */ public void visit( Element e ) throws SAXException { setCurrentLocation( e ); final NamedNodeMap attributes = e.getAttributes(); atts.clear(); int len = attributes.getLength(); for( int i=len-1; i>=0; i-- ) { Attr a = (Attr)attributes.item(i); String name = a.getName(); // start namespace binding if(name.equals("xmlns")) { receiver.startPrefixMapping( "", a.getValue() ); continue; } if(name.startsWith("xmlns:")) { receiver.startPrefixMapping( a.getLocalName(), a.getValue() ); continue; } String uri = a.getNamespaceURI(); if(uri==null) uri=""; // add other attributes to the attribute list // that we will pass to the ContentHandler atts.addAttribute( uri, a.getLocalName(), a.getName(), "CDATA", a.getValue()); } String uri = e.getNamespaceURI(); if(uri==null) uri=""; String local = e.getLocalName(); String qname = e.getTagName(); receiver.startElement( uri, local, qname, atts ); // visit its children for( Node child = e.getFirstChild(); child!=null; child=child.getNextSibling() ) visit(child); setCurrentLocation( e ); receiver.endElement( uri, local, qname ); // call the endPrefixMapping method for( int i=len-1; i>=0; i-- ) { Attr a = (Attr)attributes.item(i); String name = a.getName(); if(name.startsWith("xmlns:")) receiver.endPrefixMapping(a.getLocalName()); } } private void visit( Node n ) throws SAXException { setCurrentLocation( n ); // if a case statement gets too big, it should be made into a separate method. switch(n.getNodeType()) { case Node.CDATA_SECTION_NODE: case Node.TEXT_NODE: String value = n.getNodeValue(); receiver.characters( value.toCharArray(), 0, value.length() ); break; case Node.ELEMENT_NODE: visit( (Element)n ); break; case Node.ENTITY_REFERENCE_NODE: receiver.skippedEntity(n.getNodeName()); break; case Node.PROCESSING_INSTRUCTION_NODE: ProcessingInstruction pi = (ProcessingInstruction)n; receiver.processingInstruction(pi.getTarget(),pi.getData()); break; } } private void setCurrentLocation( Node currNode ) { currentNode = currNode; } public Node getCurrentLocation() { return currentNode; } } msv-2009.1/schmit/src/com/sun/msv/schmit/reader/0000755000175000017500000000000011622453066021624 5ustar giovannigiovannimsv-2009.1/schmit/src/com/sun/msv/schmit/reader/AnnotationParent.java0000644000175000017500000000117507634164316025764 0ustar giovannigiovanni/* * @(#)$Id: AnnotationParent.java 1523 2003-03-13 20:23:42Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.schmit.reader; import org.w3c.dom.Node; /** * Receives parsed annotations. * * @author * Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) */ public interface AnnotationParent { /** * Receives parsed annotations. * * @param annotation * Either Element or Attr. */ void onEndAnnotation( Node annotation ); } msv-2009.1/schmit/src/com/sun/msv/schmit/reader/AnnotationState.java0000644000175000017500000000467607635414443025624 0ustar giovannigiovanni/* * @(#)$Id: AnnotationState.java 1531 2003-03-17 18:51:15Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.schmit.reader; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.Attributes; import com.sun.msv.reader.State; /** * Builds DOM node from pseudo-SAX events and return it to the parent state. * * @author * Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) */ public class AnnotationState extends State { // the parent state receives startElement event for this state. // so we have to start from one, rather than zero. private int depth=1; private final Document document; private Element root; private Node currentParent; public AnnotationState( Document _document ) { this.document = _document; } protected void startSelf() { super.startSelf(); currentParent = root = createElement( startTag.namespaceURI, startTag.qName, startTag.attributes ); } public final void startElement(String namespaceURI, String localName, String qName, Attributes atts) { depth++; Element newNode = createElement( namespaceURI, qName, atts ); currentParent.appendChild(newNode); currentParent = newNode; } public final void endElement(String namespaceURI, String localName, String qName) { depth--; if (depth == 0) { ((AnnotationParent)parentState).onEndAnnotation(root); reader.popState(); } currentParent = currentParent.getParentNode(); } public final void endDocument() { throw new InternalError(); // shall never be called } public void characters(char[] buffer, int from, int len) { currentParent.appendChild(document.createTextNode(new String(buffer,from,len))); } /** * Creates a new DOM element. */ private Element createElement(String namespaceURI, String qname, Attributes attributes) { Element e = document.createElementNS(namespaceURI,qname); for( int i=0; i * Santiago told me that this area of Xalan is changing rapidly, * so I put this "dangerous" code into a separate class to isolate it * and make it pluggable. * * @author * Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) */ public abstract class XalanNodeAssociationManager { public abstract void put( Node key, Object value ); public abstract Object get( Node key ); /** * Creates a new instance. */ public static final XalanNodeAssociationManager createInstance() { String className = null; try { className = System.getProperty(XalanNodeAssociationManager.class.getName()+".implementation"); } catch( SecurityException e ) { // a security manager might reject this call } if(className!=null) { // use specified one. try { return (XalanNodeAssociationManager)Class.forName(className).newInstance(); } catch( Exception e ) { e.printStackTrace(); return null; } } else { // guess from the version number of Xalan int ver = XSLProcessorVersion.VERSION*100 + XSLProcessorVersion.RELEASE; if( Debug.debug ) System.err.println("Xalan version: "+ver); if( ver>202 ) return new XalanNodeAssociationManager_2_5(); else return new XalanNodeAssociationManager_2_0(); } } } msv-2009.1/schmit/src/com/sun/msv/schmit/XalanNodeAssociationManager_2_0.java0000644000175000017500000000151307660274526027237 0ustar giovannigiovanni/* * @(#)$Id: XalanNodeAssociationManager_2_0.java 1554 2003-05-13 23:01:42Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.schmit; import java.util.HashMap; import java.util.Map; import org.w3c.dom.Node; /** * Implementation for older version of Xalan (2.0-2.1?) * * @author * Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) */ final class XalanNodeAssociationManager_2_0 extends XalanNodeAssociationManager { /** Actual data store. */ private final Map store = new HashMap(); public Object get(Node key) { return store.get( key ); } public void put(Node key, Object value) { store.put( key, value ); } } msv-2009.1/schmit/src/com/sun/msv/schmit/XalanExtension.java0000644000175000017500000001264707660274526024210 0ustar giovannigiovanni/* * @(#)$Id: XalanExtension.java 1554 2003-05-13 23:01:42Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.schmit; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.TransformerException; import org.apache.xalan.extensions.ExpressionContext; import org.apache.xalan.extensions.XSLProcessorContext; import org.apache.xalan.templates.ElemExtensionCall; import org.apache.xpath.NodeSet; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.sun.msv.driver.textui.DebugController; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.Grammar; import com.sun.msv.reader.GrammarReader; import com.sun.msv.schmit.grammar.AnnotatedPattern; import com.sun.msv.schmit.reader.relaxng.SchmitRELAXNGReader; /** * Extension element/function definitions for Xalan. * * @author * Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) */ public class XalanExtension { /** * Stores {@link com.sun.msv.schmit.grammar.AnnotatedElementPattern} * for each Element node. */ private final XalanNodeAssociationManager psvi = XalanNodeAssociationManager.createInstance(); /** * Stores {@link PSVIRecorder} for each document. */ private final XalanNodeAssociationManager schema = XalanNodeAssociationManager.createInstance(); /** Used as a node factory. */ private final Document document; public XalanExtension(Document _document) { this.document = _document; } public XalanExtension() throws ParserConfigurationException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); this.document = dbf.newDocumentBuilder().newDocument(); } /** * useSchema extension element that * associates a schema to the input. */ public void useSchema( XSLProcessorContext context, ElemExtensionCall call ) throws TransformerException { try { // obtain the schema location Node n = context.getContextNode(); String href = call.getAttribute("href", n, context.getTransformer()); // determine the root node Element root = getFirstElement( // workaround a bug in Xalan. The getOwnerDocument method does't work correctly // if the node itself is a document. n.getNodeType()==Node.DOCUMENT_NODE?(Document)n:n.getOwnerDocument()); try { href = new URL( new URL(call.getBaseIdentifier()), href ).toExternalForm(); } catch( MalformedURLException e ) { ; // failed to absolutize } // parse the grammar SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); GrammarReader reader = new SchmitRELAXNGReader( new DebugController(false), spf, new ExpressionPool() ); reader.parse(href); Grammar grammar = reader.getResultAsGrammar(); // // remember this association // schema.put( context.getSourceTree(), new PSVIRecorder(grammar) ); // run PSVI annotation new PSVIRecorder(grammar,psvi).annotate( // DTM node proxy doesn't support the getDocumentElement method. root ); } catch( RuntimeException re ) { re.printStackTrace(); throw re; } } /** * Equivalent of the getDocumentElement method. */ private Element getFirstElement( Document document ) { for( Node n = document.getFirstChild(); n!=null; n=n.getNextSibling() ) if( n.getNodeType()==Node.ELEMENT_NODE ) return (Element)n; return null; } public NodeSet annotation( ExpressionContext context ) throws ParserConfigurationException { Element e = document.createElement("dummy"); buildResult( context.getContextNode(), e ); return new NodeSet(e); } public NodeSet annotation( ExpressionContext context, NodeList list ) throws ParserConfigurationException { // put all the nodes under a dummy element so that the stylesheets // can be written as "schmit:annotation(.)/@test" etc. Element e = document.createElement("dummy"); for( int i=0; i 4.0.0 com.sun.msv.datatype.xsd xsdlib 20060614 XML Schema datatypes library Users List users-subscribe@msv.dev.java.net users-unsubscribe@msv.dev.java.net https://msv.dev.java.net/servlets/SummarizeList?listName=users kohsuke Kohsuke Kawaguchi kk@kohsuke.org isorelax isorelax 20030108 relaxngDatatype relaxngDatatype 20020411 msv-2009.1/repo/com.sun.msv.datatype.xsd/poms/xsdlib-20060615.pom0000644000175000017500000000211110444303547024242 0ustar giovannigiovanni 4.0.0 com.sun.msv.datatype.xsd xsdlib 20060615 XML Schema datatypes library Users List users-subscribe@msv.dev.java.net users-unsubscribe@msv.dev.java.net https://msv.dev.java.net/servlets/SummarizeList?listName=users kohsuke Kohsuke Kawaguchi kk@kohsuke.org isorelax isorelax 20030108 relaxngDatatype relaxngDatatype 20020414 msv-2009.1/repo/com.sun.msv.datatype.xsd/poms/xsdlib-20060614.pom.md50000644000175000017500000000004010444202334024714 0ustar giovannigiovanni7a8632ae10f4c658819c89ac907dc366msv-2009.1/repo/com.sun.msv.datatype.xsd/poms/xsdlib-20060615.pom.md50000644000175000017500000000004010444303547024725 0ustar giovannigiovanni4869c3eb2664d6e9ddf6932fd0ff4442msv-2009.1/repo/com.sun.msv.datatype.xsd/java-sources/0000755000175000017500000000000011622453161022765 5ustar giovannigiovannimsv-2009.1/repo/com.sun.msv.datatype.xsd/java-sources/xsdlib-20060615-sources.jar.md50000644000175000017500000000004010444303547030013 0ustar giovannigiovanni017baae29a5da3d7629dbfab8e26eea2msv-2009.1/repo/com.sun.msv.datatype.xsd/java-sources/xsdlib-20060614-sources.jar.md50000644000175000017500000000004010444202334030002 0ustar giovannigiovanniceba4e01f60f483ec73dd4581da9bbe6msv-2009.1/repo/com.sun.msv.datatype.xsd/jars/0000755000175000017500000000000011622453161021322 5ustar giovannigiovannimsv-2009.1/repo/com.sun.msv.datatype.xsd/jars/xsdlib-20060614.jar.md50000644000175000017500000000004010444202334024656 0ustar giovannigiovanni51ea0e215bd2c2bc7aa207fb966fe85bmsv-2009.1/repo/com.sun.msv.datatype.xsd/jars/xsdlib-20060615.jar.md50000644000175000017500000000004010444303547024667 0ustar giovannigiovanni83cf797362461f419ffe58d776d34129msv-2009.1/rngconverter/0000755000175000017500000000000011622453070015336 5ustar giovannigiovannimsv-2009.1/rngconverter/pom.xml0000644000175000017500000001052411213776216016663 0ustar giovannigiovanni 4.0.0 net.java.dev.msv msv-rngconverter 2009.1 MSV RNG Converter net.java.dev.msv msv-parent 2009.1 ../parent/pom.xml scm:svn:http://msv.dev.java.net/svn/msv/tags/msv-2009.1/generator scm:svn:https://msv.dev.java.net/svn/msv/tags/msv-2009.1/generator org.apache.maven.plugins maven-jar-plugin true com.sun.msv.writer.relaxng.Driver true com.sun.msv.datatype.xsd xsdlib ${project.version} com.sun.msv.datatype.xsd xsdlib ${project.version} tests test net.java.dev.msv msv-testharness ${project.version} test net.java.dev.msv msv-core ${project.version} net.java.dev.msv msv-core ${project.version} tests test xml-resolver xml-resolver xerces xercesImpl isorelax isorelax relaxngDatatype relaxngDatatype junit junit test msv-2009.1/rngconverter/build.xml0000644000175000017500000000747710470130726017176 0ustar giovannigiovanni version=${DSTAMP} msv-2009.1/rngconverter/test/0000755000175000017500000000000011622453070016315 5ustar giovannigiovannimsv-2009.1/rngconverter/test/RELAXNGConverter.java0000644000175000017500000000022210023127625022142 0ustar giovannigiovannipublic class RELAXNGConverter { public static void main( String[] args ) throws Exception { com.sun.msv.writer.relaxng.Driver.main(args); } } msv-2009.1/rngconverter/test/batch/0000755000175000017500000000000011622453070017376 5ustar giovannigiovannimsv-2009.1/rngconverter/test/batch/writer/0000755000175000017500000000000011622453070020712 5ustar giovannigiovannimsv-2009.1/rngconverter/test/batch/writer/RELAXNGTester.java0000644000175000017500000000272507660506523024063 0ustar giovannigiovanni/* * @(#)$Id: RELAXNGTester.java 1557 2003-05-14 18:39:15Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package batch.writer; import batch.BatchTester; import batch.driver.IValidatorImplForRNG; import batch.model.TestReader; import com.sun.msv.writer.GrammarWriter; /** * tests RELAX NG converter. * * @author Kohsuke KAWAGUCHI */ public class RELAXNGTester extends BatchTester { protected TestReader createReader() { return new TestReader( new TestBuilderImpl(validator, new IValidatorImplForRNG(strict) ) { protected GrammarWriter getWriter() { return new com.sun.msv.writer.relaxng.RELAXNGWriter(); } } ); } public static void main(String[] av) throws Exception { new RELAXNGTester().run(av); } protected void usage() { System.out.println( "usage " + this.getClass().getName() + " (relax|trex|xsd|dtd|rng) [-strict] \n" + " tests RELAX NG converter by\n" + " 1. converting schema files of the specified type into RELAX NG\n" + " 2. then parse it by RELAX NG parser\n" + " 3. then use the test instances to ensure the correctness\n"); } } msv-2009.1/rngconverter/test/batch/writer/TestBuilderImpl.java0000644000175000017500000001052107660506523024635 0ustar giovannigiovannipackage batch.writer; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.util.Set; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.XMLSerializer; import batch.model.ISchema; import batch.model.IValidator; import batch.model.TestBuilder; import com.sun.msv.writer.GrammarWriter; /** * Builds a test suite for schema converter. * * A derived class needs to implement the getWriter method and * the createReader method. The writer is used to convert AGM into * any XML format, then the corresponding reader will be used to * parse it into AGM again. */ public abstract class TestBuilderImpl implements TestBuilder { protected abstract GrammarWriter getWriter(); /* RELAX allows undeclared attributes, but no other schema language does. Therefore, some RELAX test instances which are originally valid can results in an invalid instance. this set contains all such test cases. */ protected static final Set invalidTestCases = new java.util.HashSet(); static { Set s = invalidTestCases; s.add("relax001.v00.xml"); s.add("relax031.v00.xml"); s.add("relax039.v00.xml"); s.add("relax040.v00.xml"); s.add("relax041.v00.xml"); } public TestBuilderImpl(IValidator _firstValidator, IValidator _secondValidator) { this.firstValidator = _firstValidator; this.secondValidator = _secondValidator; } /** Used to parse the source schema language. */ private final IValidator firstValidator; /** Used to parse and validate the converted schema. */ private final IValidator secondValidator; private class SchemaTestCase extends TestCase { public SchemaTestCase(File _src) { super(TestBuilderImpl.getName(_src)); this.src = _src; } private final File src; public ISchema schema; public void runTest() throws Exception { // load grammar ISchema source = firstValidator.parseSchema(src); if (source == null) fail("failed to parse the original grammar"); // unexpected result // then convert it to the target grammar, // and parse it by the target grammar reader parser. GrammarWriter writer = getWriter(); // serialize it into the XML representation ByteArrayOutputStream baos = new ByteArrayOutputStream(); writer.setDocumentHandler(new XMLSerializer(baos, new OutputFormat("xml", null, true))); writer.write(source.asGrammar()); // then parse it again schema = secondValidator.parseSchema(new ByteArrayInputStream(baos.toByteArray())); if (schema == null) fail("conversion failed"); // unexpected result } } private SchemaTestCase current; public Test createCorrectSchemaTest(final File schema) { current = new SchemaTestCase(schema); return current; } public Test createValidDocumentTest(File document) { return createDocumentTest(document, true); } public Test createInvalidDocumentTest(File document) { return createDocumentTest(document, false); } private Test createDocumentTest(final File document, final boolean expectation) { final SchemaTestCase schema = current; return new TestCase(getName(document)) { public void runTest() throws Exception { if (schema.schema == null) // abort. there was an error in the schema return; boolean r = secondValidator.validate(schema.schema, document); if (r == expectation) return; // OK if (expectation) fail("validator failed to accept a valid document"); else fail("validator accepted an invalid document"); } }; } public Test createIncorrectSchemaTest(final File schema) { // incorrect schema is not tested return new TestSuite(); } /** Computes the test name from a file name. */ private static String getName(File f) { return f.getPath(); } } msv-2009.1/rngconverter/test/batch/writer/relaxng/0000755000175000017500000000000011622453070022352 5ustar giovannigiovannimsv-2009.1/rngconverter/test/batch/writer/relaxng/RELAXNGWriterTest.java0000644000175000017500000000207007660506523026362 0ustar giovannigiovanni/* * @(#)$Id: RELAXNGWriterTest.java 1557 2003-05-14 18:39:15Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package batch.writer.relaxng; import junit.framework.TestSuite; import batch.writer.RELAXNGTester; /** * tests the RELAXNGWriter with the multiple test directories. * * for use by automated test by ant. * * @author Kohsuke KAWAGUCHI */ public class RELAXNGWriterTest { public static TestSuite suite() throws Exception { TestSuite s = new TestSuite(); append(s, "RELAXBatchTestDir", "relax"); append(s, "TREXBatchTestDir", "trex"); append(s, "XSDBatchTestDir", "xsd"); append(s, "DTDBatchTestDir", "dtd"); return s; } private static void append(TestSuite s, String propName, String target) throws Exception { s.addTest(new RELAXNGTester().createFromProperty(target, propName)); } } msv-2009.1/rngconverter/doc/0000755000175000017500000000000011622453070016103 5ustar giovannigiovannimsv-2009.1/rngconverter/doc/copyright.txt0000644000175000017500000000534510235774051020667 0ustar giovannigiovanni(See license.txt for the actual license terms) Copyright 2001-@@YEAR@@ Sun Microsystems, Inc. 901 San Antonio Road, Palo Alto, California, 94303, U.S.A. All rights reserved. Sun Microsystems, Inc. has intellectual property rights relating to technology embodied in this product. In particular, and without limitation, these intellectual property rights may include one or more of the U.S. patents listed at http://www.sun.com/patents and one or more additional patents or pending patent applications in the U.S. and other countries. This product is distributed under licenses restricting its use, copying, distribution, and decompilation. No part of this product may be reproduced in any form by any means without prior written authorization of Sun and its licensors, if any. Third party software, including font technology, is copyrighted and licensed from Sun suppliers. Sun, the Sun logo, and Sun Microsystems are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries. This product includes software developed by the Apache Software Foundation (http://www.apache.org/). Federal Acquisitions: Commercial Software - Government Users Subject to Standard License Terms and Conditions. ---------------------------------------------------------------------- Copyright 2001-@@YEAR@@ Sun Microsystems, Inc., 901 San Antonio Road, Palo Alto, Californie 94303 États-Unis. Tous droits réservés. Distribueé par des licences qui en restreignent l'utilisation. Sun Microsystems, Inc. a les droits de propriété intellectuels relatants à la technologie incorporée dans ce produit. En particulier, et sans la limitation, ces droits de propriété intellectuels peuvent inclure un ou plus des brevets américains énumérés à http://www.sun.com/patents et un ou les brevets plus supplémentaires ou les applications de brevet en attente dans les Etats Unis et les autres pays. Ce produit ou document est protégé par un copyright et distribué avec des licences qui en restreignent l'utilisation, la copie, la distribution, et la décompilation. Aucune partie de ce produit ou document ne peut être reproduite sous aucune forme, par quelque moyen que ce soit, sans l'autorisation préalable et écrite de Sun et de ses bailleurs de licence, s'il y en a. Le logiciel détenu par des tiers, et qui comprend la technologie relative aux polices de caractères, est protégé par un copyright et licencié par des fournisseurs de Sun. Sun, le logo Sun, Sun Microsystems et sont des marques de fabrique ou des marques d?pos?es de Sun Microsystems, Inc. aux Etats-Unis et dans d'autres pays. Ce produit inclut le logiciel développé par la base de Apache Software Foundation (http://www.apache.org/). L'accord du gouvernement des États Unis est requis avant l'exportation du produit. msv-2009.1/rngconverter/doc/Apache-LICENSE-1.1.txt0000644000175000017500000000541307307235664021421 0ustar giovannigiovanni/* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * Portions of this software are based upon public domain software * originally written at the National Center for Supercomputing Applications, * University of Illinois, Urbana-Champaign. */ msv-2009.1/rngconverter/doc/license.txt0000644000175000017500000000312211156515606020272 0ustar giovannigiovanniCopyright (c) 2001-@@YEAR@@ Sun Microsystems, Inc. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistribution in binary form must reproduct the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of Sun Microsystems, Inc. or the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. This software is provided "AS IS," without a warranty of any kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. msv-2009.1/rngconverter/doc/README.txt0000644000175000017500000000556010270277621017613 0ustar giovannigiovanni====================================================================== README FILE FOR THE SUN RELAX NG CONVERTER version @@VERSION@@ Copyright (c) Sun Microsystems, 2001-@@YEAR@@ Document written by Kohsuke Kawaguchi (kohsuke.kawaguchi@eng.sun.com) ====================================================================== Sun RELAX NG Converter is a tool to convert schemas written in various schema languages to their equivalent in RELAX NG. It supports schemas written in XML DTD, RELAX Core, RELAX namespace, TREX, W3C XML Schema, and RELAX NG itself. This release includes software developed by the Apache Software Foundation (http://www.apache.org/). ---------------------------------------------------------------------- USAGE ---------------------------------------------------------------------- To convert a schema written in either RELAX Core, RELAX namespace, TREX, or W3C XML Schema, enter the following: $ java -jar rngconv.jar myschema.xsd > result.rng The converter detects the schema language automatically (except for XML DTDs) and writes the result to "result.rng". To convert an XML DTD, enter the following: java -jar rngconv.jar -dtd myschema.dtd > result.rng Note that you need the -dtd option. ---------------------------------------------------------------------- LICENSE ---------------------------------------------------------------------- The most of the code is licensed under the BSD license (see license.txt). The only exception to this is a part of the code of XSDLib, which was taken from Apache, which is licensed under ASL 1.1 (see Apache-LICENSE-1.1.txt) ---------------------------------------------------------------------- KNOWN LIMITATIONS ---------------------------------------------------------------------- * This software relies on Sun Multi-Schema Validator(MSV). Therefore any limitations of MSV apply also to this converter. See [1] for more information. * RELAX Core permits undeclared attributes to appear in instance documents. This semantics is not converted. Therefore, any undeclared attributes are considered invalid after the conversion. * Identity constraints of W3C XML Schema are not converted. So if the source schema uses ,, or , this converter ignores those declarations. The semantics of "ID", "IDREF", and "IDREFS" are converted properly. * It may fail to convert some datatype definitions, especially those that are derived in a very complex way with lots of facets. * Schemas that consist of multiple files are converted into one big RELAX NG grammar. This limitation can be used to parse modularized RELAX NG grammar and create a single monolithic grammar. [1] Sun Multi-Schema Validator http://www.sun.com/software/xml/developers/multischema/ ====================================================================== END OF README msv-2009.1/rngconverter/MANIFEST.MF0000644000175000017500000000021607334533271016776 0ustar giovannigiovanniManifest-Version: 1.0 Main-Class: com.sun.msv.writer.relaxng.Driver Created-By: 1.2.2 (Sun Microsystems Inc.) Class-Path: msv.jar xerces.jar msv-2009.1/rngconverter/src/0000755000175000017500000000000011622453070016125 5ustar giovannigiovannimsv-2009.1/rngconverter/src/com/0000755000175000017500000000000011622453070016703 5ustar giovannigiovannimsv-2009.1/rngconverter/src/com/sun/0000755000175000017500000000000011622453070017510 5ustar giovannigiovannimsv-2009.1/rngconverter/src/com/sun/msv/0000755000175000017500000000000011622453070020315 5ustar giovannigiovannimsv-2009.1/rngconverter/src/com/sun/msv/writer/0000755000175000017500000000000011622453070021631 5ustar giovannigiovannimsv-2009.1/rngconverter/src/com/sun/msv/writer/relaxng/0000755000175000017500000000000011622453070023271 5ustar giovannigiovannimsv-2009.1/rngconverter/src/com/sun/msv/writer/relaxng/Messages_ja.properties0000644000175000017500000000071107365137162027641 0ustar giovannigiovanniDriver.Usage = \ \u4F7F\u3044\u65B9\uFF1ARELAXNGConverter <\u5909\u63DB\u5143\u30B9\u30AD\u30FC\u30DE\u30D5\u30A1\u30A4\u30EB\u540D/URL>\n\ \n\ \u69D8\u3005\u306A\u30B9\u30AD\u30FC\u30DE\u8A00\u8A9E\u3067\u66F8\u304B\u308C\u305F\u30B9\u30AD\u30FC\u30DE\u3092\u3001\u540C\u7B49\u306ERELAX NG\u6587\u6CD5\u306B\u5909\u63DB\u3057\u307E\u3059\n\ Driver.GrammarError = \ \u6587\u6CD5\u306E\u8AAD\u307F\u8FBC\u307F\u306B\u5931\u6557\u3057\u307E\u3057\u305F msv-2009.1/rngconverter/src/com/sun/msv/writer/relaxng/Driver.java0000644000175000017500000000523107714506462025403 0ustar giovannigiovanni/* * @(#)$Id: Driver.java 1586 2003-08-07 17:32:34Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.writer.relaxng; import javax.xml.parsers.SAXParserFactory; import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.XMLSerializer; import org.xml.sax.SAXException; import com.sun.msv.driver.textui.DebugController; import com.sun.msv.grammar.Grammar; import com.sun.msv.reader.util.GrammarLoader; /** * converts any supported languages into the equivalent RELAX NG grammar. * * @author Kohsuke KAWAGUCHI */ public class Driver { public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println(localize(MSG_USAGE)); return; } SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); // load a grammar. Grammar g = GrammarLoader.loadSchema(args[0], new DebugController(false, false, System.err), factory); if (g == null) { System.err.println(localize(MSG_GRAMMAR_ERROR)); return; } writeGrammar(g, System.out); } /** * Writes a grammar to the specified output. */ public static void writeGrammar(Grammar g, java.io.OutputStream out) throws SAXException { RELAXNGWriter writer = new RELAXNGWriter(); // use XMLSerializer of Apache to serialize SAX event into plain text. // OutputFormat specifies "pretty printing". writer.setDocumentHandler(new XMLSerializer(out, new OutputFormat("xml", null, true))); // visit TREXGrammar and generate its XML representation. writer.write(g); } public static String localize(String propertyName, Object[] args) { String format = java.util.ResourceBundle.getBundle("com.sun.msv.writer.relaxng.Messages").getString(propertyName); return java.text.MessageFormat.format(format, args); } public static String localize(String prop) { return localize(prop, null); } public static String localize(String prop, Object arg1) { return localize(prop, new Object[] { arg1 }); } public static String localize(String prop, Object arg1, Object arg2) { return localize(prop, new Object[] { arg1, arg2 }); } private static final String MSG_USAGE = // arg:0 "Driver.Usage"; private static final String MSG_GRAMMAR_ERROR = // arg:0 "Driver.GrammarError"; } msv-2009.1/rngconverter/src/com/sun/msv/writer/relaxng/Messages.properties0000644000175000017500000000035007365137162027166 0ustar giovannigiovanni Driver.Usage = \ Usage: RELAXNGConverter \n\ \n\ converts a schema written in various schema language to\n\ the equivalent schema written in RELAX NG.\n Driver.GrammarError = \ failed to load the grammar msv-2009.1/rngconverter/setenv.bat0000644000175000017500000000032407626741573017352 0ustar giovannigiovanni@echo off set CLASSPATH=%CLASSPATH%;..\..\shared\lib\isorelax.jar set CLASSPATH=%CLASSPATH%;..\..\shared\lib\relaxngDatatype.jar set CLASSPATH=%CLASSPATH%;..\..\msv\bin set CLASSPATH=%CLASSPATH%;..\..\xsdlib\bin msv-2009.1/msv/0000755000175000017500000000000011622453067013433 5ustar giovannigiovannimsv-2009.1/msv/pom.xml0000644000175000017500000001020011213776216014741 0ustar giovannigiovanni 4.0.0 net.java.dev.msv msv-core 2009.1 MSV Core net.java.dev.msv msv-parent 2009.1 ../parent/pom.xml scm:svn:http://msv.dev.java.net/svn/msv/tags/msv-2009.1/msv scm:svn:https://msv.dev.java.net/svn/msv/tags/msv-2009.1/msv org.apache.maven.plugins maven-jar-plugin test-jar com.sun.msv.driver.textui.Driver com.sun.msv.datatype.xsd xsdlib ${project.version} com.sun.msv.datatype.xsd xsdlib ${project.version} tests test net.java.dev.msv msv-testharness ${project.version} xml-resolver xml-resolver xerces xercesImpl isorelax isorelax relaxngDatatype relaxngDatatype xerces xercesImpl junit junit test msv-2009.1/msv/contrib/0000755000175000017500000000000011622453066015072 5ustar giovannigiovannimsv-2009.1/msv/contrib/sunmsv.el0000644000175000017500000001047007427136721016755 0ustar giovannigiovanni;; sunmsv.el - XEmacs (and maybe emacs) functionality ;; for using Sun's Multi-Schema validator. ;; ;; Author - Stuart Popejoy spopejoy@pinksheets.com ;; ;; This file is not part of GNU Emacs or XEmacs. ;; ;; This program is free software; you can redistribute it and/or ;; modify it under the terms of the GNU General Public License ;; as published by the Free Software Foundation; either version 2 ;; of the License, or (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with this program; if not, write to the Free Software ;; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ;; INSTALLATION: change sunmsv-jar-path to point to where you ;; have the msv.jar file; change sunmsv-last-dtd-path to the ;; default DTD (or schema or whatever) file you use most. ;; ;; Call sunmsv-validate to validate your XML file; if you need ;; to provide a path for the java command (ie /usr/jdk/bin/java ;; or something) change the code that creates the ;; sunmsv-valid-cmd variable. ;; ;; you can use this file, ie (load-library "sunmsv") etc, or ;; copy and paste all this stuff into your .emacs file. (defvar sunmsv-jar-path "/opt/dev/tools/sunxml/msv.jar" "Path to multi-schema validator jar file.") (defvar sunmsv-last-dtd-path "/usr/lib/sgml/oasis-docbook-4.1.2/docbookx.dtd" "Last dtd used by validator, and default dtd.") (defun sunmsv-validate () (interactive) "Performs XML validation using Sun's Multi-Schema validator. Operates on saved file, not buffer." (setq old-insert-default-directory insert-default-directory) (setq sunmsv-last-dtd-path (read-file-name "Path to DTD/Schema file for validation? " (file-name-directory sunmsv-last-dtd-path) sunmsv-last-dtd-path t (file-name-nondirectory sunmsv-last-dtd-path))) (setq sunmsv-valid-cmd (concat "java -jar " sunmsv-jar-path " " sunmsv-last-dtd-path " " (buffer-file-name))) (setq sunmsv-regexp-alist '(("^\\(Fatal \\)?[Ee]rror at line:\\([0-9,]+\\), column:\\([0-9]+\\) of file:\\(.+\\)" 4 2 3))) (compile-internal sunmsv-valid-cmd "No more errors" "MSV XML validation" 'sunmsv-validate-func sunmsv-regexp-alist)) (defun sunmsv-validate-func (limit-search find-at-least) (goto-char limit-search) (setq matcher (nth 0 compilation-error-regexp-alist)) (setq re (nth 0 matcher)) (setq fname nil) (setq line nil) (setq col nil) (setq result nil) (if (looking-at re) (progn (setq compmarker (point-marker)) (setq filemarker nil) (and (nth 1 matcher) (setq fname (buffer-string (match-beginning (nth 1 matcher)) (match-end (nth 1 matcher))))) (and (nth 2 matcher) (setq line (buffer-string (match-beginning (nth 2 matcher)) (match-end (nth 2 matcher))))) (and (nth 3 matcher) (setq col (buffer-string (match-beginning (nth 3 matcher)) (match-end (nth 3 matcher))))) ;(read-string (concat fname ":" line ":" col)) (if (and fname (file-exists-p fname)) (save-excursion (set-buffer (find-file-noselect fname)) (setq line (sunmsv-remove-comma line)) (if line (progn (goto-line (string-to-number line)) (if col (forward-char (string-to-number col))))) (setq filemarker (point-marker)))) (setq result (cons compmarker filemarker)))) (if result (setq compilation-error-list (cons result compilation-error-list)))) (defun sunmsv-remove-comma (org) (setq res org) (if org (progn (setq splitted (split-string org ",")) (setq n 0) (setq res "") (while (nth n splitted) (setq res (concat res (nth n splitted))) (setq n (1+ n))))) res) msv-2009.1/msv/history.txt0000644000175000017500000001043207306037047015675 0ustar giovannigiovanni (RNG) changed namespace URI. (RNG) @datatypeLibrary supported. data/@type is modified to NCName. (DTD) supports DTD. (both) fixed a bug that a named type is not properly derived by restriction when no facet is specified. (both) fixed an inconvenience of error recovery logic. (both) fixed a bug in error recovery from bad attribute value error. improved error message of bad attribute value error in case of "none" type. (both) added version message. 2000/03/29 release ------------------ (both) documents added (both) command line Verifier now detects type ofschema automatically. (both) switched default parser back to Xerces-J, due to the bug of Crimson in SAXParserFactory.setFeature method. (TREX) added proprietary type extension mechanism for TREX. (both) SAX parser is configured not to read external DTD by default. Added error message handler for SAX parse exception. 2000/03/23 release ------------------ (TREX) added check of "sequenced string". Due to the lack of the formal description of exactly what should be prohibited, the current implementation is based on the reference implementation by James Clark. (TREX) support QName for "name" attribute of "element"/"attribute" declaration. (TREX) added support for patterns whose document element is not element but other arbitrary pattern element. (dt) 'totalDigit' facet is now correctly implemented. (dt) 'fractionDigit' facet is now correctly implemented. (both) added a mechanism to controll inclusion (RELAX) Tranquilo will issue an error for with both "includeNamespace" and "excludeNamespace" attributes. (TREX) error diagnosis for is supported (TREX) implemented check for two pattern definitions in the same file with the same name. (TREX) modified to accept old "http://www.w3.org/2000/10/XMLSchema" namespace with a warning. (RELAX) RELAX reader is modified to recognize obsoleted type names such as "decimal","uriReference", with warning. (dt) Corrected namespace URI to "http://www.w3.org/2001/XMLSchema" and "http://www.w3.org/2001/XMLSchema-datatypes" (both) Better error diagnosis gets produced when the user forgot to declare namespace URI or declared a wrong namespace. 2000/03/20 release ------------------ (RELAX) When obsoleted type names like "uriReference" is used, Tranquilo now reports a warning but pretend as if it saw a correct type. (both) "Panic mode" is implemented: Tranquilo suppress excessive error messages. (dt) Updated datatype library to catch up with PR version of XML Schema. (both) Fixed a bug that makes validation a little bit slower and that sometimes interferes with type-assignment. (both) Added "optimistic" type-assignment mechanism for Verifier. This is the equivalent of "RELAXEffortlessHandler" which is implemented in "RELAX Verifier for Java" by Swift,Inc. This mechanism is "optimistic" in the sense that Verifier will report type as long as it can decide it; once if Verifier fails to decide type, it bails out (verification will be continued). (both) Implemented VerifierFilter that acts as XMLFilter. (both) Fixed bugs in integer-derived types and uriReference type. (RELAX) Supports "Java API for RELAX Verifier". (both) XML parser can now be choosed from Xerces or Crimson, by using a command line switch. (both) Performance optimization (RELAX) Reader now detects ID/IDREF abuse, which is prohibited by the formal specification of RELAX. (RELAX) ID/IDREF types are implemented (RELAX) Reader signals an error when two declarations have the same target attribute name. (both) Reader signals an error when namespace-unaware ParserFactory is given. 2000/03/09 release ------------------ (both) done a lot of optimization that makes validation faster (RELAX) support . (RELAX) add check for those exported hedgeRules which directly or indirectly refer labels of the other namespaces. (both) better error recovery for unexpected character literals. (RELAX) detects an error when unexported elementRules/hedgeRules are referenced from the other namespaces. (RELAX) implements RELAX semantics of ignoring undeclared attributes.msv-2009.1/msv/.cvsignore0000644000175000017500000000000510326260060015413 0ustar giovannigiovannidist msv-2009.1/msv/test/0000755000175000017500000000000011622453066014411 5ustar giovannigiovannimsv-2009.1/msv/test/SerialTestTool.java0000644000175000017500000000233110326265732020171 0ustar giovannigiovanni/* * @(#)$Id: SerialTestTool.java 1697 2005-10-21 22:29:46Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import com.sun.msv.datatype.xsd.StringType; import com.sun.msv.grammar.ExpressionPool; /** * Test program for serialization compatibility of {@link ExpressionPool}. * * @author * Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) */ public class SerialTestTool { public static void main(String[] args) throws Exception { if( args[0].equals("write") ) { ExpressionPool pool = new ExpressionPool(); pool.createAnyString(); pool.createChoice( pool.createData(StringType.theInstance), pool.createEpsilon() ); ObjectOutputStream oos = new ObjectOutputStream(System.out); oos.writeObject(pool); oos.close(); } else { ObjectInputStream ois = new ObjectInputStream(System.in); ExpressionPool pool = (ExpressionPool)ois.readObject(); System.out.println(pool); } } } msv-2009.1/msv/test/Driver.java0000644000175000017500000000022307671171415016510 0ustar giovannigiovannipublic class Driver { public static void main( String[] args ) throws Exception { com.sun.msv.driver.textui.Driver.main(args); } } msv-2009.1/msv/test/com/0000755000175000017500000000000011622453066015167 5ustar giovannigiovannimsv-2009.1/msv/test/com/sun/0000755000175000017500000000000011622453066015774 5ustar giovannigiovannimsv-2009.1/msv/test/com/sun/msv/0000755000175000017500000000000011622453066016601 5ustar giovannigiovannimsv-2009.1/msv/test/com/sun/msv/reader/0000755000175000017500000000000011622453066020043 5ustar giovannigiovannimsv-2009.1/msv/test/com/sun/msv/reader/relax/0000755000175000017500000000000011622453066021156 5ustar giovannigiovannimsv-2009.1/msv/test/com/sun/msv/reader/relax/core/0000755000175000017500000000000011622453066022106 5ustar giovannigiovannimsv-2009.1/msv/test/com/sun/msv/reader/relax/core/RELAXCoreReaderTest.java0000644000175000017500000000322007714506462026423 0ustar giovannigiovannipackage com.sun.msv.reader.relax.core; import javax.xml.parsers.SAXParserFactory; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import util.Checker; import util.ResourceChecker; import com.sun.msv.reader.GrammarReader; import com.sun.msv.reader.relax.RELAXReader; public class RELAXCoreReaderTest extends TestCase { public RELAXCoreReaderTest( String name ) { super(name); } public static void main(java.lang.String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(RELAXCoreReaderTest.class); } /** tests the existence of all messages */ public void testMessages() throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); final RELAXCoreReader reader = new RELAXCoreReader(null,factory,null); Checker checker = new Checker(){ public void check( String propertyName ) { // if the specified property doesn't exist, this will throw an error System.out.println( reader.localizeMessage(propertyName,new Object[]{"@@@","@@@","@@@","@@@","@@@"})); } }; String prefixes[] = new String[]{"ERR_","WRN_"}; for( int i=0; i msv-2009.1/msv/test/com/sun/msv/reader/xmlschema/MultiSchemaReaderTest.java0000644000175000017500000000702711164025612027064 0ustar giovannigiovannipackage com.sun.msv.reader.xmlschema; import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.net.URL; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.dom.DOMSource; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.ls.LSResourceResolver; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import com.sun.msv.grammar.xmlschema.XMLSchemaGrammar; import com.sun.msv.reader.GrammarReaderController2; public class MultiSchemaReaderTest { private static class LocalController implements GrammarReaderController2 { public LSResourceResolver getLSResourceResolver() { return null; } public void error(Locator[] locs, String errorMessage, Exception nestedException) { StringBuffer errors = new StringBuffer(); for (Locator loc : locs) { errors.append("in " + loc.getSystemId() + " " + loc.getLineNumber() + ":" + loc.getColumnNumber()); } throw new RuntimeException(errors.toString(), nestedException); } public void warning(Locator[] locs, String errorMessage) { StringBuffer errors = new StringBuffer(); for (Locator loc : locs) { errors.append("in " + loc.getSystemId() + " " + loc.getLineNumber() + ":" + loc.getColumnNumber()); } // no warning allowed. throw new RuntimeException("warning: " + errors.toString()); } public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return null; } }; @Test public void testWsdlMultiSchema() throws Exception { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); URL wsdlUri = getClass().getResource("test.wsdl"); Document wsdl = documentBuilder.parse(wsdlUri.openStream()); String wsdlSystemId = wsdlUri.toExternalForm(); DOMSource source = new DOMSource(wsdl); source.setSystemId(wsdlSystemId); LocalController controller = new LocalController(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); XMLSchemaGrammar result = WSDLSchemaReader.read(source, factory, controller); assertNotNull(result); } @Test public void testWsdlMultiRefSchema() throws Exception { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); URL wsdlUri = getClass().getResource("multireference.wsdl"); Document wsdl = documentBuilder.parse(wsdlUri.openStream()); String wsdlSystemId = wsdlUri.toExternalForm(); DOMSource source = new DOMSource(wsdl); source.setSystemId(wsdlSystemId); LocalController controller = new LocalController(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); XMLSchemaGrammar result = WSDLSchemaReader.read(source, factory, controller); assertNotNull(result); } } msv-2009.1/msv/test/com/sun/msv/reader/xmlschema/multireference.wsdl0000644000175000017500000004501511164025612025726 0ustar giovannigiovanni msv-2009.1/msv/test/com/sun/msv/reader/dtd/0000755000175000017500000000000011622453066020616 5ustar giovannigiovannimsv-2009.1/msv/test/com/sun/msv/reader/dtd/DTDReaderTest.java0000644000175000017500000000200407671171415024057 0ustar giovannigiovannipackage com.sun.msv.reader.dtd; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import util.Checker; import util.ResourceChecker; public class DTDReaderTest extends TestCase { public DTDReaderTest( String name ) { super(name); } public static void main(java.lang.String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(DTDReaderTest.class); } /** tests the existence of all messages */ public void testMessages() throws Exception { ResourceChecker.check( DTDReader.class, "", new Checker(){ public void check( String propertyName ) { // if the specified property doesn't exist, this will throw an error System.out.println( Localizer.localize(propertyName,new Object[]{"@@@","@@@","@@@","@@@","@@@"})); } }); } } msv-2009.1/msv/test/com/sun/msv/grammar/0000755000175000017500000000000011622453066020227 5ustar giovannigiovannimsv-2009.1/msv/test/com/sun/msv/grammar/util/0000755000175000017500000000000011622453066021204 5ustar giovannigiovannimsv-2009.1/msv/test/com/sun/msv/grammar/util/NameClassSimplifierTest.java0000644000175000017500000000526310005264262026577 0ustar giovannigiovannipackage com.sun.msv.grammar.util; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import com.sun.msv.grammar.ChoiceNameClass; import com.sun.msv.grammar.DifferenceNameClass; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.NamespaceNameClass; import com.sun.msv.grammar.NotNameClass; import com.sun.msv.grammar.SimpleNameClass; public class NameClassSimplifierTest extends TestCase { public NameClassSimplifierTest( String name ) { super(name); } public static void main(java.lang.String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(NameClassSimplifierTest.class); } public void testSimplifier1() throws Exception { assertSame( NameClass.ALL, NameClassSimplifier.simplify( new ChoiceNameClass( NameClass.ALL, new DifferenceNameClass( new NamespaceNameClass("abc"), new SimpleNameClass("abc","def"))))); } public void testSimplifier2() throws Exception { NameClass nc = NameClassSimplifier.simplify( new DifferenceNameClass( new ChoiceNameClass( NameClass.ALL, new NamespaceNameClass("abc") ), new SimpleNameClass("abc","def"))); assertTrue( nc instanceof NotNameClass ); NotNameClass nnc = (NotNameClass)nc; assertTrue( nnc.child instanceof SimpleNameClass ); SimpleNameClass snc = (SimpleNameClass)nnc.child; assertEquals( snc.namespaceURI, "abc" ); assertEquals( snc.localName, "def"); } public void testSimplifier3() throws Exception { NameClass nc = NameClassSimplifier.simplify( new DifferenceNameClass( NameClass.ALL, new DifferenceNameClass( new NamespaceNameClass("abc"), new SimpleNameClass("abc","def")))); assertTrue( nc instanceof NotNameClass ); NotNameClass nnc = (NotNameClass)nc; assertTrue( nnc.child instanceof DifferenceNameClass ); DifferenceNameClass dnc = (DifferenceNameClass)nnc.child; assertTrue( dnc.nc1 instanceof NamespaceNameClass ); NamespaceNameClass nc1 = (NamespaceNameClass)dnc.nc1; assertEquals( "abc",nc1.namespaceURI ); assertTrue( dnc.nc2 instanceof SimpleNameClass ); SimpleNameClass nc2 = (SimpleNameClass)dnc.nc2; assertEquals( "abc",nc2.namespaceURI ); assertEquals( "def",nc2.localName ); } } msv-2009.1/msv/test/com/sun/msv/verifier/0000755000175000017500000000000011622453066020414 5ustar giovannigiovannimsv-2009.1/msv/test/com/sun/msv/verifier/multithread/0000755000175000017500000000000011622453066022736 5ustar giovannigiovannimsv-2009.1/msv/test/com/sun/msv/verifier/multithread/Daemon.java0000644000175000017500000001045011156747174025014 0ustar giovannigiovanni/* * @(#)$Id: Daemon.java 1744 2009-03-14 15:34:20Z bimargulies $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.multithread; import java.util.EmptyStackException; import java.util.Stack; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.XMLReader; import com.sun.msv.driver.textui.DebugController; import com.sun.msv.grammar.Grammar; import com.sun.msv.reader.util.GrammarLoader; import com.sun.msv.verifier.ValidityViolation; import com.sun.msv.verifier.Verifier; import com.sun.msv.verifier.regexp.REDocumentDeclaration; import com.sun.msv.verifier.util.ErrorHandlerImpl; /** * multi-thread tester. * * @author Kohsuke KAWAGUCHI */ public class Daemon implements Runnable { public static void main( String[] args ) throws Exception { new Daemon()._main(args); } Grammar grammar; /** file names that have to be validated. */ private final Stack jobs = new Stack(); private void _main( String[] args ) throws Exception { if( args.length!=4 ) { System.out.println( "Usage: Daemon (relax|trex) <# of threads>\n"+ " .trex or .rlx is used as a schema\n"+ " .v100 to .v999 are used as instances"); return; } SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); String schemaName; if( args[0].equals("relax") ) schemaName = args[1]+".rlx"; else schemaName = args[1]+".trex"; grammar = GrammarLoader.loadSchema( schemaName, new DebugController(false,false), factory ); for( int i=100; i<=999; i++ ) jobs.push( args[1]+".v"+i+args[2] ); final long startTime = System.currentTimeMillis(); final int m = Integer.parseInt( args[3] ); System.out.println("Use " + m + " threads"); Thread[] ts = new Thread[m]; for( int i=0; iKohsuke KAWAGUCHI */ public class TypeReporter extends DefaultHandler { public static void main( String[] args ) throws Exception { new TypeReporter().run(args); } private VerifierFilter filter; private void run( String[] args ) throws Exception { if( args.length!=3 ) { System.out.println("Usage: TypeReporter (relaxNS|relaxCore|trex|xsd) \n"); return; } SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); Grammar grammar; if( args[0].equals("trex") ) { TREXGrammarReader reader = new TREXGrammarReader( new com.sun.msv.driver.textui.DebugController(false,false), factory, new TypedTREXGrammarInterceptor(), new ExpressionPool() ); ((XMLFilter)reader).parse(args[1]); grammar = reader.getResult(); } else { grammar = GrammarLoader.loadSchema( args[1], new com.sun.msv.driver.textui.DebugController(false,false), factory ); } if( grammar==null ) { System.err.println("failed to load a grammar"); return; } filter = new VerifierFilter( new REDocumentDeclaration(grammar), new com.sun.msv.driver.textui.ReportErrorHandler() ); filter.setParent(factory.newSAXParser().getXMLReader()); filter.setContentHandler(this); filter.parse( args[2] ); } private int indent = 0; private void printIndent() { for( int i=0; i :"); Object o = filter.getVerifier().getCurrentElementType(); if( o instanceof ElementRule ) { // for RELAX ElementRule er = (ElementRule)o; if( er.getParent()==null ) System.out.println("##inline"); else System.out.println(er.getParent().name); return; } if( o instanceof TypedElementPattern ) { // for typed TREX System.out.println( ((TypedElementPattern)o).label ); return; } if( o instanceof ElementPattern ) { System.out.println( ExpressionPrinter.printContentModel( ((ElementPattern)o).contentModel ) ); return; } System.out.println("???"); } public void endElement( String namespaceUri, String localName, String qName ) { Datatype[] types = filter.getVerifier().getLastCharacterType(); if( types!=null ) { String r=""; for( int i=0; i"); } } msv-2009.1/msv/test/com/sun/msv/verifier/jaxp/0000755000175000017500000000000011622453066021356 5ustar giovannigiovannimsv-2009.1/msv/test/com/sun/msv/verifier/jaxp/TestConst.java0000644000175000017500000000153607671171415024160 0ustar giovannigiovannipackage com.sun.msv.verifier.jaxp; public class TestConst { static final String incorrectSchema = ""+ ""+ ""+ ""+ ""+ ""; static final String rngSchema = ""+ ""+ ""+ ""+ ""+ ""; static final String xsdSchema = ""+ ""+ ""; static final String validDocument = "abc"; static final String invalidDocument = ""; } msv-2009.1/msv/test/com/sun/msv/verifier/jaxp/DOMBuilderTest.java0000644000175000017500000001124507671171415025016 0ustar giovannigiovannipackage com.sun.msv.verifier.jaxp; import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * Tests the typical use cases of JAXP masquerading with DocumentBuilderFactory */ public class DOMBuilderTest extends TestCase { public DOMBuilderTest( String name ) { super(name); } public static void main(java.lang.String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(DOMBuilderTest.class); } // // // use of DocumentBuilderFactory without schema //==================================================== // // public void testScenario1_1() throws Exception { DocumentBuilderFactory factory = new DocumentBuilderFactoryImpl(); doTest1(factory); } public void testScenario1_2() throws Exception { DocumentBuilderFactory factory = new DocumentBuilderFactoryImpl(); factory.setNamespaceAware(true); doTest1(factory); } private void doTest1( DocumentBuilderFactory factory ) throws Exception { // use it without any schema parse(factory.newDocumentBuilder(),true); // set the incorrect schema and expect the error try { factory.setAttribute( Const.SCHEMA_PROPNAME, new InputSource( new StringReader(TestConst.incorrectSchema) ) ); fail("incorrect schema was accepted"); } catch( IllegalArgumentException e ) { // it should throw this exception } // set the schema. factory.setAttribute( Const.SCHEMA_PROPNAME, new InputSource( new StringReader(TestConst.rngSchema) ) ); // then parse again. parse(factory.newDocumentBuilder(),false); // set another schema. factory.setAttribute( Const.SCHEMA_PROPNAME, new InputSource( new StringReader(TestConst.xsdSchema) ) ); // then parse again. parse(factory.newDocumentBuilder(),false); } public void testScenario2_1() throws Exception { DocumentBuilderFactory factory = new DocumentBuilderFactoryImpl(); doTest2(factory); } public void testScenario2_2() throws Exception { DocumentBuilderFactory factory = new DocumentBuilderFactoryImpl(); factory.setNamespaceAware(true); doTest2(factory); } private void doTest2( DocumentBuilderFactory factory ) throws Exception { DocumentBuilder builder1 = factory.newDocumentBuilder(); // set the schema. // since builder1 is already created, it should not be affected // by this change. factory.setAttribute( Const.SCHEMA_PROPNAME, new InputSource( new StringReader(TestConst.xsdSchema) ) ); DocumentBuilder builder2 = factory.newDocumentBuilder(); parse(builder2,false); parse(builder1,true); } public void testScenario3_1() throws Exception { DocumentBuilderFactory factory = new DocumentBuilderFactoryImpl(); doTest3(factory); } public void testScenario3_2() throws Exception { DocumentBuilderFactory factory = new DocumentBuilderFactoryImpl(); factory.setNamespaceAware(true); doTest3(factory); } private void doTest3( DocumentBuilderFactory factory ) throws Exception { // set the schema. factory.setAttribute( Const.SCHEMA_PROPNAME, new InputSource( new StringReader(TestConst.rngSchema) ) ); factory.newDocumentBuilder().parse( new InputSource( new StringReader("abc")) ); } private void parse( DocumentBuilder builder, boolean expectationForInvalid ) throws Exception { // parse test. test the invalid case first to make sure that this failure // won't affect the rest of the story. for( int i=0; i<2; i++ ) { try { builder.parse( new InputSource( new StringReader(TestConst.invalidDocument)) ); if(expectationForInvalid==false) fail("failed to reject an invalid document"); } catch( SAXException e ) { if(expectationForInvalid==true) fail("failed to accept a valid document"); } builder.parse( new InputSource( new StringReader(TestConst.validDocument)) ); } } } msv-2009.1/msv/test/com/sun/msv/verifier/jaxp/SAXParserTest.java0000644000175000017500000001000707671171415024673 0ustar giovannigiovannipackage com.sun.msv.verifier.jaxp; import java.io.StringReader; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.xml.sax.InputSource; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; /** * Tests the typical use cases of JAXP masquerading with SAXParserFactory. */ public class SAXParserTest extends TestCase { public SAXParserTest( String name ) { super(name); } public static void main(java.lang.String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(SAXParserTest.class); } // // // use of DocumentBuilderFactory without schema //==================================================== // // public void testScenario1_1() throws Exception { SAXParserFactory factory = new SAXParserFactoryImpl(); doTest1(factory); } public void testScenario1_2() throws Exception { SAXParserFactory factory = new SAXParserFactoryImpl(); factory.setNamespaceAware(true); doTest1(factory); } private void doTest1( SAXParserFactory factory ) throws Exception { // use it without any schema SAXParser parser = factory.newSAXParser(); parse(parser,true); // set the incorrect schema and expect the error try { parser.setProperty( Const.SCHEMA_PROPNAME, new InputSource( new StringReader(TestConst.incorrectSchema) ) ); fail("incorrect schema was accepted"); } catch( org.xml.sax.SAXNotRecognizedException e ) { // it should throw an exception } // set the schema. parser.setProperty( Const.SCHEMA_PROPNAME, new InputSource( new StringReader(TestConst.rngSchema) ) ); // then parse again. parse(parser,false); // set another schema. parser.setProperty( Const.SCHEMA_PROPNAME, new InputSource( new StringReader(TestConst.xsdSchema) ) ); // then parse again. parse(parser,false); } public void testScenario3_1() throws Exception { SAXParserFactory factory = new SAXParserFactoryImpl(); doTest3(factory); } public void testScenario3_2() throws Exception { SAXParserFactory factory = new SAXParserFactoryImpl(); factory.setNamespaceAware(true); doTest3(factory); } private void doTest3( SAXParserFactory factory ) throws Exception { SAXParser parser = factory.newSAXParser(); // set the schema. parser.setProperty( Const.SCHEMA_PROPNAME, new InputSource( new StringReader(TestConst.rngSchema) ) ); parser.parse( new InputSource( new StringReader("abc")) , new Handler() ); } private void parse( SAXParser parser, boolean expectationForInvalid ) throws Exception { // parse test. test the invalid case first to make sure that this failure // won't affect the rest of the story. for( int i=0; i<2; i++ ) { try { parser.parse( new InputSource( new StringReader(TestConst.invalidDocument)), new Handler() ); if(expectationForInvalid==false) fail("failed to reject an invalid document"); } catch( Exception e ) { if(expectationForInvalid==true) fail("failed to accept a valid document"); } parser.parse( new InputSource( new StringReader(TestConst.validDocument)), new Handler() ); } } private class Handler extends DefaultHandler { public void error( SAXParseException e ) throws SAXParseException { throw e; } } } msv-2009.1/msv/test/com/sun/msv/verifier/identity/0000755000175000017500000000000011622453066022245 5ustar giovannigiovannimsv-2009.1/msv/test/com/sun/msv/verifier/identity/IDConstraintCheckerTest.java0000644000175000017500000000206607671171415027606 0ustar giovannigiovannipackage com.sun.msv.verifier.identity; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import util.Checker; import util.ResourceChecker; public class IDConstraintCheckerTest extends TestCase { public IDConstraintCheckerTest( String name ) { super(name); } public static void main(java.lang.String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(IDConstraintCheckerTest.class); } /** tests the existence of all messages */ public void testMessages() throws Exception { Checker checker = new Checker(){ public void check( String propertyName ) { // if the specified property doesn't exist, this will throw an error System.out.println( IDConstraintChecker.localizeMessage(propertyName,new Object[]{"@@@","@@@","@@@","@@@","@@@"})); } }; ResourceChecker.check( IDConstraintChecker.class, "", checker ); } } msv-2009.1/msv/test/com/sun/msv/verifier/jarv/0000755000175000017500000000000011622453066021356 5ustar giovannigiovannimsv-2009.1/msv/test/com/sun/msv/verifier/jarv/JARVTester.java0000644000175000017500000000366707671171415024172 0ustar giovannigiovanni/* * @(#)$Id: JARVTester.java 1567 2003-06-09 20:50:21Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.jarv; import org.iso_relax.verifier.Schema; import org.iso_relax.verifier.Verifier; import org.iso_relax.verifier.VerifierFactory; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXParseException; /** * tests JARV. * * This class is NOT a part of the JUnit test cases. * * @author Kohsuke KAWAGUCHI */ abstract class JARVTester { protected abstract VerifierFactory getFactory(String language) throws Exception; public void run(java.lang.String[] args) throws Exception { if(args.length<3) { System.out.println( "Usage: FactoryLoaderTester ...\n"); return; } VerifierFactory factory = getFactory(args[0]); if(factory==null) { System.out.println("unable to find an implementation"); return; } Schema schema = factory.compileSchema(args[1]); if(schema==null) { System.out.println("unable to parse this schema"); return; } Verifier verifier = schema.newVerifier(); verifier.setErrorHandler( new ErrorHandler(){ public void fatalError( SAXParseException e ) { System.out.println("fatal:"+e); } public void error( SAXParseException e ) { System.out.println("error:"+e); } public void warning( SAXParseException e ) { System.out.println("warning:"+e); } }); for( int i=2; iorg/iso_relax/verifier/FactoryLoader. * * This class is NOT a part of the JUnit test cases. * * @author Kohsuke KAWAGUCHI */ public class TheFactoryImplTester extends JARVTester { public static void main(java.lang.String[] args) throws Exception { new TheFactoryImplTester().run(args); } protected VerifierFactory getFactory(String language) { return new TheFactoryImpl(); } } msv-2009.1/msv/test/com/sun/msv/verifier/jarv/FactoryLoaderTester.java0000644000175000017500000000156707671171415026163 0ustar giovannigiovanni/* * @(#)$Id: FactoryLoaderTester.java 1567 2003-06-09 20:50:21Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.jarv; import org.iso_relax.verifier.VerifierFactory; /** * test org/iso_relax/verifier/FactoryLoader. * * This class is NOT a part of the JUnit test cases. * * @author Kohsuke KAWAGUCHI */ public class FactoryLoaderTester extends JARVTester { public static void main(java.lang.String[] args) throws Exception { new TheFactoryImplTester().run(args); } protected VerifierFactory getFactory(String language) throws Exception { return VerifierFactory.newInstance(language); } } msv-2009.1/msv/test/com/sun/msv/verifier/VerifierTest.java0000644000175000017500000000176607671171415023710 0ustar giovannigiovannipackage com.sun.msv.verifier; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import util.Checker; import util.ResourceChecker; public class VerifierTest extends TestCase { public VerifierTest( String name ) { super(name); } public static void main(java.lang.String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(VerifierTest.class); } /** tests the existence of all messages */ public void testMessages() throws Exception { Checker checker = new Checker(){ public void check( String propertyName ) { // if the specified property doesn't exist, this will throw an error System.out.println( Verifier.localizeMessage(propertyName,new Object[]{"@@@","@@@","@@@","@@@","@@@"})); } }; ResourceChecker.check( Verifier.class, "", checker ); } } msv-2009.1/msv/test/com/sun/msv/verifier/regexp/0000755000175000017500000000000011622453066021706 5ustar giovannigiovannimsv-2009.1/msv/test/com/sun/msv/verifier/regexp/REDocumentDeclarationTest.java0000644000175000017500000000222407671171415027570 0ustar giovannigiovannipackage com.sun.msv.verifier.regexp; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import util.Checker; import util.ResourceChecker; public class REDocumentDeclarationTest extends TestCase { public REDocumentDeclarationTest( String name ) { super(name); } public static void main(java.lang.String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(REDocumentDeclarationTest.class); } /** tests the existence of all messages */ public void testMessages() throws Exception { final REDocumentDeclaration decl = new REDocumentDeclaration(null,null); Checker checker = new Checker(){ public void check( String propertyName ) { // if the specified property doesn't exist, this will throw an error System.out.println( decl.localizeMessage(propertyName,new Object[]{"@@@","@@@","@@@","@@@","@@@"})); } }; ResourceChecker.check( REDocumentDeclaration.class, "", checker ); } } msv-2009.1/msv/test/com/sun/msv/util/0000755000175000017500000000000011622453066017556 5ustar giovannigiovannimsv-2009.1/msv/test/com/sun/msv/util/StringPairTest.java0000644000175000017500000000267407671171415023360 0ustar giovannigiovanni/* * @(#)$Id: StringPairTest.java 1567 2003-06-09 20:50:21Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.util; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * tests StringPair. * * @author Kohsuke KAWAGUCHI */ public class StringPairTest extends TestCase { public StringPairTest( String name ) { super(name); } public static void main(java.lang.String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(StringPairTest.class); } /** test equals and hashCode method */ public void testEqualsAndHashCode() { StringPair[] pairs = new StringPair[]{ new StringPair("namespace","foo"), new StringPair("namespac-","foo"), new StringPair("namespace","bar") }; for( int i=0; i"; } public void startModelGroup() { model += "("; } public void endModelGroup( short occurence ) { model += ")" + getOccurs(occurence); } public void connector( short connectorType ) { model += getConnector(connectorType); } String getConnector( short type ) { switch(type) { case CHOICE: return "|"; case SEQUENCE: return ","; default: throw new Error(); } } String getOccurs( short type ) { switch(type) { case OCCURENCE_ONE_OR_MORE: return "+"; case OCCURENCE_ZERO_OR_MORE: return "*"; case OCCURENCE_ZERO_OR_ONE: return "?"; case OCCURENCE_ONCE: return ""; default: throw new Error(); } } public void setDocumentLocator( Locator loc ) {} } } msv-2009.1/msv/test/com/sun/msv/scanner/dtd/Driver.java0000644000175000017500000000037607671171415023115 0ustar giovannigiovannipackage com.sun.msv.scanner.dtd; public class Driver { public static void main( String[] args ) throws Exception { DTDParser parser = new DTDParser(); parser.setDtdHandler( new DumpHandler() ); parser.parse(args[0]); } } msv-2009.1/msv/test/com/sun/msv/scanner/dtd/TestHandler.java0000644000175000017500000000004207273576330024070 0ustar giovannigiovannipackage com.sun.msv.scanner.dtd; msv-2009.1/msv/test/batch/0000755000175000017500000000000011622453066015472 5ustar giovannigiovannimsv-2009.1/msv/test/batch/WordlessErrorReporter.java0000644000175000017500000000211407671171415022676 0ustar giovannigiovanni/* * @(#)$Id: WordlessErrorReporter.java 1567 2003-06-09 20:50:21Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package batch; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXParseException; /** * {@link ErrorHandler} that reports only the first error. * * @author Kohsuke KAWAGUCHI */ public class WordlessErrorReporter implements ErrorHandler { private boolean first = true; private SAXParseException error = null; public SAXParseException getError() { return error; } public void fatalError( SAXParseException e ) throws SAXParseException { error(e); throw e; } public void error( SAXParseException error ) { if( first ) { System.out.println(error.getMessage()); this.error = error; } first = false; } public void warning( SAXParseException warning ) {} } msv-2009.1/msv/test/batch/BatchTester.java0000644000175000017500000001512711156747174020563 0ustar giovannigiovanni/* * @(#)$Id: BatchTester.java 1744 2009-03-14 15:34:20Z bimargulies $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package batch; import java.io.File; import java.util.StringTokenizer; import java.util.Vector; import javax.xml.parsers.SAXParserFactory; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.xml.resolver.tools.CatalogResolver; import batch.driver.DTDValidator; import batch.driver.GenericValidator; import batch.driver.IValidatorEx; import batch.driver.IValidatorImplForRNG; import batch.driver.IValidatorImplForXS; import batch.model.TestReader; /** * Test schemata/instances are expected to follow a naming convention. * *
    *
  1. legal schema must have "*.rlx" or "*.trex" *
  2. invalid schema must have "*.e.rlx" or "*.e.trex" *
  3. valid test document must have "*.vNN.xml". * these documents are validated against "*.rlx" or "*.trex". *
  4. invalid test document must have "*.nNN.xml". *
* * Files that follow this naming convention are all tested. If any unexpected * result is found, main method returns non-0 exit code. * * @author Kohsuke KAWAGUCHI */ public abstract class BatchTester { public SAXParserFactory factory = SAXParserFactory.newInstance(); public CatalogResolver resolver = new CatalogResolver(); /** schema file extension ".rlx", ".trex", or ".dtd" */ public String ext; public IValidatorEx validator; private TestReader reader; /** Set to true if the strict option is specified. */ protected boolean strict = false; /** * This method should print the usage information. */ protected abstract void usage(); /** * Creates the test suite from the specified file/directory. */ public Test parse( String target ) throws Exception { return parse(target,false); } /** * Creates the test suite from the specified file/directory. * * @param recursive * if the target is directory and this parameter is true, then * subdirectories are recursively parsed into a test suite. */ public Test parse( String target, boolean recursive ) throws Exception { File src = new File(target); if(src.isDirectory()) return reader.parseDirectory( src, ext, recursive ); else return reader.parseSchema(src); } /** * Initializes various fields by setting a target schema language. */ public void init( String target, boolean strict ) { if(strict) System.out.println("strict schema check will be done"); if(strict && ( target.equals("relax") || target.equals("trex") || target.equals("relax") )) System.out.println("*** strict option is not supported for the language "+target); if( target.equals("relax") ) setUp( ".rlx", new GenericValidator() ); else if( target.equals("trex") ) setUp( ".trex", new GenericValidator() ); else if( target.equals("rng") ) setUp( ".rng", new IValidatorImplForRNG(strict) ); else if( target.equals("xsd") ) setUp( ".xsd", new IValidatorImplForXS(strict) ); else if( target.equals("dtd") ) setUp( ".dtd", new DTDValidator() ); else throw new Error("unrecognized language type: "+target ); } /** * This method is called when the schema language is detected. */ protected void setUp( String _ext, IValidatorEx _validator ) { this.ext = _ext; this.validator = _validator; this.reader = createReader(); } /** * This method is called as the last step of set-up * to create TestReader object which will parse test files. */ protected abstract TestReader createReader(); protected void onOption( String opt ) throws Exception { System.out.println("unrecognized option:"+opt); throw new Error(); } public void run( String[] av ) throws Exception { String target = null; Vector instances = new Vector(); boolean recursive = false; for( int i=0; iKohsuke KAWAGUCHI */ public interface ISchema { Grammar asGrammar(); } msv-2009.1/msv/test/batch/model/TestReader.java0000644000175000017500000000731307714506462021511 0ustar giovannigiovannipackage batch.model; import java.io.File; import java.io.FilenameFilter; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.SAXParserFactory; import junit.framework.Test; import junit.framework.TestSuite; /** * Parses a directory into the test suite. * * This object will enumerate test files, and TestBuilder will create * actual test cases. * * @author * Kohsuke KAWAGUCHI */ public class TestReader { public TestReader( TestBuilder _builder ) { this.builder = _builder; } private final TestBuilder builder; /** * Obtains a test object from a schema file (e.g., abc.rng) and * its instance documents. */ public Test parseSchema( File schema ) throws Exception { String schemaName = schema.getName(); File parent = new File(schema.getParent()); final String prefix = schemaName.substring(0, schemaName.lastIndexOf('.')+1); final boolean isCorrect = schemaName.indexOf(".e.")==-1; if(isCorrect) { TestSuite suite = new TestSuite(); suite.addTest( builder.createCorrectSchemaTest(schema) ); // collects test instances. String[] instances = parent.list( new FilenameFilter(){ public boolean accept( File dir, String name ) { return name.startsWith(prefix) && name.endsWith(".xml"); } } ); if( instances!=null ) { for( int i=0; iKohsuke KAWAGUCHI */ public interface IValidator { /** * compiles the specified schema. * * @return * If the validator accepts the schema, it should return a compiled * schema object. This object will be then used to validate XML instances. * If the validator rejects the schema, it should return null. * * @exception * Any exception is considered as an conformance violation. */ ISchema parseSchema( File schema ) throws Exception; ISchema parseSchema( InputStream is ) throws Exception; /** * validates the specified instance with the schema. * * @return * If the validator judges that the document is valid, return true. * If the validator judges otherwise, return false. * * @exception * Any exception is considered as an conformance violation. */ boolean validate( ISchema schema, File document ) throws Exception; } msv-2009.1/msv/test/batch/verifier/0000755000175000017500000000000011622453066017305 5ustar giovannigiovannimsv-2009.1/msv/test/batch/verifier/RELAXBatchTest.java0000644000175000017500000000131107671171415022625 0ustar giovannigiovanni/* * @(#)$Id: RELAXBatchTest.java 1567 2003-06-09 20:50:21Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package batch.verifier; import junit.framework.TestSuite; /** * tests the entire RELAX test suite by using BatchVerifyTester. * * for use by automated test by ant. * * @author Kohsuke KAWAGUCHI */ public class RELAXBatchTest { public static TestSuite suite() throws Exception { return new BatchVerifyTester().createFromProperty( "relax","RELAXBatchTestDir"); } } msv-2009.1/msv/test/batch/verifier/XSDBatchTest.java0000644000175000017500000000130107671171415022407 0ustar giovannigiovanni/* * @(#)$Id: XSDBatchTest.java 1567 2003-06-09 20:50:21Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package batch.verifier; import junit.framework.TestSuite; /** * tests the entire RELAX test suite by using BatchVerifyTester. * * for use by automated test by ant. * * @author Kohsuke KAWAGUCHI */ public class XSDBatchTest { public static TestSuite suite() throws Exception { return new BatchVerifyTester().createFromProperty( "xsd","XSDBatchTestDir"); } } msv-2009.1/msv/test/batch/verifier/TestBuilderImpl.java0000644000175000017500000000514607716305076023234 0ustar giovannigiovannipackage batch.verifier; import java.io.File; import junit.framework.Test; import junit.framework.TestCase; import batch.model.ISchema; import batch.model.IValidator; import batch.model.TestBuilder; public class TestBuilderImpl implements TestBuilder { public TestBuilderImpl( IValidator _validator ) { this.validator = _validator; } private final IValidator validator; private class SchemaTestCase extends TestCase { public SchemaTestCase( File _src ) { super(TestBuilderImpl.getName(_src)); this.src=_src; } private final File src; public ISchema schema; public void runTest() throws Exception { schema = validator.parseSchema(src); assertNotNull( "validator "+validator+" failed to compile a correct schema "+src, schema ); } } private SchemaTestCase current; public Test createCorrectSchemaTest( final File schema ) { current = new SchemaTestCase(schema); return current; } public Test createValidDocumentTest( File document ) { return createDocumentTest(document,true); } public Test createInvalidDocumentTest( File document ) { return createDocumentTest(document,false); } private Test createDocumentTest( final File document, final boolean expectation ) { final SchemaTestCase schema = current; return new TestCase(getName(document)) { public void runTest() throws Exception { if(schema.schema==null) // abort. there was an error in the schema return; boolean r = validator.validate(schema.schema,document); if(r==expectation) return; // OK if(expectation) fail("validator "+validator+" failed to accept a valid document "+document); else fail("validator "+validator+" accepted an invalid document "+document); } }; } public Test createIncorrectSchemaTest( final File schema ) { return new TestCase(getName(schema)) { public void runTest() throws Exception { assertNull( "validator "+validator+" compiled an incorrect schema "+schema, validator.parseSchema(schema) ); } }; } /** Computes the test name from a file name. */ private static String getName( File f ) { return f.getPath(); } } msv-2009.1/msv/test/batch/verifier/TREXBatchTest.java0000644000175000017500000000130507671171415022537 0ustar giovannigiovanni/* * @(#)$Id: TREXBatchTest.java 1567 2003-06-09 20:50:21Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package batch.verifier; import junit.framework.TestSuite; /** * tests the entire RELAX test suite by using BatchVerifyTester. * * for use by automated test by ant. * * @author Kohsuke KAWAGUCHI */ public class TREXBatchTest { public static TestSuite suite() throws Exception { return new BatchVerifyTester().createFromProperty( "trex","TREXBatchTestDir"); } } msv-2009.1/msv/test/batch/verifier/BatchVerifyTester.java0000644000175000017500000000204707671171415023554 0ustar giovannigiovanni/* * @(#)$Id: BatchVerifyTester.java 1567 2003-06-09 20:50:21Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package batch.verifier; import batch.model.TestReader; /** * validates instances by schemata. * * @author Kohsuke KAWAGUCHI */ public class BatchVerifyTester extends batch.BatchTester { protected TestReader createReader() { return new TestReader( new TestBuilderImpl(validator) ); } public static void main( String[] av ) throws Exception { new BatchVerifyTester().run(av); } protected void usage() { System.out.println( "usage "+this.getClass().getName()+" (relax|trex|xsd|dtd|rng) [-strict] [-recursive] \n"+ " tests the validation engine by using schema files and test instances\n"+ " in the specified directory."); } } msv-2009.1/msv/test/batch/verifier/DTDBatchTest.java0000644000175000017500000000130207671171415022365 0ustar giovannigiovanni/* * @(#)$Id: DTDBatchTest.java 1567 2003-06-09 20:50:21Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package batch.verifier; import junit.framework.TestSuite; /** * tests the entire RELAX test suite by using BatchVerifyTester. * * for use by automated test by ant. * * @author Kohsuke KAWAGUCHI */ public class DTDBatchTest { public static TestSuite suite() throws Exception { return new BatchVerifyTester().createFromProperty( "dtd","DTDBatchTestDir"); } } msv-2009.1/msv/test/batch/verifier/RELAXNGBatchTest.java0000644000175000017500000000131507671171415023056 0ustar giovannigiovanni/* * @(#)$Id: RELAXNGBatchTest.java 1567 2003-06-09 20:50:21Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package batch.verifier; import junit.framework.TestSuite; /** * tests the entire RELAX test suite by using BatchVerifyTester. * * for use by automated test by ant. * * @author Kohsuke KAWAGUCHI */ public class RELAXNGBatchTest { public static TestSuite suite() throws Exception { return new BatchVerifyTester().createFromProperty( "rng","RELAXNGBatchTestDir"); } } msv-2009.1/msv/test/batch/driver/0000755000175000017500000000000011622453066016765 5ustar giovannigiovannimsv-2009.1/msv/test/batch/driver/AbstractValidatorExImpl.java0000644000175000017500000000541210005264262024352 0ustar giovannigiovannipackage batch.driver; import java.io.File; import java.io.InputStream; import javax.xml.parsers.SAXParserFactory; import org.apache.xml.resolver.tools.CatalogResolver; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import batch.WordlessErrorReporter; import batch.model.ISchema; import com.sun.msv.driver.textui.DebugController; import com.sun.msv.grammar.Grammar; import com.sun.msv.reader.GrammarReaderController; import com.sun.msv.verifier.IVerifier; import com.sun.msv.verifier.Verifier; import com.sun.msv.verifier.regexp.REDocumentDeclaration; abstract class AbstractValidatorExImpl implements IValidatorEx { public boolean validate( ISchema schema, File instance ) throws Exception { return validate( schema.asGrammar(), instance ); } public ISchema parseSchema( File schema ) throws Exception { return parseSchema( com.sun.msv.util.Util.getInputSource( schema.getAbsolutePath() ) ); } public ISchema parseSchema( InputStream source ) throws Exception { return parseSchema( new InputSource(source) ); } public ISchema parseSchema( InputSource source ) throws Exception { if( source==null ) throw new Error("this source doesn't support the getAsInputSource method"); Grammar g = parseSchema( source, createController() ); if(g==null) return null; else return new ISchemaImpl(g); } protected static SAXParserFactory factory = SAXParserFactory.newInstance(); static { factory.setNamespaceAware(true); } private final static CatalogResolver resolver = new CatalogResolver(); public boolean validate( Grammar grammar, File instance ) throws Exception { IVerifier verifier = getVerifier( grammar ); XMLReader reader = factory.newSAXParser().getXMLReader(); reader.setContentHandler(verifier); reader.setEntityResolver(resolver); WordlessErrorReporter eh = new WordlessErrorReporter(); reader.setErrorHandler(eh); verifier.setErrorHandler(eh); reader.parse( com.sun.msv.util.Util.getInputSource(instance.getAbsolutePath()) ); return verifier.isValid(); } // // overridable methods // /** * Creates an instance of GrammarReaderController that is used to * parse a schema. */ protected GrammarReaderController createController() { return new DebugController(true,false,resolver); } /** * Creates a new instance of Verifier that will be used to validate * a document. */ protected IVerifier getVerifier( Grammar grammar ) { return new Verifier( new REDocumentDeclaration(grammar), new WordlessErrorReporter() ); } } msv-2009.1/msv/test/batch/driver/IValidatorEx.java0000644000175000017500000000064707671171415022176 0ustar giovannigiovannipackage batch.driver; import org.xml.sax.InputSource; import batch.model.IValidator; import com.sun.msv.grammar.Grammar; import com.sun.msv.reader.GrammarReaderController; public interface IValidatorEx extends IValidator { Grammar parseSchema( InputSource source, GrammarReaderController controller ) throws Exception; // boolean validate( Grammar schema, XMLDocument instance ) throws Exception; } msv-2009.1/msv/test/batch/driver/DTDValidator.java0000644000175000017500000000170607671171415022121 0ustar giovannigiovannipackage batch.driver; import org.xml.sax.InputSource; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.Grammar; import com.sun.msv.reader.GrammarReaderController; import com.sun.msv.reader.dtd.DTDReader; public class DTDValidator extends AbstractValidatorExImpl { public Grammar parseSchema( InputSource is, GrammarReaderController controller ) throws Exception { Grammar g = DTDReader.parse(is,controller,new ExpressionPool() ); if(g==null) return null; return g; } /* protected String toURL( String path ) throws Exception { path = new File(path).getAbsolutePath(); if (File.separatorChar != '/') path = path.replace(File.separatorChar, '/'); if (!path.startsWith("/")) path = "/" + path; // if (!path.endsWith("/") && isDirectory()) // path = path + "/"; return new URL("file", "", path).toExternalForm(); } */ } msv-2009.1/msv/test/batch/driver/IValidatorImpl.java0000644000175000017500000001042007671171415022511 0ustar giovannigiovannipackage batch.driver; import java.io.File; import javax.xml.parsers.SAXParserFactory; import org.iso_relax.verifier.Schema; import org.iso_relax.verifier.VerifierFilter; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import batch.model.ISchema; import com.sun.msv.driver.textui.ReportErrorHandler; import com.sun.msv.grammar.Grammar; import com.sun.msv.reader.GrammarReader; import com.sun.msv.reader.GrammarReaderController; import com.sun.msv.reader.util.GrammarLoader; import com.sun.msv.verifier.IVerifier; import com.sun.msv.verifier.ValidityViolation; import com.sun.msv.verifier.Verifier; import com.sun.msv.verifier.regexp.REDocumentDeclaration; /** * Test harness for RELAX NG conformance test suite. */ public abstract class IValidatorImpl extends AbstractValidatorExImpl { /** * If true, this validator will apply extra checkes to the schema. */ private final boolean strictCheck; /** * SAXParserFactory which should be used to parse a schema. */ protected SAXParserFactory factory; public IValidatorImpl( boolean _strictCheck ) { strictCheck = _strictCheck; if(strictCheck) { // if we run a strict check, wrap it by the s4s factory = new com.sun.msv.verifier.jaxp.SAXParserFactoryImpl( getSchemaForSchema()); } else { // create a plain SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); } } /** * Gets the schema for schema for this language. */ protected Schema getSchemaForSchema() { return null; } public ISchema parseSchema( File file ) throws Exception { GrammarReader reader = getReader(); InputSource source = com.sun.msv.util.Util.getInputSource( file.getAbsolutePath()); XMLReader parser = factory.newSAXParser().getXMLReader(); if(!strictCheck) { parser.setContentHandler(reader); } else { Schema schema = getSchemaForSchema(); final boolean[] error = new boolean[1]; // set up a pipe line so that the file will be validated by s4s VerifierFilter filter = schema.newVerifier().getVerifierFilter(); filter.setErrorHandler( new ReportErrorHandler() { public void error( SAXParseException e ) throws SAXException { super.error(e); error[0]=true; } public void fatalError( SAXParseException e ) throws SAXException { super.fatalError(e); error[0]=true; } }); filter.setContentHandler(reader); parser.setContentHandler((ContentHandler)filter); if( error[0]==true ) return null; } try { parser.parse(source); } catch( ValidityViolation vv ) { System.out.println(vv.getMessage()); return null; } Grammar grammar = getGrammarFromReader(reader,file); if( grammar==null ) return null; else return new ISchemaImpl( grammar ); } public Grammar parseSchema( InputSource is, GrammarReaderController controller ) throws Exception { return GrammarLoader.loadSchema(is,createController(),factory); } /** * creates a GrammarReader object to parse a grammar. * *

* override this method to use different reader implementation. * RELAX NG test harness can be used to test XML Schema, TREX, etc. */ protected abstract GrammarReader getReader(); protected Grammar getGrammarFromReader( GrammarReader reader, File schema ) { return reader.getResultAsGrammar(); } /** * creates a Verifier object to validate a document. * *

* override this method to use a different verifier implementation. */ protected IVerifier getVerifier( Grammar grammar ) { return new Verifier( new REDocumentDeclaration(grammar), new ReportErrorHandler() ); } } msv-2009.1/msv/test/batch/driver/ISchemaImpl.java0000644000175000017500000000217007671171415021767 0ustar giovannigiovannipackage batch.driver; import batch.model.ISchema; import com.sun.msv.grammar.Grammar; import com.sun.msv.grammar.relaxng.RELAXNGGrammar; public class ISchemaImpl implements ISchema { private final Grammar grammar; public Grammar asGrammar() { return grammar; } ISchemaImpl( Grammar grammar ) { if(grammar==null) throw new Error("grammar is null"); this.grammar = grammar; } private Boolean getBool( boolean v ) { if(v) return Boolean.TRUE; else return Boolean.FALSE; } public Boolean isAnnotationCompatible() { if(!(grammar instanceof RELAXNGGrammar)) return null; return getBool(((RELAXNGGrammar)grammar).isAnnotationCompatible); } public Boolean isIdIdrefCompatible() { if(!(grammar instanceof RELAXNGGrammar)) return null; return getBool(((RELAXNGGrammar)grammar).isIDcompatible); } public Boolean isDefaultValueCompatible() { if(!(grammar instanceof RELAXNGGrammar)) return null; return getBool(((RELAXNGGrammar)grammar).isDefaultAttributeValueCompatible); } } msv-2009.1/msv/test/batch/driver/IValidatorImplForRNG.java0000644000175000017500000000122607671171415023533 0ustar giovannigiovannipackage batch.driver; import org.iso_relax.verifier.Schema; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.reader.GrammarReader; import com.sun.msv.reader.trex.ng.comp.RELAXNGCompReader; /** * Driver for MSV as XML Schema validator. */ public class IValidatorImplForRNG extends IValidatorImpl { public IValidatorImplForRNG( boolean strict ) { super(strict); } protected Schema getSchemaForSchema() { return RELAXNGCompReader.getRELAXNGSchema4Schema(); } protected GrammarReader getReader() { return new RELAXNGCompReader( createController(), factory, new ExpressionPool() ); } } msv-2009.1/msv/test/batch/driver/GenericValidator.java0000644000175000017500000000071507671171415023061 0ustar giovannigiovannipackage batch.driver; import org.xml.sax.InputSource; import com.sun.msv.grammar.Grammar; import com.sun.msv.reader.GrammarReaderController; import com.sun.msv.reader.util.GrammarLoader; /** * Generic Driver for MSV */ public class GenericValidator extends AbstractValidatorExImpl { public Grammar parseSchema( InputSource is, GrammarReaderController controller ) throws Exception { return GrammarLoader.loadSchema(is,controller); } } msv-2009.1/msv/test/batch/driver/IValidatorImplForXS.java0000644000175000017500000000205007671171415023433 0ustar giovannigiovannipackage batch.driver; import org.iso_relax.verifier.Schema; import com.sun.msv.driver.textui.ReportErrorHandler; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.Grammar; import com.sun.msv.grammar.xmlschema.XMLSchemaGrammar; import com.sun.msv.reader.GrammarReader; import com.sun.msv.reader.xmlschema.XMLSchemaReader; import com.sun.msv.verifier.IVerifier; import com.sun.msv.verifier.identity.IDConstraintChecker; /** * Driver for MSV as XML Schema validator. */ public class IValidatorImplForXS extends IValidatorImpl { public IValidatorImplForXS( boolean strict ) { super(strict); } protected Schema getSchemaForSchema() { return XMLSchemaReader.getXmlSchemaForXmlSchema(); } protected GrammarReader getReader() { return new XMLSchemaReader( createController(), factory, new ExpressionPool() ); } protected IVerifier getVerifier( Grammar grammar ) { return new IDConstraintChecker( (XMLSchemaGrammar)grammar, new ReportErrorHandler() ); } } msv-2009.1/msv/test/batch/ThrowErrorController.java0000644000175000017500000000275407671171415022532 0ustar giovannigiovanni/* * @(#)$Id: ThrowErrorController.java 1567 2003-06-09 20:50:21Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package batch; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import com.sun.msv.reader.GrammarReaderController; /** * GrammarReaderController implementation that throws an Error * when an error is found. * * useful for debug. * * @author Kohsuke KAWAGUCHI */ public class ThrowErrorController implements GrammarReaderController { private final EntityResolver resolver; public ThrowErrorController( EntityResolver resolver ) { this.resolver = resolver; } public ThrowErrorController() { this(null); } public InputSource resolveEntity(String s,String r) throws SAXException, java.io.IOException { if(resolver!=null) return resolver.resolveEntity(s,r); return null; } public void error( Locator[] locs, String msg, Exception nested ) { if( nested instanceof SAXException ) { if(((SAXException)nested).getException()!=null) ((SAXException)nested).getException().printStackTrace(); } throw new Error(msg); } public void warning( Locator[] locs, String msg ) {} } msv-2009.1/msv/examples/0000755000175000017500000000000011622453067015251 5ustar giovannigiovannimsv-2009.1/msv/examples/servlet/0000755000175000017500000000000011622453067016735 5ustar giovannigiovannimsv-2009.1/msv/examples/servlet/build.xml0000644000175000017500000002034607360440024020554 0ustar giovannigiovanni msv-2009.1/msv/examples/servlet/web/0000755000175000017500000000000011622453067017512 5ustar giovannigiovannimsv-2009.1/msv/examples/servlet/web/WEB-INF/0000755000175000017500000000000011622453067020541 5ustar giovannigiovannimsv-2009.1/msv/examples/servlet/web/WEB-INF/web.xml0000644000175000017500000000114307360440024022030 0ustar giovannigiovanni MSV Servlet Demo This servlet demonstrates how you can use MSV from your servlet to cache a grammar and validate documents. MSVDemoServlet ValidationServlet MSVDemoServlet /msvDemo msv-2009.1/msv/examples/servlet/web/index.html0000644000175000017500000000257707725722121021521 0ustar giovannigiovanni

MSV Servlet Demo client

1. Type an XML here
2. Then press this button to submit it
3. The result from the server will be shown here
        
msv-2009.1/msv/examples/servlet/src/0000755000175000017500000000000011622453067017524 5ustar giovannigiovannimsv-2009.1/msv/examples/servlet/src/ValidationServlet.java0000644000175000017500000000773507725722121024041 0ustar giovannigiovanniimport java.io.*; import javax.servlet.*; import javax.servlet.http.*; import org.xml.sax.*; import org.iso_relax.verifier.*; public class ValidationServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // just in case the browser tries to read this servlet, // redirect it to the demo page. response.sendRedirect("index.html"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String message; try { // parse the request body as an XML document InputSource document = new InputSource(request.getReader()); // create a verifier. Since multiple threads can concurrently call // the doGet method, we cannot reuse one verifier object. Verifier verifier = schema.newVerifier(); // set an error handler that do nothing. // we will call the isValid method, so we don't want an error to be thrown as an exception. verifier.setErrorHandler( silentErrorHandler ); boolean isValid = verifier.verify(document); if(isValid) message = "valid"; else message = "invalid"; } catch( VerifierConfigurationException e ) { // technically, this exception can be thrown from the newVerifier method. // but usually this is very unlikely (because we've already compiled schema // and there are not much things that can go wrong.) log("unable to create a new verifier",e); throw new ServletException(e); } catch( SAXException e ) { // verify method may throw this exception. // this usually happens when the input document is not wellformed. // so we don't send a log in this case. message = "SAXException:"+e.getMessage(); } // send a response back to the client response.setContentType("text/plain"); PrintWriter writer = response.getWriter(); writer.write(message); } /** * Compiled schema. */ private Schema schema = null; public void init() throws ServletException { super.init(); // compile a schema when the servlet is initialized // ------------------------------------------------ VerifierFactory factory = new com.sun.msv.verifier.jarv.TheFactoryImpl(); try { String schemaName = "myschema.dtd"; // in this example, we load a schema from a resource file, // which is not visible to clients. // you may want to use getServletContext().getResourceAsStream() InputStream stream = ValidationServlet.class.getResourceAsStream(schemaName); if(stream==null) throw new ServletException("unable to locate the schema resource"); InputSource is = new InputSource(stream); is.setSystemId(schemaName); schema = factory.compileSchema(is); } catch( Exception e ) { // VerifierConfigurationException and SAXException can be thrown, // but they don't have much difference in the meaning. // send the error message to a log file and abort. log( "unable to parse the schema file", e ); throw new ServletException(e); } } /** * An error handler implementation that doesn't report any error. */ private static final ErrorHandler silentErrorHandler = new ErrorHandler() { public void fatalError( SAXParseException e ) {} public void error( SAXParseException e ) {} public void warning( SAXParseException e ) {} }; } msv-2009.1/msv/examples/psvi/0000755000175000017500000000000011622453067016232 5ustar giovannigiovannimsv-2009.1/msv/examples/psvi/PSVIDump.java0000644000175000017500000001372707725722121020515 0ustar giovannigiovanni/* * @(#)$Id: PSVIDump.java 1598 2003-09-04 20:45:05Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package psvi; import com.sun.msv.datatype.DatabindableDatatype; import com.sun.msv.driver.textui.DebugController; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.util.ExpressionPrinter; import com.sun.msv.reader.util.GrammarLoader; import com.sun.msv.verifier.DocumentDeclaration; import com.sun.msv.verifier.psvi.*; import com.sun.msv.verifier.util.ErrorHandlerImpl; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.XMLReader; import org.relaxng.datatype.Datatype; import org.relaxng.datatype.ValidationContext; /** * An example that uses {@link TypedContentHandler} for obtaining * type information (AKA PSVI) of XML documents. * *

* This example shows the basic idea of accessing type information. * * @author Kohsuke KAWAGUCHI */ public class PSVIDump implements TypedContentHandler { public static void main( String[] args ) throws Exception { if( args.length!=2 ) { System.out.println("Usage: PSVIDump \n"); return; } // load a schema. GrammarLoader will detect the schema language automatically. GrammarLoader loader = new GrammarLoader(); loader.setController( new DebugController(false,false) ); DocumentDeclaration grammar = GrammarLoader.loadVGM( args[0] ); if( grammar==null ) { System.err.println("failed to load a grammar"); return; } // create an XMLReader to be used to parse the instance document SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); XMLReader reader = factory.newSAXParser().getXMLReader(); // create an instance of verifier, TypeDetector verifier = new TypeDetector(grammar, new ErrorHandlerImpl() ); // configure a pipeline so that the verifier will receive SAX events first. reader.setContentHandler(verifier); // then set your application handler to verifier. verifier.setContentHandler(new PSVIDump()); // finally, parse the document and see what happens! reader.parse(args[1]); } private int indent = 0; /** print indentation. */ private void printIndent() { for( int i=0; i"); } public void startAttribute( String namespaceUri, String localName, String qName ) { printIndent(); indent++; System.out.println("<@"+qName+">"); } public void endAttribute( String namespaceUri, String localName, String qName, AttributeExp type ) { indent--; printIndent(); System.out.print(" :"); // the type parameter is of interest here. // this parameter tells you the type assigned to this attribute. // for starter, use ExpressionPrinter to print a content model. System.out.println( ExpressionPrinter.printContentModel( type.exp.getExpandedExp(pool)) ); } public void endAttributePart() { // this method is called after all the attributes are reported. printIndent(); System.out.println("------"); } public void characterChunk( String literal, Datatype type ) { printIndent(); // type shows the assigned type. // if you are using W3C XML Schema, RELAX Core or DTD, then // this type parameter can be always casted into DatabindableDatatype. // if you are using RELAX NG, then it depends on the situation. if(!(type instanceof DatabindableDatatype)) { System.out.print("not databindable"); } else { DatabindableDatatype dt = (DatabindableDatatype)type; // the createJavaObject method can be used to convert this literal // into Java friendly object. Here, we use the context object // which is passed through the startDocument method. Object javaObject = dt.createJavaObject( literal, context ); // dump the class name for a proof that an object is actually created. System.out.print( javaObject.getClass().getName() ); } System.out.print(" : "); System.out.println(literal.trim()); // the trim method is called only to make the output cleaner. } public void endElement( String uri, String local, String qName, ElementExp type ) { indent--; printIndent(); System.out.print(" : "); // the type parameter is of interest here. // this parameter tells you the type assigned to this element. // for starter, use ExpressionPrinter to print a content model. System.out.println( ExpressionPrinter.printContentModel( type.contentModel.getExpandedExp(pool)) ); } private ValidationContext context; public void startDocument( ValidationContext context ) { // Later, this context object will be used to convert characters into // Java-friendly object. // So just store it for now. this.context = context; System.out.println("startDocument"); } public void endDocument() { System.out.println("endDocument"); } } msv-2009.1/msv/examples/errorinfo/0000755000175000017500000000000011622453067017256 5ustar giovannigiovannimsv-2009.1/msv/examples/errorinfo/ErrorReporter.java0000644000175000017500000001732607725722121022745 0ustar giovannigiovanni/* * @(#)$Id: ErrorReporter.java 1598 2003-09-04 20:45:05Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package errorinfo; import java.io.File; import java.io.FileInputStream; import javax.xml.parsers.SAXParserFactory; import com.sun.msv.verifier.ErrorInfo; import com.sun.msv.verifier.ValidityViolation; import org.iso_relax.verifier.*; import org.xml.sax.*; import org.xml.sax.helpers.XMLFilterImpl; /** * Uses {@link ErrorInfo} information to get detailed information about errors * and its source. * *

* This example takes a schema and a document, then dumps the document. * When an error is found, the error is highlighted. * *

* The purpose of this example is to illustrate how you can access * {@link ErrorInfo}, which will give you detailed information of * the error. * *

* {@link ValidityViolation} is derived from SAXParseException, so you can * always access line/column number information at least. * However, since this information is about the textual representation of * XML, it is sometimes not much useful. * *

* ErrorInfo provides high-level error information, * and therefore it is often useful to provide an * application-specific error messages to the user. * * @author Kohsuke KAWAGUCHI */ public class ErrorReporter { public static void main( String args[] ) throws Exception { if( args.length!=2 ) { System.out.println("ErrorReporter "); return; }; // control MSV through JARV. // For more information about JARV, see the jarv examples. VerifierFactory factory = new com.sun.msv.verifier.jarv.TheFactoryImpl(); // compile a schema and gets a verifier. final Verifier verifier = factory.newVerifier(new File(args[0])); // create a SAX parser SAXParserFactory parserFactory = SAXParserFactory.newInstance(); parserFactory.setNamespaceAware(true); XMLReader reader = parserFactory.newSAXParser().getXMLReader(); // then setup the SAX pipe line as follows: // // parser ==> interceptor ==> verifier // // "interceptor" works as a SAX filter. Interceptor interceptor = new Interceptor(); interceptor.setParent(reader); interceptor.setContentHandler(verifier.getVerifierHandler()); // set an error handler that throws any error. verifier.setErrorHandler( com.sun.msv.verifier.util.ErrorHandlerImpl.theInstance); // parse the file. interceptor.parse( new InputSource( new FileInputStream(args[1]) ) ); } /** * Interceptor works in this way: * *

  • * First, it receives a SAX event from the parser. * *
  • * It then passes a SAX event to the verifier, to see if it's correct. * *
    • * If there is no error, then the verifier will return without * reporting any error. So the interceptor will print it. * *
    • * If there is an error, the verfieier will report an error to ErrorHandler. * The error handler we set throws it, so Interceptor will catch it. * If the error is catched, the interceptor will print it accordingly. * */ private static class Interceptor extends XMLFilterImpl { /** * characters has to be buffered because of the way MSV works. * For more information, see the javadoc of * {@link ErrorInfo.BadText}. */ private StringBuffer buffer = new StringBuffer(); public void startElement( String ns, String local, String qname, Attributes atts ) throws SAXException { ErrorInfo ei = null; boolean unknownError = false; try { super.startElement(ns,local,qname,atts); // there is no error. } catch( ValidityViolation vv ) { // there was an error. ei = vv.getErrorInfo(); if(!(ei instanceof ErrorInfo.BadText) && !(ei instanceof ErrorInfo.BadTagName) && !(ei instanceof ErrorInfo.BadAttribute) && !(ei instanceof ErrorInfo.MissingAttribute) ) // if the type of information is unknown to us, // or ei equals to null unknownError = true; } // print the text printText( ei instanceof ErrorInfo.BadText ); printIndent(); print("<"); print( qname, unknownError || // if the error is unknown, highlight the tag name (ei instanceof ErrorInfo.BadTagName) ); for( int i=0; i\n"); indent++; } public void endElement( String ns, String local, String qname ) throws SAXException { ErrorInfo ei = null; try { super.endElement(ns,local,qname); // there is no error. } catch( ValidityViolation vv ) { // there was an error. ei = vv.getErrorInfo(); } // print the text printText(ei instanceof ErrorInfo.BadText); indent--; printIndent(); print("\n"); } public void characters( char[] buf, int start, int len ) throws SAXException { super.characters(buf,start,len); // just collect characters in this callback buffer.append(buf,start,len); } private void printText( boolean fError ) { String str = buffer.toString().trim(); if(str.length()!=0 || fError) { printIndent(); print(str, fError ); print("\n"); } // update the text buffer buffer = new StringBuffer(); } // // pretty print engine // /** indent depth. */ private int indent = 0; /** Prints whitespaces. */ private void printIndent() { for( int i=0; i msv-2009.1/msv/examples/schemaLookup/bar.xsd0000644000175000017500000000021107725722121021160 0ustar giovannigiovanni msv-2009.1/msv/examples/schemaLookup/test.xml0000644000175000017500000000006007725722121021377 0ustar giovannigiovanni msv-2009.1/msv/examples/schemaLookup/catalog.cat0000644000175000017500000000112107725721212022000 0ustar giovannigiovanni -- sample catalog file. double hyphens are used to begin and end a comment section. SYSTEM "" "" will define a simple redirection. Whenever XJC tries to load a file from , this statement will redirect it to . needs to be an absolute URI, and can be relative to the catalog file itself. PUBLIC "" "" will define a mapping from public ID to its actual location. This is only used in conjunction with DTD. -- PUBLIC "foo" "foo.xsd" PUBLIC "bar" "bar.xsd" msv-2009.1/msv/examples/schemaLookup/NamespaceScanner.java0000644000175000017500000000324007725721212023752 0ustar giovannigiovanni/* * @(#)$Id: NamespaceScanner.java 1597 2003-09-04 20:37:30Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package schemaLookup; import java.util.HashSet; import java.util.Set; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; /** * Enumerates all the namespaces from a DOM tree. * * @author * Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) */ public final class NamespaceScanner { public static void scan( Document d, NamespaceReceiver r ) { scan(d.getDocumentElement(),r); } public static void scan( Element e, NamespaceReceiver r ) { new NamespaceScanner(r).scan(e); } private final Set nss = new HashSet(); private final NamespaceReceiver receiver; private NamespaceScanner( NamespaceReceiver r ) { this.receiver = r; // xmlns nss.add("http://www.w3.org/2000/xmlns/"); } private void scan( Element e ) { onNamespace(e.getNamespaceURI()); NamedNodeMap atts = e.getAttributes(); for( int i=0; iKohsuke KAWAGUCHI */ public class JAXPWithMSVDemo { public static void main( String[] args ) throws Exception { if( args.length<2 ) { System.out.println("JAXPWithMSVDemo ..."); return; } // create SAXParserFactory that performs validation by the specified schema // this method will throw an exception if it fails to parse the document. SAXParserFactory factory = new SAXParserFactoryImpl(new File(args[0])); // once the parser factory is created, just do as you always do. factory.setNamespaceAware(true); SAXParser parser = factory.newSAXParser(); for( int i=1; iJARV to validate documents. * * @author Kohsuke KAWAGUCHI */ public class JARVDemo { public static void main( String args[] ) throws Exception { if( args.length<2 ) { System.out.println("JARVDemo ..."); return; }; /* Implementation independent way to create a VerifierFactory. This method will discover an appropriate JARV implementation and returns the factory of that implementation. To load a validator engine for RELAX NG, simply change the argument to "http://relaxng.org/ns/structure/0.9" */ // VerifierFactory factory = VerifierFactory.newInstance("http://www.w3.org/2001/XMLSchema"); /* MSV dependent way to create a VerifierFactory. But this allows MSV to detect the schema language. */ VerifierFactory factory = new com.sun.msv.verifier.jarv.TheFactoryImpl(); // parse a schema. // other overloaded methods allows you to parse a schema from InputSource, URL, etc. Verifier verifier = factory.newVerifier(new File(args[0])); // set the error handler. This object receives validation errors. // you can pass any class that implements org.sax.ErrorHandler. verifier.setErrorHandler( new ReportErrorHandler() ); // use the verify method to validate documents. // or you can validate SAX events by using the getVerifierHandler method. for( int i=1; iKohsuke KAWAGUCHI */ public class GrammarCacheDemo { public static void main( String args[] ) throws Exception { if( args.length<2 ) { System.out.println("GrammarCacheDemo ..."); return; }; /* Implementation independent way to create a VerifierFactory. This method will discover an appropriate JARV implementation and returns the factory of that implementation. To load a validator engine for RELAX NG, simply change the argument to "http://relaxng.org/ns/structure/0.9" */ // VerifierFactory factory = VerifierFactory.newInstance("http://www.w3.org/2001/XMLSchema"); /* MSV dependent way to create a VerifierFactory. But this allows MSV to detect the schema language. */ VerifierFactory factory = new com.sun.msv.verifier.jarv.TheFactoryImpl(); // compile a schema. // other overloaded methods allows you to parse a schema from InputSource, URL, etc. final Schema schema = factory.compileSchema(new File(args[0])); // launch a thread for each instance file. // this will simulate the multi-thread environment. for( int i=1; iJARV * to validate DOM documents/subtree. * * @author Kohsuke KAWAGUCHI */ public class DOMVerifier { public static void main( String[] args ) throws Exception { if(args.length<2) { System.out.println("Usage: DOMVerifier ..."); return; } // setup JARV and compile a schema. VerifierFactory factory = new com.sun.msv.verifier.jarv.TheFactoryImpl(); Verifier verifier = factory.compileSchema(args[0]).newVerifier(); // instead, you can call factory.newVerifier(args[0]) // this will result in the same behavior. // setup JAXP DocumentBuilderFactory domf = DocumentBuilderFactory.newInstance(); domf.setNamespaceAware(true); DocumentBuilder builder = domf.newDocumentBuilder(); for( int i=1; i * The XPath computed by this tool is of the form: * /foo/bar[3]/zot[2] ... * *

      * This can be used for example to point to the location of the error. * To do this, set up SAX pipeline as follows: * *

       * EventSource -> XPathLocationTracker -> Verifier -> ...
       * 
      * *

      * Then when you receive an error from a verifier, query this component * about the XPath location of the error. * * @author * Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) */ public class XPathLocationTracker extends XMLFilterImpl { public XPathLocationTracker( XMLReader r ) { super(r); } public XPathLocationTracker( ContentHandler handler ) { setContentHandler(handler); } /** * Captures the occurrences of elements among siblings. */ private static final class State { /** * Counts the occurence of element names. * Counting is done by using rawName. */ private final Map counters = new HashMap(); /** * Parent state, or null if this state governs the document element. */ private final State parent; /** * Child state, or null if it's not yet created. * *

      * To reuse {@link State} objects, we only create one child state. */ private State child; /** * Name of the current element which we are parsing right now. */ private String currentName; State( State parent ) { this.parent = parent; } /** * Accounts a new cihld element and then * returns a new child state. */ protected State push( String rawName ) { count(rawName); currentName = rawName; if(child==null) child = new State(this); else child.reset(); return child; } /** * Goes back to the parent state. */ protected State pop() { parent.currentName = null; return parent; } private void count( String rawName ) { Integer i = (Integer)counters.get(rawName); if(i==null) i = getInt(1); else i = getInt(i.intValue()+1); counters.put(rawName,i); } void reset() { counters.clear(); currentName = null; } String getXPath() { String r; if(parent==null) { // root state r = "/"; if(currentName!=null) r += currentName; } else { // child state r = parent.getXPath(); if(currentName!=null) { r += '/' + currentName; Integer i = (Integer)counters.get(currentName); r += '[' + i.toString() + ']'; } } return r; } } /** * Current state. */ private State state; public void startDocument() throws SAXException { state = new State(null); super.startDocument(); } public void endDocument() throws SAXException { super.endDocument(); state = null; } public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { state = state.push(qName); super.startElement(uri, localName, qName, atts); } public void endElement(String uri, String localName, String qName) throws SAXException { super.endElement(uri, localName, qName); state = state.pop(); } /** * Gets the XPath expression that points to the current location. * * @throws IllegalStateException * If the component is not parsing a document. */ public final String getXPath() { if(state==null) throw new IllegalStateException("startDocument event is not invoked"); return state.getXPath(); } /** * Effectively the same as

      new Integer(i)
      */ private static Integer getInt(int i) { if(i ..."); return; }; // see JARVDemo for more about how you "properly" use JARV. VerifierFactory factory = new com.sun.msv.verifier.jarv.TheFactoryImpl(); Verifier verifier = factory.newVerifier(new File(args[0])); // create a SAX Parser SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); XMLReader reader = spf.newSAXParser().getXMLReader(); // set up a pipeline VerifierHandler handler = verifier.getVerifierHandler(); XPathLocationTracker tracker = new XPathLocationTracker(handler); reader.setContentHandler(tracker); verifier.setErrorHandler( new ErrorHandlerImpl(tracker) ); for( int i=1; i MSV: RELAX NG User-Defined Datatype Libraries

      RELAX NG User-Defined Datatype Libraries

      Written by Kohsuke KAWAGUCHI

      Introduction

      The specification of RELAX NG proclaims that it can work with external datatype libraries. The implication is that you can implement your own datatype library and it should work with existing tools like MSV.

      To serve this objective, James Clark and Kohsuke KAWAGUCHI developed a datatype interface for Java, which is hosted at SourceForge.

      MSV supports this interface, so you can write your own datatype library on top of this interface and it will work with MSV. One can also expect that a datatype library developed by using this interface will work with many other RELAX NG tools as well.

      Custom datatype libraries are very flexible solutions. For example, you can write a datatype that checks the product code by querying a database.

      Sample

      For more information about how to develop a datatype library for RELAX NG, please download this (which is developed and maintained by Thai Open Source Software Center.)

      Writing Portable Schema

      One problem of using a custom datatype library is the portability; once you use it, your schema will not work with other non-Java RELAX NG tools.

      This section explains a technique to avoid this problem. Consider the following schema:

      
      <grammar datatypeLibrary="urn:custom:datatype:library">
        <start>
          <element name="root">
            <data type="myType"/>
          </element>
        </start>
      </grammar>
      

      As you see, this schema is not portable since some other tools may not recognize "myType" datatype.

      You can avoid this problem by writing two schemas. The first schema would be:

      
      <grammar>
        <start>
          <element name="root">
            <ref name="myType" />
          </element>
        </start>
        
        <define name="myType">
          <data type="string" />
        </define>
      </grammar>
      

      The point is, to provide a <define> for a datatype. This is much like writing a parameter entity for a datatype in DTD.

      Then write a second schema as follows:

      
      <grammar datatypeLibrary="urn:custom:datatype:library">
        <include name="original.rng">
          <define name="myType">
            <data type="myType" />
          </define>
        </include>
      </grammar>
      

      The first schema is portable since it doesn't use any of the custom datatype libraries. Instead it falls back to the built-in "string" type.

      The second schema is relatively short. It just overrides the definition of "myType" by using the custom datatype library. So in environments where the custom datatype library is available, you can use this schema to get a better validation.

      msv-2009.1/msv/doc/JAXPmasquerading.html0000644000175000017500000001502007356162432020231 0ustar giovannigiovanni MSV: JAXP masquerading

      JAXP Masquerading

      Written by Kohsuke KAWAGUCHI

      Introduction

      "JAXP masquerading" is a feature of MSV that allows developers to incorporate MSV into existing JAXP-based applications relatively easily.

      The key advantage of this feature is that the change to your existing code will be minimal.

      How It Works

      MSV implements the JAXP interface, which is basically a proxy (or a wrapper) to another JAXP implementation. MSV does not do any actual work except the validation; all other parsing tasks are delegated to another JAXP implementation.

      As a whole, from the application developer's perspective, this feature effectively adds the multi-schema validation capability into any JAXP parser.

      Using JAXP masquerading

      If your application is using DOM, it must have some code to create a new instance of DocumentBuilderFactory:

      // create a new parser
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      
      factory.setNamespaceAware(true);
      Document dom =
        factory.newDocumentBuilder().parse(urlOfDocument);
      
      // do something with the parsed dom
      

      To use JAXP masquerading, change the above code as shown in the following example:

      // create a new parser
      DocumentBuilderFactory factory =
        com.sun.msv.verifier.jaxp.DocumentBuilderFactoryImpl();
      
      factory.setNamespaceAware(true);
      factory.setAttribute("http://www.sun.com/xml/msv/schema",
           schemaUrl);
      
      Document dom =
        factory.newDocumentBuilder().parse(urlOfDocument);
      
      // do something with the parsed dom
      

      If your application is using SAX, it must have some code to create a new instance of SAXParserFactory:

      // create a new parser
      SAXParserFactory factory = SAXParserFactory.newInstance();
      
      factory.setNamespaceAware(true);
      
      SAXParser parser = factory.newSAXParser();
      
      // parse the document
      parser.parse(new File("abc.xml"),myHandler);
      

      To use JAXP masquerading, change the above code as shown in the following example:

      // create a new parser
      SAXParserFactory factory =
        com.sun.msv.verifier.jaxp.SAXParserFactoryImpl();
      
      factory.setNamespaceAware(true);
      
      SAXParser parser = factory.newSAXParser();
      factory.setProperty("http://www.sun.com/xml/msv/schema",
           schemaUrl);
      
      // parse the document
      parser.parse(new File("abc.xml"),myHandler);
      

      The first thing you'd notice is that it creates an instance of com.sun.msv.verifier.jaxp.***Impl instead of using the newInstance method. In this way, you can use the JAXP masquerading implementation of MSV, instead of the normal XML parser implementation.

      The next thing you'd notice is that it calls the setAttribute method or the setProperty method to set a schema. Once the schema is set, it is applied whenever a document is parsed. Although the URL of the schema is passed in this example, it can accept several types of input. For details, please read this.

      Once the schema is set, all the successive calls of the parse method will be validated with the schema. Any validation error will be reported just like any other well-formedness errors; if you set an error handler, it will receive the errors; otherwise the parse method will throw a SAXException.

      As you expect, MSV provides the multi-schema capability so you can pass a schema written in any of the supported schema languages.

      Syntax of Property

      The JAXP masquerading implementation of MSV supports only one property/attribute. All other properties/attributes will be processed by the underlying implementation.

      Name: http://www.sun.com/xml/msv/schema
      Type: java.lang.String, java.io.File, java.io.InputStream, org.xml.sax.InputSource, org.iso_relax.verifier.Schema
      Access: read-only
      Desc: Set the schema which will be used to validate documents. If a String is passed, it will be treated as the URL of the schema. If a File is passed, the schema will be parsed from that file. If an InputStream is passed, the schema will be read from that stream. If a Schema object is passed, then that schema will be used.
      Note:

      Currently, the detection of DTD is done by checking the file extension ".dtd". Therefore, if you are planning to use DTDs, then you cannot pass an InputStream (because it doesn't have a name). If you pass an InputSource, don't forget to call the setSystemId method to set the name.

      All other schemas written in XML-syntax (RELAX, W3C XML Schema, TREX and etc) will be detected correctly no matter what the format is.

      Advanced Usage

      For further advanced use, please consult the javadoc of the com.sun.msv.verifier.jaxp package. Here are several tips:

      msv-2009.1/msv/doc/JARV.html0000644000175000017500000004411510264522560015631 0ustar giovannigiovanni MSV: JARV interface

      JARV interface

      Written by Kohsuke KAWAGUCHI

      Table of Contents

      1. Introduction
      2. Architecture
      3. Using JARV
        1. Step 1: create VerifierFactory
        2. Step 2: compile a schema
        3. Step 3: create a verifier
        4. Step 4-1: perform validation
        5. Step 4-2: validation via SAX
      4. Advanced Topics
        1. Finding implementation at Run-time
        2. Fail-fast Design
        3. Creating Verifier directly from VerifierFactory
        4. Thread Affinity
        5. Schema Language Auto Detection
      5. Examples
        1. Validating bunch of files
        2. Multi-threaded example
        3. DOM validation
        4. SAX validation

      Introduction

      MSV implements JARV interface, which allows you to easily use MSV in whatever way you like. JARV is an implementation-independent interface set developed by the RELAX community and there are several implementations available that supports this interface, including MSV

      Although it came from the RELAX community, JARV is not limited to RELAX; it can be used with any schema language that MSV supports. For information about JARV, see http://iso-relax.sourceforge.net/.

      Architecture

      JARV consists of three components. VerifierFactory, Schema and Verifier.

      The VerifierFactory interface is the main interface between the implementation and your application. It has a method to compile a schema into a Schema object. The Schema interface is the internal representation of the schema. This interface is thread-safe, so you can have multiple threads access one Schema object concurrently. Also, this interface has a method to create a new Verifier object. The Verifier interface represents a so-called "validator"; it has a schema object in it and it validates documents by using that schema.

      Using JARV

      Step 1: create VerifierFactory

      The first thing you would do is to create an instance of VerifierFactory. To do that, simply create an instance of TheFactoryImpl:

      VerifierFactory factory = new com.sun.msv.verifier.jarv.TheFactoryImpl();
      

      JARV is also capable of finding an implementation that supports a particular schema language at run-time. To learn more about this discovery mechanism, please read this.

      Step 2: compile a schema

      Once you get a factory, then you can use it to compile a schema. To compile a schema, call the compileSchema method of the factory.

      Schema schema = factory.compileSchema("http://www.example.org/test.xsd");
      

      This method can accept many types of input. For example, you can pass InputSource, File, InputStream, etc.

      Schema objects are thread-safe. So even if you have more than one threads, you only need one instance of Schema; you can share that one instance with as many threads as you want.

      Step 3: create a verifier

      Schema is just a compiled schema, so it cannot do anything by itself. Verifier object is the object that performs the actual validation. To create a Verifier object, do as follows:

      Verifier verifier = schema.newVerifier();
      

      In this way, you can create a Verifier that checks documents against a particular schema.

      Verifier is not thread-safe. So typically you want to create one instance per one validation (or one thread.)

      Step 4-1: perform validation

      Verifier has several methods to validate documents. One way is to call the verify method, which accepts a DOM tree, File, URL, etc and returns the validity. For example, to validate a DOM document, simply pass it as an argument:

      if(verifier.verify(domDocument))
        // the document is valid
      else
        // the document is invalid (wrong)
      

      This method will only give you yes/no answer, but you can get more detailed error information by setting an error handler through the setErrorHandler method.

      Just like a parser reports well-formedness errores through org.xml.sax.ErrorHandler, JARV implementations (like MSV) reports validity errors through the same interface. In this way, you can get the error message, line number that caused the error, etc. For example, in the following code, a custom error handler is set to report error messages to the client.

      verifier.setErrorHandler( new MyErrorHandler() );
      try {
        if(verifier.verify(new File("abc.xml")))
          // the document is valid
        else
          // the execution will never reach here because
          // if the document is invalid, then an exception should be thrown.
      } catch( SAXParseException e ) {
        // if the document is invalid, then the execution will reach here
        // because we throw an exception for an error.
      }
      ...
      
      class MyErrorHandler implements ErrorHandler {
        public void fatalError( SAXParseException e ) throws SAXException {
          error(e);
        }
        public void error( SAXParseException e ) throws SAXException {
          System.out.println(e);
          throw e;
        }
        public void warning( SAXParseException e ) {
          // ignore warnings
        }
      }
      

      If you throw an exception from the error handler, that exception will not be catched by the verify method. So the validation is effectively aborted there. If you return from the error handler normally, then MSV will try to recover from the error and find as much errors as possible.

      Step 4-2: perform validation via SAX

      Every JARV implementation supports the validation via SAX2 in two ways.

      The first one is a validator implemented as ContentHandler, which can be obtained by calling the getVerifierHandler method. This content handler will validate incoming SAX2 events, and you can obtain the validaity through the isValid method. For example,

      XMLReader reader = ... ; // get XML reader from somewhere
      VerifierHandler handler = verifier.getVerifierHandler();
      reader.setContentHandler(handler);
      reader.parse("http://www.mydomain.com/some/file.xml");
      
      if(handler.isValid())
        // the document is correct
      else
        // the document is incorrect
      

      The second one is a validator implemented as XMLFilter, which can be obtained by calling the getVerifierFilter method.

      A verifier implemented as a filter, VerifierFilter, is particularly useful because you can plug it right in the middle of any SAX event pipeline.

      Not only you can validate documents before you process them, you can validate them after your application process them.

      In the following example, a verifier filter is used to validate documents before your own handler process it.

      VerifierFilter filter = verifier.getVerifierFilter();
      // create a new XML reader and setup the pipeline
      filter.setParent(getNewXMLReader());
      filter.setContentHandler( new MyApplicationHandler() );
      
      // parse the document
      filter.parse("http://www.mydomain.com/some/file.xml");
      if(filter.isValid())
        // the parsed document was valid
      else
        // invalid
      

      SAX-based validation will not make much sense unless you set an error handler, because to know that the document was invalid after you've processed it is too late.

      To set an error handler, call the setErrorHandler method just as you did with the verify method.

      filter = verifier.getXMLFilter();
      verifier.setErrorHandler(new MyErrorHandler());
      ...
      filter.parse(...);
      

      In this way, you can abort the processing by throwing an exception in case of an error. If you are using VerifierFilter you can also set an error handler by calling the setErrorHandler method of the VerifierFilter interface.

      MSV always runs in the fail-fast manner. So as long as you set an error handler, it is guaranteed that your application will never see incorrect document at all.

      Advanced Topics

      Finding implementation at Run-time

      A simple, obvious way to create a VerifierFactory is to create a new instance of com.sun.msv.verifier.jarv.TheFactoryImpl.

      The advantage of this way is the support of the "multi-schema" capability. The factory will accept any schema written in any of the supported languages. Thus you can instantly change the schema language without changing your code at all

      However, there is one problem in this approach. Specifically, it locks you into MSV, so you need to change your code to use other JARV implementations.

      For this reason, you may want to "discover" an implementation at run-time by calling the static newInstance method of the VerifierFactory class. To do that, you need to pass the name of schema language you want to use. This method will find an implementation that supports a given schema language from the class path and returns its VerifierFactory.

      VerifierFactory factory = VerifierFactory.newInstance(
        "http://relaxng.org/ns/structure/0,9");
      

      Usually, the namespace URI of the schema language is used as the name. For the complete list, plaese consult the javadoc.

      Fail-Fast Design

      One of the problems of some validators (like DTD validator in Xerces) is that it doesn't work in the fail-fast manner. This problem is unique to SAX.

      What is "fail-fast"? A fail-fast validator is a validator that can flag an error as soon as an error is found. A non fail-fast validator may let some part of the wrong document slip in (they will flag an error at the later moment.)

      When you are using non fail-fast validator, you need to take extra care to write your code because your code may be exposed to bad documents.

      For example, imagine a following simple DTD and a bad document:

      <!ELEMENT root (a,b)*>
      <!ELEMENT a    #EMPTY>
      <!ELEMENT b    #EMPTY>
      
      <root>
        <b/>  <!-- error -->
        <b/>
      </root>
      

      Suprisingly, in a typical non-fail-fast validator, the error will be signaled as late as in the end-element event of the root element. So you have to make sure that your application behaves gracefully when it sees the wrong 'b'.

      Typically, this robs the merit of the validation because you do the validation to protect your application code from unexpected inputs.

      MSV is a fail-fast validator; so it will signal an error at the start-element event of the first 'b'. This guarantees that the application will never see a wrong document.

      Note that some other JARV implementations may be non fail-fast validators.

      Creating Verifier directly from VerifierFactory

      The VerifierFactory class has the newVerifier method as a short-cut. It is a short-cut in the sense that the following two code fragments have exactly the same meaning:

      Verifier v = factory.compileSchema(x).newVerifier();
      
      Verifier v = factory.newVerifier(x);
      

      This is sometimes useful when you are using only one thread.

      Thread Affinity

      The VerifierFactory interface is not thread-safe. This basically means that you cannot use one object from two threads.

      The Schema interface is thread-safe. So once you compile a schema file into a Schema object, it can be shared by multiple threads and accessed concurrently. This is useful at server-side, where multiple threads process client requests simultaneously.

      The Verifier interface is again not thread-safe. Each thread needs its own copy of Verifier. Verifier objects are still re-usable, as you can use the same object to validate multiple documents one by one. What you cannot do is to validate multiple documents simultaneously.

      The thread affinity of JARV is designed after that of TrAX API (javax.transform package). Familiarity with TrAX will help you understand JARV better.

      Schema Language Auto Detection

      com.sun.msv.verifier.jarv.TheFactoryImpl automatically detects the schema language from the schema file. However, there is one important limitation. Currently, the detection of XML DTDs is based on the file extension. Specifically, if the schema name has ".dtd" extension, it is treated as XML DTD and otherwise it is treated as other schema languages.

      This causes a problem when you are passing InputStream as the parameter to the compileSchema method. Since InputStreams do not have names, they are always treated as non-DTD schemas.

      To avoid this problem, wrap it by an InputSource and call the setSystemId method to set the system id. The following example shows how to do that:

      InputSource is = new InputSource(
        MyClass.class.getResourceAsStream("abc.dtd") );
      is.setSystemId("abc.dtd");
      
      verifierFactory.compileSchema(is);
      

      This ugly limitation came from the difficulty in correctly detecting XML DTDs, which are written in non-XML syntax, from other schema languages, which are written in XML syntax.

      Any input on this restriction is very welcome.

      Examples

      If you need an example that is not listed here, please let me know so that I can add it in the next release.

      Validating bunch of files

      The distribution should contain this example at examples/jarv/jarvDemo.java. It compiles a schema and obtains a verifier object, then use the same verifier to validate multiple documents.

      Multi-threaded example

      The distribution should contain this example at examples/jarv/GrammarCacheDemo.java. This example first compiles a schema, then it launches a lot of threads and let them share one schema object.

      This example shows you how to use JARV in the multi-threaded environment and how you can cache a compiled schema into memory.

      DOM validation

      The following code shows how you can validate DOM by using JARV.

      import org.iso_relax.verifier.*;
      
      void f( org.w3c.dom.Document dom )
      {
        // create a VerifierFactory
        VerifierFactory factory = new com.sun.msv.verifier.jarv.TheFactoryImpl();
        
        // compile a RELAX schema (or whatever schema you like)
        Schema schema = factory.compileSchema( new File("foo.rxg") );
        
        // obtain a verifier
        Verifier verifier = schema.newVerifier();
        
        
        // check the validity of a DOM.
        if( verifier.verify(dom) )
          // the document is valid
        else
          // the document is not valid
        
        
        // you can use the same verifier object to test multiple DOMs
        // as long as you don't use it concurrently.
        if( verifier.verify(anotherDom) )
          ...
        
        
        // or you can pass an Element to validate that subtree.
        Element e = (Element)dom.getDocumentElement().getFirstSibling();
        if( verifier.verify(e) )
          ...
      }
      

      Passing an Element is supported by MSV, but please be warned that other JARV implementations may not support this capability.

      SAX validation

      The following code shows how you can use JARV together with JARV.

      import org.iso_relax.verifier.*;
      
      void f( javax.xml.parsers.SAXParserFactory parserFactory )
      {
        // create a VerifierFactory with the default SAX parser
        VerifierFactory factory = new com.sun.msv.verifier.jarv.TheFactoryImpl();
      
        // compile a RELAX schema (or whatever schema you like)
        Schema schema = factory.compileSchema( new File("foo.rxg") );
        
        
        
        // obtain a verifier
        Verifier verifier = schema.newVerifier();
        
        // set an error handler
        // this error handler will throw an exception if there is an error
        verifier.setErrorHandler( com.sun.msv.verifier.util.ErrorHandlerImpl.theInstance );
        
        // get a XMLFilter
        VerifierFilter filter = verifier.getVerifierFilter();
        
        // set up the pipe-line
        XMLReader reader = parserFactory.newSAXParser().getXMLReader();
        filter.setParent( reader );
        filter.setContentHandler( new MyContentHandler() );
        
        
        // parse the document
        try {
          filter.parse( "MyInstance.xml" );
          // if the execution reaches here, the document was valid and
          // there was nothing wrong.
        } catch( SAXException e ) {
          // error.
          
          // maybe the document is not well-formed, or it's not valid
          // or some other reasons.
        }
      }
      
      msv-2009.1/msv/doc/nativeAPI.html0000644000175000017500000006330107626727516016725 0ustar giovannigiovanni MSV: Native API

      Sun Multi-Schema XML Validator

      version @@VERSION@@

      Kohsuke KAWAGUCHI

      Copyright © 2001-@@YEAR@@
      Sun Microsystems, Inc.
      All Rights Reserved

      Native API

      This document describes how you can use the native API of MSV to drive it to the limit.


      Contents

      1. Design Overview
      2. Loading Schemata
      3. Playing with AGM
      4. Controlling Parsing of Schemata
      5. Validating Documents
      6. Type Assignment

      Design Overview

      MSV comprises six components.

      Component Description
      Abstract grammar model (AGM) Schema-independent grammar model. All supported schemata are parsed into this internal representation. This model, coupled with the grammar reader, may be useful for other applications.
      Grammar reader Component used to parse schemata by using SAX to construct AGMs.
      Verification grammar model (VGM) Bridge between AGM and Validator. It works as an abstraction layer between them, thereby makeing non-automaton-based algorithms possible.
      Validator Component to validate an XML instance with a VGM by using SAX.
      Datatype validator Component separately available as the Sun XML Datatypes Library.
      RELAX Namespace ("divide&validate" framework) Component that allows multiple schema languages to cooperatively validate one instance. The mplementation of this component is likely to change substantially in the future.

      Loading Schemata

      If you need finer control, then you may want to control MSV directly instead of using the generic JARV interface. This section and following sections will focus on the direct use of MSV.

      The easiest way to load a grammar is to use the loadSchema method of com.sun.msv.reader.util.GrammarLoader.


      Grammar loadGrammar( String schemaFileNameOrURL )
      {
        SAXParserFactory factory = new javax.xml.parsers.SAXParserFactory();
        // or you can use different parser like Xerces-J by
        // new org.apache.xerces.parsers.jaxp.SAXParserFactoryImpl();
      
        factory.setNamespaceAware(true);
      
        return GrammarLoader.loadSchema(
                              schemaFileNameOrURL,
                              new com.sun.msv.reader.util.IgnoreController(),
                              factory );
      }
      

      GrammarLoader automatically detects the type of schema (RELAX Core/TREX/RELAX Namespace/RELAX NG/W3C) and handles it appropriately.

      The second parameter specifies a controller object that receives notifications and controls the loading behavior. IgnoreController does nothing, but by providing a different object, you can control the parsing process.

      The third parameter specifies SAXParserFactory to be used. Factory has to be configured as namespace-aware.

      Alternatively, to load a specific language:


      import com.sun.msv.grammar.Grammar;
      import com.sun.msv.reader.trex.ng.RELAXNGReader;
      import javax.xml.parsers.SAXParserFactory;
      
      TREXGrammar loadRELAXNG( String schemaFileNameOrURL )
      {
        SAXParserFactory factory = new javax.xml.parsers.SAXParserFactory();
        factory.setNamespaceAware(true);
      
        return RELAXNGReader.parse(
                              schemaFileNameOrURL,
                              factory,
                              new com.sun.msv.reader.util.IgnoreController() );
      }
      

      The parse method also accepts several other forms of arguments (e.g., InputSource). If loading fails, the parse method returns null.

      Grammar readers implements ContentHandler, so you can also parse a grammar by the following way:


      TREXGrammar loadRELAXNG( String schemaFileNameOrURL )
      {
        RELAXNGReader reader = new RELAXNGReader( factory, new IgnoreController() );
      
        XMLReader xmlParser = new YourFavoriteXMLReader();
      
        xmlParser.setContentHandler(reader);
        xmlParser.parse(schemaFileNameOrURL);  // parse
      
        // this method returns null if loading fails.
        return reader.getResult();
      }
      

      In these ways, you can parse the XML representation of the specific language into MSV's AGM.

      Since XML DTDs are not written in XML format, they have to be parsed differently. To parse an XML DTD, do as follows


      Grammar loadDTD( String schemaFileNameOrURL )
      {
        return DTDReader.parse(
          new InputSource(schemaFileNameOrURL),
          new com.sun.msv.reader.util.IgnoreController() );
      }
      

      The first parameter specifies the InputSource object from which the DTD is read. The second paramter controls the parsing behavior. Currently, MSV cannot parse an internal DTD subset.


      Playing with AGM

      The AGM is the internal representation of a schema used by MSV. It is a binarized regular expression commonly seen in many validating processors.

      Schema Language Dependency

      The AGM consists of two parts.

      1. Core: common part of various languages. e.g., ChoiceExp, SequenceExp, MixedExp, and more. Also contains several abstract classes (ReferenceExp and ElementExp).

      2. Language-specific stubs: concrete implementations of abstract classes and composite expressions of the specific language.

      Several primitives in the core set (concur, list, and interleave) are not used by some languages. Those primitives are still placed in the core set, but the application may want to refuse to process such primitives. For example, AGMs from RELAX Core never contain ConcurExp or InterleaveExp. So an application that only processes RELAX Core can safely skip implementing concur related operations.

      You should also note that the AGM is designed to handle differences between schema languages.

      • Reference to another part of the grammar -- Most of the schema languages have a mechanism to name declarations and refer to them by name from other locations. TREX has only one mechanism (<ref>&<define>), whereas RELAX has four separate definitions/references (<tag>, <attPool>, <hedgeRule>, <elementRule> and <ref>, and <hedgeRef>). W3C XML Schema has six distinct mechanisms. To handle the difference, the core part provides an abstract ReferenceExp class, which is used as the base class that represents the referencable declaration. Language stubs then derive ReferenceExp and provide concrete implementations.

      • Constraint of tag name -- RELAX constrains tag name by a <tag> declaration, which is in turn referenced by an <elementRule> declaration. TREX constrains tag name by element declaration itself. So RELAX has one more abstraction layer between constraint over element and that over tag name. To handle such difference, the core part provides abstract ElementExp class, and stubs provide concrete implementations respectively.

      Generally speaking, you may want to avoid dependency on the stub parts. If your code only depends on the core part, then your code will work with AGMs created from any language. com.sun.msv.verifier.regexp is one of such code that works with any AGM.

      InterleaveExp is used only by RELAX NG, TREX, and W3C XML Schema Part1. ConcurExp is used solely by TREX. Application may reject those primitives if your target schema language does not use them.

      Expression and ExpressionPool

      Expression and most of the derived classes are immutable, and they have to be created through ExpressionPool. Internally, every Expression is memorized by ExpressionPool so that sub expressions can be shared and reused.

      Mixing two expressions created from two different pools is possible, but not recommended. If you are going to use MSV in a multithreaded environment, or you are going to use it in a daemon process, see "Multithreaded Environment" and "Daemon Process" respectively.

      Creating AGM From Scratch

      RELAXCoreReader/TREXGrammarReader/RELAXNSReader/XMLSchemaReader/DTDReader is just one way to create an AGM. Alternatively, you can create it from scratch.


      import com.sun.msv.grammar.trex.*;
      import com.sun.msv.grammar.*;
      
      TREXGrammar create()
      {
        ExpressionPool pool = new ExpressionPool();
        TREXGrammar g = new TREXGrammar(pool); // create an empty grammar
      
        g.start = new ElementPattern(
          // name class that constrains tag name
          new SimpleNameClass("http://namespace.uri/","tagname"),
          // content model
            pool.createMixed(
              pool.createSequence(
                new ElementPattern(
                  new SimpleNameClass("http://namespace.uri/","tagname2"),
                  pool.createEpsilon() // empty
                ),
                pool.createAttribute(
                  new SimpleNameClass("","attr"),
                  pool.createAnyString()
                )
              )
            )
          );
        // ElementPatterns are created outside ExpressionPool
      
        return g;
      }
      

      The AGM created by the above example is equivalent to the following TREX grammar.


      <element name="tagname" ns="http://namespace.uri/">
        <mixed>
          <group>
            <element name="tagname2">
              <empty />
            </element>
            <attribute name="attr" />
          </group>
        </mixed>
      </element>
      

      As you see, you have to use the ExpressionPool to create a tree of Expression. All the primitive operators are immutable.

      Also, all associative operators like choice and sequence are binary (they can only have two operands): to create an expression of (A|B|C), create (A|(B|C)) or ((A|B)|C). For more, see the JavaDoc for ExpressionPool.

      A named expression can be created as follows:


      {
        ExpressionPool pool = new ExpressionPool();
        TREXGrammar g = new TREXGrammar(pool); // create an empty grammar
      
        g.start = pool.createZeroOrMore( g.namedPatterns.getOrCreate("label") );
      
        g.namedPatterns.getOrCreate("label").exp =
            pool.createChoice( ... ); // whatever expression you like
      }
      

      You can refer to the named expression before the actual definition is provided. It is the responsibility of the application to ensure that every named expression has a definition. The grammar created by this example is equivalent to the following TREX pattern:


      <xmp>
      <grammar>
        <start>
          <zeroormore>
            <ref name="label" />
          </zeroormore>
        </start>
        <define name="label">
          <choice>
            ...
          </choice>
        </define>
      </grammar>
      </xmp>
      

      To create a RELAX AGM, use RELAXGrammar and RELAXModule as a starting point.

      Accessing AGM

      One feature that you may find useful is the "visitor" design pattern support. You can write your own visitor by implementing ExpressionVisitor. See the JavaDoc for ExpressionVisitor for details.

      Usually, this is the easiest way to access AGMs

      Manipulating AGM

      Due to the immutability of the AGM, you cannot "modify" an AGM. Instead, you create a modified AGM. To do this, use ExpressionCloner. The following example creates a new AGM that changes ChoiceExp to SequenceExp and SequenceExp to ChoiceExp.


      class SwitchChoiceAndSequence extends com.sun.msv.grammar.ExpressionCloner {
      
        private ExpressionPool pool;
      
        public Expression onSequence( SequenceExp exp ) {
          return pool.createChoice( exp.exp1, exp.exp2 );
        }
        public Expression onChoice( ChoiceExp exp ) {
          return pool.createSequence( exp.exp1, exp.exp2 );
        }
      }
      
      // usage
      Expression modifiedExp = originalExp.visit( new SwitchChoiceAndSequence() );
      

      See javadoc of ExpressionCloner for details.


      Controlling Parsing of Schemata

      Any application can use GrammarReaderController to control how a grammar is parsed. For example, it can:

      • Receive errors and warnings encountered during the parsing
      • Prohibit inclusions
      • Resolve inclusion to a different source.

      See GrammarReaderController and IgnoreController for details.


      Validating Documents

      Validation Grammar Model (VGM)

      To validate documents with a AGM, you have to "wrap" it in a VGM. The VGM can be understood as an abstraction of an AGM for the validator.

      The VGM is a simple model which consists of two interfaces only: Acceptor and DocumentDeclaration. Any VGM implementation can be used as long as it implements them.

      Currently, only one VGM implementation is available, which is placed under the com.sun.msv.verifier.regexp package.

      The following example creates a RegExp VGM from a Grammar object. Grammar is an interface implemented by RELAXGrammar, RELAXModule, TREXGrammar, and XMLSchemaGrammar.


      import com.sun.msv.verifier.regexp.REDocumentDeclaration;
      import com.sun.msv.grammar.Grammar;
      
      DocumentDeclaration createVGM( Grammar g ) {
        return new REDocumentDeclaration(g);
      }
      

      Alternatively, you can pass an arbitrary expression as the first parameter and a newly created pool as the second parameter.


      DocumentDeclaration createVGM( Expression exp ) {
        return new REDocumentDeclaration( exp, new ExpressionPool() );
      }
      

      Then VGM can be passed to the constructor of Verifier class to actually perform a validation.

      Multithreaded Environment

      AGMs are thread-safe because they are immutable. A thread can safely use an AGM parsed by a different thread; or two threads can safely share the same AGM. ExpressionPool is also thread-safe. Multiple threads can share the same pool, which is created by another thread.

      VGM, on the other hand, is not thread-safe. Each thread has to create its own VGM and use its own. You should never share a VGM between threads. Verifier is another thread-unsafe component. Also, it's not reentrant, so you can only use one object to validate one document at a time.

      When a new expression is found, it is stored to the pool. To do this, a thread has to acquire a lock. And the pool is very frequently called during validation. So you might think that sharing a pool might cause a performance bottleneck.

      However, a casual experiment shows that this is not always the case. Yes, a thread has to acquire a lock to modify the pool, but this update can be done concurrently while other threads read the pool. And update is far less frequent than retrieval. So please benchmark by yourself if you need to achieve the optimal performance.

      Daemon Process

      Generally, it's a good practice to keep re-using the same ExpressionPool. Using the same pool makes it bigger, and a bigger pool contains more expressions, which in turn results in faster validation.

      If you keep using the same ExpressionPool, it gradually expands. Its expansion is like a square-root function. It grows rapidly at first, but its growth becomes slower and slower as time goes by.

      Its size will eventually reach a certain limit, and the growth stops there. If your schema is DTD, RELAX, TREX without <interleave>, or W3C XML Schema without <all>, then this size limit is mostly moderate, so you can keep using the same pool forever.

      However, if a grammar is TREX with <interleave> patterns, or W3C XML Schema with <all>s, then the upper bound of a pool could be exponential to the size of the grammar (especially if interleave/all contains large patterns). If this is the case, and your application runs 24/7 as a daemon process, then you should occasionally throw away the pool to prevent its size from expanding indefinitely.

      Note that pool expansion is slow; the size of a pool is proportional to the number of validated documents even in the worst case. So usually it takes quite a long time to make a pool explode.

      To throw away ExpressionPool, simply create a new VGM with a brand-new pool, like this.


      DocumentDeclaration vgm = new REDocumentDeclaration( grammar.getTopLevel(), new ExpressionPool() );
      


      Type Assignment

      MSV can report the element declaration which is applied to the current element, and what datatype is applied to text. This information is useful for deciding what to do with the reported element.

      To retrieve these information, call the getCurrentElementType method of the Verifier class. This method returns the correct value only when called immediately after it processed the startElement method. If you are using com.sun.msv.verifier.VerifierFilter, then you can call this method only in your handler's startElement method.

      The following code illustrates how to retrieve RELAX "label" from your own ContentHandler.


      void startElement( .... )
      {// SAX startElement event
      
        ElementRule er = (ElementRule)currentVerifier.getCurrentElementType();
        if( er==null )
          // this may happen when the schema is complex.
          // MSV is unable to determine label/role at this moment.
        else
        {
          // er holds a reference to ElementRule object which is applied to this element.
      
          if(er.getParent()==null )
            // this element is declared by inline <element> declaration.
            // so it doesn't have any role/label
          else
          {
            final String label = er.getParent().name; // obtain label name
            final String role = er.clause.name; // obtain role name
      
            ....
          }
        }
      
        ...
      }
      

      TREX extension

      TREX doesn't have a mechanism to name the <element> pattern. Therefore, MSV introduces a proprietary extension to TREX that provides this naming mechanism.

      Annotation is done by adding a "label" attribute to the <element> pattern. The "label" attribute has to be in the "http://www.sun.com/xml/msv/trex-type" namespace. These attributes will be ignored by other TREX validating processors.


      <xmp>
      <grammar xmlns:ext="http://www.sun.com/xml/msv/trex-type">
        <start>
          <element ext:label="rootLabel" name="root">
            ...
            <element name="child"> <!-- label attribute is optional -->
              ...
            </element>
          </element>
        </start>
      </grammar>
      </xmp>
      

      The following example illustrates how to load an annotated TREX pattern.


      TREXGrammarReader reader = new TREXGrammarReader(
          myGrammarReaderControllerObject,
          saxParserFactory,
          new com.sun.msv.reader.trex.typed.TypedTREXGrammarInterceptor(),
          new ExpressionPool() );
      ((XMLReader)reader).parse(schemaFileName);
      
      // obtain parsed grammar object. it returns null in case of error
      TREXGrammar grammar = reader.getResult();
      

      The following example shows how to access TREX "label" information from your ContentHandler.


      import com.sun.msv.grammar.trex.typed.TypedElementPattern;
      
      void startElement( .... )
      {// SAX startElement event
      
        Object o = currentVerifier.getCurrentElementType();
        if( o==null )
          // this may happen when the schema is complex.
          // MSV is unable to determine label/role at this moment.
        else
        if( o instanceod TypedElementPattern )
        {
          // the current element declaration has label attribute.
      
          final String label = ((TypedElementPattern)o).label;
      
          ....
        }
        else
          // the current element declaration has no label attribute.
      
        ...
      }
      

      msv-2009.1/msv/doc/ChangeLog.txt0000644000175000017500000000576411213775530016602 0ustar giovannigiovanniFrom points unknown to 2009.1: The 2009.1 version supports multiple interrelated W3C XML Schemas. This includes support for crossreferences. The build system is now maven, and there were some other minor cleanups. From Apr,2002 version to Mar,2003 version ----------------------------------------- - fixed a problem in the DOMVerifier example. - fixed a bug regarding the inclusion of a chameleon schema. - added serialVersionUID for better Java object serialization support - fixed a bug where @final of simple types are incorrectly handled - fixed various bugs that occur when the system default encoding is not ascii compatible (such as EBCDIC). - fixed a problem where Base64BinaryType may throw ArrayIndexOutOfBoundException when the input is not a valid base64 string. - fixed a bug in the problem diagnosis code when a bad attribute value is encountered. - An external datatype loader can be specified for RELAXNGReader to override default datatype library discovery logic. - reimplemented some of the constraint check so that it is less likely to cause a StackOverflowError. - the NameClass class has more convenience methods. - modified to work with Xerces-2. - XSDatatype interface now has more methods to inspect datatype objects. - Fixed a bug reported by Danny Vint regarding multiple derivation chain of complex types with simple content. - Fixed the incorrect handling of relative URIs. Now relative URI references are properly handled for all schema languages. Thanks to Damian Gajda for pointing out this problem. - Fixed a bug in TypeDetector so that an error in an attribute is reported after the startAttribute event is fired. Thanks to Damian Gajda for this patch. From Nov,2001 version to Apr,2002 version ----------------------------------------- - The "-maxerror" option is added to the command line version of MSV. This option prohibits the "panic mode" behavior of MSV. - Changed the way XML Schema datatypes are parsed - bug fixes From 2001/09/10 version to Nov,2001 version ------------------------------------------- - RELAX NG DTD compatibility spec is supported. For details and limitations go to commandline.html. - Conformance to RELAX NG spec is improved. MSV is now intended to fully conform to the version 1 spec when the "strict schema check" switch is turned on. For details of the limitation, see commandline.html - "JAXP masquerading" feature is implemented For details, look at JAXPmasquerading.html - W3C XML Schema support is improved Several bugs (handling of attribute wildcards, etc) are fixed. - "strict" schema check is implemented Schema parser now has a switch to perform extra schema checks, at the expense of consuming more time to parse a schema. Command line tool is updated to accept the "-strict" option for this purpose. - internal representation is modified TypedStringExp is splitted into DataExp and ValueExp. - more examples are added msv-2009.1/msv/doc/acceptor.html0000644000175000017500000003120307374334310016663 0ustar giovannigiovanni MSV: Native Validation Interface

      Native Validation Interface

      Written by Kohsuke KAWAGUCHI

      Table of Contents

      1. Introduction
      2. Model
      3. Obtaining VGM
      4. Validation
      5. Context
      6. Error Reporting and Recovery
      7. Advanced Topics

      Introduction

      MSV has a native API for validation which enables better error reporting and flexible validation. This document describes this native API of MSV.

      Model

      The native API consists of two interfaces: Acceptor and DocumentDeclaration.

      DocumentDeclaration is the VGM. Its sole purpose is to create an Acceptor which validates the top level sequence, which is usually the root element.

      An Acceptor performs a validation for one content model (siblings). It can create new "child" acceptors to validate child content models, thereby validating the whole tree.

      Obtaining VGM

      One simple way to compile a schema into a VGM is to use the GrammarLoader.loadVGM method. This method takes a schema as an argument and compiles it into a AGM, then wrap it into VGM. The source code of GrammarLoader should reveal how you can create VGM in other ways.

      It is important that some schema languages may use different VGM implementations, or there might be more than one VGM implementations for one schema language.For example, right now W3C XML Schema uses com.sun.verifier.regexp.xmlschema.XSREDocDecl while all others use com.sun.verifier.regexp.REDocumentDecl. So creating a VGM from an AGM is non trivial.

      Validation

      Let's assume that we have a DocumentDeclaration object and see how we can perform a plain-vanilla validation by traversing a DOM tree.

      From the higher point of view, the validation will be done by passing information about XML document through various methods of the Acceptor interface, creating acceptors for each element.

      The first thing to do is to create an Acceptor and use it to validate the top level, as follows:

      void validate( Document dom, DocumentDeclaration docDecl ) {
        Acceptor acc = docDecl.createAcceptor();
        return validateElement(dom.getDocumentElement(),acc);
      }
      

      The validateElement method is defined here as validating a given element with a given acceptor:

      void validateElement( Element node, Acceptor acc ) {
        ...
      }
      

      Validation of an element is done by the createChildAcceptor method. This method creates a child acceptor, which will validate children of that element. This method takes a StartTagInfo as a parameter; this object holds the information about the element name and attributes (information about the start tag), and you are responsible for creating that object.

      void validateElement( Element node, Acceptor acc ) {
        org.xml.sax.helpers.AttributesImpl atts =
          /* create SAX Attributes object from attributes of this node. */
        
        // StartTagInfo uses Attributes object for keeping attributes.
        StartTagInfo sti = new StartTagInfo(
          node.getNamespaceURI(), // information about the element name.
          node.getLocalName(),
          node.getName(),
          attributes,
          context );
        
        Acceptor child = acc.createChildAcceptor(sti,null);
        if(child==null)  throw new InvalidException();
      }
      

      If there is a validation error (e.g., unexpected element), the createChildAcceptor method returns null.

      Once you create a child acceptor, the next thing to do is to validate children (attributes of that element, child elements, and texts within that element) with it. After that, call the isAcceptState method to see if the child acceptor is "satisfied". An acceptor is satisfied when the whole content model was OK.

        Acceptor child = acc.createChildAcceptor(sti,null);
        if(child==null)  throw new InvalidException();
        
        validateChildren(node,child);
        
        // test if it's OK to end the contents here.
        if(!child.isAcceptState())
          throw new InvalidException();
      

      For example, when the content model is (a,b,c) and the actual content is <a/><b/>, then the acceptor won't be satisfied because it still need to see c. So when false is returned from this method, then it means mandatory elements are missing.

      Once you make sure that the child acceptor is in a valid state, then you'll pass it back to the parent acceptor. The parent acceptor will step forward (think of it as an automaton) by eating the child acceptor.

        acc.stepForward(child);
      

      The complete code of the validateElement method will be as follows:

      void validateElement( Element node, Acceptor acc ) {
        // create StartTagInfo
        StartTagInfo sti = new StartTagInfo( ... );
        
        Acceptor child = acc.createChildAcceptor(sti,null);
        if(child==null)  throw new InvalidException();
        
        validateChildren(node,child,sti);
        
        // test if it's OK to end the contents here.
        if(!child.isAcceptState())
          throw new InvalidException();
        
        acc.stepForward(child);
      }
      

      Let's move on to the validateChildren method. First, call the onAttribute method for each attribute:

      void validateChildren( Element node, Acceptor acc, StartTagInfo sti ) {
        
        NamedNodeMap atts = node.getAttributes();
        
        for( int i=0; i<atts.getLength(); i++ ) {
          Attr a = atts.item(i);
          if( !acc.onAttribute(a.getNamespaceURI(),a.getLocalName(), ... ) )
            throw new InvalidException();
        }
      }
      

      It returns false if there is an error in the attribute (e.g., undefined attribute, or the attribute value is wrong).

      Then, call the onEndAttributes method to indicate that no more attribute is there.

        if(!acc.onEndAttributes(acc,null))
          throw new InvalidException();
      

      This method returns false when there has to be more attributes. For example, this method returns false when a mandatory attribute is missing.

      Once you processed attributes, you'll process the children (contents) of the element.

        node.normalize();
        for( Node n = node.getFirstChild(); n!=null; n=n.getNextSibling() ) {
          switch(n.getNodeType()) {
          
          case Node.ELEMENT_NODE:
            validateElement( (Element)n, acc );
            break;
          
          case Node.TEXT_NODE:
          case Node.CDATA_SECTION_NODE:
            String text = n.getNodeValue();
            
            if(!acc.onText(text,context,null,null))
              throw new InvalidException();
            break;
          }
        }
      

      It is important to normalize the DOM tree. This is because the onText method has to be called with the whole text chunk. For example, if you have an XML like <foo>abcdef</foo>, then you cannot call the onText method twice by splitting "abcdef" into two substrings.

      The onText method returns false if the text is invalid. Usually, it is because the text is not allowed there at all, or the text is invalid wrt the datatype.



      The following table summarizes atoms in XML documents and actions you have to take.

      Atom Action
      start tag call the createChildAcceptor and switch to the child acceptor
      end tag call the isAcceptState then stepForward, switch back to the parent acceptor.
      attribute call the onAttribute method. Don't forget to call the onEndAttributes.
      text call the onText method. Be careful with the normalization.

      Context

      Although I didn't mentioned in the previous section, one needs to specify a "context" object (com.sun.msv.verifier.IDContextProvider) to some of the abovementioned methods. Those objects are used to provide contextual information (like namespace prefix bindings, the base URI, etc). For example, "QName" datatype needs to resolve a namespace prefix into a namespace URI.

      You have to implement a context object by yourself and pass it to methods that need it. If you are not interested in xml:base, then you can return null from the getBaseUri method. Similarly, if you don't care about entities and notations, then you can return false from the isNotation and isUnparsedEntity methods.

      Error message and recovery

      Most of the methods on the Acceptor interface returns false to indicate a validation error. To obtain more detailed error message, pass a StringRef object to those methods.

      Consider the following example for the isAcceptState method:

        if(!acc.isAcceptState(null)) {
          // there was an error in the document.
          
          // create a StringRef object. This object will
          // receive error message.
          StringRef ref = new StringRef();
          
          // call the isAcceptState method again
          acc.isAcceptState(ref);
          
          // print the error message
          System.out.println(ref.str);
        }
      

      These methods do not change the state of the acceptor when they return false. So you can call the same method again (with a valid StringRef object) to get the error message.

      If you specify a StringRef object, the acceptor will recover from the error as a side-effect. For example, if the createChildAcceptor method returns null and you call the same method again with a StringRef, then it will return a valid child acceptor object.

        Acceptor child = parent.createChildAcceptor(sti,null);
        if(child==null) {
          // get the error message
          StringRef ref = new StringRef();
          child = parent.createChildAcceptor(sti,ref);
          
          System.out.println(ref.str);
          
          // the above statement will return a valid acceptor
          // so we can continue validating documents.
        }
        
        ...
      

      The same recovery behavior will apply for all other methods. This makes it possible to continue validation after seeing errors.

      Note that because the error recovery is highly ad-hoc, somtimes it will fall into the panic mode, in which a lot of false errors are reported. So you may want to implement some kind of filters to suppress error messages until you are sure that it gets back to sync.

      Advanced Topics

      Re-validation

      Acceptors can be always cloned by calling the createClone method. Such a clone is useful to "bookmark" a particular element of a document.

      For example, you can run the normal validation once to associate each DOM Node with Acceptor. Later, you can use that cloned acceptor to re-validate a subtree.

      Datatype Assignment

      In the onText and onAttribute methods, applications can obtain datatypes that are assigned to those text.

      To obtain this information, pass a non-null DatatypeRef object to those methods. Upon the method completion, this DatatypeRef object will receive an array of Datatypes.

      When the array is null or empty, it means there was an error or the datatype was not uniquely determined. When there is only one item in the array, it means the attribute value (or the text) is validated as that datatype. If there are more than one items in the array, it measn the attribute value (or the text) was validated as a <list> (of RELAX NG) and each datatype in the array indicates the datatype of each token.

      msv-2009.1/msv/doc/Apache-LICENSE-1.1.txt0000644000175000017500000000541307272343420017477 0ustar giovannigiovanni/* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * Portions of this software are based upon public domain software * originally written at the National Center for Supercomputing Applications, * University of Illinois, Urbana-Champaign. */ msv-2009.1/msv/doc/commandline.html0000644000175000017500000002410110000546522017336 0ustar giovannigiovanni Usage Guide For Sun Multi-Schema Validator

      Sun Multi-Schema XML Validator

      version @@VERSION@@

      Kohsuke KAWAGUCHI

      Copyright © 2001-@@YEAR@@
      Sun Microsystems, Inc.
      All Rights Reserved

      Command Line Usage Guide

      The Sun Multi-Schema Validator(MSV) is a JavaTM technology tool to validate XML documents against a variety of XML schemata. It supports RELAX Namespace, RELAX Core, RELAX NG, TREX, XML DTDs, and a subset of W3C XML Schema Part 1.

      Usage

      To validate XML documents with a RELAX grammar/module, enter a command of the following form:


      $ java -jar msv.jar MySchema.rxg MyDocument1.xml MyDocument2.xml ...

      If you'd like to use TREX, enter a command of the form:


      $ java -jar msv.jar MySchema.trex MyDocument1.xml MyDocument2.xml ...

      Or if you'd like to use W3C XML Schema, enter the command:


      $ java -jar msv.jar MySchema.xsd MyDocument1.xml MyDocument2.xml ...

      MSV will detect the schema language regardless of its file extension if the schema is written in XML syntax.

      However, DTD is only one exception. MSV relies on the file extension ".dtd" to detect XML DTDs. That means you have to have the ".dtd" extension for your DTDs. To validate XMLs with a DTD, enter the command:


      $ java -jar msv.jar my.dtd MyDocument1.xml MyDocument2.xml ...

      Some environments support wild cards for filenames, while others (e.g., "jview" VM from Microsoft) don't. You can also use a URL instead of a filename.

      If the schema contains errors, you will see messages like this.


      start parsing a grammar.
      the following hedgeRules form an infinite recursion ( y > z > y )
        18:23@file:///c:/work/relax/relax024.e.rlx
        14:23@file:///c:/work/relax/relax024.e.rlx
      failed to load a grammar.
      

      18:23@XYZ indicates that the error is located at line 18, column 23 of file XYZ.

      If the document and the schema are both valid, you will see messages like this:


      start parsing a grammar.
      validating c:\work\relax\relax001.v00.xml
      the document is valid.
      

      If the schema is valid but the document has errors, you will see messages like this:


      start parsing a grammar.
      validating c:\work\relax\relax001.n02.xml
      Error at line:5, column:5 of file:///c:/work/relax/relax001.n02.xml
        tag name "q" is not allowed. possible tag names are:
      
      the document is NOT valid.
      

      Please note that line/column infomation is sometimes inaccurate, and one tab char is counted as one character, not 4 or 8. So you might want to look around to find the actual error.

      Options

      The command line tool has several other options. You can see the list of available options by invoking MSV without any arguments.


      $ java -jar msv.jar

      Here are some notable ones that require some explanations.

      -catalog
      This option will enable the catalog support, which allows you to resolve external references to schemas/DTDs to your local copies. This can be used to avoid costly network operations to obtain a standard schema, for example.
      To use this option, you have to download resolver.jar from
      http://xml.apache.org/commons/ and place it in the same directory as msv.jar (or make it somehow available to the classpath.)
      For detailed instruction regarding how to use/configure catalogs, refer to the documentation of the entity resolver.

      Known Limitations

      DTD

      1. Attribute declarations of the form of xmlns:*** are ignored. All namespace declarations within the instance document are also ignored.

      2. The detection of XML DTD is based on the file extension. This causes a problem when you are using MSV through JARV or GrammarLoader. For details, see this.

      3. In general, MSV handles XML namespaces differently from most DTD validators. As a result, MSV may validate documents that other DTD validators reject. When this is the case, MSV always issues a warning.

      4. Strictly speaking, MSV cannot replace XML parser's DTD validation because DTD validation affects lot of other things. For example, DTD validation in XML parser can expand entity references and provides default attribute values; DTD validation by MSV doesn't do those things.

      TREX

      This implementation fully conforms to the current specification (2001-02-13 version).

      RELAX NG

      This implementation is intended to almost fully implement the spec (Aug,11,2001 version) except the followings:

      • recursive self reference check is performed after notAllowed is expanded. Therefore MSV fails to catch some of the error. (section 4.18 of the spec.)

      MSV supports RELAX NG DTD Compatibility Spec (2001/09/07). MSV implements all three features and all of them conform to level 1 (everything except infoset modification.)

      MSV supports a vendor-independent Java interface for RELAX NG datatype libraries. MSV can work with any datatype library that implements this interface. For more information, see RNGDatatypeLibrary.html.

      RELAX Core

      This implementation fully conforms to the current JIS TR specification. ( English , Japanese )

      RELAX Namespace

      <anyOtherAttribute> is not implemented.

      W3C XML Schema Part 1

      1. "Schema component constraints" and "Schema representation constraints" are not fully enforced. In other words, MSV may accept schemas that are rejected by other conforming processors.

        Unimplemented checks include (but not limited to) "UPA constraint" and "Particle Valid Restriction"

      2. "Missing sub-components" are treated as immediate errors. This behavior better serves the majority of users.

      3. Default values are ignored. In fact, no infoset contribution is supported: MSV validates documents, but it doesn't augment them. Post Schema-Validation Infoset (PSVI) is also not supported.

      Further Reading

      To learn RELAX, "How to RELAX" is a good starter. To learn TREX, there is the "TREX tutorial". RELAX NG also has its own tutorial. For W3C XML Schema Part 2, see section 2.3 of XML Schema Part 0: Primer.

      msv-2009.1/msv/doc/license.txt0000644000175000017500000000311511213775530016361 0ustar giovannigiovanniCopyright (c) 2001-2009 Sun Microsystems, Inc. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistribution in binary form must reproduct the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of Sun Microsystems, Inc. or the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. This software is provided "AS IS," without a warranty of any kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. msv-2009.1/msv/doc/README.txt0000644000175000017500000001220010233225233015656 0ustar giovannigiovanni====================================================================== README FILE FOR SUN MULTI-SCHEMA XML VALIDATOR Version @@VERSION@@ Copyright (c) Sun Microsystems, 2001-@@YEAR@@ Document written by Kohsuke Kawaguchi (kohsuke.kawaguchi@eng.sun.com) $Revision: 1662 $ ====================================================================== The Sun Multi-Schema XML Validator is a Java tool to validate XML documents against several kinds of XML schemata. It supports DTD, RELAX Namespace, RELAX Core, RELAX NG, TREX, and a subset of W3C XML Schema Part 1. This release includes software developed by the Apache Software Foundation [1]. ---------------------------------------------------------------------- OVERVIEW ---------------------------------------------------------------------- This tool is: * A command line tool that can read XML documents and validate them against a schema (DTD/RELAX/TREX/W3C). If an error is found, error messages are provided. * A library that can be incorporated into Java applications as a validator. See commandline.html for details on how to use MSV from the command line. See developer.html for details on how to use it as a library. ChangeLog.txt contains changes made from previous versions. ---------------------------------------------------------------------- LICENSE ---------------------------------------------------------------------- The most of the code is licensed under the BSD license (see license.txt). The only exception to this is a part of the code of XSDLib, which was taken from Apache, which is licensed under ASL 1.1 (see Apache-LICENSE-1.1.txt) ---------------------------------------------------------------------- TECHNICAL SUPPROT ---------------------------------------------------------------------- Sun does not provide any official support for this software. However, Kohsuke KAWAGUCHI provides personal, best-effort support for this software. Please post any questions/comments to the msv project [19] ---------------------------------------------------------------------- CURRENT STATUS ---------------------------------------------------------------------- This preview version implements: 1. XML DTD [2] 2. RELAX Core [3], based on the JIS:TR X 0029:2000 [4] specification, and enhancements based on discussions held on the mailing list relstdj [5], reluserj [6], and reldeve [7]. 3. RELAX Namespace [3], based on the draft of 2001-03-11 [8] plus enhancements based on discussions held at the same mailing list. 4. RELAX NG [14], based on the spec [15]. See commandline.html for details of limitations. 5. RELAX NG DTD compatibility extension[18]. See commandline.html for details of limitations. 6. TREX [9], based on the draft of 2001-02-13 [10] and the reference implementation [11]. The only datatype vocabulary available is W3C XML Schema Part 2 PR [12]. 7. A limited subset of W3C XML Schema Part 1 REC [13]. See commandline.html for details of limitations. 8. W3C XML Schema Part 2 REC [12] as a datatype vocabulary. For limitations, see commandline.html. ---------------------------------------------------------------------- REFERENCES ---------------------------------------------------------------------- [ 1] Apache Software Foundation http://www.apache.org/ [ 2] XML DTD http://www.w3.org/TR/REC-xml [ 3] RELAX homepage http://www.xml.gr.jp/relax/ [ 4] RELAX Core JIS:TR X 0029:2000 The original written in Japanese http://www.y-adagio.com/public/standards/tr_relax_c/toc.htm Translation to English http://www.egroups.co.jp/files/reldeve/JISTRtranslation.pdf [ 5] RELAX standardalization mailing list (Japanese) http://www2.xml.gr.jp/1ml_main.html?MLID=relax-std-j [ 6] RELAX user's mailing list (Japanese) http://www2.xml.gr.jp/1ml_main.html?MLID=relax-users-j [ 7] RELAX developer's mailing list (English) http://groups.yahoo.com/group/reldeve [ 8] RELAX Namespace specification The original writen in Japanese http://www.y-adagio.com/public/standards/tr_relax_ns/toc.htm No translation available. [ 9] TREX http://www.thaiopensource.com/trex/ [10] TREX draft specification http://www.thaiopensource.com/trex/spec.html [11] TREX reference implementation (JTREX) http://www.thaiopensource.com/trex/jtrex.html [12] W3C XML Schema Part 2: Datatypes http://www.w3.org/TR/2001/REC-xmlschema-2-20010502/ [13] W3C XML Schema Part 1: Structure http://www.w3.org/TR/2001/REC-xmlschema-1-20010502/ [14] RELAX NG http://www.oasis-open.org/committees/relax-ng/ [15] RELAX NG Spec (Upcoming version.1.0) (URL is not decided yet. follow the link from [14]) [16] RELAX NG tutorial http://www.oasis-open.org/committees/relax-ng/tutorial.html [17] RELAX NG discussion list archive http://lists.oasis-open.org/archives/relax-ng/ [18] RELAX NG DTD Compatibility Spec (Upcoming version.1.0) (URL is not decided yet. follow the link from [14]) [19] MSV project on java.net http://msv.dev.java.net/ ====================================================================== END OF README msv-2009.1/msv/doc/SAXfilter.gif0000644000175000017500000000756607357173760016557 0ustar giovannigiovanniGIF89aôb¢ÿÿÿÚÚÚ¨¨¨‚‚‚fff;;;!ùÿ,ôbÿxºÜþ0ÊI«½x À»ÿ`(v‘hª®ª0¾ð(°tmßVpDïÿÀ pH,ȤryØÄžÏRaI­Z¯Øl¯ppA¿²ÃTK.›ÏD®Žn»ßð¸¼cpΡ%û}Ïïû9:^"3‚ƒ‡ˆ‰ 3kŠŽƒy€u“–—n–…˜žaŸ¢¢’“¥£¨—š“œ©®Œl¯´‰§·µº|«°]»À|±³ÁÅp¹ŠÈÆË1½­ÌÑ1ÃÒÕ/ʈØÖÕÎŽÐÛàÔááÚp"æäÅÝwé!ßìÒãôÜ•~ðêù÷ÒîsÄ[ôË_½¡ 2[çf€ º(‡€!ó$³§1ÿXD0 ð{ØQÅ8 *Xr#BY-=öãr Ä™1i„“Òf‡Œ9Sq :ç;˜ >5Å’’âš.E5t*)£sˆ ¡Ôj2©w¸ÃÖk§ªf1u}¢ìÚ´v¾ábàbT»p7½›WV9mI¾í»G®.`ö¶w±Ú¿q´(às°ã8†Û VùAñåCh?²<"¤ÖÊEûÉ &åéÎeUÿ -»i!g<¼]»Yl”´^ôÜûíâsxƒ¨I@äM¨Èï°þÒ3%l¼ÑçÏþFù‡À?ç¾ú7O•ÖÉb'ÿf;û/Þ=€Ï=þ½tósÑ×UoßxãþÿrÄ×xRÔà1ø¦’3w î=8ÒâõDBjŽ0éñ0ƒÊó_ˆðaØsZÙ!`*9´Þ(>‘,H"Y ¡À)¹æôhS|aŒ&¶!ž*&©dë¥DÊÇ,*1ë<â'ÕîsM£.̰î…u¥]Tî qÖcåú¡ ßÖÕòV­Rs x;9¨ÿm5®4àþ}ß‹…Ur¶>ÔrnSævýµÖS¹· ;{÷'™“ÂÂO‰¨ú+‡{ÐÓá »:i ² $i:Õ*õžð"þ¨®€ÔÊ)²q‘‡‡£û!–àÏÛ‘©p·®¶ã¢ì,0~€;ë€Ð»%½» “s±Ä… øútÄÃuª¸BËD¨–5êUï}é‚¢ü)±eí!~KGøå:Âajv¤Rêv@ŒLÙÁtIa!¿=ÍÏ‚‡^ÒA—õˆ_Qñœß˜—-˜äÊ…/|Uøˆ‹.dtDjtÈ: Q(LE¤Ä§tQ‹d¤úŽ Æ;úaæ`VlÃÐÿ$¨5®= oŒ! hà p±L¶±Þ1¦FÐìàÄâ)å:”ù"G‰ ǼؾD_UDa ºE0ÄÑy˪ÆrŒ€«cC®~õ6ö•g„€©KaÄ 5ïˆ|ã©’ÄW­rá‚$rwH%²=MxåÔÅ  p%2ôŸ*÷¿ìð’0Í&÷E1â•lVˆœX‘ˆÇ³@Å`0i‹O>IvÐ%tôd%Q®.ˆ€`d.ϵˆ‘c•DãØ0¨4±ÓÀËÈ"§ðIf™¤l&&ð§öQ &(Ò;5Al œ¤ïtK×ym@Sr$=ÇXÿ͈õ“cRš£-†™BŽö¡“®Ú¦¨¼Ìásæcà&“ƥØ!èY ”—H†N¡u""®ö£Ì¹†EÓ½Êõ(M͆M¿À©wrÒ›dCK‹çO–ÒE”­Di)/q(>ö„‹0AKñ²Â9Y¢¡ kŸ‚Ô€)€1žFì%Q¿æU8ý2NíNµÏtqm pü«E°ºK¼mU-$3ÄÅd`;uÜlK²¬NÛ°XÆ‚ "%Ác3+Îfì²?á,I¸× ®ç³}B-ÎBkÇgöFpŒl&d  Â2¯J郲y¡‹ÂöKý‚n~û݈·”ð-q¹\(ÿ w¹/0nmikHêÚǶnøá¤ÛäÊs›Ðe.nÝPÚðÂFŸæUÛd%›^ñš¢¼í zÍ‹ÜÀÄŽÍASï‹#K¦¹ å/ ò»( X¾þ¥¯u›˜õ—À2pç¬ÎÅ µZ\0„bé`µ\øÂIÁ0) Œ›:x"13ýÛ1Çö ´‹€qe周?¾ÉÑpt ÙáM¤I  *0°;KMŽŽ¢e­kåN»¡7iÏÜOo·€xà˜?~Z}álB“A[FÓ•jåÈ%*W‰'¬‘?ÚĦ™,rû¤“šŒÿþ)XÿHòUk äiš¿G=wÆvâsHñWMÄSjT‚|õOêƒê4Ï7Y†vd¨‚V;â¹s{¡ò ’‘*Ç2> £'Íá*yÒlâœãmgVhí‡eVNb ‚e”mÉaéñvñðzÏC­¶)¿§?º"(ý³mbƒÞ‡ƒÇ—r¶;dÔs U(Œã-@WvOQ¸ðõ3 Ȧ!„f'Ö1AÂGÎQ-d‚2rÅt¤WC IÏV:x.öö(U7/i8v£TSR|J°„°V\È·Bwò ÓÃ3lЧ@é¦|œÃx|—&Vµ6_‚ö·xKX‚eø0ÛÿDt…7Us'+õ‚C‡ïWCág(ÑV{˜Häd3‡m sŠù·m¾S„PUˆ‡t‰‹ç|!ÇfNÈK48{U…!ÐŒ:uWNd‚Pçæ‰žsø¡'â‘"y¤æ=P%-PÛò†î׊Ò8‹ÎV‹’WI¸X‹”ÆÈŽÊˆÞ6ˆÁX€È´Žà& ¯<„2p3cÎ¥`•TqX¦|x. §ujêE!ê‡,&H€„R縌Œ†ŽÈ\Lˆwˆe僣‹„B=quŒß¥àÔ’¯"‘d8’ÙuXéD_•`³s¨BчY^^l“)flßå[ÑŠ0À"ÿQ ßøþB÷ä'9ó<ƒü÷~8Gû³$K#¹‚D[´F‹{kG»´L;Û´ù^NµRkx"}V{µX›µZ»µ\Ûµ^ûµ`¶[« b[¶f{¶h›¶hëajÛ¶nû¶pÛµ;msv-2009.1/msv/doc/developer.html0000644000175000017500000000565607626727516017103 0ustar giovannigiovanni MSV Developer's Guide

      Sun Multi-Schema XML Validator

      version @@VERSION@@

      Kohsuke KAWAGUCHI

      Copyright © 2001-@@YEAR@@
      Sun Microsystems, Inc.
      All Rights Reserved

      Developer's Guide

      The Sun Multi-Schema Validator(MSV) is a JavaTM technology tool to validate XML documents against a variety of XML schemata. It supports RELAX Namespace, RELAX Core, RELAX NG, TREX, XML DTDs, and a subset of W3C XML Schema Part 1.


      Simple API for MSV

      Most of the time, you just need plain simple validation and nothing else. If so, you can use JARV, an implementation-independent, simple and easy interface set.

      More information about JARV is available here.


      JAXP masquerading

      If you have existing code that works with JAXP and you don't want to change it, then you should have a look at the JAXP-masquerading feature of MSV.


      Native API

      If you need even more control over the validation process (for example, you are developing a schema-related tool), then you may want to understand the native API of MSV. For more information, read this document.

      msv-2009.1/msv/doc/JARV_API.gif0000644000175000017500000001270207357173760016135 0ustar giovannigiovanniGIF89aܳÿÿÿîîîÜÜÜÌÌ̸¸¸«««™™™~~~fffRRR???333!ù,ÜÿÐÉI«½8ëÍ»ÿ`(‚Oižhª®lë¾p,Ïtmßx®Ã΂üÀ pH,ȤrÉl:ŸÉDcG­Z¯Ø¬vË=9€°xL.›Ïè´zÍn»ßðøZ0íÚïø¼~ýÊÿ€‚ƒ„…bt|‰Š‹ŒW~†‘’“”•dˆŽ™š›œŠ– ¡¢£e˜§¨©ª4Ÿ¤®¯°¦«´µ¶­±º»¼—u·ÀÁÂx¹½ÆÇ£³ÃËÌÍ6ÅÈÑÒ†ÊÎÖר%ÐÓÜÝpÕÙáâ·ÛÞæçfàãëìœåèðçêíôõ|ïñùÓóöýþZøô 4ÆïŸÁƒ8\« ‡](dH1Ù¯ˆ3¶˜X±c%‡ÿC"äè±$µ‹"Sb$i²¥,”*cd鲿7˜2sÚ£i³çœ:ƒ®ãé³h: B“b#j´iJ£cêÔ(T©XiQ­êójÖ¯§¶rµé¬ÙLbǺ,{¶­'0jã¢aë¶nž´r=ҵ˗ Þ¼÷öü.à +Öñ÷ðÂÄ‹#×hìX dɘy®÷ræÏ+(sŽç´i¢G£+}ÚtjÕæX·þüv7Ù]$˜±¶í}HÃ:à Ñ÷ïh¸¹4N¼ñãÇ’oYÞ|äfè]™s¢^Ýàsì¼X;`ð`„Ý&¨#èa"Áô'8h€€{ùá&Ì£p/Á þ_ü7ÿvÝÙñxºˆç€%¬_=Œ·@ ðÀóåÇÞòý¢Ÿ†'Tø@}é9`a}þ=ày(0a‹ˆ ,â±X6B¸€…%HÁã… 0øÀ†zˆ_ ¶ØÀ<*p‘{ÊwÂ0ÞsÝŒ-‰÷bƒ>`Ÿ6["9\’E‚hæa¢¦{þIY¥#2bIŠ–'¬—â—h¢ ™^yB’Dz¤n ÈçŸy À÷f"qþ!À §tš`g™^¤¹ç‘˜Þ÷ç‘¢ÖÀ¤. €JÎǪ‹Þu%@¬²À ÆæI À0°k¬±ÂfgE —ö‰Bÿ¨›¢`™€¦ ¦ (Ð_«zp4޳–AŽ’2€„Á«ª $€áƒ`˜„@²ÈTÊå(ªçÚJë§ nzi­Á0h›"·w$¾cЃ œªkˆ € À«p`¸ê©$Ÿ 2Ú M!戒{ðÁ¬ÎÞhb´GŸ¥=î<¥Š'(Ì01'›aºŽ€‘ð0%ÒkIÊ+ƒ b§;°ÛŠíØë/.™€s赊¿È÷`›B‚=tÃE—²\ºcœÛÞbàwÒJ'ýw~?%_®…xà‹÷-xáQ«ñ÷ägPNxÊ–;8ÿá‰O¾yàmÔX_ P‰£ Z/G%ÛKrHó 4°Û4¸\ë–ÞNóè¸Ïm`Ý—,ÐÄ0*ß@;Ž” À· Ž ðý”òä7?.„¤wŸôoß°C€ @>´  ÚCÀçΠ/ßE…%ƒWß̃¯¥Y |Þ|¤0è-{¡Ÿ×+ P/ "Ó–p«¥A…ˆß!`8à,€ D”ë]0,ßx6g=8RVãÁÁ¨Ž pNžVdX±>Ø{`Eÿ`w |deEº@T  0N€Œ³¡æè.œm\ÐÅ´$+ÂŽPÞÖX<! ‹ˆJ—¼0¸FÕatGL˘ø@à‘aiKŠö.20 Œ²Û(ñö41HLj§”_ã8ž ŠA^€WãŠ7DBœ +ªõM <„y(2W†ÁAc0ÊB—Ä|Œ’•Œƒ¦ø ÷ìèX0FIn:Í;¥â܆MØ9€•RƒÈÊY,cê°XëÉ¡¶dh_†µ>Yx4q]¯\ãò¡¤M¡Ðä['œ  lónÝ„è7ÃéÂof@ÿXìSç+7€³U@ž&Bƒ=m™O1ì³…à+ƒ/§9ÐfÔ.¯!jü éx¸ª… ¶/M¯d¸!ÖäÇS¸¨†[}íYˆ"1 ò*±´ÙXîzS­âD£ p,\¢—­÷u+Æ×bm/‡XÏxàYË~¡X Hž|èëß)Ò´éPaS[šs¾G¼n!/Ï‹Þí ¨ttì®æ“®Èu„óð OXÜâÒ°Îg€UüDÅ ¯†ººß€è‰]2”ÍÝEJ¡XûL g…)Ùšð%ÎF²\êªbÏ Ÿž»´_öcJ@ÉÀ±0xìJ_NCòH–+-Gù)LV@®úf’E9{$ó¢)é›ÙÇÁ!ß]áꌔFMŠRNre`áPñY&~þ3ÿ"¸ÀAÓG˜ò¡MXE‡â›áº³KÛã¤ïyÒÅ©´¥-±Ã,–™:ÈfA‘D:oVl´£wðG ‰U¬ö‡«_]ÜœµŠºÅû†MìbûØÈN¶²—Íìf;ûÙÐŽ6ù†$j^sƒ ÷Ñ30¼ÆÎn{ûÛà·¸ÇMîr›ûÜè·¨míÀlúÑ6U-¤Øn†Ýõ~Ì»k€´Ùº]ª w¾²C|\Ø^ACKw <ßõÃo²Hc ׌pøÄÏñjoÌüæÇ°9Ðÿ“Š<“n‰ZøùÐy!ô¥ç«åw¨`n¥;=M¿z/r^…_\9Ö:Ö§ q±?ê|HÀØÂ»«›}Y;Ю©Ÿ'æ6p»ÜA÷½Ï‰î‹ò ‹¼Œ«@ï~§Dß ®ßÁ£+Vu_€xÆGbñ–ÿà7¡bw•¨x÷RØ3¯x²{œôŽÚ<'?ž<_x•G½ 0/û“ÔòvzF_ûBо÷ƒp|&T< Ãóø³7=ò5ÿS&±_þ~/}9¿ ½ Í¢_}6P¿ûõG 3£ãƒúÊ??!®Ï¬Jôê'Ä÷ãDÐñþtÔ–ù鯆ÿù󟪗 Ü÷“~¨i91€¨C¸€& x€þç€g—€ûG¦Ô€Xx8È~·‚(‚¶@‚ÿg‚ ˆ‚óæÈ‚è‚´ ‚ü'ƒHƒ«`ƒô‡ƒÿ§ƒƒèƒü„©ÀƒñG„ôg„¨€„ê§„ñÇ„ '„…ê'…à„çg…燅ÛA… q\¶1dX†fx†h˜†j¸†l؆nø†p‡r8‡mF¸mq·³‡|؇~ø‡€ˆ‚8ˆ„Xˆ†xˆˆ˜ˆˆÈ))¡…àWp¹ÖŽØ}‰v1‰ÕW‰–è˜(}š¸‰gщË÷‰ ¢ˆÿ|¤XŠYqŠº0iÐ‘Šª(¬è(A Wmàb°!‹³¨µ3V¤rjÄ…_¶Á‹½(¿èÔ.„²=°Xg‚ŒÉ¨ËÈ6CÀEl ‹ªAÕØÑðM‚6KP†E%5ê˜d¸9éˆ7dx ]Fe(k» Žã¨׸˜æ <˱¹t_ 0Ú3î•ËørKѪ3+±² PŠ“:{LÑ û(ý(9nƒŠÃ·#¬t=󱚵+汇ó‘A¿¥B[”G,iDg·’'É‘A€Ù!©y´#óHñäCB;¬dX"HYDYH ÿ)Zcgø$Ì,‰”üegs•¢=e—?A)”$7‘.i"›ãA÷eC£UKÆS]b -ô[¦Lo™Cg€LÈà‘c‰e©Ü(¬%@÷%Pk¥_~¥-> cDRz#uC‘©.@`)Õ“™éR¹=ÄdŒ˜¥OµDC 2~5—vEKz¹K´S™i ~¹™љ̸"-¤_¥˜¥ÙE@‘Q5™µTDãq™¦™´i` y%šùµ_½©dÐY™Â™C©S+n›½0›Éi¶yI<™—Ù³î9lÅYŠe9œ«I™º‚—¥Lç“Ýy ßY[ PE£5ÿ’Ðå5øRÞxY~E&‹s¹9Õùž_8sœ²IŸõé ÷Ù7ÿüY<Û2\¤ `é…¡!•š’Ùž! ð"Ÿù(¡Ê *9~ãqfÅsc¶&PZR…¶B p@î™L& `8Zœ|‰œ/ ’Ëi Äx@ÐT€îÄ?áÙ¤@à†¤.ó±TàÒÙÙó_ú“Qö>†åF8’?Yد¿®ÍÃæ@@r‰PÍeñó7Ús\瓃sRéø0ƒÃ>`Ô SÏ•^08D÷Úl·Ü3ÆlBMMµCôäÞ!æN~õë¨ÿ8˜][çÔ–Äøtê £L ,eÙÔ42%ó˜¼=1½ß÷ýSAÕ¡Ï)küß^à“°J xÜv¤¹5ÜUßP½›ã¤NáÚ`á’YñîÁ`å4+ýáµdߘõM0ÇN¦›çâp¢â’AÊãÔb•3®à#‹‘ÃÒ‰Ér>Ž@ }C"†^ËáÐé¨AXõ¡ ®ä¥-«FºŽþýäPƘÄ&ðè6ÆÔ¾åP`!~ß$E™v+ Pâ8wâ(þÆå5Û£…?%S!ZNãrÎࣙ­§T(á&nægå‘G eÚC§ÍÖÐÙ].â¯D£S6ÿT.M|NáŠÜÍQmJÇÂ7»´fáƒ+}Á,—p,ÆDÓNé1"éw[êÿ½Í‡Å ì'ì LìùfìhŒÂº~Â"ìëêìõ¦ìû+ííFíòkíÖ†íê«í¼Æíëí¯î_ÌëÀGînlîè*î£Æîáêî–ïÚ*ïŠFïÕjï†ïЪï“ÂïËêïrðÆ*ðXBðÁjð3‚ð¼ªðÂð·êðàñ²*ñØAñ­jñÐñ¨ªñÇÁñ£êñ¿òž*ò¶Aò™jò°ò”ªòªÁòêò£óŠ*óœAó…jó•ó€ªóŽÁó{êóˆíË-ô€ôvjôyoôqªôrÁôlêôAô®-õjõgjõcõIªõ\Áõ/êõUö¶¬îµGöõ)öNöÝ©öMTÄ bt_÷v÷xŸ÷z¿÷|ß÷~ÿ÷€ø‚?ø„ï÷ÔÛìÖ*±Š¿øŒßøŽˆˆù’;msv-2009.1/msv/src/0000755000175000017500000000000011622453066014221 5ustar giovannigiovannimsv-2009.1/msv/src/com/0000755000175000017500000000000011622453066014777 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/0000755000175000017500000000000011622453066015604 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/0000755000175000017500000000000011622453067016412 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/reader/0000755000175000017500000000000011622453066017653 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/reader/AbortException.java0000644000175000017500000000247007440554324023451 0ustar giovannigiovanni/* * @(#)$Id: AbortException.java 1371 2002-03-04 02:15:48Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader; /** * This exception will be thrown when the schema parsing is aborted * after all the errors are reported through GrammarReaderController. * * To throw this exception, the thrower must report an error to * the controller. This exception can be catched anytime by anyone * who can recover from the error. * The receiver shouldn't report this exception to the application, * since it has already been reported by the thrower. */ public class AbortException extends Exception { private AbortException() { super("aborted. Errors should have been reported"); } public static final AbortException theInstance = new AbortException(); /* private final Exception nestedException; public Exception getNestedException() { return nestedException; } public void printStackTrace( java.io.PrintWriter out ) { super.printStackTrace(out); if(nestedException!=null) { out.println("nested exception:"); nestedException.printStackTrace(out); } } */ } msv-2009.1/msv/src/com/sun/msv/reader/ExpressionWithChildState.java0000644000175000017500000000553410034315204025450 0ustar giovannigiovanni/* * @(#)$Id: ExpressionWithChildState.java 1634 2004-04-05 17:42:28Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader; import com.sun.msv.grammar.Expression; import com.sun.msv.util.StartTagInfo; /** * State that parses Expression which contains other expressions. * * @author Kohsuke KAWAGUCHI */ public abstract class ExpressionWithChildState extends ExpressionState implements ExpressionOwner { /** * expression object that is being created. * See {@link #castPattern} and {@link #annealPattern} methods * for how will a pattern be created. */ protected Expression exp; protected void startSelf() { super.startSelf(); exp = initialExpression(); } /** sets initial pattern */ protected Expression initialExpression() { return null; } /** * computes default expression. * this method is called before annealExpression when no child expression * is given during parsing. return null to signal an error. */ protected Expression defaultExpression() { return null; } /** receives a Pattern object that is contained in this element. */ public final void onEndChild( Expression childExpression ) { exp = castExpression( exp, childExpression ); } protected final Expression makeExpression() { if( exp==null ) exp = defaultExpression(); if( exp==null ) { reader.reportError( GrammarReader.ERR_MISSING_CHILD_EXPRESSION ); exp = Expression.nullSet; // recover by assuming some pattern. } return annealExpression(exp); } protected State createChildState( StartTagInfo tag ) { return reader.createExpressionChildState(this,tag); } /** * combines half-made expression and newly found child expression into the expression. * *

      * Say this container has three child expression exp1,exp2, and exp3. * Then, the expression of this state will be made by the following method * invocations. * *

           *   annealExpression(
           *     castExpression(
           *       castExpression(
           *         castExpression(null,exp1), exp2), exp3 ) )
           * 
      */ protected abstract Expression castExpression( Expression halfCastedExpression, Expression newChildExpression ); /** * performs final wrap-up and returns a fully created Expression object * that represents this element. */ protected Expression annealExpression( Expression exp ) { // default implementation do nothing. return exp; } } msv-2009.1/msv/src/com/sun/msv/reader/RunAwayExpressionChecker.java0000644000175000017500000001556710052717112025456 0ustar giovannigiovanni/* * @(#)$Id: RunAwayExpressionChecker.java 1641 2004-05-19 17:50:02Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader; import java.util.Set; import java.util.Stack; import java.util.Vector; import org.xml.sax.Locator; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.BinaryExp; import com.sun.msv.grammar.ChoiceExp; import com.sun.msv.grammar.ConcurExp; import com.sun.msv.grammar.DataExp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionVisitorVoid; import com.sun.msv.grammar.InterleaveExp; import com.sun.msv.grammar.ListExp; import com.sun.msv.grammar.MixedExp; import com.sun.msv.grammar.OneOrMoreExp; import com.sun.msv.grammar.OtherExp; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.SequenceExp; import com.sun.msv.grammar.UnaryExp; import com.sun.msv.grammar.ValueExp; /** * makes sure that the expression does not run away. * * "run-away" expressions are expressions like this. * * <hedgeRule label="foo" /> * <hedgeRef label="foo" /> * </hedgeRule> * * Apparently, those expressions cannot be expressed in string regular expression. * Therefore run-away expressions are prohibited in both RELAX and TREX. * * @author Kohsuke KAWAGUCHI */ public class RunAwayExpressionChecker implements ExpressionVisitorVoid { /** this exception is thrown to abort check when a error is found. */ protected static final RuntimeException eureka = new RuntimeException(); /** set of ElementExps which are already confirmed as being not a run-away exp. */ private final Set testedExps = new java.util.HashSet(); /** Expressions which are used as the content model of current element. */ private Set contentModel = new java.util.HashSet(); /** * visited Expressions. * this information is useful for the user to figure out where did they make a mistake. */ private Stack refStack = new Stack(); /** * Queue of unchecked element exps. */ private Stack unprocessedElementExps = new Stack(); private final GrammarReader reader; protected RunAwayExpressionChecker( GrammarReader reader ) { this.reader = reader; } private void check( Expression exp ) { try { exp.visit(this); while(!unprocessedElementExps.isEmpty()) { contentModel.clear(); refStack.clear(); ElementExp e = (ElementExp)unprocessedElementExps.pop(); e.contentModel.visit(this); } } catch( RuntimeException e ) { if(e!=eureka) throw e; } } public static void check( GrammarReader reader, Expression exp ) { new RunAwayExpressionChecker(reader).check(exp); } public void onAttribute( AttributeExp exp ) { enter(exp); exp.exp.visit(this); leave(); } public void onConcur( ConcurExp exp ) { binaryVisit(exp); } public void onInterleave( InterleaveExp exp ) { binaryVisit(exp); } public void onSequence( SequenceExp exp ) { binaryVisit(exp); } public void onChoice( ChoiceExp exp ) { binaryVisit(exp); } public void onOneOrMore( OneOrMoreExp exp ) { unaryVisit(exp); } public void onMixed( MixedExp exp ) { unaryVisit(exp); } public void onList( ListExp exp ) { unaryVisit(exp); } public void onEpsilon() {} public void onNullSet() {} public void onAnyString() {} public void onData( DataExp exp ) {} public void onValue( ValueExp exp ) {} protected final void binaryVisit( BinaryExp exp ) { // do the tail recursion to avoid StackOverflowError as much as possible int cnt=0; while(true) { enter(exp); cnt++; exp.exp2.visit(this); if( exp.exp1 instanceof BinaryExp ) exp = (BinaryExp)exp.exp1; else break; } exp.exp1.visit(this); for( ; cnt>0; cnt-- ) leave(); } protected final void unaryVisit( UnaryExp exp ) { enter(exp); exp.exp.visit(this); leave(); } private void enter( Expression exp ) { if(contentModel.contains(exp)) { // this indicates that we have reached the same expression object // without visiting any ElementExp. // so this one is a run-away expression. // check stack to find actual sequence of reference. String s = ""; int i = refStack.indexOf(exp); int sz = refStack.size(); Vector locs = new Vector(); for( ; iKohsuke KAWAGUCHI */ public class InterleaveState extends ExpressionWithChildState { protected Expression castExpression( Expression exp, Expression child ) { // first one. if( exp==null ) return child; return reader.pool.createInterleave(exp,child); } } msv-2009.1/msv/src/com/sun/msv/reader/IgnoreState.java0000644000175000017500000000221307671170035022741 0ustar giovannigiovanni/* * @(#)$Id: IgnoreState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader; import org.xml.sax.Attributes; /** * state that ignores the entire subtree. * * @author Kohsuke KAWAGUCHI */ public class IgnoreState extends State { // the parent state receives startElement event for this state. // so we have to start from one, rather than zero. private int depth = 1; public final void startElement(String namespaceURI, String localName, String qName, Attributes atts) { depth++; } public final void endElement(String namespaceURI, String localName, String qName) { depth--; if (depth == 0) reader.popState(); } public final void endDocument() { // assert depth==0 reader.popState(); } public void characters(char[] buffer, int from, int len) { // ignore literals } } msv-2009.1/msv/src/com/sun/msv/reader/SimpleState.java0000644000175000017500000001032511156747174022761 0ustar giovannigiovanni/* * @(#)$Id: SimpleState.java 1744 2009-03-14 15:34:20Z bimargulies $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.helpers.AttributesImpl; import com.sun.msv.util.StartTagInfo; /** * base interface of the most of parsing states. * *

      * In this level of inheritance, contract is as follows. * *

        *
      1. startElement() event is received by the parent state. * It usually creates a child state by this event. * *
      2. startSelf method of the child SimpleState is called. * derived classes should perform necessary things * by reading start tag information. * *
      3. Whenever startElement method is received by * SimpleState object, createChildState method is * called to create a child state. * Derived classes are responsible for providing * appropriate child state objects. * *
      4. Child state handles descendants. Usually, it finishes * parsing when it sees endElement. * *
      5. When endElement() event is received by this object, * it calls endSelf method and reverts to the parent state. * Derived classes are responsible for doing anything * necessary within endSelf method. *
      * * In other words, this state is only active for one hierarchy of XML elements * and derived classes are responsible for three abstract methods. * * @author Kohsuke KAWAGUCHI */ public abstract class SimpleState extends State { /** checks if this element belongs to the grammar. */ protected boolean isGrammarElement( StartTagInfo tag ) { return reader.isGrammarElement(tag); } public void startElement( String namespaceURI, String localName, String qName, Attributes atts ) { final StartTagInfo tag = new StartTagInfo( namespaceURI,localName,qName,new AttributesImpl(atts)); // we have to copy Attributes, otherwise it will be mutated by SAX parser if( isGrammarElement(tag) ) { // this is a grammar element. // creates appropriate child state for it. State nextState = createChildState(tag); if(nextState!=null) { reader.pushState(nextState,this,tag); return; } // unacceptable element reader.reportError(GrammarReader.ERR_MALPLACED_ELEMENT, tag.qName ); // try to recover from error by just ignoring it. } else { // usually, foreign elements are silently ignored. // However, for the document element, we have to report an error if( parentState==null ) { reader.reportError(GrammarReader.ERR_MALPLACED_ELEMENT, tag.qName ); // probably user is using a wrong namespace. reader.reportError(GrammarReader.WRN_MAYBE_WRONG_NAMESPACE, tag.namespaceURI ); } } // element of a foreign namespace. skip subtree reader.pushState(new IgnoreState(),this,tag); } /** creates appropriate child state object for this element */ abstract protected State createChildState( StartTagInfo tag ); public final void endElement( String namespaceURI, String localName, String qName ) { // while processing endSelf, error should be reported for its start tag. Locator prevLoc = reader.getLocator(); try { reader.setLocator(this.location); endSelf(); } finally { reader.setLocator(prevLoc); } reader.popState(); } public final void endDocument() { // top-level state receives endDocument event instead of endElement event. endSelf(); reader.popState(); } /** * this method is called in endElement method * when the state is about to be removed. * * derived-class should perform any wrap-up job */ protected void endSelf() {} } msv-2009.1/msv/src/com/sun/msv/reader/package.html0000644000175000017500000000013007260744467022141 0ustar giovannigiovanni

      reads XML representation of grammar and creates AGM.

      msv-2009.1/msv/src/com/sun/msv/reader/ChoiceState.java0000644000175000017500000000204107671170035022707 0ustar giovannigiovanni/* * @(#)$Id: ChoiceState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader; import com.sun.msv.grammar.Expression; /** * state that creates ChoiceExp. * * @author Kohsuke KAWAGUCHI */ public class ChoiceState extends ExpressionWithChildState { public ChoiceState() { this(false); } public ChoiceState( boolean allowEmptyChoice ) { this.allowEmptyChoice = allowEmptyChoice; } protected boolean allowEmptyChoice; protected Expression initialExpression() { return allowEmptyChoice?Expression.nullSet:null; } protected Expression castExpression( Expression exp, Expression child ) { // first one. if( exp==null ) return child; else return reader.pool.createChoice(exp,child); } } msv-2009.1/msv/src/com/sun/msv/reader/Messages_ja.properties0000644000175000017500000000475607440542635024232 0ustar giovannigiovanni GrammarReader.MalplacedElement =\ "{0}"\u8981\u7D20\u306F\u3053\u3053\u306B\u306F\u66F8\u3051\u307E\u305B\u3093 GrammarReader.BadType =\ {0} GrammarReader.Characters =\ \u30AD\u30E3\u30E9\u30AF\u30BF\u30C7\u30FC\u30BF\u306F\u8A31\u3055\u308C\u307E\u305B\u3093: {0} GrammarReader.DisallowedAttribute =\ "{0}"\u8981\u7D20\u306B"{1}"\u5C5E\u6027\u3092\u6307\u5B9A\u3059\u308B\u3053\u3068\u306F\u51FA\u6765\u307E\u305B\u3093 GrammarReader.MissingAttribute =\ "{0}"\u8981\u7D20\u306B\u306F"{1}"\u5C5E\u6027\u304C\u5FC5\u8981\u3067\u3059\u304C\u3001\u6307\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093 GrammarReader.MissingAttribute.2 =\ "{0}"\u8981\u7D20\u306B\u306F"{1}"\u5C5E\u6027\u304B"{2}"\u5C5E\u6027\u304C\u5FC5\u8981\u3067\u3059\u304C\u3001\u6307\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093 GrammarReader.BadAttributeValue =\ "{1}"\u306F"{0}"\u5C5E\u6027\u306B\u6307\u5B9A\u3067\u304D\u308B\u5024\u3067\u306F\u3042\u308A\u307E\u305B\u3093 GrammarReader.ConflictingAttribute =\ "{0}"\u5C5E\u6027\u3068"{1}"\u5C5E\u6027\u306F\u80CC\u53CD\u306A\u306E\u3067\u3001\u540C\u6642\u306B\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093 GrammarReader.Abstract.MoreThanOneChildType =\ \u8907\u6570\u306E\u5B50\u4F9B\u304C\u6307\u5B9A\u3055\u308C\u3066\u3044\u307E\u3059 GrammarReader.Abstract.MissingChildType =\ \u5B50\u4F9B\u306E\u6307\u5B9A\u304C\u3042\u308A\u307E\u305B\u3093 GrammarReader.IllegalFinalValue = \ "{0}"\u306F\u7121\u52B9\u306Afinal\u5C5E\u6027\u306E\u5024\u3067\u3059 GrammarReader.RecursiveInclude =\ \u518D\u5E30\u7684\u306A\u30A4\u30F3\u30AF\u30EB\u30FC\u30C9\u304C\u898B\u3064\u304B\u308A\u307E\u3057\u305F ( {0} ) GrammarReader.FragmentIdentifier = \ URL "{0}"\u306B\u306F\u30D5\u30E9\u30B0\u30E1\u30F3\u30C8\u8B58\u5225\u5B50\u304C\u542B\u307E\u308C\u3066\u3044\u307E\u3059 GrammarReader.UndefinedDataType =\ \u30C7\u30FC\u30BF\u578B"{0}"\u306F\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u305B\u3093 GrammarReader.DataTypeAlreadyDefined =\ \u30C7\u30FC\u30BF\u578B"{0}"\u306F\u65E2\u306B\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u3059 GrammarReader.Warning.MaybeWrongNamespace = \ \u6050\u3089\u304Fnamespace URI "{0}"\u304C\u9593\u9055\u3063\u3066\u3044\u307E\u3059 GrammarReader.Warning.DeprecatedTypeName =\ "{0}"\u306F\u53E4\u3044\u540D\u524D\u3067\u3059\u3002"{1}"\u3092\u4EE3\u308F\u308A\u306B\u4F7F\u3063\u3066\u304F\u3060\u3055\u3044 GrammarReader.RecursiveDatatypeDefinition =\ \u30C7\u30FC\u30BF\u578B\u304C\u5FAA\u74B0\u3057\u3066\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u3059 msv-2009.1/msv/src/com/sun/msv/reader/relax/0000755000175000017500000000000011622453066020766 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/reader/relax/ElementRefState.java0000644000175000017500000000124307671170035024661 0ustar giovannigiovanni/* * @(#)$Id: ElementRefState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax; import com.sun.msv.grammar.Expression; /** * parses <ref label="..." /> element. * * @author Kohsuke KAWAGUCHI */ public class ElementRefState extends LabelRefState { protected final Expression resolve( String namespace, String label ) { return ((RELAXReader)reader).resolveElementRef(namespace,label); } } msv-2009.1/msv/src/com/sun/msv/reader/relax/package.html0000644000175000017500000000014107266664043023253 0ustar giovannigiovanni

      common parts for parseing RELAX Core/Namespace into AGM.

      msv-2009.1/msv/src/com/sun/msv/reader/relax/core/0000755000175000017500000000000011622453066021716 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/reader/relax/core/RELAXCoreReader.java0000644000175000017500000005001710034315204025356 0ustar giovannigiovanni/* * @(#)$Id: RELAXCoreReader.java 1634 2004-04-05 17:42:28Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax.core; import java.util.Iterator; import java.util.Map; import javax.xml.parsers.SAXParserFactory; import org.iso_relax.verifier.Schema; import org.relaxng.datatype.DatatypeException; import org.xml.sax.InputSource; import org.xml.sax.Locator; import com.sun.msv.datatype.xsd.DatatypeFactory; import com.sun.msv.datatype.xsd.XSDatatype; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.Grammar; import com.sun.msv.grammar.ReferenceContainer; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.relax.AttPoolClause; import com.sun.msv.grammar.relax.EmptyStringType; import com.sun.msv.grammar.relax.Exportable; import com.sun.msv.grammar.relax.HedgeRules; import com.sun.msv.grammar.relax.NoneType; import com.sun.msv.grammar.relax.RELAXModule; import com.sun.msv.grammar.relax.TagClause; import com.sun.msv.reader.ExpressionState; import com.sun.msv.reader.GrammarReaderController; import com.sun.msv.reader.RunAwayExpressionChecker; import com.sun.msv.reader.State; import com.sun.msv.reader.datatype.xsd.XSDVocabulary; import com.sun.msv.reader.datatype.xsd.XSDatatypeExp; import com.sun.msv.reader.datatype.xsd.XSDatatypeResolver; import com.sun.msv.reader.relax.RELAXReader; import com.sun.msv.reader.relax.core.checker.DblAttrConstraintChecker; import com.sun.msv.reader.relax.core.checker.ExportedHedgeRuleChecker; import com.sun.msv.reader.relax.core.checker.IdAbuseChecker; import com.sun.msv.util.StartTagInfo; /** * reads RELAX module (classic RELAX module; no namespace extension) * by SAX2 and constructs abstract grammar model. * * This class does not recognize extensions introduced by RELAX Namespace * (like anyOtherElement, or <ref label="..." namespace="..." />. * * @author Kohsuke KAWAGUCHI */ public class RELAXCoreReader extends RELAXReader implements XSDatatypeResolver { /** loads RELAX module */ public static RELAXModule parse( String moduleURL, SAXParserFactory factory, GrammarReaderController controller, ExpressionPool pool ) { RELAXCoreReader reader = new RELAXCoreReader(controller,factory,pool); reader.parse(moduleURL); return reader.getResult(); } /** loads RELAX module */ public static RELAXModule parse( InputSource module, SAXParserFactory factory, GrammarReaderController controller, ExpressionPool pool ) { RELAXCoreReader reader = new RELAXCoreReader(controller,factory,pool); reader.parse(module); return reader.getResult(); } /** * Schema for schema of RELAX Core. * * Unless overrided, this schema for schema will be used to parse a RELAX Core schema. * To override, call the full constructor of this class and change the parameter. */ protected static Schema relaxCoreSchema4Schema = null; public static Schema getRELAXCoreSchema4Schema() { // under the multi-thread environment, more than once s4s could be loaded. // it's a waste of resource, but by no means fatal. if(relaxCoreSchema4Schema==null) { try { relaxCoreSchema4Schema = new com.sun.msv.verifier.jarv.RELAXCoreFactoryImpl().compileSchema( RELAXCoreReader.class.getResourceAsStream("relaxCore.rlx")); } catch( Exception e ) { e.printStackTrace(); throw new Error("unable to load schema-for-schema for RELAX Core"); } } return relaxCoreSchema4Schema; } public RELAXCoreReader( GrammarReaderController controller, SAXParserFactory parserFactory, ExpressionPool pool ) { this(controller,parserFactory,new StateFactory(),pool,null); } /** * full constructor. * * @param stateFactory * this object creates all parsing state object. * Parsing behavior can be modified by changing this object. * @param expectedTargetNamespace * expected value of 'targetNamespace' attribute. * If this value is null, then the module must have 'targetNamepsace' * attribute. If this value is non-null and module doesn't have * targetNamespace attribute, then expectedTargetNamespace is used * as the module's target namespace (chameleon effect). * If expectedNamespace differs from the module's targetNamespace attribute, * then an error will be issued. */ public RELAXCoreReader( GrammarReaderController controller, SAXParserFactory parserFactory, StateFactory stateFactory, ExpressionPool pool, String expectedTargetNamespace) { super(controller,parserFactory,stateFactory,pool,new RootModuleState(expectedTargetNamespace)); } /** * RELAX module object being under construction. * * object is created when target namespace is identified. */ protected RELAXModule module; /** obtains parsed grammar object only if parsing was successful. */ public final RELAXModule getResult() { if(controller.hadError()) return null; else return module; } public final Grammar getResultAsGrammar() { return getResult(); } /** * contains all expressions that are going to be combined. * ReferenceExp is used to wrap an expression to provide location information. * (attPool element with combine attribute). */ protected final ReferenceContainer combinedAttPools = new ReferenceContainer(){ protected ReferenceExp createReference( String name ) { return new ReferenceExp(name); } }; protected boolean isGrammarElement( StartTagInfo tag ) { if( !RELAXCoreNamespace.equals(tag.namespaceURI) ) return false; // annotation is ignored at this level. // by returning false, the entire subtree will be simply ignored. if(tag.localName.equals("annotation")) return false; return true; } /** * User-defined datatypes (from type name to XSDatatypeExp object. */ private final Map userDefinedTypes = new java.util.HashMap(); public final void addUserDefinedType( XSDatatypeExp exp ) { userDefinedTypes.put( exp.name, exp ); } /** * gets DataType object from type name. * * If undefined type name is specified, this method is responsible * to report an error, and recovers. */ public XSDatatypeExp resolveXSDatatype( String typeName ) { // look up user defined types first try { XSDatatypeExp e = (XSDatatypeExp)userDefinedTypes.get(typeName); if(e!=null) return e; // then try as a built-in type // if this method fails, it throws an exception return new XSDatatypeExp( DatatypeFactory.getTypeByName(typeName), pool ); } catch( DatatypeException e ) { XSDatatype dt = getBackwardCompatibleType(typeName); if(typeName.equals("none")) dt = NoneType.theInstance; if(typeName.equals("emptyString")) dt = EmptyStringType.theInstance; if(dt==null) { reportError( ERR_UNDEFINED_DATATYPE, typeName ); dt = NoneType.theInstance; // recover by assuming a valid DataType } return new XSDatatypeExp( dt, pool ); } } public static class StateFactory extends RELAXReader.StateFactory { protected State mixed(State parent,StartTagInfo tag) { return new MixedState(); } protected State element(State parent,StartTagInfo tag) { return new InlineElementState(); } protected State attribute(State parent,StartTagInfo tag) { return new AttributeState(); } protected State refRole(State parent,StartTagInfo tag) { return new AttPoolRefState(); } protected State divInModule(State parent,StartTagInfo tag) { return new DivInModuleState(); } protected State hedgeRule(State parent,StartTagInfo tag) { return new HedgeRuleState(); } protected State tag(State parent,StartTagInfo tag) { return new TagState(); } protected State tagInline(State parent,StartTagInfo tag) { return new InlineTagState(); } protected State attPool(State parent,StartTagInfo tag) { return new AttPoolState(); } protected State include(State parent,StartTagInfo tag) { return new IncludeModuleState(); } protected State interface_(State parent,StartTagInfo tag) { return new InterfaceState(); } protected State elementRule(State parent,StartTagInfo tag) { if(tag.containsAttribute("type")) return new ElementRuleWithTypeState(); else return new ElementRuleWithHedgeState(); } protected XSDVocabulary vocabulary = new XSDVocabulary(); protected State simpleType( State parent, StartTagInfo tag) { return vocabulary.createTopLevelReaderState(tag); } } protected final StateFactory getStateFactory() { return (StateFactory)super.sfactory; } public State createExpressionChildState( State parent, StartTagInfo tag ) { if(! RELAXCoreNamespace.equals(tag.namespaceURI) ) return null; if(tag.localName.equals("mixed")) return getStateFactory().mixed(parent,tag); if(tag.localName.equals("element")) return getStateFactory().element(parent,tag); return super.createExpressionChildState(parent,tag); } /** returns true if the given state can have "occurs" attribute. */ protected boolean canHaveOccurs( ExpressionState state ) { return super.canHaveOccurs(state) || state instanceof InlineElementState; } protected Expression resolveElementRef( String namespace, String label ) { if( namespace!=null ) { reportError( ERR_NAMESPACE_NOT_SUPPROTED ); return Expression.nullSet; } Expression exp = module.elementRules.getOrCreate(label); backwardReference.memorizeLink(exp); return exp; } protected Expression resolveHedgeRef( String namespace, String label ) { if( namespace!=null ) { reportError( ERR_NAMESPACE_NOT_SUPPROTED ); return Expression.nullSet; } Expression exp = module.hedgeRules.getOrCreate(label); backwardReference.memorizeLink(exp); return exp; } protected Expression resolveAttPoolRef( String namespace, String role ) { if( namespace!=null ) { reportError( ERR_NAMESPACE_NOT_SUPPROTED ); return Expression.nullSet; } AttPoolClause c = module.attPools.getOrCreate(role); backwardReference.memorizeLink(c); return c; } protected void wrapUp() { runBackPatchJob(); // register user-defined types to the module Iterator itr = userDefinedTypes.entrySet().iterator(); while( itr.hasNext() ) { XSDatatypeExp e = (XSDatatypeExp)((Map.Entry)itr.next()).getValue(); module.datatypes.add(e.getCreatedType()); } // combine expressions to their masters. // if no master is found, then create a new AttPool. { ReferenceExp[] combines = combinedAttPools.getAll(); for ( int i=0; i for hedgeRule, // detect label collision. // it is prohibited for elementRule and hedgeRule to share the same label. detectCollision( module.elementRules, module.hedgeRules, ERR_LABEL_COLLISION ); detectDoubleAttributeConstraints( module ); // checks ID abuse IdAbuseChecker.check( this, module ); // supply top-level expression. Expression exp = pool.createChoice( choiceOfExported( module.elementRules ), choiceOfExported( module.hedgeRules ) ); if( exp==Expression.nullSet ) // at least one element must be exported or // the grammar accepts nothing. reportWarning( WRN_NO_EXPROTED_LABEL ); module.topLevel = exp; // make sure that there is no recurisve hedge rules. RunAwayExpressionChecker.check( this, module.topLevel ); {// make sure that there is no exported hedgeRule that references a label in the other namespace. Iterator jtr = module.hedgeRules.iterator(); while(jtr.hasNext()) { HedgeRules hr = (HedgeRules)jtr.next(); if(!hr.exported) continue; ExportedHedgeRuleChecker ehrc = new ExportedHedgeRuleChecker(module); if(!hr.visit( ehrc )) { // this hedgeRule directly/indirectly references exported labels. // report it to the user. // TODO: source information? String dependency=""; for( int i=0; i "; dependency += ehrc.errorSnapshot[ehrc.errorSnapshot.length-1].name; reportError( ERR_EXPROTED_HEDGERULE_CONSTRAINT, dependency ); } } } } private Expression choiceOfExported( ReferenceContainer con ) { Iterator itr = con.iterator(); Expression r = Expression.nullSet; while( itr.hasNext() ) { Exportable ex= (Exportable)itr.next(); if( ex.isExported() ) r = pool.createChoice(r,(Expression)ex); } return r; } /** detect two AttributeExps that share the same target name. * * See {@link DblAttrConstraintChecker} for details. */ private void detectDoubleAttributeConstraints( RELAXModule module ) { final DblAttrConstraintChecker checker = new DblAttrConstraintChecker(); Iterator itr = module.tags.iterator(); while( itr.hasNext() ) // errors will be reported within this method // no recovery is necessary. checker.check( (TagClause)itr.next(), this ); } private void detectCollision( ReferenceContainer col1, ReferenceContainer col2, String errMsg ) { Iterator itr = col1.iterator(); while( itr.hasNext() ) { ReferenceExp r1 = (ReferenceExp)itr.next(); ReferenceExp r2 = col2._get( r1.name ); // if the grammar references elementRule by hedgeRef, // (or hedgeRule by ref), HedgeRules object and ElementRules object // are created under the same name. // And it is inappropriate to report this situation as "label collision". // Therefore, we have to check both have definitions before reporting an error. if( r2!=null && r1.exp!=null && r2.exp!=null ) reportError( new Locator[]{ getDeclaredLocationOf(r1), getDeclaredLocationOf(r2) }, errMsg, new Object[]{r1.name} ); } } // error messages protected String localizeMessage( String propertyName, Object[] args ) { return super.localizeMessage(propertyName,args); } public static final String ERR_NAMESPACE_NOT_SUPPROTED = "RELAXReader.NamespaceNotSupported"; // arg:0 public static final String ERR_INCONSISTENT_TARGET_NAMESPACE // arg:2 = "RELAXReader.InconsistentTargetNamespace"; public static final String ERR_MISSING_TARGET_NAMESPACE // arg:0 = "RELAXReader.MissingTargetNamespace"; public static final String ERR_MULTIPLE_TAG_DECLARATIONS // arg:1 = "RELAXReader.MultipleTagDeclarations"; public static final String ERR_MORE_THAN_ONE_INLINE_TAG // arg:0 = "RELAXReader.MoreThanOneInlineTag"; public static final String ERR_MULTIPLE_ATTPOOL_DECLARATIONS // arg:1 = "RELAXReader.MultipleAttPoolDeclarations"; public static final String ERR_UNDEFINED_ELEMENTRULE // arg:1 = "RELAXReader.UndefinedElementRule"; public static final String ERR_UNDEFINED_HEDGERULE // arg:1 = "RELAXReader.UndefinedHedgeRule"; public static final String ERR_UNDEFINED_TAG // arg:1 = "RELAXReader.UndefinedTag"; public static final String ERR_UNDEFINED_ATTPOOL // arg:1 = "RELAXReader.UndefinedAttPool"; public static final String ERR_LABEL_COLLISION // arg:1 = "RELAXReader.LabelCollision"; public static final String ERR_ROLE_COLLISION // arg:1 = "RELAXReader.RoleCollision"; public static final String WRN_NO_EXPROTED_LABEL // arg:0 = "RELAXReader.NoExportedLabel"; public static final String ERR_EXPROTED_HEDGERULE_CONSTRAINT = "RELAXReader.ExportedHedgeRuleConstraint"; // arg:1 public static final String ERR_MULTIPLE_ATTRIBUTE_CONSTRAINT // arg:1 = "RELAXReader.MultipleAttributeConstraint"; public static final String ERR_ID_ABUSE // arg:0 = "RELAXReader.IdAbuse"; public static final String ERR_ID_ABUSE_1 // arg:1 = "RELAXReader.IdAbuse.1"; // public static final String ERR_REFERENCE_TO_MERGED_ATTPOOL // arg:1 // = "RELAXReader.ReferenceToMergedAttPool"; // public static final String WRN_DEPRECATED_TYPENAME = // arg:2 // "RELAXReader.Warning.DeprecatedTypeName"; public static final String WRN_ILLEGAL_RELAXCORE_VERSION // arg:1 = "RELAXReader.Warning.IllegalRelaxCoreVersion"; } msv-2009.1/msv/src/com/sun/msv/reader/relax/core/InterfaceState.java0000644000175000017500000000312107671170035025460 0ustar giovannigiovanni/* * @(#)$Id: InterfaceState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax.core; import com.sun.msv.grammar.relax.RELAXModule; import com.sun.msv.reader.ChildlessState; import com.sun.msv.reader.SimpleState; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * parses <interface> element and <div> in interface. * * @author Kohsuke KAWAGUCHI */ public class InterfaceState extends SimpleState { protected State createChildState( StartTagInfo tag ) { if(!tag.namespaceURI.equals(RELAXCoreReader.RELAXCoreNamespace)) return null; if(tag.localName.equals("div")) return new InterfaceState(); RELAXModule module = getReader().module; if(tag.localName.equals("export")) { final String label = tag.getAttribute("label"); if(label!=null) module.elementRules.getOrCreate(label).exported = true; else reader.reportError(RELAXCoreReader.ERR_MISSING_ATTRIBUTE, "export", "label" ); // recover by ignoring this export return new ChildlessState(); } return null; } protected RELAXCoreReader getReader() { return (RELAXCoreReader)reader; } } msv-2009.1/msv/src/com/sun/msv/reader/relax/core/IncludeModuleState.java0000644000175000017500000000213607671170035026316 0ustar giovannigiovanni/* * @(#)$Id: IncludeModuleState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax.core; import com.sun.msv.reader.AbortException; import com.sun.msv.reader.ChildlessState; /** * parses <include> element of RELAX Core. * * @author Kohsuke KAWAGUCHI */ public class IncludeModuleState extends ChildlessState { protected void startSelf() { super.startSelf(); final String href = startTag.getAttribute("moduleLocation"); if(href==null) { // name attribute is required. reader.reportError( RELAXCoreReader.ERR_MISSING_ATTRIBUTE, "include","moduleLocation"); } else try { reader.switchSource(this,href,new RootModuleMergeState()); } catch( AbortException e ) {} // recover by ignoring this include element } } msv-2009.1/msv/src/com/sun/msv/reader/relax/core/ElementRuleWithHedgeState.java0000644000175000017500000000350607671170035027601 0ustar giovannigiovanni/* * @(#)$Id: ElementRuleWithHedgeState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax.core; import com.sun.msv.grammar.Expression; import com.sun.msv.reader.ExpressionOwner; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * parses <elementRule> without 'type' attribute. * * @author Kohsuke KAWAGUCHI */ public class ElementRuleWithHedgeState extends ElementRuleBaseState implements ExpressionOwner { protected Expression contentModel = null; public void onEndChild( Expression exp ) {// this method is called after child expression is found and parsed if( contentModel!=null ) reader.reportError( RELAXCoreReader.ERR_MORE_THAN_ONE_CHILD_EXPRESSION ); // recover by ignoring previous expression contentModel = exp; } protected Expression getContentModel() { if( contentModel==null ) { reader.reportError( RELAXCoreReader.ERR_MISSING_CHILD_EXPRESSION ); // recover by assuming a harmless content model return Expression.epsilon; // anything will do. } return contentModel; } protected State createChildState( StartTagInfo tag ) { if( !tag.namespaceURI.equals(RELAXCoreReader.RELAXCoreNamespace) ) return null; State next; // particles next = reader.createExpressionChildState(this,tag); if(next!=null) return next; // or delegate to the base class return super.createChildState(tag); } } msv-2009.1/msv/src/com/sun/msv/reader/relax/core/ElementRuleBaseState.java0000644000175000017500000000636607730143103026602 0ustar giovannigiovanni/* * @(#)$Id: ElementRuleBaseState.java 1601 2003-09-11 19:00:19Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax.core; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.relax.ElementRule; import com.sun.msv.grammar.relax.ElementRules; import com.sun.msv.grammar.relax.TagClause; import com.sun.msv.reader.SimpleState; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * Base implementation for ElementRuleWithHedgeState and ElementRuleWithTypeState. * * @author Kohsuke KAWAGUCHI */ abstract class ElementRuleBaseState extends SimpleState { protected TagClause clause; /** gets reader in type-safe fashion */ protected RELAXCoreReader getReader() { return (RELAXCoreReader)reader; } /** gets content model of this elementRule */ protected abstract Expression getContentModel(); /** notification of inline tag element. * * this method is called by InlineTagState after it is parsed */ protected void onEndInlineClause( TagClause inlineTag ) { if(clause!=null) {// more than one inline tag was specified reader.reportError( RELAXCoreReader.ERR_MORE_THAN_ONE_INLINE_TAG ); // recover by ignoring previous local tag. } clause = inlineTag; } protected void endSelf() { String role = startTag.getAttribute("role"); String label = startTag.getAttribute("label"); if(role==null && label==null) { reader.reportError( RELAXCoreReader.ERR_MISSING_ATTRIBUTE_2, "elementRule", "role", "label" ); // recover from error by supplying dummy label label = ""; } if( label==null ) label=role; // label attribute defaults to role attribute. if( clause==null ) { // inline element was not found. // role element must point to some TagClause if( role==null ) { reader.reportError( RELAXCoreReader.ERR_MISSING_ATTRIBUTE, "elementRule","role"); // recover by assuming a harmless Clause clause = new TagClause(); clause.nameClass = NameClass.ALL; clause.exp = Expression.nullSet; } else { clause = getReader().module.tags.getOrCreate(role); } } ElementRules er = getReader().module.elementRules.getOrCreate(label); getReader().setDeclaredLocationOf(er); // remember where this ElementRules is defined er.addElementRule( reader.pool, new ElementRule( reader.pool, clause, getContentModel() ) ); super.endSelf(); } protected State createChildState( StartTagInfo tag ) { if( tag.localName.equals("tag") ) return getReader().getStateFactory().tagInline(this,tag); return null; // otherwise unknown } } msv-2009.1/msv/src/com/sun/msv/reader/relax/core/package.html0000644000175000017500000000010207266664124024200 0ustar giovannigiovanni

      parses RELAX Core into AGM.

      msv-2009.1/msv/src/com/sun/msv/reader/relax/core/MixedState.java0000644000175000017500000000200407671170035024625 0ustar giovannigiovanni/* * @(#)$Id: MixedState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax.core; import com.sun.msv.grammar.Expression; import com.sun.msv.reader.ExpressionWithChildState; /** * parses <mixed> element. * * @author Kohsuke KAWAGUCHI */ public class MixedState extends ExpressionWithChildState { protected Expression castExpression( Expression current, Expression child ) { if( current!=null ) {// mixed has more than one child. reader.reportError( RELAXCoreReader.ERR_MORE_THAN_ONE_CHILD_EXPRESSION ); // recover by ignoring previous expression } return child; } protected Expression annealExpression( Expression exp ) { return reader.pool.createMixed(exp); } } msv-2009.1/msv/src/com/sun/msv/reader/relax/core/relaxCore.rlx0000644000175000017500000003570507357444653024417 0ustar giovannigiovanni
      The overall structure of RELAX modules div elements in modules
      Interface div elements in interfaces
      Include
      Hedge Models This is used to describe element hedge models. It is also used as subordinates of sequence, choice, and mixed. This is used to specify the "occurs" attribute, which is shared by several elements. ref elements with the label attribute with the type attribute
      Rules without an embedded tag element with the type attribute with an embedded tag element with the type attribute without an embedded tag element with a hedge model with an embedded tag element with a hedge model
      Clauses tag elements embedded in elementRules ref elements with the role attribute Since RELAX Core is concerned with a single namespace, NCName might be more appropriate. However, xml:space and xml:lang are so common that RELAX Core should allow them.
      each (8-bit) byte is encoded as a sequence of 2 hexidecimal digits value is encoded in Base64 as defined in the MIME RFC
      msv-2009.1/msv/src/com/sun/msv/reader/relax/core/InlineTagState.java0000644000175000017500000000350707671170035025442 0ustar giovannigiovanni/* * @(#)$Id: InlineTagState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax.core; import com.sun.msv.grammar.SimpleNameClass; import com.sun.msv.grammar.relax.TagClause; /** * parses <tag> element inlined in <elementRule> * * @author Kohsuke KAWAGUCHI */ public class InlineTagState extends ClauseState { protected void endSelf() { super.endSelf(); String name = startTag.getAttribute("name"); if(name==null) {// then it defaults to the label of parent state name = parentState.getStartTag().getAttribute("label"); if(name==null) // label attribute of the parent itself defaults to role attribute. name = parentState.getStartTag().getAttribute("role"); if(name==null) // this is an error of elementRule. // so user will receive an error by ElementRuleBaseState. // silently ignore this error here. name = ""; } if(!(parentState instanceof ElementRuleBaseState )) // inline element must be used as a child of elementRule throw new Error(); // assertion failed. TagClause c = new TagClause(); c.nameClass = new SimpleNameClass( getReader().module.targetNamespace, name ); c.exp = exp; // exp holds a sequence of AttributeExp ((ElementRuleBaseState)parentState).onEndInlineClause(c); return; } } msv-2009.1/msv/src/com/sun/msv/reader/relax/core/RootModuleState.java0000644000175000017500000000244607671170035025662 0ustar giovannigiovanni/* * @(#)$Id: RootModuleState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax.core; import com.sun.msv.reader.SimpleState; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * invokes State object that parses the document element. * * this state is used to parse RELAX module referenced by RELAX Namespace. * * @author Kohsuke KAWAGUCHI */ class RootModuleState extends SimpleState { protected final String expectedNamespace; RootModuleState( String expectedNamespace ) { this.expectedNamespace = expectedNamespace; } protected State createChildState( StartTagInfo tag ) { if(tag.namespaceURI.equals(RELAXCoreReader.RELAXCoreNamespace) && tag.localName.equals("module")) return new ModuleState(expectedNamespace); return null; } // module wrap-up. protected void endSelf() { final RELAXCoreReader reader = (RELAXCoreReader)this.reader; reader.wrapUp(); super.endSelf(); } } msv-2009.1/msv/src/com/sun/msv/reader/relax/core/InlineElementState.java0000644000175000017500000001025307671170035026314 0ustar giovannigiovanni/* * @(#)$Id: InlineElementState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax.core; import org.relaxng.datatype.DatatypeException; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.SimpleNameClass; import com.sun.msv.grammar.relax.AttPoolClause; import com.sun.msv.grammar.relax.ElementRule; import com.sun.msv.grammar.relax.TagClause; import com.sun.msv.reader.ExpressionState; import com.sun.msv.reader.State; import com.sun.msv.reader.datatype.xsd.FacetStateParent; import com.sun.msv.reader.datatype.xsd.XSTypeIncubator; import com.sun.msv.util.StartTagInfo; /** * parses <element> element. * * @author Kohsuke KAWAGUCHI */ public class InlineElementState extends ExpressionState implements FacetStateParent { /** this field is set to null if this element has label attribute. */ protected XSTypeIncubator incubator; public XSTypeIncubator getIncubator() { return incubator; } protected State createChildState( StartTagInfo tag ) { if( incubator!=null ) return ((RELAXCoreReader)reader).createFacetState(this,tag); // facets else return null; // nothing is allowed when @label is used. } protected void startSelf() { super.startSelf(); final RELAXCoreReader reader = (RELAXCoreReader)this.reader; String type = startTag.getAttribute("type"); String label = startTag.getAttribute("label"); if( type!=null && label!=null ) reader.reportError( RELAXCoreReader.ERR_CONFLICTING_ATTRIBUTES, "type", "label" ); // recover by ignoring one attribute. if( type==null && label==null ) { reader.reportError( RELAXCoreReader.ERR_MISSING_ATTRIBUTE_2, "element", "type", "label" ); type="string"; } if( label!=null ) { incubator = null; } else { incubator = reader.resolveXSDatatype(type).createIncubator(); } } protected Expression makeExpression() { try { final RELAXCoreReader reader = (RELAXCoreReader)this.reader; final String name = startTag.getAttribute("name"); if( name==null ) { reader.reportError( RELAXCoreReader.ERR_MISSING_ATTRIBUTE, "element","name" ); // recover by ignoring this element. return Expression.nullSet; } Expression contentModel; if( incubator!=null ) { contentModel = incubator.derive(null,null); } else { // @label is used String label = startTag.getAttribute("label"); if(label==null) throw new Error(); contentModel = reader.module.hedgeRules.getOrCreate(label); reader.backwardReference.memorizeLink(contentModel); } TagClause c = new TagClause(); c.nameClass = new SimpleNameClass( ((RELAXCoreReader)reader).module.targetNamespace, name ); final String role = startTag.getAttribute("role"); if( role==null ) c.exp = Expression.epsilon; // no attribute else { // role attribute AttPoolClause att = reader.module.attPools.getOrCreate(role); c.exp = att; reader.backwardReference.memorizeLink(att); } // create anonymous ElementRule. this rule will never be added to // RefContainer. return new ElementRule( reader.pool, c, contentModel ); } catch( DatatypeException e ) { // derivation failed reader.reportError( e, RELAXCoreReader.ERR_BAD_TYPE, e.getMessage() ); // recover by using harmless expression. anything will do. return Expression.nullSet; } } } msv-2009.1/msv/src/com/sun/msv/reader/relax/core/AttPoolState.java0000644000175000017500000000420107671170035025142 0ustar giovannigiovanni/* * @(#)$Id: AttPoolState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax.core; import org.xml.sax.Locator; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.relax.AttPoolClause; /** * parses <attPool> element. * * @author Kohsuke KAWAGUCHI */ public class AttPoolState extends ClauseState { protected void endSelf( ) { super.endSelf(); final String role = startTag.getAttribute("role"); if(role==null) { reader.reportError(RELAXCoreReader.ERR_MISSING_ATTRIBUTE, "attPool","role"); return; // recover by ignoring this declaration } if( startTag.getAttribute("combine")==null ) { AttPoolClause c = getReader().module.attPools.getOrCreate(role); if(c.exp!=null) { // someone has already initialized this clause. // this happens when more than one attPool element declares the same role. reader.reportError( new Locator[]{getReader().getDeclaredLocationOf(c),location}, RELAXCoreReader.ERR_MULTIPLE_ATTPOOL_DECLARATIONS, new Object[]{role} ); // recover from error by ignoring previous tag declaration } c.exp = exp; // exp holds a sequence of AttributeExp getReader().setDeclaredLocationOf(c); // remember where this AttPool is declared } else { // this attPool has @combine ReferenceExp e = getReader().combinedAttPools._getOrCreate(role); if( e.exp==null ) e.exp = Expression.epsilon; // append newly found attributes. e.exp = reader.pool.createSequence( exp, e.exp ); reader.setDeclaredLocationOf(e); } return; } } msv-2009.1/msv/src/com/sun/msv/reader/relax/core/RootModuleMergeState.java0000644000175000017500000000213007671170035026630 0ustar giovannigiovanni/* * @(#)$Id: RootModuleMergeState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax.core; import com.sun.msv.reader.SimpleState; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * invokes State object that parses the document element. * * this state is used for parsing included module. * * @author Kohsuke KAWAGUCHI */ class RootModuleMergeState extends SimpleState { protected State createChildState( StartTagInfo tag ) { if(tag.namespaceURI.equals(RELAXCoreReader.RELAXCoreNamespace) && tag.localName.equals("module")) return new ModuleMergeState( ((RELAXCoreReader)reader).module.targetNamespace ); // included module must have the same target namespace // or it must be a chameleon module. return null; } } msv-2009.1/msv/src/com/sun/msv/reader/relax/core/DivInModuleState.java0000644000175000017500000000505407671170035025746 0ustar giovannigiovanni/* * @(#)$Id: DivInModuleState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax.core; import com.sun.msv.grammar.Expression; import com.sun.msv.reader.ExpressionOwner; import com.sun.msv.reader.SimpleState; import com.sun.msv.reader.State; import com.sun.msv.reader.datatype.xsd.XSDatatypeExp; import com.sun.msv.reader.datatype.xsd.XSTypeOwner; import com.sun.msv.util.StartTagInfo; /** * parses <div> element under <module> element. * * @author Kohsuke KAWAGUCHI */ public class DivInModuleState extends SimpleState implements ExpressionOwner, XSTypeOwner { /** gets reader in type-safe fashion */ protected RELAXCoreReader getReader() { return (RELAXCoreReader)reader; } protected State createChildState( StartTagInfo tag ) { if(tag.localName.equals("div")) return getReader().getStateFactory().divInModule(this,tag); if(tag.localName.equals("hedgeRule")) return getReader().getStateFactory().hedgeRule(this,tag); if(tag.localName.equals("tag")) return getReader().getStateFactory().tag(this,tag); if(tag.localName.equals("attPool")) return getReader().getStateFactory().attPool(this,tag); if(tag.localName.equals("include")) return getReader().getStateFactory().include(this,tag); if(tag.localName.equals("interface")) return getReader().getStateFactory().interface_(this,tag); if(tag.localName.equals("elementRule")) return getReader().getStateFactory().elementRule(this,tag); if(tag.localName.equals("simpleType")) return getReader().getStateFactory().simpleType(this,tag); return null; } // do nothing. declarations register themselves by themselves. public void onEndChild( Expression exp ) {} public String getTargetNamespaceUri() { return ""; } public void onEndChild( XSDatatypeExp type ) { // user-defined simple types final String typeName = type.name; if( typeName==null ) { // top-level simpleType must define a named type reader.reportError( RELAXCoreReader.ERR_MISSING_ATTRIBUTE, "simpleType", "name" ); return; // recover by ignoring this declaration } // memorize this type. getReader().addUserDefinedType(type); } } msv-2009.1/msv/src/com/sun/msv/reader/relax/core/ModuleState.java0000644000175000017500000000211007671170035025002 0ustar giovannigiovanni/* * @(#)$Id: ModuleState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax.core; import com.sun.msv.grammar.relax.RELAXModule; /** * parses <module> element. * * this state is used to parse "head module", which is not included by * any other modules. * * modules merged by include element are handled by MergeModuleState. * *

      * this class switchs RELAXReader.currentModule so that successive declarations * are placed in the proper module. * * @author Kohsuke KAWAGUCHI */ public class ModuleState extends ModuleMergeState { protected ModuleState(String expectedNamespace) { super(expectedNamespace); } protected void startSelf() { super.startSelf(); // switch current module to new one. getReader().module = new RELAXModule(reader.pool,targetNamespace); } } msv-2009.1/msv/src/com/sun/msv/reader/relax/core/AttPoolRefState.java0000644000175000017500000000211507671170035025601 0ustar giovannigiovanni/* * @(#)$Id: AttPoolRefState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax.core; import com.sun.msv.grammar.Expression; import com.sun.msv.reader.ExpressionWithoutChildState; /** * parses <ref role="..." />. * * @author Kohsuke KAWAGUCHI */ public class AttPoolRefState extends ExpressionWithoutChildState { protected Expression makeExpression() { final String role = startTag.getAttribute("role"); if( role==null ) { reader.reportError( RELAXCoreReader.ERR_MISSING_ATTRIBUTE, "ref", "role" ); return Expression.epsilon; } final String namespace = startTag.getAttribute("namespace"); final RELAXCoreReader reader = (RELAXCoreReader)this.reader; return reader.resolveAttPoolRef(namespace,role); } } msv-2009.1/msv/src/com/sun/msv/reader/relax/core/ElementRuleWithTypeState.java0000644000175000017500000000370307671170035027505 0ustar giovannigiovanni/* * @(#)$Id: ElementRuleWithTypeState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax.core; import org.relaxng.datatype.DatatypeException; import com.sun.msv.grammar.Expression; import com.sun.msv.reader.State; import com.sun.msv.reader.datatype.xsd.FacetStateParent; import com.sun.msv.reader.datatype.xsd.XSTypeIncubator; import com.sun.msv.util.StartTagInfo; /** * parses <elementRule> with 'type' attribute. * * @author Kohsuke KAWAGUCHI */ public class ElementRuleWithTypeState extends ElementRuleBaseState implements FacetStateParent { protected XSTypeIncubator incubator; public XSTypeIncubator getIncubator() { return incubator; } protected void startSelf() { super.startSelf(); final RELAXCoreReader reader = (RELAXCoreReader)this.reader; // existance of type attribute has already checked before // this state is created. incubator = reader.resolveXSDatatype(startTag.getAttribute("type")) .createIncubator(); } protected Expression getContentModel() { try { return incubator.derive(null,null); } catch( DatatypeException e ) { // derivation failed reader.reportError( e, RELAXCoreReader.ERR_BAD_TYPE, e.getMessage() ); // recover by using harmless expression. anything will do. return Expression.anyString; } } protected State createChildState( StartTagInfo tag ) { State next = getReader().createFacetState(this,tag); if(next!=null) return next; // facets return super.createChildState(tag); // or delegate to the base class } } msv-2009.1/msv/src/com/sun/msv/reader/relax/core/HedgeRuleState.java0000644000175000017500000000243107671170035025427 0ustar giovannigiovanni/* * @(#)$Id: HedgeRuleState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax.core; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.relax.HedgeRules; import com.sun.msv.reader.relax.HedgeRuleBaseState; /** * parses <hedgeRule> element * * this class is used as the base class of TopLevelState * * @author Kohsuke KAWAGUCHI */ public class HedgeRuleState extends HedgeRuleBaseState { protected void endSelf( Expression contentModel ) { final String label = startTag.getAttribute("label"); if( label==null ) { reader.reportError( RELAXCoreReader.ERR_MISSING_ATTRIBUTE, "hedgeRule", "label" ); return; // recover by ignoring this hedgeRule } final RELAXCoreReader reader = (RELAXCoreReader)this.reader; HedgeRules hr = reader.module.hedgeRules.getOrCreate(label); reader.setDeclaredLocationOf(hr); // remember where this hedgeRule is defined. hr.addHedge(contentModel,reader.pool); } } msv-2009.1/msv/src/com/sun/msv/reader/relax/core/ModuleMergeState.java0000644000175000017500000000620507671170035025773 0ustar giovannigiovanni/* * @(#)$Id: ModuleMergeState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax.core; /** * Used to parse module. * * As stand-alone, this state is used to parse a module included by another module. * By a base class, this state is used to parse a "head" module. * * This class checks consistency between targetNamespace attribute * and the namespace specified by its caller (grammar/module). * * @author Kohsuke KAWAGUCHI */ public class ModuleMergeState extends DivInModuleState { protected ModuleMergeState( String expectedTargetNamespace ) { this.expectedTargetNamespace = expectedTargetNamespace; } /** expected targetNamespace for this module. * * null indicates that module must have targetNamespace attribute. * *

      * If RELAX module has 'targetNamespace' attribute, then its value * must be equal to this value, or this value must be null. * *

      * If RELAX module doesn't have the attribute, then this value is * used as the target namespace. If this value is null, then it is * an error. */ protected final String expectedTargetNamespace; /** * computed targetNamespace. * * actual target namespace depends on expected target namespace * and module. this field is set in startSelf method. */ protected String targetNamespace; protected void startSelf() { super.startSelf(); {// check relaxCoreVersion final String coreVersion = startTag.getAttribute("relaxCoreVersion"); if( coreVersion==null ) reader.reportWarning( RELAXCoreReader.ERR_MISSING_ATTRIBUTE, "module", "relaxCoreVersion" ); else if(!"1.0".equals(coreVersion)) reader.reportWarning( RELAXCoreReader.WRN_ILLEGAL_RELAXCORE_VERSION, coreVersion ); } targetNamespace = startTag.getAttribute("targetNamespace"); if(targetNamespace!=null) { // check accordance with expected namespace if( expectedTargetNamespace!=null && !expectedTargetNamespace.equals(targetNamespace) ) {// error reader.reportError( RELAXCoreReader.ERR_INCONSISTENT_TARGET_NAMESPACE, targetNamespace, expectedTargetNamespace ); // recover by ignoring one specified in the module targetNamespace = expectedTargetNamespace; } } else {// no targetnamespace attribute is given. if( expectedTargetNamespace==null ) { reader.reportError( RELAXCoreReader.ERR_MISSING_TARGET_NAMESPACE ); targetNamespace = ""; // recover by assuming the default namespace } else targetNamespace = expectedTargetNamespace; } } } msv-2009.1/msv/src/com/sun/msv/reader/relax/core/checker/0000755000175000017500000000000011622453066023322 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/reader/relax/core/checker/package.html0000644000175000017500000000057407265752221025614 0ustar giovannigiovanni

      Non-essential schema conformance checks.

      This packages contains various check against grammar/module, which is mandated by RELAX specification. Most of them can be skipped if you are sure that the grammars/modules are error-free.

      msv-2009.1/msv/src/com/sun/msv/reader/relax/core/checker/DblAttrConstraintChecker.java0000644000175000017500000001074207671170035031060 0ustar giovannigiovanni/* * @(#)$Id: DblAttrConstraintChecker.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax.core.checker; import java.util.Map; import org.xml.sax.Locator; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.ChoiceExp; import com.sun.msv.grammar.ConcurExp; import com.sun.msv.grammar.DataExp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.InterleaveExp; import com.sun.msv.grammar.ListExp; import com.sun.msv.grammar.MixedExp; import com.sun.msv.grammar.OneOrMoreExp; import com.sun.msv.grammar.OtherExp; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.SequenceExp; import com.sun.msv.grammar.SimpleNameClass; import com.sun.msv.grammar.ValueExp; import com.sun.msv.grammar.relax.AttPoolClause; import com.sun.msv.grammar.relax.ElementRules; import com.sun.msv.grammar.relax.HedgeRules; import com.sun.msv.grammar.relax.RELAXExpressionVisitorVoid; import com.sun.msv.grammar.relax.TagClause; import com.sun.msv.reader.relax.core.RELAXCoreReader; import com.sun.msv.util.StringPair; /** * makes sure that no two AttributeExps have the same attribute name as their target. * * @author Kohsuke KAWAGUCHI */ public class DblAttrConstraintChecker implements RELAXExpressionVisitorVoid { /** map of StringPairs to ReferenceExp(TagClause/AttPoolClause). * * keys are names of visited AttributeExps, and its value is * Clause object in which AttributeExp is declared. */ private final Map atts = new java.util.HashMap(); /** current clause. */ private ReferenceExp current; public void check( TagClause clause, RELAXCoreReader reader ) { atts.clear(); current = clause; try { clause.visit(this); } catch( Eureka e ) { reader.reportError( new Locator[]{reader.getDeclaredLocationOf(current), reader.getDeclaredLocationOf((ReferenceExp)atts.get(e.name)) }, RELAXCoreReader.ERR_MULTIPLE_ATTRIBUTE_CONSTRAINT, new Object[]{ e.name.localName } ); } } private static final class Eureka extends RuntimeException { final StringPair name; Eureka( StringPair an ) { name=an; } }; public void onAttribute( AttributeExp exp ) { if( exp.nameClass instanceof SimpleNameClass ) { // this check is only appliable for those who constrains // one particular attribute. SimpleNameClass nc = (SimpleNameClass)exp.nameClass; StringPair p = new StringPair( nc.namespaceURI, nc.localName ); if( atts.containsKey(p) ) throw new Eureka(p); // eureka! : find two AttributeExps that share the same name. atts.put(p,current); } } public void onAttPool( AttPoolClause exp ) { ReferenceExp old = current; current = exp; exp.exp.visit(this); current = old; } public void onSequence( SequenceExp exp ) { exp.exp1.visit(this);exp.exp2.visit(this); } public void onChoice( ChoiceExp exp ) { exp.exp1.visit(this);exp.exp2.visit(this); } public void onEpsilon() {;} public void onRef( ReferenceExp exp ) {;} public void onOther( OtherExp exp ) { exp.exp.visit(this); } public void onElement( ElementExp exp ) {;} public void onOneOrMore( OneOrMoreExp exp ) { exp.exp.visit(this); } public void onMixed( MixedExp exp ) { exp.exp.visit(this); } public void onNullSet() {;} public void onAnyString() {;} public void onData( DataExp exp ) {;} public void onValue( ValueExp exp ) {;} public void onTag( TagClause exp ) { exp.exp.visit(this); } public void onElementRules( ElementRules exp ) { exp.exp.visit(this); } public void onHedgeRules( HedgeRules exp ) { exp.exp.visit(this); } // those methods should also never be called in case of RELAX. public void onConcur( ConcurExp exp ) {;} public void onInterleave( InterleaveExp exp ) {;} public void onList( ListExp exp ) {;} } msv-2009.1/msv/src/com/sun/msv/reader/relax/core/checker/ExportedHedgeRuleChecker.java0000644000175000017500000001115507671170035031035 0ustar giovannigiovanni/* * @(#)$Id: ExportedHedgeRuleChecker.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax.core.checker; import java.util.Stack; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.ChoiceExp; import com.sun.msv.grammar.ConcurExp; import com.sun.msv.grammar.DataExp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.InterleaveExp; import com.sun.msv.grammar.ListExp; import com.sun.msv.grammar.MixedExp; import com.sun.msv.grammar.OneOrMoreExp; import com.sun.msv.grammar.OtherExp; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.SequenceExp; import com.sun.msv.grammar.ValueExp; import com.sun.msv.grammar.relax.AttPoolClause; import com.sun.msv.grammar.relax.ElementRules; import com.sun.msv.grammar.relax.HedgeRules; import com.sun.msv.grammar.relax.RELAXExpressionVisitorBoolean; import com.sun.msv.grammar.relax.RELAXModule; import com.sun.msv.grammar.relax.TagClause; /** * the purpose of this function object is to make sure * that the expression does not contain references to modules * other than one specified by this variable. * * @author Kohsuke KAWAGUCHI */ public final class ExportedHedgeRuleChecker implements RELAXExpressionVisitorBoolean { private final RELAXModule module; public ExportedHedgeRuleChecker( RELAXModule module ) { this.module = module; } /** * traversal stack. * * This object keeps track of how hedgeRules are visited so that * detailed error message can be provided when an error is found. * * Say if you start from hr1, hr1 refers hr2, hr2 refers hr3, * and hr3 has a reference to the other module, this stack is * {hr1,hr2,hr3} when an error is found. */ private final Stack traversalStack = new Stack(); public ReferenceExp[] errorSnapshot = null; public boolean onAttribute( AttributeExp exp ) { return true; } public boolean onChoice( ChoiceExp exp ) { return exp.exp1.visit(this) && exp.exp2.visit(this); } public boolean onSequence( SequenceExp exp ) { return exp.exp1.visit(this) && exp.exp2.visit(this); } public boolean onElement( ElementExp exp ) { return true; } public boolean onOneOrMore( OneOrMoreExp exp ) { return exp.exp.visit(this); } public boolean onMixed( MixedExp exp ) { return exp.exp.visit(this); } public boolean onRef( ReferenceExp exp ) { throw new Error(); } // should never be called public boolean onOther( OtherExp exp ) { return exp.exp.visit(this); } public boolean onEpsilon() { return true; } public boolean onNullSet() { return true; } public boolean onAnyString() { return true; } public boolean onData( DataExp exp ) { return true; } public boolean onValue( ValueExp exp ) { return true; } public boolean onAttPool( AttPoolClause exp ) { throw new Error(); } // should never be called public boolean onTag( TagClause exp ) { throw new Error(); } // should never be called // these two shall never be called in case of RELAX. public boolean onInterleave( InterleaveExp exp ) { throw new Error(); } public boolean onConcur( ConcurExp exp ) { throw new Error(); } public boolean onList( ListExp exp ) { throw new Error(); } public boolean onElementRules( ElementRules exp ) { if(exp.ownerModule==module) return true; takeSnapshot(exp); return false; } public boolean onHedgeRules( HedgeRules exp ) { if( exp.ownerModule!=module ) { // reference to the other namespace takeSnapshot(exp); return false; } traversalStack.push(exp); // we have to make sure the same thing for this referenced hedgeRule. boolean r = exp.exp.visit(this); traversalStack.pop(); return r; } /** * takes a snap shot of traversal to this.errorSnapshot * so that the user will know what references cause this problem. */ private void takeSnapshot( ReferenceExp lastExp ) { errorSnapshot = new ReferenceExp[ traversalStack.size()+1 ]; traversalStack.toArray(errorSnapshot); errorSnapshot[errorSnapshot.length-1] = lastExp; } } msv-2009.1/msv/src/com/sun/msv/reader/relax/core/checker/IdAbuseChecker.java0000644000175000017500000001603407671170035026773 0ustar giovannigiovanni/* * @(#)$Id: IdAbuseChecker.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax.core.checker; import java.util.Iterator; import java.util.Set; import org.relaxng.datatype.Datatype; import com.sun.msv.datatype.xsd.IDREFType; import com.sun.msv.datatype.xsd.IDType; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.ChoiceExp; import com.sun.msv.grammar.ConcurExp; import com.sun.msv.grammar.DataExp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.InterleaveExp; import com.sun.msv.grammar.ListExp; import com.sun.msv.grammar.MixedExp; import com.sun.msv.grammar.OneOrMoreExp; import com.sun.msv.grammar.OtherExp; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.SequenceExp; import com.sun.msv.grammar.SimpleNameClass; import com.sun.msv.grammar.ValueExp; import com.sun.msv.grammar.relax.AttPoolClause; import com.sun.msv.grammar.relax.ElementRules; import com.sun.msv.grammar.relax.HedgeRules; import com.sun.msv.grammar.relax.RELAXExpressionVisitorVoid; import com.sun.msv.grammar.relax.RELAXModule; import com.sun.msv.grammar.relax.TagClause; import com.sun.msv.reader.relax.core.RELAXCoreReader; /** * makes sure that ID/IDREF are not abused. * * RELAX has the following constraint over the use of ID/IDREF. * *

      * First, ID and IDREF can be only used as attribute values. * They cannot be used from type attribute of elementRules. * *

      * Second, if <tag> clause declares directly or indirectly * (by referencing attPool) one of its attribute as ID/IDREF type, * it must satisfies either (or both) of the following statement. * *

        *
      1. no other tag clause shares the same tag name. *
      2. no other attribute of non-ID/IDREF types shares the same attribute name. *
      * * @author Kohsuke KAWAGUCHI */ public class IdAbuseChecker implements RELAXExpressionVisitorVoid { /** set of Strings: tag names that are used in this module */ private final Set tagNames = new java.util.HashSet(); /** set of Strings: tag names that are used more than once in this module */ private final Set overloadedNames = new java.util.HashSet(); /** set of Strings: names of non-ID/IDREF attributes */ private final Set nonIdAttrNames = new java.util.HashSet(); /** set of AttributeExps: that have ID/IDREF values */ private final Set idAttributes = new java.util.HashSet(); private final RELAXModule module; private final RELAXCoreReader reader; private String currentTagName; private IdAbuseChecker(RELAXCoreReader r,RELAXModule m) { this.reader = r; this.module = m; } public static void check( RELAXCoreReader reader, RELAXModule module ) { new IdAbuseChecker(reader,module).run(); } private void run() { Iterator itr; // extracts all tag names and // classify attribute names into // (1) names that are used as ID/IDREF // (2) names that are used as other datatypes. itr= module.tags.iterator(); while( itr.hasNext() ) { final TagClause tag = (TagClause)itr.next(); if( tag.nameClass instanceof SimpleNameClass ) { SimpleNameClass snc = (SimpleNameClass)tag.nameClass; if( tagNames.contains(snc.localName) ) overloadedNames.add(snc.localName); else tagNames.add(snc.localName); } } // 1st filter: collect those AttributeExps which have overloaded tag names. itr= module.tags.iterator(); while( itr.hasNext() ) { final TagClause tag = (TagClause)itr.next(); if( tag.nameClass instanceof SimpleNameClass ) currentTagName = ((SimpleNameClass)tag.nameClass).localName; else currentTagName = null; // indicates wild card tag.exp.visit(this); } // make sure that filtered AttributeExp satisifies the second statement itr = idAttributes.iterator(); while( itr.hasNext() ) { final AttributeExp atr = (AttributeExp)itr.next(); if( atr.nameClass instanceof SimpleNameClass ) { final String name = ((SimpleNameClass)atr.nameClass).localName; if( nonIdAttrNames.contains(name) ) reader.reportError( RELAXCoreReader.ERR_ID_ABUSE_1, name ); } else reader.reportError( RELAXCoreReader.ERR_ID_ABUSE ); } } public void onAttribute( AttributeExp exp ) { if(!(exp.nameClass instanceof SimpleNameClass )) return; Expression body = exp.exp.getExpandedExp(reader.pool); if(!(body instanceof DataExp )) return; SimpleNameClass snc = (SimpleNameClass)exp.nameClass; if(!snc.namespaceURI.equals("")) return; Datatype dt = ((DataExp)body).dt; if( dt==IDType.theInstance || dt==IDREFType.theInstance ) { if( currentTagName==null // complex attribute name is used. // ID/IDREF must have an unique attribute name || overloadedNames.contains(currentTagName) ) idAttributes.add(exp); // possibility of abuse. // use of ID/IDREF in this way is OK. } else nonIdAttrNames.add(snc.localName); } public void onChoice( ChoiceExp exp ) { exp.exp1.visit(this);exp.exp2.visit(this); } public void onElement( ElementExp exp ) { throw new Error(); } public void onOneOrMore( OneOrMoreExp exp ) { exp.exp.visit(this); } public void onMixed( MixedExp exp ) { throw new Error(); } public void onRef( ReferenceExp exp ) { exp.exp.visit(this); } public void onOther( OtherExp exp ) { exp.exp.visit(this); } public void onEpsilon() {} public void onNullSet() {} public void onAnyString() {} public void onSequence( SequenceExp exp ) {} public void onData( DataExp exp ) { throw new Error(); } public void onValue( ValueExp exp ) { throw new Error(); } public void onAttPool( AttPoolClause exp ) { exp.exp.visit(this); } public void onTag( TagClause exp ) { throw new Error(); } public void onElementRules( ElementRules exp ) { throw new Error(); } public void onHedgeRules( HedgeRules exp ) { throw new Error(); } public void onInterleave( InterleaveExp exp ) { throw new Error(); } public void onConcur( ConcurExp exp ) { throw new Error(); } public void onList( ListExp exp ) { throw new Error(); } } msv-2009.1/msv/src/com/sun/msv/reader/relax/core/AttributeState.java0000644000175000017500000000520607671170035025531 0ustar giovannigiovanni/* * @(#)$Id: AttributeState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax.core; import org.relaxng.datatype.DatatypeException; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.SimpleNameClass; import com.sun.msv.reader.ExpressionState; import com.sun.msv.reader.State; import com.sun.msv.reader.datatype.xsd.FacetStateParent; import com.sun.msv.reader.datatype.xsd.XSTypeIncubator; import com.sun.msv.util.StartTagInfo; /** * parses <attribute> element. * * @author Kohsuke KAWAGUCHI */ public class AttributeState extends ExpressionState implements FacetStateParent { protected XSTypeIncubator incubator; public XSTypeIncubator getIncubator() { return incubator; } protected void startSelf() { super.startSelf(); final RELAXCoreReader reader = (RELAXCoreReader)this.reader; String type = startTag.getAttribute("type"); if(type==null) type="string"; incubator = reader.resolveXSDatatype(type).createIncubator(); } protected Expression makeExpression() { try { final String name = startTag.getAttribute("name"); final String required = startTag.getAttribute("required"); if( name==null ) { reader.reportError( RELAXCoreReader.ERR_MISSING_ATTRIBUTE, "attribute","name" ); // recover by ignoring this attribute. // since attributes are combined by sequence, so epsilon is appropriate. return Expression.epsilon; } Expression exp = reader.pool.createAttribute( new SimpleNameClass("",name), incubator.derive(null,null) ); // unless required attribute is specified, it is considered optional if(! "true".equals(required) ) exp = reader.pool.createOptional(exp); return exp; } catch( DatatypeException e ) { // derivation failed reader.reportError( e, RELAXCoreReader.ERR_BAD_TYPE, e.getMessage() ); // recover by using harmless expression. anything will do. return Expression.anyString; } } protected State createChildState( StartTagInfo tag ) { return ((RELAXCoreReader)reader).createFacetState(this,tag); // facets } } msv-2009.1/msv/src/com/sun/msv/reader/relax/core/TagState.java0000644000175000017500000000346007671170035024301 0ustar giovannigiovanni/* * @(#)$Id: TagState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax.core; import org.xml.sax.Locator; import com.sun.msv.grammar.SimpleNameClass; import com.sun.msv.grammar.relax.TagClause; /** * parses <tag> element. * * @author Kohsuke KAWAGUCHI */ public class TagState extends ClauseState { protected void endSelf( ) { super.endSelf(); final String name = startTag.getAttribute("name"); String role = startTag.getAttribute("role"); if(role==null) role=name; // role defaults to name if(name==null) { reader.reportError(RELAXCoreReader.ERR_MISSING_ATTRIBUTE, "tag","name"); return; } TagClause c = getReader().module.tags.getOrCreate(role); if(c.nameClass!=null) { // someone has already initialized this clause. // this happens when more than one tag element declares the same role. reader.reportError( new Locator[]{getReader().getDeclaredLocationOf(c),location}, RELAXCoreReader.ERR_MULTIPLE_TAG_DECLARATIONS, new Object[]{role} ); // recover from error by ignoring previous tag declaration } c.nameClass = new SimpleNameClass( getReader().module.targetNamespace, name ); c.exp = exp; // exp holds a sequence of AttributeExp getReader().setDeclaredLocationOf(c); // remember where this tag is declared return; } } msv-2009.1/msv/src/com/sun/msv/reader/relax/core/ClauseState.java0000644000175000017500000000354210034315204024765 0ustar giovannigiovanni/* * @(#)$Id: ClauseState.java 1634 2004-04-05 17:42:28Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax.core; import com.sun.msv.grammar.Expression; import com.sun.msv.reader.ExpressionOwner; import com.sun.msv.reader.SimpleState; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * common part of <tag> and <attPool>. * * @author Kohsuke KAWAGUCHI */ abstract class ClauseState extends SimpleState implements ExpressionOwner { protected State createChildState( StartTagInfo tag ) { if(tag.localName.equals("ref")) return getReader().getStateFactory().refRole(this,tag); if(tag.localName.equals("attribute")) return getReader().getStateFactory().attribute(this,tag); return null; // unrecognized } protected Expression initialExpression() { return Expression.epsilon; } protected Expression castExpression( Expression exp, Expression child ) { // attributes and references are combined in one sequence return reader.pool.createSequence(exp,child); } /** gets reader in type-safe fashion */ protected RELAXCoreReader getReader() { return (RELAXCoreReader)reader; } /** * expression object that is being created. * See {@link #castPattern} and {@link #annealPattern} methods * for how will a pattern be created. */ protected Expression exp = initialExpression(); /** receives a Pattern object that is contained in this element. */ public final void onEndChild( Expression childExpression ) { exp = castExpression( exp, childExpression ); } } msv-2009.1/msv/src/com/sun/msv/reader/relax/HedgeRefState.java0000644000175000017500000000124207671170035024303 0ustar giovannigiovanni/* * @(#)$Id: HedgeRefState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax; import com.sun.msv.grammar.Expression; /** * parses <hedgeRef label="..." /> element. * * @author Kohsuke KAWAGUCHI */ public class HedgeRefState extends LabelRefState { protected final Expression resolve( String namespace, String label ) { return ((RELAXReader)reader).resolveHedgeRef(namespace,label); } } msv-2009.1/msv/src/com/sun/msv/reader/relax/Messages_ja.properties0000644000175000017500000001425507307765244025345 0ustar giovannigiovanni## abstract error messages defined for RELAX GrammarReader.Abstract.MissingChildExpression =\ \u30B3\u30F3\u30C6\u30F3\u30C8\u30E2\u30C7\u30EB\u306E\u5B9A\u7FA9\u304C\u3042\u308A\u307E\u305B\u3093 GrammarReader.Abstract.MoreThanOneChildExpression =\ \u8907\u6570\u306E\u30B3\u30F3\u30C6\u30F3\u30C8\u30E2\u30C7\u30EB\u5B9A\u7FA9\u304C\u3042\u308A\u307E\u3059 GrammarReader.Abstract.RunAwayExpression =\ \u6B21\u306EhedgeRule\u304C\u5FAA\u74B0\u53C2\u7167\u3092\u8D77\u3053\u3057\u3066\u3044\u307E\u3059 ( {0} ) GrammarReader.Abstract.MissingTopLevel =\ \u8981\u7D20\u304C\u3042\u308A\u307E\u305B\u3093\u3067\u3057\u305F ## RELAXReader error messages RELAXReader.NamespaceNotSupported =\ namespace\u5C5E\u6027\u3092\u4F7F\u3046\u306B\u306FRELAX Namespace\u304C\u5FC5\u8981\u3067\u3059 RELAXReader.InconsistentTargetNamespace =\ \u30E2\u30B8\u30E5\u30FC\u30EB\u306Etarget namespace\u304C"{0}"\u3068\u6307\u5B9A\u3055\u308C\u3066\u3044\u307E\u3059\u304C\u3001RELAX Namespace \ \u30B0\u30E9\u30DE\u30FC\u306B\u3088\u308C\u3070\u3001"{1}"\u306E\u306F\u305A\u3067\u3059\u3002 RELAXReader.MissingTargetNamespace =\ RELAX Core\u3060\u3051\u3067\u4F7F\u3046\u5834\u5408\u306B\u306Ftarget namespace\u5C5E\u6027\u304C\u5FC5\u9808\u3067\u3059 RELAXReader.IllegalOccurs =\ occurs\u306E\u5024\u306F*,?.+\u306E\u3069\u308C\u304B\u3067\u306A\u304F\u3066\u306F\u3044\u3051\u307E\u305B\u3093: {0} RELAXReader.MisplacedOccurs =\ {0}\u8981\u7D20\u306Foccurs\u5C5E\u6027\u3092\u3082\u3066\u307E\u305B\u3093 RELAXReader.MultipleTagDeclarations =\ \u8907\u6570\u306Etag\u8981\u7D20\u304C"{0}"\u3092\u5B9A\u7FA9\u3057\u3088\u3046\u3068\u3057\u3066\u3044\u307E\u3059 RELAXReader.MoreThanOneInlineTag =\ elementRule\u8981\u7D20\u306E\u4E2D\u306B\u306Ftag\u8981\u7D20\u306F\uFF11\u3064\u3057\u304B\u66F8\u3051\u307E\u305B\u3093 RELAXReader.MultipleAttPoolDeclarations =\ \u8907\u6570\u306EattPool\u8981\u7D20\u304C"{0}"\u3092\u5B9A\u7FA9\u3057\u3088\u3046\u3068\u3057\u3066\u3044\u307E\u3059 RELAXReader.Warning.IllegalRelaxCoreVersion =\ \u30B5\u30DD\u30FC\u30C8\u3057\u3066\u3044\u306A\u3044\u30D0\u30FC\u30B8\u30E7\u30F3\u3067\u3059\u3002RELAX Core Ver.1.0\u3060\u3051\u304C\u4F7F\u3048\u307E\u3059 RELAXReader.LanguageNotSupported =\ language\u5C5E\u6027\u306F\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u307E\u305B\u3093 RELAXReader.UndefinedElementRule =\ \u30E9\u30D9\u30EB"{0}"\u3092\u5B9A\u7FA9\u3059\u308BelementRule\u304C\u3042\u308A\u307E\u305B\u3093 RELAXReader.UndefinedHedgeRule =\ \u30E9\u30D9\u30EB"{0}"\u3092\u5B9A\u7FA9\u3059\u308BhedgeRule\u304C\u3042\u308A\u307E\u305B\u3093 RELAXReader.UndefinedTag =\ \u30ED\u30FC\u30EB"{0}"\u3092\u5B9A\u7FA9\u3059\u308Btag\u304C\u3042\u308A\u307E\u305B\u3093 RELAXReader.UndefinedAttPool =\ \u30ED\u30FC\u30EB"{0}"\u3092\u5B9A\u7FA9\u3059\u308BattPool\u304C\u3042\u308A\u307E\u305B\u3093 RELAXReader.LabelCollision =\ elementRule\u3068hedgeRule\u304C\u540C\u3058\u540D\u524D"{0}"\u3092\u4F7F\u3063\u3066\u3044\u307E\u3059\u304C\u3001\ \u3053\u308C\u306F\u7981\u6B62\u3055\u308C\u3066\u3044\u307E\u3059 RELAXReader.RoleCollision =\ tag\u3068attPool\u304C\u540C\u3058\u540D\u524D"{0}"\u3092\u4F7F\u3063\u3066\u3044\u307E\u3059\u304C\u3001\ \u3053\u308C\u306F\u7981\u6B62\u3055\u308C\u3066\u3044\u307E\u3059 RELAXReader.NoExportedLabel =\ \u4F55\u3082export\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002\u4F55\u304B\u304Cexport\u3055\u308C\u3066\u3044\u306A\u3044\u3068\u8AB0\u3082\u3053\u306E\u30E2\u30B8\u30E5\u30FC\u30EB\u3092\u4F7F\u3048\u307E\u305B\u3093 RELAXReader.ExportedHedgeRuleConstraint =\ export\u3055\u308C\u305FhedgeRule\u3084\u305D\u308C\u304C\u9593\u63A5\u7684\u306B\u53C2\u7167\u3059\u308BhedgeRule\u306F\u3001\u4ED6\u306Enamespace\u3092\u53C2\u7167\u3059\u308B\u3053\u3068\u306F\u51FA\u6765\u307E\u305B\u3093\u3002\n\ \u53C2\u7167\u95A2\u4FC2\u306F: {0} RELAXReader.MultipleAttributeConstraint =\ \u540C\u3058tag\u304B\u3089\u53C2\u7167\u3055\u308C\u3066\u3044\u308B\u7BC4\u56F2\u5185\u3067\u3001\u8907\u6570\u306Eattribute\u8981\u7D20\u304C\u540C\u540D"{0}"\u306E\u5C5E\u6027\u3092\u5BA3\u8A00\u3057\u3066\u3044\u307E\u3059 RELAXReader.IdAbuse =\ ID/IDREF\u306E\u9593\u9055\u3063\u305F\u4F7F\u3044\u65B9\u3067\u3059\u3002ID\u3001IDREF\u307E\u305F\u306F\u305D\u308C\u3089\u306E\u6D3E\u751F\u578B\u3092\u4F7F\u3046\u6642\u306B\u306F\u3001\n\ 1.\u5C5E\u6027\u306E\u540D\u524D\u304CID/IDREF\u4EE5\u5916\u306E\u5C5E\u6027\u306E\u540D\u524D\u3068\u304B\u3076\u3089\u306A\u3044\u3053\u3068\u3001\u307E\u305F\u306F\n\ 2.\u3053\u306E\u5C5E\u6027\u3092\u4F7F\u3046\u30BF\u30B0\u540D\u304C\u4ED6\u306E\u30BF\u30B0\u540D\u3068\u304B\u3076\u3089\u306A\u3044\u3053\u3068\n\ \u304C\u5FC5\u8981\u3067\u3059 RELAXReader.IdAbuse.1 =\ ID/IDREF\u306E\u9593\u9055\u3063\u305F\u4F7F\u3044\u65B9\u3067\u3059\u3002ID\u3001IDREF\u307E\u305F\u306F\u305D\u308C\u3089\u306E\u6D3E\u751F\u578B\u3092\u4F7F\u3046\u6642\u306B\u306F\u3001\n\ 1.\u5C5E\u6027\u306E\u540D\u524D\u304CID/IDREF\u4EE5\u5916\u306E\u5C5E\u6027\u306E\u540D\u524D\u3068\u304B\u3076\u3089\u306A\u3044\u3053\u3068\u3001\u307E\u305F\u306F\n\ 2.\u3053\u306E\u5C5E\u6027\u3092\u4F7F\u3046\u30BF\u30B0\u540D\u304C\u4ED6\u306E\u30BF\u30B0\u540D\u3068\u304B\u3076\u3089\u306A\u3044\u3053\u3068\n\ \u304C\u5FC5\u8981\u3067\u3059\u3002\u5F93\u3063\u3066\u3053\u306E\u5C5E\u6027\u540D\u3092\u4ED6\u306E\u30C7\u30FC\u30BF\u578B\u306E\u305F\u3081\u306B\u4F7F\u3046\u3053\u3068\u306F\u51FA\u6765\u307E\u305B\u3093 ## RELAXNSReader error messages RELAXNSReader.Warning.IllegalRelaxNamespaceVersion =\ \u30B5\u30DD\u30FC\u30C8\u3057\u3066\u3044\u306A\u3044\u30D0\u30FC\u30B8\u30E7\u30F3\u3067\u3059\u3002RELAX Namespace Ver.1.0\u3060\u3051\u304C\u4F7F\u3048\u307E\u3059 RELAXNSReader.TopLevelParticleMustBeRelaxCore =\ topLevel\u8981\u7D20\u306E\u5B50\u4F9B\u306B\u306F\u3001RELAX Core\u3060\u3051\u304C\u4F7F\u3048\u307E\u3059 RELAXNSReader.InlineModuleNotFound =\ namespace\u8981\u7D20\u306B\u306FmoduleLocation\u5C5E\u6027\u304B\u3001\u5B50\u4F9B\u306Emodule\u8981\u7D20\u304C\u5FC5\u8981\u3067\u3059 RELAXNSReader.UnknownLanguage =\ "{0}"\u306F\u672A\u77E5\u306E\u8A00\u8A9E\u3067\u3059 RELAXNSReader.NamespaceCollision =\ namespace "{0}" \u304C\u8907\u6570\u306E\u30E2\u30B8\u30E5\u30FC\u30EB\u3067\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u3059 msv-2009.1/msv/src/com/sun/msv/reader/relax/LabelRefState.java0000644000175000017500000000274007671170035024312 0ustar giovannigiovanni/* * @(#)$Id: LabelRefState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax; import com.sun.msv.grammar.Expression; import com.sun.msv.reader.ExpressionWithoutChildState; import com.sun.msv.reader.GrammarReader; /** * base implementation of HedgeRefState and ElementRefState. * * this class resolves namespace attribute and label attribute into the actual * ReferenceExp object. * * @author Kohsuke KAWAGUCHI */ abstract class LabelRefState extends ExpressionWithoutChildState { protected Expression makeExpression() { final String label = startTag.getAttribute("label"); final String namespace = startTag.getAttribute("namespace"); final RELAXReader reader = (RELAXReader)this.reader; if(label==null) {// label attribute is required. reader.reportError( GrammarReader.ERR_MISSING_ATTRIBUTE, startTag.localName,"label"); // recover by returning something that can be interpreted as Pattern return Expression.nullSet; } return resolve(namespace,label); } /** gets or creates appropriate reference */ protected abstract Expression resolve( String namespace, String label ); } msv-2009.1/msv/src/com/sun/msv/reader/relax/HedgeRuleBaseState.java0000644000175000017500000000345407671170035025300 0ustar giovannigiovanni/* * @(#)$Id: HedgeRuleBaseState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax; import com.sun.msv.grammar.Expression; import com.sun.msv.reader.ExpressionOwner; import com.sun.msv.reader.SimpleState; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * Base implementation for HedgeRuleState and TopLevelState. * * expects one and only one expression as its child. * * @author Kohsuke KAWAGUCHI */ public abstract class HedgeRuleBaseState extends SimpleState implements ExpressionOwner { private Expression contentModel = null; public void onEndChild( Expression exp ) {// this method is called after child expression is found and parsed if( contentModel!=null ) reader.reportError( RELAXReader.ERR_MORE_THAN_ONE_CHILD_EXPRESSION ); // recover by ignoring previous expression contentModel = exp; } protected final void endSelf() { super.endSelf(); if( contentModel==null ) { reader.reportError( RELAXReader.ERR_MISSING_CHILD_EXPRESSION ); return; // recover by ignoring this hedgeRule. } endSelf(contentModel); // do something useful with child expression } /** derived class will receive child expression by this method */ protected abstract void endSelf( Expression contentModel ); protected State createChildState( StartTagInfo tag ) { // particles only return reader.createExpressionChildState(this,tag); } } msv-2009.1/msv/src/com/sun/msv/reader/relax/RELAXReader.java0000644000175000017500000001414011156747174023637 0ustar giovannigiovanni/* * @(#)$Id: RELAXReader.java 1744 2009-03-14 15:34:20Z bimargulies $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax; import java.text.MessageFormat; import java.util.ResourceBundle; import javax.xml.parsers.SAXParserFactory; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.reader.ChoiceState; import com.sun.msv.reader.GrammarReader; import com.sun.msv.reader.GrammarReaderController; import com.sun.msv.reader.SequenceState; import com.sun.msv.reader.State; import com.sun.msv.reader.TerminalState; import com.sun.msv.reader.datatype.xsd.FacetState; import com.sun.msv.reader.relax.core.InlineElementState; import com.sun.msv.util.StartTagInfo; /** * reads RELAX grammar/module by SAX2 and constructs abstract grammar model. * * @author Kohsuke KAWAGUCHI */ public abstract class RELAXReader extends GrammarReader { public RELAXReader( GrammarReaderController controller, SAXParserFactory parserFactory, StateFactory stateFactory, ExpressionPool pool, State initialState ) { super(controller,parserFactory,pool,initialState); this.sfactory = stateFactory; } /** Namespace URI of RELAX Core */ public static final String RELAXCoreNamespace = "http://www.xml.gr.jp/xmlns/relaxCore"; /** * creates various State object, which in turn parses grammar. * parsing behavior can be customized by implementing custom StateFactory. */ public static class StateFactory { protected State refLabel(State parent,StartTagInfo tag) { return new ElementRefState(); } protected State hedgeRef(State parent,StartTagInfo tag) { return new HedgeRefState(); } protected State choice(State parent,StartTagInfo tag) { return new ChoiceState(); } protected State none(State parent,StartTagInfo tag) { return new TerminalState(Expression.nullSet); } protected State empty(State parent,StartTagInfo tag) { return new TerminalState(Expression.epsilon); } protected State sequence(State parent,StartTagInfo tag) { return new SequenceState(); } protected FacetState facets(State parent,StartTagInfo tag) { return new FacetState(); } } public final StateFactory sfactory; public State createExpressionChildState( State parent, StartTagInfo tag ) { if(tag.localName.equals("ref")) return sfactory.refLabel(parent,tag); if(tag.localName.equals("hedgeRef")) return sfactory.hedgeRef(parent,tag); if(tag.localName.equals("choice")) return sfactory.choice(parent,tag); if(tag.localName.equals("none")) return sfactory.none(parent,tag); if(tag.localName.equals("empty")) return sfactory.empty(parent,tag); if(tag.localName.equals("sequence")) return sfactory.sequence(parent,tag); return null; // unknown element. let the default error be thrown. } public FacetState createFacetState( State parent, StartTagInfo tag ) { if(! RELAXCoreNamespace.equals(tag.namespaceURI) ) return null; if( FacetState.facetNames.contains(tag.localName) ) return sfactory.facets(parent,tag); else return null; } /** returns true if the given state can have "occurs" attribute. */ protected boolean canHaveOccurs( State state ) { return state instanceof SequenceState || state instanceof ElementRefState || state instanceof HedgeRefState || state instanceof ChoiceState || state instanceof InlineElementState; } protected Expression interceptExpression( State state, Expression exp ) { // handle occurs attribute here. final String occurs= state.getStartTag().getAttribute("occurs"); if( canHaveOccurs(state) ) {// these are the repeatable expressions if( occurs!=null ) { if( occurs.equals("?") ) exp = pool.createOptional(exp); else if( occurs.equals("+") ) exp = pool.createOneOrMore(exp); else if( occurs.equals("*") ) exp = pool.createZeroOrMore(exp); else reportError( ERR_ILLEGAL_OCCURS, occurs ); // recover from error by ignoring this occurs attribute } } else { if( occurs!=null ) reportError( ERR_MISPLACED_OCCURS, state.getStartTag().localName ); } return exp; } /** * obtains an Expression specified by given (namespace,label) pair. * this method is called to parse <ref label="..." /> element. */ protected abstract Expression resolveElementRef( String namespace, String label ); /** * obtains an Expression specified by given (namespace,label) pair. * this method is called to parse <hedgeRef label="..." /> element. */ protected abstract Expression resolveHedgeRef( String namespace, String label ); // error related service //============================================= protected String localizeMessage( String propertyName, Object[] args ) { String format; try { format = ResourceBundle.getBundle("com.sun.msv.reader.relax.Messages").getString(propertyName); } catch( Exception e ) { format = ResourceBundle.getBundle("com.sun.msv.reader.Messages").getString(propertyName); } return MessageFormat.format(format, args ); } protected ExpressionPool getPool() { return super.pool; } // error message public static final String ERR_ILLEGAL_OCCURS // arg:1 = "RELAXReader.IllegalOccurs"; public static final String ERR_MISPLACED_OCCURS // arg:1 = "RELAXReader.MisplacedOccurs"; } msv-2009.1/msv/src/com/sun/msv/reader/relax/Messages.properties0000644000175000017500000000624307300552602024652 0ustar giovannigiovanni## abstract error messages defined for RELAX GrammarReader.Abstract.MissingChildExpression =\ hedge model is missing GrammarReader.Abstract.MoreThanOneChildExpression =\ more than one hedge model is specified where only one is allowed GrammarReader.Abstract.RunAwayExpression =\ the following hedgeRules form an infinite recursion ( {0} ) GrammarReader.Abstract.MissingTopLevel =\ declaration was not found. ## RELAXReader error messages RELAXReader.NamespaceNotSupported =\ namespace attribute is not supported. RELAXReader.InconsistentTargetNamespace =\ module''s target namespace is "{0}" where "{1}" is expected RELAXReader.MissingTargetNamespace =\ "targetNamespace" attribute is required to use a module without a grammar. RELAXReader.IllegalOccurs =\ "{0}" is not allowed for "occurs", it must be one "*","?", or "+" RELAXReader.MisplacedOccurs =\ "{0}" element cannot have "occurs" attribute RELAXReader.MultipleTagDeclarations =\ "{0}" is defined by more than one "tag" element RELAXReader.MoreThanOneInlineTag =\ "elementRule" can only have at most one inner tag declaration RELAXReader.MultipleAttPoolDeclarations =\ "{0}" is defined by more than one "attPool" element RELAXReader.Warning.IllegalRelaxCoreVersion =\ Unsupported version: only RELAX Core Ver.1.0 is supported RELAXReader.LanguageNotSupported =\ "language" attribute is not yet supported RELAXReader.UndefinedElementRule =\ elementRule "{0}" is not defined RELAXReader.UndefinedHedgeRule =\ hedgeRule "{0}" is not defined RELAXReader.UndefinedTag =\ tag "{0}" is not defined RELAXReader.UndefinedAttPool =\ attPool "{0}" is not defined RELAXReader.LabelCollision =\ elementRule and hedgeRule declare the same label name "{0}" RELAXReader.RoleCollision =\ tag and attPool declare the same role name "{0}" RELAXReader.NoExportedLabel =\ at least one elementRule or hedgeRule must be exported RELAXReader.ExportedHedgeRuleConstraint =\ exported hedgeRule cannot reference labels of another namespace.\n\ dependencies are: {0} RELAXReader.MultipleAttributeConstraint =\ two s declare the same name "{0}", and \ are referenced from the same . RELAXReader.IdAbuse =\ Invalid use of an ID/IDREF or derived type. \ "ID", "IDREF", and types derived from them must have unique \ attribute names or their declarations must have unique tag \ names. RELAXReader.IdAbuse.1 =\ Invalid datatype used for attribute "{0}". Attributes used for \ "ID", "IDREF", and types derived from them must have unique \ attribute names or their declarations must have unique tag \ names. No other datatypes are allowed for this attribute name. ## RELAXNSReader error messages RELAXNSReader.Warning.IllegalRelaxNamespaceVersion =\ Unsupported version: only RELAX Namespace Ver.1.0 is supported RELAXNSReader.TopLevelParticleMustBeRelaxCore =\ children of has to be elements of the RELAX Core. RELAXNSReader.InlineModuleNotFound =\ "namespace" element has neither "moduleLocation" attribute nor child "module" element RELAXNSReader.UnknownLanguage =\ language "{0}" is not recognized. RELAXNSReader.NamespaceCollision =\ namespace "{0}" is defined by more than one module msv-2009.1/msv/src/com/sun/msv/reader/DOMLSInput.java0000644000175000017500000000061311164025612022405 0ustar giovannigiovannipackage com.sun.msv.reader; import org.w3c.dom.Element; /** * A GrammarReaderController2 may already have a DOM element for an imported schema. In that case, * we do not want to force the caller to serialize to bytes so that we can parse them again. * If the LSInput object implements this interface, it can return the Element. */ public interface DOMLSInput { Element getElement(); } msv-2009.1/msv/src/com/sun/msv/reader/util/0000755000175000017500000000000011622453066020630 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/reader/util/IgnoreController.java0000644000175000017500000000161707671170035024770 0ustar giovannigiovanni/* * @(#)$Id: IgnoreController.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.util; import org.xml.sax.InputSource; import org.xml.sax.Locator; import com.sun.msv.reader.GrammarReaderController; /** * Default implementation of GrammarReaderController. * * This class ignores every errors and warnings. * * @author Kohsuke KAWAGUCHI */ public class IgnoreController implements GrammarReaderController { public void warning( Locator[] locs, String errorMessage ) {} public void error( Locator[] locs, String errorMessage, Exception nestedException ) {} public InputSource resolveEntity( String p, String s ) { return null; } } msv-2009.1/msv/src/com/sun/msv/reader/util/ForkContentHandler.java0000644000175000017500000000524507671170035025234 0ustar giovannigiovanni/* * @(#)$Id: ForkContentHandler.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.util; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; /** * feeds SAX events to two ContentHandlers. * * @author Kohsuke KAWAGUCHI */ public class ForkContentHandler implements ContentHandler { protected ContentHandler lhs; protected ContentHandler rhs; public ForkContentHandler( ContentHandler lhs, ContentHandler rhs ) { this.lhs = lhs; this.rhs = rhs; } public void setDocumentLocator (Locator locator) { lhs.setDocumentLocator(locator); rhs.setDocumentLocator(locator); } public void startDocument() throws SAXException { lhs.startDocument(); rhs.startDocument(); } public void endDocument () throws SAXException { lhs.endDocument(); rhs.endDocument(); } public void startPrefixMapping (String prefix, String uri) throws SAXException { lhs.startPrefixMapping(prefix,uri); rhs.startPrefixMapping(prefix,uri); } public void endPrefixMapping (String prefix) throws SAXException { lhs.endPrefixMapping(prefix); rhs.endPrefixMapping(prefix); } public void startElement (String uri, String localName, String qName, Attributes attributes) throws SAXException { lhs.startElement(uri,localName,qName,attributes); rhs.startElement(uri,localName,qName,attributes); } public void endElement (String uri, String localName, String qName) throws SAXException { lhs.endElement(uri,localName,qName); rhs.endElement(uri,localName,qName); } public void characters (char ch[], int start, int length) throws SAXException { lhs.characters(ch,start,length); rhs.characters(ch,start,length); } public void ignorableWhitespace (char ch[], int start, int length) throws SAXException { lhs.ignorableWhitespace(ch,start,length); rhs.ignorableWhitespace(ch,start,length); } public void processingInstruction (String target, String data) throws SAXException { lhs.processingInstruction(target,data); rhs.processingInstruction(target,data); } public void skippedEntity (String name) throws SAXException { lhs.skippedEntity(name); rhs.skippedEntity(name); } } msv-2009.1/msv/src/com/sun/msv/reader/util/package.html0000644000175000017500000000007307273576330023120 0ustar giovannigiovanni

      Miscellaneous utilities

      msv-2009.1/msv/src/com/sun/msv/reader/util/GrammarLoader.java0000644000175000017500000004603307707533604024224 0ustar giovannigiovanni/* * @(#)$Id: GrammarLoader.java 1582 2003-07-23 16:27:48Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.util; import java.util.Vector; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; import org.iso_relax.verifier.Schema; import org.iso_relax.verifier.Verifier; import org.iso_relax.verifier.VerifierConfigurationException; import org.iso_relax.verifier.VerifierFilter; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.Grammar; import com.sun.msv.grammar.xmlschema.XMLSchemaGrammar; import com.sun.msv.reader.Controller; import com.sun.msv.reader.GrammarReader; import com.sun.msv.reader.GrammarReaderController; import com.sun.msv.reader.dtd.DTDReader; import com.sun.msv.reader.relax.core.RELAXCoreReader; import com.sun.msv.reader.trex.classic.TREXGrammarReader; import com.sun.msv.reader.trex.ng.comp.RELAXNGCompReader; import com.sun.msv.reader.xmlschema.XMLSchemaReader; import com.sun.msv.relaxns.reader.RELAXNSReader; import com.sun.msv.util.Util; import com.sun.msv.verifier.jaxp.SAXParserFactoryImpl; import com.sun.msv.verifier.regexp.REDocumentDeclaration; import com.sun.msv.verifier.regexp.xmlschema.XSREDocDecl; /** * loads any supported grammar (except XML DTD) * by automatically detecting the schema language. * *

      * The static version of loadVGM/loadSchema methods provides simple ways to * load a grammar. * *

      * Another way to use GrammarLoader is * *

        *
      1. To instanciate an object of GrammarLoader *
      2. call setXXX methods to configure the parameters *
      3. call loadSchema/loadVGM methods (possibly multiple times) to * load grammars. *
      * * This approach will give you finer control. * * @author Kohsuke KAWAGUCHI */ public class GrammarLoader { // // static utility methods //============================== // /** * parses the specified schema and returns the result as a VGM. * * This method is an utility method for those applications which * don't need AGM (e.g., a single thread application). * * @return * null if there was an error in the grammar. */ public static REDocumentDeclaration loadVGM( String url, GrammarReaderController controller, SAXParserFactory factory ) throws SAXException, ParserConfigurationException, java.io.IOException { Grammar g = loadSchema(url,controller,factory); if(g!=null) return wrapByVGM(g); else return null; } public static REDocumentDeclaration loadVGM( InputSource source, GrammarReaderController controller, SAXParserFactory factory ) throws SAXException, ParserConfigurationException, java.io.IOException { Grammar g = loadSchema(source,controller,factory); if(g!=null) return wrapByVGM(g); else return null; } private static REDocumentDeclaration wrapByVGM( Grammar g ) { if( g instanceof XMLSchemaGrammar ) return new XSREDocDecl((XMLSchemaGrammar)g); else return new REDocumentDeclaration(g); } /** * parses the specified schema and returns the result as a VGM. * * This method uses the default SAX parser and throws an exception * if there is an error in the schema. * * @return * non-null valid VGM object. */ public static REDocumentDeclaration loadVGM( String url ) throws SAXException, ParserConfigurationException, java.io.IOException { try { return loadVGM(url, new ThrowController(), null ); } catch( GrammarLoaderException e ) { throw e.e; } } public static REDocumentDeclaration loadVGM( InputSource source ) throws SAXException, ParserConfigurationException, java.io.IOException { try { return loadVGM(source, new ThrowController(), null ); } catch( GrammarLoaderException e ) { throw e.e; } } /** wrapper exception so that we can throw it from the GrammarReaderController. */ private static class GrammarLoaderException extends RuntimeException { GrammarLoaderException( SAXException e ) { super(e.getMessage()); this.e = e; } public final SAXException e; } private static class ThrowController implements GrammarReaderController { public void warning( Locator[] locs, String errorMessage ) {} public void error( Locator[] locs, String errorMessage, Exception nestedException ) { for( int i=0; i * If no SAXParserFactory is set, then the default parser is used. * (The parser that can be obtained by SAXParserFactory.newInstance()). */ public void setSAXParserFactory( SAXParserFactory factory ) { this.factory = factory; } public SAXParserFactory getSAXParserFactory() { if(factory==null) { factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); } return factory; } private Controller controller; /** * sets the GrammarReaderController object that will control * various aspects of the parsing. If not set, no error report will be * done. */ public void setController( GrammarReaderController controller ) { this.controller = new Controller(controller); } public Controller getController() { if(controller==null) controller = new Controller(new GrammarReaderController() { public void warning( Locator[] locs, String errorMessage ) {} public void error( Locator[] locs, String errorMessage, Exception nestedException ) {} public InputSource resolveEntity( String s, String p ) { return null; } }); return controller; } private ExpressionPool pool; /** * Sets the ExpressionPool object that will be used during the loading process. * If not set, a fresh one is used for each time the loadXXX method is called. */ public void setPool( ExpressionPool pool ) { this.pool = pool; } public ExpressionPool getPool() { if( pool==null) return new ExpressionPool(); else return pool; } private boolean strictCheck = false; /** * Sets the strict check flag. If set to true, schema readers will apply * stricter checks so that it can find errors in the schema. If set to false, * readers will skip some of the checks. * *

      * When this flag is set to false, which is the default, the reader may accept * incorrect schemas. */ public void setStrictCheck( boolean value ) { strictCheck = value; } public boolean getStrictCheck() { return strictCheck; } public Grammar parse( InputSource source ) throws SAXException, ParserConfigurationException, java.io.IOException { return _loadSchema(source); } public Grammar parse( String url ) throws SAXException, ParserConfigurationException, java.io.IOException { return _loadSchema(url); } public REDocumentDeclaration parseVGM( String url ) throws SAXException, ParserConfigurationException, java.io.IOException { Grammar g = _loadSchema(url); if(g==null) return null; else return new REDocumentDeclaration(g); } public REDocumentDeclaration parseVGM( InputSource source ) throws SAXException, ParserConfigurationException, java.io.IOException { Grammar g = _loadSchema(source); if(g==null) return null; else return new REDocumentDeclaration(g); } /** * Checks if the specified name has ".dtd" extension. */ private boolean hasDTDextension( String name ) { if(name==null) return false; int idx = name.length()-4; if(idx<0) return false; return name.substring(idx).equalsIgnoreCase(".dtd"); } /** * Actual "meat" of parsing schema. * * All other methods will ultimately come down to this method. */ private Grammar _loadSchema( Object source ) throws SAXException, ParserConfigurationException, java.io.IOException { // perform the auto detection to decide whether // it is XML syntax based schema or DTD. // TODO: implement more serious detection algorithm. // use the file extension to decide language type. // sure this is a sloppy job, but works in practice. // and easy to implement. boolean isDTD = false; if( source instanceof String ) { if( hasDTDextension( (String)source) ) isDTD = true; } if( source instanceof InputSource ) { if( hasDTDextension( ((InputSource)source).getSystemId() ) ) isDTD = true; } if(isDTD) { // load as DTD if( source instanceof String ) source = Util.getInputSource((String)source); return DTDReader.parse((InputSource)source,getController()); } // otherwise this schema is an XML syntax based schema. // this field will receive the grammar reader final GrammarReader[] reader = new GrammarReader[1]; final XMLReader parser = getSAXParserFactory().newSAXParser().getXMLReader(); /* Use a "sniffer" handler and decide which reader to use. Once the schema language is detected, the appropriate reader instance is created and events are passed to that handler. From the performance perspective, it is important not to create unnecessary reader objects. Because readers typically have a lot of references to other classes, instanciating a reader instance will cause a lot of class loadings in the first time, which makes non-trivial difference in the performance. */ parser.setContentHandler( new DefaultHandler(){ private Locator locator; private Vector prefixes = new Vector(); public void setDocumentLocator( Locator loc ) { this.locator = loc; } public void startPrefixMapping( String prefix, String uri ) { prefixes.add( new String[]{prefix,uri} ); } /** * Sets up the pipe line of "VerifierFilter > GrammarReader" * so that the grammar will be properly validated. */ private ContentHandler setupPipeline( Schema schema ) throws SAXException { try { Verifier v = schema.newVerifier(); v.setErrorHandler(getController()); v.setEntityResolver(getController()); VerifierFilter filter = v.getVerifierFilter(); filter.setContentHandler(reader[0]); return (ContentHandler)filter; } catch( VerifierConfigurationException vce ) { throw new SAXException(vce); } } public void startElement( String namespaceURI, String localName, String qName, Attributes atts ) throws SAXException { ContentHandler winner; // sniff the XML and decide the reader to use. if( localName.equals("module") ) { // assume RELAX Core. if( strictCheck ) { Schema s = RELAXCoreReader.getRELAXCoreSchema4Schema(); reader[0] = new RELAXCoreReader( getController(), new SAXParserFactoryImpl(getSAXParserFactory(),s), getPool() ); winner = setupPipeline(s); } else { winner = reader[0] = new RELAXCoreReader( getController(),getSAXParserFactory(),getPool()); } } else if( localName.equals("schema") ) { // assume W3C XML Schema if( strictCheck ) { Schema s = XMLSchemaReader.getXmlSchemaForXmlSchema(); reader[0] = new XMLSchemaReader( getController(), new SAXParserFactoryImpl(getSAXParserFactory(),s), getPool() ); winner = setupPipeline(s); } else { winner = reader[0] = new XMLSchemaReader( getController(),getSAXParserFactory(),getPool()); } } else if( RELAXNSReader.RELAXNamespaceNamespace.equals(namespaceURI) ) // assume RELAX Namespace winner = reader[0] = new RELAXNSReader( getController(), getSAXParserFactory(), getPool() ); else if( TREXGrammarReader.TREXNamespace.equals(namespaceURI) || namespaceURI.equals("") ) // assume TREX winner = reader[0] = new TREXGrammarReader( getController(), getSAXParserFactory(), getPool() ); else { // otherwise assume RELAX NG if( strictCheck ) { Schema s = RELAXNGCompReader.getRELAXNGSchema4Schema(); reader[0] = new RELAXNGCompReader( getController(), new SAXParserFactoryImpl(getSAXParserFactory(),s), getPool() ); winner = setupPipeline(s); } else { winner = reader[0] = new RELAXNGCompReader( getController(), getSAXParserFactory(), getPool() ); } } // simulate the start of the document. winner.setDocumentLocator(locator); winner.startDocument(); for( int i=0; i * Responsibility of derived classes are: * *

        *
      1. if necessary, implement startSelf method to do something. *
      2. implement createChildState method, which is mandated by SimpleState. *
      3. implement makeExpression method to create Expression object * as the outcome of parsing. This method is called at endElement. *
      * * @author Kohsuke KAWAGUCHI */ public abstract class ExpressionState extends SimpleState { protected void endSelf() { // creates a expression, then calls a hook of reader, Expression exp = reader.interceptExpression( this, makeExpression() ); if( parentState!=null ) // then finally pass it to the parent ((ExpressionOwner)parentState).onEndChild(exp); // interceptExpression is a hook by reader. // it is used to implement handling of occurs attribute in RELAX. // application-defined reader can also do something useful for them here. super.endSelf(); } /** * This method is called from endElement method. * Implementation has to provide Expression object that represents the content of * this element. */ protected abstract Expression makeExpression(); } msv-2009.1/msv/src/com/sun/msv/reader/Controller.java0000644000175000017500000000664511156723336022656 0ustar giovannigiovannipackage com.sun.msv.reader; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.ls.LSResourceResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.LocatorImpl; /** * Internal view of GrammarReaderController. * * This class wraps a GrammarReaderController and * adds several convenient methods for the caller. */ public class Controller implements GrammarReaderController2, ErrorHandler { /** Controller works as a wrapper to this object. */ private final GrammarReaderController core; public GrammarReaderController getCore() { return core; } /** This flag will be set to true in case of any error. */ private boolean _hadError = false; /** Returns true if an error had been reported. */ public boolean hadError() { return _hadError; } /** Force set the error flag to true. */ public final void setErrorFlag() { _hadError=true; } public Controller( GrammarReaderController _core ) { this.core = _core; } @Deprecated public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return core.resolveEntity(publicId, systemId); } public void warning( Locator[] locs, String errorMessage ) { core.warning(locs,errorMessage); } public void error( Locator[] locs, String errorMessage, Exception nestedException ) { setErrorFlag(); core.error(locs,errorMessage,nestedException); } public void error( String errorMessage, Exception nestedException ) { error( new Locator[0], errorMessage, nestedException ); } public void fatalError( SAXParseException spe ) { error(spe); } public void error( SAXParseException spe ) { error( getLocator(spe), spe.getMessage(), spe.getException() ); } public void warning( SAXParseException spe ) { warning( getLocator(spe), spe.getMessage() ); } public void error( IOException e, Locator source ) { error( new Locator[]{source}, e.getMessage(), e ); } public void error( SAXException e, Locator source ) { // if a nested exception is a RuntimeException, // this shouldn't be handled. if( e.getException() instanceof RuntimeException ) throw (RuntimeException)e.getException(); if(e instanceof SAXParseException) error( (SAXParseException)e ); else error( new Locator[]{source}, e.getMessage(), e ); } public void error( ParserConfigurationException e, Locator source ) { error( new Locator[]{source}, e.getMessage(), e ); } protected Locator[] getLocator( SAXParseException spe ) { LocatorImpl loc = new LocatorImpl(); loc.setColumnNumber( spe.getColumnNumber() ); loc.setLineNumber( spe.getLineNumber() ); loc.setSystemId( spe.getSystemId() ); loc.setPublicId( spe.getPublicId() ); return new Locator[]{loc}; } /** * Return the full resolver. */ public LSResourceResolver getLSResourceResolver() { if (core instanceof GrammarReaderController2) { return ((GrammarReaderController2)core).getLSResourceResolver(); } else { return null; } } } msv-2009.1/msv/src/com/sun/msv/reader/TerminalState.java0000644000175000017500000000143607671170035023277 0ustar giovannigiovanni/* * @(#)$Id: TerminalState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader; import com.sun.msv.grammar.Expression; /** * State that always returns the same expression. * * Typically used for <empty/>, <notAllowed/> and <text/> of RELAX NG. * * @author Kohsuke KAWAGUCHI */ public class TerminalState extends ExpressionWithoutChildState { private final Expression exp; public TerminalState( Expression exp ) { this.exp = exp; } protected Expression makeExpression() { return exp; } } msv-2009.1/msv/src/com/sun/msv/reader/GrammarReader.java0000644000175000017500000010213011164025612023215 0ustar giovannigiovanni/* * @(#)$Id: GrammarReader.java 1751 2009-03-30 02:16:42Z bimargulies $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.util.Vector; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.Source; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.sax.SAXSource; import org.relaxng.datatype.Datatype; import org.w3c.dom.ls.LSInput; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.LocatorImpl; import org.xml.sax.helpers.XMLFilterImpl; import com.sun.msv.datatype.xsd.XSDatatype; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.Grammar; import com.sun.msv.grammar.IDContextProvider2; import com.sun.msv.grammar.ReferenceContainer; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.reader.datatype.xsd.XSDatatypeExp; import com.sun.msv.util.StartTagInfo; import com.sun.msv.util.Uri; import com.sun.msv.verifier.regexp.StringToken; /** * base implementation of grammar readers that read grammar from SAX2 stream. * * GrammarReader class can be used as a ContentHandler that parses a grammar. * So the typical usage is *
      
       * 
       * GrammarReader reader = new RELAXGrammarReader(...);
       * XMLReader parser = .... // create a new XMLReader here
       * 
       * parser.setContentHandler(reader);
       * parser.parse(whateverYouLike);
       * return reader.grammar;  // obtain parsed grammar.
       * 
      * * Or you may want to use several pre-defined static "parse" methods for * ease of use. * * @seealso com.sun.msv.reader.relax.RELAXReader#parse * @seealso com.sun.msv.reader.trex.TREXGrammarReader#parse * * @author Kohsuke KAWAGUCHI */ public abstract class GrammarReader extends XMLFilterImpl implements IDContextProvider2 { /** document Locator that is given by XML reader */ private Locator locator; /** this object receives errors and warnings */ public final Controller controller; /** Reader may create another SAXParser from this factory */ public final SAXParserFactory parserFactory; /** this object must be used to create a new expression */ public final ExpressionPool pool; /** * Creates a default SAXParserFactory. */ protected static SAXParserFactory createParserFactory() { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); return factory; } /** constructor that should be called from parse method. */ protected GrammarReader( GrammarReaderController _controller, SAXParserFactory parserFactory, ExpressionPool pool, State initialState ) { this.controller = new Controller(_controller); this.parserFactory = parserFactory; // parserFactory may be null when using javax.xml.transform. if (parserFactory != null && !parserFactory.isNamespaceAware()) { throw new IllegalArgumentException("parser factory must be namespace-aware"); } this.pool = pool; pushState( initialState, null, null ); } /** * gets the parsed AGM. * * Should any error happens, this method should returns null. * * derived classes should implement type-safe getGrammar method, * along with this method. */ public abstract Grammar getResultAsGrammar(); /** checks if given element is that of the grammar elements. */ protected abstract boolean isGrammarElement( StartTagInfo tag ); /** * namespace prefix to URI conversion map. * this variable is evacuated to InclusionContext when the parser is switched. */ public static interface PrefixResolver { /** returns URI. Or null if the prefix is not declared. */ String resolve( String prefix ); } /** * The namespace prefix resolver that only resolves "xml" prefix. * This class should be used as the base resolver. */ public static final PrefixResolver basePrefixResolver = new PrefixResolver() { public String resolve( String prefix ) { if(prefix.equals("xml")) return "http://www.w3.org/XML/1998/namespace"; else return null; } }; public class ChainPrefixResolver implements PrefixResolver { public ChainPrefixResolver( String prefix, String uri ) { this.prefix=prefix;this.uri=uri; this.previous = prefixResolver; } public String resolve( String p ) { if(p.equals(prefix)) return uri; else return previous.resolve(p); } public final PrefixResolver previous; public final String prefix; public final String uri; } // public NamespaceSupport namespaceSupport = new NamespaceSupport(); public PrefixResolver prefixResolver = basePrefixResolver; public void startPrefixMapping( String prefix, String uri ) throws SAXException { prefixResolver = new ChainPrefixResolver(prefix,uri); super.startPrefixMapping(prefix,uri); } public void endPrefixMapping(String prefix) throws SAXException { prefixResolver = ((ChainPrefixResolver)prefixResolver).previous; super.endPrefixMapping(prefix); } /** * Iterates Map.Entry objects which has the prefix as key and * the namespace URI as value. */ public Iterator iterateInscopeNamespaces() { return new Iterator() { private PrefixResolver resolver = proceed(prefixResolver); public Object next() { final ChainPrefixResolver cpr = (ChainPrefixResolver)resolver; resolver = proceed(cpr.previous); return new Map.Entry() { public Object getKey() { return cpr.prefix; } public Object getValue() { return cpr.uri; } public Object setValue(Object o) { throw new UnsupportedOperationException(); } }; } public boolean hasNext() { return resolver instanceof ChainPrefixResolver; } private PrefixResolver proceed( PrefixResolver resolver ) { while(true) { if(!(resolver instanceof ChainPrefixResolver)) return resolver; // reached at the end ChainPrefixResolver cpr = (ChainPrefixResolver)resolver; if(resolveNamespacePrefix(cpr.prefix)==cpr.uri) return resolver; // this resolver is in-scope resolver = cpr.previous; } } public void remove() { throw new UnsupportedOperationException(); } }; } /** * Resolves a QName into a pair of (namespace URI,local name). * Therefore this method returns null if it fails to process QName. */ public String[] splitQName( String qName ) { int idx = qName.indexOf(':'); if(idx<0) { String ns = prefixResolver.resolve(""); // if the default namespace is not bounded, return "". // this behavior is consistent with SAX. if(ns==null) ns=""; return new String[]{ns,qName,qName}; } String uri = prefixResolver.resolve(qName.substring(0,idx)); if(uri==null) return null; // prefix is not defined. return new String[]{uri, qName.substring(idx+1), qName}; } /** * intercepts an expression made by ExpressionState * before it is passed to the parent state. * * derived class can perform further wrap-up before it is received by the parent. * This mechanism is used by RELAXReader to handle occurs attribute. */ protected Expression interceptExpression( State state, Expression exp ) { return exp; } /** * tries to obtain a DataType object by resolving obsolete names. * this method is useful for backward compatibility purpose. */ public XSDatatype getBackwardCompatibleType( String typeName ) { /* This method is not heavily used. So it is a good idea not to create a reference to the actual instance unless it's absolutely necessary, so that the class loader doesn't load the datatype class easily. If we use a map, it makes the class loader loads all classes. */ XSDatatype dt = null; if( typeName.equals("uriReference") ) dt = com.sun.msv.datatype.xsd.AnyURIType.theInstance; else if( typeName.equals("number") ) dt = com.sun.msv.datatype.xsd.NumberType.theInstance; else if( typeName.equals("timeDuration") ) dt = com.sun.msv.datatype.xsd.DurationType.theInstance; else if( typeName.equals("CDATA") ) dt = com.sun.msv.datatype.xsd.NormalizedStringType.theInstance; else if( typeName.equals("year") ) dt = com.sun.msv.datatype.xsd.GYearType.theInstance; else if( typeName.equals("yearMonth") ) dt = com.sun.msv.datatype.xsd.GYearMonthType.theInstance; else if( typeName.equals("month") ) dt = com.sun.msv.datatype.xsd.GMonthType.theInstance; else if( typeName.equals("monthDay") ) dt = com.sun.msv.datatype.xsd.GMonthDayType.theInstance; else if( typeName.equals("day") ) dt = com.sun.msv.datatype.xsd.GDayType.theInstance; if( dt!=null ) reportWarning( WRN_DEPRECATED_TYPENAME, typeName, dt.displayName() ); return dt; } // parsing and related services //====================================================== /** * information that must be sheltered before switching InputSource * (typically by inclusion). * * It is chained by previousContext field and used as a stack. */ private class InclusionContext { final PrefixResolver prefixResolver; final Locator locator; final String systemId; final InclusionContext previousContext; InclusionContext( PrefixResolver prefix, Locator loc, String sysId, InclusionContext prev ) { this.prefixResolver = prefix; this.locator = loc; this.systemId = sysId; this.previousContext = prev; } } /** current inclusion context */ private InclusionContext pendingIncludes; private void pushInclusionContext( ) { pendingIncludes = new InclusionContext( prefixResolver, getLocator(), getLocator().getSystemId(), pendingIncludes ); prefixResolver = basePrefixResolver; setLocator(null); } private void popInclusionContext() { prefixResolver = pendingIncludes.prefixResolver; setLocator(pendingIncludes.locator); pendingIncludes = pendingIncludes.previousContext; } /** * obtains InputSource for the specified url. * * Also this method allows GrammarReaderController to redirect or * prohibit inclusion. * * @param sourceState * The base URI of this state is used to resolve the resource. * * @return * always return non-null valid object */ public final InputSource resolveLocation( State sourceState, String uri ) throws AbortException { try { // resolve a relative URI to an absolute one uri = combineURI( sourceState.getBaseURI(), uri ); InputSource source = controller.resolveEntity(null,uri); if(source==null) return new InputSource(uri); // default handling else return source; // in case of an error, throw the AbortException } catch( IOException e ) { controller.error(e,getLocator()); } catch( SAXException e ) { controller.error(e,getLocator()); } throw AbortException.theInstance; } /** * converts the relative URL to the absolute one by using the specified base URL. */ public final String combineURI( String baseURI, String relativeURI ) { return Uri.resolve(baseURI,relativeURI); } /** * @deprecated use the combineURI method. */ public final String combineURL( String baseURI, String relativeURI ) { return Uri.resolve(baseURI,relativeURI); } /** * Switchs InputSource to the specified URL and * parses it by the specified state. * * The method will return after the parsing of the new source is completed. * derived classes can use this method to realize semantics of 'include'. * * @param sourceState * this state is used to resolve the URL. * @param newState * this state will parse top-level of new XML source. * this state receives document element by its createChildState method. */ public void switchSource( State sourceState, String url, State newState ) throws AbortException { if( url.indexOf('#')>=0 ) { // this href contains the fragment identifier. // we cannot handle them properly. reportError( ERR_FRAGMENT_IDENTIFIER, url ); throw AbortException.theInstance; } switchSource( resolveLocation(sourceState,url), newState ); } /** * start reading input from a source defined by a SAX InputSource. * @param source * @param newState */ public void switchSource(InputSource source, State newState) { switchSource(new SAXSource(source), newState); } /** * Start reading input from a source defined by a javax.xml.transform source. * @param source * @param newState */ public void switchSource(Source source, State newState ) { String url = source.getSystemId(); for( InclusionContext ic = pendingIncludes; ic!=null; ic=ic.previousContext ) if (ic.systemId != null && ic.systemId.equals(url) ) { // recursive include. // computes what files are recurisve. String s=""; for( InclusionContext i = pendingIncludes; i!=ic; i=i.previousContext ) s = i.systemId + " > " + s; s = url + " > " + s + url; reportError( ERR_RECURSIVE_INCLUDE, s ); return; // recover by ignoring this include. } pushInclusionContext(); State currentState = getCurrentState(); try { // this state will receive endDocument event. pushState( newState, null, null ); try { parse(source); } catch (TransformerConfigurationException e) { controller.error("transform error", e); } catch (TransformerException e) { controller.error("transform error", e); } } finally { // restore the current state. super.setContentHandler(currentState); popInclusionContext(); } } /** parses a grammar from the specified source */ public final void parse( String source ) { _parse(source,null); } /** parses a grammar from the specified source */ public final void parse( InputSource source ) { _parse(source,null); } /** * Parse from an arbitrary javax.xml.transform source. * If the Source can be processed by {@link SAXSource#sourceToInputSource(Source)}, * then this API will use that. Otherwise, it will use a transformer to * create a stream of SAX events. In that later case, the grammar controller * will not be called for any errors on the source side or to resolve * any references; the caller is responsible for making separate arrangements. * @param source * @throws TransformerConfigurationException * @throws TransformerException */ public void parse(Source source) throws TransformerConfigurationException, TransformerException { InputSource saxSource = SAXSource.sourceToInputSource(source); if (saxSource != null) { parse(saxSource); } else { /* a sax parser will always set up a locator to the ID information * in the InputSource. TraX does not do this, so we have to. */ LocatorImpl sourceLocator = new LocatorImpl(); sourceLocator.setSystemId(source.getSystemId()); setLocator(sourceLocator); // take an arbitrary TraX source. TransformerFactory factory = TransformerFactory.newInstance(); SAXResult result = new SAXResult(this); factory.newTransformer().transform(source, result); } } /** parses a grammar from the specified source */ public final void _parse( Object source, Locator errorSource ) { try { XMLReader reader = parserFactory.newSAXParser().getXMLReader(); reader.setContentHandler(this); reader.setErrorHandler(controller); reader.setEntityResolver(controller); // invoke XMLReader if( source instanceof InputSource ) reader.parse((InputSource)source); if( source instanceof String ) reader.parse((String)source); } catch( ParserConfigurationException e ) { controller.error(e,errorSource); } catch( IOException e ) { controller.error(e,errorSource); } catch( SAXParseException e ) { controller.error(e); } catch( SAXException e ) { controller.error( e, errorSource ); } // TODO: shall we throw AbortException here? } /** * memorizes what declarations are referenced from where. * * this information is used to report the source of errors. */ public class BackwardReferenceMap { private final Map impl = new java.util.HashMap(); /** memorize a reference to an object. */ public void memorizeLink( Object target ) { ArrayList list; if( impl.containsKey(target) ) list = (ArrayList)impl.get(target); else { // new target. list = new ArrayList(); impl.put(target,list); } list.add(new LocatorImpl(getLocator())); } /** * gets all the refer who have a reference to this object. * @return null * if no one refers it. */ public Locator[] getReferer( Object target ) { // TODO: does anyone want to get all of the referer? if( impl.containsKey(target) ) { ArrayList lst = (ArrayList)impl.get(target); Locator[] locs = new Locator[lst.size()]; lst.toArray(locs); return locs; } else return null; } } /** keeps track of all backward references to every ReferenceExp. * * this map should be used to report the source of error * of undefined-something. */ public final BackwardReferenceMap backwardReference = new BackwardReferenceMap(); /** this map remembers where ReferenceExps are defined, * and where user defined types are defined. * * some ReferenceExp can be defined * in more than one location. * In those cases, the last one is always memorized. * This behavior is essential to correctly implement * TREX constraint that no two <define> is allowed in the same file. */ private final Map declaredLocations = new java.util.HashMap(); public void setDeclaredLocationOf( Object o ) { declaredLocations.put(o, new LocatorImpl(getLocator()) ); } public Locator getDeclaredLocationOf( Object o ) { return (Locator)declaredLocations.get(o); } /** * detects undefined ReferenceExp and reports it as an error. * * this method is used in the final wrap-up process of parsing. */ public void detectUndefinedOnes( ReferenceContainer container, String errMsg ) { Iterator itr = container.iterator(); while( itr.hasNext() ) { // ReferenceExp object is created when it is first referenced or defined. // its exp field is supplied when it is defined. // therefore, ReferenceExp with its exp field null means // it is referenced but not defined. ReferenceExp ref = (ReferenceExp)itr.next(); if( !ref.isDefined() ) { reportError( backwardReference.getReferer(ref), errMsg, new Object[]{ref.name} ); ref.exp=Expression.nullSet; // recover by assuming a null definition. } } } // // stack of State objects and related services //============================================================ /** pushs the current state into the stack and sets new one */ public void pushState( State newState, State parentState, StartTagInfo startTag ) { super.setContentHandler(newState); newState.init( this, parentState, startTag ); // this order of statements ensures that // getCurrentState can be implemented by using getContentHandler() } /** pops the previous state from the stack */ public void popState() { State currentState = getCurrentState(); if( currentState.parentState!=null ) super.setContentHandler( currentState.parentState ); else // if the root state is poped, supply a dummy. super.setContentHandler( new org.xml.sax.helpers.DefaultHandler() ); } /** gets current State object. */ public final State getCurrentState() { return (State)super.getContentHandler(); } /** * this method must be implemented by the derived class to create * language-default expresion state. * * @return null if the start tag is an error. */ public abstract State createExpressionChildState( State parent, StartTagInfo tag ); public void setDocumentLocator( Locator loc ) { super.setDocumentLocator(loc); this.setLocator(loc); } // validation context provider //============================================ // implementing ValidationContextProvider is neccessary // to correctly handle facets. public String resolveNamespacePrefix( String prefix ) { return prefixResolver.resolve(prefix); } public boolean isUnparsedEntity( String entityName ) { // we have to allow everything here? return true; } public boolean isNotation( String notationName ) { return true; } public String getBaseUri() { return getCurrentState().getBaseURI(); } // when the user uses enumeration over ID type, // this method will be called. // To make it work, simply allow everything. public final void onID( Datatype dt, StringToken token ) {} // back patching //=========================================== /* several things cannot be done at the moment when the declaration is seen. These things have to be postponed until all the necessary information is prepared. (e.g., generating the expression that matches to ). those jobs are queued here and processed after the parsing is completed. Note that there is no mechanism in this class to execute jobs. The derived class has to decide its own timing to perform jobs. */ public static interface BackPatch { /** do back-patching. */ void patch(); /** gets State object who has submitted this patch job. */ State getOwnerState(); } private final Vector backPatchJobs = new Vector(); private final Vector delayedBackPatchJobs = new Vector(); public final void addBackPatchJob( BackPatch job ) { backPatchJobs.add(job); } public final void addBackPatchJob( XSDatatypeExp job ) { // UGLY. DatatypeExp patching needs to run after // other back patch jobs, so we use two sets. delayedBackPatchJobs.add(job); } /** Performs all back-patchings. */ public final void runBackPatchJob() { Locator oldLoc = getLocator(); runBackPatchJob(backPatchJobs); runBackPatchJob(delayedBackPatchJobs); setLocator(oldLoc); } private final void runBackPatchJob( Vector vec ) { Iterator itr = vec.iterator(); while( itr.hasNext() ) { BackPatch job = ((BackPatch)itr.next()); // so that errors reported in the patch job will have // position of its start tag. setLocator(job.getOwnerState().getLocation()); job.patch(); } } // error related services //======================================================== public final void reportError( String propertyName ) { reportError( propertyName, null, null, null ); } public final void reportError( String propertyName, Object arg1 ) { reportError( propertyName, new Object[]{arg1}, null, null ); } public final void reportError( String propertyName, Object arg1, Object arg2 ) { reportError( propertyName, new Object[]{arg1,arg2}, null, null ); } public final void reportError( String propertyName, Object arg1, Object arg2, Object arg3 ) { reportError( propertyName, new Object[]{arg1,arg2,arg3}, null, null ); } public final void reportError( Exception nestedException, String propertyName ) { reportError( propertyName, null, nestedException, null ); } public final void reportError( Exception nestedException, String propertyName, Object arg1 ) { reportError( propertyName, new Object[]{arg1}, nestedException, null ); } public final void reportError( Locator[] locs, String propertyName, Object[] args ) { reportError( propertyName, args, null, locs ); } public final void reportWarning( String propertyName ) { reportWarning( propertyName, null, null ); } public final void reportWarning( String propertyName, Object arg1 ) { reportWarning( propertyName, new Object[]{arg1}, null ); } public final void reportWarning( String propertyName, Object arg1, Object arg2 ) { reportWarning( propertyName, new Object[]{arg1,arg2}, null ); } private Locator[] prepareLocation( Locator[] param ) { // if null is given, use the current location. if( param!=null ) { int cnt=0; for( int i=0; iKohsuke KAWAGUCHI */ public class SequenceState extends ExpressionWithChildState { public SequenceState() { this(false); } public SequenceState( boolean allowEmptySequence ) { this.allowEmptySequence = allowEmptySequence; } protected boolean allowEmptySequence; protected Expression initialExpression() { return allowEmptySequence?Expression.epsilon:null; } protected Expression castExpression( Expression exp, Expression child ) { // first one. if( exp==null ) return child; return reader.pool.createSequence(exp,child); } } msv-2009.1/msv/src/com/sun/msv/reader/State.java0000644000175000017500000001516311156747174021614 0ustar giovannigiovanni/* * @(#)$Id: State.java 1744 2009-03-14 15:34:20Z bimargulies $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.helpers.LocatorImpl; import com.sun.msv.grammar.Expression; import com.sun.msv.util.StartTagInfo; /** * base interface of 'parsing state'. * * parsing of XML representation of a grammar is done by * using various states. * *

      * Each State-derived class is responsible for a particular type of * declaration of the grammar. For example, SequenceState is responsible * for parsing <sequence> element of RELAX module. * *

      * State objects interact each other. There are two ways of interaction. * *

        *
      • from parent to child *
      • from child to parent *
      * * The first type of communication occurs only when a child state object is * created. The last type of communication occurs usually (but not limited to) * when a child state sees its end tag. * * *

      * In this level of inheritance, contract is somewhat abstract. * *

        *
      1. When a State object is created, its init method is called * and various information is set. Particularly, start tag * information (if any) and the parent state is set. * This process should only be initiated by GrammarReader. * *
      2. After that, startSelf method is called. Usually, * this is the place to do something useful. * *
      3. State object is registered as a ContentHandler, and * therefore will receive SAX events from now on. * *
      4. Derived classes are expected to do something useful * by receiving SAX events. * *
      5. When a State object finishes its own part, it should * call GrammarReader.popState method. It will remove * the current State object and registers the parent state * as a ContentHandler again. *
      * * Of course some derived classes introduce more restricted * contract. See {@link SimpleState}. * *

      * this class also provides: *

        *
      • access to the parent state *
      • default implementations for all ContentHandler callbacks * except startElement and endElement *
      * * @author Kohsuke KAWAGUCHI */ public abstract class State implements ContentHandler { /** * parent state of this state. * * In other words, the parent state is a state who is responsible * for the parent element of the current element. * * For states responsible for the document element, the parent state is * a state who is responsible for the entire document. * * For states responsible for the entire document, the parent state is * always null. */ protected State parentState; public final State getParentState() { return parentState; } /** * reader object who is the owner of this object. * This information is avaiable after init method is called. */ public GrammarReader reader; /** * information of the start tag. * This information is avaiable after init method is called. */ protected StartTagInfo startTag; public StartTagInfo getStartTag() { return startTag; } /** * Location of the start tag. * This information is avaiable after init method is called. */ protected Locator location; public Locator getLocation() { return location; } /** * base URI for this state. * This information is avaiable after init method is called. */ protected String baseURI; public String getBaseURI() { return baseURI; } protected final void init( GrammarReader reader, State parentState, StartTagInfo startTag ) { // use of the constructor, which is usually the preferable way, // is intentionally avoided for short hand. // if we use the constructor to do the initialization, every derived class // has to have a dumb constructor, which simply delegates all the parameter // to the super class. this.reader = reader; this.parentState = parentState; this.startTag = startTag; if( reader.getLocator()!=null ) // locator could be null, in case of the root state. this.location = new LocatorImpl( reader.getLocator() ); // handle the xml:base attribute. String base=null; if( startTag!=null ) base = startTag.getAttribute("http://www.w3.org/XML/1998/namespace","base"); if( parentState==null ) // this state is the root state and therefore we don't have locator. this.baseURI = null; else { this.baseURI = parentState.baseURI; if( this.baseURI==null ) this.baseURI = reader.getLocator().getSystemId(); } if( base!=null ) this.baseURI = reader.combineURI( this.baseURI, base ); startSelf(); } /** performs a task that should be done before reading any child elements. * * derived-class can safely read startTag and/or parentState values. */ protected void startSelf() {} public static void _assert( boolean b ) { if(!b) throw new InternalError(); } public void characters(char[] buffer, int from, int len ) throws SAXException { // both RELAX and TREX prohibits characters in their grammar. for( int i=from; iKohsuke KAWAGUCHI */ public interface TypeOwner { void onEndChildType( Expression datatype, String typeName ); } msv-2009.1/msv/src/com/sun/msv/reader/datatype/xsd/0000755000175000017500000000000011622453066022264 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/reader/datatype/xsd/FacetState.java0000644000175000017500000000362407671170035025160 0ustar giovannigiovanni/* * @(#)$Id: FacetState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.datatype.xsd; import java.util.Set; import org.relaxng.datatype.DatatypeException; import com.sun.msv.reader.ChildlessState; import com.sun.msv.reader.GrammarReader; /** * state that reads facets. * * @author Kohsuke KAWAGUCHI */ public class FacetState extends ChildlessState { /** set of recognizable facet names */ public static final Set facetNames = initFacetNames(); static private Set initFacetNames() { Set s = new java.util.HashSet(); s.add("length"); s.add("minLength"); s.add("maxLength"); s.add("pattern"); s.add("enumeration"); s.add("maxInclusive"); s.add("minInclusive"); s.add("maxExclusive"); s.add("minExclusive"); s.add("whiteSpace"); s.add("fractionDigits"); s.add("totalDigits"); return s; } protected void startSelf() { super.startSelf(); final String value = startTag.getAttribute("value"); if( value==null ) { reader.reportError( GrammarReader.ERR_MISSING_ATTRIBUTE, startTag.localName, "value" ); // recover by ignoring this facet. } else { try { ((FacetStateParent)parentState).getIncubator().addFacet( startTag.localName, value, "true".equals(startTag.getAttribute("fixed")), reader ); } catch( DatatypeException e ) { reader.reportError( e, GrammarReader.ERR_BAD_TYPE, e.getMessage() ); // recover by ignoring this facet } } } } msv-2009.1/msv/src/com/sun/msv/reader/datatype/xsd/TypeState.java0000644000175000017500000000747211156747174025073 0ustar giovannigiovanni/* * @(#)$Id: TypeState.java 1744 2009-03-14 15:34:20Z bimargulies $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.datatype.xsd; import org.relaxng.datatype.DatatypeException; import org.xml.sax.Attributes; import org.xml.sax.helpers.AttributesImpl; import com.sun.msv.datatype.xsd.StringType; import com.sun.msv.reader.ExpressionOwner; import com.sun.msv.reader.GrammarReader; import com.sun.msv.reader.IgnoreState; import com.sun.msv.reader.SimpleState; import com.sun.msv.reader.State; import com.sun.msv.reader.datatype.TypeOwner; import com.sun.msv.util.StartTagInfo; /** * Base implementation for those states which produce a type object * as its parsing result. * * @author Kohsuke KAWAGUCHI */ abstract class TypeState extends SimpleState { /** Gets the parent state as TypeOwner. */ private XSTypeOwner getParent() { if( parentState instanceof XSTypeOwner ) return (XSTypeOwner)parentState; else return null; // parent is allowed not to implement this interface } public final String getTargetNamespaceUri() { XSTypeOwner parent = getParent(); if(parent!=null) return getParent().getTargetNamespaceUri(); else return ""; // we don't have the notion of the namespace URI in this context } public void endSelf() { super.endSelf(); XSDatatypeExp type = _makeType(); if( parentState instanceof XSTypeOwner ) { ((XSTypeOwner)parentState).onEndChild(type); return; } if( parentState instanceof TypeOwner ) { // if the parent can understand what we are creating, // then pass the result. ((TypeOwner)parentState).onEndChildType(type,type.name); return; } if( parentState instanceof ExpressionOwner ) { ((ExpressionOwner)parentState).onEndChild(type); return; } // we have no option to let the parent state know our result. throw new Error(parentState.getClass().getName()+" doesn't implement any of TypeOwner"); } /** the makeType method with protection against possible exception. */ XSDatatypeExp _makeType() { try { return makeType(); } catch( DatatypeException be ) { reader.reportError( be, GrammarReader.ERR_BAD_TYPE ); // recover by assuming a valid type. return new XSDatatypeExp(StringType.theInstance,reader.pool); } } /** * This method is called from endElement method. * Implementation has to provide DataType object that represents the content of * this element. */ protected abstract XSDatatypeExp makeType() throws DatatypeException; public final void startElement( String namespaceURI, String localName, String qName, Attributes atts ) {// within the island of XSD, foreign namespaces are prohibited. final StartTagInfo tag = new StartTagInfo( namespaceURI,localName,qName,new AttributesImpl(atts)); // we have to copy Attributes, otherwise it will be mutated by SAX parser State nextState = createChildState(tag); if(nextState!=null) { reader.pushState(nextState,this,tag); return; } // unacceptable element reader.reportError(GrammarReader.ERR_MALPLACED_ELEMENT, tag.qName ); // try to recover from error by just ignoring it. // element of a foreign namespace. skip subtree reader.pushState(new IgnoreState(),this,tag); } } msv-2009.1/msv/src/com/sun/msv/reader/datatype/xsd/RestrictionState.java0000644000175000017500000000504107671170035026436 0ustar giovannigiovanni/* * @(#)$Id: RestrictionState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.datatype.xsd; import org.relaxng.datatype.DatatypeException; import com.sun.msv.datatype.xsd.StringType; import com.sun.msv.reader.GrammarReader; import com.sun.msv.reader.IgnoreState; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * state that parses <restriction> element. * * @author Kohsuke KAWAGUCHI */ public class RestrictionState extends TypeWithOneChildState implements FacetStateParent { protected final String newTypeUri; protected final String newTypeName; protected RestrictionState( String newTypeUri, String newTypeName ) { this.newTypeUri = newTypeUri; this.newTypeName = newTypeName; } protected XSTypeIncubator incubator; public final XSTypeIncubator getIncubator() { return incubator; } protected XSDatatypeExp annealType( XSDatatypeExp baseType ) throws DatatypeException { return incubator.derive(newTypeUri,newTypeName); } public void onEndChild( XSDatatypeExp child ) { super.onEndChild(child); createTypeIncubator(); } private void createTypeIncubator() { incubator = type.createIncubator(); } protected void startSelf() { super.startSelf(); // if the base attribute is used, try to load it. String base = startTag.getAttribute("base"); if(base!=null) onEndChild( ((XSDatatypeResolver)reader).resolveXSDatatype(base) ); } protected State createChildState( StartTagInfo tag ) { // accepts elements from the same namespace only. if( !startTag.namespaceURI.equals(tag.namespaceURI) ) return null; if( tag.localName.equals("annotation") ) return new IgnoreState(); if( tag.localName.equals("simpleType") ) return new SimpleTypeState(); if( FacetState.facetNames.contains(tag.localName) ) { if( incubator==null ) { reader.reportError( GrammarReader.ERR_MISSING_ATTRIBUTE, "restriction", "base" ); onEndChild(new XSDatatypeExp(StringType.theInstance,reader.pool)); } return new FacetState(); } return null; // unrecognized } } msv-2009.1/msv/src/com/sun/msv/reader/datatype/xsd/ListState.java0000644000175000017500000000341707671170035025051 0ustar giovannigiovanni/* * @(#)$Id: ListState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.datatype.xsd; import org.relaxng.datatype.DatatypeException; import com.sun.msv.reader.IgnoreState; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * state that parses <list> element of XSD. * * @author Kohsuke KAWAGUCHI */ public class ListState extends TypeWithOneChildState { protected final String newTypeUri; protected final String newTypeName; protected ListState( String newTypeUri, String newTypeName ) { this.newTypeUri = newTypeUri; this.newTypeName = newTypeName; } protected XSDatatypeExp annealType( final XSDatatypeExp itemType ) throws DatatypeException { return XSDatatypeExp.makeList( newTypeUri, newTypeName, itemType, reader ); } protected void startSelf() { super.startSelf(); // if itemType attribute is used, use it. String itemType = startTag.getAttribute("itemType"); if(itemType!=null) onEndChild( ((XSDatatypeResolver)reader).resolveXSDatatype(itemType) ); } protected State createChildState( StartTagInfo tag ) { // accepts elements from the same namespace only. if( !startTag.namespaceURI.equals(tag.namespaceURI) ) return null; if( tag.localName.equals("annotation") ) return new IgnoreState(); if( tag.localName.equals("simpleType") ) return new SimpleTypeState(); return null; // unrecognized } } msv-2009.1/msv/src/com/sun/msv/reader/datatype/xsd/XSTypeOwner.java0000644000175000017500000000140307607361514025340 0ustar giovannigiovanni/* * @(#)$Id: XSTypeOwner.java 1482 2003-01-09 21:02:04Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.datatype.xsd; /** * Type owner for XML Schema datatypes. * * @author Kohsuke KAWAGUCHI */ public interface XSTypeOwner { /** * Returns the target namespace URI of newly created simple types. * If the context you are using this package doesn't have the notion * of the target namespace URI, return the empty string. */ String getTargetNamespaceUri(); void onEndChild( XSDatatypeExp data ); } msv-2009.1/msv/src/com/sun/msv/reader/datatype/xsd/package.html0000644000175000017500000000042707266637326024564 0ustar giovannigiovanni

      reads XML representation for XML Schema Part.2

      msv-2009.1/msv/src/com/sun/msv/reader/datatype/xsd/XSTypeIncubator.java0000644000175000017500000000144507607361514026202 0ustar giovannigiovanni/* * @(#)$Id: XSTypeIncubator.java 1482 2003-01-09 21:02:04Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.datatype.xsd; import org.relaxng.datatype.DatatypeException; import org.relaxng.datatype.ValidationContext; /** * Interface for the type incubator. *

      * One layer of abstraction is necessary * to support the lazy type construction. */ public interface XSTypeIncubator { void addFacet( String name, String value, boolean fixed, ValidationContext context ) throws DatatypeException; XSDatatypeExp derive( String newTypeNameUri, String newLocalName ) throws DatatypeException; } msv-2009.1/msv/src/com/sun/msv/reader/datatype/xsd/XSDVocabulary.java0000644000175000017500000000252007671170035025615 0ustar giovannigiovanni/* * @(#)$Id: XSDVocabulary.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.datatype.xsd; import org.relaxng.datatype.Datatype; import org.relaxng.datatype.DatatypeException; import com.sun.msv.datatype.xsd.DatatypeFactory; import com.sun.msv.reader.State; import com.sun.msv.reader.datatype.DataTypeVocabulary; import com.sun.msv.util.StartTagInfo; /** * XSD implementation of {@link DataTypeVocabulary}. * * @author Kohsuke KAWAGUCHI */ public class XSDVocabulary implements DataTypeVocabulary, java.io.Serializable { /** namespace URI of XML Schema */ public static final String XMLSchemaNamespace = "http://www.w3.org/2001/XMLSchema-datatypes"; public static final String XMLSchemaNamespace2= "http://www.w3.org/2001/XMLSchema"; public State createTopLevelReaderState( StartTagInfo tag ) { if( tag.localName.equals("simpleType") ) return new SimpleTypeState(); else return null; } public Datatype getType( String localTypeName ) throws DatatypeException { return DatatypeFactory.getTypeByName(localTypeName); } } msv-2009.1/msv/src/com/sun/msv/reader/datatype/xsd/XSDatatypeResolver.java0000644000175000017500000000215607401041362026673 0ustar giovannigiovanni/* * @(#)$Id: XSDatatypeResolver.java 1332 2001-11-28 01:50:42Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.datatype.xsd; /** * Resolves a datatype name to the corresponding XSDatatypeExp object. * *

      * This interface has to be implemented by the GrammarReader * if that GrammarReader uses this package. */ public interface XSDatatypeResolver { /** * @param datatypeName * The type of this value varies in the schema language. * In XML Schema, for example, in which QNames are used * to designate datatypes, this parameter will be QName. * In RELAX Core, in which the same syntax is used but * NCName is used to designate datatypes. So this parameter * will be NCName. * * @return * A non-null valid object. An error should be reported * and recovered by the callee. */ XSDatatypeExp resolveXSDatatype( String datatypeName ); } msv-2009.1/msv/src/com/sun/msv/reader/datatype/xsd/UnionState.java0000644000175000017500000000432607671170035025226 0ustar giovannigiovanni/* * @(#)$Id: UnionState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.datatype.xsd; import java.util.ArrayList; import java.util.StringTokenizer; import org.relaxng.datatype.DatatypeException; import com.sun.msv.reader.IgnoreState; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * State that parses <union> element and its children. * * @author Kohsuke KAWAGUCHI */ public class UnionState extends TypeState implements XSTypeOwner { protected final String newTypeUri; protected final String newTypeName; protected UnionState( String newTypeUri, String newTypeName ) { this.newTypeUri = newTypeUri; this.newTypeName = newTypeName; } private final ArrayList memberTypes = new ArrayList(); protected State createChildState( StartTagInfo tag ) { // accepts elements from the same namespace only. if( !startTag.namespaceURI.equals(tag.namespaceURI) ) return null; if( tag.localName.equals("annotation") ) return new IgnoreState(); if( tag.localName.equals("simpleType") ) return new SimpleTypeState(); return null; // unrecognized } protected void startSelf() { super.startSelf(); // if memberTypes attribute is used, load it. String memberTypes = startTag.getAttribute("memberTypes"); if(memberTypes!=null) { StringTokenizer tokens = new StringTokenizer(memberTypes); while( tokens.hasMoreTokens() ) onEndChild( ((XSDatatypeResolver)reader) .resolveXSDatatype(tokens.nextToken()) ); } } public void onEndChild( XSDatatypeExp type ) { memberTypes.add(type); } protected final XSDatatypeExp makeType() throws DatatypeException { return XSDatatypeExp.makeUnion( newTypeUri, newTypeName, memberTypes, reader ); } } msv-2009.1/msv/src/com/sun/msv/reader/datatype/xsd/TypeWithOneChildState.java0000644000175000017500000000320707671170035027316 0ustar giovannigiovanni/* * @(#)$Id: TypeWithOneChildState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.datatype.xsd; import org.relaxng.datatype.DatatypeException; import com.sun.msv.datatype.xsd.StringType; import com.sun.msv.reader.GrammarReader; /** * State which has at most one TypeState as its child. * * @author Kohsuke KAWAGUCHI */ abstract class TypeWithOneChildState extends TypeState implements XSTypeOwner { protected XSDatatypeExp type; /** receives a Pattern object that is contained in this element. */ public void onEndChild( XSDatatypeExp child ) { if( type!=null ) reader.reportError( GrammarReader.ERR_MORE_THAN_ONE_CHILD_TYPE ); // recover by ignoring this child else type = child; } protected final XSDatatypeExp makeType() throws DatatypeException { if( type==null ) { reader.reportError( GrammarReader.ERR_MISSING_CHILD_TYPE ); // recover by supplying a dummy DataType return new XSDatatypeExp( StringType.theInstance, reader.pool ); } return annealType(type); } /** * performs final wrap-up and returns a fully created DataType object * that represents this element. */ protected XSDatatypeExp annealType( XSDatatypeExp dt ) throws DatatypeException { // default implementation do nothing. return dt; } } msv-2009.1/msv/src/com/sun/msv/reader/datatype/xsd/FacetStateParent.java0000644000175000017500000000136007671170035026325 0ustar giovannigiovanni/* * @(#)$Id: FacetStateParent.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.datatype.xsd; /** * Interface implemented by the parent state of FacetState. * * the parent holds a Facets object, to which FacetState will add * facets. * * After all facets are added, the parent state should derive a * new type. * * @author Kohsuke KAWAGUCHI */ public interface FacetStateParent { /** gets an incubator object that the owner holds. */ XSTypeIncubator getIncubator(); } msv-2009.1/msv/src/com/sun/msv/reader/datatype/xsd/LazyTypeIncubator.java0000644000175000017500000000610307671170035026560 0ustar giovannigiovanni/* * @(#)$Id: LazyTypeIncubator.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.datatype.xsd; /* import com.sun.msv.datatype.xsd.StringType; */ import java.util.Iterator; import java.util.List; import org.relaxng.datatype.DatatypeException; import org.relaxng.datatype.ValidationContext; import com.sun.msv.datatype.xsd.TypeIncubator; import com.sun.msv.datatype.xsd.XSDatatype; import com.sun.msv.reader.GrammarReader; /** * Lazy XSTypeIncubator * *

      * This incubator is used to add facets to lazily created XSDatatypeExp object. * Since the actual Datatype object is not available when facets are parsed, * this object merely stores all facets when the addFacet method is called. * *

      * Once the actual Datatype is provided, this class uses ordinary * TypeIncubator and builds a real type object. * * @author Kohsuke KAWAGUCHI */ class LazyTypeIncubator implements XSTypeIncubator { // package local public LazyTypeIncubator( XSDatatypeExp base, GrammarReader reader ) { this.baseType = base; this.reader = reader; } /** base object. */ private final XSDatatypeExp baseType; private final GrammarReader reader; /** * applied facets. * Order between facets are possibly significant. */ private final List facets = new java.util.LinkedList(); public void addFacet( String name, String strValue, boolean fixed, ValidationContext context ) { facets.add( new Facet(name,strValue,fixed,context) ); } public XSDatatypeExp derive( final String nsUri, final String localName ) throws DatatypeException { // facets might be further added, so remember the size of the facet. final int facetSize = facets.size(); if(facetSize==0) return baseType; return new XSDatatypeExp(nsUri,localName,reader,new XSDatatypeExp.Renderer(){ public XSDatatype render( XSDatatypeExp.RenderingContext context ) throws DatatypeException { TypeIncubator ti = new TypeIncubator( baseType.getType(context) ); Iterator itr = facets.iterator(); for( int i=0; iKohsuke KAWAGUCHI */ public class XSDatatypeExp extends ReferenceExp implements GrammarReader.BackPatch { /** Creates this object from existing XSDatatype. */ public XSDatatypeExp( XSDatatype dt, ExpressionPool _pool ) { super(dt.getName()); this.namespaceUri = dt.getNamespaceUri(); this.dt = dt; this.pool = _pool; this.ownerState = null; this.renderer = null; super.exp = _pool.createData(dt); } /** Creates lazily created datatype. */ public XSDatatypeExp( String nsUri, String typeName, GrammarReader reader, Renderer _renderer ) { // this(typeName, reader, reader.getCurrentState(), _renderer ); super(typeName); this.namespaceUri = nsUri; this.dt = null; this.ownerState = reader.getCurrentState(); this.renderer = _renderer; this.pool = reader.pool; reader.addBackPatchJob(this); } /** Used only for cloning */ private XSDatatypeExp( String nsUri, String localName ) { super(localName); this.namespaceUri = nsUri; } /** * Namespace URI of this datatype. * Local name is stored in the name field of ReferenceExp. */ private final String namespaceUri; /** * Creates an incubator so that the caller can add more facets * and derive a new type. */ public XSTypeIncubator createIncubator() { if( isLateBind() ) return new LazyTypeIncubator(this,ownerState.reader); // normal incubator return new XSTypeIncubator() { private final TypeIncubator core = new TypeIncubator(dt); public void addFacet( String name, String value, boolean fixed, ValidationContext context ) throws DatatypeException { core.addFacet(name,value,fixed,context); } public XSDatatypeExp derive(String uri,String localName) throws DatatypeException { return new XSDatatypeExp( core.derive(uri,localName), pool ); } }; } /** * Datatype object wrapped by this expression. * * This field can be null if the datatype object is not available * at this moment (say, because of the forward reference). In this * case, {@link #ownerState} and {@link #renderer} fields are * available. */ private XSDatatype dt; /** ExpressionPool that can be used if necessary. */ private ExpressionPool pool; /** * Gets a encapsulated datatype object * This method can be called only after all the datatypes are created. * *

      * Some of the datatypes are lazily during the back-patching phase. */ public XSDatatype getCreatedType() { if(dt==null) throw new IllegalStateException(); return dt; } /** * Gets the type definition. * This method renders the datatype object if it's not rendered yet. * Internal use only. */ public XSDatatype getType( RenderingContext context ) { if(dt!=null) // the datatype is already rendered. return dt; if(context==null) // create a new context. context = new RenderingContext(); if( context.callStack.contains(this) ) { // a recursive definition is detected. Vector locs = new Vector(); for( int i=0; i * This method is typically called from the wrapUp method of the GrammarReader. * * @return * the XSDatatype object which this LateBindDatatype object is representing. * It shall not return an instance of LateBindDatatype object. * * @param context * If this renderer calls the getBody method of the other * LateBindDatatype objects, then this context should be passed * to the getBody method. This context object is responsible for * detecting recursive references. * * @exception DatatypeException * If an error occurs during rendering, the renderer should throw * a DatatypeException instead of trying to report an error by itself. * The caller of this method will report an error message to the appropriate * handler. */ XSDatatype render( RenderingContext context ) throws DatatypeException; } /** * this object is used to keep the information about * the dependency between late-bind datatype objects. * *

      * Consider the following schema: * *

      
           * <xs:simpleType name="foo">
           *   <xs:restriction base="bar">
           *     <xs:minLength value="3"/>
           *   </xs:restriction>
           * </xs:simpleType>
           * <xs:simpleType name="bar">
           *   <xs:restriction base="foo">
           *     <xs:minLength value="3"/>
           *   </xs:restriction>
           * </xs:simpleType>
           * 
      * * Since two types are depending on each other, if you call the * getBody method of "foo" type, it will call the getBody method of "bar" type. * Then in turn it will call "foo" again. So this will result in the * infinite recursion. * *

      * This context object is used to detect such condition and reports the * dependency to the user. * *

      * No method is publicly accessible. */ public static class RenderingContext { RenderingContext() {} private final Stack callStack = new Stack(); } } msv-2009.1/msv/src/com/sun/msv/reader/datatype/xsd/SimpleTypeState.java0000644000175000017500000000565507671170035026237 0ustar giovannigiovanni/* * @(#)$Id: SimpleTypeState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.datatype.xsd; import java.util.StringTokenizer; import com.sun.msv.datatype.xsd.XSDatatype; import com.sun.msv.reader.GrammarReader; import com.sun.msv.reader.IgnoreState; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * State that parses <simpleType> element and its children. * * @author Kohsuke KAWAGUCHI */ public class SimpleTypeState extends TypeWithOneChildState { protected State createChildState( StartTagInfo tag ) { // accepts elements from the same namespace only. if( !startTag.namespaceURI.equals(tag.namespaceURI) ) return null; final String name = startTag.getAttribute("name"); String uri = getTargetNamespaceUri(); if( tag.localName.equals("annotation") ) return new IgnoreState(); if( tag.localName.equals("restriction") ) return new RestrictionState(uri,name); if( tag.localName.equals("list") ) return new ListState(uri,name); if( tag.localName.equals("union") ) return new UnionState(uri,name); return null; // unrecognized } protected XSDatatypeExp annealType( final XSDatatypeExp dt ) { final String finalValueStr = startTag.getAttribute("final"); if(finalValueStr!=null) { final int finalValue = getFinalValue(finalValueStr); // create a new type by adding final constraint. return dt.createFinalizedType(finalValue,reader); } else return dt; } /** parses final attribute */ public int getFinalValue( String list ) { int finalValue = 0; StringTokenizer tokens = new StringTokenizer(list); while(tokens.hasMoreTokens()) { String token = tokens.nextToken(); if( token.equals("#all") ) finalValue |= XSDatatype.DERIVATION_BY_LIST| XSDatatype.DERIVATION_BY_RESTRICTION| XSDatatype.DERIVATION_BY_UNION; else if( token.equals("restriction") ) finalValue |= XSDatatype.DERIVATION_BY_RESTRICTION; else if( token.equals("list") ) finalValue |= XSDatatype.DERIVATION_BY_LIST; else if( token.equals("union") ) finalValue |= XSDatatype.DERIVATION_BY_UNION; else { reader.reportError( GrammarReader.ERR_ILLEGAL_FINAL_VALUE, token ); return 0; // abort } } return finalValue; } } msv-2009.1/msv/src/com/sun/msv/reader/datatype/package.html0000644000175000017500000000011707260744467023761 0ustar giovannigiovanni

      interface of Datatype vocabulary reader.

      msv-2009.1/msv/src/com/sun/msv/reader/datatype/DataTypeVocabulary.java0000644000175000017500000000542707671170035026105 0ustar giovannigiovanni/* * @(#)$Id: DataTypeVocabulary.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.datatype; import org.relaxng.datatype.Datatype; import org.relaxng.datatype.DatatypeException; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * this class is used to parse foreign datatype vocabulary. * * Each datatype vocabulary must be associated with one namespace URI. * When the element with that namespace URI is first found, this object is * instanciated. After that, whenever the element with the namespace URI * is found, createTopLevelReaderState method will be used to parse the element * (and its descendants.) * * And whenever a reference to this vocabulary by name (e.g., "mydt:mytypename") * is found, getType method is called to resolve this name into DataType object. * * One instance of this class is used throughout the parsing of one grammar. * Therefore, implementations are encouraged to take advantages of this property * and keep context information (e.g., user-defined named datatypes). * * @author Kohsuke KAWAGUCHI */ public interface DataTypeVocabulary { /** * creates a State object that will parse the element specified * by tag parameter. * * @return null * if given start tag is not recognized by this object. * * This method is called when an "island" of this vocabulary was found. * The state returned from this method will be used to parse the root * element of this island. * * The parent state of this state must implement TypeOwner or ExpressionOwner. * In either case, the implementation must report its parsing result * by calling either interface. If both interface is implemented, * the implementation must notify via TypeOwner interface only and may not * call methods of ExpressionOwner. * * If the parsed island is not a type definition (for example, comments or * inclusion), the implementation may not call TypeOwner nor ExpressionOwner. */ State createTopLevelReaderState( StartTagInfo tag ); /** * resolves a type name to Datatype object. * * @param localTypeName * local part of the qualified name, like "string" or "integer". * prefix part must be removed by the caller. * * @return * a non-null valid datatype object. * * @exception DatatypeException * if the specified type name is a valid type name. */ Datatype getType( String localTypeName ) throws DatatypeException; } msv-2009.1/msv/src/com/sun/msv/reader/datatype/DataTypeVocabularyMap.java0000644000175000017500000000314107671170035026532 0ustar giovannigiovanni/* * @(#)$Id: DataTypeVocabularyMap.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.datatype; import java.util.Map; /** * a map from namespace URI to DataTypeVocabulary * * @author Kohsuke KAWAGUCHI */ public class DataTypeVocabularyMap implements java.io.Serializable { /** map from namespace URI to DataTypeVocabulary */ private final Map impl = new java.util.HashMap(); /** * obtains an DataTypeVocabulary associated to the namespace. * * If necessary, Vocabulary is located and instanciated. */ public DataTypeVocabulary get( String namespaceURI ) { DataTypeVocabulary v = (DataTypeVocabulary)impl.get(namespaceURI); if(v!=null) return v; // TODO: generic way to load a vocabulary if( namespaceURI.equals( com.sun.msv.reader.datatype.xsd.XSDVocabulary.XMLSchemaNamespace ) ) { v = new com.sun.msv.reader.datatype.xsd.XSDVocabulary(); impl.put( com.sun.msv.reader.datatype.xsd.XSDVocabulary.XMLSchemaNamespace, v ); impl.put( com.sun.msv.reader.datatype.xsd.XSDVocabulary.XMLSchemaNamespace2, v ); } return v; } /** manually adds DataTypeVocabulary into this map. */ public void put( String namespaceURI, DataTypeVocabulary voc ) { impl.put( namespaceURI, voc ); } } msv-2009.1/msv/src/com/sun/msv/reader/GrammarReaderController.java0000644000175000017500000000165307671170035025301 0ustar giovannigiovanni/* * @(#)$Id: GrammarReaderController.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader; import org.xml.sax.EntityResolver; import org.xml.sax.Locator; /** * Event notification interface for controlling grammar parsing process. * *
        *
      1. receives notification of errors and warnings while parsing a grammar *
      2. controls how inclusion of other grammars are processed (through * {@link EntityResolver}. *
      * * @author Kohsuke KAWAGUCHI */ public interface GrammarReaderController extends EntityResolver { void warning( Locator[] locs, String errorMessage ); void error( Locator[] locs, String errorMessage, Exception nestedException ); } msv-2009.1/msv/src/com/sun/msv/reader/trex/0000755000175000017500000000000011622453066020635 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/reader/trex/ZeroOrMoreState.java0000644000175000017500000000125007671170035024543 0ustar giovannigiovanni/* * @(#)$Id: ZeroOrMoreState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import com.sun.msv.grammar.Expression; import com.sun.msv.reader.SequenceState; /** * parses <zeroOrMore> pattern. * * @author Kohsuke KAWAGUCHI */ public class ZeroOrMoreState extends SequenceState { protected Expression annealExpression( Expression exp ) { return reader.pool.createZeroOrMore(exp); } } msv-2009.1/msv/src/com/sun/msv/reader/trex/typed/0000755000175000017500000000000011622453066021762 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/reader/trex/typed/TypedElementState.java0000644000175000017500000000177307671170035026236 0ustar giovannigiovanni/* * @(#)$Id: TypedElementState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex.typed; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.trex.typed.TypedElementPattern; import com.sun.msv.reader.trex.ElementState; /** * reads <element> element with 'label' annotation. * * @author Kohsuke KAWAGUCHI */ public class TypedElementState extends ElementState { protected Expression annealExpression( Expression contentModel ) { final String label = startTag.getAttribute( TypedTREXGrammarInterceptor.LABEL_NAMESPACE, "label" ); if( label==null ) return super.annealExpression( contentModel ); else return new TypedElementPattern( nameClass, contentModel, label ); } } msv-2009.1/msv/src/com/sun/msv/reader/trex/typed/package.html0000644000175000017500000000241107273576330024250 0ustar giovannigiovanni

      reads TREX grammar with "label annotation".

      "label annotation" is a proprietary extension to TREX by MSV.

      How it works

      With this extension, <element> pattern in TREX pattern can have "label" attribute in http://www.sun.com/xml/msv/trex-type namespace.

      <grammar xmlns:ext="http://www.sun.com/xml/msv/trex-type">
      <start>
      <element name="root" ext:label="root">
      <choice>
      <element name="child1"><empty /></element>
      <element name="child2" ext:label="foo"><empty /></element>
      </choice>
      </element>
      </start>
      </grammar>

      Once label is specified to <element> pattern, application can call Verifier.getCurrentElementType method to obtain a reference to TypedElementPattern object, which has label field.

      void startElement( ... ) {
      Object o = verifier.getCurrentElementType();
      if(!( o instanceof TypedElementPattern ))
      ... // the current element does not have 'label' attribute.
      else {
      String labelOfTheCurrentElement = ((TypedElementPattern)o).label;
      ... // do whatever useful
      }
      }
      msv-2009.1/msv/src/com/sun/msv/reader/trex/typed/TypedTREXGrammarInterceptor.java0000644000175000017500000000155407671170035030151 0ustar giovannigiovanni/* * @(#)$Id: TypedTREXGrammarInterceptor.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex.typed; import com.sun.msv.reader.State; import com.sun.msv.reader.trex.classic.TREXGrammarReader; import com.sun.msv.util.StartTagInfo; /** * reads TREX grammar with 'label' annotation. * * @author Kohsuke KAWAGUCHI */ public class TypedTREXGrammarInterceptor extends TREXGrammarReader.StateFactory { public final static String LABEL_NAMESPACE = "http://www.sun.com/xml/msv/trex-type"; public State element( State parent, StartTagInfo tag ) { return new TypedElementState(); } } msv-2009.1/msv/src/com/sun/msv/reader/trex/DefineState.java0000644000175000017500000000720010326264125023666 0ustar giovannigiovanni/* * @(#)$Id: DefineState.java 1696 2005-10-21 22:14:45Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.reader.ExpressionOwner; import com.sun.msv.reader.GrammarReader; import com.sun.msv.reader.SimpleState; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * parses <define> declaration. * * @author Kohsuke KAWAGUCHI */ public abstract class DefineState extends SimpleState implements ExpressionOwner { /** * expression object that is being created. * See {@link #castPattern} and {@link #annealPattern} methods * for how will a pattern be created. */ protected Expression exp = null; // or Expression.epsilon if is allowed. /** * Container to which the expression will be assigned. */ private ReferenceExp ref; /** * Obtains a {@link ReferenceExp} that represents the target * pattern block. * * @return null * If there was an error in the input, this method may * return null. */ public final ReferenceExp getRef() { return ref; } /** receives a Pattern object that is contained in this element. */ public final void onEndChild( Expression child ) { if( exp==null ) { // first one. exp = child; } else { exp = reader.pool.createSequence(exp,child); } } protected void startSelf() { super.startSelf(); ref = getReference(); } protected void endSelf() { if( exp==null ) { reader.reportError( GrammarReader.ERR_MISSING_CHILD_EXPRESSION ); exp = Expression.nullSet; // recover by assuming some pattern. } if(ref==null) return; // error. abort. final TREXBaseReader reader = (TREXBaseReader)this.reader; final String combine = startTag.getCollapsedAttribute("combine"); exp = callInterceptExpression(exp); // combine two patterns Expression newexp = doCombine( ref, exp, combine ); if( newexp==null ) reader.reportError( TREXBaseReader.ERR_BAD_COMBINE, combine ); // recover by ignoring this definition else ref.exp = newexp; reader.setDeclaredLocationOf(ref); ((ExpressionOwner)parentState).onEndChild(ref); } protected State createChildState( StartTagInfo tag ) { return reader.createExpressionChildState(this,tag); } /** * * @return null in case of error. */ protected ReferenceExp getReference() { final String name = startTag.getCollapsedAttribute("name"); if(name==null) { // name attribute is required. reader.reportError( TREXBaseReader.ERR_MISSING_ATTRIBUTE, "ref","name"); return null; } final TREXBaseReader reader = (TREXBaseReader)this.reader; return reader.grammar.namedPatterns.getOrCreate(name); } /** * combines two expressions into one as specified by the combine parameter, * and returns a new expression. * * If the combine parameter is invalid, then return null. */ protected abstract Expression doCombine( ReferenceExp baseExp, Expression newExp, String combine ); } msv-2009.1/msv/src/com/sun/msv/reader/trex/NameClassNotState.java0000644000175000017500000000205407671170035025032 0ustar giovannigiovanni/* * @(#)$Id: NameClassNotState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.NotNameClass; /** * parses <not> name class. * * @author Kohsuke KAWAGUCHI */ public class NameClassNotState extends NameClassWithChildState { protected NameClass castNameClass( NameClass halfCastedNameClass, NameClass child ) { // this parameter is null only for the first time invocation. if( halfCastedNameClass!=null ) { // only allows one child. reader.reportError( TREXBaseReader.ERR_MORE_THAN_ONE_NAMECLASS ); // recovery can be done by simply doing nothing at all. return halfCastedNameClass; } else return new NotNameClass(child); } } msv-2009.1/msv/src/com/sun/msv/reader/trex/OptionalState.java0000644000175000017500000000124007671170035024264 0ustar giovannigiovanni/* * @(#)$Id: OptionalState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import com.sun.msv.grammar.Expression; import com.sun.msv.reader.SequenceState; /** * parses <optional> pattern. * * @author Kohsuke KAWAGUCHI */ public class OptionalState extends SequenceState { protected Expression annealExpression( Expression exp ) { return reader.pool.createOptional(exp); } } msv-2009.1/msv/src/com/sun/msv/reader/trex/IncludePatternState.java0000644000175000017500000000332607671170035025427 0ustar giovannigiovanni/* * @(#)$Id: IncludePatternState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import com.sun.msv.grammar.Expression; import com.sun.msv.reader.AbortException; import com.sun.msv.reader.ExpressionOwner; import com.sun.msv.reader.ExpressionWithoutChildState; /** * <include> element in the pattern. (<externalRef> of RELAX NG). * * @author Kohsuke KAWAGUCHI */ public class IncludePatternState extends ExpressionWithoutChildState implements ExpressionOwner { protected Expression included = Expression.nullSet; // assign a default value just in case something goes wrong and onEndChild is not called. public void onEndChild( Expression included ) { this.included = included; } protected Expression makeExpression() { final String href = startTag.getAttribute("href"); if(href==null) {// name attribute is required. reader.reportError( TREXBaseReader.ERR_MISSING_ATTRIBUTE, startTag.localName,"href"); // recover by returning something that can be interpreted as Pattern return Expression.nullSet; } try { reader.switchSource(this,href,new RootIncludedPatternState(this)); } catch( AbortException e ) {} // recover by ignoring an error // onEndChild method is called inside the above function call and // included will be set. return included; } } msv-2009.1/msv/src/com/sun/msv/reader/trex/NameClassAndExpressionState.java0000644000175000017500000000671407730143103027053 0ustar giovannigiovanni/* * @(#)$Id: NameClassAndExpressionState.java 1601 2003-09-11 19:00:19Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.SimpleNameClass; import com.sun.msv.reader.SequenceState; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * Base implementation for ElementState and AttributeState * * This class collects one name class and patterns * * @author Kohsuke KAWAGUCHI */ public abstract class NameClassAndExpressionState extends SequenceState implements NameClassOwner { protected NameClass nameClass = null; /** * gets namespace URI to which this declaration belongs */ protected String getNamespace() { // usually, propagated "ns" attribute should be used return ((TREXBaseReader) reader).targetNamespace; } protected void startSelf() { super.startSelf(); // if name attribtue is specified, use it. final String name = startTag.getCollapsedAttribute("name"); if (name == null) return; final int idx = name.indexOf(':'); if (idx != -1) { // QName is specified. resolve this prefix. final String[] s = reader.splitQName(name); if (s == null) { reader.reportError(TREXBaseReader.ERR_UNDECLARED_PREFIX, name); // recover by using a dummy name nameClass = new SimpleNameClass("", name); } else nameClass = new SimpleNameClass(s[0], s[1]); } else nameClass = new SimpleNameClass(getNamespace(), name); } public void onEndChild(NameClass p) { if (nameClass != null) // name class has already specified reader.reportError(TREXBaseReader.ERR_MORE_THAN_ONE_NAMECLASS); nameClass = p; } protected State createChildState(StartTagInfo tag) { if (nameClass == null) // nameClass should be specified before content model. { State nextState = ((TREXBaseReader) reader).createNameClassChildState(this, tag); if (nextState != null) return nextState; // to provide better error message, analyze the situation further. // users tend to forget to supply nameClass and name attribute. nextState = reader.createExpressionChildState(this, tag); if (nextState != null) { // OK. tag is recognized as an content model. // so probably this user forgot to specify name class. // report so and recover by assuming some NameClass reader.reportError(TREXBaseReader.ERR_MISSING_CHILD_NAMECLASS); nameClass = NameClass.ALL; return nextState; } else // probably this user made a typo. let the default handler reports an error return null; } else return reader.createExpressionChildState(this, tag); } protected void endSelf() { if (nameClass == null) { // name class is missing reader.reportError(TREXBaseReader.ERR_MISSING_CHILD_NAMECLASS); nameClass = NameClass.ALL; } super.endSelf(); } } msv-2009.1/msv/src/com/sun/msv/reader/trex/NameClassDifferenceState.java0000644000175000017500000000147207671170035026327 0ustar giovannigiovanni/* * @(#)$Id: NameClassDifferenceState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import com.sun.msv.grammar.DifferenceNameClass; import com.sun.msv.grammar.NameClass; /** * parses <difference> name class. * * @author Kohsuke KAWAGUCHI */ public class NameClassDifferenceState extends NameClassWithChildState { protected NameClass castNameClass( NameClass halfCasted, NameClass newChild ) { if( halfCasted==null ) return newChild; // first item else return new DifferenceNameClass( halfCasted, newChild ); } } msv-2009.1/msv/src/com/sun/msv/reader/trex/package.html0000644000175000017500000000013307350477355023125 0ustar giovannigiovanni

      shared code between RELAX NG reader and TREX reader.

      msv-2009.1/msv/src/com/sun/msv/reader/trex/NameClassWithoutChildState.java0000644000175000017500000000166307671170035026706 0ustar giovannigiovanni/* * @(#)$Id: NameClassWithoutChildState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * Base implementation for those states who cannot have any child name class. * (e.g., nsName, anyName) * * Note that this class does not prohibit children from different namespace. * Those "foreign" elements are just ignored. * * @author Kohsuke KAWAGUCHI */ public abstract class NameClassWithoutChildState extends NameClassState { protected final State createChildState(StartTagInfo tag) { // return null to indicate that this element does not accept a child. return null; } } msv-2009.1/msv/src/com/sun/msv/reader/trex/Messages_ja.properties0000644000175000017500000000637207310247776025214 0ustar giovannigiovanni## abstract error messages defined for TREX GrammarReader.Abstract.MissingChildExpression =\ \u5B50\u30D1\u30BF\u30FC\u30F3\u304C\u3042\u308A\u307E\u305B\u3093 GrammarReader.Abstract.MoreThanOneChildExpression =\ \u30D1\u30BF\u30FC\u30F3\u306F\uFF11\u3064\u3060\u3051\u3057\u304B\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093 GrammarReader.Abstract.RunAwayExpression =\ \u6B21\u306E\u30D1\u30BF\u30FC\u30F3\u304C\u5FAA\u74B0\u53C2\u7167\u3092\u8D77\u3053\u3057\u3066\u3044\u307E\u3059: {0} GrammarReader.Abstract.MissingTopLevel =\ \u8981\u7D20\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093 ## TREX reader error messages TREXGrammarReader.MissingChildNameClass = \ name\u5C5E\u6027\u304B\u3001name class\u5B9A\u7FA9\u304C\u5FC5\u8981\u3067\u3059 TREXGrammarReader.MoreThanOneNameClass = \ \u8907\u6570\u306Ename class\u5B9A\u7FA9\u304C\u3042\u308A\u307E\u3059 TREXGrammarReader.UndeclaredPrefix = \ \u30D7\u30EC\u30D5\u30A3\u30AF\u30B9"{0}"\u304C\u5BA3\u8A00\u3055\u308C\u3066\u3044\u307E\u305B\u3093 TREXGrammarReader.UndefinedPattern = \ \u5B9A\u7FA9\u3055\u308C\u3066\u3044\u306A\u3044\u30D1\u30BF\u30FC\u30F3"{0}"\u3092\u53C2\u7167\u3057\u3066\u3044\u307E\u3059 TREXGrammarReader.UnknownDataTypeVocabulary =\ "{0}"\u306F\u672A\u77E5\u306E\u30C7\u30FC\u30BF\u578B\u30E9\u30A4\u30D6\u30E9\u30EA\u3067\u3059 TREXGrammarReader.FailedToParseDataType =\ \u30C7\u30FC\u30BF\u578B\u6307\u5B9A\u306E\u8AAD\u307F\u53D6\u308A\u306B\u5931\u6557\u3057\u307E\u3057\u305F TREXGrammarReader.BadCombine =\ combine\u5C5E\u6027\u306E\u5024\u3068\u3057\u3066"{0}"\u306F\u7121\u52B9\u3067\u3059 TREXGrammarReader.CombineMissing =\ \u540C\u540D\u306E\u30D1\u30BF\u30FC\u30F3\u304C\u65E2\u306B\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u3059\u3002combine\u5C5E\u6027\u3092\u4F7F\u3063\u3066\u7D50\u5408\u3059\u308B\u304B\u3001\u30D1\u30BF\u30FC\u30F3\u540D\u3092"{0}"\u4EE5\u5916\u306E\u3082\u306E\u306B\u5909\u66F4\u3057\u3066\u304F\u3060\u3055\u3044 TREXGrammarReader.Warning.CombineIgnored =\ combine\u5C5E\u6027\u304C\u898B\u3064\u304B\u308A\u307E\u3057\u305F\u304C\u3001\u3053\u308C\u304C\u306F\u3058\u3081\u3066\u306E\u5B9A\u7FA9\u3067\u3059 TREXGrammarReader.Warning.ObsoletedXMLSchemaNamespace =\ "{0}"\u306F\u53E4\u3044namespace URI\u3067\u3059\u3002"http://www.w3.org/2001/XMLSchema"\u3092\u4F7F\u3063\u3066\u304F\u3060\u3055\u3044 TREXGrammarReader.DuplicateDefinition =\ \u30D1\u30BF\u30FC\u30F3"{0}"\u306F\u540C\u3058\u30D5\u30A1\u30A4\u30EB\u4E2D\u3067\u8907\u6570\u56DE\u5B9A\u7FA9\u3055\u308C\u307E\u3057\u305F TREXGrammarReader.NonExistentParentGrammar =\ \u89AA\u30B0\u30E9\u30DE\u30FC\u304C\u306A\u3044\u306B\u3082\u95A2\u308F\u3089\u305A\u53C2\u7167\u3055\u308C\u3066\u3044\u307E\u3059 TREXGrammarReader.InterleavedString =\ \u8981\u7D20\u3084\u30C7\u30FC\u30BF\u578B\u6307\u5B9A\u306F\u8981\u7D20\u306E\u4E2D\u3067\u306F\u4F7F\u3048\u307E\u305B\u3093 TREXGrammarReader.SequencedString =\ \u8981\u7D20\u3084\u30C7\u30FC\u30BF\u578B\u6307\u5B9A\u306F\u8981\u7D20\u306E\u4E2D\u3067\u306F\u4F7F\u3048\u307E\u305B\u3093 TREXGrammarReader.RepeatedString =\ \u8981\u7D20\u3084\u30C7\u30FC\u30BF\u578B\u6307\u5B9A\u3092\u7E70\u308A\u8FD4\u3057\u6307\u5B9A\u306E\u4E2D\u3067\u4F7F\u3046\u3053\u3068\u306F\u51FA\u6765\u307E\u305B\u3093 msv-2009.1/msv/src/com/sun/msv/reader/trex/TREXBaseReader.java0000644000175000017500000002473210326262540024203 0ustar giovannigiovanni/* * @(#)$Id: TREXBaseReader.java 1695 2005-10-21 22:02:08Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import java.text.MessageFormat; import java.util.ResourceBundle; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.Grammar; import com.sun.msv.grammar.trex.TREXGrammar; import com.sun.msv.reader.ChoiceState; import com.sun.msv.reader.GrammarReader; import com.sun.msv.reader.GrammarReaderController; import com.sun.msv.reader.InterleaveState; import com.sun.msv.reader.SequenceState; import com.sun.msv.reader.State; import com.sun.msv.reader.TerminalState; import com.sun.msv.util.LightStack; import com.sun.msv.util.StartTagInfo; /** * reads TREX grammar from SAX2 and constructs abstract grammar model. * * @author Kohsuke KAWAGUCHI */ public abstract class TREXBaseReader extends GrammarReader { /** full constructor */ public TREXBaseReader( GrammarReaderController controller, SAXParserFactory parserFactory, ExpressionPool pool, StateFactory stateFactory, State rootState ) { super(controller,parserFactory,pool,rootState); this.sfactory = stateFactory; } protected String localizeMessage( String propertyName, Object[] args ) { String format; try { format = ResourceBundle.getBundle("com.sun.msv.reader.trex.Messages").getString(propertyName); } catch( Exception e ) { format = ResourceBundle.getBundle("com.sun.msv.reader.Messages").getString(propertyName); } return MessageFormat.format(format, args ); } /** grammar object currently being loaded. */ protected TREXGrammar grammar; /** obtains parsed grammar object only if parsing was successful. */ public final TREXGrammar getResult() { if(controller.hadError()) return null; else return grammar; } public Grammar getResultAsGrammar() { return getResult(); } /** stack that stores value of ancestor 'ns' attribute. */ private LightStack nsStack = new LightStack(); /** target namespace: currently active 'ns' attribute */ protected String targetNamespace =""; public final String getTargetNamespace() { return targetNamespace; } /** * creates various State object, which in turn parses grammar. * parsing behavior can be customized by implementing custom StateFactory. */ public static abstract class StateFactory { public State nsName ( State parent, StartTagInfo tag ) { return new NameClassNameState(); } public State nsAnyName ( State parent, StartTagInfo tag ) { return new NameClassAnyNameState(); } public State nsNsName ( State parent, StartTagInfo tag ) { return new NameClassNsNameState(); } public State nsNot ( State parent, StartTagInfo tag ) { return new NameClassNotState(); } public State nsDifference( State parent, StartTagInfo tag ) { return new NameClassDifferenceState(); } public State nsChoice ( State parent, StartTagInfo tag ) { return new NameClassChoiceState(); } public State element ( State parent, StartTagInfo tag ) { return new ElementState(); } public State attribute ( State parent, StartTagInfo tag ) { return new AttributeState(); } public State group ( State parent, StartTagInfo tag ) { return new SequenceState(); } public State interleave ( State parent, StartTagInfo tag ) { return new InterleaveState(); } public State choice ( State parent, StartTagInfo tag ) { return new ChoiceState(); } public State optional ( State parent, StartTagInfo tag ) { return new OptionalState(); } public State zeroOrMore ( State parent, StartTagInfo tag ) { return new ZeroOrMoreState(); } public State oneOrMore ( State parent, StartTagInfo tag ) { return new OneOrMoreState(); } public State mixed ( State parent, StartTagInfo tag ) { return new MixedState(); } public State empty ( State parent, StartTagInfo tag ) { return new TerminalState(Expression.epsilon); } public State notAllowed ( State parent, StartTagInfo tag ) { return new TerminalState(Expression.nullSet); } public State includeGrammar( State parent, StartTagInfo tag ) { return new IncludeMergeState(); } public State grammar ( State parent, StartTagInfo tag ) { return new GrammarState(); } public State start ( State parent, StartTagInfo tag ) { return new StartState(); } public abstract State define( State parent, StartTagInfo tag ); public State ref ( State parent, StartTagInfo tag ) { return new RefState("true".equals(tag.getAttribute("parent"))); } //
      s in the element is not available by default. public State divInGrammar( State parent, StartTagInfo tag ) { return null; } public TREXGrammar createGrammar( ExpressionPool pool, TREXGrammar parent ) { return new TREXGrammar(pool,parent); } public State includedGrammar() { return new RootMergedGrammarState(); } } public final StateFactory sfactory; protected State createNameClassChildState( State parent, StartTagInfo tag ) { if(tag.localName.equals("name")) return sfactory.nsName(parent,tag); if(tag.localName.equals("anyName")) return sfactory.nsAnyName(parent,tag); if(tag.localName.equals("nsName")) return sfactory.nsNsName(parent,tag); if(tag.localName.equals("not")) return sfactory.nsNot(parent,tag); if(tag.localName.equals("difference")) return sfactory.nsDifference(parent,tag); if(tag.localName.equals("choice")) return sfactory.nsChoice(parent,tag); return null; // unknown element. let the default error be thrown. } public State createExpressionChildState( State parent, StartTagInfo tag ) { if(tag.localName.equals("element")) return sfactory.element(parent,tag); if(tag.localName.equals("attribute")) return sfactory.attribute(parent,tag); if(tag.localName.equals("group")) return sfactory.group(parent,tag); if(tag.localName.equals("interleave")) return sfactory.interleave(parent,tag); if(tag.localName.equals("choice")) return sfactory.choice(parent,tag); // if(tag.localName.equals("concur")) return sfactory.concur(parent,tag); if(tag.localName.equals("optional")) return sfactory.optional(parent,tag); if(tag.localName.equals("zeroOrMore")) return sfactory.zeroOrMore(parent,tag); if(tag.localName.equals("oneOrMore")) return sfactory.oneOrMore(parent,tag); if(tag.localName.equals("mixed")) return sfactory.mixed(parent,tag); if(tag.localName.equals("ref")) return sfactory.ref(parent,tag); if(tag.localName.equals("empty")) return sfactory.empty(parent,tag); // if(tag.localName.equals("anyString")) return sfactory.anyString(parent,tag); // if(tag.localName.equals("string")) return sfactory.string(parent,tag); // if(tag.localName.equals("data")) return sfactory.data(parent,tag); if(tag.localName.equals("notAllowed")) return sfactory.notAllowed(parent,tag); if(tag.localName.equals("grammar")) return sfactory.grammar(parent,tag); return null; // unknown element. let the default error be thrown. } /** * performs final wrap-up. * This method is called from the RootState object, after the parsing is completed. * *

      * This method has to be called after the run-away expression check is done. */ public void wrapUp() {} // SAX event interception //-------------------------------- public void startElement( String a, String b, String c, Attributes d ) throws SAXException { // handle 'ns' attribute propagation nsStack.push(targetNamespace); if( d.getIndex("ns")!=-1 ) targetNamespace = d.getValue("ns"); // if nothing specified, targetNamespace stays the same. // for root state, startTag is null. super.startElement(a,b,c,d); } public void endElement( String a, String b, String c ) throws SAXException { super.endElement(a,b,c); targetNamespace = (String)nsStack.pop(); } // error messages public static final String ERR_MISSING_CHILD_NAMECLASS = // arg:0 "TREXGrammarReader.MissingChildNameClass"; public static final String ERR_MORE_THAN_ONE_NAMECLASS = // arg:0 "TREXGrammarReader.MoreThanOneNameClass"; public static final String ERR_UNDECLARED_PREFIX = // arg:1 "TREXGrammarReader.UndeclaredPrefix"; public static final String ERR_UNDEFINED_PATTERN = // arg:1 "TREXGrammarReader.UndefinedPattern"; public static final String ERR_UNKNOWN_DATATYPE_VOCABULARY = // arg:1 "TREXGrammarReader.UnknownDataTypeVocabulary"; public static final String ERR_BAD_COMBINE = // arg:1 "TREXGrammarReader.BadCombine"; public static final String ERR_COMBINE_MISSING = // arg:1 "TREXGrammarReader.CombineMissing"; public static final String WRN_COMBINE_IGNORED = "TREXGrammarReader.Warning.CombineIgnored"; public static final String WRN_OBSOLETED_XMLSCHEMA_NAMSPACE = "TREXGrammarReader.Warning.ObsoletedXMLSchemaNamespace"; public static final String ERR_DUPLICATE_DEFINITION = "TREXGrammarReader.DuplicateDefinition"; public static final String ERR_NONEXISTENT_PARENT_GRAMMAR = "TREXGrammarReader.NonExistentParentGrammar"; public static final String ERR_INTERLEAVED_STRING = "TREXGrammarReader.InterleavedString"; public static final String ERR_SEQUENCED_STRING = "TREXGrammarReader.SequencedString"; public static final String ERR_REPEATED_STRING = "TREXGrammarReader.RepeatedString"; public static final String ERR_INTERLEAVED_ANYSTRING = "TREXGrammarReader.InterleavedAnyString"; } msv-2009.1/msv/src/com/sun/msv/reader/trex/MixedState.java0000644000175000017500000000123007671170035023544 0ustar giovannigiovanni/* * @(#)$Id: MixedState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import com.sun.msv.grammar.Expression; import com.sun.msv.reader.SequenceState; /** * parses <mixed> pattern. * * @author Kohsuke KAWAGUCHI */ public class MixedState extends SequenceState { protected Expression annealExpression( Expression exp ) { return reader.pool.createMixed(exp); } } msv-2009.1/msv/src/com/sun/msv/reader/trex/NameClassState.java0000644000175000017500000000212007671170035024343 0ustar giovannigiovanni/* * @(#)$Id: NameClassState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import com.sun.msv.grammar.NameClass; import com.sun.msv.reader.SimpleState; /** * Base implementation for NameClass primitives * * @author Kohsuke KAWAGUCHI */ public abstract class NameClassState extends SimpleState { public final void endSelf() { // pass the pattern to the parent ((NameClassOwner)parentState).onEndChild(makeNameClass()); super.endSelf(); } /** * This method is called from endElement method. * Implementation has to provide NameClass object that represents the content of * this element. */ protected abstract NameClass makeNameClass(); protected final String getPropagatedNamespace() { return ((TREXBaseReader)reader).targetNamespace; } } msv-2009.1/msv/src/com/sun/msv/reader/trex/RootMergedGrammarState.java0000644000175000017500000000176507671170035026071 0ustar giovannigiovanni/* * @(#)$Id: RootMergedGrammarState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import com.sun.msv.grammar.Expression; import com.sun.msv.reader.ExpressionOwner; import com.sun.msv.reader.SimpleState; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * parses root state of a merged grammar. * * @author Kohsuke KAWAGUCHI */ public class RootMergedGrammarState extends SimpleState implements ExpressionOwner { protected State createChildState( StartTagInfo tag ) { // expects "grammar" element only, and creates MergeGrammarState if( tag.localName.equals("grammar") ) return new DivInGrammarState(); return null; } public void onEndChild(Expression exp) { } } msv-2009.1/msv/src/com/sun/msv/reader/trex/NameClassNameState.java0000644000175000017500000000256307671170035025157 0ustar giovannigiovanni/* * @(#)$Id: NameClassNameState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import com.sun.msv.datatype.xsd.WhiteSpaceProcessor; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.SimpleNameClass; /** * parses <name> name class. * * @author Kohsuke KAWAGUCHI */ public class NameClassNameState extends NameClassWithoutChildState { protected final StringBuffer text = new StringBuffer(); public void characters( char[] buf, int from, int len ) { text.append(buf,from,len); } public void ignorableWhitespace( char[] buf, int from, int len ) { text.append(buf,from,len); } protected NameClass makeNameClass() { String name = WhiteSpaceProcessor.collapse(new String(text)); int idx = name.indexOf(':'); if(idx<0) // if the name is NCName return new SimpleNameClass( getPropagatedNamespace(), name ); // if it's a QName, resolve it. String[] qname = reader.splitQName(name); return new SimpleNameClass( qname[0], qname[1] ); } } msv-2009.1/msv/src/com/sun/msv/reader/trex/RootIncludedPatternState.java0000644000175000017500000000362707671170035026443 0ustar giovannigiovanni/* * @(#)$Id: RootIncludedPatternState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import com.sun.msv.grammar.Expression; import com.sun.msv.reader.ExpressionOwner; import com.sun.msv.reader.SimpleState; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * parses the root state of a grammar included as a pattern. * * @author Kohsuke KAWAGUCHI */ public class RootIncludedPatternState extends SimpleState implements ExpressionOwner { protected State createChildState( StartTagInfo tag ) { // grammar has to be treated separately so as not to // create unnecessary TREXGrammar object. // if(tag.localName.equals("grammar")) // return new GrammarState(); State s = reader.createExpressionChildState(this,tag); // if(s!=null) { // // other pattern element is specified. // // create wrapper grammar // final TREXBaseReader reader = (TREXBaseReader)this.reader; // reader.grammar = new TREXGrammar( reader.pool, null ); // simple = true; // } return s; } /** * parsed external pattern will be reported to this object. * This state parses top-level, so parentState is null. */ private final IncludePatternState grandParent; protected RootIncludedPatternState( IncludePatternState grandpa ) { this.grandParent = grandpa; } public void onEndChild(Expression exp) { if( grandParent!=null ) // this must be from grammar element. pass it to the IncludePatternState. grandParent.onEndChild(exp); } } msv-2009.1/msv/src/com/sun/msv/reader/trex/OneOrMoreState.java0000644000175000017500000000124407671170035024350 0ustar giovannigiovanni/* * @(#)$Id: OneOrMoreState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import com.sun.msv.grammar.Expression; import com.sun.msv.reader.SequenceState; /** * parses <oneOrMore> pattern. * * @author Kohsuke KAWAGUCHI */ public class OneOrMoreState extends SequenceState { protected Expression annealExpression( Expression exp ) { return reader.pool.createOneOrMore(exp); } } msv-2009.1/msv/src/com/sun/msv/reader/trex/RootState.java0000644000175000017500000000372710326250764023435 0ustar giovannigiovanni/* * @(#)$Id: RootState.java 1689 2005-10-21 20:39:16Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import com.sun.msv.grammar.Expression; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * invokes State object that parses the document element. * * This class is used to parse the first grammar. * * @author Kohsuke KAWAGUCHI */ public class RootState extends RootIncludedPatternState { public RootState() { super(null); } protected State createChildState( StartTagInfo tag ) { final TREXBaseReader reader = (TREXBaseReader)this.reader; // grammar has to be treated separately so as not to // create unnecessary TREXGrammar object. if(tag.localName.equals("grammar")) return reader.sfactory.grammar(null,tag); State s = super.createChildState(tag); if(s!=null) { // other pattern element is specified. // create wrapper grammar reader.grammar = reader.sfactory.createGrammar( reader.pool, null ); simple = true; } return s; } /** * a flag that indicates 'grammar' element was not used. * In that case, this object is responsible to set start pattern. */ private boolean simple = false; // GrammarState implements ExpressionState, // so RootState has to implement ExpressionOwner. public void onEndChild(Expression exp) { super.onEndChild(exp); final TREXBaseReader reader = (TREXBaseReader)this.reader; if( simple ) // set the top-level expression if that is necessary. reader.grammar.exp = exp; // perform final wrap-up. reader.wrapUp(); } } msv-2009.1/msv/src/com/sun/msv/reader/trex/DivInGrammarState.java0000644000175000017500000000373507671170035025032 0ustar giovannigiovanni/* * @(#)$Id: DivInGrammarState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import com.sun.msv.grammar.Expression; import com.sun.msv.reader.ExpressionOwner; import com.sun.msv.reader.ExpressionState; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * Used to parse merged grammars. Also <div> element in the grammar element * (of RELAX NG). * * DivInGrammarState itself should not be a ExpressionState. However, GrammarState, * which is a derived class of this class, is a ExpressionState. * * Therefore this class has to extend ExpressionState. * * @author Kohsuke KAWAGUCHI */ public class DivInGrammarState extends ExpressionState implements ExpressionOwner { protected final TREXBaseReader getReader() { return (TREXBaseReader)reader; } protected Expression makeExpression() { // this method doesn't provide any pattern return null; } protected State createChildState( StartTagInfo tag ) { if(tag.localName.equals("start")) return getReader().sfactory.start(this,tag); if(tag.localName.equals("define")) return getReader().sfactory.define(this,tag); if(tag.localName.equals("include")) return getReader().sfactory.includeGrammar(this,tag); // div is available only for RELAX NG. // The default implementation of divInGrammar returns null. if(tag.localName.equals("div")) return getReader().sfactory.divInGrammar(this,tag); return null; } // DefineState and StartState is implemented by using ExpressionState. // By contract of that interface, this object has to implement ExpressionOwner. public void onEndChild( Expression exp ) {} // do nothing. } msv-2009.1/msv/src/com/sun/msv/reader/trex/NameClassAnyNameState.java0000644000175000017500000000115607730143103025614 0ustar giovannigiovanni/* * @(#)$Id: NameClassAnyNameState.java 1601 2003-09-11 19:00:19Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import com.sun.msv.grammar.NameClass; /** * parses <anyName> name class. * * @author Kohsuke KAWAGUCHI */ public class NameClassAnyNameState extends NameClassWithoutChildState { protected NameClass makeNameClass() { return NameClass.ALL; } } msv-2009.1/msv/src/com/sun/msv/reader/trex/RefState.java0000644000175000017500000000370707671170035023225 0ustar giovannigiovanni/* * @(#)$Id: RefState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.trex.TREXGrammar; import com.sun.msv.reader.ExpressionWithoutChildState; /** * parses <ref> pattern. * * @author Kohsuke KAWAGUCHI */ public class RefState extends ExpressionWithoutChildState { public RefState( boolean parentRef ) { this.parentRef = parentRef; } protected boolean parentRef; protected Expression makeExpression() { final String name = startTag.getCollapsedAttribute("name"); if(name==null) { // name attribute is required. reader.reportError( TREXBaseReader.ERR_MISSING_ATTRIBUTE, "ref","name"); // recover by returning something that can be interpreted as Pattern return Expression.nullSet; } TREXGrammar grammar = ((TREXBaseReader)this.reader).grammar; if( parentRef ) { grammar = grammar.getParentGrammar(); if( grammar==null ) { reader.reportError( TREXBaseReader.ERR_NONEXISTENT_PARENT_GRAMMAR ); return Expression.nullSet; // recover by returning something that can be interpreted as Pattern } } ReferenceExp r = grammar.namedPatterns.getOrCreate(name); wrapUp(r); return r; } /** * Performs the final wrap-up. */ protected void wrapUp( ReferenceExp r ) { reader.backwardReference.memorizeLink(r); } } msv-2009.1/msv/src/com/sun/msv/reader/trex/TREXSequencedStringChecker.java0000644000175000017500000001503007671170035026573 0ustar giovannigiovanni/* * @(#)$Id: TREXSequencedStringChecker.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import java.util.Map; import java.util.Set; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.ChoiceExp; import com.sun.msv.grammar.ConcurExp; import com.sun.msv.grammar.DataExp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.ExpressionVisitor; import com.sun.msv.grammar.InterleaveExp; import com.sun.msv.grammar.ListExp; import com.sun.msv.grammar.MixedExp; import com.sun.msv.grammar.OneOrMoreExp; import com.sun.msv.grammar.OtherExp; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.SequenceExp; import com.sun.msv.grammar.ValueExp; /** * makes sure that there is no sequenced string. * * "sequenced string" is something like this. *

      * <oneOrMore> * <string> abc </string> * </oneOrMore> * * * Also, TREX prohibits sequence of typed strings and elements. * *

      * In this checker, we introduce a function "f" that takes * a string and computes the string-sensitivity of the pattern. * *

      * "f" returns 3 bits of information. One is whether it contains * elements. Another is whehter it contains text. And the last is * whether it contains DataExp/ValueExp. * *

      * "f" is computed recursively through the pattern. * * @author Kohsuke KAWAGUCHI */ public class TREXSequencedStringChecker implements ExpressionVisitor { /** * If this flag is set to true, this class raises an error for * anyStrings in two branches of interleave. */ private final boolean rejectTextInInterleave; /** integer pool implementation. */ private static final Integer[] intPool = new Integer[]{ new Integer(0),new Integer(1),new Integer(2),new Integer(3), new Integer(4),new Integer(5),new Integer(6),new Integer(7) }; // 3 bit of information private static final int HAS_ELEMENT = 4; private static final int HAS_ANYSTRING = 2; private static final int HAS_DATA = 1; // data or value. private final TREXBaseReader reader; public TREXSequencedStringChecker( TREXBaseReader reader, boolean _rejectTextInInterleave ) { this.reader = reader; this.rejectTextInInterleave = _rejectTextInInterleave; } /** * set of checked Expressions. * * once an ElementExp/AttributeExp is checked, it will be added to this set. * this set is used to prevent infinite recursion. */ private final Set checkedExps = new java.util.HashSet(); /** * set of checked ReferenceExps. * * Once a ReferenceExp is checked, it will be added (with its result) * to this map. This is useful to speed up the check. */ private final Map checkedRefExps = new java.util.HashMap(); public Object onRef( ReferenceExp exp ) { Object r = checkedRefExps.get(exp); if(r!=null) return r; checkedRefExps.put(exp, r=exp.exp.visit(this) ); return r; } public Object onOther( OtherExp exp ) { return exp.exp.visit(this); } public Object onInterleave( InterleaveExp exp ) { Object l = exp.exp1.visit(this); Object r = exp.exp2.visit(this); if(isError(l,r)) { // where is the source of error? reader.reportError( TREXBaseReader.ERR_INTERLEAVED_STRING ); return intPool[0]; } if( rejectTextInInterleave && (toInt(l)&HAS_ANYSTRING)!=0 && (toInt(r)&HAS_ANYSTRING)!=0 ) { reader.reportError( TREXBaseReader.ERR_INTERLEAVED_ANYSTRING ); return intPool[0]; } return merge(l,r); } public Object onSequence( SequenceExp exp ) { Object l = exp.exp1.visit(this); Object r = exp.exp2.visit(this); if(isError(l,r)) { // where is the source of error? reader.reportError( TREXBaseReader.ERR_SEQUENCED_STRING ); return intPool[0]; } return merge(l,r); } public Object onEpsilon() { return intPool[0]; } public Object onNullSet() { return intPool[0]; } public Object onData( DataExp exp ) { return intPool[HAS_DATA]; } public Object onValue( ValueExp exp ) { return intPool[HAS_DATA]; } // do not traverse contents of list. public Object onList( ListExp exp ) { return intPool[HAS_DATA]; } public Object onAnyString() { return intPool[HAS_ANYSTRING]; } public Object onAttribute( AttributeExp exp ) { if( checkedExps.add(exp) ) exp.exp.visit(this); return intPool[0]; } public Object onElement( ElementExp exp ) { if( checkedExps.add(exp) ) // if this is the first visit // this has to be done before checking content model // otherwise it leads to the infinite recursion. exp.contentModel.visit(this); return intPool[HAS_ELEMENT]; } private static final int toInt( Object o ) { return ((Integer)o).intValue(); } private static Object merge( Object o1, Object o2 ) { return intPool[toInt(o1)|toInt(o2)]; } /** * It is an error if a pattern with data is combined to other patterns. */ private static boolean isError( Object o1, Object o2 ) { return (toInt(o1)&HAS_DATA)!=0 && toInt(o2)!=0 || (toInt(o2)&HAS_DATA)!=0 && toInt(o1)!=0; } public Object onChoice( ChoiceExp exp ) { return merge( exp.exp1.visit(this), exp.exp2.visit(this) ); } public Object onConcur( ConcurExp exp ) { return merge( exp.exp1.visit(this), exp.exp2.visit(this) ); } public Object onOneOrMore( OneOrMoreExp exp ) { Object o = exp.exp.visit(this); if( (toInt(o)&HAS_DATA) !=0 ) { reader.reportError(TREXBaseReader.ERR_REPEATED_STRING); return intPool[0]; } return o; } public Object onMixed( MixedExp exp ) { Object o = exp.exp.visit(this); if( rejectTextInInterleave && (toInt(o)&HAS_ANYSTRING)!=0 ) { reader.reportError( TREXBaseReader.ERR_INTERLEAVED_ANYSTRING ); return intPool[0]; } return merge(o,intPool[HAS_ANYSTRING]); } } msv-2009.1/msv/src/com/sun/msv/reader/trex/NameClassOwner.java0000644000175000017500000000117307671170035024364 0ustar giovannigiovanni/* * @(#)$Id: NameClassOwner.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import com.sun.msv.grammar.NameClass; /** * interface that must be implemented by the parent state of NameClassState. * * NameClassState notifies its parent by using this interface. * * @author Kohsuke KAWAGUCHI */ interface NameClassOwner { void onEndChild( NameClass p ); } msv-2009.1/msv/src/com/sun/msv/reader/trex/NameClassNsNameState.java0000644000175000017500000000130007671170035025444 0ustar giovannigiovanni/* * @(#)$Id: NameClassNsNameState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.NamespaceNameClass; /** * parses <nsName> name class. * * @author Kohsuke KAWAGUCHI */ public class NameClassNsNameState extends NameClassWithoutChildState { protected NameClass makeNameClass() { return new NamespaceNameClass( getPropagatedNamespace() ); } } msv-2009.1/msv/src/com/sun/msv/reader/trex/GrammarState.java0000644000175000017500000000430507671170035024072 0ustar giovannigiovanni/* * @(#)$Id: GrammarState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.trex.TREXGrammar; /** * parses <grammar> element. * * this state is used to parse top-level grammars and nested grammars. * grammars merged by include element are handled by MergeGrammarState. * *

      * this class provides a new TREXGrammar object to localize names defined * within this grammar. * * @author Kohsuke KAWAGUCHI */ public class GrammarState extends DivInGrammarState { protected TREXGrammar previousGrammar; protected TREXGrammar newGrammar; protected Expression makeExpression() { // start pattern is the grammar-as-a-pattern. return newGrammar; } protected void startSelf() { super.startSelf(); previousGrammar = getReader().grammar; newGrammar = getReader().sfactory.createGrammar( reader.pool, previousGrammar ); getReader().grammar = newGrammar; } public void endSelf() { final TREXGrammar grammar = getReader().grammar; // detect references to undefined pattterns reader.detectUndefinedOnes( grammar.namedPatterns, TREXBaseReader.ERR_UNDEFINED_PATTERN ); // is start pattern defined? if( grammar.exp==null ) { reader.reportError( TREXBaseReader.ERR_MISSING_TOPLEVEL ); grammar.exp = Expression.nullSet; // recover by assuming a valid pattern } // this method is called when this State is about to be removed. // restore the previous grammar if( previousGrammar!=null ) getReader().grammar = previousGrammar; // if the previous grammar is null, it means this grammar is the top-level // grammar. In that case, leave it there so that GrammarReader can access // the loaded grammar. super.endSelf(); } } msv-2009.1/msv/src/com/sun/msv/reader/trex/NameClassWithChildState.java0000644000175000017500000000501010034315204026126 0ustar giovannigiovanni/* * @(#)$Id: NameClassWithChildState.java 1634 2004-04-05 17:42:28Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import com.sun.msv.grammar.NameClass; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * parses name class that has child name classes * * @author Kohsuke KAWAGUCHI */ public abstract class NameClassWithChildState extends NameClassState implements NameClassOwner { /** * name class object that is being created. * See {@link #castNameClass(NameClass, NameClass)} and {@link #annealNameClass(NameClass)} methods * for how a pattern will be created. */ protected NameClass nameClass = null; /** * if this flag is true, then it is OK not to have any children. */ protected boolean allowNullChild = false; /** * receives a Pattern object that is contained in this element. */ public final void onEndChild( NameClass childNameClass ) { nameClass = castNameClass( nameClass, childNameClass ); } protected final NameClass makeNameClass() { if( nameClass==null && !allowNullChild ) { reader.reportError( TREXBaseReader.ERR_MISSING_CHILD_NAMECLASS ); nameClass = NameClass.ALL; // recover by assuming some name class. } return annealNameClass(nameClass); } protected State createChildState( StartTagInfo tag ) { return ((TREXBaseReader)reader).createNameClassChildState(this,tag); } /** * combines half-made name class and newly found child name class into the name class. * *

      * Say this container has three child name class n1,n2, and n3. * Then, the name class of this container will be made by the following method * invocations. * *

           *   annealNameClass( castNameClass( castNameClass( castNameClass(null,p1), p2), p3 ) )
           * 
      */ protected abstract NameClass castNameClass( NameClass halfCastedNameClass, NameClass newChildNameClass ); /** * performs final wrap-up and returns a fully created NameClass object * that represents this element. */ protected NameClass annealNameClass( NameClass nameClass ) { // default implementation does nothing. return nameClass; } } msv-2009.1/msv/src/com/sun/msv/reader/trex/NameClassChoiceState.java0000644000175000017500000000144607671170035025470 0ustar giovannigiovanni/* * @(#)$Id: NameClassChoiceState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import com.sun.msv.grammar.ChoiceNameClass; import com.sun.msv.grammar.NameClass; /** * parses <choice> name class. * * @author Kohsuke KAWAGUCHI */ public class NameClassChoiceState extends NameClassWithChildState { protected NameClass castNameClass( NameClass halfCasted, NameClass newChild ) { if( halfCasted==null ) return newChild; // first item else return new ChoiceNameClass( halfCasted, newChild ); } } msv-2009.1/msv/src/com/sun/msv/reader/trex/ng/0000755000175000017500000000000011622453066021241 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/reader/trex/ng/DefineState.java0000644000175000017500000001132207671170035024277 0ustar giovannigiovanni/* * @(#)$Id: DefineState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex.ng; import org.xml.sax.Locator; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ReferenceExp; /** * parses <define> declaration. * * @author Kohsuke KAWAGUCHI */ public class DefineState extends com.sun.msv.reader.trex.DefineState { private RELAXNGReader.RefExpParseInfo prevNamedPattern; private boolean previousDirectRefernce; protected void startSelf() { final RELAXNGReader reader = (RELAXNGReader)this.reader; super.startSelf(); // update the currentNamedPattern field. prevNamedPattern = reader.currentNamedPattern; // push previousDirectRefernce = reader.directRefernce; reader.directRefernce = true; ReferenceExp exp = getReference(); if(exp==null) //abort. there was an error in this declaration reader.currentNamedPattern = null; else { reader.currentNamedPattern = reader.getRefExpParseInfo(exp); if(reader.currentNamedPattern.redefinition!= RELAXNGReader.RefExpParseInfo.notBeingRedefined ) // if this pattern is being redefined, // we must not augument RefParseInfo.refs from this pattern. reader.currentNamedPattern = null; } } protected void endSelf() { final RELAXNGReader reader = (RELAXNGReader)this.reader; reader.currentNamedPattern = prevNamedPattern; // pop reader.directRefernce = previousDirectRefernce; super.endSelf(); } /** * combines two expressions into one as specified by the combine parameter, * and returns a new expression. * * If the combine parameter is invalid, then return null. */ protected Expression doCombine( ReferenceExp baseExp, Expression newExp, String combine ) { final RELAXNGReader reader = (RELAXNGReader)this.reader; RELAXNGReader.RefExpParseInfo info = reader.getRefExpParseInfo(baseExp); // RELAX NG allows multiple definitions in the same file. if( combine==null ) { // this is a head declaration if( info.haveHead ) { // two head declarations: an error. reader.reportError( RELAXNGReader.ERR_COMBINE_MISSING, baseExp.name ); return baseExp.exp; } info.haveHead = true; } else { // check the consistency of the combine method. if( info.combineMethod==null ) { // If this is the first time @combine is used for this pattern... info.combineMethod = combine.trim(); // make sure that the value is ok. if( !info.combineMethod.equals("choice") && !info.combineMethod.equals("interleave") ) reader.reportError( RELAXNGReader.ERR_BAD_COMBINE, info.combineMethod ); } else { if( !info.combineMethod.equals(combine) ) { // different combine method. reader.reportError( new Locator[]{location, reader.getDeclaredLocationOf(baseExp)}, RELAXNGReader.ERR_INCONSISTENT_COMBINE, new Object[]{baseExp.name} ); // reset the combine method to null // to surpress excessive error messages. info.combineMethod = null; return baseExp.exp; // ignore the new pattern } } } if( baseExp.exp==null ) // the first definition return newExp; if( info.redefinition!=RELAXNGReader.RefExpParseInfo.notBeingRedefined ) { // ignore the new definition // because this definition is currently being redefined by // the caller. // the original definition was found. info.redefinition = RELAXNGReader.RefExpParseInfo.originalFound; return baseExp.exp; } if( info.combineMethod.equals("choice") ) return reader.pool.createChoice( baseExp.exp, newExp ); if( info.combineMethod.equals("interleave") ) return reader.pool.createInterleave( baseExp.exp, newExp ); // some kind of error. return null; } } msv-2009.1/msv/src/com/sun/msv/reader/trex/ng/NGNameState.java0000644000175000017500000000432207730143103024204 0ustar giovannigiovanni/* * @(#)$Id: NGNameState.java 1601 2003-09-11 19:00:19Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex.ng; import com.sun.msv.grammar.DifferenceNameClass; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.NamespaceNameClass; import com.sun.msv.reader.State; import com.sun.msv.reader.trex.NameClassWithChildState; import com.sun.msv.util.StartTagInfo; /** * parses <anyName> name class. * * @author Kohsuke KAWAGUCHI */ public abstract class NGNameState extends NameClassWithChildState { NGNameState() { allowNullChild = true; } protected State createChildState( StartTagInfo tag ) { // tag is allowed only once. if( super.nameClass==null && tag.localName.equals("except") ) return ((RELAXNGReader)reader).getStateFactory().nsExcept(this,tag); return null; } protected NameClass castNameClass( NameClass halfCastedNameClass, NameClass newChildNameClass ) { // error check is done by the createChildState method. return newChildNameClass; } /** * performs final wrap-up and returns a fully created NameClass object * that represents this element. */ protected NameClass annealNameClass( NameClass nameClass ) { NameClass r = getMainNameClass(); if( nameClass!=null ) r = new DifferenceNameClass( r, nameClass ); return r; } /** this method should return the name class that is used as the base. */ protected abstract NameClass getMainNameClass(); /** Parsing state for <anyName> */ public static class AnyNameState extends NGNameState { protected NameClass getMainNameClass() { return NameClass.ALL; } } /** Parsing state for <nsName> */ public static class NsNameState extends NGNameState { protected NameClass getMainNameClass() { return new NamespaceNameClass( getPropagatedNamespace() ); } } } msv-2009.1/msv/src/com/sun/msv/reader/trex/ng/ListState.java0000644000175000017500000000125207671170035024021 0ustar giovannigiovanni/* * @(#)$Id: ListState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex.ng; import com.sun.msv.grammar.Expression; import com.sun.msv.reader.SequenceState; /** * state that parses <list> pattern of RELAX NG. * * @author Kohsuke KAWAGUCHI */ public class ListState extends SequenceState { protected Expression annealExpression( Expression exp ) { return reader.pool.createList(exp); } } msv-2009.1/msv/src/com/sun/msv/reader/trex/ng/package.html0000644000175000017500000000010007350477355023523 0ustar giovannigiovanni

      parses RELAX NG into AGM.

      msv-2009.1/msv/src/com/sun/msv/reader/trex/ng/Messages_ja.properties0000644000175000017500000001415007401037066025577 0ustar giovannigiovanni TREXGrammarReader.InterleavedAnyString = \ \u304C\u4E8C\u3064\u4EE5\u4E0A\u306E\u679D\u306B\u3092\u6301\u3064\u3053\u3068\u306F\u51FA\u6765\u307E\u305B\u3093 RELAXNGReader.BadFacet =\ \u30C7\u30FC\u30BF\u578B\u306B\u30D1\u30E9\u30E1\u30FC\u30BF"{0}"\u3092\u30BB\u30C3\u30C8\u3059\u308B\u3053\u3068\u304C\u3067\u304D\u307E\u305B\u3093: {1} RELAXNGReader.InvalidParameters =\ \u30D1\u30E9\u30E1\u30FC\u30BF\u304C\u4E0D\u6B63\u3067\u3059\uFF1A{0} RELAXNGReader.BadDataValue =\ \u30C7\u30FC\u30BF\u578B"{0}"\u306B\u306F\u4E0D\u9069\u5207\u306A\u5024\u3067\u3059\uFF1A{1} RELAXNGReader.UndefinedKey =\ \u5B9A\u7FA9\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC"{0}"\u3092\u53C2\u7167\u3057\u3066\u3044\u307E\u3059 RELAXNGReader.UndefinedDataType1 =\ \u30C7\u30FC\u30BF\u578B"{0}"\u306F\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u305B\u3093\uFF1A{1} RELAXNGReader.InconsistentKeyType =\ \u30AD\u30FC"{0}"\u3092\u53C2\u7167\u3059\u308Bkey/keyref\u306F\u5168\u3066\u540C\u3058\u30C7\u30FC\u30BF\u578B\u3067\u306A\u304F\u3066\u306F\u306A\u308A\u307E\u305B\u3093 RELAXNGReader.InconsistentCombine =\ \u30D1\u30BF\u30FC\u30F3"{0}"\u306B\u5BFE\u3057\u3066\u8907\u6570\u306E\u4E92\u3044\u306B\u7570\u306A\u308Bcombine\u65B9\u6CD5\u304C\u6307\u5B9A\u3055\u308C\u3066\u3044\u307E\u3059 RELAXNGReader.RedefiningUndefined =\ \u30D1\u30BF\u30FC\u30F3"{0}"\u306F\u30AA\u30FC\u30D0\u30FC\u30E9\u30A4\u30C9\u3055\u308C\u3066\u3044\u307E\u3059\u304C\u3001\u305D\u3082\u305D\u3082\u5143\u306E\u5B9A\u7FA9\u304C\u3042\u308A\u307E\u305B\u3093 RELAXNGReader.UnknownDatatypeVocabulary1 =\ \u30C7\u30FC\u30BF\u578B\u30E9\u30A4\u30D6\u30E9\u30EA"{0}"\u306F\u4F7F\u3048\u307E\u305B\u3093: {1} RELAXNGReader.MultipleExcept =\ \u3092\u8907\u6570\u500B\u6307\u5B9A\u3059\u308B\u3053\u3068\u306F\u51FA\u6765\u307E\u305B\u3093 RELAXNGReader.NotAbsoluteURI = \ "{0}"\u306Fabsolute URI(\u7D76\u5BFEURI)\u3067\u306F\u3042\u308A\u307E\u305B\u3093 RELAXNGReader.AttributeInExcept = \ \u306E\u4E2D\u306B\u306F\u306F\u66F8\u3051\u307E\u305B\u3093 RELAXNGReader.ElementInExcept = \ \u306E\u4E2D\u306B\u306F\u306F\u66F8\u3051\u307E\u305B\u3093 RELAXNGReader.ListInExcept = \ \u306E\u4E2D\u306B\u306F\u306F\u66F8\u3051\u307E\u305B\u3093 RELAXNGReader.TextInExcept = \ \u306E\u4E2D\u306B\u306F\u306F\u66F8\u3051\u307E\u305B\u3093 RELAXNGReader.EmptyInExcept = \ \u306E\u4E2D\u306B\u306F\u306F\u66F8\u3051\u307E\u305B\u3093 RELAXNGReader.SequenceInExcept = \ \u306E\u4E2D\u306B\u306F\u306F\u66F8\u3051\u307E\u305B\u3093 RELAXNGReader.InterleaveInExcept = \ \u306E\u4E2D\u306B\u306F\u306F\u66F8\u3051\u307E\u305B\u3093 RELAXNGReader.OneOrMoreInExcept = \ \u306E\u4E2D\u306B\u306F/\u306F\u66F8\u3051\u307E\u305B\u3093 RELAXNGReader.RepeatedGroupedAttribute = \ \u3092\u30B0\u30EB\u30FC\u30D7\u5316\u3057\u3066\u7E70\u308A\u8FD4\u3059\u3053\u3068\u306F\u51FA\u6765\u307E\u305B\u3093 RELAXNGReader.ElementInAttribute = \ \u306E\u4E2D\u306B\u306F\u306F\u66F8\u3051\u307E\u305B\u3093 RELAXNGReader.AttributeInAttribute = \ \u306E\u4E2D\u306B\u306F\u306F\u66F8\u3051\u307E\u305B\u3093 RELAXNGReader.AttributeInList = \ \u306E\u4E2D\u306B\u306F\u306F\u66F8\u3051\u307E\u305B\u3093 RELAXNGReader.ElementInList = \ \u306E\u4E2D\u306B\u306F\u306F\u66F8\u3051\u307E\u305B\u3093 RELAXNGReader.ListInList = \ \u306E\u4E2D\u306B\u306F\u306F\u66F8\u3051\u307E\u305B\u3093 RELAXNGReader.TextInList = \ \u306E\u4E2D\u306B\u306F\u306F\u66F8\u3051\u307E\u305B\u3093\u3002\u306F\u4F7F\u3048\u307E\u3059 RELAXNGReader.AttributeInStart = \ \u306E\u4E2D\u306B\u306F\u306F\u66F8\u3051\u307E\u305B\u3093 RELAXNGReader.ListInStart = \ \u306E\u4E2D\u306B\u306F\u306F\u66F8\u3051\u307E\u305B\u3093 RELAXNGReader.TextInStart = \ \u306E\u4E2D\u306B\u306F\u306F\u66F8\u3051\u307E\u305B\u3093 RELAXNGReader.EmptyInStart = \ \u306E\u4E2D\u306B\u306F\u306F\u66F8\u3051\u307E\u305B\u3093 RELAXNGReader.SequenceInStart = \ \u306E\u4E2D\u306B\u306F\u306F\u66F8\u3051\u307E\u305B\u3093 RELAXNGReader.InterleaveInStart = \ \u306E\u4E2D\u306B\u306F\u306F\u66F8\u3051\u307E\u305B\u3093 RELAXNGReader.DataInStart = \ \u306E\u4E2D\u306B\u306F\u306F\u66F8\u3051\u307E\u305B\u3093 RELAXNGReader.OneOrMoreInStart = \ \u306E\u4E2D\u306B\u306F/\u306F\u66F8\u3051\u307E\u305B\u3093 RELAXNGReader.DataInInterleaveInList = \ \u306E\u4E2D\u306E\u306E\u4E2D\u306B\u306F\u3092\u66F8\u3051\u307E\u305B\u3093 RELAXNGReader.ValueInInterleaveInList = \ \u306E\u4E2D\u306E\u306E\u4E2D\u306B\u306F\u3092\u66F8\u3051\u307E\u305B\u3093 RELAXNGReader.AnyNameInAnyName = \ \u306E\u4E2D\u306B\u306F\u306F\u66F8\u3051\u307E\u305B\u3093 RELAXNGReader.AnyNameInNsName = \ \u306E\u4E2D\u306B\u306F\u306F\u66F8\u3051\u307E\u305B\u3093 RELAXNGReader.NsNameInNsName = \ \u306E\u4E2D\u306B\u306F\u306F\u66F8\u3051\u307E\u305B\u3093 RELAXNGReader.DuplicateAttributes = \ \uFF12\u3064\u4EE5\u4E0A\u306E\u304C\u540C\u3058\u540D\u524D"{0}"\u3092\u6301\u3063\u3066\u3044\u307E\u3059 RELAXNGReader.DuplicateElements = \ interleave\u306E\u8907\u6570\u306E\u679D\u306B\u540C\u540D\u306E\u8981\u7D20"{0}"\u304C\u542B\u307E\u308C\u3066\u3044\u307E\u3059 RELAXNGReader.InfosetUriAttribute = \ "http://www.w3.org/2000/xmlns"\u3092\u5C5E\u6027\u306E\u540D\u524D\u7A7A\u9593URI\u3068\u3057\u3066\u4F7F\u3046\u3053\u3068\u306F\u51FA\u6765\u307E\u305B\u3093 RELAXNGReader.XmlnsAttribute = \ "xmlns"\u3068\u3044\u3046\u540D\u524D\u306E\u5C5E\u6027\u3092\u5BA3\u8A00\u3059\u308B\u3053\u3068\u306F\u51FA\u6765\u307E\u305B\u3093 RELAXNGReader.NakedInfiniteAttributeNameClass = \ \u3084\u3092\u5C5E\u6027\u306B\u4F7F\u3046\u5834\u5408\u306F\u3001\u305D\u306E\u5C5E\u6027\u3092/\u3067\u56F2\u3093\u3067\u304F\u3060\u3055\u3044msv-2009.1/msv/src/com/sun/msv/reader/trex/ng/DataState.java0000644000175000017500000000673407671170035023771 0ustar giovannigiovanni/* * @(#)$Id: DataState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex.ng; import org.relaxng.datatype.DatatypeBuilder; import org.relaxng.datatype.DatatypeException; import com.sun.msv.datatype.ErrorDatatypeLibrary; import com.sun.msv.grammar.Expression; import com.sun.msv.reader.ExpressionOwner; import com.sun.msv.reader.ExpressionState; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; import com.sun.msv.util.StringPair; /** * parses <data> pattern. * * @author Kohsuke KAWAGUCHI */ public class DataState extends ExpressionState implements ExpressionOwner { protected State createChildState( StartTagInfo tag ) { final RELAXNGReader reader = (RELAXNGReader)this.reader; if( tag.localName.equals("except") ) return reader.getStateFactory().dataExcept(this,tag); if( tag.localName.equals("param") ) return reader.getStateFactory().dataParam(this,tag); return null; } /** type incubator object to be used to create a type. */ protected DatatypeBuilder typeBuilder; /** the name of the base type. */ protected StringPair baseTypeName; protected void startSelf() { final RELAXNGReader reader = (RELAXNGReader)this.reader; super.startSelf(); final String localName = startTag.getCollapsedAttribute("type"); if( localName==null ) { reader.reportError( RELAXNGReader.ERR_MISSING_ATTRIBUTE, "data", "type" ); } else { // create a type incubator baseTypeName = new StringPair( reader.datatypeLibURI, localName ); try { typeBuilder = reader.getCurrentDatatypeLibrary().createDatatypeBuilder(localName); } catch( DatatypeException dte ) { reader.reportError( RELAXNGReader.ERR_UNDEFINED_DATATYPE_1, localName, dte.getMessage() ); } } if( typeBuilder==null ) { // if an error is encountered, then typeIncubator field is left null. // In that case, set a dummy implementation so that the successive param // statements are happy. typeBuilder = ErrorDatatypeLibrary.theInstance; } } /** the 'except' clause. Null if nothing was specified */ protected Expression except = null; public void onEndChild( Expression child ) { final RELAXNGReader reader = (RELAXNGReader)this.reader; // this method receives the 'except' clause, if any. if( except!=null ) reader.reportError( RELAXNGReader.ERR_MULTIPLE_EXCEPT ); except = child; } protected Expression makeExpression() { final RELAXNGReader reader = (RELAXNGReader)this.reader; try { if( except==null ) except=Expression.nullSet; return reader.pool.createData( typeBuilder.createDatatype(), baseTypeName, except ); } catch( DatatypeException dte ) { reader.reportError( RELAXNGReader.ERR_INVALID_PARAMETERS, dte.getMessage() ); // recover by returning something. return Expression.nullSet; } } } msv-2009.1/msv/src/com/sun/msv/reader/trex/ng/RefState.java0000644000175000017500000000213707671170035023625 0ustar giovannigiovanni/* * @(#)$Id: RefState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex.ng; import com.sun.msv.grammar.ReferenceExp; /** * parses <ref> pattern. * * @author Kohsuke KAWAGUCHI */ public class RefState extends com.sun.msv.reader.trex.RefState { public RefState( boolean parentRef ) { super(parentRef); } /** * Performs the final wrap-up. */ protected void wrapUp( ReferenceExp r ) { super.wrapUp(r); final RELAXNGReader reader = (RELAXNGReader)this.reader; // memorize this reference as a direct reference. if( reader.currentNamedPattern!=null ) { if(reader.directRefernce) reader.currentNamedPattern.directRefs.add(r); else reader.currentNamedPattern.indirectRefs.add(r); } } } msv-2009.1/msv/src/com/sun/msv/reader/trex/ng/relaxng.rng0000644000175000017500000001553507656052224023425 0ustar giovannigiovanni choice interleave msv-2009.1/msv/src/com/sun/msv/reader/trex/ng/comp/0000755000175000017500000000000011622453066022177 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/reader/trex/ng/comp/package.html0000644000175000017500000000014207350477355024467 0ustar giovannigiovanni

      parses RELAX NG with DTD compatibility annotation into AGM.

      msv-2009.1/msv/src/com/sun/msv/reader/trex/ng/comp/CompAttributeState.java0000644000175000017500000000315007671170035026625 0ustar giovannigiovanni/* * @(#)$Id: CompAttributeState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex.ng.comp; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.Expression; import com.sun.msv.reader.trex.ng.AttributeState; /** * parses <attribute> pattern. * * @author Kohsuke KAWAGUCHI */ public class CompAttributeState extends AttributeState { protected Expression annealExpression( Expression contentModel ) { final Expression exp = super.annealExpression(contentModel); String defaultValue = startTag.getAttribute( RELAXNGCompReader.AnnotationNamespace, "defaultValue" ); if(defaultValue!=null && (exp instanceof AttributeExp)) { // if(!nameClass instanceof SimpleNameClass) // // attribute with a:defaultValue must be a simple name. // reader.reportError( // RELAXNGCompReader.ERR_NAME_IS_NOT_SIMPLE_FOR_DEFAULTEDATTRIBUTE ); // // remember that a default value is specified for this attribute. // Since AttributeExps are not unified, it is safe to use it as a key. // all checks are performed later. RELAXNGCompReader reader = (RELAXNGCompReader)this.reader; reader.addDefaultValue((AttributeExp)exp,defaultValue); } return exp; } } msv-2009.1/msv/src/com/sun/msv/reader/trex/ng/comp/Messages_ja.properties0000644000175000017500000001020707352230447026537 0ustar giovannigiovanni RELAXNGReader.Compatibility.Annotation.ChildElement = \ annotation\u8981\u7D20\u306F\u5B50\u8981\u7D20\u3092\u4E00\u5207\u3082\u3066\u307E\u305B\u3093 RELAXNGReader.Compatibility.Annotation.InvalidAttribute = \ annotation\u8981\u7D20\u306B"{0}"\u5C5E\u6027\u3092\u66F8\u304F\u3053\u3068\u306F\u51FA\u6765\u307E\u305B\u3093 RELAXNGReader.Compatibility.Annotation.Misplaced = \ "{0}"\u8981\u7D20\u306E\u5F8C\u308D\u306Bannotation\u8981\u7D20\u3092\u66F8\u304F\u3053\u3068\u306F\u51FA\u6765\u307E\u305B\u3093 RELAXNGReader.Compatibility.ID.MalplacedIDType = \ "{0}"\u578B\u306F{1}\u3068\u3057\u3066\u6A5F\u80FD\u3059\u308B\u306E\u3067\u3001attribute\u30D1\u30BF\u30FC\u30F3\u306E\u3059\u3050\u4E0B\u306B\u66F8\u304F\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059 RELAXNGReader.Compatibility.ID.IDTypeWithNonSimpleAttName = \ "{0}"\u578B\u306F{1}\u3068\u3057\u3066\u6A5F\u80FD\u3059\u308B\u306E\u3067\u3001\u305D\u306E\u89AA\u306Eattribute\u30D1\u30BF\u30FC\u30F3\u306E\u540D\u524D\u306F\u5358\u7D14\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059 RELAXNGReader.Compatibility.ID.IDTypeWithNonSimpleElementName = \ "{0}"\u578B\u306F{1}\u3068\u3057\u3066\u6A5F\u80FD\u3059\u308B\u306E\u3067\u3001\u305D\u306E\u89AA\u306Eelement\u30D1\u30BF\u30FC\u30F3\u306E\u540D\u524D\u306F\u5358\u7D14\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059 RELAXNGReader.Compatibility.ID.Competing = \ "{0}"\u5C5E\u6027\u306FID/IDREF(S)\u306E"{1}"\u578B\u3092\u6301\u3061\u307E\u3059\u304C\u3001\u7AF6\u5408\u3059\u308B\u4ED6\u306E\u5C5E\u6027\u304C\u3042\u308A\u307E\u3059 RELAXNGReader.Compatibility.ID.Competing2 = \ "{0}"\u5C5E\u6027\u306FID/IDREF(S)\u306E"{1}"\u578B\u3092\u6301\u3061\u307E\u3059\u304C\u3001\u7AF6\u5408\u3059\u308B\u4ED6\u306E\u5C5E\u6027\u306E\u578B\u304C\u7570\u306A\u308A\u307E\u3059 RELAXNGReader.Compatibility.DefaultValue.NameIsNotSimple = \ \u30C7\u30A3\u30D5\u30A9\u30EB\u30C8\u5024\u3092\u3064\u3051\u308B\u305F\u3081\u306B\u306F\u5C5E\u6027\u306E\u540D\u524D\u304C\u5358\u7D14\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059 RELAXNGReader.Compatibility.DefaultValue.Invalid = \ \u8A2D\u5B9A\u3055\u308C\u305F\u30C7\u30A3\u30D5\u30A9\u30EB\u30C8\u5024"{0}"\u306F\u3053\u306E\u5C5E\u6027\u306E\u5185\u5BB9\u30E2\u30C7\u30EB\u306B\u53D7\u7406\u3055\u308C\u307E\u305B\u3093 RELAXNGReader.Compatibility.DefaultValue.NotOptional = \ \u7701\u7565\u53EF\u80FD\u3067\u306A\u3044\u5C5E\u6027\u306B\u30C7\u30A3\u30D5\u30A9\u30EB\u30C8\u5024\u3092\u3064\u3051\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093 RELAXNGReader.Compatibility.DefaultValue.Repeatable = \ \u8907\u6570\u500B\u66F8\u3051\u308B\u5C5E\u6027\u306B\u30C7\u30A3\u30D5\u30A9\u30EB\u30C8\u5024\u3092\u3064\u3051\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093 RELAXNGReader.Compatibility.DefaultValue.ComplexElementName = \ \u5C5E\u6027\u30C7\u30A3\u30D5\u30A9\u30EB\u30C8\u5024\u3092\u3064\u3051\u308B\u305F\u3081\u306B\u306F\u89AA\u8981\u7D20\u306E\u540D\u524D\u304C\u5358\u7D14\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059 RELAXNGReader.Compatibility.DefaultValue.DifferentValues = \ "{2}"\u8981\u7D20\u306E"{3}"\u5C5E\u6027\u306E\u30C7\u30A3\u30D5\u30A9\u30EB\u30C8\u5024\u3068\u3057\u3066"{0}"\u3068"{1}"\u306E\u8907\u6570\u306E\u7570\u306A\u308B\u5024\u304C\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u307E\u3059 RELAXNGReader.Compatibility.DefaultValue.ContextDependentType = \ \u30C7\u30FC\u30BF\u578B"{0}"\u3092\u542B\u3080\u5C5E\u6027\u306B\u306F\u30C7\u30A3\u30D5\u30A9\u30EB\u30C8\u5024\u306F\u3064\u3051\u3089\u308C\u307E\u305B\u3093 RELAXNGReader.Compatibility.DefaultValue.CompetingElements = \ \u8981\u7D20\u540D"{0}"\u306B\u30DE\u30C3\u30C1\u3059\u308B\u30D1\u30BF\u30FC\u30F3\u304C\u8907\u6570\u3042\u308A\u3001\u5C5E\u6027\u30C7\u30A3\u30D5\u30A9\u30EB\u30C8\u5024\u304C\u3064\u3044\u3066\u3044\u308B\u3082\u306E\u3068\ \u3064\u3044\u3066\u3044\u306A\u3044\u3082\u306E\u304C\u3042\u308A\u307E\u3059\u3002\u8981\u7D20\u540D\u3068\u5C5E\u6027\u540D\u304B\u3089\u3001\u30C7\u30A3\u30D5\u30A9\u30EB\u30C8\u5024\u3092\u4E00\u610F\u306B\u8B58\u5225\ \u3067\u304D\u308B\u3088\u3046\u306B\u30B9\u30AD\u30FC\u30DE\u3092\u66F8\u304F\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059 msv-2009.1/msv/src/com/sun/msv/reader/trex/ng/comp/DefAttCompatibilityChecker.java0000644000175000017500000003606107671170035030237 0ustar giovannigiovannipackage com.sun.msv.reader.trex.ng.comp; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.relaxng.datatype.Datatype; import org.xml.sax.Locator; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.ChoiceExp; import com.sun.msv.grammar.DataExp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ListExp; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.OneOrMoreExp; import com.sun.msv.grammar.SimpleNameClass; import com.sun.msv.grammar.ValueExp; import com.sun.msv.grammar.util.ExpressionWalker; import com.sun.msv.grammar.util.RefExpRemover; import com.sun.msv.util.StringPair; import com.sun.msv.verifier.regexp.ResidualCalculator; import com.sun.msv.verifier.regexp.StringToken; class DefAttCompatibilityChecker extends CompatibilityChecker { DefAttCompatibilityChecker( RELAXNGCompReader _reader, Map _defaultedAttributes ) { super(_reader); this.defaultedAttributes = _defaultedAttributes; } protected void setCompatibility( boolean val ) { grammar.isDefaultAttributeValueCompatible = val; } private final Map defaultedAttributes; /** * used to abort the check. */ private static final class Abort extends RuntimeException {} private static final class DefAttMap { /** * the map from the attribute name (as StringPair) to the default value (as String). */ final Map defaultAttributes; /** * one of the ElementExps that have this particular element name. * used only for the error reporting. */ final ElementExp sampleDecl; DefAttMap( ElementExp sample, Map atts ) { this.sampleDecl=sample; this.defaultAttributes=atts; } } private final RefExpRemover refRemover = new RefExpRemover(reader.pool,false); /** * returns true if the exp is equivalent to <empty/> after * the simplification. */ private boolean isEpsilon( Expression exp ) { if(exp==Expression.epsilon) return true; return exp.visit(refRemover) == Expression.epsilon; } /** * tests the compatibility with the default attribute feature. */ public void test() { grammar.isDefaultAttributeValueCompatible = true; if( defaultedAttributes.size()==0 ) return; // no default attribute is used. no need for the check. Iterator itr = defaultedAttributes.entrySet().iterator(); ResidualCalculator resCalc = new ResidualCalculator(reader.pool); while( itr.hasNext() ) { Map.Entry item = (Map.Entry)itr.next(); AttributeExp exp = (AttributeExp)item.getKey(); String value = (String)item.getValue(); // tests if the name class is simple if(!(exp.nameClass instanceof SimpleNameClass)) reportCompError( new Locator[]{reader.getDeclaredLocationOf(exp)}, CERR_DEFVALUE_NAME_IS_NOT_SIMPLE); // tests if there is no context-dependent datatypes try { exp.exp.visit( contextDependentTypeChecker ); } catch( Abort a ) { continue; // abort further check. this error is already reported. } // tests if the default value matches the content model of this attribute StringToken token = new StringToken(resCalc,value,null,null); if(!resCalc.calcResidual( exp.exp, token ).isEpsilonReducible() ) { // the default value was rejected by the content model. reportCompError( new Locator[]{reader.getDeclaredLocationOf(exp)}, CERR_DEFVALUE_INVALID, new Object[]{value}); } } if( !grammar.isDefaultAttributeValueCompatible ) // if there already is an error, abort further check. return; // a map from element names to DefAttMap final Map name2value = new HashMap(); // a set of all ElementExps in the grammar. final Set elements = new HashSet(); // tests if defaulted attributes are optional and doesn't have // oneOrMoreAncestor. // also (element name,attribute name)->default value // map is created here. grammar.visit( new ExpressionWalker() { // in the first pass, the elements variable // is used to record visited ElementExps. // condition that has to be met for default attributes to be valid. private boolean inOneOrMore = false; private boolean inChoice = false; private boolean inOptionalChoice = false; private boolean inSimpleElement = false; /** * A map from attribute name to defaulted AttributeExps * of the current element. */ private Map currentAttributes = null; /** * name of the current ElementExp * within which we are currently processing. */ private SimpleNameClass currentElementName = null; public void onElement( ElementExp exp ) { if( !elements.add(exp) ) return; // this element is already checked. // otherwise check the content model of this element. // update the value of the isSimpleElement field. final boolean oldSE = inSimpleElement; final boolean oldOC = inOptionalChoice; final boolean oldC = inChoice; final boolean oldOOM = inOneOrMore; final SimpleNameClass prevElemName = currentElementName; final Map oldCA = currentAttributes; inSimpleElement = (exp.getNameClass() instanceof SimpleNameClass); inOptionalChoice = true; inChoice = false; inOneOrMore = false; StringPair en = null; if(inSimpleElement) { currentElementName = (SimpleNameClass)exp.getNameClass(); en = new StringPair(currentElementName); currentAttributes = new HashMap(); } else currentElementName = null; exp.contentModel.visit(this); if(en!=null) { DefAttMap m = (DefAttMap)name2value.get(en); if(m==null) name2value.put(en, new DefAttMap(exp,currentAttributes)); else { // there was another ElementExp with the same name. // we need to check that their default attribute values // are consistent. if(!m.defaultAttributes.equals(currentAttributes)) { // TODO: provide better message reportCompError( new Locator[]{ reader.getDeclaredLocationOf(m.sampleDecl), reader.getDeclaredLocationOf(exp)}, CERR_DEFVALUE_COMPETING_ELEMENTS, new Object[]{ ((SimpleNameClass)m.sampleDecl.getNameClass()).localName }); // make this element name fresh // so that the user won't see excessive error messages. name2value.remove(en); } } } inSimpleElement = oldSE; inOptionalChoice = oldOC; inChoice = oldC; inOneOrMore = oldOOM; currentElementName = prevElemName; currentAttributes = oldCA; } public void onOneOrMore( OneOrMoreExp exp ) { final boolean oldOOM = inOneOrMore; inOneOrMore = true; exp.exp.visit(this); inOneOrMore=oldOOM; } public void onChoice( ChoiceExp exp ) { final boolean oldOC = inOptionalChoice; final boolean oldC = inChoice; inChoice = true; if(!isEpsilon(exp.exp1) && !isEpsilon(exp.exp2)) inOptionalChoice = false; super.onChoice(exp); inOptionalChoice = oldOC; inChoice = oldC; } public void onAttribute( AttributeExp exp ) { if( defaultedAttributes.containsKey(exp) ) { // this attribute has a default value. if(!inOptionalChoice || !inChoice) { reportCompError( new Locator[]{reader.getDeclaredLocationOf(exp)}, CERR_DEFVALUE_NOT_OPTIONAL); return; // abort } if(inOneOrMore) { reportCompError( new Locator[]{reader.getDeclaredLocationOf(exp)}, CERR_DEFVALUE_REPEATABLE); return; // abort } if(!inSimpleElement) { reportCompError( new Locator[]{reader.getDeclaredLocationOf(exp)}, CERR_DEFVALUE_COMPLEX_ELEMENTNAME); return; // abort } String value = (String)defaultedAttributes.get(exp); String v = (String)currentAttributes.put( new StringPair((SimpleNameClass)exp.nameClass), value ); if(v!=null) { // make sure that this value and the previous value // are the same if(!v.equals(value)) reportCompError( new Locator[]{reader.getDeclaredLocationOf(exp)}, CERR_DEFVALUE_DIFFERENT_VALUES, new Object[]{v,value, currentElementName.localName, ((SimpleNameClass)exp.nameClass).localName}); } } } public void onList( ListExp exp ) { // ListExp may never contain ElementExp nor AttributeExp, // so visiting its children is nothing but a waste of time. } }); // test that the competing elements also has the same default values. itr = elements.iterator(); while(itr.hasNext()) { final ElementExp eexp = (ElementExp)itr.next(); NameClass nc = eexp.getNameClass(); if(!(nc instanceof SimpleNameClass)) { // if the element has a complex name class, // it cannot have a default attribute value. // (this is checked within the first pass. // so in this case, we just need to make sure that // any competing elements do not have defaulted attributes. Iterator jtr = name2value.entrySet().iterator(); while(jtr.hasNext()) { Map.Entry e = (Map.Entry)jtr.next(); if(nc.accepts((StringPair)e.getKey())) { // this element competes with this eexp. DefAttMap defAtts = (DefAttMap)e.getValue(); if(defAtts.defaultAttributes.size()>0) { // TODO: what should the error message be? reportCompError( new Locator[]{ reader.getDeclaredLocationOf(defAtts.sampleDecl), reader.getDeclaredLocationOf(eexp)}, CERR_DEFVALUE_COMPETING_ELEMENTS, new Object[]{ ((SimpleNameClass)defAtts.sampleDecl.getNameClass()).localName }); return; // abort the check } } } } /* else { if the element has a simple name, then all checks are done in the 1st pass. } */ } } /** * checks if the expression contains context-dependent datatypes. * If so, it reports an error and throws an Abort exception. */ private ExpressionWalker contextDependentTypeChecker = new ExpressionWalker(){ public void onData( DataExp exp ) { check(exp.dt,exp.name); } public void onValue( ValueExp exp ) { check(exp.dt,exp.name); } private void check( Datatype dt, StringPair name ) { if(dt.isContextDependent()) { reportCompError( null, CERR_DEFVALUE_CONTEXT_DEPENDENT_TYPE, new Object[]{name.localName}); throw new Abort(); } } }; public static final String CERR_DEFVALUE_NAME_IS_NOT_SIMPLE = // arg:0 "RELAXNGReader.Compatibility.DefaultValue.NameIsNotSimple"; public static final String CERR_DEFVALUE_INVALID = // arg:1 "RELAXNGReader.Compatibility.DefaultValue.Invalid"; public static final String CERR_DEFVALUE_NOT_OPTIONAL = // arg:0 "RELAXNGReader.Compatibility.DefaultValue.NotOptional"; public static final String CERR_DEFVALUE_REPEATABLE = // arg:0 "RELAXNGReader.Compatibility.DefaultValue.Repeatable"; public static final String CERR_DEFVALUE_COMPLEX_ELEMENTNAME = // arg:0 "RELAXNGReader.Compatibility.DefaultValue.ComplexElementName"; public static final String CERR_DEFVALUE_DIFFERENT_VALUES = // arg:4 "RELAXNGReader.Compatibility.DefaultValue.DifferentValues"; // public static final String CERR_DEFVALUE_POSSIBLY_UNCOMPATIBLE_TYPE = // arg:1 // "RELAXNGReader.Compatibility.DefaultValue.PossiblyUncompatibleType"; public static final String CERR_DEFVALUE_CONTEXT_DEPENDENT_TYPE = // arg:1 "RELAXNGReader.Compatibility.DefaultValue.ContextDependentType"; public static final String CERR_DEFVALUE_COMPETING_ELEMENTS = // arg:1 "RELAXNGReader.Compatibility.DefaultValue.CompetingElements"; } msv-2009.1/msv/src/com/sun/msv/reader/trex/ng/comp/CompatibilityChecker.java0000644000175000017500000000223607671170035027144 0ustar giovannigiovannipackage com.sun.msv.reader.trex.ng.comp; import org.xml.sax.Locator; import com.sun.msv.grammar.relaxng.RELAXNGGrammar; abstract class CompatibilityChecker { protected final RELAXNGCompReader reader; protected final RELAXNGGrammar grammar; protected CompatibilityChecker( RELAXNGCompReader _reader ) { this.reader = _reader; this.grammar = (RELAXNGGrammar)_reader.getGrammar(); } protected abstract void setCompatibility( boolean val ); /** * reports the compatibility related error. * *

      * Since the processor is required to validate a schema even if * it's not compatible with some of the features, we cannot report * those errors as real "errors". */ protected void reportCompError( Locator[] locs, String propertyName ) { // TODO: it maybe useful to implement a switch // that makes those warnings as errors. reportCompError(locs,propertyName,null); } protected void reportCompError( Locator[] locs, String propertyName, Object[] args ) { setCompatibility(false); reader.reportWarning(propertyName,args,locs); } } msv-2009.1/msv/src/com/sun/msv/reader/trex/ng/comp/Messages.properties0000644000175000017500000000467307352230447026077 0ustar giovannigiovanni RELAXNGReader.Compatibility.Annotation.ChildElement = \ the annotation element cannot have any child element. RELAXNGReader.Compatibility.Annotation.InvalidAttribute = \ the annotation element cannot have the "{0}" attribute. RELAXNGReader.Compatibility.Annotation.Misplaced = \ the annotation element cannot be written after the "{0}" element. RELAXNGReader.Compatibility.ID.MalplacedIDType = \ The "{0}" type has {1} semantics and therefore it must be placed \ directly under an attribute pattern. RELAXNGReader.Compatibility.ID.IDTypeWithNonSimpleAttName = \ The "{0}" type has {1} semantics and therefore its parent attribute pattern \ must have a simple name. RELAXNGReader.Compatibility.ID.IDTypeWithNonSimpleElementName = \ The "{0}" type has {1} semantics and therefore the enclosing element pattern \ must have a simple name. RELAXNGReader.Compatibility.ID.Competing = \ The "{0}" type has {1} semantics but a competing attribute of another element \ doesn't have the same type. RELAXNGReader.Compatibility.ID.Competing2 = \ The "{1}" type of the "{0}" attribute has ID semantics but a competing attribute \ doesn't have the same type. RELAXNGReader.Compatibility.DefaultValue.NameIsNotSimple = \ For an attribute to have a default value, its name must be simple. RELAXNGReader.Compatibility.DefaultValue.Invalid = \ The specified default value "{0}" does not match the content model of the attribute. RELAXNGReader.Compatibility.DefaultValue.NotOptional = \ For an attribute to have a default value, it must be optional. RELAXNGReader.Compatibility.DefaultValue.Repeatable = \ For an attribute to have a default value, it cannot be enclosed by nor . RELAXNGReader.Compatibility.DefaultValue.ComplexElementName = \ For an attribute to have a default value, the name of its parent element must be simple. RELAXNGReader.Compatibility.DefaultValue.DifferentValues = \ The "{3}" attribute of the "{2}" element has two different default values ("{0}" and "{1}"). RELAXNGReader.Compatibility.DefaultValue.ContextDependentType = \ An attribute with a default value cannot contain the "{0}" datatype. RELAXNGReader.Compatibility.DefaultValue.CompetingElements = \ There are more than one patterns that can match the "{0}" element, and some of them \ have attribute default values and some of them don't. For the schema to be compatible, \ there must be a functional mapping from element and attribute names to default values. msv-2009.1/msv/src/com/sun/msv/reader/trex/ng/comp/IDCompatibilityChecker.java0000644000175000017500000003006307671170035027360 0ustar giovannigiovannipackage com.sun.msv.reader.trex.ng.comp; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Vector; import org.relaxng.datatype.Datatype; import org.xml.sax.Locator; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.DataExp; import com.sun.msv.grammar.DataOrValueExp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.ListExp; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.SimpleNameClass; import com.sun.msv.grammar.ValueExp; import com.sun.msv.grammar.util.ExpressionWalker; import com.sun.msv.grammar.util.RefExpRemover; import com.sun.msv.util.StringPair; /** * checks the compatibility of RELAX NG grammar with the ID/IDREF feature. */ class IDCompatibilityChecker extends CompatibilityChecker { IDCompatibilityChecker( RELAXNGCompReader reader ) { super(reader); } protected void setCompatibility( boolean val ) { grammar.isIDcompatible = val; } private static class IDAttMap { final ElementExp sampleDecl; final Map idatts = new java.util.HashMap(); IDAttMap( ElementExp e ) { this.sampleDecl=e; } } public void test( ) { grammar.isIDcompatible = true; // a map from element names(StringPair) to DefAttMap final Map name2value = new HashMap(); // a set of all ElementExps in the grammar. final Set elements = new HashSet(); final RefExpRemover remover = new RefExpRemover(reader.pool,false); /* The first pass -------------- create a "(element name,attribute name)->Id datatype name" map. Also detects invalid use of datatypes. */ reader.getGrammar().visit( new ExpressionWalker(){ /** current element name. Only available when in a simple-name element */ private StringPair elementName=null; /** current element. */ private ElementExp curElm=null; private IDAttMap curAtts = null; public void onElement( ElementExp exp ) { if(!elements.add(exp)) return; // this element has already processed. StringPair _en = elementName; IDAttMap _curAtts = curAtts; ElementExp _curElm = curElm; NameClass nc = exp.getNameClass(); if(nc instanceof SimpleNameClass) { elementName = new StringPair((SimpleNameClass)nc); curAtts = (IDAttMap)name2value.get(elementName); // maybe null. } else elementName = null; curElm = exp; // System.out.println("tested:" + // com.sun.msv.grammar.util.ExpressionPrinter.printContentModel( // exp.contentModel.visit(remover))); // visit the content model, but remove reference exps first. exp.contentModel.visit(remover).visit(this); if( elementName!=null && curAtts!=null ) name2value.put(elementName,curAtts); elementName = _en; curAtts = _curAtts; curElm = _curElm; } public void onAttribute( AttributeExp exp ) { if(!(exp.exp instanceof DataOrValueExp)) { // otherwise visit the content model normally // so that we can find any invalid use of ID/IDREF types. exp.exp.visit(this); return; } DataOrValueExp texp = (DataOrValueExp)exp.exp; if(texp.getType().getIdType()==Datatype.ID_TYPE_NULL) { // if this type is not ID/IDREF type, then it's OK return; } if(!(exp.nameClass instanceof SimpleNameClass)) { reportCompError( new Locator[]{reader.getDeclaredLocationOf(exp)}, CERR_ID_TYPE_WITH_NON_SIMPLE_ATTNAME, new Object[]{ texp.getName().localName, getSemanticsStr(texp.getType().getIdType())} ); return; } StringPair attName = new StringPair((SimpleNameClass)exp.nameClass); if( elementName==null ) { reportCompError( new Locator[]{ reader.getDeclaredLocationOf(exp), reader.getDeclaredLocationOf(curElm)}, CERR_ID_TYPE_WITH_NON_SIMPLE_ELEMENTNAME, new Object[]{ texp.getName().localName, getSemanticsStr(texp.getType().getIdType())} ); return; } // the enclosing attribute name is simple, and // the enclosing element name is simple, too. // this is the only place we can have ID/IDREF types. // store that this attribute is used for ID/IDREF. if(curAtts==null) curAtts = new IDAttMap(curElm); curAtts.idatts.put(attName,texp.getName()); } public void onData( DataExp exp ) { checkIdType(exp); } public void onValue( ValueExp exp ) { checkIdType(exp); } private void checkIdType( DataOrValueExp exp ) { if(exp.getType().getIdType()!=Datatype.ID_TYPE_NULL) { // ID/IDREF type in all other locations are subject to // a compatibility error. reportCompError( new Locator[]{reader.getDeclaredLocationOf(exp)}, CERR_MALPLACED_ID_TYPE, new Object[]{ exp.getName().localName, getSemanticsStr(exp.getType().getIdType())}); } } }); if(!grammar.isIDcompatible) // if an compatibility error has been found, abort further check. return; /* 2nd pass ======== make sure that no other attributes are competing with id attributes. */ Iterator itr = elements.iterator(); final Vector vec = new Vector(); // IDAttMaps of the competing elements while( itr.hasNext() ) { final ElementExp eexp = (ElementExp)itr.next(); // list up all competing elements. vec.clear(); Iterator jtr = name2value.entrySet().iterator(); while(jtr.hasNext()) { Map.Entry e = (Map.Entry)jtr.next(); if( eexp.getNameClass().accepts((StringPair)e.getKey()) ) vec.add( e.getValue()/*IDAttMap*/ ); } if(vec.size()==0) continue; // this element does not comete with anything. // no need to check // make sure that no attributes are actually competing. eexp.contentModel.visit(remover).visit( new ExpressionWalker() { public void onElement( ElementExp exp ) { return; // do not recurse child elements. } public void onAttribute( AttributeExp exp ) { if(exp.exp instanceof DataOrValueExp) { DataOrValueExp texp = (DataOrValueExp)exp.exp; if(texp.getType().getIdType()!=Datatype.ID_TYPE_NULL) { // if the schema is OK with the 1st pass check // and if this element contains the ID type, then // this element must be simple-named. // so at most one IDAttMap can match it. _assert(vec.size()==1); // by the same assumption, the attribute name must be // simple. SimpleNameClass attName = (SimpleNameClass)exp.nameClass; IDAttMap iam = (IDAttMap)vec.get(0); if(!texp.getName().equals(iam.idatts.get(new StringPair(attName)))) reportCompError( new Locator[]{ reader.getDeclaredLocationOf(exp), reader.getDeclaredLocationOf(iam.sampleDecl)}, CERR_COMPETING, new Object[]{ texp.getName().localName, getSemanticsStr(texp.getType().getIdType()) } ); return; } } // otherwise, make sure that this attribute name doesn't // compete with ID. for( int i=vec.size()-1; i>=0; i-- ) { IDAttMap iam = (IDAttMap)vec.get(i); Iterator jtr = iam.idatts.entrySet().iterator(); while( jtr.hasNext() ) { Map.Entry e = (Map.Entry)jtr.next(); if(exp.nameClass.accepts( (StringPair)e.getKey() )) { // competing attributes reportCompError( new Locator[]{ reader.getDeclaredLocationOf(exp), reader.getDeclaredLocationOf(eexp), reader.getDeclaredLocationOf(iam.sampleDecl)}, CERR_COMPETING2, new Object[]{ ((StringPair)e.getKey()).localName, ((StringPair)e.getValue()).localName}); return; } } } } public void onList( ListExp exp ) { // since there can be no AttributeExp within a list, // there is no need to visit its children. } }); } } private static String getSemanticsStr( int type ) { switch(type) { case Datatype.ID_TYPE_ID: return "ID"; case Datatype.ID_TYPE_IDREF: return "IDREF"; case Datatype.ID_TYPE_IDREFS: return "IDREFS"; default: throw new Error(); } } private static final void _assert( boolean b ) { if(!b) throw new Error("assertion failed"); } private static final String CERR_MALPLACED_ID_TYPE = // arg:2 "RELAXNGReader.Compatibility.ID.MalplacedIDType"; private static final String CERR_ID_TYPE_WITH_NON_SIMPLE_ATTNAME = // arg:2 "RELAXNGReader.Compatibility.ID.IDTypeWithNonSimpleAttName"; private static final String CERR_ID_TYPE_WITH_NON_SIMPLE_ELEMENTNAME = // arg:2 "RELAXNGReader.Compatibility.ID.IDTypeWithNonSimpleElementName"; private static final String CERR_COMPETING = // arg:2 "RELAXNGReader.Compatibility.ID.Competing"; private static final String CERR_COMPETING2 = // arg:0 "RELAXNGReader.Compatibility.ID.Competing2"; } msv-2009.1/msv/src/com/sun/msv/reader/trex/ng/comp/RELAXNGCompReader.java0000644000175000017500000002156611156747174026126 0ustar giovannigiovanni/* * @(#)$Id: RELAXNGCompReader.java 1744 2009-03-14 15:34:20Z bimargulies $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex.ng.comp; import java.text.MessageFormat; import java.util.Map; import java.util.ResourceBundle; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.relaxng.RELAXNGGrammar; import com.sun.msv.grammar.trex.TREXGrammar; import com.sun.msv.reader.GrammarReaderController; import com.sun.msv.reader.State; import com.sun.msv.reader.trex.ng.RELAXNGReader; import com.sun.msv.util.LightStack; import com.sun.msv.util.StartTagInfo; /** * reads RELAX NG grammar with DTD compatibility annotation * and constructs abstract grammar model. * * @author Kohsuke KAWAGUCHI */ public class RELAXNGCompReader extends RELAXNGReader { /** loads RELAX NG pattern. * * @return * it always returns {@link RELAXNGGrammar}, but due to the * restriction imposed by Java language, I cannot change the * signature of this method. */ public static TREXGrammar parse( String grammarURL, GrammarReaderController controller ) { RELAXNGCompReader reader = new RELAXNGCompReader(controller); reader.parse(grammarURL); return reader.getResult(); } /** loads RELAX NG pattern. * * @return * it always returns {@link RELAXNGGrammar}, but due to the * restriction imposed by Java language, I cannot change the * signature of this method. */ public static TREXGrammar parse( InputSource grammar, GrammarReaderController controller ) { RELAXNGCompReader reader = new RELAXNGCompReader(controller); reader.parse(grammar); return reader.getResult(); } /** easy-to-use constructor. */ public RELAXNGCompReader( GrammarReaderController controller ) { this(controller,createParserFactory(),new ExpressionPool()); } /** easy-to-use constructor. */ public RELAXNGCompReader( GrammarReaderController controller, SAXParserFactory parserFactory, ExpressionPool pool ) { this(controller,parserFactory,new StateFactory(),pool); } /** full constructor */ public RELAXNGCompReader( GrammarReaderController controller, SAXParserFactory parserFactory, StateFactory stateFactory, ExpressionPool pool ) { super( controller, parserFactory, stateFactory, pool ); lastRNGElement.push(null); } private final Map defaultedAttributes = new java.util.HashMap(); /** * note that the specified expression is marked with the default value. * this method is called when a:defaultValue is found. */ protected final void addDefaultValue( AttributeExp exp, String value ) { // record the location where this attribute is declared. setDeclaredLocationOf(exp); if(defaultedAttributes.put(exp,value)!=null) throw new Error(); // it is not possible for one AttributeExp to be processed twice. } protected TREXGrammar getGrammar() { return grammar; } protected String localizeMessage( String propertyName, Object[] args ) { String format; try { format = ResourceBundle.getBundle("com.sun.msv.reader.trex.ng.comp.Messages").getString(propertyName); } catch( Exception e ) { return super.localizeMessage(propertyName,args); } return MessageFormat.format(format, args ); } /** Namespace URI of RELAX NG DTD compatibility annotation */ public static final String AnnotationNamespace = "http://relaxng.org/ns/compatibility/annotations/1.0"; /** * creates various State object, which in turn parses grammar. * parsing behavior can be customized by implementing custom StateFactory. */ public static class StateFactory extends RELAXNGReader.StateFactory { public State attribute ( State parent, StartTagInfo tag ) { return new CompAttributeState(); } public TREXGrammar createGrammar( ExpressionPool pool, TREXGrammar parent ) { return new RELAXNGGrammar(pool,parent); } } // protected StateFactory getStateFactory() { // return (StateFactory)super.sfactory; // } public void wrapUp() { super.wrapUp(); if(!controller.hadError()) { // do not check the compatibilities if some errors // are already reported. new DefAttCompatibilityChecker(this,defaultedAttributes).test(); new IDCompatibilityChecker(this).test(); } } /** * pair of an element name and an attribute name. */ /* private final static class ElemAttrNamePair { public final StringPair element; public final StringPair attribute; public int hashCode() { return element.hashCode()^attribute.hashCode(); } public boolean equals( Object o ) { if(!(o instanceof ElemAttrNamePair)) return false; ElemAttrNamePair rhs = (ElemAttrNamePair)o; return element.equals(rhs.element) && attribute.equals(rhs.attribute); } public ElemAttrNamePair( StringPair e, StringPair a ) { element=e; attribute=a; } public ElemAttrNamePair( String e_uri, String e_local, String a_uri, String a_local ) { this( new StringPair(e_uri,e_local), new StringPair(a_uri,a_local) ); } public ElemAttrNamePair( SimpleNameClass e, SimpleNameClass a ) { this( e.namespaceURI, e.localName, a.namespaceURI, a.localName ); } } */ /** * The local name of the preceding RELAX NG element sibling. */ private final LightStack lastRNGElement = new LightStack(); private boolean inAnnotation = false; public void startElement( String uri, String local, String qname, Attributes atts ) throws SAXException { super.startElement(uri,local,qname,atts); if(inAnnotation) { // we found a child element for a:annotation. // this is not OK. reportWarning( CERR_ANN_CHILD_ELEMENT, null, new Locator[]{getLocator()} ); ((RELAXNGGrammar)grammar).isAnnotationCompatible = false; } if(uri.equals(AnnotationNamespace) && local.equals("annotation")) { // check the compatibility with the annotation feature. for( int i=0; iKohsuke KAWAGUCHI */ public class GrammarState extends com.sun.msv.reader.trex.GrammarState { protected void startSelf() { super.startSelf(); final RELAXNGReader reader = (RELAXNGReader)this.reader; // memorize this reference as a direct reference. if( reader.currentNamedPattern!=null ) { if(reader.directRefernce) reader.currentNamedPattern.directRefs.add(newGrammar); else reader.currentNamedPattern.indirectRefs.add(newGrammar); } } } msv-2009.1/msv/src/com/sun/msv/reader/trex/ng/RestrictionChecker.java0000644000175000017500000005331310034315204025666 0ustar giovannigiovanni/* * @(#)$Id: RestrictionChecker.java 1634 2004-04-05 17:42:28Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex.ng; import org.xml.sax.Locator; import com.sun.msv.grammar.AnyNameClass; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.ChoiceExp; import com.sun.msv.grammar.ChoiceNameClass; import com.sun.msv.grammar.DataExp; import com.sun.msv.grammar.DifferenceNameClass; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.InterleaveExp; import com.sun.msv.grammar.ListExp; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.NameClassAndExpression; import com.sun.msv.grammar.NameClassVisitor; import com.sun.msv.grammar.NamespaceNameClass; import com.sun.msv.grammar.NotNameClass; import com.sun.msv.grammar.OneOrMoreExp; import com.sun.msv.grammar.SequenceExp; import com.sun.msv.grammar.SimpleNameClass; import com.sun.msv.grammar.ValueExp; import com.sun.msv.grammar.util.ExpressionWalker; import com.sun.msv.grammar.util.NameClassCollisionChecker; /** * Checks RELAX NG contextual restrictions defined in the section 7. * *

      * ExpressionWalker is used to walk the content model thoroughly. * Depending on the current context, different walkers are used so that * we can detect contextual restrictions properly. * *

      * For each ElementExp and AttributeExp, its name class is checked to detect * the constraint set out in the section 7.1.6. Also, a set is used to avoid * redundant checks. * * * @author Kohsuke KAWAGUCHI */ public class RestrictionChecker { public RestrictionChecker( RELAXNGReader _reader ) { this.reader = _reader; } /** * Traverses the grammar and performs the contextual check. */ public void check() { reader.getGrammar().visit(inStart); } /** Reader object to which errors are reported. */ private final RELAXNGReader reader; /** * The source location of this expression should be also reported in case of error. */ private Expression errorContext; private void reportError( Expression exp, String errorMsg ) { reportError(exp,errorMsg,null); } private void reportError( Expression exp, String errorMsg, Object[] args ) { reader.reportError( new Locator[]{ reader.getDeclaredLocationOf(exp), reader.getDeclaredLocationOf(errorContext) }, errorMsg, args ); } /** Visited ElementExp/AttributeExps. */ private final java.util.Set visitedExps = new java.util.HashSet(); /** Object that checks duplicate attributes in a content model. */ private DuplicateAttributesChecker attDupChecker; /** Object that checks conflicting elements in interleave. */ private DuplicateElementsChecker elemDupChecker; /* content model checker ===================== */ /** * The base class of all other context-specific checker. * This class performs the context switching. */ private class DefaultChecker extends ExpressionWalker { public void onElement( ElementExp exp ) { if( !visitedExps.add(exp) ) return; // check conflicting elements if(elemDupChecker!=null) elemDupChecker.add(exp); // push context element, final Expression oldContext = errorContext; final DuplicateAttributesChecker oldADC = attDupChecker; final DuplicateElementsChecker oldEDC = elemDupChecker; errorContext = exp; attDupChecker = new DuplicateAttributesChecker(); elemDupChecker = new DuplicateElementsChecker(); // it is important to use the expanded exp because // section 7 has to be applied after patterns are expanded. exp.contentModel.getExpandedExp(reader.pool).visit(inElement); errorContext = oldContext; attDupChecker = oldADC; elemDupChecker = oldEDC; } public void onAttribute( AttributeExp exp ) { if( !visitedExps.add(exp) ) return; // check duplicate attributes attDupChecker.add(exp); // check infinite name checkAttributeInfiniteName(exp); final Expression oldContext = errorContext; errorContext = exp; exp.exp.getExpandedExp(reader.pool).visit(inAttribute); errorContext = oldContext; } protected void checkAttributeInfiniteName( final AttributeExp exp ) { exp.nameClass.visit( new NameClassVisitor() { public Object onAnyName( AnyNameClass nc ) { return error(); } public Object onSimple( SimpleNameClass nc ) { return null; } public Object onNsName( NamespaceNameClass nc ) { return error(); } public Object onNot( NotNameClass nc ) { throw new Error(); } // should not be used public Object onDifference( DifferenceNameClass nc ) { nc.nc1.visit(this); nc.nc2.visit(this); return null; } public Object onChoice( ChoiceNameClass nc ) { nc.nc1.visit(this); nc.nc2.visit(this); return null; } private Object error() { reportError(exp, RELAXNGReader.ERR_NAKED_INFINITE_ATTRIBUTE_NAMECLASS ); return null; } }); } public void onList( ListExp exp ) { exp.exp.visit(inList); } public void onData( DataExp exp ) { exp.except.visit(inExcept); } public void onChoice( ChoiceExp exp ) { if(attDupChecker==null) // if a 'choice' appears at the top level, // there is no enclosing element, so no attDupChecker is present. super.onChoice(exp); else { int idx = attDupChecker.start(); exp.exp1.visit(this); attDupChecker.endLeftBranch(idx); exp.exp2.visit(this); attDupChecker.endRightBranch(); } } public void onInterleave( InterleaveExp exp ) { if(elemDupChecker==null) super.onInterleave(exp); else { int idx = elemDupChecker.start(); exp.exp1.visit(this); elemDupChecker.endLeftBranch(idx); exp.exp2.visit(this); elemDupChecker.endRightBranch(); } } public void onAnyString() { super.onAnyString(); } } /** * Used to visit children of the 'except' clause of data. */ private final ExpressionWalker inExcept = new DefaultChecker() { public void onAttribute( AttributeExp exp ) { reportError( exp, ERR_ATTRIBUTE_IN_EXCEPT ); } public void onElement( ElementExp exp ) { reportError( exp, ERR_ELEMENT_IN_EXCEPT ); } public void onList( ListExp exp ) { reportError( exp, ERR_LIST_IN_EXCEPT ); } public void onAnyString() { reportError( null, ERR_TEXT_IN_EXCEPT ); } public void onEpsilon() { reportError( null, ERR_EMPTY_IN_EXCEPT ); } public void onSequence( SequenceExp exp ) { reportError( exp, ERR_SEQUENCE_IN_EXCEPT ); } public void onInterleave( InterleaveExp exp ) { reportError( exp, ERR_INTERLEAVE_IN_EXCEPT ); } public void onOneOrMore( OneOrMoreExp exp ) { reportError( exp, ERR_ONEORMORE_IN_EXCEPT ); } }; /** * Used to visit children of group/interleave in oneOrMore in elements. */ private final ExpressionWalker inGroupInOneOrMoreInElement = new DefaultChecker() { public void onAttribute( AttributeExp exp ) { reportError( exp, ERR_REPEATED_GROUPED_ATTRIBUTE ); } }; /** * Used to visit children of oneOrMore in elements. */ private final ExpressionWalker inOneOrMoreInElement = new DefaultChecker() { public void onSequence( SequenceExp exp ) { exp.visit(inGroupInOneOrMoreInElement); } public void onInterleave( InterleaveExp exp ) { exp.visit(inGroupInOneOrMoreInElement); } protected void checkAttributeInfiniteName( AttributeExp exp ) { // attribute name class whose size is infinite // is allowed inside oneOrMore. } }; /** * Used to visit children of elements. */ private final ExpressionWalker inElement = new DefaultChecker() { public void onOneOrMore( OneOrMoreExp exp ) { exp.exp.visit(inOneOrMoreInElement); } }; /** * Used to visit children of attributes. */ private final ExpressionWalker inAttribute = new DefaultChecker(){ public void onElement( ElementExp exp ) { reportError( exp, ERR_ELEMENT_IN_ATTRIBUTE ); } public void onAttribute( AttributeExp exp ) { reportError( exp, ERR_ATTRIBUTE_IN_ATTRIBUTE ); } }; private class ListChecker extends DefaultChecker { public void onAttribute( AttributeExp exp ) { reportError( exp, ERR_ATTRIBUTE_IN_LIST ); } public void onElement( ElementExp exp ) { reportError( exp, ERR_ELEMENT_IN_LIST ); } public void onList( ListExp exp ) { reportError( exp, ERR_LIST_IN_LIST ); } public void onAnyString() { reportError( null, ERR_TEXT_IN_LIST ); } } /** * Used to visit children of interleaves in lists. */ private final ExpressionWalker inInterleaveInList = new ListChecker() { public void onData( DataExp exp ) { reportError( exp, ERR_DATA_IN_INTERLEAVE_IN_LIST ); } public void onValue( ValueExp exp ) { reportError( exp, ERR_VALUE_IN_INTERLEAVE_IN_LIST ); } }; /** * Used to visit children of lists. */ private final ExpressionWalker inList = new ListChecker() { public void onInterleave( InterleaveExp exp ) { inInterleaveInList.onInterleave(exp); } }; /** * Used to visit the start pattern. */ private final ExpressionWalker inStart = new DefaultChecker() { public void onAttribute( AttributeExp exp ) { reportError( exp, ERR_ATTRIBUTE_IN_START ); } public void onList( ListExp exp ) { reportError( exp, ERR_LIST_IN_START ); } public void onAnyString() { reportError( null, ERR_TEXT_IN_START ); } public void onEpsilon() { reportError( null, ERR_EMPTY_IN_START ); } public void onSequence( SequenceExp exp ) { reportError( exp, ERR_SEQUENCE_IN_START ); } public void onInterleave( InterleaveExp exp ) { reportError( exp, ERR_INTERLEAVE_IN_START ); } public void onData( DataExp exp ) { reportError( exp, ERR_DATA_IN_START ); } public void onValue( ValueExp exp ) { reportError( exp, ERR_DATA_IN_START ); } public void onOneOrMore( OneOrMoreExp exp ) { reportError( exp, ERR_ONEORMORE_IN_START ); } }; /* name class checker ================== */ class NameClassWalker implements NameClassVisitor { public Object onAnyName( AnyNameClass nc ) { return null; } public Object onSimple( SimpleNameClass nc ) { return null; } public Object onNsName( NamespaceNameClass nc ) { return null; } public Object onNot( NotNameClass nc ) { throw new Error(); } // should not be used public Object onDifference( DifferenceNameClass nc ) { nc.nc1.visit(this); if(nc.nc1 instanceof AnyNameClass) nc.nc2.visit(inAnyNameClass); else if(nc.nc1 instanceof NamespaceNameClass) nc.nc2.visit(inNsNameClass); else throw new Error(); // this is not possible in RELAX NG. return null; } public Object onChoice( ChoiceNameClass nc ) { nc.nc1.visit(this); nc.nc2.visit(this); return null; } } /** * Checks the contextual restriction on a name class. * *

      * If an error is found, it is reported through GrammarReader. */ public void checkNameClass( NameClass nc ) { nc.visit(inNameClass); } /** * Used to visit name classes. */ private final NameClassWalker inNameClass = new NameClassWalker(); /** * Used to visit children of AnyNameClass */ private final NameClassVisitor inAnyNameClass = new NameClassWalker(){ public Object onAnyName( AnyNameClass nc ) { reportError(null,ERR_ANYNAME_IN_ANYNAME); return null; } }; /** * Used to visit children of NamespaceNameClass */ private final NameClassVisitor inNsNameClass = new NameClassWalker(){ public Object onAnyName( AnyNameClass nc ) { reportError(null,ERR_ANYNAME_IN_NSNAME); return null; } public Object onNsName( NamespaceNameClass nc ) { reportError(null,ERR_NSNAME_IN_NSNAME); return null; } }; /* duplicate attributes check ========================== */ protected abstract class DuplicateNameChecker { /** ElementExps will be added into this array. */ protected NameClassAndExpression[] exps = new NameClassAndExpression[16]; /** Number of items in the atts array. */ protected int expsLen=0; /** * areas. * *

      * An area is a range of index designated by the start and end. * * Areas are stored as: *

      { start, end, start, end, ... }
      * *

      * The start method gives the index. The endLeftBranch method creates * an area by using the start index given by the start method. * The endRightBranch method will remove the area. * *

      * When testing duplicate attributes, areas are created by ChoiceExp * and used to exclude test candidates (as two attributes can share the * same name if they are in different branches of choice.) * *

      * When testing duplicate elements, areas are created by InterleaveExp * and used to include test candidates (as two elements cannot share * the same name if they are in different branches of interleave.) */ protected int[] areas = new int[8]; protected int areaLen=0; /** * Adds newly found element or attribute. */ public void add( NameClassAndExpression exp ) { check(exp); // perform duplication check // add it to the array if(exps.length==expsLen) { // expand buffer NameClassAndExpression[] n = new NameClassAndExpression[expsLen*2]; System.arraycopy(exps,0,n,0,expsLen); exps = n; } exps[expsLen++] = exp; } /** * tests a given exp against existing expressions (which are stored in * the exps field.) */ protected abstract void check( NameClassAndExpression exp ); public int start() { return expsLen; } public void endLeftBranch( int start ) { if( areas.length==areaLen ) { // expand buffer int[] n = new int[areaLen*2]; System.arraycopy(areas,0,n,0,areaLen); areas = n; } // create an area areas[areaLen++] = start; areas[areaLen++] = expsLen; } public void endRightBranch() { // remove an area areaLen-=2; } /** * Name class checker object. One object is reused throughout the test. */ private final NameClassCollisionChecker checker = new NameClassCollisionChecker(); /** Tests two name classes to see if they collide. */ protected void check( NameClassAndExpression newExp, NameClassAndExpression oldExp ) { if(checker.check( newExp.getNameClass(), oldExp.getNameClass() )) { // two attributes/elements collide NameClass intersection = NameClass.intersection( newExp.getNameClass(), oldExp.getNameClass() ); reader.reportError( new Locator[]{ reader.getDeclaredLocationOf(errorContext), // the parent element reader.getDeclaredLocationOf(newExp), reader.getDeclaredLocationOf(oldExp)}, getErrorMessage(), new Object[]{intersection.toString()} ); } } /** Gets the error message resource name. */ protected abstract String getErrorMessage(); } private class DuplicateElementsChecker extends DuplicateNameChecker { protected void check( NameClassAndExpression exp ) { // check this element with elements in the area for( int i=0; iKohsuke KAWAGUCHI */ public class ValueState extends ExpressionWithoutChildState { protected final StringBuffer text = new StringBuffer(); public void characters( char[] buf, int from, int len ) { text.append(buf,from,len); } public void ignorableWhitespace( char[] buf, int from, int len ) { text.append(buf,from,len); } protected Expression makeExpression() { final RELAXNGReader reader = (RELAXNGReader)this.reader; String typeName = startTag.getCollapsedAttribute("type"); Datatype type; StringPair typeFullName; if(typeName==null) { try { // defaults to built-in token type. type = reader.resolveDataTypeLibrary("").createDatatype("token"); typeFullName = new StringPair("","token"); } catch( DatatypeException e ) { // since token is the built-in datatype, // this can't happen e.printStackTrace(); throw new InternalError(); } } else { type = reader.resolveDataType(typeName); typeFullName = new StringPair(reader.datatypeLibURI,typeName); } Object value = type.createValue(text.toString(),reader); if( value==null ) { // this is not a good value for this type. reader.reportError( RELAXNGReader.ERR_BAD_DATA_VALUE, typeName, text.toString().trim() ); return Expression.nullSet; // recover by returning something. } return reader.pool.createValue( type, typeFullName, value ); } } msv-2009.1/msv/src/com/sun/msv/reader/trex/ng/DataParamState.java0000644000175000017500000000265007671170035024743 0ustar giovannigiovanni/* * @(#)$Id: DataParamState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex.ng; import org.relaxng.datatype.DatatypeException; import com.sun.msv.reader.ChildlessState; /** * parses <param> element inside <data> element. * * @author Kohsuke KAWAGUCHI */ public class DataParamState extends ChildlessState { protected final StringBuffer text = new StringBuffer(); public void characters( char[] buf, int from, int len ) { text.append(buf,from,len); } public void ignorableWhitespace( char[] buf, int from, int len ) { text.append(buf,from,len); } protected void endSelf() { final String facet = startTag.getAttribute("name"); if(facet==null) reader.reportError( RELAXNGReader.ERR_MISSING_ATTRIBUTE, startTag.qName, "name" ); else { try { ((DataState)parentState).typeBuilder.addParameter( facet, text.toString(), reader ); } catch( DatatypeException dte ) { reader.reportError( RELAXNGReader.ERR_BAD_FACET, facet, dte.getMessage() ); } } super.endSelf(); } } msv-2009.1/msv/src/com/sun/msv/reader/trex/ng/Messages.properties0000644000175000017500000000673507401037066025137 0ustar giovannigiovanni TREXGrammarReader.InterleavedAnyString = \ cannot contain in more than one branch RELAXNGReader.BadFacet =\ cannot set parameter {0} to this datatype: {1} RELAXNGReader.InvalidParameters =\ invalid parameter setting: {0} RELAXNGReader.BadDataValue =\ invalid value for the type "{0}": {1} RELAXNGReader.UndefinedKey =\ reference to the undefined key "{0}" RELAXNGReader.UndefinedDataType1 =\ datatype "{0}" is not defined: {1} RELAXNGReader.InconsistentKeyType =\ types of all keys/keyrefs "{0}" must be the same RELAXNGReader.InconsistentCombine =\ different combine methods are used for the same pattern "{0}" RELAXNGReader.RedefiningUndefined =\ pattern "{0}" is redefined but it is not defined in the included file. RELAXNGReader.UnknownDatatypeVocabulary1 =\ "{0}" is not a recognized data type vocabulary: {1} RELAXNGReader.MultipleExcept =\ only one is allowed RELAXNGReader.NotAbsoluteURI = \ "{0}" is not an absolute URI RELAXNGReader.AttributeInExcept = \ cannot contain RELAXNGReader.ElementInExcept = \ cannot contain RELAXNGReader.ListInExcept = \ cannot contain RELAXNGReader.TextInExcept = \ cannot contain RELAXNGReader.EmptyInExcept = \ cannot contain RELAXNGReader.SequenceInExcept = \ cannot contain RELAXNGReader.InterleaveInExcept = \ cannot contain RELAXNGReader.OneOrMoreInExcept = \ cannot contain / RELAXNGReader.RepeatedGroupedAttribute = \ is grouped and that group is repeated RELAXNGReader.ElementInAttribute = \ cannot contain RELAXNGReader.AttributeInAttribute = \ cannot contain RELAXNGReader.AttributeInList = \ cannot contain RELAXNGReader.ElementInList = \ cannot contain RELAXNGReader.ListInList = \ cannot contain RELAXNGReader.TextInList = \ cannot contain . Use . RELAXNGReader.AttributeInStart = \ cannot contain RELAXNGReader.ListInStart = \ cannot contain RELAXNGReader.TextInStart = \ cannot contain RELAXNGReader.EmptyInStart = \ cannot contain RELAXNGReader.SequenceInStart = \ cannot contain RELAXNGReader.InterleaveInStart = \ cannot contain RELAXNGReader.DataInStart = \ cannot contain RELAXNGReader.OneOrMoreInStart = \ cannot contain / RELAXNGReader.DataInInterleaveInList = \ is not allowed inside inside RELAXNGReader.ValueInInterleaveInList = \ is not allowed inside inside RELAXNGReader.AnyNameInAnyName = \ cannot contain RELAXNGReader.AnyNameInNsName = \ cannot contain RELAXNGReader.NsNameInNsName = \ cannot contain RELAXNGReader.DuplicateAttributes = \ more than one attribute accepts the same name "{0}" RELAXNGReader.DuplicateElements = \ more than one branch of accepts the element "{0}" RELAXNGReader.InfosetUriAttribute = \ Namespace URI "http://www.w3.org/2000/xmlns" is reserved and cannot be used RELAXNGReader.XmlnsAttribute = \ Attribute cannot have "xmlns" as its name RELAXNGReader.NakedInfiniteAttributeNameClass = \ Attribute with / must be wrapped by /msv-2009.1/msv/src/com/sun/msv/reader/trex/ng/AttributeState.java0000644000175000017500000000446007671170035025055 0ustar giovannigiovanni/* * @(#)$Id: AttributeState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex.ng; import com.sun.msv.grammar.AnyNameClass; import com.sun.msv.grammar.ChoiceNameClass; import com.sun.msv.grammar.DifferenceNameClass; import com.sun.msv.grammar.NameClassVisitor; import com.sun.msv.grammar.NamespaceNameClass; import com.sun.msv.grammar.NotNameClass; import com.sun.msv.grammar.SimpleNameClass; /** * parses <attribute> pattern. * * @author Kohsuke KAWAGUCHI */ public class AttributeState extends com.sun.msv.reader.trex.AttributeState { private static final String infosetURI = "http://www.w3.org/2000/xmlns"; protected void endSelf() { super.endSelf(); final RELAXNGReader reader = (RELAXNGReader)this.reader; reader.restrictionChecker.checkNameClass(nameClass); nameClass.visit( new NameClassVisitor() { public Object onAnyName( AnyNameClass nc ) { return null; } public Object onSimple(SimpleNameClass nc) { if(nc.namespaceURI.equals(infosetURI)) reader.reportError( RELAXNGReader.ERR_INFOSET_URI_ATTRIBUTE ); if(nc.namespaceURI.length()==0 && nc.localName.equals("xmlns")) reader.reportError( RELAXNGReader.ERR_XMLNS_ATTRIBUTE ); return null; } public Object onNsName( NamespaceNameClass nc ) { if(nc.namespaceURI.equals(infosetURI)) reader.reportError( RELAXNGReader.ERR_INFOSET_URI_ATTRIBUTE ); return null; } public Object onNot( NotNameClass nc ) { nc.child.visit(this); return null; } public Object onDifference( DifferenceNameClass nc ) { nc.nc1.visit(this); nc.nc2.visit(this); return null; } public Object onChoice( ChoiceNameClass nc ) { nc.nc1.visit(this); nc.nc2.visit(this); return null; } }); } } msv-2009.1/msv/src/com/sun/msv/reader/trex/ng/RELAXNGReader.java0000644000175000017500000005337010034315204024322 0ustar giovannigiovanni/* * @(#)$Id: RELAXNGReader.java 1634 2004-04-05 17:42:28Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex.ng; import java.text.MessageFormat; import java.util.Iterator; import java.util.Map; import java.util.ResourceBundle; import java.util.Set; import java.util.Stack; import java.util.Vector; import javax.xml.parsers.SAXParserFactory; import org.iso_relax.verifier.Schema; import org.relaxng.datatype.Datatype; import org.relaxng.datatype.DatatypeException; import org.relaxng.datatype.DatatypeLibrary; import org.relaxng.datatype.DatatypeLibraryFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import com.sun.msv.datatype.ErrorDatatypeLibrary; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.trex.TREXGrammar; import com.sun.msv.reader.ChoiceState; import com.sun.msv.reader.GrammarReaderController; import com.sun.msv.reader.State; import com.sun.msv.reader.TerminalState; import com.sun.msv.reader.trex.DivInGrammarState; import com.sun.msv.reader.trex.IncludePatternState; import com.sun.msv.reader.trex.NameClassChoiceState; import com.sun.msv.reader.trex.RootState; import com.sun.msv.reader.trex.TREXBaseReader; import com.sun.msv.reader.trex.TREXSequencedStringChecker; import com.sun.msv.util.LightStack; import com.sun.msv.util.StartTagInfo; import com.sun.msv.util.Util; /** * reads RELAX NG grammar from SAX2 and constructs abstract grammar model. * * @author Kohsuke KAWAGUCHI */ public class RELAXNGReader extends TREXBaseReader { /** loads RELAX NG pattern */ public static TREXGrammar parse( String grammarURL, SAXParserFactory factory, GrammarReaderController controller ) { RELAXNGReader reader = new RELAXNGReader(controller,factory); reader.parse(grammarURL); return reader.getResult(); } /** loads RELAX NG pattern */ public static TREXGrammar parse( InputSource grammar, SAXParserFactory factory, GrammarReaderController controller ) { RELAXNGReader reader = new RELAXNGReader(controller,factory); reader.parse(grammar); return reader.getResult(); } /** easy-to-use constructor. */ public RELAXNGReader( GrammarReaderController controller ) { this(controller,createParserFactory()); } /** easy-to-use constructor. */ public RELAXNGReader( GrammarReaderController controller, SAXParserFactory parserFactory) { // TODO: add s4s this(controller,parserFactory,new StateFactory(),new ExpressionPool()); } /** full constructor */ public RELAXNGReader( GrammarReaderController controller, SAXParserFactory parserFactory, StateFactory stateFactory, ExpressionPool pool ) { super( controller, parserFactory, pool, stateFactory, new RootState() ); } /** * Schema for schema of RELAX NG. */ protected static Schema relaxNGSchema4Schema = null; public static Schema getRELAXNGSchema4Schema() { // under the multi-thread environment, more than once s4s could be loaded. // it's a waste of resource, but by no means fatal. if(relaxNGSchema4Schema==null) { try { relaxNGSchema4Schema = new com.sun.msv.verifier.jarv.RELAXNGFactoryImpl().compileSchema( RELAXNGReader.class.getResourceAsStream("relaxng.rng")); } catch( Exception e ) { e.printStackTrace(); throw new Error("unable to load schema-for-schema for RELAX NG"); } } return relaxNGSchema4Schema; } protected String localizeMessage( String propertyName, Object[] args ) { String format; try { format = ResourceBundle.getBundle("com.sun.msv.reader.trex.ng.Messages").getString(propertyName); } catch( Exception e ) { return super.localizeMessage(propertyName,args); } return MessageFormat.format(format, args ); } protected TREXGrammar getGrammar() { return grammar; } /** Map from ReferenceExps to RefExpParseInfos. */ private final Map refExpParseInfos = new java.util.HashMap(); /** Gets RefExpParseInfo object for the specified ReferenceExp. */ protected RefExpParseInfo getRefExpParseInfo( ReferenceExp exp ) { RefExpParseInfo r = (RefExpParseInfo)refExpParseInfos.get(exp); if(r==null) refExpParseInfos.put(exp, r = new RefExpParseInfo()); return r; } /** * Info about the current ReferenceExp object which is being defined. * This field is maintained by DefineState. *

      * This field is set to null when there is an error, or the pattern being * defined is being re-defined. * *

      * This is a part of the process of the recursive self reference error detection. */ protected RefExpParseInfo currentNamedPattern = null; /** * Flag to indicate whether we saw <element> or not. If we don't see * any <element> between <define>/<start> and <ref>/<parentRef>, * then that reference will go to currentNamedPattern.refs. * *

      * This is a part of the process of the recursive self reference error detection. */ protected boolean directRefernce = true; /** * information necessary to correctly parse pattern definitions. */ protected static class RefExpParseInfo { /** * This field is set to true once the head declaration is found. * A head declaration is a define element without the combine attribute. * It is an error that two head declarations share the same name. */ public boolean haveHead = false; /** * The combine method which is used to combine this pattern. * this field is set to null if combine attribute is not yet used. */ public String combineMethod = null; public static class RedefinitionStatus {} /** * This named pattern is not being redefined. * So it will be a part of the grammar. */ public static RedefinitionStatus notBeingRedefined = new RedefinitionStatus(); /** * This named pattern is being redefined. So even if we'll see some * <define> with this name, it will not be a part of the grammar. * This state means that we don't yet see the definition of the original. * We need to issue an error if the pattern is redefined but there is no original * in the included grammar. */ public static RedefinitionStatus originalNotFoundYet = new RedefinitionStatus(); /** * The same as {@link #originalNotFoundYet}, but we saw the original definition. */ public static RedefinitionStatus originalFound = new RedefinitionStatus(); /** * Current redefinition status. */ public RedefinitionStatus redefinition = notBeingRedefined; /** * Copies the contents of rhs into this object. */ public void set( RefExpParseInfo rhs ) { this.haveHead = rhs.haveHead; this.combineMethod = rhs.combineMethod; this.redefinition = rhs.redefinition; } /** * ReferenceExps which are referenced from this pattern directly * (without having ElementExp in between.) * *

      * This is used to detect recursive self reference errors. */ public final Vector directRefs = new Vector(); /** * ReferenceExps which are referenced from this pattern indirectly * (with ElementExp in between.) */ public final Vector indirectRefs = new Vector(); } /** Namespace URI of RELAX NG */ public static final String RELAXNGNamespace = "http://relaxng.org/ns/structure/1.0"; protected boolean isGrammarElement( StartTagInfo tag ) { return RELAXNGNamespace.equals(tag.namespaceURI) // allow old namespace URI for now. || "http://relaxng.org/ns/structure/0.9".equals(tag.namespaceURI); } /** * DatatypeLibrary factory object. */ private DatatypeLibraryFactory datatypeLibraryFactory = new DefaultDatatypeLibraryFactory(); /** * Returns the datatypeLibraryFactory. */ public DatatypeLibraryFactory getDatatypeLibraryFactory() { return datatypeLibraryFactory; } /** * Sets the datatypeLibraryFactory. */ public void setDatatypeLibraryFactory(DatatypeLibraryFactory datatypeLibraryFactory) { this.datatypeLibraryFactory = datatypeLibraryFactory; } /** * creates various State object, which in turn parses grammar. * parsing behavior can be customized by implementing custom StateFactory. */ public static class StateFactory extends TREXBaseReader.StateFactory { public State nsAnyName ( State parent, StartTagInfo tag ) { return new NGNameState.AnyNameState(); } public State nsNsName ( State parent, StartTagInfo tag ) { return new NGNameState.NsNameState(); } public State nsExcept ( State parent, StartTagInfo tag ) { return new NameClassChoiceState(); } public State text ( State parent, StartTagInfo tag ) { return new TerminalState(Expression.anyString); } public State data ( State parent, StartTagInfo tag ) { return new DataState(); } public State dataParam ( State parent, StartTagInfo tag ) { return new DataParamState(); } public State value ( State parent, StartTagInfo tag ) { return new ValueState(); } public State list ( State parent, StartTagInfo tag ) { return new ListState(); } public State define ( State parent, StartTagInfo tag ) { return new DefineState(); } public State start ( State parent, StartTagInfo tag ) { return new StartState(); } public State redefine ( State parent, StartTagInfo tag ) { return new DefineState(); } public State redefineStart ( State parent, StartTagInfo tag ) { return new StartState(); } public State includeGrammar ( State parent, StartTagInfo tag ) { return new IncludeMergeState(); } public State externalRef ( State parent, StartTagInfo tag ) { return new IncludePatternState(); } public State divInGrammar ( State parent, StartTagInfo tag ) { return new DivInGrammarState(); } public State dataExcept ( State parent, StartTagInfo tag ) { return new ChoiceState(); } public State attribute ( State parent, StartTagInfo tag ) { return new AttributeState(); } public State element ( State parent, StartTagInfo tag ) { return new ElementState(); } public State grammar ( State parent, StartTagInfo tag ) { return new GrammarState(); } public State ref ( State parent, StartTagInfo tag ) { return new RefState(false); } public State parentRef ( State parent, StartTagInfo tag ) { return new RefState(true); } /** * to cause errors if someone is deriving this method. * this method is no longer used. * * @deprecated */ protected final DatatypeLibrary getDatatypeLibrary( String namespaceURI ) throws Exception { // unused throw new UnsupportedOperationException(); } } protected StateFactory getStateFactory() { return (StateFactory)super.sfactory; } protected State createNameClassChildState( State parent, StartTagInfo tag ) { if(tag.localName.equals("name")) return sfactory.nsName(parent,tag); if(tag.localName.equals("anyName")) return sfactory.nsAnyName(parent,tag); if(tag.localName.equals("nsName")) return sfactory.nsNsName(parent,tag); if(tag.localName.equals("choice")) return sfactory.nsChoice(parent,tag); return null; // unknown element. let the default error be thrown. } public State createExpressionChildState( State parent, StartTagInfo tag ) { if(tag.localName.equals("text")) return getStateFactory().text(parent,tag); if(tag.localName.equals("data")) return getStateFactory().data(parent,tag); if(tag.localName.equals("value")) return getStateFactory().value(parent,tag); if(tag.localName.equals("list")) return getStateFactory().list(parent,tag); if(tag.localName.equals("externalRef")) return getStateFactory().externalRef(parent,tag); if(tag.localName.equals("parentRef")) return getStateFactory().parentRef(parent,tag); return super.createExpressionChildState(parent,tag); } /** obtains a named DataType object referenced by a local name. */ public Datatype resolveDataType( String localName ) { try { return getCurrentDatatypeLibrary().createDatatype(localName); } catch( DatatypeException dte ) { reportError( ERR_UNDEFINED_DATATYPE_1, localName, dte.getMessage() ); return com.sun.msv.datatype.xsd.StringType.theInstance; } } /** * obtains the DataTypeLibrary that represents the specified namespace URI. * * If the specified URI is undefined, then this method issues an error to * the user and must return a dummy datatype library. */ public DatatypeLibrary resolveDataTypeLibrary( String uri ) { try { DatatypeLibrary lib = datatypeLibraryFactory.createDatatypeLibrary(uri); if(lib!=null) return lib; // issue an error reportError( ERR_UNKNOWN_DATATYPE_VOCABULARY, uri ); } catch( Throwable e ) { reportError( ERR_UNKNOWN_DATATYPE_VOCABULARY_1, uri, e.toString() ); } return ErrorDatatypeLibrary.theInstance; } private static class AbortException extends Exception {} private void checkRunawayExpression( ReferenceExp node, Stack items, Set visitedExps ) throws AbortException { if( !visitedExps.add(node) ) return; // this ReferenceExp has already been processed. items.push(node); // test direct references Iterator itr = getRefExpParseInfo(node).directRefs.iterator(); while( itr.hasNext() ) { ReferenceExp child = (ReferenceExp)itr.next(); int idx = items.lastIndexOf(child); if(idx!=-1) { // find a cycle. String s = ""; Vector locs = new Vector(); for( ; idx=0 ) reportError( ERR_FRAGMENT_IDENTIFIER, datatypeLibURI ); } // if nothing specified, datatype library stays the same. super.startElement(a,b,c,d); } public void endElement( String a, String b, String c ) throws SAXException { super.endElement(a,b,c); datatypeLib = (DatatypeLibrary)dtLibStack.pop(); datatypeLibURI = (String)dtLibURIStack.pop(); } // error messages public static final String ERR_BAD_FACET = // arg:2 "RELAXNGReader.BadFacet"; public static final String ERR_INVALID_PARAMETERS = // arg:1 "RELAXNGReader.InvalidParameters"; public static final String ERR_BAD_DATA_VALUE = // arg:2 "RELAXNGReader.BadDataValue"; public static final String ERR_UNDEFINED_KEY = // arg:1 "RELAXNGReader.UndefinedKey"; public static final String ERR_UNDEFINED_DATATYPE_1 = // arg:2 "RELAXNGReader.UndefinedDataType1"; public static final String ERR_INCONSISTENT_KEY_TYPE = // arg:1 "RELAXNGReader.InconsistentKeyType"; public static final String ERR_INCONSISTENT_COMBINE = // arg:1 "RELAXNGReader.InconsistentCombine"; public static final String ERR_REDEFINING_UNDEFINED = // arg:1 "RELAXNGReader.RedefiningUndefined"; public static final String ERR_UNKNOWN_DATATYPE_VOCABULARY_1 = // arg:2 "RELAXNGReader.UnknownDatatypeVocabulary1"; public static final String ERR_MULTIPLE_EXCEPT = // arg:0 "RELAXNGReader.MultipleExcept"; public static final String ERR_NOT_ABSOLUTE_URI = // arg:1 "RELAXNGReader.NotAbsoluteURI"; public static final String ERR_INFOSET_URI_ATTRIBUTE = // arg:0 "RELAXNGReader.InfosetUriAttribute"; public static final String ERR_XMLNS_ATTRIBUTE = // arg:0 "RELAXNGReader.XmlnsAttribute"; public static final String ERR_NAKED_INFINITE_ATTRIBUTE_NAMECLASS = //arg:0 "RELAXNGReader.NakedInfiniteAttributeNameClass"; } msv-2009.1/msv/src/com/sun/msv/reader/trex/ng/ElementState.java0000644000175000017500000000204407671170035024477 0ustar giovannigiovanni/* * @(#)$Id: ElementState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex.ng; /** * parses <element> pattern. * * @author Kohsuke KAWAGUCHI */ public class ElementState extends com.sun.msv.reader.trex.ElementState { private boolean previousDirectReference; protected void startSelf() { super.startSelf(); // set directReference to false. previousDirectReference = ((RELAXNGReader)reader).directRefernce; ((RELAXNGReader)reader).directRefernce = false; } protected void endSelf() { final RELAXNGReader reader = (RELAXNGReader)this.reader; reader.directRefernce = previousDirectReference; super.endSelf(); reader.restrictionChecker.checkNameClass(nameClass); } } msv-2009.1/msv/src/com/sun/msv/reader/trex/ng/IncludeMergeState.java0000644000175000017500000000606007703116256025454 0ustar giovannigiovanni/* * @(#)$Id: IncludeMergeState.java 1575 2003-07-09 22:52:30Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex.ng; import java.util.Set; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.reader.ExpressionOwner; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * parses <include> element as a child of <grammar> element. * * @author Kohsuke KAWAGUCHI */ public class IncludeMergeState extends com.sun.msv.reader.trex.IncludeMergeState implements ExpressionOwner { protected State createChildState( StartTagInfo tag ) { final RELAXNGReader reader = (RELAXNGReader)this.reader; if(tag.localName.equals("define")) return reader.getStateFactory().redefine(this,tag); if(tag.localName.equals("start")) return reader.getStateFactory().redefineStart(this,tag); return null; } /** set of ReferenceExps which are redefined by this inclusion. */ private final Set redefinedPatterns = new java.util.HashSet(); // this class has to implement ExpressionOwner because // state requires this interface. public void onEndChild( Expression child ) { // if child element has an error, // then it may not return ReferenceExp. if(!(child instanceof ReferenceExp)) return; redefinedPatterns.add(child); } public void endSelf() { final RELAXNGReader reader = (RELAXNGReader)this.reader; ReferenceExp[] patterns = (ReferenceExp[])redefinedPatterns.toArray(new ReferenceExp[0]); RELAXNGReader.RefExpParseInfo[] old = new RELAXNGReader.RefExpParseInfo[patterns.length]; // back-up the current values of RefExpParseInfo, // and reset the values. for( int i=0; iKohsuke KAWAGUCHI */ public class StartState extends DefineState { protected ReferenceExp getReference() { final RELAXNGReader reader = (RELAXNGReader)this.reader; if( startTag.containsAttribute("name") ) { // since the name attribute is allowed to the certain point, // it is useful to explicitly raise this as an error. reader.reportError( RELAXNGReader.ERR_DISALLOWED_ATTRIBUTE, startTag.qName, "name" ); return null; } return reader.getGrammar(); } } msv-2009.1/msv/src/com/sun/msv/reader/trex/Messages.properties0000644000175000017500000000376007366026273024536 0ustar giovannigiovanni## abstract error messages defined for TREX GrammarReader.Abstract.MissingChildExpression =\ child pattern is missing GrammarReader.Abstract.MoreThanOneChildExpression =\ more than one child pattern is specified where only one is allowed GrammarReader.Abstract.RunAwayExpression =\ the following patterns form an infinite recursion ( {0} ) GrammarReader.Abstract.MissingTopLevel =\ declaration was not found. ## TREX reader error messages TREXGrammarReader.MissingChildNameClass = \ name attribute or name class is required TREXGrammarReader.MoreThanOneNameClass = \ more than one name class is specified TREXGrammarReader.UndeclaredPrefix = \ namespace prefix "{0}" is not declared TREXGrammarReader.UndefinedPattern = \ reference to the undefined pattern "{0}" TREXGrammarReader.UnknownDataTypeVocabulary =\ "{0}" is not a recognized data type vocabulary TREXGrammarReader.FailedToParseDataType =\ failed to parse datatype TREXGrammarReader.BadCombine =\ "{0}" is a bad value for the "combine" attribute TREXGrammarReader.CombineMissing =\ pattern "{0}" is already defined. Specify "combine" \ attribute to combine patterns, or change pattern name to \ avoid conflict. TREXGrammarReader.Warning.CombineIgnored =\ combine attribute is specified, but no predecessor exists. TREXGrammarReader.Warning.ObsoletedXMLSchemaNamespace =\ "{0}" is the old namespace URI. Please use "http://www.w3.org/2001/XMLSchema" TREXGrammarReader.DuplicateDefinition =\ pattern "{0}" is defined more than once in the same file. TREXGrammarReader.NonExistentParentGrammar =\ reference to the nonexistent parent grammar. TREXGrammarReader.InterleavedString =\ "string" or datatype element is used within element. TREXGrammarReader.SequencedString =\ "string" or datatype element is used within element. TREXGrammarReader.RepeatedString =\ "string" or datatype element cannot be repeated. # this error is not applicable for classic TREX TREXGrammarReader.InterleavedAnyString = msv-2009.1/msv/src/com/sun/msv/reader/trex/AttributeState.java0000644000175000017500000000354607671170035024455 0ustar giovannigiovanni/* * @(#)$Id: AttributeState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.Expression; /** * parses <attribute> pattern. * * @author Kohsuke KAWAGUCHI */ public class AttributeState extends NameClassAndExpressionState { protected boolean firstChild=true; protected Expression initialExpression() { // defaults to return Expression.anyString; } protected String getNamespace() { final String ns = startTag.getAttribute("ns"); final boolean global = "true".equals(startTag.getAttribute("global")); if( ns!=null ) return ns; // "ns" attribute always has precedence. // if global="true" is specified, it defaults to propagated ns attribute. if( global ) return ((TREXBaseReader)reader).targetNamespace; // otherwise, it defaults to "" return ""; } protected Expression castExpression( Expression initialExpression, Expression newChild ) { // is allowed to have only one pattern if(!firstChild) reader.reportError( TREXBaseReader.ERR_MORE_THAN_ONE_CHILD_EXPRESSION ); // recover by ignore the error firstChild = false; return newChild; } protected Expression annealExpression( Expression contentModel ) { Expression e = reader.pool.createAttribute( nameClass, contentModel ); if(e instanceof AttributeExp) reader.setDeclaredLocationOf(e); return e; } } msv-2009.1/msv/src/com/sun/msv/reader/trex/classic/0000755000175000017500000000000011622453066022256 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/reader/trex/classic/TREXGrammarReader.java0000644000175000017500000002354007671170035026342 0ustar giovannigiovanni/* * @(#)$Id: TREXGrammarReader.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex.classic; import java.text.MessageFormat; import java.util.ResourceBundle; import javax.xml.parsers.SAXParserFactory; import org.relaxng.datatype.Datatype; import org.relaxng.datatype.DatatypeException; import org.xml.sax.InputSource; import com.sun.msv.datatype.xsd.StringType; import com.sun.msv.datatype.xsd.XSDatatype; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.trex.TREXGrammar; import com.sun.msv.reader.GrammarReaderController; import com.sun.msv.reader.IgnoreState; import com.sun.msv.reader.RunAwayExpressionChecker; import com.sun.msv.reader.State; import com.sun.msv.reader.TerminalState; import com.sun.msv.reader.datatype.DataTypeVocabulary; import com.sun.msv.reader.datatype.xsd.XSDatatypeExp; import com.sun.msv.reader.datatype.xsd.XSDatatypeResolver; import com.sun.msv.reader.trex.IncludePatternState; import com.sun.msv.reader.trex.RootState; import com.sun.msv.reader.trex.TREXBaseReader; import com.sun.msv.reader.trex.TREXSequencedStringChecker; import com.sun.msv.util.StartTagInfo; /** * reads TREX grammar from SAX2 and constructs abstract grammar model. * * @author Kohsuke KAWAGUCHI */ public class TREXGrammarReader extends TREXBaseReader implements XSDatatypeResolver { /** loads TREX pattern */ public static TREXGrammar parse( String grammarURL, SAXParserFactory factory, GrammarReaderController controller ) { TREXGrammarReader reader = new TREXGrammarReader(controller,factory,new ExpressionPool()); reader.parse(grammarURL); return reader.getResult(); } /** loads TREX pattern */ public static TREXGrammar parse( InputSource grammar, SAXParserFactory factory, GrammarReaderController controller ) { TREXGrammarReader reader = new TREXGrammarReader(controller,factory,new ExpressionPool()); reader.parse(grammar); return reader.getResult(); } /** easy-to-use constructor. */ public TREXGrammarReader( GrammarReaderController controller) { this(controller,createParserFactory(),new ExpressionPool()); } /** easy-to-use constructor. */ public TREXGrammarReader( GrammarReaderController controller, SAXParserFactory parserFactory, ExpressionPool pool ) { this(controller,parserFactory,new StateFactory(),pool); } /** full constructor */ public TREXGrammarReader( GrammarReaderController controller, SAXParserFactory parserFactory, StateFactory stateFactory, ExpressionPool pool ) { super( controller, parserFactory, pool, stateFactory, new RootState() ); } protected String localizeMessage( String propertyName, Object[] args ) { String format; try { format = ResourceBundle.getBundle("com.sun.msv.reader.trex.classic.Messages").getString(propertyName); } catch( Exception e ) { return super.localizeMessage(propertyName,args); } return MessageFormat.format(format, args ); } /** * TREX allows either * (1) the predefined namespace for TREX or * (2) default namespace "" * * as its namespace. This variable holds which namespace is currently in use. */ protected String currentGrammarURI; protected TREXGrammar getGrammar() { return grammar; } /** Namespace URI of TREX */ public static final String TREXNamespace = "http://www.thaiopensource.com/trex"; protected boolean isGrammarElement( StartTagInfo tag ) { if( currentGrammarURI==null ) { // first time. if( tag.namespaceURI.equals(TREXNamespace) ) { currentGrammarURI = TREXNamespace; return true; } if( tag.namespaceURI.equals("") ) { currentGrammarURI = ""; return true; } return false; } else { if(currentGrammarURI.equals(tag.namespaceURI)) return true; if(tag.containsAttribute(TREXNamespace,"role")) return true; return false; } } /** * creates various State object, which in turn parses grammar. * parsing behavior can be customized by implementing custom StateFactory. */ public static class StateFactory extends TREXBaseReader.StateFactory { public State concur ( State parent, StartTagInfo tag ) { return new ConcurState(); } public State anyString ( State parent, StartTagInfo tag ) { return new TerminalState(Expression.anyString); } public State string ( State parent, StartTagInfo tag ) { return new StringState(); } public State data ( State parent, StartTagInfo tag ) { return new DataState(); } public State define ( State parent, StartTagInfo tag ) { return new DefineState(); } public State includePattern( State parent, StartTagInfo tag ) { return new IncludePatternState(); } } protected StateFactory getStateFactory() { return (StateFactory)super.sfactory; } private boolean issueObsoletedXMLSchemaNamespace = false; /** * maps obsoleted XML Schema namespace to the current one. */ private String mapNamespace( String namespace ) { if(namespace.equals("http://www.w3.org/2000/10/XMLSchema") || namespace.equals("http://www.w3.org/2000/10/XMLSchema-datatypes")) { // namespace of CR version. if( !issueObsoletedXMLSchemaNamespace ) // report warning only once. reportWarning(WRN_OBSOLETED_XMLSCHEMA_NAMSPACE,namespace); issueObsoletedXMLSchemaNamespace = true; return com.sun.msv.reader.datatype.xsd.XSDVocabulary.XMLSchemaNamespace; } return namespace; } public State createExpressionChildState( State parent, StartTagInfo tag ) { if(tag.localName.equals("concur")) return getStateFactory().concur(parent,tag); if(tag.localName.equals("anyString")) return getStateFactory().anyString(parent,tag); if(tag.localName.equals("string")) return getStateFactory().string(parent,tag); if(tag.localName.equals("data")) return getStateFactory().data(parent,tag); if(tag.localName.equals("include")) return getStateFactory().includePattern(parent,tag); final String role = tag.getAttribute(TREXNamespace,"role"); if("datatype".equals(role)) { String namespaceURI = mapNamespace(tag.namespaceURI); DataTypeVocabulary v = grammar.dataTypes.get(namespaceURI); if(v==null) { reportError( ERR_UNKNOWN_DATATYPE_VOCABULARY, tag.namespaceURI ); // put a dummy vocabulary into the map // so that user will never receive the same error again. grammar.dataTypes.put( tag.namespaceURI, new UndefinedDataTypeVocabulary() ); return new IgnoreState(); // recover by ignoring this element. } return v.createTopLevelReaderState(tag); } return super.createExpressionChildState(parent,tag); } public XSDatatypeExp resolveXSDatatype( String qName ) { return new XSDatatypeExp( (XSDatatype)resolveDatatype(qName),pool); } /** obtains a named DataType object referenced by a QName. */ public Datatype resolveDatatype( String qName ) { String[] s = splitQName(qName); if(s==null) { reportError( ERR_UNDECLARED_PREFIX, qName ); // recover by using a dummy DataType return StringType.theInstance; } s[0] = mapNamespace(s[0]); // s[0] == namespace URI DataTypeVocabulary v = grammar.dataTypes.get(s[0]); if(v==null) { reportError( ERR_UNKNOWN_DATATYPE_VOCABULARY, s[0] ); // put a dummy vocabulary into the map // so that user will never receive the same error again. grammar.dataTypes.put( s[0], new UndefinedDataTypeVocabulary() ); } else { try { return v.getType( s[1] ); // s[1] == local name } catch( DatatypeException e ) { reportError( ERR_UNDEFINED_DATATYPE, qName ); } } // recover by using a dummy DataType return StringType.theInstance; } public void wrapUp() { // make sure that there is no recurisve patterns. RunAwayExpressionChecker.check(this,grammar); if( !controller.hadError() ) // make sure that there is no sequenced string. // when run-away expression is found, calling this method results in // stack overflow. grammar.visit( new TREXSequencedStringChecker(this,false) ); } /** * Dummy DataTypeVocabulary for better error recovery. * * If DataTypeVocabulary is not found, the error is reported * and this class is used to prevent further repetitive error messages. */ private static class UndefinedDataTypeVocabulary implements DataTypeVocabulary { public State createTopLevelReaderState( StartTagInfo tag ) { return new IgnoreState(); } // ignore everything public Datatype getType( String localTypeName ) { return StringType.theInstance; } // accepts any type name } // error messages } msv-2009.1/msv/src/com/sun/msv/reader/trex/classic/DefineState.java0000644000175000017500000000530211156747174025324 0ustar giovannigiovanni/* * @(#)$Id: DefineState.java 1744 2009-03-14 15:34:20Z bimargulies $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex.classic; import org.xml.sax.Locator; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ReferenceExp; /** * parses <define> declaration. * * @author Kohsuke KAWAGUCHI */ public class DefineState extends com.sun.msv.reader.trex.DefineState { /** * combines two expressions into one as specified by the combine parameter, * and returns a new expression. * * If the combine parameter is invalid, then return null. */ protected Expression doCombine( ReferenceExp baseExp, Expression newExp, String combine ) { final TREXGrammarReader reader = (TREXGrammarReader)this.reader; if( baseExp.exp==null ) { // this is the first time definition if( combine!=null ) // "combine" attribute will be ignored reader.reportWarning( TREXGrammarReader.WRN_COMBINE_IGNORED, baseExp.name ); return newExp; } // some pattern is already defined under this name. // make sure that the previous definition was in a different file. if( reader.getDeclaredLocationOf(baseExp).getSystemId().equals( reader.getLocator().getSystemId() ) ) { reader.reportError( TREXGrammarReader.ERR_DUPLICATE_DEFINITION, baseExp.name ); // recovery by ignoring this definition return baseExp.exp; } if( combine==null ) { // second definition without @combine. reader.reportError( new Locator[]{location, reader.getDeclaredLocationOf(baseExp)}, TREXGrammarReader.ERR_COMBINE_MISSING, new Object[]{baseExp.name} ); // recover by ignoring this definition return baseExp.exp; } if( combine.equals("group") ) return reader.pool.createSequence( baseExp.exp, newExp ); else if( combine.equals("choice") ) return reader.pool.createChoice( baseExp.exp, newExp ); else if( combine.equals("replace") ) return exp; else if( combine.equals("interleave") ) return reader.pool.createInterleave( baseExp.exp, newExp ); else if( combine.equals("concur") ) return reader.pool.createConcur( baseExp.exp, newExp ); else return null; } } msv-2009.1/msv/src/com/sun/msv/reader/trex/classic/ConcurState.java0000644000175000017500000000142407671170035025355 0ustar giovannigiovanni/* * @(#)$Id: ConcurState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex.classic; import com.sun.msv.grammar.Expression; import com.sun.msv.reader.ExpressionWithChildState; /** * parses <concur> pattern. * * @author Kohsuke KAWAGUCHI */ public class ConcurState extends ExpressionWithChildState { protected Expression castExpression( Expression exp, Expression child ) { // first one. if( exp==null ) return child; return reader.pool.createConcur(exp,child); } } msv-2009.1/msv/src/com/sun/msv/reader/trex/classic/package.html0000644000175000017500000000010407350477355024544 0ustar giovannigiovanni

      parses TREX pattern into AGM.

      msv-2009.1/msv/src/com/sun/msv/reader/trex/classic/DataState.java0000644000175000017500000000230507671170035024774 0ustar giovannigiovanni/* * @(#)$Id: DataState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex.classic; import com.sun.msv.grammar.Expression; import com.sun.msv.reader.ExpressionWithoutChildState; import com.sun.msv.util.StringPair; /** * parses <data> pattern. * * @author Kohsuke KAWAGUCHI */ public class DataState extends ExpressionWithoutChildState { protected Expression makeExpression() { final String typeName = startTag.getAttribute("type"); if( typeName==null ) { // type attribute is required reader.reportError( TREXGrammarReader.ERR_MISSING_ATTRIBUTE, startTag.qName, "type" ); // recover from error by assuming anyString. return Expression.anyString; } else { return reader.pool.createData( ((TREXGrammarReader)reader).resolveDatatype(typeName), new StringPair("",typeName) ); } } } msv-2009.1/msv/src/com/sun/msv/reader/trex/classic/StringState.java0000644000175000017500000000307507671170035025376 0ustar giovannigiovanni/* * @(#)$Id: StringState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex.classic; import com.sun.msv.datatype.xsd.StringType; import com.sun.msv.datatype.xsd.TokenType; import com.sun.msv.datatype.xsd.WhiteSpaceProcessor; import com.sun.msv.grammar.Expression; import com.sun.msv.reader.ExpressionWithoutChildState; import com.sun.msv.util.StringPair; /** * parses <string> pattern. * * @author Kohsuke KAWAGUCHI */ public class StringState extends ExpressionWithoutChildState { protected final StringBuffer text = new StringBuffer(); public void characters( char[] buf, int from, int len ) { text.append(buf,from,len); } public void ignorableWhitespace( char[] buf, int from, int len ) { text.append(buf,from,len); } protected Expression makeExpression() { if("preserve".equals(startTag.getAttribute("whiteSpace"))) return reader.pool.createValue( StringType.theInstance, new StringPair("","string"), text.toString() ); else return reader.pool.createValue( TokenType.theInstance, new StringPair("","token"), WhiteSpaceProcessor.collapse(text.toString()) ); // masquerade RELAX NG built-in datatypes } } msv-2009.1/msv/src/com/sun/msv/reader/trex/ElementState.java0000644000175000017500000000142007671170035024070 0ustar giovannigiovanni/* * @(#)$Id: ElementState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.trex.ElementPattern; /** * parses <element> pattern. * * @author Kohsuke KAWAGUCHI */ public class ElementState extends NameClassAndExpressionState { protected Expression annealExpression( Expression contentModel ) { ElementPattern e = new ElementPattern( nameClass, contentModel ); reader.setDeclaredLocationOf(e); return e; } } msv-2009.1/msv/src/com/sun/msv/reader/trex/IncludeMergeState.java0000644000175000017500000000313310326262540025037 0ustar giovannigiovanni/* * @(#)$Id: IncludeMergeState.java 1695 2005-10-21 22:02:08Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import com.sun.msv.reader.AbortException; import com.sun.msv.reader.SimpleState; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * <include> element as an immediate child of <grammar> element. * * @author Kohsuke KAWAGUCHI */ public class IncludeMergeState extends SimpleState { protected State createChildState( StartTagInfo tag ) { // no child element is allowed by default. return null; } protected void endSelf() { // For RELAX NG, inclusion has to be done at the endSelf method, // not in the startSelf method. final String href = startTag.getAttribute("href"); if(href==null) {// name attribute is required. reader.reportError( TREXBaseReader.ERR_MISSING_ATTRIBUTE, "include","href"); // recover by ignoring this include element } else try { // parse specified file TREXBaseReader reader = (TREXBaseReader) this.reader; reader.switchSource(this,href,reader.sfactory.includedGrammar()); } catch( AbortException e ) { // recover by ignoring the error } super.endSelf(); } } msv-2009.1/msv/src/com/sun/msv/reader/trex/StartState.java0000644000175000017500000000215407671170035023601 0ustar giovannigiovanni/* * @(#)$Id: StartState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.trex; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.reader.SequenceState; /** * parses <start> element. * * @author Kohsuke KAWAGUCHI */ public class StartState extends SequenceState { protected final TREXBaseReader getReader() { return (TREXBaseReader)reader; } protected Expression annealExpression( Expression exp ) { final String name = startTag.getAttribute("name"); if(name!=null) { // name attribute is optional. ReferenceExp ref = getReader().grammar.namedPatterns.getOrCreate(name); ref.exp = exp; exp = ref; } getReader().grammar.exp = exp; return null; // return value is meaningless. } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/0000755000175000017500000000000011622453066021634 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/reader/xmlschema/XMLSchemaReader.java0000644000175000017500000013003611164025612025377 0ustar giovannigiovanni/* * @(#)$Id: XMLSchemaReader.java 1751 2009-03-30 02:16:42Z bimargulies $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import java.text.MessageFormat; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.ResourceBundle; import java.util.Set; import javax.xml.XMLConstants; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.Source; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import org.iso_relax.verifier.Schema; import org.relaxng.datatype.DatatypeException; import org.w3c.dom.ls.LSInput; import org.w3c.dom.ls.LSResourceResolver; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.Locator; import com.sun.msv.datatype.xsd.DatatypeFactory; import com.sun.msv.datatype.xsd.StringType; import com.sun.msv.datatype.xsd.XSDatatype; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.Grammar; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.ReferenceContainer; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.SimpleNameClass; import com.sun.msv.grammar.trex.ElementPattern; import com.sun.msv.grammar.xmlschema.ComplexTypeExp; import com.sun.msv.grammar.xmlschema.ElementDeclExp; import com.sun.msv.grammar.xmlschema.OccurrenceExp; import com.sun.msv.grammar.xmlschema.SimpleTypeExp; import com.sun.msv.grammar.xmlschema.XMLSchemaGrammar; import com.sun.msv.grammar.xmlschema.XMLSchemaSchema; import com.sun.msv.grammar.xmlschema.XMLSchemaTypeExp; import com.sun.msv.reader.AbortException; import com.sun.msv.reader.ChoiceState; import com.sun.msv.reader.GrammarReader; import com.sun.msv.reader.GrammarReaderController; import com.sun.msv.reader.IgnoreState; import com.sun.msv.reader.InterleaveState; import com.sun.msv.reader.RunAwayExpressionChecker; import com.sun.msv.reader.SequenceState; import com.sun.msv.reader.State; import com.sun.msv.reader.datatype.xsd.FacetState; import com.sun.msv.reader.datatype.xsd.SimpleTypeState; import com.sun.msv.reader.datatype.xsd.XSDatatypeExp; import com.sun.msv.reader.datatype.xsd.XSDatatypeResolver; import com.sun.msv.util.StartTagInfo; import com.sun.msv.verifier.jarv.XSFactoryImpl; /** * parses XML representation of XML Schema and constructs AGM. * * @author Kohsuke KAWAGUCHI */ public class XMLSchemaReader extends GrammarReader implements XSDatatypeResolver { /* A schema may be embedded in a larger document with additional prefix/namespace * mappings. */ private Map additionalNamespaceMap; /** loads XML Schema */ public static XMLSchemaGrammar parse( String grammarURL, SAXParserFactory factory, GrammarReaderController controller ) { XMLSchemaReader reader = new XMLSchemaReader(controller,factory); reader.parse(grammarURL); return reader.getResult(); } /** loads XML Schema */ public static XMLSchemaGrammar parse( InputSource grammar, SAXParserFactory factory, GrammarReaderController controller ) { XMLSchemaReader reader = new XMLSchemaReader(controller,factory); reader.parse(grammar); return reader.getResult(); } /** * Convenience method to create a reader and read a single scheme. * @param schema * @param controller * @return * @throws TransformerConfigurationException * @throws TransformerException */ public static XMLSchemaGrammar parse(Source schema, GrammarReaderController controller) throws TransformerConfigurationException, TransformerException { /* If the source is a SAXSource, we will still use a SAXParser, * so we still create the parser factory. */ XMLSchemaReader reader = new XMLSchemaReader(controller); reader.parse(schema); return reader.getResult(); } /** easy-to-use constructor. */ public XMLSchemaReader( GrammarReaderController controller ) { this(controller,createParserFactory()); } public XMLSchemaReader( GrammarReaderController controller, SAXParserFactory parserFactory ) { this( controller, parserFactory, new ExpressionPool() ); } public XMLSchemaReader( GrammarReaderController controller, SAXParserFactory parserFactory, ExpressionPool pool ) { this( controller, parserFactory, new StateFactory(), pool ); } public XMLSchemaReader( GrammarReaderController controller, SAXParserFactory parserFactory, StateFactory stateFactory, ExpressionPool pool ) { super(controller,parserFactory,pool,new RootState(stateFactory.schemaHead(null))); this.sfactory = stateFactory; // by putting them into ReferenceExp, # of expressions usually gets smaller // because createSequence are right-associative and any attempt to extend // this sequence will end up creating new SequenceExps. // It's also good for writer: it can generate more compact XML representation. ReferenceExp exp = new ReferenceExp( XMLSchemaSchemaLocationAttributes ); xsiSchemaLocationExp = exp; exp.exp = pool.createSequence( pool.createOptional( pool.createAttribute( new SimpleNameClass(XMLSchemaSchema.XMLSchemaInstanceNamespace,"schemaLocation") ) ), pool.createOptional( pool.createAttribute( new SimpleNameClass(XMLSchemaSchema.XMLSchemaInstanceNamespace,"noNamespaceSchemaLocation") ) ) ); this.grammar = new XMLSchemaGrammar(pool); xsdSchema = new XMLSchemaSchema( XMLSchemaNamespace, grammar ); // since we might parse the schema-for-schema, we cannot mark // this schema as "already defined." // markSchemaAsDefined(xsdSchema); ElementPattern e = new ElementPattern( NameClass.ALL, Expression.nullSet ); e.contentModel = pool.createMixed( pool.createZeroOrMore( pool.createChoice( pool.createAttribute( NameClass.ALL ), e ))); complexUrType = xsdSchema.complexTypes.getOrCreate( "anyType" ); complexUrType.body.exp = e.contentModel; complexUrType.complexBaseType = complexUrType; complexUrType.derivationMethod = ComplexTypeExp.RESTRICTION; } /** Schema for schema of W3C XML Schema. */ protected static Schema xmlSchema4XmlSchema = null; public static Schema getXmlSchemaForXmlSchema() { // under the multi-thread environment, more than once s4s could be loaded. // it's a waste of resource, but by no means fatal. if(xmlSchema4XmlSchema==null) { try { XSFactoryImpl factory = new XSFactoryImpl(); factory.setEntityResolver( new EntityResolver() { public InputSource resolveEntity( String publicId, String systemId ) { if(systemId.endsWith("datatypes.xsd")) return new InputSource(XMLSchemaReader.class.getResourceAsStream( "datatypes.xsd")); if(systemId.endsWith("xml.xsd")) return new InputSource(XMLSchemaReader.class.getResourceAsStream( "xml.xsd")); System.out.println("unexpected system ID: "+systemId); return null; } }); xmlSchema4XmlSchema = factory.compileSchema( XMLSchemaReader.class.getResourceAsStream("xmlschema.xsd")); } catch( Exception e ) { e.printStackTrace(); throw new Error("unable to load schema-for-schema for W3C XML Schema"); } } return xmlSchema4XmlSchema; } /** * content model that matches to * optional xsi:schemaLocation or xsi:noNamespaceSchemaLocation. */ public final ReferenceExp xsiSchemaLocationExp; public final static String XMLSchemaSchemaLocationAttributes = "____internal_XML_schema_SchemaLocation_attributes"; /** * expression that matches to "ur-type" when used as a complex type. */ public final ComplexTypeExp complexUrType; /** value of the "attributeFormDefault" attribute. */ protected String attributeFormDefault; /** value of the "elementFormDefault" attribute. */ protected String elementFormDefault; /** * value of the "finalDefault" attribute. * Set to null if the attribute was not specified. */ protected String finalDefault; /** * value of the "blockDefault" attribute. * Set to null if the attribute was not specified. */ protected String blockDefault; /** grammar object which is being under construction. */ protected final XMLSchemaGrammar grammar; protected XMLSchemaSchema currentSchema; /** * XMLSchemaSchema object that has XMLSchemaNamespace as its target namespace. */ protected final XMLSchemaSchema xsdSchema; /** * tables that store all SystemIds that we've read. * * map from target namespace URI to set of system ids. * This field is used to prevent double inclusion. * * Strictly speaking, comparision based on system id is not enough. * The spec calls for "the necessity of establishing identity * component by component" (section 4.2.1, last note). */ public final Map> parsedFiles = new HashMap>(); public final XMLSchemaGrammar getResult() { if(controller.hadError()) return null; else return grammar; } public Grammar getResultAsGrammar() { return getResult(); } /** * gets a reference to XMLSchemaGrammar object whose target namespace * is the specified one. * * If there is no such object, this method creates a new instance and * returns it. */ public XMLSchemaSchema getOrCreateSchema( String namespaceURI ) { XMLSchemaSchema g = (XMLSchemaSchema)grammar.getByNamespace(namespaceURI); if(g!=null) return g; // create new one. g = new XMLSchemaSchema(namespaceURI,grammar); // memorize the first link so that we can report the source of error // if this namespace turns out to be undefined. backwardReference.memorizeLink(g); return g; } /** * creates various State object, which in turn parses grammar. * parsing behavior can be customized by implementing custom StateFactory. */ public static class StateFactory { public State schemaHead (String expectedNamespace ) { return new SchemaState(expectedNamespace); } public State schemaIncluded (State parent, String expectedNamespace ) { return new SchemaIncludedState(expectedNamespace); } public State simpleType (State parent,StartTagInfo tag) { return new SimpleTypeState(); } public State all (State parent,StartTagInfo tag) { return new InterleaveState(); } public State choice (State parent,StartTagInfo tag) { return new ChoiceState(true); } public State sequence (State parent,StartTagInfo tag) { return new SequenceState(true); } public State group (State parent,StartTagInfo tag) { return new GroupState(); } public State complexTypeDecl (State parent,StartTagInfo tag) { return new ComplexTypeDeclState(); } public State attribute (State parent,StartTagInfo tag) { return new AttributeState(); } public State attributeGroup (State parent,StartTagInfo tag) { return new AttributeGroupState(); } public State elementDecl (State parent,StartTagInfo tag) { return new ElementDeclState(); } public State elementRef (State parent,StartTagInfo tag) { return new ElementRefState(); } public State any (State parent,StartTagInfo tag) { return new AnyElementState(); } public State anyAttribute (State parent,StartTagInfo tag) { return new AnyAttributeState(); } public State include (State parent,StartTagInfo tag) { return new IncludeState(); } public State import_ (State parent,StartTagInfo tag) { return new ImportState(); } public State redefine (State parent,StartTagInfo tag) { return new RedefineState(); } public State notation (State parent,StartTagInfo tag) { return new IgnoreState(); } public State facets (State parent,StartTagInfo tag) { return new FacetState(); } public State unique (State parent,StartTagInfo tag) { return new IdentityConstraintState(); } public State key (State parent,StartTagInfo tag) { return new IdentityConstraintState(); } public State keyref (State parent,StartTagInfo tag) { return new IdentityConstraintState(); } public State complexContent (State parent,StartTagInfo tag,ComplexTypeExp decl) { return new ComplexContentState(decl); } // complexContent/restriction public State complexRst (State parent,StartTagInfo tag,ComplexTypeExp decl) { return new ComplexContentBodyState(decl,false); } // complexContent/extension public State complexExt (State parent,StartTagInfo tag,ComplexTypeExp decl) { return new ComplexContentBodyState(decl,true); } public State simpleContent (State parent,StartTagInfo tag,ComplexTypeExp decl) { return new SimpleContentState(decl); } // simpleContent/restriction public State simpleRst (State parent,StartTagInfo tag,ComplexTypeExp decl) { return new SimpleContentRestrictionState(decl); } // simpleContent/extension public State simpleExt (State parent,StartTagInfo tag,ComplexTypeExp decl) { return new SimpleContentExtensionState(decl); } } public final StateFactory sfactory; public State createExpressionChildState( State parent, StartTagInfo tag ) { if(tag.localName.equals("element")) { if(tag.containsAttribute("ref")) return sfactory.elementRef(parent,tag); else return sfactory.elementDecl(parent,tag); } if(tag.localName.equals("any")) return sfactory.any(parent,tag); return createModelGroupState(parent,tag); } /** * creates a state object that parses "all"/"group ref"/"choice" and "sequence". */ public State createModelGroupState( State parent, StartTagInfo tag ) { if(tag.localName.equals("all")) return sfactory.all(parent,tag); if(tag.localName.equals("choice")) return sfactory.choice(parent,tag); if(tag.localName.equals("sequence")) return sfactory.sequence(parent,tag); if(tag.localName.equals("group")) return sfactory.group(parent,tag); return null; } /** * creates a state object that parses "attribute","attributeGroup ref", and "anyAttribute". */ public State createAttributeState( State parent, StartTagInfo tag ) { if(tag.localName.equals("attribute")) return sfactory.attribute(parent,tag); if(tag.localName.equals("anyAttribute")) return sfactory.anyAttribute(parent,tag); if(tag.localName.equals("attributeGroup")) return sfactory.attributeGroup(parent,tag); return null; } public State createFacetState( State parent, StartTagInfo tag ) { if( FacetState.facetNames.contains(tag.localName) ) return sfactory.facets(parent,tag); else return null; } /** namespace URI of XML Schema declarations. */ public static final String XMLSchemaNamespace = "http://www.w3.org/2001/XMLSchema"; public static final String XMLSchemaNamespace_old = "http://www.w3.org/2000/10/XMLSchema"; private boolean issuedOldNamespaceWarning = false; protected boolean isGrammarElement( StartTagInfo tag ) { if(!isSchemaNamespace(tag.namespaceURI)) return false; // annotation is ignored at this level. // by returning false, the entire subtree will be simply ignored. if(tag.localName.equals("annotation")) return false; return true; } /** set of XMLSchemaGrammar that is already defined. * XMLSchemaGrammar object is created when it is first referenced or defined. */ private final Set definedSchemata = new java.util.HashSet(); public final void markSchemaAsDefined( XMLSchemaSchema schema ) { definedSchemata.add( schema ); } public final boolean isSchemaDefined( XMLSchemaSchema schema ) { return definedSchemata.contains(schema); } protected String resolveNamespaceOfAttributeDecl( String formValue ) { return resolveNamespaceOfDeclaration( formValue, attributeFormDefault ); } protected String resolveNamespaceOfElementDecl( String formValue ) { return resolveNamespaceOfDeclaration( formValue, elementFormDefault ); } private String resolveNamespaceOfDeclaration( String formValue, String defaultValue ) { if( "qualified".equals(formValue) ) return currentSchema.targetNamespace; if( "unqualified".equals(formValue) ) return ""; if( formValue!=null ) { reportError( ERR_BAD_ATTRIBUTE_VALUE, "form", formValue ); return "$$recover$$"; // recovery by returning whatever } return defaultValue; } /** * resolves built-in datatypes (URI: http://www.w3.org/2001/XMLSchema) * * @return * null if the type is not defined. */ public XSDatatype resolveBuiltinDataType( String typeLocalName ) { // datatypes of XML Schema part 2 try { return DatatypeFactory.getTypeByName(typeLocalName); } catch( DatatypeException e ) { return null; // not found. } } /** * Gets a built-in datatype as SimpleTypeExp. * * @return * null if the type is not defined. */ public SimpleTypeExp resolveBuiltinSimpleType( String typeLocalName ) { // datatypes of XML Schema part 2 try { XSDatatype dt = DatatypeFactory.getTypeByName(typeLocalName); SimpleTypeExp sexp = xsdSchema.simpleTypes.getOrCreate(typeLocalName); if(!sexp.isDefined()) sexp.set( new XSDatatypeExp(dt,pool) ); return sexp; } catch( DatatypeException e ) { return null; // not found. } } public boolean isSchemaNamespace( String ns ) { if( ns.equals(XMLSchemaNamespace) ) return true; if( ns.equals(XMLSchemaNamespace_old) ) { // old namespace. // report a warning only once. if( !issuedOldNamespaceWarning ) reportWarning( WRN_OBSOLETED_NAMESPACE, null ); issuedOldNamespaceWarning = true; return true; } return false; } /** * Resolves a simple type name into the corresponding XSDatatypeExp object. */ public XSDatatypeExp resolveXSDatatype( String typeQName ) { final String[] r = splitQName(typeQName); if(r==null) { reportError( ERR_UNDECLARED_PREFIX, typeQName ); // TODO: implement UndefinedType, that is used only when an error is encountered. // it should accept anything and any facets. // recover by assuming string. return new XSDatatypeExp(StringType.theInstance,pool); } if( isSchemaNamespace(r[0]) ) { // internal definitions should be consulted first. XSDatatype dt = resolveBuiltinDataType(r[1]); if(dt!=null) return new XSDatatypeExp(dt,pool); // the name was not found. // maybe we are parsing schema for schema. // consult the externally defined types. } final SimpleTypeExp sexp = getOrCreateSchema(r[0]).simpleTypes. getOrCreate(r[1]); backwardReference.memorizeLink(sexp); // simple type might be re-defined later. // therefore, we always need a late-binding datatype, // even if the datatype is defined already. return new XSDatatypeExp(r[0],r[1],this,new XSDatatypeExp.Renderer(){ public XSDatatype render( XSDatatypeExp.RenderingContext context ) { if(sexp.getType()!=null) return sexp.getType().getType(context); else // undefined error is alreadyreported by // the detectUndefinedOnes(simpleTypes) method // so silently recover by using some sort of expression return StringType.theInstance; } }); } public static interface RefResolver { ReferenceContainer get( XMLSchemaSchema schema ); } public Expression resolveQNameRef( StartTagInfo tag, String attName, RefResolver resolver ) { String refQName = tag.getAttribute(attName); if( refQName==null ) { reportError( ERR_MISSING_ATTRIBUTE, tag.qName, attName ); return null; // failed. } String[] r = splitQName(refQName); if(r==null) { reportError( ERR_UNDECLARED_PREFIX, refQName ); return null; } Expression e = resolver.get( getOrCreateSchema(r[0]/*uri*/) )._getOrCreate(r[1]/*local name*/); backwardReference.memorizeLink(e); return e; } /** * The intended target namespace of the chameleon schema. * *

      * When parsing a chameleon schema (inclusion of a schema without * the targetNamespace attribute), this field is set to the target namespace * of the callee, so that any reference occured in the chameleon schema * is treated correctly. * *

      * This field must be set to null in other cases. In that case, QName resolution * is handled just normally. * *

      * This field is maintained by {@link SchemaIncludedState}. */ protected String chameleonTargetNamespace = null; /** * Resolves a QName into a pair of (namespace URI,local name). * *

      * When we are parsing a "chameleon schema", any reference to * the default empty namespace("") has to be treated as a reference to * the intended target namespace. */ public String[] splitQName( String qName ) { String[] r = super.splitQName(qName); if(r == null) { /* This code copies code in the base class. * Perhaps it would be better to push and pop these prefixes, * but they have to be at the end of the chain so they would * have to be pushed at 'parse', which in turn suggests * pushing this functionality down into the grammar controller, * which I'm not willing to try today. */ int idx = qName.indexOf(':'); if (idx > 0) { String prefix = qName.substring(0, idx); String uri = additionalNamespaceMap.get(prefix); if (uri != null) { return new String[]{uri, qName.substring(idx+1), qName}; } } return null; } if(r[0].length()==0 && chameleonTargetNamespace!=null) r[0] = chameleonTargetNamespace; return r; } protected Expression interceptExpression( State state, Expression exp ) { // process minOccurs/maxOccurs if( state instanceof SequenceState || state instanceof ChoiceState || state instanceof InterleaveState || state instanceof AnyElementState || state instanceof ElementDeclState || state instanceof ElementRefState || state instanceof GroupState ) // TODO: is limited upto 1 return processOccurs(state.getStartTag(),exp); return exp; } /** * Adds maxOccurs/minOccurs semantics to a given expression. * * For example, if this method receives A, minOccurs=0, and maxOccurs=3, * then this method should return something like (A,(A,A?)?)? */ public Expression processOccurs( StartTagInfo startTag, Expression item ) { String minOccurs = startTag.getAttribute("minOccurs"); int minOccursValue=1; if( minOccurs!=null ) { try { minOccursValue = Integer.parseInt(minOccurs); if(minOccursValue<0) throw new NumberFormatException(); } catch( NumberFormatException e ) { reportError( ERR_BAD_ATTRIBUTE_VALUE, "minOccurs", minOccurs ); minOccursValue = 1; } } String maxOccurs = startTag.getAttribute("maxOccurs"); int maxOccursValue; // -1 for 'unbounded' if( maxOccurs==null ) { // maxOccurs if not present. make sure that minOccurs<=1 if( minOccursValue>1 ) reportError( ERR_MAXOCCURS_IS_NECESSARY ); maxOccursValue = 1; } else if( maxOccurs.equals("unbounded") ) { maxOccursValue = -1; } else { try { maxOccursValue = Integer.parseInt(maxOccurs); if(maxOccursValue<0 || maxOccursValue recursiveSubstBuffer = new java.util.HashSet(); itr = grammar.iterateSchemas(); while( itr.hasNext() ) { XMLSchemaSchema schema = (XMLSchemaSchema)itr.next(); ReferenceExp[] elems = schema.elementDecls.getAll(); for( int i=0; itrue if d can validly substitute c. * * @param c * the substitution head * @param d * a member of the substitution group of c. */ private boolean isSubstitutable( ElementDeclExp c, ElementDeclExp d ) { // clause 1 if(c.isSubstitutionBlocked()) return false; // clause 2 must be implicitly tested before this method is called. final Type cType = getType(c.getTypeDefinition()); Type dType = getType(d.getTypeDefinition()); // test clause 3 int constraint = c.block; int derivationMethod = 0; while( true ) { if( dType.getCore()==cType.getCore() ) {// if they represents the same object, if( (constraint&derivationMethod)==0 ) // this substitution doesn't violate blocking constraint. return true; else // it is rejected by the blocking constraint return false; } derivationMethod |= dType.getDerivationMethod(); constraint |= dType.getBlockValue(); if( dType.getCore()==complexUrType ) { // error: substitution group has to be related by types. reportError( new Locator[]{getDeclaredLocationOf(c),getDeclaredLocationOf(d)}, ERR_UNRELATED_TYPES_IN_SUBSTITUTIONGROUP, new Object[]{c.name, d.name} ); return false; } dType = dType.getBaseType(); /* TODO: thre is a bug in the spec. According to the "SCC:Element Declaration Properties Correct", clause 3, the type of the substitution group head and the type of this element declaration has to be related to through "Type Derivation OK". Now assume that the type of the head is union of int and token, and the type of this declaration is int. These two types satisfies the constraint imposed on "Type Derivation OK". Let's move to the "SCC:Substitution Group OK (Transitive)". Now the problem arises. According to the clause 3, it is assumed that there is a chain of derivation from union(int,token) to int, but there is no such thing! The decision here is to reject them as errors. But it may be better to allow them. */ } } protected String localizeMessage( String propertyName, Object[] args ) { String format; try { format = ResourceBundle.getBundle("com.sun.msv.reader.xmlschema.Messages").getString(propertyName); } catch( Exception e ) { format = ResourceBundle.getBundle("com.sun.msv.reader.Messages").getString(propertyName); } return MessageFormat.format(format, args ); } public static final String ERR_MAXOCCURS_IS_NECESSARY = // arg:0 "XMLSchemaReader.MaxOccursIsNecessary"; public static final String ERR_UNIMPLEMENTED_FEATURE = // arg:1 "XMLSchemaReader.UnimplementedFeature"; public static final String ERR_UNDECLARED_PREFIX = // arg:1 "XMLSchemaReader.UndeclaredPrefix"; public static final String ERR_INCONSISTENT_TARGETNAMESPACE = // arg:2 "XMLSchemaReader.InconsistentTargetNamespace"; public static final String ERR_IMPORTING_SAME_NAMESPACE = // arg:1 "XMLSchemaReader.ImportingSameNamespace"; public static final String ERR_DUPLICATE_SCHEMA_DEFINITION = // arg:1 "XMLSchemaReader.DuplicateSchemaDefinition"; public static final String ERR_UNDEFINED_ELEMENTTYPE = // arg:1 "XMLSchemaReader.UndefinedElementType"; public static final String ERR_UNDEFINED_ATTRIBUTE_DECL = "XMLSchemaReader.UndefinedAttributeDecl"; public static final String ERR_UNDEFINED_ATTRIBUTE_GROUP = "XMLSchemaReader.UndefinedAttributeGroup"; public static final String ERR_UNDEFINED_COMPLEX_TYPE = "XMLSchemaReader.UndefinedComplexType"; public static final String ERR_UNDEFINED_SIMPLE_TYPE = "XMLSchemaReader.UndefinedSimpleType"; public static final String ERR_UNDEFINED_COMPLEX_OR_SIMPLE_TYPE = "XMLSchemaReader.UndefinedComplexOrSimpleType"; public static final String ERR_UNDEFINED_ELEMENT_DECL = "XMLSchemaReader.UndefinedElementDecl"; public static final String ERR_UNDEFINED_GROUP = "XMLSchemaReader.UndefinedGroup"; public static final String ERR_UNDEFINED_SCHEMA = "XMLSchemaReader.UndefinedSchema"; public static final String WRN_UNSUPPORTED_ANYELEMENT = // arg:1 "XMLSchemaReader.Warning.UnsupportedAnyElement"; public static final String WRN_OBSOLETED_NAMESPACE = // arg:0 "XMLSchemaReader.Warning.ObsoletedNamespace"; public static final String ERR_UNDEFINED_OR_FORWARD_REFERENCED_TYPE = //arg:1 "XMLSchemaReader.UndefinedOrForwardReferencedType"; public static final String ERR_REDEFINE_UNDEFINED = // arg:1 "XMLSchemaReader.RedefineUndefined"; public static final String ERR_DUPLICATE_ATTRIBUTE_DEFINITION = // arg:1 "XMLSchemaReader.DuplicateAttributeDefinition"; public static final String ERR_DUPLICATE_COMPLEXTYPE_DEFINITION = // arg:1 "XMLSchemaReader.DuplicateComplexTypeDefinition"; public static final String ERR_DUPLICATE_ATTRIBUTE_GROUP_DEFINITION = // arg:1 "XMLSchemaReader.DuplicateAttributeGroupDefinition"; public static final String ERR_DUPLICATE_GROUP_DEFINITION = // arg:1 "XMLSchemaReader.DuplicateGroupDefinition"; public static final String ERR_DUPLICATE_ELEMENT_DEFINITION = // arg:1 "XMLSchemaReader.DuplicateElementDefinition"; public static final String ERR_DUPLICATE_IDENTITY_CONSTRAINT_DEFINITION = // arg:1 "XMLSchemaReader.DuplicateIdentityConstraintDefinition"; public static final String ERR_BAD_XPATH = // arg:1 "XMLSchemaReader.BadXPath"; public static final String ERR_UNDEFINED_KEY = // arg:1 "XMLSchemaReader.UndefinedKey"; public static final String ERR_INVALID_BASETYPE_FOR_SIMPLECONTENT = // arg:1 "XMLSchemaReader.InvalidBasetypeForSimpleContent"; public static final String ERR_KEY_FIELD_NUMBER_MISMATCH = // arg:2 "XMLSchemaReader.KeyFieldNumberMismatch"; public static final String ERR_KEYREF_REFERRING_NON_KEY = // arg:1 "XMLSchemaReader.KeyrefReferringNonKey"; public static final String ERR_UNRELATED_TYPES_IN_SUBSTITUTIONGROUP = // arg:2 "XMLSchemaReader.UnrelatedTypesInSubstitutionGroup"; public static final String ERR_RECURSIVE_SUBSTITUTION_GROUP = // arg:2 "XMLSchemaReader.RecursiveSubstitutionGroup"; public static final String WRN_IMPLICIT_URTYPE_FOR_ELEMENT = // arg:0 "XMLSchemaReader.Warning.ImplicitUrTypeForElement"; public Map getAdditionalNamespaceMap() { return additionalNamespaceMap; } public void setAdditionalNamespaceMap(Map additionalNamespaceMap) { this.additionalNamespaceMap = additionalNamespaceMap; } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/AnyAttributeState.java0000644000175000017500000000336607671170035026124 0ustar giovannigiovanni/* * @(#)$Id: AnyAttributeState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.xmlschema.AttributeDeclExp; import com.sun.msv.grammar.xmlschema.AttributeWildcard; import com.sun.msv.grammar.xmlschema.XMLSchemaSchema; /** * used to parse <anyAttribute > element. * * @author Kohsuke KAWAGUCHI */ public class AnyAttributeState extends AnyState { protected Expression createExpression( final String namespace, final String process ) { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; final XMLSchemaSchema currentSchema = reader.currentSchema; int mode; if(process.equals("skip")) mode = AttributeWildcard.SKIP; else if(process.equals("lax")) mode = AttributeWildcard.LAX; else if(process.equals("strict")) mode = AttributeWildcard.STRICT; else { reader.reportError( XMLSchemaReader.ERR_BAD_ATTRIBUTE_VALUE, "processContents", process ); mode = AttributeWildcard.SKIP; } ((AnyAttributeOwner)parentState).setAttributeWildcard( new AttributeWildcard( getNameClass(namespace,currentSchema), mode ) ); return Expression.epsilon; } protected NameClass getNameClassFrom( ReferenceExp exp ) { return ((AttributeDeclExp)exp).self.nameClass; } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/WSDLSchemaReader.java0000644000175000017500000001240311164025612025505 0ustar giovannigiovannipackage com.sun.msv.reader.xmlschema; import java.io.StringReader; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.xml.XMLConstants; import javax.xml.namespace.NamespaceContext; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.Source; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import com.sun.msv.grammar.xmlschema.XMLSchemaGrammar; import com.sun.msv.reader.GrammarReaderController2; /** * A utility class that reads all the schemas from a WSDL. */ public final class WSDLSchemaReader { private static final class SimpleNamespaceContext implements NamespaceContext { public String getNamespaceURI(String prefix) { if ("xs".equals(prefix)) { return XMLConstants.W3C_XML_SCHEMA_NS_URI; } else { return null; } } public String getPrefix(String namespaceURI) { if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(namespaceURI)) { return "xs"; } else { return null; } } public Iterator getPrefixes(String namespaceURI) { List prefixes = new ArrayList(); if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(namespaceURI)) { prefixes.add("xs"); } return prefixes.iterator(); } } private WSDLSchemaReader() { } /** * Read the schemas from a WSDL. * * @param wsdlSource the WSDL, in any of the TRaX sources. * @param factory a SAX parser factory, used to obtain a SAX parser used internally in the reading * process. * @param controller Object to handle errors, warnings, and provide a resolver for non-local schemas. * @return the MSV grammar. * @throws XPathExpressionException * @throws TransformerException * @throws TransformerConfigurationException */ public static XMLSchemaGrammar read(Source wsdlSource, SAXParserFactory factory, GrammarReaderController2 controller) throws XPathExpressionException, TransformerConfigurationException, TransformerException { TransformerFactory transformerFactory = TransformerFactory.newInstance(); DOMResult wsdlDom = new DOMResult(); transformerFactory.newTransformer().transform(wsdlSource, wsdlDom); Node wsdl = wsdlDom.getNode(); // for the xml schema a:b references to work, // we have to push the wsdl mappings down when not already overriden Map wsdlNamespaceMappings = new HashMap(); Document wsdlDoc = (Document)wsdl; NamedNodeMap attrMap = wsdlDoc.getDocumentElement().getAttributes(); if (attrMap != null) { for (int x = 0; x < attrMap.getLength(); x++) { Attr attr = (Attr)attrMap.item(x); String ns = attr.getNamespaceURI(); if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(ns)) { String localName = attr.getLocalName(); String uri = attr.getValue(); wsdlNamespaceMappings.put(localName, uri); } } } String wsdlSystemId = wsdlSource.getSystemId(); XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(new SimpleNamespaceContext()); Map schemas = new HashMap(); NodeList schemaNodes = (NodeList)xpath.evaluate("//xs:schema", wsdl, XPathConstants.NODESET); for (int x = 0; x < schemaNodes.getLength(); x++) { Element schema = (Element)schemaNodes.item(x); String targetNamespace = schema.getAttribute("targetNamespace"); String systemId = wsdlSystemId + "#" + x; EmbeddedSchema embeddedWSDLSchema = new EmbeddedSchema(systemId, schema); schemas.put(targetNamespace, embeddedWSDLSchema); } WSDLGrammarReaderController wsdlController = new WSDLGrammarReaderController(controller, wsdlSystemId, schemas); XMLSchemaReader reader = new XMLSchemaReader(wsdlController); reader.setAdditionalNamespaceMap(wsdlNamespaceMappings); MultiSchemaReader multiSchemaReader = new MultiSchemaReader(reader); for (EmbeddedSchema schema : schemas.values()) { DOMSource source = new DOMSource(schema.getSchemaElement()); source.setSystemId(schema.getSystemId()); multiSchemaReader.parse(source); } return multiSchemaReader.getResult(); } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/EmbeddedSchema.java0000644000175000017500000000160211164025612025301 0ustar giovannigiovannipackage com.sun.msv.reader.xmlschema; import java.io.StringWriter; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Element; /** * A schema in a DOM Element. This is used in the WSDLSchemaReader to handle * inter-schema cross-references. XS * */ public class EmbeddedSchema { private String systemId; private Element schemaElement; /** * Create object to represent one of the schemas in a WSDL * * @param systemId * schema system Id. * @param schemaElement * Element for the schema. */ public EmbeddedSchema(String systemId, Element schemaElement) { this.systemId = systemId; this.schemaElement = schemaElement; } public String getSystemId() { return systemId; } public Element getSchemaElement() { return schemaElement; } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/IdentityConstraintState.java0000644000175000017500000002323607730143103027335 0ustar giovannigiovanni/* * @(#)$Id: IdentityConstraintState.java 1601 2003-09-11 19:00:19Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import java.util.StringTokenizer; import java.util.Vector; import org.xml.sax.Locator; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.NamespaceNameClass; import com.sun.msv.grammar.SimpleNameClass; import com.sun.msv.grammar.xmlschema.Field; import com.sun.msv.grammar.xmlschema.IdentityConstraint; import com.sun.msv.grammar.xmlschema.KeyConstraint; import com.sun.msv.grammar.xmlschema.KeyRefConstraint; import com.sun.msv.grammar.xmlschema.UniqueConstraint; import com.sun.msv.grammar.xmlschema.XMLSchemaSchema; import com.sun.msv.grammar.xmlschema.XPath; import com.sun.msv.reader.ChildlessState; import com.sun.msv.reader.GrammarReader; import com.sun.msv.reader.SimpleState; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * used to parse <unique>,<key>, and <keyref> element. * * @author Kohsuke KAWAGUCHI */ public class IdentityConstraintState extends SimpleState { protected XPath[] selector; protected final Vector fields = new Vector(); protected State createChildState( StartTagInfo tag ) { if(tag.localName.equals("selector")) { String v = tag.getAttribute("xpath"); if(v!=null) selector = parseSelector(v); else { reader.reportError(XMLSchemaReader.ERR_MISSING_ATTRIBUTE, "selector", "xpath" ); selector = new XPath[0]; // recover by providing a dummy selector } return new ChildlessState(); } if(tag.localName.equals("field")) { String v = tag.getAttribute("xpath"); if(v!=null) fields.add( parseField(v) ); else { reader.reportError(XMLSchemaReader.ERR_MISSING_ATTRIBUTE, "field", "xpath" ); // recover by ignoring this field. } return new ChildlessState(); } return null; } protected void endSelf() { createIdentityConstraint(); super.endSelf(); } protected void createIdentityConstraint() { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; IdentityConstraint id; String name = startTag.getAttribute("name"); if(name==null) { reader.reportError( XMLSchemaReader.ERR_MISSING_ATTRIBUTE, startTag.localName, "name" ); return; // recover by ignoring this constraint. } Field[] fs = (Field[])fields.toArray( new Field[fields.size()] ); if( startTag.localName.equals("key") ) id = new KeyConstraint( reader.currentSchema.targetNamespace, name, selector, fs ); else if( startTag.localName.equals("unique") ) id = new UniqueConstraint( reader.currentSchema.targetNamespace, name, selector, fs ); else if( startTag.localName.equals("keyref") ) { final String refer = startTag.getAttribute("refer"); if(refer==null) { reader.reportError( XMLSchemaReader.ERR_MISSING_ATTRIBUTE, startTag.localName, "refer" ); return; // recover by ignoring this constraint. } final String[] qn = reader.splitQName(refer); if(qn==null) { reader.reportError( XMLSchemaReader.ERR_UNDECLARED_PREFIX, qn ); return; } final KeyRefConstraint keyRef = new KeyRefConstraint( reader.currentSchema.targetNamespace, name, selector, fs ); id = keyRef; // back patch "key" field of KeyRefConstraint. reader.addBackPatchJob( new GrammarReader.BackPatch(){ public State getOwnerState() { return IdentityConstraintState.this; } public void patch() { XMLSchemaSchema s = reader.grammar.getByNamespace(qn[0]); if(s==null) { reader.reportError( XMLSchemaReader.ERR_UNDEFINED_SCHEMA, qn[0] ); return; } IdentityConstraint idc = s.identityConstraints.get(qn[1]); if(idc==null) { reader.reportError( XMLSchemaReader.ERR_UNDEFINED_KEY, refer ); return; } if(!(idc instanceof KeyConstraint )) { reader.reportError( XMLSchemaReader.ERR_KEYREF_REFERRING_NON_KEY, refer ); return; } if( idc.fields.length != keyRef.fields.length ) { reader.reportError( new Locator[]{ getLocation(), reader.getDeclaredLocationOf(idc) }, XMLSchemaReader.ERR_KEY_FIELD_NUMBER_MISMATCH, new Object[]{ idc.localName, new Integer(idc.fields.length), keyRef.localName, new Integer(keyRef.fields.length) } ); return; } keyRef.key = (KeyConstraint)idc; } }); } else // this state can be used only when local name is "key","keyref", or "unique". throw new Error(); if( reader.currentSchema.identityConstraints.get(name)!=null ) { reader.reportError( new Locator[]{ this.location, reader.getDeclaredLocationOf(id) }, XMLSchemaReader.ERR_DUPLICATE_IDENTITY_CONSTRAINT_DEFINITION, new Object[]{name} ); } else { reader.currentSchema.identityConstraints.add(name,id); } reader.setDeclaredLocationOf(id); ((ElementDeclState)parentState).onIdentityConstraint(id); } protected XPath[] parseSelector( String xpath ) { final Vector pathObjs = new Vector(); // split to A|B|C StringTokenizer paths = new StringTokenizer(xpath,"|"); while(paths.hasMoreTokens()) { XPath pathObj = new XPath(); pathObjs.add(pathObj); if(!parsePath(pathObj,paths.nextToken(),false)) return new XPath[0]; } return (XPath[])pathObjs.toArray(new XPath[pathObjs.size()]); } protected Field parseField( String xpath ) { final Vector pathObjs = new Vector(); Field field = new Field(); // split to A|B|C StringTokenizer paths = new StringTokenizer(xpath,"|"); while(paths.hasMoreTokens()) { XPath pathObj = new XPath(); pathObjs.add(pathObj); if(!parsePath(pathObj,paths.nextToken(),true)) return new Field(); // recover by retuning a dummy field. } field.paths = (XPath[])pathObjs.toArray(new XPath[pathObjs.size()]); return field; } /** * parses "aa/bb/cc/.../". * * @return true if it succeeds in parsing. Otherwise false. */ protected boolean parsePath( XPath pathObj, String xpath, boolean parseField ) { final Vector stepObjs = new Vector(); if(xpath.startsWith(".//")) { pathObj.isAnyDescendant = true; xpath = xpath.substring(3); } // split to X/Y/Z StringTokenizer steps = new StringTokenizer(xpath,"/"); stepObjs.clear(); while(steps.hasMoreTokens()) { String step = steps.nextToken(); if( step.equals(".") ) continue; if( step.equals("*") ) { stepObjs.add( NameClass.ALL ); continue; } boolean attribute = false; if( step.charAt(0)=='@' && parseField && !steps.hasMoreTokens()) { // attribute step is allowed only when parsing a field XPath // and as the last token. attribute = true; step = step.substring(1); } // otherwise the following statement will fail to parse this token. // resolve QName. String[] qn = reader.splitQName(step); if(qn==null) { // failed to resolve QName properly reader.reportError( XMLSchemaReader.ERR_BAD_XPATH, step ); return false; } if( attribute && step.indexOf(':')<0 ) qn[0] = ""; // if this is an attribute and step is NCName, // then its namespace URI is "", rather than the // default namespace. NameClass nc; // TODO: NCName test. if( qn[1].equals("*") ) nc = new NamespaceNameClass(qn[0]); else nc = new SimpleNameClass(qn[0],qn[1]); if( attribute==true ) pathObj.attributeStep = nc; else stepObjs.add(nc); } pathObj.steps = (NameClass[])stepObjs.toArray(new NameClass[stepObjs.size()]); return true; } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/AnyAttributeOwner.java0000644000175000017500000000125707671170035026133 0ustar giovannigiovanni/* * @(#)$Id: AnyAttributeOwner.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import com.sun.msv.grammar.xmlschema.AttributeWildcard; /** * A state that can have <anyAttribute > element must implement this interface. * * @author Kohsuke KAWAGUCHI */ public interface AnyAttributeOwner { /** * Sets the attribtue wildcard. */ void setAttributeWildcard( AttributeWildcard local ); } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/ElementDeclState.java0000644000175000017500000002674510034315204025662 0ustar giovannigiovanni/* * @(#)$Id: ElementDeclState.java 1634 2004-04-05 17:42:28Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import java.util.Vector; import org.xml.sax.Locator; import com.sun.msv.datatype.xsd.BooleanType; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.SimpleNameClass; import com.sun.msv.grammar.xmlschema.ElementDeclExp; import com.sun.msv.grammar.xmlschema.IdentityConstraint; import com.sun.msv.grammar.xmlschema.XMLSchemaSchema; import com.sun.msv.reader.ExpressionWithChildState; import com.sun.msv.reader.GrammarReader; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; import com.sun.msv.util.StringPair; /** * used to parse <element > element without ref attribute. * * this state uses ExpressionWithChildState to collect content model * of this element declaration. * * @author Kohsuke KAWAGUCHI */ public class ElementDeclState extends ExpressionWithChildState { protected State createChildState( StartTagInfo tag ) { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; // type declaration is allowed only when we haven't seen type definition. if( super.exp==null ) { if( tag.localName.equals("simpleType") ) return reader.sfactory.simpleType(this,tag); if( tag.localName.equals("complexType") ) return reader.sfactory.complexTypeDecl(this,tag); } // unique/key/keyref are ignored. if( tag.localName.equals("unique") ) return reader.sfactory.unique(this,tag); if( tag.localName.equals("key") ) return reader.sfactory.key(this,tag); if( tag.localName.equals("keyref") ) return reader.sfactory.keyref(this,tag); return null; } protected Expression initialExpression() { // if element has type attribute, then // it shall be used as content type. String typeQName = startTag.getAttribute("type"); if( typeQName==null ) return null; return resolveTypeRef(typeQName); } /** * If this element declaration has @type, then this method * is called to resolve it. * * Since the type refered to may not be processed yet, * a late binding is needed here. */ protected Expression resolveTypeRef( final String typeQName ) { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; // TODO: shall I memorize this as a backward reference? // reader.backwardReference.memorizeLink(???); // symbol may not be defined at this moment. // so just return an empty ReferenceExp and back-patch the actual definition later. final ReferenceExp ref = new ReferenceExp("elementType("+typeQName+")"); final String[] s = reader.splitQName(typeQName); if(s==null) { reader.reportError( XMLSchemaReader.ERR_UNDECLARED_PREFIX, typeQName ); ref.exp = Expression.nullSet; // recover by setting a dummy definition. return ref; } reader.addBackPatchJob( new GrammarReader.BackPatch(){ public State getOwnerState() { return ElementDeclState.this; } public void patch() { Expression e=null; if( reader.isSchemaNamespace(s[0]) ) // datatypes of XML Schema part 2 e = reader.resolveBuiltinSimpleType(s[1]); if(e==null) { XMLSchemaSchema g = reader.getOrCreateSchema(s[0]/*uri*/); e = g.simpleTypes.get(s[1]/*local name*/); if(e==null) e = g.complexTypes.get(s[1]); if(e==null ) { // both simpleType and complexType are undefined. reader.reportError( XMLSchemaReader.ERR_UNDEFINED_ELEMENTTYPE, typeQName ); e = Expression.nullSet; // recover by dummy definition. } } ref.exp = e; } }); return ref; } protected Expression castExpression( Expression halfCastedExpression, Expression newChildExpression ) { if( halfCastedExpression!=null ) // assertion failed: // createChildState shouldn't allow parsing child // if one is already present. throw new Error(); return newChildExpression; } protected Expression defaultExpression() { if( startTag.containsAttribute("substitutionGroup") ) reader.reportError( XMLSchemaReader.ERR_UNIMPLEMENTED_FEATURE, "omitting type attribute in element with substitutionGroup attribute"); // recover by assuming ur-type. // if no content model is given, then this element type is ur-type. // TODO: confirm it. final XMLSchemaReader reader = (XMLSchemaReader)this.reader; reader.reportWarning( XMLSchemaReader.WRN_IMPLICIT_URTYPE_FOR_ELEMENT, null ); return reader.complexUrType; } protected Expression annealExpression(Expression contentType) { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; String name = startTag.getAttribute("name"); if( name==null ) { reader.reportError( XMLSchemaReader.ERR_MISSING_ATTRIBUTE, "element", "name" ); // recover by abandoning this element. return Expression.nullSet; } String targetNamespace; if( isGlobal() ) // TODO: form attribute is prohibited at toplevel. targetNamespace = reader.currentSchema.targetNamespace; else // in local attribute declaration, // targetNamespace is affected by @form and schema's @attributeFormDefault. targetNamespace = ((XMLSchemaReader)reader).resolveNamespaceOfElementDecl( startTag.getAttribute("form") ); // TODO: better way to handle the "fixed" attribtue. String fixed = startTag.getAttribute("fixed"); if( fixed!=null ) // TODO: is this 'fixed' value should be added through enumeration facet? // TODO: check if content model is a simpleType. contentType = reader.pool.createValue( com.sun.msv.datatype.xsd.TokenType.theInstance, new StringPair("","token"), fixed ); // emulate RELAX NG built-in token type ElementDeclExp decl; if( isGlobal() ) { decl = reader.currentSchema.elementDecls.getOrCreate(name); if( decl.getElementExp()!=null ) reader.reportError( new Locator[]{this.location,reader.getDeclaredLocationOf(decl)}, XMLSchemaReader.ERR_DUPLICATE_ELEMENT_DEFINITION, new Object[]{name} ); } else { // create a local object. decl = new ElementDeclExp(reader.currentSchema,null); } reader.setDeclaredLocationOf(decl); ElementDeclExp.XSElementExp exp = decl.new XSElementExp( new SimpleNameClass(targetNamespace,name), contentType ); // set the body. decl.setElementExp(exp); // set identity constraints exp.identityConstraints.addAll(idcs); // process the nillable attribute. String nillable = startTag.getAttribute("nillable"); if( nillable!=null ) decl.isNillable = nillable.equals("true") || nillable.equals("1"); // process the "abstract" attribute. String abstract_ = startTag.getAttribute("abstract"); decl.setAbstract( "true".equals(abstract_)||"1".equals(abstract_) ); if( abstract_!=null && !BooleanType.theInstance.isValid(abstract_,null) ) // recover by assuming false. reader.reportError( XMLSchemaReader.ERR_BAD_ATTRIBUTE_VALUE, "abstract", abstract_ ); // TODO: abstract is prohibited for the local element. // TODO: substitutionGroup is also prohibited for the local element. String substitutionGroupQName = startTag.getAttribute("substitutionGroup"); if( substitutionGroupQName!=null ) { String[] r = reader.splitQName(substitutionGroupQName); if(r==null) { reader.reportError( XMLSchemaReader.ERR_UNDECLARED_PREFIX, substitutionGroupQName ); // recover by ignoring substitutionGroup. } else { // register this declaration to the head elementDecl. ElementDeclExp head = reader.getOrCreateSchema(r[0]/*uri*/). elementDecls.getOrCreate(r[1]/*local name*/); decl.substitutionAffiliation = head; // before adding this "decl" to "head.substitutions", // we need to check the block attribute of various related components. // Therefore, this process is done at the wrapUp method of XMLSchemaReader. } } String block = startTag.getAttribute("block"); if(block==null) block = reader.blockDefault; if(block!=null) { if( block.indexOf("#all")>=0 ) decl.block |= ElementDeclExp.ALL; if( block.indexOf("extension")>=0 ) decl.block |= ElementDeclExp.EXTENSION; if( block.indexOf("restriction")>=0 ) decl.block |= ElementDeclExp.RESTRICTION; if( block.indexOf("substitution")>=0 ) decl.block |= ElementDeclExp.SUBSTITUTION; } String finalValue = startTag.getAttribute("final"); if(finalValue==null) finalValue = reader.finalDefault; if(finalValue!=null) { if( finalValue.indexOf("#all")>=0 ) decl.finalValue |= ElementDeclExp.ALL; if( finalValue.indexOf("extension")>=0 ) decl.finalValue |= ElementDeclExp.EXTENSION; if( finalValue.indexOf("restriction")>=0 ) decl.finalValue |= ElementDeclExp.RESTRICTION; } // minOccurs/maxOccurs is processed through interception // call the hook to let derived classes modify the content model return annealDeclaration(decl); } /** * This method is called after this class finishes augmenting * ElementDeclExp. Derived classes can override this method * and modify an ElementDeclExp further. */ protected Expression annealDeclaration( ElementDeclExp exp ) { return exp; } /** * Returns true if this element declaration is a global element declaration. */ public boolean isGlobal() { return parentState instanceof GlobalDeclState; } /** identity constraints found in this element. */ protected final Vector idcs = new Vector(); /** this method is called when an identity constraint declaration is found. */ protected void onIdentityConstraint( IdentityConstraint idc ) { idcs.add(idc); } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/SchemaIncludedState.java0000644000175000017500000001351211156723336026354 0ustar giovannigiovanni/* * @(#)$Id: SchemaIncludedState.java 1741 2009-03-14 12:45:18Z bimargulies $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import java.util.HashSet; import java.util.Set; import com.sun.msv.reader.IgnoreState; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * used to parse <schema> element of included schema. * * @author Kohsuke KAWAGUCHI */ public class SchemaIncludedState extends GlobalDeclState { /** * target namespace that the caller expects. * * If this field is null, that indicates caller doesn't * expect particular target namespace. * * If this field is non-null and schema element has a different * value as targetNamespace, then error will be reported. */ protected String expectedTargetNamespace; protected SchemaIncludedState( String expectedTargetNamespace ) { this.expectedTargetNamespace = expectedTargetNamespace; } // these fields keep the previous values. private String previousElementFormDefault; private String previousAttributeFormDefault; private String previousFinalDefault; private String previousBlockDefault; private String previousChameleonTargetNamespace; /** * this flag is set to true to indicate all the contents of this element * will be skipped (due to the double inclusion). */ private boolean ignoreContents = false; protected State createChildState( StartTagInfo tag ) { if( ignoreContents ) return new IgnoreState(); else return super.createChildState(tag); } protected void startSelf() { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; super.startSelf(); // back up the current values previousElementFormDefault = reader.elementFormDefault; previousAttributeFormDefault = reader.attributeFormDefault; previousFinalDefault = reader.finalDefault; previousBlockDefault = reader.blockDefault; previousChameleonTargetNamespace = reader.chameleonTargetNamespace; // the chameleonTargetNamespace is usually null, unless we are parsing // a chameleon schema. reader.chameleonTargetNamespace = null; String targetNs = startTag.getAttribute("targetNamespace"); if( targetNs==null ) { if( expectedTargetNamespace==null ) { // this is not an error. It just means that the target namespace is absent. // reader.reportError( reader.ERR_MISSING_ATTRIBUTE, "schema", "targetNamespace" ); targetNs = ""; // recover by assuming "" namespace. } else { // this is a chameleon schema. targetNs = expectedTargetNamespace; reader.chameleonTargetNamespace = expectedTargetNamespace; } } else { if( expectedTargetNamespace!=null && !expectedTargetNamespace.equals(targetNs) ) reader.reportError( XMLSchemaReader.ERR_INCONSISTENT_TARGETNAMESPACE, targetNs, expectedTargetNamespace ); // recover by adopting the one specified in the schema. } // check double inclusion. Set s = reader.parsedFiles.get(targetNs); if(s==null) { reader.parsedFiles.put( targetNs, s = new HashSet() ); } if( s.contains(this.location.getSystemId()) ) { // this file is already included. So skip processing it. ignoreContents = true; } else { s.add(this.location.getSystemId()); } /* * onTargetNamespace complains if we've seen this schema before, so we * cannot call it before establishing ignoreContents. */ onTargetNamespaceResolved(targetNs, ignoreContents); // process other attributes. String form; form = startTag.getDefaultedAttribute("elementFormDefault","unqualified"); if( form.equals("qualified") ) reader.elementFormDefault = targetNs; else { reader.elementFormDefault = ""; if( !form.equals("unqualified") ) reader.reportError( XMLSchemaReader.ERR_BAD_ATTRIBUTE_VALUE, "elementFormDefault", form ); } form = startTag.getDefaultedAttribute("attributeFormDefault","unqualified"); if( form.equals("qualified") ) reader.attributeFormDefault = targetNs; else { reader.attributeFormDefault = ""; if( !form.equals("unqualified") ) reader.reportError( XMLSchemaReader.ERR_BAD_ATTRIBUTE_VALUE, "attributeFormDefault", form ); } reader.finalDefault = startTag.getAttribute("finalDefault"); reader.blockDefault = startTag.getAttribute("blockDefault"); } /** * This is called when the target namespace is determined for a new schema. * @param targetNs namespace of the schema * @param ignoreContents TODO */ protected void onTargetNamespaceResolved( String targetNs, boolean ignoreContents ) { } protected void endSelf() { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; reader.elementFormDefault = previousElementFormDefault; reader.attributeFormDefault = previousAttributeFormDefault; reader.finalDefault = previousFinalDefault; reader.blockDefault = previousBlockDefault; reader.chameleonTargetNamespace = previousChameleonTargetNamespace; super.endSelf(); } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/ElementRefState.java0000644000175000017500000000305307671170035025530 0ustar giovannigiovanni/* * @(#)$Id: ElementRefState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ReferenceContainer; import com.sun.msv.grammar.xmlschema.XMLSchemaSchema; import com.sun.msv.reader.ExpressionWithoutChildState; /** * used to parse <element > element with ref attribute. * * @author Kohsuke KAWAGUCHI */ public class ElementRefState extends ExpressionWithoutChildState { protected Expression makeExpression() { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; // TODO: what attributes can be used with @ref? if( !startTag.containsAttribute("ref") ) // existance of @ref must be checked before instanciation of this object. throw new Error(); // this this tag has @ref. Expression exp = reader.resolveQNameRef( startTag, "ref", new XMLSchemaReader.RefResolver() { public ReferenceContainer get( XMLSchemaSchema g ) { return g.elementDecls; } } ); if( exp==null ) return Expression.epsilon; // couldn't resolve QName. // minOccurs/maxOccurs is processed through interception return exp; } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/DOMLSInputImpl.java0000644000175000017500000000544411164025612025217 0ustar giovannigiovanni/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.sun.msv.reader.xmlschema; import java.io.InputStream; import java.io.Reader; import org.w3c.dom.Element; import org.w3c.dom.ls.LSInput; import com.sun.msv.reader.DOMLSInput; /** * implementation class for an LSInput where the only data source is an existing DOM element. */ public class DOMLSInputImpl implements LSInput, DOMLSInput { private String baseURI; private String systemId; private Element element; public DOMLSInputImpl(String baseURI, String systemId, Element data) { this.baseURI = baseURI; this.element = data; this.systemId = systemId; } public String getBaseURI() { return baseURI; } public InputStream getByteStream() { return null; } public boolean getCertifiedText() { return false; } public Reader getCharacterStream() { return null; } public String getEncoding() { return null; } public String getPublicId() { return null; } public String getStringData() { return null; } public String getSystemId() { return systemId; } public void setBaseURI(String baseURI) { this.baseURI = baseURI; } public void setByteStream(InputStream byteStream) { throw new UnsupportedOperationException(); } public void setCertifiedText(boolean certifiedText) { throw new UnsupportedOperationException(); } public void setCharacterStream(Reader characterStream) { throw new UnsupportedOperationException(); } public void setEncoding(String encoding) { throw new UnsupportedOperationException(); } public void setPublicId(String publicId) { throw new UnsupportedOperationException(); } public void setStringData(String stringData) { throw new UnsupportedOperationException(); } public void setSystemId(String systemId) { this.systemId = systemId; } public Element getElement() { return element; } }msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/package.html0000644000175000017500000000014707272342147024122 0ustar giovannigiovanni

      parses XML representation of XML Schema into AGM.

      msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/GlobalDeclState.java0000644000175000017500000000642607671170035025501 0ustar giovannigiovanni/* * @(#)$Id: GlobalDeclState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.xmlschema.SimpleTypeExp; import com.sun.msv.reader.ExpressionOwner; import com.sun.msv.reader.SimpleState; import com.sun.msv.reader.State; import com.sun.msv.reader.datatype.xsd.XSDatatypeExp; import com.sun.msv.reader.datatype.xsd.XSTypeOwner; import com.sun.msv.util.StartTagInfo; /** * State that parses global declarations. * * @author Kohsuke KAWAGUCHI */ public class GlobalDeclState extends SimpleState implements ExpressionOwner,XSTypeOwner { protected State createChildState( StartTagInfo tag ) { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; if(tag.localName.equals("include")) return reader.sfactory.include(this,tag); if(tag.localName.equals("import")) return reader.sfactory.import_(this,tag); if(tag.localName.equals("redefine")) return reader.sfactory.redefine(this,tag); if(tag.localName.equals("simpleType")) return reader.sfactory.simpleType(this,tag); if(tag.localName.equals("complexType")) return reader.sfactory.complexTypeDecl(this,tag); if(tag.localName.equals("group")) return reader.sfactory.group(this,tag); if(tag.localName.equals("attributeGroup")) return reader.sfactory.attributeGroup(this,tag); if(tag.localName.equals("element")) return reader.sfactory.elementDecl(this,tag); if(tag.localName.equals("attribute")) return reader.sfactory.attribute(this,tag); if(tag.localName.equals("notation")) return reader.sfactory.notation(this,tag); return null; } public String getTargetNamespaceUri() { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; return reader.currentSchema.targetNamespace; } // do nothing. declarations register themselves by themselves. public void onEndChild( Expression exp ) {} public void onEndChild( XSDatatypeExp type ) { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; // final XSDatatypeImpl dti = (XSDatatypeImpl)type; // final String typeName = dti.getName(); String typeName = reader.getCurrentState().getStartTag().getAttribute("name"); if( typeName==null ) { // top-level simpleType must define a named type reader.reportError( XMLSchemaReader.ERR_MISSING_ATTRIBUTE, "simpleType", "name" ); return; // recover by ignoring this declaration } // memorize this type. final SimpleTypeExp exp = reader.currentSchema.simpleTypes.getOrCreate(typeName); if(exp.getType()!=null ) { reader.reportError( XMLSchemaReader.ERR_DATATYPE_ALREADY_DEFINED, typeName ); return; // recover by ignoring this declaration } exp.set(type); reader.setDeclaredLocationOf(exp); } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/SimpleContentExtensionState.java0000644000175000017500000001117007671170035030162 0ustar giovannigiovanni/* * @(#)$Id: SimpleContentExtensionState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import com.sun.msv.datatype.xsd.XSDatatype; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.xmlschema.AttributeWildcard; import com.sun.msv.grammar.xmlschema.ComplexTypeExp; import com.sun.msv.grammar.xmlschema.SimpleTypeExp; import com.sun.msv.grammar.xmlschema.XMLSchemaSchema; import com.sun.msv.reader.GrammarReader; import com.sun.msv.reader.SequenceState; import com.sun.msv.reader.State; import com.sun.msv.reader.datatype.xsd.XSDatatypeExp; import com.sun.msv.util.StartTagInfo; /** * used to parse extension element as a child of <simpleContent> element. * * @author Kohsuke KAWAGUCHI */ public class SimpleContentExtensionState extends SequenceState implements AnyAttributeOwner { /** ComplexType object that we are now constructing. */ protected ComplexTypeExp parentDecl; protected SimpleContentExtensionState( ComplexTypeExp parentDecl ) { this.parentDecl = parentDecl; } public void setAttributeWildcard( AttributeWildcard local ) { parentDecl.wildcard = local; } protected State createChildState( StartTagInfo tag ) { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; return reader.createAttributeState(this,tag); } protected Expression initialExpression() { // without this statement, // without any attribute will be prohibited. return Expression.epsilon; } protected Expression annealExpression( Expression exp ) { parentDecl.derivationMethod = ComplexTypeExp.EXTENSION; return reader.pool.createSequence( super.annealExpression(exp), getBody()); } /** * Gets the expression for the base type. */ private Expression getBody() { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; final String base = startTag.getAttribute("base"); if(base==null) { // in extension, base attribute must is mandatory. reader.reportError( XMLSchemaReader.ERR_MISSING_ATTRIBUTE, startTag.localName, "base"); return Expression.nullSet; } final String[] baseTypeName = reader.splitQName(base); if( baseTypeName==null ) { reader.reportError( XMLSchemaReader.ERR_UNDECLARED_PREFIX, base ); return Expression.nullSet; } // we need a special handling for built-in types if(reader.isSchemaNamespace(baseTypeName[0])) { XSDatatype dt = reader.resolveBuiltinDataType(baseTypeName[1]); if(dt!=null) { XSDatatypeExp dtexp = new XSDatatypeExp(dt,reader.pool); parentDecl.simpleBaseType = dtexp; return dtexp; } // maybe we are parsing the schema for schema. // consult externally specified schema. } final XMLSchemaSchema schema = reader.grammar.getByNamespace(baseTypeName[0]); // we don't know whether it's a complex type or a simple type. // so back patch it final ReferenceExp ref = new ReferenceExp(null); reader.addBackPatchJob( new GrammarReader.BackPatch(){ public State getOwnerState() { return SimpleContentExtensionState.this; } public void patch() { SimpleTypeExp sexp = schema.simpleTypes.get(baseTypeName[1]); if(sexp!=null) { // we've found the simple type ref.exp = sexp; parentDecl.simpleBaseType = sexp.getType(); _assert(parentDecl.simpleBaseType!=null); return; } ComplexTypeExp cexp = schema.complexTypes.get(baseTypeName[1]); if(cexp!=null) { // we've found the complex type as the base type ref.exp = cexp.body; parentDecl.complexBaseType = cexp; return; } // there is no base type. reader.reportError( XMLSchemaReader.ERR_UNDEFINED_COMPLEX_OR_SIMPLE_TYPE, base ); } }); return ref; } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/Messages_ja.properties0000644000175000017500000001604007432374002026170 0ustar giovannigiovanni## abstract error messages defined for XML Schema GrammarReader.Abstract.MissingChildExpression =\ \u5B50\u30B3\u30F3\u30C6\u30F3\u30C8\u30E2\u30C7\u30EB\u304C\u3042\u308A\u307E\u305B\u3093 GrammarReader.Abstract.MoreThanOneChildExpression =\ \u8907\u6570\u306E\u30B3\u30F3\u30C6\u30F3\u30C8\u30E2\u30C7\u30EB\u304C\u6307\u5B9A\u3055\u308C\u3066\u3044\u307E\u3059 GrammarReader.Abstract.RunAwayExpression =\ \u30E2\u30C7\u30EB\u30B0\u30EB\u30FC\u30D7\u5B9A\u7FA9\u304C\u5FAA\u74B0\u53C2\u7167\u3092\u8D77\u3053\u3057\u3066\u3044\u307E\u3059 ( {0} ) GrammarReader.Abstract.MissingTopLevel =\ @@@\u3053\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u306F\u4F7F\u308F\u308C\u306A\u3044\u306F\u305A@@@ ## XML Schema reader error messages XMLSchemaReader.MaxOccursIsNecessary =\ minOccurs\u5C5E\u6027\u304C\uFF11\u3088\u308A\u5927\u304D\u3044\u306E\u3067maxOccurs\u5C5E\u6027\u304C\u5FC5\u8981\u3067\u3059 XMLSchemaReader.UnimplementedFeature =\ \u672A\u30B5\u30DD\u30FC\u30C8\u306E\u6A5F\u80FD\u3067\u3059: "{0}" XMLSchemaReader.UndeclaredPrefix =\ namespace prefix "{0}"\u306F\u5BA3\u8A00\u3055\u308C\u3066\u3044\u307E\u305B\u3093 XMLSchemaReader.InconsistentTargetNamespace =\ \u30B9\u30AD\u30FC\u30DE\u306Etarget namespace\u3068\u3057\u3066"{0}"\u304C\u6307\u5B9A\u3055\u308C\u3066\u3044\u307E\u3059\u304C\u3001\u547C\u3073\u51FA\u3057\u5074\u306F"{1}"\u3092\u671F\u5F85\u3057\u3066\u3044\u307E\u3059 XMLSchemaReader.ImportingSameNamespace =\ \u540C\u3058\u540D\u524D\u7A7A\u9593\u306B\u5C5E\u3059\u308B\u30B9\u30AD\u30FC\u30DE\u3092import\u3057\u3066\u3044\u307E\u3059 XMLSchemaReader.DuplicateSchemaDefinition =\ \u540D\u524D\u7A7A\u9593"{0}"\u306F\u65E2\u306B\u5225\u306E\u30B9\u30AD\u30FC\u30DE\u306B\u3088\u3063\u3066\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u3059 XMLSchemaReader.UndefinedElementType =\ simple type\u306B\u3082complex type\u306B\u3082\u578B"{0}"\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093 XMLSchemaReader.UndefinedAttributeDecl = \ \u5B9A\u7FA9\u3055\u308C\u3066\u3044\u306A\u3044\u5C5E\u6027\u5BA3\u8A00"{0}"\u3092\u53C2\u7167\u3057\u3066\u3044\u307E\u3059 XMLSchemaReader.UndefinedAttributeGroup = \ \u5B9A\u7FA9\u3055\u308C\u3066\u3044\u306A\u3044\u5C5E\u6027\u30B0\u30EB\u30FC\u30D7"{0}"\u3092\u53C2\u7167\u3057\u3066\u3044\u307E\u3059 XMLSchemaReader.UndefinedComplexType = \ \u5B9A\u7FA9\u3055\u308C\u3066\u3044\u306A\u3044complex type"{0}"\u3092\u53C2\u7167\u3057\u3066\u3044\u307E\u3059 XMLSchemaReader.UndefinedSimpleType = \ \u5B9A\u7FA9\u3055\u308C\u3066\u3044\u306A\u3044simple type"{0}"\u3092\u53C2\u7167\u3057\u3066\u3044\u307E\u3059 XMLSchemaReader.UndefinedElementDecl = \ \u5B9A\u7FA9\u3055\u308C\u3066\u3044\u306A\u3044\u8981\u7D20\u5BA3\u8A00"{0}"\u3092\u53C2\u7167\u3057\u3066\u3044\u307E\u3059 XMLSchemaReader.UndefinedGroup = \ \u5B9A\u7FA9\u3055\u308C\u3066\u3044\u306A\u3044\u30B0\u30EB\u30FC\u30D7"{0}"\u3092\u53C2\u7167\u3057\u3066\u3044\u307E\u3059 XMLSchemaReader.UndefinedComplexOrSimpleType = \ \u5B9A\u7FA9\u3055\u308C\u3066\u3044\u306A\u3044complex type\u3082\u3057\u304F\u306Fsimple type "{0}"\u3092\u53C2\u7167\u3057\u3066\u3044\u307E\u3059 XMLSchemaReader.UndefinedKey = \ \u5B9A\u7FA9\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC"{0}"\u3092\u53C2\u7167\u3057\u3066\u3044\u307E\u3059 XMLSchemaReader.UndefinedSchema = \ \u540D\u524D\u7A7A\u9593"{0}"\u3092\u53C2\u7167\u3057\u3066\u3044\u307E\u3059\u304C\u3001\u3053\u306E\u540D\u524D\u7A7A\u9593\u3092\u5B9A\u7FA9\u3059\u308B\u30B9\u30AD\u30FC\u30DE\u304C\u3042\u308A\u307E\u305B\u3093 XMLSchemaReader.InvalidBasetypeForSimpleContent = \ \u30B7\u30F3\u30D7\u30EB\u30B3\u30F3\u30C6\u30F3\u30C8\u3092\u6301\u3064\u30B3\u30F3\u30D7\u30EC\u30C3\u30AF\u30B9\u30BF\u30A4\u30D7\u306E\u30D9\u30FC\u30B9\u30BF\u30A4\u30D7\u3068\u3057\u3066\u306F"{0}"\u306F\u4E0D\u9069\u5207\u3067\u3059 XMLSchemaReader.Warning.UnsupportedAnyElement = \ anyElement processContents="{0}"\u306F\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002skip\u3068\u307F\u306A\u3057\u307E\u3059 XMLSchemaReader.Warning.ObsoletedNamespace = \ "http://www.w3.org/2000/10/XMLSchema"\u306F\u53E4\u3044\u540D\u524D\u7A7A\u9593\u3067\u3059\u3002"http://www.w3.org/2001/XMLSchema"\u3092\u4F7F\u3063\u3066\u304F\u3060\u3055\u3044 XMLSchemaReader.UndefinedOrForwardReferencedType = \ "{0}"\u306F\u672A\u5B9A\u7FA9\u304B\u3001\u3082\u3057\u304F\u306F\u3053\u308C\u304B\u3089\u5B9A\u7FA9\u3055\u308C\u308B\u578B\u3067\u3059\u3002simple type\u306E\u524D\u65B9\u53C2\u7167\u306F\u30B5\u30DD\u30FC\u30C8\u3057\u3066\u3044\u307E\u305B\u3093 XMLSchemaReader.RedefineUndefined = \ \u30B3\u30F3\u30DD\u30FC\u30CD\u30F3\u30C8"{0}"\u3092redefine\u3057\u3088\u3046\u3068\u3057\u3066\u3044\u307E\u3059\u304C\u3001\u305D\u3082\u305D\u3082\u5143\u5B9A\u7FA9\u304C\u3042\u308A\u307E\u305B\u3093 XMLSchemaReader.DuplicateAttributeDefinition = \ \u5C5E\u6027\u5BA3\u8A00"{0}"\u306F\u65E2\u306B\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u3059 XMLSchemaReader.DuplicateComplexTypeDefinition = \ complex type "{0}"\u306F\u65E2\u306B\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u3059 XMLSchemaReader.DuplicateAttributeGroupDefinition = \ \u5C5E\u6027\u30B0\u30EB\u30FC\u30D7"{0}"\u306F\u65E2\u306B\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u3059 XMLSchemaReader.DuplicateGroupDefinition = \ \u30B0\u30EB\u30FC\u30D7"{0}"\u306F\u65E2\u306B\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u3059 XMLSchemaReader.DuplicateElementDefinition = \ \u8981\u7D20\u5BA3\u8A00"{0}"\u306F\u65E2\u306B\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u3059 XMLSchemaReader.DuplicateIdentityConstraintDefinition = \ \u4E00\u610F\u6027\u5236\u7D04"{0}"\u306F\u65E2\u306B\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u3059 XMLSchemaReader.BadXPath = \ XPath\u304C\u9593\u9055\u3063\u3066\u3044\u307E\u3059: {0} XMLSchemaReader.KeyrefReferringNonKey = \ "{0}"\u306F\u30AD\u30FC\u306E\u540D\u524D\u3067\u306F\u3042\u308A\u307E\u305B\u3093 XMLSchemaReader.KeyFieldNumberMismatch = \ \u53C2\u7167\u3057\u3066\u3044\u308B\u30AD\u30FC"{0}"\u306B\u306F\u30D5\u30A3\u30FC\u30EB\u30C9\u304C{1}\u500B\u3042\u308A\u307E\u3059\u304C\u3001\u30AD\u30FC\u53C2\u7167"{2}"\u306B\u306F{3}\u500B\u3057\u304B\u3042\u308A\u307E\u305B\u3093 XMLSchemaReader.UnrelatedTypesInSubstitutionGroup = \ \u8981\u7D20\u5BA3\u8A00"{0}"\u306E\u7F6E\u63DB\u7FA4\u306E\u4E2D\u306B\u8981\u7D20\u5BA3\u8A00"{1}"\u304C\u542B\u307E\u308C\u3066\u3044\u307E\u3059\u304C\u3001\ \u4E92\u3044\u306E\u578B\u306B\u95A2\u9023\u304C\u3042\u308A\u307E\u305B\u3093\u3002 XMLSchemaReader.RecursiveSubstitutionGroup = \ \u8981\u7D20\u5BA3\u8A00"{0}"\u3068"{1}"\u304C\u5FAA\u74B0\u3059\u308B\u7F6E\u63DB\u7FA4(substitution group)\u3092\u69CB\u6210\u3057\u3066\u3044\u307E\u3059 XMLSchemaReader.Warning.ImplicitUrTypeForElement = \ type\u5C5E\u6027\u304C\u306A\u3044\u306E\u3067\u3053\u306E\u8981\u7D20\u306E\u4E2D\u8EAB\u306F\u5168\u304F\u691C\u8A3C\u3055\u308C\u307E\u305B\u3093\u304C\u3001\u610F\u56F3\u3057\u305F\u52D5\u4F5C\u3067\u3057\u3087\u3046\u304B\uFF1F\ \u3082\u3057\u305D\u3046\u306A\u3089\u3001type="anyType"\u3068\u660E\u793A\u7684\u306B\u3053\u308C\u3092\u8A18\u8FF0\u3059\u308B\u3053\u3068\u3092\u304A\u5968\u3081\u3057\u307E\u3059 msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/SchemaState.java0000644000175000017500000000355511156723336024712 0ustar giovannigiovanni/* * @(#)$Id: SchemaState.java 1741 2009-03-14 12:45:18Z bimargulies $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import com.sun.msv.grammar.xmlschema.XMLSchemaSchema; /** * used to parse <schema> element. * * @author Kohsuke KAWAGUCHI */ public class SchemaState extends SchemaIncludedState { protected SchemaState( String expectedTargetNamespace ) { super(expectedTargetNamespace); } private XMLSchemaSchema old; protected void onTargetNamespaceResolved( String targetNs, boolean ignoreContents ) { super.onTargetNamespaceResolved(targetNs, ignoreContents); XMLSchemaReader reader = (XMLSchemaReader)this.reader; // sets new XMLSchemaGrammar object. old = reader.currentSchema; reader.currentSchema = reader.getOrCreateSchema(targetNs); /* * Don't check for errors if this is a redundant read that we are ignoring. */ if (ignoreContents) { return; } if( reader.isSchemaDefined(reader.currentSchema) ) { reader.reportError( XMLSchemaReader.ERR_DUPLICATE_SCHEMA_DEFINITION, targetNs ); // recover by providing dummy grammar object. // this object is not registered to the map, // so it cannot be referenced. reader.currentSchema = new XMLSchemaSchema(targetNs,reader.grammar); } reader.markSchemaAsDefined(reader.currentSchema); } protected void endSelf() { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; reader.currentSchema = old; super.endSelf(); } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/SimpleContentState.java0000644000175000017500000000343607671170035026273 0ustar giovannigiovanni/* * @(#)$Id: SimpleContentState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.xmlschema.ComplexTypeExp; import com.sun.msv.reader.ExpressionWithChildState; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * used to parse <simpleContent> element. * * @author Kohsuke KAWAGUCHI */ public class SimpleContentState extends ExpressionWithChildState { /** ComplexType object that we are now constructing. */ protected ComplexTypeExp parentDecl; protected SimpleContentState( ComplexTypeExp decl ) { this.parentDecl = decl; } protected State createChildState( StartTagInfo tag ) { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; if( super.exp!=null ) // we have already parsed restriction/extension. return null; if( tag.localName.equals("restriction") ) return reader.sfactory.simpleRst(this,tag,parentDecl); if( tag.localName.equals("extension") ) return reader.sfactory.simpleExt(this,tag,parentDecl); return super.createChildState(tag); } protected Expression castExpression( Expression halfCastedExpression, Expression newChildExpression ) { if( halfCastedExpression!=null ) // assertion failed. // this situation should be prevented by createChildState method. throw new Error(); return newChildExpression; } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/RootState.java0000644000175000017500000000145107671170035024425 0ustar giovannigiovanni/* * @(#)$Id: RootState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import com.sun.msv.reader.State; /** * RootIncludedSchemaState + final wrap up. * * @author Kohsuke KAWAGUCHI */ public class RootState extends RootIncludedSchemaState { protected RootState( State topLevelState ) { super(topLevelState); } protected void endSelf() { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; // perform final wrap up. reader.wrapUp(); super.endSelf(); } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/xmlschema.xsd0000644000175000017500000014172207361153644024350 0ustar giovannigiovanni The schema corresponding to this document is normative, with respect to the syntactic constraints it expresses in the XML Schema language. The documentation (within <documentation> elements) below, is not normative, but rather highlights important aspects of the W3C Recommendation of which this is a part The simpleType element and all of its members are defined in datatypes.xsd Get access to the xml: attribute groups for xml:lang as declared on 'schema' and 'documentation' below This type is extended by almost all schema types to allow attributes from other namespaces to be added to user schemas. This type is extended by all types which allow annotation other than <schema> itself This group is for the elements which occur freely at the top level of schemas. All of their types are based on the "annotated" type by extension. This group is for the elements which can self-redefine (see <redefine> below). A utility type, not for public use A utility type, not for public use A utility type, not for public use #all or (possibly empty) subset of {extension, restriction} for maxOccurs for all particles for element, group and attributeGroup, which both define and reference 'complexType' uses this This branch is short for <complexContent> <restriction base="xs:anyType"> ... </restriction> </complexContent> Will be restricted to required or forbidden Not allowed if simpleContent child is chosen. May be overriden by setting on complexContent child. Overrides any setting on complexType parent. No typeDefParticle group reference A utility type, not for public use #all or (possibly empty) subset of {substitution, extension, restriction} The element element can be used either at the top level to define an element-type binding globally, or within a content model to either reference a globally-defined element or type or declare an element-type binding locally. The ref form is not allowed at the top level. group type for explicit groups, named top-level groups and group references Should derive this from realGroup, but too complicated for now group type for the three kinds of group restricted max/min Only elements allowed inside simple type for the value of the 'namespace' attr of 'any' and 'anyAttribute' Value is ##any - - any non-conflicting WFXML/attribute at all ##other - - any non-conflicting WFXML/attribute from namespace other than targetNS ##local - - any unqualified non-conflicting WFXML/attribute one or - - any non-conflicting WFXML/attribute from more URI the listed namespaces references (space separated) ##targetNamespace or ##local may appear in the above list, to refer to the targetNamespace of the enclosing schema or an absent targetNamespace respectively A utility type, not for public use A subset of XPath expressions for use in selectors A utility type, not for public use The following pattern is intended to allow XPath expressions per the following EBNF: Selector ::= Path ( '|' Path )* Path ::= ('.//')? Step ( '/' Step )* Step ::= '.' | NameTest NameTest ::= QName | '*' | NCName ':' '*' child:: is also allowed A subset of XPath expressions for use in fields A utility type, not for public use The following pattern is intended to allow XPath expressions per the same EBNF as for selector, with the following change: Path ::= ('.//')? ( Step '/' )* ( Step | '@' NameTest ) The three kinds of identity constraints, all with type of or derived from 'keybase'. A utility type, not for public use A public identifier, per ISO 8879 notations for use within XML Schema schemas Not the real urType, but as close an approximation as we can get in the XML representation A utility type, not for public use #all or (possibly empty) subset of {restriction, union, list} A utility type, not for public use Can be restricted to required or forbidden Required at the top level Forbidden when nested We should use a substitution group for facets, but that's ruled out because it would allow users to add their own, which we're not ready for yet. base attribute and simpleType child are mutually exclusive, but one or other is required itemType attribute and simpleType child are mutually exclusive, but one or other is required memberTypes attribute must be non-empty or there must be at least one simpleType child msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/RedefinableDeclState.java0000644000175000017500000001067207671170035026477 0ustar giovannigiovanni/* * @(#)$Id: RedefinableDeclState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import com.sun.msv.grammar.ReferenceContainer; import com.sun.msv.grammar.xmlschema.RedefinableExp; import com.sun.msv.reader.ExpressionWithChildState; /** state that parses redefinable declaration. * * "Declarations" are attribute, element, complexType, group, and attributeGroup. * simpleType is treated differently. * *

      * When this state is used under states other than RedefineState, this class * doesn't do anything. When used under RedefineState, this class does several * tricks to make redefinition easy. * *

      * Redefinition is done in the following steps. * *

      Step.1

      *

      * First, say redefinition of declaration "ABC" is found, "ABC" has already * defined once and it is * *

        *
      • referenced from {@link ReferenceContainer} by name, and *
      • referenced from other expressions directly. *
      * * * *

      Step.2

      *

      * In startSelf method, this class clones the current definition, and updates * ReferenceContainer to point to the cloned definition (right side). * * * *

      * Note that other expressions hold direct reference to the original definition * (left side), and these references are not affected by this update. * *

      Step.3

      *

      * Body of redefinition is parsed and corresponding expression is created by * derived class. This step is done no differently. * *

      * Since ReferenceContainer has updated, any reference to this expression found * during this step is bound to the cloned definition. This self reference usually * happens. * *

      Step.4

      *

      * After the body of redefinition is parsed, the original definition (left side) * is updated by using new expression. * * * *

      * From now on, redefinition becomes visible to all expressions that hold * direct reference to the original definition. The cloned definition is kept * as-is so that any self reference found in the body will be maintained correctly. * *

      Step.5

      *

      * Finally, ReferenceContainer is updated again to point to the updated definition. * Therefore successive reference to "ABC" will be bound to the updated definition. * Cloned old definition is kept as-is. * * */ public abstract class RedefinableDeclState extends ExpressionWithChildState { protected boolean isGlobal() { return parentState instanceof GlobalDeclState; } /** * Returns true if this declaration is a redefinition of an * existing declaration. */ protected boolean isRedefine() { return parentState instanceof RedefineState; } /** * keeps a reference to previous declaration. * * this field is used only when in redefine mode. Derived class should use * this declaration instead of getting one from ReferenceContainer through * XMLSchemaSchema. */ protected RedefinableExp oldDecl; /** gets appropriate ReferenceContainer to store this declaration. */ protected abstract ReferenceContainer getContainer(); protected void startSelf() { super.startSelf(); if( isRedefine() ) { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; String name = startTag.getAttribute("name"); if( name==null ) // ignore this error just for now. // this error will be reported in annealExpression method. return; oldDecl = (RedefinableExp)getContainer()._get(name); if(oldDecl==null) { reader.reportError( XMLSchemaReader.ERR_REDEFINE_UNDEFINED, name ); // recover by creating a dummy object. oldDecl = (RedefinableExp)getContainer()._getOrCreate(name); return; } getContainer().redefine( name, oldDecl.getClone() ); } } protected void endSelf() { if( oldDecl!=null ) getContainer().redefine( oldDecl.name, oldDecl ); super.endSelf(); } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/MultiSchemaReader.java0000644000175000017500000000502311156731756026044 0ustar giovannigiovanni/* * @(#)$Id: MultiSchemaReader.java 1743 2009-03-14 13:41:02Z bimargulies $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import javax.xml.transform.Source; import org.xml.sax.InputSource; import org.xml.sax.helpers.LocatorImpl; import com.sun.msv.grammar.xmlschema.XMLSchemaGrammar; import com.sun.msv.util.Util; /** * An utility class that * reads multiple XML Schema documents and combines them into one schema object. * *

      Usage

      *

      * Creates a new instance of {@link XMLSchemaReader}, then pass it to the * constructor of this class. Then call the parse method as many times as you want. * Finally, call the finish method. *

      * The parsed grammar can be obtained from the underlying XMLSchemaReader object. *

      * * @author Kohsuke KAWAGUCHI */ public class MultiSchemaReader { public MultiSchemaReader( XMLSchemaReader _reader ) { this.reader = _reader; reader.setDocumentLocator(new LocatorImpl()); } private final XMLSchemaReader reader; private boolean finalized = false; /** * @deprecated */ public final XMLSchemaReader getReader() { return reader; } /** * Obtains the parsed grammar. */ public final XMLSchemaGrammar getResult() { finish(); return reader.getResult(); } /** * Parse a schema supplied by a javax.xml.transform Source. * @param source */ public void parse(Source source) { reader.switchSource(source, new RootIncludedSchemaState( reader.sfactory.schemaHead(null)) ); } public final void parse( String source ) { parse(Util.getInputSource(source)); } /** * Parses an additional schema. * * The caller can call this method many times to parse * multiple schemas. * * If possible, the caller should set the system Id to the InputSource. */ public void parse( InputSource is ) { reader.switchSource( is, new RootIncludedSchemaState( reader.sfactory.schemaHead(null)) ); } /** * This method should be called when all the schemas are parsed. */ public void finish() { if( !finalized ) { finalized = true; reader.wrapUp(); } } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/AttributeWildcardComputer.java0000644000175000017500000002407307671170035027642 0ustar giovannigiovanni/* * @(#)$Id: AttributeWildcardComputer.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import java.util.HashSet; import java.util.Set; import java.util.Stack; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.ChoiceExp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.SimpleNameClass; import com.sun.msv.grammar.util.ExpressionWalker; import com.sun.msv.grammar.xmlschema.AttWildcardExp; import com.sun.msv.grammar.xmlschema.AttributeGroupExp; import com.sun.msv.grammar.xmlschema.AttributeWildcard; import com.sun.msv.grammar.xmlschema.ComplexTypeExp; /** * Processes the attribtue wildcard according to the spec. * *

      * Since the definition of the attribute wildcard is very adhoc, * it cannot be naturally caputred by our AGM. * *

      * Therefore, when we parse a schema, we just parse <anyAttribute> directly. * After all components are loaded, arcane computation is done to correctly * compute the attribute wildcard. * *

      * Attribute wildcard will be ultimately converted into an expression, and that * will be attached to the {@link ComplexTypeExp#attWildcard}. * *

      * This class also computes the attribute propagation that happens * only when a complex type is derived by restriction. * * Consider the following fragment: * *

      
       * <complexType name="base">
       *   <attribute name="abc" ... />
       * </complexType>
       * 
       * <complexType name="derived">
       *   <complexContent>
       *     <restriction base="base"/>
       *   </complexContent>
       * </complexType>
       * 
      * *

      * According to the spec, the derived type will have the 'abc' attribute. * By "propagation", we mean this behavior. * * * @author Kohsuke KAWAGUCHI */ public class AttributeWildcardComputer extends ExpressionWalker { public static void compute( XMLSchemaReader reader, Expression topLevel ) { new AttributeWildcardComputer(reader).compute(topLevel); } private void compute( Expression topLevel ) { topLevel.visit(this); while(!unprocessedElementExps.isEmpty()) ((ElementExp)unprocessedElementExps.pop()).contentModel.visit(this); } protected AttributeWildcardComputer( XMLSchemaReader _reader ) { this.reader = _reader; } private final XMLSchemaReader reader; /** * Visited ElementExps and ReferenceExps to prevent infinite recursion. */ private final Set visitedExps = new HashSet(); private final Stack unprocessedElementExps = new Stack(); /** * Used to collect AttributeWildcards of children. */ private Set wildcards = null; public void onElement( ElementExp exp ) { if( !visitedExps.add(exp) ) return; // this element has already been processed unprocessedElementExps.add(exp); } public void onRef( ReferenceExp exp ) { if( visitedExps.add(exp) ) { if( exp instanceof AttributeGroupExp ) { AttributeGroupExp aexp = (AttributeGroupExp)exp; final Set o = wildcards; { // process children and collect their wildcards. wildcards = new HashSet(); exp.exp.visit(this); // compute the attribute wildcard aexp.wildcard = calcCompleteWildcard( aexp.wildcard, wildcards ); } wildcards = o; } else if( exp instanceof ComplexTypeExp ) { ComplexTypeExp cexp = (ComplexTypeExp)exp; final Set o = wildcards; { // process children and collect their wildcards. wildcards = new HashSet(); exp.exp.visit(this); // compute the attribute wildcard cexp.wildcard = calcCompleteWildcard( cexp.wildcard, wildcards ); // if(cexp.wildcard==null) // System.out.println("complete wildcard is: none"); // else // System.out.println("complete wildcard is: "+cexp.wildcard.getName()); // if the base type is a complex type and the extension is chosen, // then we need one last step. Sigh. if(cexp.complexBaseType!=null) { // System.out.println("check the base type"); // process the base type first. cexp.complexBaseType.visit(this); if(cexp.derivationMethod==ComplexTypeExp.EXTENSION) cexp.wildcard = calcComplexTypeWildcard( cexp.wildcard, cexp.complexBaseType.wildcard ); propagateAttributes(cexp); } // create the expression for this complex type. if( cexp.wildcard!=null ) cexp.attWildcard.exp = cexp.wildcard.createExpression(reader.grammar); } wildcards = o; } else // otherwise process it normally. super.onRef(exp); } if( wildcards!=null ) { // add the complete att wildcard of this component. if( exp instanceof AttWildcardExp ) { AttributeWildcard w = ((AttWildcardExp)exp).getAttributeWildcard(); if(w!=null) wildcards.add(w); } } } /** * Computes the "complete attribute wildcard" */ private AttributeWildcard calcCompleteWildcard( AttributeWildcard local, Set s ) { final AttributeWildcard[] children = (AttributeWildcard[])s.toArray(new AttributeWildcard[s.size()]); // 1st step is to compute the complete wildcard. if( children.length==0 ) return local; // assert(children.length>0) // compute the intersection of wildcard. NameClass target = children[0].getName(); for( int i=1; iKohsuke KAWAGUCHI */ public class ImportState extends ChildlessState { protected void startSelf() { super.startSelf(); final XMLSchemaReader reader = (XMLSchemaReader)this.reader; // TODO: @schemaLocation is optional. String namespace = startTag.getAttribute("namespace"); if( namespace==null ) namespace=""; if( namespace.equals(reader.currentSchema.targetNamespace) ) { reader.reportError( XMLSchemaReader.ERR_IMPORTING_SAME_NAMESPACE ); return; } if( reader.isSchemaDefined( reader.getOrCreateSchema(namespace) ) ) // this grammar is already defined. // so ignore it. return; try { reader.switchSource( this, new RootIncludedSchemaState(reader.sfactory.schemaHead(namespace)) ); } catch( AbortException e ) { // recover by ignoring the error } } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/WSDLGrammarReaderController.java0000644000175000017500000000323211164025612027737 0ustar giovannigiovannipackage com.sun.msv.reader.xmlschema; import java.util.Map; import org.w3c.dom.ls.LSInput; import org.w3c.dom.ls.LSResourceResolver; import org.xml.sax.InputSource; import org.xml.sax.Locator; import com.sun.msv.reader.GrammarReaderController2; /** * Catch error messages and resolve schema locations. */ public class WSDLGrammarReaderController implements GrammarReaderController2, LSResourceResolver { private GrammarReaderController2 nextController; private Map schemas; private String baseURI; /** * create the resolving controller. * @param baseURI URI of the WSDL. * @param sources */ public WSDLGrammarReaderController(GrammarReaderController2 nextController, String baseURI, Map sources) { this.nextController = nextController; this.baseURI = baseURI; this.schemas = sources; } public void error(Locator[] locs, String msg, Exception nestedException) { if (nextController != null) { nextController.error(locs, msg, nestedException); } } public void warning(Locator[] locs, String errorMessage) { if (nextController != null) { nextController.warning(locs, errorMessage); } } public InputSource resolveEntity(String publicId, String systemId) { return null; } public LSResourceResolver getLSResourceResolver() { return this; } public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) { EmbeddedSchema schema = schemas.get(namespaceURI); if (schema != null) { return new DOMLSInputImpl(this.baseURI, schema.getSystemId(), schema.getSchemaElement()); } else { return null; } } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/ComplexContentBodyState.java0000644000175000017500000001112207671170035027256 0ustar giovannigiovanni/* * @(#)$Id: ComplexContentBodyState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.xmlschema.AttributeWildcard; import com.sun.msv.grammar.xmlschema.ComplexTypeExp; import com.sun.msv.reader.SequenceState; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * used to parse restriction/extension element as a child of complexContent element. * * @author Kohsuke KAWAGUCHI */ public class ComplexContentBodyState extends SequenceState implements AnyAttributeOwner { /** ComplexType object that we are now constructing. */ protected ComplexTypeExp parentDecl; /** * if this state is used to parse <extension>, then true. * if this state is used to parse <restension>, then false. */ protected boolean extension; protected ComplexContentBodyState( ComplexTypeExp parentDecl, boolean extension ) { this.parentDecl = parentDecl; this.extension = extension; } protected State createChildState( StartTagInfo tag ) { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; State s; if( super.exp==Expression.epsilon ) { // model group must be the first expression child. s = reader.createModelGroupState(this,tag); if(s!=null ) return s; } // attribute, attributeGroup, and anyAttribtue can be specified // after content model is given. return reader.createAttributeState(this,tag); } public void setAttributeWildcard( AttributeWildcard local ) { parentDecl.wildcard = local; } protected Expression initialExpression() { // if nothing is specified, then empty return Expression.epsilon; } protected Expression annealExpression( Expression exp ) { // hook this ComplexTypeExp into the base type's restrictions list. final XMLSchemaReader reader = (XMLSchemaReader)this.reader; exp = super.annealExpression(exp); String refQName = startTag.getAttribute("base"); if( refQName==null ) { reader.reportError( XMLSchemaReader.ERR_MISSING_ATTRIBUTE, startTag.qName, "base" ); return exp; // recover by abandoning proper derivation processing } String[] r = reader.splitQName(refQName); if(r==null) { reader.reportError( XMLSchemaReader.ERR_UNDECLARED_PREFIX, refQName ); return exp; // recover by abandoning proper derivation processing } if( reader.isSchemaNamespace(r[0]) && r[1].equals("anyType") ) // derivation from anyType means this expression is the root of // derivation. So we don't have to connect this complex type to // the super class. return exp; ComplexTypeExp baseType = reader.getOrCreateSchema(r[0]/*uri*/).complexTypes.getOrCreate(r[1]/*local name*/); if( baseType==null ) return exp; // recover by abandoning further processing of this declaration. reader.backwardReference.memorizeLink(baseType); /* if( extension ) baseType.extensions.exp = reader.pool.createChoice( baseType.extensions.exp, parentDecl.selfWType ); // actual content model will be , else baseType.restrictions.exp = reader.pool.createChoice( baseType.restrictions.exp, parentDecl.selfWType ); */ // set other fields of the ComplexTypeExp. parentDecl.derivationMethod = extension?ComplexTypeExp.EXTENSION:ComplexTypeExp.RESTRICTION; parentDecl.complexBaseType = baseType; return combineToBaseType( baseType, exp ); } /** * combines the base type content model and this content model */ protected Expression combineToBaseType( ComplexTypeExp baseType, Expression addedExp ) { if( extension ) return reader.pool.createSequence( baseType.body, addedExp ); else return addedExp; } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/AnyElementState.java0000644000175000017500000001114507730143103025534 0ustar giovannigiovanni/* * @(#)$Id: AnyElementState.java 1601 2003-09-11 19:00:19Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import java.util.Iterator; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.ReferenceContainer; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.trex.ElementPattern; import com.sun.msv.grammar.xmlschema.ElementDeclExp; import com.sun.msv.grammar.xmlschema.XMLSchemaSchema; import com.sun.msv.reader.GrammarReader; import com.sun.msv.reader.State; /** * used to parse <any > element. * * @author Kohsuke KAWAGUCHI */ public class AnyElementState extends AnyState { protected Expression createExpression( final String namespace, final String process ) { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; final XMLSchemaSchema currentSchema = reader.currentSchema; if( process.equals("skip") ) { // "skip" can be expanded now. NameClass nc = getNameClass(namespace,currentSchema); ElementPattern ep = new ElementPattern(nc,Expression.nullSet); ep.contentModel = // reader.pool.createMixed( reader.pool.createZeroOrMore( reader.pool.createChoice( ep, reader.pool.createAttribute(nc) ) ) ); // minOccurs/maxOccurs is processed through interception return ep; } // "lax"/"strict" has to be back-patched later. final ReferenceExp exp = new ReferenceExp("any("+process+":"+namespace+")"); reader.addBackPatchJob( new GrammarReader.BackPatch(){ public State getOwnerState() { return AnyElementState.this; } public void patch() { if( !process.equals("lax") && !process.equals("strict") ) { reader.reportError( XMLSchemaReader.ERR_BAD_ATTRIBUTE_VALUE, "processContents", process ); exp.exp = Expression.nullSet; return; } exp.exp = Expression.nullSet; NameClass nc = getNameClass(namespace,currentSchema); Iterator itr; itr = reader.grammar.iterateSchemas(); while( itr.hasNext() ) { XMLSchemaSchema schema = (XMLSchemaSchema)itr.next(); // nc is built by using NamespaceNameClass. // "strict" allows global element declarations of // specified namespaces. if(nc.accepts( schema.targetNamespace, NameClass.LOCALNAME_WILDCARD )) // schema.topLevel is choices of globally declared elements. exp.exp = reader.pool.createChoice( exp.exp, schema.topLevel ); } if( !process.equals("lax") ) return; // if processContents="strict", the above is fine. // if "lax", we have to add an expression to // match other elements. NameClass laxNc = createLaxNameClass( nc, new XMLSchemaReader.RefResolver() { public ReferenceContainer get( XMLSchemaSchema schema ) { return schema.elementDecls; } }); exp.exp = reader.pool.createChoice( new ElementPattern( laxNc, reader.pool.createMixed( reader.pool.createZeroOrMore( reader.pool.createChoice( reader.pool.createAttribute(NameClass.ALL), exp)))), exp.exp ); } }); exp.exp = Expression.nullSet; // dummy for a while. // minOccurs/maxOccurs is processed through interception return exp; } protected NameClass getNameClassFrom( ReferenceExp exp ) { return ((ElementDeclExp)exp).getElementExp().getNameClass(); } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/ComplexTypeDeclState.java0000644000175000017500000001530207671170035026543 0ustar giovannigiovanni/* * @(#)$Id: ComplexTypeDeclState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import org.xml.sax.Locator; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ReferenceContainer; import com.sun.msv.grammar.xmlschema.AttributeWildcard; import com.sun.msv.grammar.xmlschema.ComplexTypeExp; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * used to parse <complexType> element. * * @author Kohsuke KAWAGUCHI */ public class ComplexTypeDeclState extends RedefinableDeclState implements AnyAttributeOwner { /** ComplexType object that we are now constructing. */ protected ComplexTypeExp decl; protected ReferenceContainer getContainer() { return ((XMLSchemaReader)reader).currentSchema.complexTypes; } protected void startSelf() { super.startSelf(); final XMLSchemaReader reader = (XMLSchemaReader)this.reader; String name = startTag.getAttribute("name"); if( name==null ) { if( isGlobal() ) reader.reportError( XMLSchemaReader.ERR_MISSING_ATTRIBUTE, "complexType", "name" ); decl = new ComplexTypeExp( reader.currentSchema, null ); } else { if( isRedefine() ) // in redefine mode, use temporary object. // parsed complexType will be copied into the original one. decl = new ComplexTypeExp( reader.currentSchema, name ); else { decl = reader.currentSchema.complexTypes.getOrCreate(name); // MSV has pre-defiend types in xsd namespace (such as xs:anyType) // this causes a problem when we are parsing schema4schema. // to avoid this problem, we won't issue this error when we are // parsing schema4schema. // // But this is more like a quick hack. What is the correct way to // solve this problem? if( decl.body.exp!=null && reader.currentSchema!=reader.xsdSchema ) reader.reportError( new Locator[]{this.location,reader.getDeclaredLocationOf(decl)}, XMLSchemaReader.ERR_DUPLICATE_COMPLEXTYPE_DEFINITION, new Object[]{name} ); } } // set the final attribute to ComplexTypeExp. decl.finalValue = parseFinalValue( "final", reader.finalDefault ); decl.block = parseFinalValue( "block", reader.blockDefault ); } /** * parses the value of the block/finel attribute. */ private int parseFinalValue( String attName, String defaultValue ) { int r = 0; String value = startTag.getAttribute(attName); if( value==null ) value = defaultValue; if( value!=null ) { if( value.indexOf("#all")>=0 ) r |= ComplexTypeExp.RESTRICTION|ComplexTypeExp.EXTENSION; if( value.indexOf("extension")>=0 ) r |= ComplexTypeExp.EXTENSION; if( value.indexOf("restriction")>=0 ) r |= ComplexTypeExp.RESTRICTION; } return r; } public void setAttributeWildcard( AttributeWildcard local ) { decl.wildcard = local; } protected State createChildState( StartTagInfo tag ) { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; // simpleContent, ComplexContent, group, all, choice, and sequence // are allowed only when we haven't seen type definition. if(tag.localName.equals("simpleContent") ) return reader.sfactory.simpleContent(this,tag,decl); if(tag.localName.equals("complexContent") ) return reader.sfactory.complexContent(this,tag,decl); State s = reader.createModelGroupState(this,tag); if(s!=null) return s; if( super.exp==null ) { // no content model was given. // I couldn't "decipher" what should we do in this case. // I assume "empty" just because it's most likely. exp = Expression.epsilon; } // TODO: attributes are prohibited after simpleContent/complexContent. // attribute, attributeGroup, and anyAttribtue can be specified // after content model is given. return reader.createAttributeState(this,tag); } protected Expression castExpression( Expression halfCastedExpression, Expression newChildExpression ) { if( halfCastedExpression==null ) return newChildExpression; // the first one // only the first one contains element. // the rest consists of attributes. // so this order of parameters is fine. return reader.pool.createSequence( newChildExpression, halfCastedExpression ); } protected Expression defaultExpression() { // if no content model is given, then this complex type is empty return Expression.epsilon; } protected Expression annealExpression(Expression contentType) { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; String abstract_ = startTag.getAttribute("abstract"); if( "false".equals(abstract_) || abstract_==null ) // allow the content model to directly appear as this type. decl.setAbstract(false); else { decl.setAbstract(true); if( !"true".equals(abstract_) ) reader.reportError( XMLSchemaReader.ERR_BAD_ATTRIBUTE_VALUE, "abstract", abstract_ ); // recover by ignoring this error. } String mixed = startTag.getAttribute("mixed"); if( "true".equals(mixed) ) contentType = reader.pool.createMixed(contentType); else if( mixed!=null && !"false".equals(mixed) ) reader.reportError( XMLSchemaReader.ERR_BAD_ATTRIBUTE_VALUE, "mixed", mixed ); // recover by ignoring this error. decl.body.exp = contentType; if( isRedefine() ) { // copy new definition back into the original definition. oldDecl.redefine(decl); decl = (ComplexTypeExp)oldDecl; } reader.setDeclaredLocationOf(decl); reader.setDeclaredLocationOf(decl.body); return decl; } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/xml.xsd0000644000175000017500000000325107357444653023171 0ustar giovannigiovanni This schema defines attributes and an attribute group suitable for use by schemas wishing to allow xml:lang or xml:space attributes on elements they define. To enable this, such a schema must import this schema for the XML namespace, e.g. as follows: <schema . . .> . . . <import namespace="http://www.w3.org/XML/1998/namespace" schemaLocation="http://www.w3.org/2001/03/xml.xsd"/> Subsequently, qualified reference to either of the attributes or the group defined below will have the desired effect, e.g. <type . . .> . . . <attributeGroup ref="xml:specialAttrs"/> will define a type which will schema-validate a instance element with both xml:space and xml:lang attribute In due course, we should install the relevant ISO 2- and 3-letter codes as the enumerated possible values . . . msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/RootIncludedSchemaState.java0000644000175000017500000000166307671170035027223 0ustar giovannigiovanni/* * @(#)$Id: RootIncludedSchemaState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import com.sun.msv.reader.SimpleState; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * used to parse root of schema document. * * @author Kohsuke KAWAGUCHI */ public class RootIncludedSchemaState extends SimpleState { protected State topLevelState; public RootIncludedSchemaState( State topLevelState ) { this.topLevelState = topLevelState; } protected State createChildState( StartTagInfo tag ) { if(tag.localName.equals("schema")) return topLevelState; return null; } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/SimpleContentRestrictionState.java0000644000175000017500000002377107671170035030525 0ustar giovannigiovanni/* * @(#)$Id: SimpleContentRestrictionState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import org.relaxng.datatype.DatatypeException; import com.sun.msv.datatype.xsd.StringType; import com.sun.msv.datatype.xsd.XSDatatype; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.util.ExpressionWalker; import com.sun.msv.grammar.xmlschema.AttributeWildcard; import com.sun.msv.grammar.xmlschema.ComplexTypeExp; import com.sun.msv.grammar.xmlschema.SimpleTypeExp; import com.sun.msv.grammar.xmlschema.XMLSchemaSchema; import com.sun.msv.reader.GrammarReader; import com.sun.msv.reader.SequenceState; import com.sun.msv.reader.State; import com.sun.msv.reader.datatype.xsd.FacetStateParent; import com.sun.msv.reader.datatype.xsd.XSDatatypeExp; import com.sun.msv.reader.datatype.xsd.XSTypeIncubator; import com.sun.msv.reader.datatype.xsd.XSTypeOwner; import com.sun.msv.util.StartTagInfo; /** * used to parse restriction/extension element as a child of <simpleContent> element. * * @author Kohsuke KAWAGUCHI */ public class SimpleContentRestrictionState extends SequenceState implements FacetStateParent,XSTypeOwner,AnyAttributeOwner { /** ComplexType object that we are now constructing. */ protected ComplexTypeExp parentDecl; protected SimpleContentRestrictionState( ComplexTypeExp parentDecl ) { this.parentDecl = parentDecl; } public void setAttributeWildcard( AttributeWildcard local ) { parentDecl.wildcard = local; } /** used to restrict simpleType */ protected XSTypeIncubator incubator; public XSTypeIncubator getIncubator() { // If no incubator is specified, // we consider that there is no in the children. // // In that case, we use the content type of the base type. if(incubator==null) { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; if(baseTypeName==null) { // there was an error and we cannot determine the base type. // assume xs:string and recover incubator = new XSDatatypeExp(StringType.theInstance,reader.pool).createIncubator(); } else { // we need a special handling for built-in types if(reader.isSchemaNamespace(baseTypeName[0])) { XSDatatype dt = reader.resolveBuiltinDataType(baseTypeName[1]); if(dt!=null) incubator = new XSDatatypeExp(dt,reader.pool).createIncubator(); // maybe we are parsing the schema for schema. // consult externally specified schema. } if(incubator==null) { // we don't know whether it's a simple type or a complex type. // so use a late binding. incubator = new XSDatatypeExp(baseTypeName[0],baseTypeName[1],reader, new BaseContentTypeRenderer()).createIncubator(); } } } return incubator; } private class BaseContentTypeRenderer implements XSDatatypeExp.Renderer { public XSDatatype render( XSDatatypeExp.RenderingContext context ) { final XMLSchemaReader reader = (XMLSchemaReader) SimpleContentRestrictionState.this.reader; SimpleTypeExp sexp = baseSchema.simpleTypes.get(baseTypeName[1]); if(sexp!=null) { // we've found the simple type as the base type return sexp.getType().getType(context); } ComplexTypeExp cexp = baseSchema.complexTypes.get(baseTypeName[1]); if(cexp!=null) { // we've found the complex type as the base type // look for XSDatatypeExp inside final XSDatatypeExp[] dexp = new XSDatatypeExp[1]; cexp.body.visit(new ExpressionWalker() { public void onAttribute( AttributeExp exp ) { // don't visit inside attributes } public void onRef( ReferenceExp exp ) { if(exp instanceof XSDatatypeExp) { dexp[0] = (XSDatatypeExp)exp; return; } super.onRef(exp); } }); if(dexp[0]==null) { // we didn't find any XSDatatypeExp in it. reader.reportError( XMLSchemaReader.ERR_INVALID_BASETYPE_FOR_SIMPLECONTENT, base ); return StringType.theInstance; } return dexp[0].getType(context); } // this is an error, but // we don't need to report an error here. // this error should be reported as a part of // back patch job. // recover by assuming string type return StringType.theInstance; } } public String getTargetNamespaceUri() { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; return reader.currentSchema.targetNamespace; } public void onEndChild( XSDatatypeExp child ) { if( incubator!=null ) // assertion failed. // createChildState should reject 2nd element. throw new Error(); incubator = child.createIncubator(); } protected State createChildState( StartTagInfo tag ) { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; if( incubator==null && tag.localName.equals("simpleType") ) return reader.sfactory.simpleType(this,tag); State s = reader.createAttributeState(this,tag); if(s!=null ) return s; return reader.createFacetState(this,tag); // facets } protected Expression initialExpression() { // without this statement, // / without any attribute will be prohibited. return Expression.epsilon; } /** value of the base attribute. null in case of an error. */ private String base; /** * Namespace URI and local name of the base attribute. * null in case of an error. */ private String[] baseTypeName; /** * XMLSchemaSchema object of the base type. * We should have this reference so that * XMLSchemaReader can detect an error if this schema is undefined. * * Null in case of an error. */ private XMLSchemaSchema baseSchema; protected void startSelf() { super.startSelf(); final XMLSchemaReader reader = (XMLSchemaReader)this.reader; base = startTag.getAttribute("base"); if(base==null) { // in extension, base attribute is mandatory. reader.reportError( XMLSchemaReader.ERR_MISSING_ATTRIBUTE, startTag.localName, "base"); return; } baseTypeName = reader.splitQName(base); if( baseTypeName==null ) { reader.reportError( XMLSchemaReader.ERR_UNDECLARED_PREFIX, base ); return; } baseSchema = reader.grammar.getByNamespace(baseTypeName[0]); } protected Expression annealExpression( Expression exp ) { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; parentDecl.derivationMethod = ComplexTypeExp.RESTRICTION; try { XSDatatypeExp p = getIncubator().derive(null,null); exp = reader.pool.createSequence( super.annealExpression(exp), p ); } catch( DatatypeException e ) { // derivation failed reader.reportError( e, XMLSchemaReader.ERR_BAD_TYPE, e.getMessage() ); // recover by using harmless expression. anything will do. return Expression.nullSet; } // we need a special handling for built-in types if(reader.isSchemaNamespace(baseTypeName[0])) { XSDatatype dt = reader.resolveBuiltinDataType(baseTypeName[1]); if(dt!=null) { parentDecl.simpleBaseType = new XSDatatypeExp(dt,reader.pool); return exp; } } // in other cases, we don't know the base type yet. // let back patch it // compute the base type and sets the appropriate property // (either simpleBaseType or complexBaseType.) reader.addBackPatchJob( new GrammarReader.BackPatch(){ public State getOwnerState() { return SimpleContentRestrictionState.this; } public void patch() { SimpleTypeExp sexp = baseSchema.simpleTypes.get(baseTypeName[1]); if(sexp!=null) { // we've found the simple type parentDecl.simpleBaseType = sexp.getType(); _assert(parentDecl.simpleBaseType!=null); return; } ComplexTypeExp cexp = baseSchema.complexTypes.get(baseTypeName[1]); if(cexp!=null) { // we've found the complex type as the base type parentDecl.complexBaseType = cexp; return; } // there is no base type. reader.reportError( XMLSchemaReader.ERR_UNDEFINED_COMPLEX_OR_SIMPLE_TYPE, base ); } }); return exp; } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/AnyState.java0000644000175000017500000001123307730143103024220 0ustar giovannigiovanni/* * @(#)$Id: AnyState.java 1601 2003-09-11 19:00:19Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import java.util.Iterator; import java.util.StringTokenizer; import com.sun.msv.grammar.ChoiceNameClass; import com.sun.msv.grammar.DifferenceNameClass; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.NamespaceNameClass; import com.sun.msv.grammar.NotNameClass; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.SimpleNameClass; import com.sun.msv.grammar.xmlschema.LaxDefaultNameClass; import com.sun.msv.grammar.xmlschema.XMLSchemaSchema; import com.sun.msv.reader.ExpressionWithoutChildState; /** * base implementation of AnyAttributeState and AnyElementState. * * @author Kohsuke KAWAGUCHI */ public abstract class AnyState extends ExpressionWithoutChildState { protected final Expression makeExpression() { return createExpression( startTag.getDefaultedAttribute("namespace","##any"), startTag.getDefaultedAttribute("processContents","strict") ); } /** * creates AGM that corresponds to the specified parameters. */ protected abstract Expression createExpression( String namespace, String process ); /** * processes 'namepsace' attribute and gets corresponding NameClass object. */ protected NameClass getNameClass( String namespace, XMLSchemaSchema currentSchema ) { // we have to get currentSchema through parameter because // this method is also used while back-patching, and // reader.currentSchema points to the invalid schema in that case. final XMLSchemaReader reader = (XMLSchemaReader)this.reader; namespace = namespace.trim(); if( namespace.equals("##any") ) return NameClass.ALL; if( namespace.equals("##other") ) // ##other means anything other than the target namespace and local. return new NotNameClass( new ChoiceNameClass( new NamespaceNameClass(currentSchema.targetNamespace), new NamespaceNameClass("")) ); NameClass choices=null; StringTokenizer tokens = new StringTokenizer(namespace); while( tokens.hasMoreTokens() ) { String token = tokens.nextToken(); NameClass nc; if( token.equals("##targetNamespace") ) nc = new NamespaceNameClass(currentSchema.targetNamespace); else if( token.equals("##local") ) nc = new NamespaceNameClass(""); else nc = new NamespaceNameClass(token); if( choices==null ) choices = nc; else choices = new ChoiceNameClass(choices,nc); } if( choices==null ) { // no item was found. reader.reportError( XMLSchemaReader.ERR_BAD_ATTRIBUTE_VALUE, "namespace", namespace ); return NameClass.ALL; } return choices; } protected abstract NameClass getNameClassFrom( ReferenceExp exp ); protected NameClass createLaxNameClass( NameClass allowedNc, XMLSchemaReader.RefResolver res ) { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; LaxDefaultNameClass laxNc = new LaxDefaultNameClass(allowedNc); Iterator itr = reader.grammar.iterateSchemas(); while( itr.hasNext() ) { XMLSchemaSchema schema = (XMLSchemaSchema)itr.next(); if(allowedNc.accepts( schema.targetNamespace, NameClass.LOCALNAME_WILDCARD )) { ReferenceExp[] refs = res.get(schema).getAll(); for( int i=0; iKohsuke KAWAGUCHI */ public class AttributeState extends ExpressionWithChildState implements XSTypeOwner { protected State createChildState( StartTagInfo tag ) { if( tag.localName.equals("simpleType") ) return ((XMLSchemaReader)reader).sfactory.simpleType(this,tag); return super.createChildState(tag); } protected Expression initialExpression() { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; if( startTag.containsAttribute("ref") ) { if( isGlobal() ) { reader.reportError( XMLSchemaReader.ERR_DISALLOWED_ATTRIBUTE, startTag.qName, "ref" ); return Expression.epsilon; } // this tag has @ref. Expression exp = reader.resolveQNameRef( startTag, "ref", new XMLSchemaReader.RefResolver() { public ReferenceContainer get( XMLSchemaSchema g ) { return g.attributeDecls; } } ); if( exp==null ) return Expression.epsilon; // couldn't resolve QName. return exp; } final String typeAttr = startTag.getAttribute("type"); if( typeAttr==null ) // return null to indicate that no type definition is given. return null; // if element has @type, then // it shall be used as content type. return reader.resolveXSDatatype( typeAttr ); } protected Expression defaultExpression() { // if no type definition is given, assume ur-type. return Expression.anyString; } protected Expression castExpression( Expression halfCastedExpression, Expression newChildExpression ) { if( halfCastedExpression!=null ) // only one child is allowed. // recover by ignoring previously found child expressions. reader.reportError( XMLSchemaReader.ERR_MORE_THAN_ONE_CHILD_EXPRESSION ); return newChildExpression; } protected Expression annealExpression(Expression contentType) { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; final String fixed = startTag.getAttribute("fixed"); final String name = startTag.getAttribute("name"); final String use = startTag.getAttribute("use"); Expression exp; if( startTag.containsAttribute("ref") ) { if( fixed!=null ) reader.reportWarning( XMLSchemaReader.ERR_UNIMPLEMENTED_FEATURE, " element with both 'ref' and 'fixed' attributes" ); exp = contentType; } else { // TODO: form attribute is prohibited in several occasions. String targetNamespace; // @name is mandatory if( name==null ) { reader.reportError( XMLSchemaReader.ERR_MISSING_ATTRIBUTE, "attribute","name"); return Expression.nullSet; } if( isGlobal() ) targetNamespace = reader.currentSchema.targetNamespace; else // in local attribute declaration, // targetNamespace is affected by @form and schema's @attributeFormDefault. targetNamespace = reader.resolveNamespaceOfAttributeDecl( startTag.getAttribute("form") ); if( fixed!=null ) { if(contentType instanceof XSDatatypeExp ) { // we know that the attribute value is of XSDatatypeExp final XSDatatypeExp baseType = (XSDatatypeExp)contentType; try { XSTypeIncubator inc = baseType.createIncubator(); inc.addFacet("enumeration",fixed,false,reader); contentType = inc.derive(null,null); } catch( DatatypeException e ) { reader.reportError( e, XMLSchemaReader.ERR_BAD_TYPE, e.getMessage() ); return Expression.nullSet; } } else { // this is strange, as the type of the attribute // must be a simple type in theory. // but I'm not sure if we receive XSDatatypeExp as // the content type --- it maybe some ReferenceExp, // for example. So just degrade and assume token here. // I know this is a sloppy work contentType = reader.pool.createValue( com.sun.msv.datatype.xsd.TokenType.theInstance, new StringPair("","token"), // emulate RELAX NG built-in "token" type fixed ); } } if( "prohibited".equals(use) ) // use='prohibited' is implemented through NoneType contentType = reader.pool.createData( NoneType.theInstance ); exp = createAttribute( new SimpleNameClass( targetNamespace, name ), contentType ); } if( isGlobal() ) { // register this expression as a global attribtue declaration. AttributeDeclExp decl = reader.currentSchema.attributeDecls.getOrCreate(name); if(decl.exp!=null) reader.reportError( new Locator[]{this.location,reader.getDeclaredLocationOf(decl)}, XMLSchemaReader.ERR_DUPLICATE_ATTRIBUTE_DEFINITION, new Object[]{name} ); reader.setDeclaredLocationOf(decl); if( exp instanceof AttributeExp ) decl.set( (AttributeExp)exp ); else { // sometimes, because of the error recovery, // exp can be something other than an AttributeExp. if( !reader.controller.hadError() ) throw new Error(); } // TODO: @use is prohibited in global } else { // handle @use if( "optional".equals(use) || use==null || "prohibited".equals(use) ) exp = reader.pool.createOptional(exp); else if( !"required".equals(use) ) reader.reportError( XMLSchemaReader.ERR_BAD_ATTRIBUTE_VALUE, "use", use ); // recover by assuming "required" (i.e., do nothing) } return exp; } /** * Allows the derived class to change it. */ protected Expression createAttribute( NameClass nc, Expression exp ) { return reader.pool.createAttribute(nc,exp); } public String getTargetNamespaceUri() { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; return reader.currentSchema.targetNamespace; } public void onEndChild( XSDatatypeExp type ) { super.onEndChild(type); } protected boolean isGlobal() { return parentState instanceof GlobalDeclState; } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/ComplexContentState.java0000644000175000017500000000356307671170035026452 0ustar giovannigiovanni/* * @(#)$Id: ComplexContentState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.xmlschema.ComplexTypeExp; import com.sun.msv.reader.ExpressionWithChildState; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * parses <complexContent> element. * * the expression created by this state is used as ComplexTypeExp.self field. * * @author Kohsuke KAWAGUCHI */ public class ComplexContentState extends ExpressionWithChildState { /** ComplexType object that we are now constructing. */ protected ComplexTypeExp parentDecl; protected ComplexContentState( ComplexTypeExp decl ) { this.parentDecl = decl; } protected State createChildState( StartTagInfo tag ) { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; if( super.exp!=null ) // we have already parsed restriction/extension. return null; if( tag.localName.equals("restriction") ) return reader.sfactory.complexRst(this,tag,parentDecl); if( tag.localName.equals("extension") ) return reader.sfactory.complexExt(this,tag,parentDecl); return super.createChildState(tag); } protected Expression castExpression( Expression halfCastedExpression, Expression newChildExpression ) { if( halfCastedExpression!=null ) // assertion failed. // this situation should be prevented by createChildState method. throw new Error(); return newChildExpression; } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/RedefineState.java0000644000175000017500000000744307671170035025232 0ustar giovannigiovanni/* * @(#)$Id: RedefineState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import com.sun.msv.grammar.xmlschema.SimpleTypeExp; import com.sun.msv.reader.AbortException; import com.sun.msv.reader.State; import com.sun.msv.reader.datatype.xsd.XSDatatypeExp; import com.sun.msv.util.StartTagInfo; /** * used to parse <redefine> element. * * @author Kohsuke KAWAGUCHI */ public class RedefineState extends GlobalDeclState { // TODO: elementDecl/attributeDecl are prohibited in redefine. // TODO: it probably is an error to redefine undefined components. // TODO: it is NOT an error to fail to load the specified schema (see 4.2.3) /** * When a simple type is being redefined, the original declaration * will be stored here. */ private SimpleTypeExp oldSimpleTypeExp; protected State createChildState( StartTagInfo tag ) { // SimpleType parsing is implemented in reader.datatype.xsd, // and therefore it doesn't support redefinition by itself. // so we need to take care of redefinition for them. // for detail, see RedefinableDeclState if( tag.localName.equals("simpleType") ) { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; String name = tag.getAttribute("name"); SimpleTypeExp sexp = reader.currentSchema.simpleTypes.get(name); if( sexp==null ) { reader.reportError( XMLSchemaReader.ERR_REDEFINE_UNDEFINED, name ); // recover by using an empty declaration sexp = reader.currentSchema.simpleTypes.getOrCreate(name); } reader.currentSchema.simpleTypes.redefine( name, sexp.getClone() ); oldSimpleTypeExp = sexp; // memorize this declaration } return super.createChildState(tag); } protected void startSelf() { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; super.startSelf(); try {// parse included grammar first. reader.switchSource( this, new RootIncludedSchemaState( reader.sfactory.schemaIncluded(this,reader.currentSchema.targetNamespace) ) ); } catch( AbortException e ) { // recover by ignoring the error } // disable duplicate definition check. prevDuplicateCheck = reader.doDuplicateDefinitionCheck; } /** previous value of reader#doDuplicateDefinitionCheck. */ private boolean prevDuplicateCheck; protected void endSelf() { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; reader.doDuplicateDefinitionCheck = prevDuplicateCheck; super.endSelf(); } public void onEndChild( XSDatatypeExp type ) { // handle redefinition of simpleType. final XMLSchemaReader reader = (XMLSchemaReader)this.reader; final String typeName = type.name; if( typeName==null ) { // top-level simpleType must define a named type reader.reportError( XMLSchemaReader.ERR_MISSING_ATTRIBUTE, "simpleType", "name" ); return; // recover by ignoring this declaration } oldSimpleTypeExp.set(type); reader.setDeclaredLocationOf(oldSimpleTypeExp); // restore the association reader.currentSchema.simpleTypes.redefine( oldSimpleTypeExp.name, oldSimpleTypeExp ); oldSimpleTypeExp = null; } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/GroupState.java0000644000175000017500000000711507671170035024601 0ustar giovannigiovanni/* * @(#)$Id: GroupState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import org.xml.sax.Locator; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ReferenceContainer; import com.sun.msv.grammar.xmlschema.GroupDeclExp; import com.sun.msv.grammar.xmlschema.XMLSchemaSchema; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * used to parse <group> element. * * @author Kohsuke KAWAGUCHI */ public class GroupState extends RedefinableDeclState { protected State createChildState( StartTagInfo tag ) { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; // TODO: group reference is prohibited under group element. return reader.createModelGroupState(this,tag); } protected ReferenceContainer getContainer() { return ((XMLSchemaReader)reader).currentSchema.groupDecls; } protected Expression initialExpression() { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; if( startTag.containsAttribute("ref") ) { // this this tag has @ref. Expression exp = reader.resolveQNameRef( startTag, "ref", new XMLSchemaReader.RefResolver() { public ReferenceContainer get( XMLSchemaSchema g ) { return g.groupDecls; } } ); if( exp==null ) return Expression.epsilon; // couldn't resolve QName. return exp; } return null; // use null to indicate that there is no child expression. } protected Expression castExpression( Expression halfCastedExpression, Expression newChildExpression ) { if( halfCastedExpression!=null ) { reader.reportError( XMLSchemaReader.ERR_MORE_THAN_ONE_CHILD_EXPRESSION ); return halfCastedExpression; } return newChildExpression; // the first one. } protected Expression annealExpression(Expression contentType) { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; if( !isGlobal() ) return contentType; // this element is global. // register this as a global group definition. String name = startTag.getAttribute("name"); if( name==null ) { reader.reportError( XMLSchemaReader.ERR_MISSING_ATTRIBUTE, "group", "name" ); // recover by returning a meaningless value, thereby ignoring this declaration. return Expression.nullSet; } if( contentType==null ) { reader.reportError( XMLSchemaReader.ERR_MISSING_CHILD_EXPRESSION ); return Expression.nullSet; } GroupDeclExp decl; if( isRedefine() ) decl = (GroupDeclExp)super.oldDecl; else { decl = reader.currentSchema.groupDecls.getOrCreate(name); if( decl.exp!=null ) reader.reportError( new Locator[]{this.location,reader.getDeclaredLocationOf(decl)}, XMLSchemaReader.ERR_DUPLICATE_GROUP_DEFINITION, new Object[]{name} ); } reader.setDeclaredLocationOf(decl); decl.exp = contentType; return decl; } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/IncludeState.java0000644000175000017500000000175007671170035025067 0ustar giovannigiovanni/* * @(#)$Id: IncludeState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import com.sun.msv.reader.AbortException; import com.sun.msv.reader.ChildlessState; /** * used to parse <include> element. * * @author Kohsuke KAWAGUCHI */ public class IncludeState extends ChildlessState { protected void startSelf() { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; super.startSelf(); try { reader.switchSource( this, new RootIncludedSchemaState( reader.sfactory.schemaIncluded(this,reader.currentSchema.targetNamespace) ) ); } catch( AbortException e ) { // recover by ignoring the error } } } msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/doc-files/0000755000175000017500000000000011622453166023502 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/reader/xmlschema/doc-files/redefine4.gif0000644000175000017500000002056607271644421026050 0ustar giovannigiovanniGIF89aY÷ÿÿÿÿÿ÷ÿ÷÷ÿ÷ïÿïïÿïçÿççÿçß÷çß÷ßß÷ß×÷××÷×Ï÷ÏÏ÷ÏÇ÷ÇÇ÷ǿ￿￷﷯³Ìæÿÿÿ::ÿWWÿuuÿ’’ÿ¯¯ÿÌÌ3J` w(Ž/¤7»>ÒFèMÿUÿl"ÿ‚Dÿ™fÿ°ˆÿƪÿÝÌ3"J1`@wOŽ^¤n»}ÒŒè›ÿªÿµ"ÿÁDÿÌfÿ׈ÿãªÿîÌ33GG\\pp……™™­­ÂÂÖÖëëÿÿÿÿ)ÿÿRÿÿzÿÿ£ÿÿÌ"31J@`Ow^Žn¤}»ŒÒ›èªÿµÿ"ÁÿDÌÿf×ÿˆãÿªîÿÌ3M"f+€3™<³DÌMæUÿhÿ|ÿ:ÿW£ÿu¶ÿ’Êÿ¯ÝÿÌ3PmЍÅâÿÿ3ÿ3MÿMfÿf€ÿ€™ÿ™³ÿ³ÌÿÌ3Mf"€+™3³<ÌDæMÿUÿh:ÿ|Wÿuÿ£’ÿ¶¯ÿÊÌÿÝ3"J1`@wOŽ^¤n»}ÒŒè›ÿª"ÿµDÿÁfÿ̈ÿתÿãÌÿî33MMff€€™™³³ÌÌææÿÿÿÿ:ÿÿWÿÿuÿÿ’ÿÿ¯ÿÿÌÿÿ3(P7mEŠT¨bÅqâ€ÿŒÿ3™ÿM¦ÿf³ÿ€¿ÿ™Ìÿ³ÙÿÌæÿ3Uw™»Ýÿÿ--ÿDDÿ[[ÿqqÿˆˆÿŸŸÿµµÿÌÌÿ3&M3f@€M™Y³fÌsæ€ÿŽÿ:ÿ«WÿºuÿÈ’ÿׯÿæÌÿ33MMff€€™™³³ÌÌææÿÿÿÿÿ:ÿÿWÿÿuÿÿ’ÿÿ¯ÿÿÌÿ3M&f3€@™M³YÌfæsÿ€ÿŽÿ:ÿW«ÿuºÿ’Èÿ¯×ÿÌæ!ù,Y@þH° Áƒ*\Ȱ¡Ã‡#JœH±¢Å‹3jÜȱ£Ç CŠIr …’(Sª\ɲ¥Ë‡'_Êœ92&Í›l Ô‰çK <}:Z(Σ"]ÊÔ Ò¦5‹šì9Õ©T«R}ÝjUëΪUczúªÊ²fÓÎD«¶­Û·p+²K÷ãܺx)ÍËäݾ€ ötïàÈ+^|¶0ãÇ#KVk8gåœIOÞ̹³g–†/3,ü÷³éÓr#jF-˜4ë׌I¯ÆLЦì½A±ê+W4l¤® ^×7q»³+?,Ú6XÚ´›‡Ý –÷WèØ-_î4xrîàÃþC¾=ú;ßÛæÅ«_ÓxIô'ÓS@¿¾ýûô À¿ÿ  €X`"¨À‚ 4¸BØÀ„Th¡@ á†t(Á‡ †(Á$–h"‰òÑU{ϱX”{ Á8~4Ú§Ÿ8XÀ€ˆ@‚ 2è`„Rxa…n¨a‡ˆèä‰PNb\+ºX%w2¾—eD5vy#ŽÿHÁ€>þä‚ 8ø ‘6àG&©$“NŠå‰SÂueG{6Ôgj.ª¶%G…uiè¡÷Q€Ÿ¢|É@J€ŽŒY© ˜i  ÇEº ç…rrèa Þibžoý™ÔAþÖÕ–fèÍêêD·Z¹ÝF…éë¯À+lŽòX&œ Ù ‘ ´y$’J.y*ª#ªŠâ nåŠe (Áçí‹–òÈc¸’î¹âZŠn¹ã–kî€`šPÉvê ¨RÐæ¨£b-LRð!P! líµÚʤTnÕµ«sÓÉzÝW—A ]¬XEGÝPÜRF/² ‡,òÈ$—l2²hªÉ¬³Ï–*m“×y°”ض•pl€v UaÌöìóÏ@-ôÐD¯ldœÑB@'µÕZËj¶:ÃõÎ@=kµ…Øò„¨£þk€g¦¹l„GCk*ÌvFYXˆ3?m³jR'VÚÍœ¹Ý-PLæ­wþÞ›¼é¦@f x‚‚‡<8Ê IvpŽúg œ6”k§z°Ýiý5Æw«BFÅ×⬠Í=uw5F°·•KÀúë°Ç.ûì´ßÆöå©g7j¦Ÿž|0Á>óðÄß6PÆ'¯¼ª˜›E7qÏûÎZóÒÓômõØ–{ö)9¶+÷à·¶}øÚOþù}Q>¸ë·›ùÕ«ïþü]Ÿ½üôçÏ{ô‘á¯ÿÿ“qY2Â?|ÏO–±Me¶³šø,p JÅÜ#›¤‡<ßó_SÀný~«MÁÅ9 †&c³9 IB“¢*„Ïo`¨Á–tP$‹áûÎb«‰a§„Qï) s6†}ncc ¡Ÿ³±Î‘*KÔáin¨½!JñŠža‹EE.:¬‡ºñ\VˆˆÅ2ê #TÔ’×x¾4F…pÄbÂrHÀ8ÚñŽxô@þH° Áƒ*\Ȱ¡Ã‡#  ±¢Å‹3jÜȱ£Ç ;R I²¤É“G¢\ɲ¥Ë—0c^T)³¦M”4oêœHfΑ*òìYbNžG…˜t(Q§ lªt§Õ”W³j•¸t«×¯`Ãfí*¶ìM²fÓª]Ëö!Ú¶pãÊK¡îÛ¹xóêÝËw«Ý»} L8.àˆv +^̸ñ×ÄL¥"®ë¸²å˘ÍBÎ̹ðf¥§Rž:‘²ÑÍ¢GCu{¸³×Юc;†-4ujÉL£ÞÚ:¡jÙgQι·æßÄ7ÂNΜqmݤ¡ç–ž»éBãÿbw®]{óïàÛ"þ/Ù½¼ùóèÓ«_Ͼ½û÷ë÷ŸO¿¾ýûèÃgßN~âTWh¦$²IÁÙ݃-©Ý…vmØawSVi%–ZºØåŒ_Â5æLªùôYiÈ ×L‡†É¨™lªié¥ à¦vrÚeÖIA…vái”9@AŸV^©b ,þ*c¡âAšhO‹æ¸[d¦A*iËU&®ÙiœÆ&+§²› ³‰¤J.™À¨ \¨€† På‡ ˆhНÂú¢¬4»Zr¥O‘Åny!Eú+¢éñZmµ(Ù¯„ÿò»o¿ p„#Œ@£b«m·zË€·àŠ+¢Ÿ'R,rì"è¦k¯Nì>®DuïjHåhn&dÔt1¿{ïqp«óÎ<÷ìóÏ@í3” T<%‰­B¨¹ç¢K+[#ƒõÍ$ÙîÕXg­õÖ\wíõ×`‡{4Æ®fÉtÈ^ª«ÖÔͱMõGv%-wÆ•ZZé™Þ]·¦þ- ÖEí„â™áÄ®âªÔåªÇ‚viW‹h?½.bn‰öÔoAM7lç'µrvî¾M¬U“ZžŽÏíúë°Ç.{Òkvä\¦¾båj§eœÛ.ñˆðÃ{’]i›‡öòÌ3|óÐG¿¼åk›ž¹õاÔ{ö†Ïý÷/Q~pço~_âŸüöê·¯Wúîsüô Æ~ý»â¯¿låÓ?ÿþÌL»²÷¿Ð5´º_d|£À×4!¤Ë轪å5£—Sèõ“GQ%*4™uPF•NPR„I ms‡x+]¢@·Aœì(x1|ÌxC3º¬fšM ¢«³9šÑÐ…¼—è0è‘ÆÄ‰Ht˜TÅ*¾í-òªáHèì°e(ë¡Í¬HFóÍ,0¢+£'E´qpü•{7Ç7Ʊ#þ p Á‚"L¨p!ÆBŒ(q"ÅŠ/b̨q#ÇŽ?‚ )r$ÉJ¢L©r%Ë–.ž|)sæÈ˜4oâÌ©s§H›<5è3(QŽMª”äÐ¥N]6}êq(U¤Z5šõ$V“[µf½¶ëÕ…Xmr% ÖêY“eÛT›6ªÔtëâ y7ïE´Ï’E ˜ëßÁF…. 8ñÁ¦„ÿ–u+9¦ãµ]÷òåˆ93g‹›;CŒ*økÜÀMCë®Wµk%ÇmýšräØªiƒÖ›{wÆÏ¼Z8ñ†¾‹#OÎû¸òÜÌ›C¾ô¹ôêÖw²¾®};÷îzÃz/þ~<ùÓàË£O¯ºëõîßÃ_y¾oûøöïã§ÿ¶Äìùÿ q‹Í§"˜ €”1Ñ Ba~&ô „.G†šÕ·¡‡žÕÔŸ†Š8"‰RåÖjü–bj©Há‰%š8£„wíǘh/ª£g2Úh^Cj×a™¤tF^Ȥ’O:TcPN®ç•P>éâd,æÈØ[ˆU›”féÝ`Wb™f˜‘­Ø#]&æ——9ŽiàbÝiXš{*˜gU~â…$ŸƒFWæw~ê‹2Ú¨£‹0“RJi—i¦pÊiŸ~ª€¨ º§žÚ€ª°Úª@þ«¬Ð*­·â*Á»òÚë®h*Ug• [¢P‰*ú¨²ŒFZ©³— é¦"j¨£–Šjª«ºÊ*¬²ÆJk¹’뫹›T±é­k]ºL!Ûвó6묥˜JKmµÖŠª@©¦j«jÝz n¸µ’‹ë¹¾¾KT»å=ìn¼‡r4ï²õÚK´Ò ¯µ ôû¯¶ Lð«C n /ÌkÃSžñuÛE³B+‹±½çKíÇ!g0·Ý~ ®Ê+ÛÚ²Ë6ÿ$³xNÏÌtoGá\µÕôJš±Æ˜R ©Ç Pp­¿A£Z2D£|4ÒJÿ*5v8Aí¥Jqé6EX]÷£þì-:S@@à[GÛõ´œ† v¨ŒM* ó‹-ùBì|iS_ÂØ'½·‘zïÑÓm˜„hAZˆà#hA Vð‚È £Õ³N}êvþ[@äx×*ß¡Omë+ž{b äç…}© ™B(2!ê2GáÇÓÃþNZ³û¡‚XÄL‰›Œâ@6* 8îT3›Pˆ2 D€·Òb®(`@÷Ýd/ò«Í—–g›6­‰@Ÿ#c‹^('Û0¤…”jô¥/ ؈«Ý;u”>öQÌ#YȰ‰w¥*!¨hEpa‘V\ä≧´êDŒÎCciȈ61Ï+r{ãŠp¤<Õð†úé+[éÊWÂ2–²œ%-GX¾¡Un€Â“%YvI0ÒDŽªˆ0x”!3™Ê\&3›éÌg2ó–D›ÁTX@:~ªÄVFæÍo‚3œâ'9Ë)M“¥€åÂ&hŠÉžmró(&›gshÏ{â3þŸú̧/[†Éã9hŸ(A Úxêç ](Cúª©Îj:»×þöu-²IŽšÁ»¦¹°ÒÏ…ýó}Ã)ÒAJÌ£ ,¥²:J)x)¾tƒ”)'h8ŠŠÿ›bÎF¹‡^.‹ëìèQ>z®†ÑA0acÍè&„hi?£3KIçÌù o‹g1gäJˆªÇyUŠbýêîÄéÕ)úîl@=X/oÒ¢º•yÎq>ùÔS6•†§´«Ü¨ªÔ>]õnpå%¢l5ج"6±Š]¬aûÖ^~Ñ¡+gjDɇŽ5óbÛÎÔ«‚‚6´¢õ,û–†Ùœ9©MÎ7{†½¶´þ²mdikÛÛþrµÜÔfüD«˜Ñ7¸Ân6hÒºéVM­=.seÓÜxÚó¹Ò=Ítç·ÜêV7°7ôOr±kÕî©Þe®x“TÞñJ÷¼R/z½«]½·½ò/~Ø+ßûƹ1£/~û›ÃõÚ·¿6fïà#‡à}JìàmøÁ¥ˆÈtºÛ)b ¾,*'LRie²œ“š–@ÉÆ.¥(tÉÛSYÜW{X8Ža0ÝWb8º˜©/ÞqQébÇXÆ»iaƒƒlä™Á ÔH„,à¿ä²MfW‡œIÂЮœ„£npø¼Pr©6rò]¡ÊeR¶ØG:™¶rRC„×7Ή?ȳ’d]4º6ÁÏ«¡Sóäü¦3úÄlns|’ìfà@yÐ ²O¢ý\æÈey¬™‹~_s9G:;†n´£ÓÇ%ã¹Ìgº4©ãæÉ¼‹Óžîfà’bù‰F.²&M©ÃÔ`U¯z¼¸ sík¿÷×¾re‡mlÎñºËÇ^vÓ¤4»õšÙÒžltûßi_ þ$XÐàA„ .dØÐáCˆ%N¤XÑâEŒ5näØÑãG!EŽ$9ÂI”)U®dÙÒåK˜1eΤYÓæMœ9uîäÙÓgÍ’A…¥HèQ¤I•.eúÑhS¨Q5>•ZÕêU¬Y!RÕÚ5+W¯aÅŽ%ëlY´CϦeÛÖ-ÙµoåN[×î]¥qñîm¨—o_•}«.ÊÐïß ‡/¨˜±A°Š—œ,øñ×Ë™ VΙ UПM6öܘ´hÓ©CðËõéIÔ¬c˦ {têÚœ5ÏÞýX·ï”›…Ó&nºôè³F“ ×»|yqÖÁkC†®¼÷Äß×Ùf_ìš÷mè¸ÅþƒGNÝüAçæWß~M}-÷ÝðµÃŸðyñöä­7®ž=jÛþ@ýò{Î;ù:«±tðA‘„ð* '´ðÂÂ0¬«B ;ô½ßâ0D5±D¡NDqÅUd1Âc”‘¼1«ñÆ]ÄqªŸzôñG ƒrH"‹,rG$;D)I&›tò"éž”rJ*?[²J,³dòJ-»ôòÅ(¿sL Ã$óL4µ33M6Ûì.@7ã”ó(8y¬sN<óéN‹ÖÔóO@+‚m?ò3PD5”´•$âRQH#Eϵõ¶zTRL3}ôRÃ8ÍôÓHu”OPK…”»CMU5QÎR]õÕUþ]…URRKõtÖu,´ÓWeÅ•D]Ç34X,}ýu¾õ’í5J—%pTbŸ4öXdù#”8ÏŽ0øjÅóVj-l¿]µíïÙ¢¢½qÚpô[ýD3W¶fËÈÛ3Ùm÷XpÅìw_€Mú·J}Þw`' 6ØC„Ãjx݇–¯ˆY¬Xâj¹ÔxãÐ8FîÒMáT¡‹! _ŒÅåO5¯­.<—_Öqdd[JÌÍD­ÑÈxv2Kîåm¾çïp{oåBc–,$šß|éè\' °gÛÞ»ò¾“w&#Q냉j²G2è°ÛJ»l¶OÛsj#ã–[ȶýU×ê¹óÖ{'þ»înǯ{# 7üpÄ `wÜñ"7`òɰÜò2Ï\Îð|B½Ò0ýt€`uÖ#p]Øc—]‚ j·ýöÚ…¦PK¿ÿ ¼£°u?(qâ_üqä#/€òÊ/G@óÍ;ÿ\ôÑKGÝtÕY_Ýõf÷wð'~0Þwü²ó*~ý㑇\ræzÎøtêIoàzìµßþuïÉ.|¸ŸTzW-óp!$ÈúŠ×>÷@yÌ3€ü —€úÝz ÐÿRç?p/€ í^'…{IÔZ˜‚î›`üœwÁ N/Ö»^ö´'Âþ®„&|áî²´B¼œlE^ 7ÃäÁr¤Ÿô<·Áòχ­`‡˜;&’ïˆ[ £8âÄ'2.‚”bó.‡C+âOtYì!èÅ/*‘)HÔ “XÆ%ŽÆSck8ÅVÑ~:œ#Q·Åÿu/ˆ´Ë# QX¾&é;–È ÅÇÒ˜S¤w¸?-Ú±‹#ü¢ø8¹GLfR“–¢€'m9HP¾oy@ä@è-òЧtêè¿;²²’~Ü3…¼¤8“…¯¤å-­éÀ\6n‚¼åü€‰Á8b±tÆ|¤*%‰Ç!Î2šQ!Ö ¥9͢䚶¬%âjy’BRþÀqúÜæä(à¼o~“søDgÐ’ót á*ØJu"%žz—ȶղuR)jéªç<ÑØQÃÝs†úÔ'wI9•dN æ jPŽó˜?tè÷–Ù7:f;ÍÖyˆòNÄDÔj$H 'ÒB€¤Ú”/y P•nŽ¥¦„iBgÊÅs*3ÔÌKNýÜŸùô™”éÒF"O¢~ôp' XR¥šô$xªåNUp´ ¡C(éNrÕHN’’[jŸ$JQt h:˨—„ʨ´zÔ­IâòlèKÍåp˜D%`šÕ‡ÞtC±ü’Yís’5¦Vµ«u\×(Ê &2þ³á$f*‘YÓÙA”«%šÓLÔ²V¸Ã%®I)HÅÙ¶Tœ-çmAkSÂâtŒlZG‹{ÝÆ¹6‚(¡acëKƦÕcîBÍ)XÝVPf[`ÇÕõÖlM¿%Ypר]í 7¿s­kaKÅð¶t¼1í¬BšÌÐFw´öašeH–4Ã0XÂ$‰¯»xv6+Q@yVž†7ìោÃ+ 1ˆS9k8%ñKITSr¿£ätÖ>+ àÇ(¢hçÒ¦ì·3Ptê$ål*û’™‘[Å*šŒ›D)ó¦LW :•ÊZ¶²?»Œå,w˜v©ç`Ú×ý³%þ¬£@r »7ËŽé•îƒã%¯°*6?IsËäÅ’òk26ÑMä'¿ÚÑ+A@¢ÚhF7úÑ’F´¢/7æ`–Ù¥|]I1Í‹Ì6Ç.΢¦ó‚í\Ÿ1Gg‰õó¹žèü Âb †3|èI_Zׇv´®{kJÿZÒ¿Æ48í§×3xÆŸ®±›Eí½9ûX.@v­c&ž=ZÛZƒ+5VZ÷ꮄÞ7/hîk®ÅèF‰ºË×wÿ²ÝcV Œ©—Ó­ÙÆ"ÌñJz¬à+¤ÛNÎ0¡¢TQõ,)Éa¢TÖ`­j}bæ&wÅ-~qŒg\ã׬ÉëÁwqÔ±þ+uÀQÔ-j¡¤~+gyË]þr˜Ç\æ3§-gA~ÞI–|Ú¤Jî÷s ]èC'zÑ>ôåÞܹ蕶ˆx+Ÿ]êS§zÕžtÛÒô¹¹mº[$nj\¡dƒc'{ÙÍ~v´§]íX÷,‚¡[ÂǪåé⦀þì~w¼ç]ï{ç{ßýþ÷òöoé9ïºÚæ«¿zPñ{c|LHðO÷W2V¼ù–<î»=ìVÜ娔'¾ò×ûXœ˜K)bœŒŒéUÝ>XžDóŒ{ŠîuVŠž_'aïÙlÔõÕóžhmk[QòVÔ¢˜®'™_ô\z’ƒ2—°qJ¶N{Ù“¼ðÛ¹þý¢è¥1‚/Ù8¤?ž ö›¯Ï%¾÷½}W[Òü.yòßg¸©zè}U3ölÉ‘ƒ½Ûá1íƒ<§ó<ïK°Â³ Sxi°ô¾á¼>9 î¹@ ¼À¹¢2ä¦+ó²Ä2–3üc‰Ö3°ÿû¬Ä¾QÓ¹Ľ̳ ŒÖHYc2B@ˆ± ”È@t¨3:d:‚Ò¿‚Ò´Ÿ3B"d=¿ò´ÔIAîYÁð!ÀÛ¼ô“@,\ Aã©ìÂÜ©,t°‰“&*  –=Ô!'…Z¶5Ì·£¼6´<8$=êS‰ë›Âì«B¬³0”0\–­šlû¾óÓ=$©=Àþ¹—رlDG|DHŒDl3 L°ØkÁíK ݸB3¬î## LÄ™€³hk%SÔ(ê)s );GxeŒÇltFöâF7±‰ÓúE~$’¾éG€ü‘º¡N,-{H©iHÀ Å?‰ †L‡œˆŒÈh,ÈC\H‹L’ƒLÜHŽœÈ6ñÔ(‘$“a,I09ÉnÄH•¼‹ŽFP–|I%qÉB³Išœ&PIÉœÌHL‰Éž ‘™œ¸ Ô Ì•¡,J‹IÊ“cJ¥\Jœô£|J¨ÌG§¤Jõ»Ê™J¬ÌÊê’ɨìJbG° K²þ,hð „ 2lèð!Ĉ'R¬˜ÆŒ-rìèñãÁŒ G’,iò$Ê”*W²ô¨qc˘2Cbœió&Μ:wòtù’BÏ E -jô(Ò¤J ¾\êt ѧR§R­j•aÔ«É{æä†Ÿ ¾žíÀpÔ.'ÒøqÚÈc'×m]n×ß+ƒ³uþ<ºwèþà 7Ç*þ1lò×׫Õ.Ù2àŠå£ÛV~zùÖõïïŸ_6{Våžh7& ‚ H S ZÄ‚Jx—ƒ ²á„jx†tÅGQ‡¾å؇"šø`„"WâS*ö”Þ‰1¢è[V£1—Y!Ê™Ž(ru£i|%ÇZTùådm0¾V£_K²(#” ¹¸Ð|©8–â•Ä[”Qw–°ç\s¸õ'æxiŽ™e”m §Lÿçä¾Iù$Je÷xú}é]ãí'&Qmõé&¢TÊÄmg¦zx¦¤ç•dÊFi¥lÎy%£ÏEc¢¡jJc“5rJ¢¤ž¡:%eM=º¢äjœæ(9Z©EBǪ¨Öñº’/Öõk¯Å›X—Å*»ìˆ2¦Ê,´Ñ’–ÒZ{-ˆQ‹-·nj‡&}õŦr—nº¢¹ZbÖ-»íJ'¥Ybªæ¨è=Úi¹½¹»ï¾fb*¾¯‚In½l+¿ »ë¯•ôúnÀÚp¾¬0ÆÑþº­e{Ìî”ã$òÇ%KØÔ³%I²É-›ÈòÈ.Ël2ÌÀÍ|óÇ5·¤3Î=kÈó¤> 1Ð[}´Â¬*ÒMóKlu^:=uÂ*‚f5ÕYgœjʵ W´Öa‹=6N;msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/doc-files/redefine1.gif0000644000175000017500000000672307271644421026044 0ustar giovannigiovanniGIF89aç÷ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ::ÿWWÿuuÿ’’ÿ¯¯ÿÌÌ3J` w(Ž/¤7»>ÒFèMÿUÿl"ÿ‚Dÿ™fÿ°ˆÿƪÿÝÌ3"J1`@wOŽ^¤n»}ÒŒè›ÿªÿµ"ÿÁDÿÌfÿ׈ÿãªÿîÌ33GG\\pp……™™­­ÂÂÖÖëëÿÿÿÿ)ÿÿRÿÿzÿÿ£ÿÿÌ"31J@`Ow^Žn¤}»ŒÒ›èªÿµÿ"ÁÿDÌÿf×ÿˆãÿªîÿÌ3M"f+€3™<³DÌMæUÿhÿ|ÿ:ÿW£ÿu¶ÿ’Êÿ¯ÝÿÌ3PmЍÅâÿÿ3ÿ3MÿMfÿf€ÿ€™ÿ™³ÿ³ÌÿÌ3Mf"€+™3³<ÌDæMÿUÿh:ÿ|Wÿuÿ£’ÿ¶¯ÿÊÌÿÝ3"J1`@wOŽ^¤n»}ÒŒè›ÿª"ÿµDÿÁfÿ̈ÿתÿãÌÿî33MMff€€™™³³ÌÌææÿÿÿÿ:ÿÿWÿÿuÿÿ’ÿÿ¯ÿÿÌÿÿ3(P7mEŠT¨bÅqâ€ÿŒÿ3™ÿM¦ÿf³ÿ€¿ÿ™Ìÿ³ÙÿÌæÿ3Uw™»Ýÿÿ--ÿDDÿ[[ÿqqÿˆˆÿŸŸÿµµÿÌÌÿ3&M3f@€M™Y³fÌsæ€ÿŽÿ:ÿ«WÿºuÿÈ’ÿׯÿæÌÿ33MMff€€™™³³ÌÌææÿÿÿÿÿ:ÿÿWÿÿuÿÿ’ÿÿ¯ÿÿÌÿ3M&f3€@™M³YÌfæsÿ€ÿŽÿ:ÿW«ÿuºÿ’Èÿ¯×ÿÌæ!ù,ç@þH° Áƒ*\Ȱ¡Ã‡#JœH±¢Å‹3jÜȱ£Ç€I²¤É“(%ŠLÉåÊ–_ ”‰&Ì4m:ÔYçM—?ƒvô)ô`Î5‘<º´©MžP6ð’éʧTµHt«×…]¿ŠKVhزcÏ¢]»4€Z¶p³ÆK·.ηvóêÝË÷¤[¼} ¬0UÄ+^\ôªÛ†K øïd—"ÏF¾Ìò_ËJC¶Ì”àUÓ3+nî|s5ë×°M»ŽÍq6íË®«†–+7·ÒÕºSó>½›«íÛ G+Gμ9Øå Aþì¼zbé-•GFl=f÷ïF¹‡ƒ~gùó=ÉkT>yû÷éa²‡ß“¾ýðó“ÞϘÿwíÎÖUiÃG\¿É\jÀ‰ö›{Â5™–ÔßkÜ]Xá†Åqø†Vhˆv"nØ}eℼ!…•v-¶5j¾µâ‰°QTfbGb]7âÞŒÍø#zG ©ä’L6éä’þ8`Aƒ&T¸aC‡ <”8‘bE‹1fÔ¸‘ãĈA†9ðãH“'Q¦T¹2cI–/Yº„IÑeÍ‚KÊŒ¨ó&™>ö$¸3áO¢B’ˆÓàQ¥Ig^„•êÆ©U±fÕºUãU®_‹‚;–ìX¯eѦU 1ÀÙµoáÆ•û¶­Û¹wñæÕ‹²î^¿*´h[Á‡'¦[÷j_Å%:ú”ñRÃK}Þ)ÙòåÉ‘íBVÉYti…•?OvŒš'Ò¾L1’6Í7ôlÛ©˾ý±îÝ[7U*|0ñÁFÖæíûwæÞÍ¡f²wuë×±g×¾{wïßÁ[£>>¹òÑäc¢W_ø«ùõßÇGè9ª{ù íßoŽ:e~ýaÿ ¿çš®¸Âø‹ì´œï4ñ¨P–¸c°@“B*›ps 3ä‚ÊpÁœŒ[pÂÏC16YÉ?_lQF ñsˆ)þ6£Ï9Ê6ôŒ§•3/ÆÕJP«Æ´ ¶ãŒc­¼Ë~$7šˆŒNÊ•p®J·ìÒË/Á SÌ1É,%€þH° Áƒ*\Ȱ¡Ã‡#JœH±¢Å‹3jÜȱ£Ç€I²¤É“(%ŠLÉåÊ–0cÊœIó%Í›mâô çΟ@9ê JáТu*õ™´çK§!@múTêÔL©FUè´jW¬S¿&+lÔ«HM‹tmѪ»†ûu©\©E•ëÓí^¼WÚ<p\«wݲݺx±â GŸ^µ+XíÜÀfé.‹îa­u ÿ¥Z¹qÂǦo¢NͺµkﮎM»öÎÙ¶KâÎÍ»·nßÀƒoD+¼¸ñ㮉#_μ9NåΣKŸÎ3+õëØ³«Ü­½»wçп‹þÿzôiîäÓ«—>óú÷ð!o}l=¾ýŽíïãå˵¾~ãèE„žÿm¶6¦ÔYŸÁ¶fB U n7a…3ù›g vØ‚ ˆ †q]Hâ‰ç¡˜—‰*¶¸"‹Úè¢i0¶%ãw|ñ7ãsŠÆY=>ˆ™y@Ž”v9Þ¸#KD–æ¡ê•—‡NB¢Pœ]§ã’\”ä‹9Ʀd—]Ž R’w‘Ù¡šåÕ8tnÚ'›^šékâ™ÜœñùžŸz2 ¨J^YhkGþè ‡ Ê(W…>Ú¨£’æ©f¥“Ö))¦ÞqšiLYfäiŒŸJ&]ùÑdCŠÁ¨ái'½Zªh¦I_– þ"a!JÕhUZ9%‡OÂ:kw¡uà”OVɯÐ[¢ƒžö*` 2$ë±¹m[Û„ÞrK[¸Ó‘+nr‘žû߀µ¶ëî»ðÆ+o¢Ìª+'¡¬ˆ¯½ñ èP°Â +¥±Œ ÜëCþòûœw²Ú׿Ål°¥?Y±¡jí«ð  fš§fbÂ2“¨ž|¢¹%#œ,–h½Œ!Ë-ç4/š«^ZóÎ<÷ìóÏ@-ôÐDÍ/@þ$XÐàA„ .dØÐáCˆ%N¤XÑâEŒ5näØÑãÇDŽ$YÒäI”)U®dÙÒåK˜1eΤYÓ&K9uN °ÓçO A…í9Ԩ΢G•.eÚÔgR§Q%B•ZÕêÕ«T±n%¨•ëW°a7z[•lY´iÕ<»Vi[«&ÂZ²"]ºnæÕK-U¼RùÎí‹´pÔÁMw ÙØ1€¢"Ù:–ü8idÊ ¡FÞü2ãÏ; ¼L:qÜÃNO/µ :3éÉ‹kíI;vBÛ¶C‡$ {wãūͦVü×õo×^eO¾ÍܹÁÜÐ}#ÇŒü³ò‰5î|ôhغÃþKß]Ýwå×çÉ—æ­žyg툷³ž_ß¾ßûBãççßÿ¹ÿœöp@û$p¯Tð¿32°AÅz0Âé(´°¾ )ÌðB‹ëð®›BqDK4ñDkúpŬÐcñEïs1FkÔk$sÔ±,wôñG³frH"ƒ²H$“ì¨G%›tò"&Ÿ”rÊ¹Ž¤òJ,EËrË-£äòK]ÄËJ0ËÔ<„¼4sM /ƒ‹L6ã$Nè6”óNÝÃN<ûÜ®µ7íôsÐ dKPBSSóÇÊòâ3ѧvZíQù\Rý$å ÑÅô#öÊóŒ=1ÁûnSN?¤ôSˆ–«-¹æþ<›PŠ.urUV:ëUËZ¸÷@LUC\suèÔYãUÖëº2¯Öa!,ÖXi§¥ÑZj´•Ñh³ÅÛ·õÖApã*7A&ÏAÕ0¥u#ª ½të-Í^༌r_quu—?œâeè×ÐBï¸fc•uÙ%ÿ-^ s–VÓìL®è´ß©8F÷¤ˆu5TT4+d–a“} Ðcÿä Yä:éÕøYÞE“_zY¶ÈåN{{9K”ÒäÙ-Nr%Ñ–ÐhU–÷¥.™µÛ=!þ’êˆnÕgf±ÄZ`­,ók°É–øj©WF L³ã-Ú0¶Ó^¹í4Ç–{nù⾤þ·=¢»Ó½ñfêo Ï:l˜Ñ)ÄÏæÒð¹6ÒîÅŸj7Ê+·ükÈçÔÜȾåÍüs¢.·ÎkÒ’œ;½S¯+tÌ5Õ Ü]Us}ðÖ&¶”Ý®yW¹wßGNÔÛÛäßc_xFží­n^æ{„¼¤{.éÁ:/~f¥OWa”N¯à’ –:ì¹^V<ͶÇj&Þ/¶X:ä‘ ¾õ*îíM„½Þý·­níƒUùÄ÷šPä;][ÖgÀäðFÁ›ÎÖ—®û­GÓ“îô·¿Øän`Ì£jE¾hï](œ`ëX˜¶ì…k‰aj8ú‡a¹a~z¸ÃζªMSbžDç¸ùLªˆK;b„”¸D°<1‡ÔR¯Îã@+Œz9"Mw"J,c³QXùîu²Ä¥±ˆ_äÉÖø’Àð…Ïþ{àÿìÁ%ÂŽx{¡é—?ó)ƒž Eæ-fKáΈȉٮfœ#OØDH&ò(œ±ÚSôI=2“‹TîVW¤zK„ŒÛß)Q9J7jm•íyR*_ÖI>Öot°ÜLfJ`sD¼$f1yLd&S™Ëdf3ùLhFSšÓJ@;msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/doc-files/redefine3.gif0000644000175000017500000002060207271644421026036 0ustar giovannigiovanniGIF89aY÷ÿÿÿÿÿ÷ÿ÷÷ÿ÷ïÿïïÿïçÿççÿçß÷çß÷ßß÷ß×÷××÷×Ï÷ÏÏ÷ÏÇ÷ÇÇ÷ǿ￿￷﷯³Ìæÿÿÿ::ÿWWÿuuÿ’’ÿ¯¯ÿÌÌ3J` w(Ž/¤7»>ÒFèMÿUÿl"ÿ‚Dÿ™fÿ°ˆÿƪÿÝÌ3"J1`@wOŽ^¤n»}ÒŒè›ÿªÿµ"ÿÁDÿÌfÿ׈ÿãªÿîÌ33GG\\pp……™™­­ÂÂÖÖëëÿÿÿÿ)ÿÿRÿÿzÿÿ£ÿÿÌ"31J@`Ow^Žn¤}»ŒÒ›èªÿµÿ"ÁÿDÌÿf×ÿˆãÿªîÿÌ3M"f+€3™<³DÌMæUÿhÿ|ÿ:ÿW£ÿu¶ÿ’Êÿ¯ÝÿÌ3PmЍÅâÿÿ3ÿ3MÿMfÿf€ÿ€™ÿ™³ÿ³ÌÿÌ3Mf"€+™3³<ÌDæMÿUÿh:ÿ|Wÿuÿ£’ÿ¶¯ÿÊÌÿÝ3"J1`@wOŽ^¤n»}ÒŒè›ÿª"ÿµDÿÁfÿ̈ÿתÿãÌÿî33MMff€€™™³³ÌÌææÿÿÿÿ:ÿÿWÿÿuÿÿ’ÿÿ¯ÿÿÌÿÿ3(P7mEŠT¨bÅqâ€ÿŒÿ3™ÿM¦ÿf³ÿ€¿ÿ™Ìÿ³ÙÿÌæÿ3Uw™»Ýÿÿ--ÿDDÿ[[ÿqqÿˆˆÿŸŸÿµµÿÌÌÿ3&M3f@€M™Y³fÌsæ€ÿŽÿ:ÿ«WÿºuÿÈ’ÿׯÿæÌÿ33MMff€€™™³³ÌÌææÿÿÿÿÿ:ÿÿWÿÿuÿÿ’ÿÿ¯ÿÿÌÿ3M&f3€@™M³YÌfæsÿ€ÿŽÿ:ÿW«ÿuºÿ’Èÿ¯×ÿÌæ!ù ,Y@þH° Áƒ*\Ȱ¡Ã‡#JœH±¢Å‹3jÜȱ£Ç CŠIr …’(Sª\ɲ¥Ë‡'_Êœ92&Í›l Ô‰çK <}:Z(Σ"]ÊÔ Ò¦5‹šì9Õ©T«R}ÝjUëΪUczúªÊ²fÓÎD«¶­Û·p+²K÷ãܺx)ÍËäݾ€ Æ tïàÈ+^ü¶ð_Æ#KžLyaáˆ{/ç[¹³çÏ —j†º4Æ¿£M«îœzucdž¿´ ;óÕÙ²e?6ÛµoÏ­ ïØ{¸qÊÁ[,NlΰA¡ãÎÍY÷ôÓÉ•kW¬ööï kþ3t ¾¼èÚÙÍ÷-žýÉôÈŸO¿¾üèß¿¿€ˆÀ€&`  $¸À‚ 0à ƒ DèÀ„:ðfÁ†tèá‡L âˆ$Š_\»©—›ŠN±çÒ‰Ù'#}øñg£( ˆ ‚ >¡„Nxa†nˆL–èä06ÆâD)jçâYWR4ã–5ÚØßÈc>&¨ƒ aPPä‘H*É$ˆO–¥[UUKy–w§F…m)è õQ`Ÿ¡t©0JŽ„)Xi  ÇC²éf…pjÈáœÖIâŸjõIåAÕá6–xþ^ñ9eFÞ”—¸æªë®¼ÞøŸŽcúˆ) ÉÀšE‰d’£’¢©&fI—ªàQ;ëxî¹WP:vi·’î¸àŠ ¹çŠî·âRšPÃfÊ §R°æ§ŸZ¸,JRÐ!Pú m´ÖÒ¤Tt`57ÂÏI—°«:1¬°QGLÚµf&ìÆwìñÇ ‡¼±™h‹l²¡2»ä¿s ¥´(šWeÁ{T˜±8ç¬óÎ<÷ìóÏ&ùæ²Èéì³Ð¢šÍÊ1]óF…%+5…0;¡Šò÷«–yf± ­¬¨+Óùdaº¬tƘ]ŒØcN³VõJ…)i÷ÝvÃ+òþ¥—úXißþÍ1àÂÊ ön~údûk¶“h—:ðÚP¡vñX]±^BïYÝpCp?ÝâÜ~œm䜮úꬷîúëµ¥=9émYnZè¢'•-L«»ìûïÀ« TðÄo*åMÅ=œò¹«†|ó2íýôƒÑN=Ý™=ýö•[Ï=vÌ/~÷áç®ýøè¿]~µÞ§ï~eÒSþûôß¾>cóׯ?r´j~Zík{OlFCž p3´9`y±+ÕjÛ"¸?ÑÝ$dUû8§ÁΦ;lUÂz3ÁŠ>%Là+?߬xÉ ]<ÇBçåsa¹NÃdHCòÐsMÓaV–¹ÛÐÐbÎ b±‚ÃÚP=ùs¢AÄ=‡aS±âWbuÌ Q/S ãÓ^ØÃþPŒhüÌg˜Æ6¢‘iXìŸçHÇ:N þ$XÐàA„ .dØÐáCˆPXÑâEŒ5näØÑãG)†$YÒäI„#Q®dÙÒåK˜1/ª”YÓ&Jš7uN$H3çH•?yö,H1'Ï£BL:”¨Sƒ@6UºÓjÊ«YµJ\ºÕëW°a³v[ö&Y³iÕ®eûm[¸qåÂ¥P÷í\¼yõîåÛ×îݾ&\¸å_‘€ /fÜØqYÄnƒBUüØòeÌ™MFÖ¼×.Ó¢#ž*ڨ韤¡Jîܺ5g×bG‡žZ·¶íÕMQ­œwlàša×ÙÛ¬jâÉ/WΕvTÐП>­[¡q‡±7çÎVû÷îþŸü^ÞüyôéÕ¯gßÞýûõžáϧ_ßþýóá³o/‰\£p@€L° pÐA"Œ0 )TàÂ2\€9làCBÑ 0ñÄR”`E[”`c”FÿäâO?êp\¨F˜x¼ˆ@ 4PA",àA%D B 1Ô°CA1ÄO41Å\ÔrF.'ð±­u,M̈ÆsÉ® ÓT3H l“‚þ"ò»ÿZR» íÚ°Ã怜ÒJ,µt±Ë¿ôN&Õ|Jt·žÌ/¦0ɼ §ºÖ´ôRþÊ4Síæ´Ë ´“‚ íÊÓ.(ÿr€?­¼REAþY$TFC׊t¦ßÍU:Fo; RIIz4*3Sª‹HOåDvÙ9™E¡]°A$•\2R¸P  ÊÑ<aõÅYi,6.´†…¨ÝéÞõíºòBº5X\Ócª.k­¥@É% Øß~ÿ˜`#~ú ›¿þ¢àÇÿÁÊw_þð1îzx@Ì|é~3#‹DzÀ2AðwÜûúóÀH¥F;)«—ã²ümWÖétêEÁ`YX+q ]ömŽ2û¢!QvÁý¨0OqTËhã¹1N0eª!o^ÆÃÐÝð…ÂI¡¯ŠC.Q<ìZ¡­(©·4Ð)BâÍ|X3š)Ñf3»bÁFÏpÎŒk `…ÅF8šQ‚jÜæÜÇþ€À <ˆ0¡Â… :|1¢Ä‰+Z¼ˆ1£Æ;zü2¤È‘$R(‰2¥Ê•,[º|xò¥Ì™#cÒ¼‰3§Î"mòü Ô Ï DP8Z4©R’C—:uÙô©Ç¡T‘ ½zñ®×»ùùøôëÛ¯;æãÚ÷ûûÿ_Q~ ±µxˆ`‚¥8  >პF]„Á1ha†úa¨!T5™Wa‡"¾6¢FT¹µlo¥f[j!rXbŒ M(ãŒ6¦è ƒ•ÈØDíÕäŒ?)ŒDI"’Ä ©d“4–bQL6éäQjÇãd*–åŠUÛ• MI%’ƒ‘I˜‘áèe‹\"Ænmö8Õbeyæ™w.—§b}€2%¦gy> ‘Š.Êh£Š0’N:i–€)¦lºižzª@¨ Œº¦šÚ@ª¬Êª@þk¬Ì*A­¶Þ*ÁºîÊ«®h:U¨{Áb9,ˆŽ‘£Ê2 )¥ÎZZ@¦šrŠÀ§ ŠJꩨªÚêª¯Æ ë¬àJn¯æNðët#{]º(¹ëвò6ël¥—JKmµÖ†ª©¥j›jÝz n¸´’{ë¹½Â+åº 2¬²‰Ê«,½õ­´äkmüú«-ìjÁˆ‹p ï 1v+(qM1ÇK±£×›1¾Ôvüq¶sÛí·à¢œr­+³æQNO}õÖ_}ö«[ ¸Æ[Úó¨!<°ï'Sž2Úè”óM+)(FXqOýöß߽ΜòŒ­ø? \¾²¡aêƒ^NÜ×ÒÇ0­™V AhQ ‚Œ -XÁ  ƒŒ–þ:e8õoÓ«xg>³¥ox ,É^ºäÊÏF4dÊ „t¨¶`EcL(þ8iÅî‡b1eD$j 0!ügªÅ‰Í(4"@[eW( û~òÂóœhG.²š '9Í 1~a‘ænH¡Í`%_ù¢íH¸Ùå‘SGÙãñøÇ;"ƒìZíBõD(FqŠU×gµÅ-jQxG3 NdÈ"­FœDÞ&éÔÆu.“:‚ ç†8~©r•¬l¥+_ ËXÊ2qÿ Ð"'@àI@’*«ä1Ÿ(µ°FXñ—1‰Ìd*s™Ìl¦2ÇwËÞå2x”\™%o2ÌvÒP% ™7¿ ÎpŠsœä,§ X0…ÎyÙ6}t’É“Š9¬§=ï‰Ïþ|ê0½´æ/wòœ} t -(u²#¬<`¡ m¨C@7ÔIíföÒ¯6Ç‘mrºì'¯°âÑs]“&ÝÎAßI¬˜l¥±:J)h)Ætƒ¤)'(¸ý/‘ÿ’bÆ9ˆr”—FéQBj®‘Τ¤1ô$?WÃÚìGMc2€”*¿£Rs—g1gãºÅÜ…ì«ÚZX½ÙM)ònlB5Q‹šT­ÂÕŸÕÍpšš¼Q&&E˜Ñ¤–ÜTÕÒÁìŸ&’k=k%×­*v±ŒUì[×W^z±® a*_®tR !ªN]LÛ™>jÐЊv´GQh)kw.m³Ü,íiM ÛØþš+²­­m}‰Ú©¨öH£õi Üà´KC©u°j\"7¹Zî ñÉÜèFºYe u¯«ìư=¹Õn  (çz÷Nâ]xÇÝòJè¼èÕ.{5ûÞö¢7¾ÿQ¯|½»ú¦Ç¾÷uo5ÄÚþ 8@Ö}˜~ŒàñwI N°ƒ¿ÛÝã·BFbß{rà#$³É“°65“–Žhxÿ„¡œÆèFå…iy%óâôTÀz˜¸x±%a›ãÉ8¯<lI Õ_h7 °¬`#«À½¹0’k– *t(E D"Mªt)ÓF›Bªñ©ÔªV¯bÍ ‘ªÖ®Y¹z +v,Y`Ë¢z6-Û¶nÉ®}+wêܺvï*‹woC½|ûªì[5pQ†~ÿ=Œx±@ÅŒ ‚Uì¸ädÁ¿^Î\°ræÈ©‚þl²±çƤE›N€_®OO¢f[6mØ£S׿¬yöîǺ}§Ü,œ6qÓ¥GŸ5š\¸ÞåË‹³^2tå½'þ¾Î6ûb×¼oCÇ-þÙ5ñÀ8îÍ÷Ù ¸â‹3žø¹ä’P¹—_Ž€æš'Ðyç €¾€è 0Pzé  î€ê«;ð¯ÃìÐ^»íL»î»çž7T‚C¼cáfQê»@#¿øã“3_y˜g¾9žú覟ž:못ûë²Gp»ø¼“?ñL¯]úx ŸXû %ÿòÌSn9ôÒOO=è ŒN:ö¨7`{ÜóÞ÷f'>Û•wç[ÊúT†¤÷ä|ñKÞüèGçAÏø£^ö×?ì1€l!¾"0º[`^´Ô@ö½ðT#š ò*H? ÞOzôàõþ§½íuþÏ{'D!íT¸BÚK1 5C2Άͳæ6¨?뉄"`cg@"±wM¤ ™ÄÂ`=ŠŠ“âäpXE^‘=4ÝXÂ!‚1ŒgDÊ/ÓG&öQ‚j\#ä,xA*Fos;Ä¢ÿèøCÖu±€á#"îô8F«ü‘ANÚãC9H°±~ÏË¡"ãøA‹wü" Ãh¾K¦Œ›ä¤aNòÉ[2”‘à ÞXJ TOŽYD¥(`Gⱕ–Ì$F2 ,>J –è¢.«9A]òy½L$çÌ2R‹©3&$W9É<‘–j‰Ê3ÂL®%Ö¼%5GÍ“’þÜ>yy9 Hï›ßFGÓT„ä\]$MÈʺR)‚æËšµ¨ka”\‰©ÒÍšiËy²ž‹»§ ÷¹Ïl`›)MIçJa.à  á8)ćŽo™s§Ó„VÑ܇(ïü‹D}Ò6ޤùÔ'SQÚË^´¥Ÿ{é)gªP›zñœÊL§4ÙÉSÿ`+¬L ÏF]XTyU"€-)PÁ“2Õy'I©5w©‚³ -]BQw¬J’’•äêP÷DÑéX4jîšWR Û®Zé£iµ¦[—:ÅQú²›žãá0™JÀ:T«Õé†d)¦ŽŽí$†\-k[K?¸ÒþÜÌßfÃILU"§·‹(d›âXö¡émA‰k‹kÜãî‘u-ema*ÎÏ–3·¢Í)awš¥ßj†mrS-r»ÛÔÕ÷²´â@9ÓìA—¡æ,o±‘vjjŒâò­œ´ÛµŠ…×°ýîq÷Ë<ØÂV¶Ëífyaz^š~v¡ Mæh«[ZûŒUQÖ¨„¦©²Ú‰%"nלça¹~˜!>ɈS"WWÎÄñŠWŒ’û±Ô›ÞDIÿŒ’Õ)Ø{­(Ð㣤ˆ¤%–•˜¦'¶…ÍkÆ9r˜4F²¡QØ3NŽ”¡€Òµ fP¥tÅœ–éÚe/gùŸÐÛæ—·‰?`8¦¢þ›i_hÌ–ÀŽð1íèl; ´×º†Påu®Š>fˆ•²†ûèɸ÷B8Áß™7Ѐ®¨¤#-iJ_ºÑ™¶«ŒÁÉ?½²y%ÅT/2å\;;Ÿ:ÏÞsu6å²-v8«†ì§Y¸Ê…–!£1íè_3zÒ¿¶¯3MìKÍÁTsLùŠ`“ZÇs>µøð‰Ò«nõ«c}èLÇíM§»[¨»%Ñ)ŸúAhö³£=íj_;ÛÛþl®gõé÷¹~â=ïzß;ßûî÷¿>ðé Óyö¶ˆîd!ã‹ù·ÇÃ$…súÏYþׯ òšo‰äUXTʼ·eˆ²ûB1cDŠ¡¤"sÁ9Gšb•ÁWàI:ŸÀÏ“D7•I|è{oñ“”0øq^ëëyO´²•­(y«jS¼R€^1¦'A(t)ð€§Äë·¯ýþÉ¿ßKxÊÈarh¥ðþÜLW¤¾ð¹ëÚ“úפ¯å¯>WœHýéÕ}}3÷v,I“í¡ZÏQ^' ÔøÔ¤Tܵ¬…‰›eÔHo¥ÍI€OZ`Ζi ™aÙSuàó¥Ä–µž°ì)˜ÿ…nßz_ZèÞ&सZd½ÍÃ1JÁàHàpQàúàœQÒÚÐTþ³ áëùÕ¨µ ‚ –Oußä…øI Ž®Ý ¡‘[¹ÍážÑౄéA›²ÿmÏBí›6Þ–^1]ŸJhßrßì­ ž…aÆ`Â)ÒË”½ú%ɆþŠÉ½ý`#:â#Bb$ú œY`ƒ  íá!ïá&¢…|¢!"¦ÐDY›+™â)¢b*ªâ± "æÌèm jy-â©m^.R¡f"BŠ.jž,R -ÅI°¢J¬b2¦"J(c36c(òÔqÔY!££3b£ç]c6r£+~_å}‰}mW5’O)vã9¾’9¢#:B£SH㼄(êL׬c=® =²ã¶8†‹•­ 0äR@d´Í`h⪴ãAZ>êÍ®1$á8d¡\MDâDâIEZ$(&¤ð¨ÍF6ÉBÂ#ŤGv¤Œ$YIFÓI–‰Hª¤Ê`$Þ[ÄäKzˆKr$MK*ÚLâdÆèdËØdOªÉOªO å½evåQ"eR&S2å^¥‰,eT¢dUæÈTZeMb%WBåVÇWº`W‚¥DŠãJ–å¡häJŠ¥Vþ 4xaB… 6tøbD‰)VLHcF9vôøñ`F#I–4yeJ•+YzÔ¸±eL™!1δygN;yº|I¡gPŽ"…5ziR¥_.u:èS©S©VµÊ0êUž0µvõú¬N amf%{mZµ𕨶&Z·kéÖµku.͇q±òÅë÷ãX£‚÷B½{1IÂlñqÒ¼#ï¬|ÑpbÍ›!ƒ\|¹³R® 6í8séÔ„O Ûš)ê̱]³ž šsn²¸Ÿä=srÃÏ_Ïv `8êÆ@—iü8m䱓ë¶.·ëï•ÁÙ:Ý;tþð†›cÿ6ùëëÕj—lpÅòÑm«?½|ëú÷÷‡Ï/›½«rO´›FÁ$Ð)-âNÁ%¼ËÁY‚p 5¼ Cºâ£¨Ã ßrìCM|0 ‘+ñ){JïÄQô-«Ñ˜‹Ë¬åƒLG¹ºÑ4¾’c-ªüò²6_«Ñ¯%Y”J…\\h¾ÔœKñJâ­Gʨ»KØŠs®9Üús¼4ÇÌ2Ê6…S ¦ÿŒsò@ߤ|¥2‰û <ý¾ô®Îñö“¨¶útQ*eb޶3ÓŒ =ZaŽVé¦ù%¶:/ž:aA³šê¬3N5åÚ„+Zë°Å§€;msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/doc-files/redefine2.gif0000644000175000017500000001034607271644421026041 0ustar giovannigiovanniGIF89añç÷ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿuuÿ’’ÿ¯¯ÿÌÌ3J` w(Ž/¤7»>ÒFèMÿUÿl"ÿ‚Dÿ™fÿ°ˆÿƪÿÝÌ3"J1`@wOŽ^¤n»}ÒŒè›ÿªÿµ"ÿÁDÿÌfÿ׈ÿãªÿîÌ33GG\\pp……™™­­ÂÂÖÖëëÿÿÿÿ)ÿÿRÿÿzÿÿ£ÿÿÌ"31J@`Ow^Žn¤}»ŒÒ›èªÿµÿ"ÁÿDÌÿf×ÿˆãÿªîÿÌ3M"f+€3™<³DÌMæUÿhÿ|ÿ:ÿW£ÿu¶ÿ’Êÿ¯ÝÿÌ3PmЍÅâÿÿ3ÿ3MÿMfÿf€ÿ€™ÿ™³ÿ³ÌÿÌ3Mf"€+™3³<ÌDæMÿUÿh:ÿ|Wÿuÿ£’ÿ¶¯ÿÊÌÿÝ3"J1`@wOŽ^¤n»}ÒŒè›ÿª"ÿµDÿÁfÿ̈ÿתÿãÌÿî33MMff€€™™³³ÌÌææÿÿÿÿ:ÿÿWÿÿuÿÿ’ÿÿ¯ÿÿÌÿÿ3(P7mEŠT¨bÅqâ€ÿŒÿ3™ÿM¦ÿf³ÿ€¿ÿ™Ìÿ³ÙÿÌæÿ3Uw™»Ýÿÿ--ÿDDÿ[[ÿqqÿˆˆÿŸŸÿµµÿÌÌÿ3&M3f@€M™Y³fÌsæ€ÿŽÿ:ÿ«WÿºuÿÈ’ÿׯÿæÌÿ33MMff€€™™³³ÌÌææÿÿÿÿÿ:ÿÿWÿÿuÿÿ’ÿÿ¯ÿÿÌÿ3M&f3€@™M³YÌfæsÿ€ÿŽÿ:ÿW«ÿuºÿ’Èÿ¯×ÿÌæ!ù,ñç@þH° Áƒ*\Ȱ¡Ã‡#JœH±¢Å‹3jÜȱ£Ç CŠY1É“(Sª\ɲåE“.cʤs¦Í5æD¸3f€=-8ô¦QšG“*-ª%Pœ<¡|:µjÏ¡X­VP“*Ì«\2mÚr,Ù³"Í¢]˶­[jßÊ•w®ÝŒ?ïê%Yw¯ß¿€Yþ츰áÈ Ϋ¸±ãÇ#—d,4ï`“]%kÞ̹³OÊ {†LxðèÓ¨ šN}óòjDqºÆ»vί“E³Þø5ïß}îY8q±TÖª´òæ·™ã^¯ñãØ#¯vøl†—»ë‹G;ûûø·ÎS–Ÿ~Þ¢î³ïÛ3~Ýe|ùÏß—¿_{ú•ý QbT`Teá§Ói)ˆ”a %Örªå[yf蔃<Õg ‡t!v#f·Þ‰[%”Üs™UÈâ|_U—f2¶ØœŠRW‰ö-´¢^I碎0rU£R£‹à(~ïñ˜ :©ž•¡‰ˆ¥„[ž$š”m}©eD`²%&púbCìA†LaXdml®YØ™MfH[lp*$'…zfIæxá©yb¡€g§~‹*:è–æ†h—8BH©—fªé¦œvêé§þ8`Aƒ&T¸aC‡!F@bE‹1fÔ¸‘cGAv¤’dI“GžT¹’eK—/a~L“fÍ‹3mæ8“gÁ‘)qR ês¢A¡F‰â$¨ô(Ñ¢ dút'UW*źõªV®_Á†;Ö)Y³+½žU»–mÛ›náÆ•Û6@ݹwñæÕ»—ïD»}<˜pɺi%.¼˜qcÇa;< ÔêßÇ—1gÖ,ÒòfÈ–‡Nþ ÚïÑÉ>#[}˜Úsȩ̈]Ç„=TêßÙe«–nЏ!ëØ¿_û.°ðáÇÃFž›yY­´qKU=)HÑ˱3}=;ÜÎ&·‡þ?ž|yóçѧW¿Þ<_öïáÇ—?Ÿ<òï:yw_í^?ÊìÆaʯ?†\«À:°5URÁêôr3ÊvJM(ß0ä.Àº/$ 9”n/Q"­B—:‘'ÅHÔ¨Åÿ4D­@Þ¶«±žKP!ñ¬ãoÇ÷Ó±¹ ³ú±FâBäè¼wdRÄèŠò Ç©B«.*‹¤ÐÉ&G\Ç'·”NJ&©LÊJ0‡4Mê°L²¥„“+9û£Ó͈ìì.Oüî„hÏ> ̱71-ÔMƪ,4Å =äÒO4ÊB•«²DQÓÐH9®R›nänÆ5›rò6/# È@ñ„”H/I)¨T ¤uÑUamõÁ#Ѳ4<@לëÏå†ÖØc‘MVÙe™mÖÙgþ€À <ˆ0¡Â… :|1¢Ä‰+Z¼ˆ1£Æ;zü2¤È‘<‰2¥Ê•,[^4é2¦LŠ0gÚ¼‰3§N•5wú”Ùó§Ð‚Š=Š”eФL=.m 2¨T£‹R`u É¬U¯nåªõ*V¯ ­ÖüêÕlW²XÇŠu«.Ô”OçÚ¥yWäY¢f©ží»•oß¶D áÒć«6ŽKx±[µuóFµŒybåÌ%þeÖ¯g®’×»V¬ZÇ…MSf]z2kÎziÛ.{;·îÝ'7ó¶ìû·ðáÄ /Îô8òåÌ9+o=úMÔÒ«[¿ŽäÛìÜ»{ÿ®:þøñäËGßn>½úõ´Å³?þÏÕšau/?¿þý£ŸŸFË_€š‘G`‚ ²‡Ÿb .˜zNXŸ„rd D>xa‡qè¡Tqõ´Wc"¶ÖZ†¦yÈ¢EôµXc†=u¢‰)ºha‹:~˜ãŽs½èc)ä=‰¤`ª˜ˆI>)Š×Õd#JÙ–d±9Æ$]BÉ"bG·¥}q‰à•7V©æl &”bÂçQb7ç—u‚Øž8êYRžcòhN…ªwèmN:…^¢æ9:¤äIêÜ (QÊgn˜~·i„–ŽÔiw¡òcz‹Ö¦¦¥"zªS«Ú6þꇠº+¬ŸnT딪®D£›h&â–¤æ×êK¯¶§”g¾f‰`¯XÒ%`±ëµÑ颵˜åj·çÑ9Ùƒ¾Q)kB€Æ^o»šû,C›Ën¼³")èjãl³k²yæ`¥™i#»%ž™®¢eá ¬¾‘¸ìg÷¥ p›ÊleÁEb›¦¼V2lØXnF|`ÂauÄŠÃI,1<—Å/T‘E‰\|QÆøbœ10q̱ÆòÉÇ RÈ!‰,ÒÈ#yLRÃÿ”lÒÉ')ŠÊ)©¬’(&­ÌRK¥ÜÒË/WìÌ1É\Ë2ÑLÓ:1ÕlÓMúÎ|SÎ9ߊ“Î;ñìŠÍ‰<1Ï?…ÑιþKÎÐ@M¢=nPE!”QBY.ÒK/´GKÁÃÔSD5ëÓQG%ì·IM•ÊPSÕUHYþ}©Ge 1Ö@QÕŒÖZ?4Ó\ùD•×ÅvÝ2µcm 5îü VØa‰}¶Cãöºk˳Խ[¡µµØ'™³ÏÚNÏ °¤o»í•[%›íŽ»jÇ-γÏM7I_íõhÝ|=Ü—ß¿ÐýwZ¦´`ñ’`>¸Å…I”Ö«†¶â¡­Ð.9Îø5ÐSä‹K£¸â ñ%Ù.jÕ»–exg«OÞ>Å–P.Y[Õ™°rçÕVeój¶9b–|ÙÚöô‹f?›æ¨h£ÆyÁö:š^­OüŒI_§î0ª+œ‰ìSÆŽÓ³ýBšíE{z;ÚZMΨ¦,%– ̼þ3«;-—öÆ‹ï«ûõ[«µ§QðÀN\Ô/§™ñÆ«ŠÜ7ËÅž|àÊ5— sÝ>¿jèBßnqÈ.½ôÊVO«óÆ?o¾Ó½”CÃí~Ý-ÛÛ÷‹xß+x>£vVGR÷ìŠ/‹Á“‡qù·ŽoÙ?f—ŽšBè—õ»gz½üŽO{ †Ï*ú¿_9Bóº=ù«G¸{ök§Ý+¿ÛºåÛ–õ¼{Ýïqùßôd´>òKZJYÖ¦‘öæ€íƒÒØ\ç<ƒ)¯UL™ ˆ4¸)ø„˃Œ Ú #•ó~NÃßa’þE…záµC†ÐXB[ÉþH,acRºOÈŒ¨6ü*ˆÕIÛ ×Ò——±‰ˆë{¨˜Ä”Í….S" Ñô“.Žë]O{ÚÖü7?òñ¯3nƒ—ÌzÔ@’K~Æi— ÍX 6þpfô«¡šlòÇǦ9c»#ÿúÈFBþÑ,ôœ }Bî ‘•\£z~(Ef†mãc ã˜,PÆ ˆi¼ä%è§Ö ŽAŒ‹&ECTö/~mäE•¨A1O°ÌÖÈHã5&V7’Dá»L…´=>Ìs¤»€I>°™Ë@ÆÄ }Œ˜Éåœ0”’J Ý=p hé¤3½iÁGª3Qç¤^ ˜ÎxRpžŠrgåhþ¥{Ž»+'žt¡€Â„¨< ÊH‚‚1œ‹bh>ÚNït¢ôL¨â"²OŒ:”}_{M,¸Jwõ§Œ¥ÌBoJÖ&{Å, ²XºËQ>´l¼;h FÊòus¤ºœŸ+OÚЋªt:95#ûØJžÒ´¦²› ·LYÇ™®Pš1\jJý™Q0õ¨"…ŸO#sS3­2?ÛjQo™ÈQÒËO­è:9zR®¢ñ§d)¶˜ÔÂp7D3ä+ûW‹æ‚ê^KÈ37jT¦z%ì;‹ÏëD6uŽS–Õ{$ÍR«(5ÌfA{·Î"™™Ë¬ù)TÚµŽqTiÃÑFU±‹›‡;!_*[…]ÐÒf?ÑÉÀÚ™M„¡5îq?Éä.—¹rsîs¡]éN—ºÕµîu±›]ín—»ÝõîwÁ^ñú& ;msv-2009.1/msv/src/com/sun/msv/reader/xmlschema/AttributeGroupState.java0000644000175000017500000000723307671170035026466 0ustar giovannigiovanni/* * @(#)$Id: AttributeGroupState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import org.xml.sax.Locator; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ReferenceContainer; import com.sun.msv.grammar.xmlschema.AttributeGroupExp; import com.sun.msv.grammar.xmlschema.AttributeWildcard; import com.sun.msv.grammar.xmlschema.XMLSchemaSchema; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * parses <attributeGroup /> element. * * @author Kohsuke KAWAGUCHI */ public class AttributeGroupState extends RedefinableDeclState implements AnyAttributeOwner { protected State createChildState( StartTagInfo tag ) { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; return reader.createAttributeState(this,tag); } protected ReferenceContainer getContainer() { return ((XMLSchemaReader)reader).currentSchema.attributeGroups; } protected Expression initialExpression() { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; String refQName = startTag.getAttribute("ref"); if( refQName==null ) // child expressions are expected. (although it's optional) return Expression.epsilon; Expression exp = reader.resolveQNameRef( startTag, "ref", new XMLSchemaReader.RefResolver() { public ReferenceContainer get( XMLSchemaSchema g ) { return g.attributeGroups; } } ); if( exp==null ) return Expression.epsilon; // couldn't resolve QName. return exp; } private AttributeWildcard wildcard; public void setAttributeWildcard( AttributeWildcard local ) { this.wildcard = local; } protected Expression castExpression( Expression halfCastedExpression, Expression newChildExpression ) { if( startTag.containsAttribute("ref") ) reader.reportError( XMLSchemaReader.ERR_MORE_THAN_ONE_CHILD_EXPRESSION ); if( halfCastedExpression==null ) return newChildExpression; // the first one. return reader.pool.createSequence( newChildExpression, halfCastedExpression ); } protected Expression annealExpression(Expression contentType) { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; if( !isGlobal() ) return contentType; // if this is a global declaration register it. String name = startTag.getAttribute("name"); if( name==null ) { reader.reportError( XMLSchemaReader.ERR_MISSING_ATTRIBUTE, "attributeGroup", "name" ); return Expression.epsilon; // recover by returning something meaningless. // the parent state will ignore this. } AttributeGroupExp exp; if( isRedefine() ) exp = (AttributeGroupExp)super.oldDecl; else { exp = reader.currentSchema.attributeGroups.getOrCreate(name); if( exp.exp!=null ) reader.reportError( new Locator[]{this.location,reader.getDeclaredLocationOf(exp)}, XMLSchemaReader.ERR_DUPLICATE_ATTRIBUTE_GROUP_DEFINITION, new Object[]{name} ); } reader.setDeclaredLocationOf(exp); exp.exp = contentType; exp.wildcard = this.wildcard; return exp; } } msv-2009.1/msv/src/com/sun/msv/reader/Messages.properties0000644000175000017500000000272207440542635023547 0ustar giovannigiovanni GrammarReader.MalplacedElement =\ element "{0}" is not allowed here GrammarReader.BadType =\ {0} GrammarReader.Characters =\ character data not allowed: {0} GrammarReader.DisallowedAttribute =\ "{1}" attribute is not allowed for "{0}" element. GrammarReader.MissingAttribute =\ "{1}" attribute is required for "{0}" element, but is not specified GrammarReader.MissingAttribute.2 =\ "{1}" or "{2}" attribute is required for "{0}" element, but none is specified GrammarReader.BadAttributeValue =\ "{1}" is invalid value for "{0}" attribute GrammarReader.ConflictingAttribute =\ "{0}" and "{1}" are mutually exclusive, so cannot be specified at the same time. GrammarReader.Abstract.MoreThanOneChildType =\ more than one child type is specified GrammarReader.Abstract.MissingChildType =\ no child type is specified GrammarReader.IllegalFinalValue = \ unrecognized value "{0}" in final attribute. GrammarReader.RecursiveInclude =\ recursive inclusion is detected ( {0} ) GrammarReader.FragmentIdentifier = \ URL "{0}" contains a fragment identifier. GrammarReader.UndefinedDataType =\ data type "{0}" is not defined GrammarReader.DataTypeAlreadyDefined =\ data type "{0}" is already defined GrammarReader.Warning.MaybeWrongNamespace = \ perhaps namespace URI "{0}" is incorrect? GrammarReader.Warning.DeprecatedTypeName =\ Datatype "{0}" is obsolete name. Please use "{1}" instead. GrammarReader.RecursiveDatatypeDefinition =\ Recursive datatype definition. msv-2009.1/msv/src/com/sun/msv/reader/ExpressionWithoutChildState.java0000644000175000017500000000167107671170035026214 0ustar giovannigiovanni/* * @(#)$Id: ExpressionWithoutChildState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader; import com.sun.msv.util.StartTagInfo; /** * Base implementation for those states who cannot have any children. * (e.g., RELAX: empty, null, etc. TREX: anyString, notAllowed, etc.) * * Note that this class does not prohibit children from different namespace. * Those "foreign" elements are just ignored. * * @author Kohsuke KAWAGUCHI */ public abstract class ExpressionWithoutChildState extends ExpressionState { protected final State createChildState(StartTagInfo tag) { // return null to indicate that this element does not accept a child. return null; } } msv-2009.1/msv/src/com/sun/msv/reader/dtd/0000755000175000017500000000000011622453066020426 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/reader/dtd/package.html0000644000175000017500000000010407271137707022710 0ustar giovannigiovanni

      reads DTD and constructs AGM.

      msv-2009.1/msv/src/com/sun/msv/reader/dtd/Localizer.java0000644000175000017500000000162707671170035023224 0ustar giovannigiovanni/* * @(#)$Id: Localizer.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.dtd; /** * formats messages by using a resource file. * * @author Kohsuke KAWAGUCHI */ class Localizer { public static String localize( String prop, Object[] args ) { return java.text.MessageFormat.format( java.util.ResourceBundle.getBundle("com.sun.msv.reader.dtd.Messages").getString(prop), args ); } public static String localize( String prop ) { return localize( prop, null ); } public static String localize( String prop, Object arg1 ) { return localize( prop, new Object[]{arg1} ); } } msv-2009.1/msv/src/com/sun/msv/reader/dtd/Messages_ja.properties0000644000175000017500000000133407307765244024777 0ustar giovannigiovanniDTDReader.UndefinedElement = \ "{0}"\u8981\u7D20\u306B\u95A2\u3059\u308B\u5B9A\u7FA9\u304C\u3042\u308A\u307E\u305B\u3093 DTDReader.Warning.AttemptToUseNamespace = \ DTD\u306Fxmlns:\u2026\u5C5E\u6027\u3092\u5B9A\u7FA9\u3057\u3088\u3046\u3068\u3057\u3066\u3044\u307E\u3059\u304C\u3001\ namespace\u95A2\u4FC2\u306E\u5C5E\u6027\u5B9A\u7FA9\u306F\u7121\u8996\u3055\u308C\u307E\u3059 DTDReader.UndeclaredPrefix = \ namespace prefix "{0}"\u304C\u8981\u7D20\u5BA3\u8A00\u306B\u73FE\u308C\u307E\u3057\u305F\u304C\u3001\ \u3053\u306Eprefix\u3092\u5B9A\u7FA9\u3059\u308Bxmlns\u5C5E\u6027\u304C\u3042\u308A\u307E\u305B\u3093\u3002\ \u3053\u306EDTD\u306Fnamespace\u3092\u6B63\u3057\u304F\u51E6\u7406\u3057\u3066\u3044\u307E\u305B\u3093 msv-2009.1/msv/src/com/sun/msv/reader/dtd/DTDReader.java0000644000175000017500000005644110023656337023041 0ustar giovannigiovanni/* * @(#)$Id: DTDReader.java 1633 2004-03-10 18:22:23Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.dtd; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.relaxng.datatype.Datatype; import org.relaxng.datatype.DatatypeException; import org.relaxng.datatype.DatatypeLibrary; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.LocatorImpl; import com.sun.msv.datatype.xsd.ngimpl.DataTypeLibraryImpl; import com.sun.msv.grammar.ChoiceNameClass; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.SimpleNameClass; import com.sun.msv.grammar.dtd.LocalNameClass; import com.sun.msv.grammar.trex.ElementPattern; import com.sun.msv.grammar.trex.TREXGrammar; import com.sun.msv.reader.Controller; import com.sun.msv.reader.GrammarReaderController; import com.sun.msv.scanner.dtd.DTDEventListener; import com.sun.msv.scanner.dtd.DTDParser; import com.sun.msv.scanner.dtd.InputEntity; import com.sun.msv.util.StringPair; /** * constructs {@link TREXGrammar} object that exactly matches to * the parsed DTD. * *

      * Each element declaration will have its own ReferenceExp by the name * of the element. * *

      * Note that this class does NOT extend GrammarReader, because DTD * is not written in XML format. * * @author Kohsuke KAWAGUCHI */ public class DTDReader implements DTDEventListener { public DTDReader( GrammarReaderController controller, ExpressionPool pool ) { this.controller = new Controller(controller); grammar = new TREXGrammar(pool); } public static TREXGrammar parse( InputSource source, GrammarReaderController controller ) { return parse( source, controller, new ExpressionPool() ); } public static TREXGrammar parse( InputSource source, GrammarReaderController controller, ExpressionPool pool ) { try { DTDReader reader = new DTDReader(controller,pool); DTDParser parser = new DTDParser(); parser.setDtdHandler(reader); parser.setEntityResolver(controller); parser.parse(source); return reader.getResult(); } catch( SAXParseException e ) { return null; // this error was already handled by GrammarReaderController } catch( Exception e ) { controller.error( new Locator[0], e.getMessage(), e ); return null; } } protected final Controller controller; /** * Used to create Datatype objects. This datatype library * should be able to handle XML Schema datatypes because * those are the names we ask to this library. */ private DatatypeLibrary datatypeLibrary = new DataTypeLibraryImpl(); public void setDatatypeLibrary( DatatypeLibrary datatypeLibrary ) { this.datatypeLibrary = datatypeLibrary; } /** * Obtains a Datatype object from its name. */ public Datatype createDatatype( String name ) { try { if( DTDParser.TYPE_CDATA.equals(name) ) return datatypeLibrary.createDatatype("normalizedString"); if( DTDParser.TYPE_ENUMERATION.equals(name) ) return datatypeLibrary.createDatatype("token"); return datatypeLibrary.createDatatype(name); } catch( DatatypeException e ) { // we expect this datatype library to be complete e.printStackTrace(); throw new InternalError(); } } /** * map from prefix to set of possible namespace URI. * default namespace (without prefix) is stored by using "" as a key. */ protected final Map namespaces = createInitialNamespaceMap(); protected final static Map createInitialNamespaceMap() { Map m = new java.util.HashMap(); // prefix xml is implicitly declared. Set s = new java.util.HashSet(); s.add("http://www.w3.org/XML/1998/namespace"); m.put("xml",s); return m; } /** * when this value is in the above set, that indicates * we couldn't detect what URIs are going to be used with that prefix. */ protected static final String ABANDON_URI_SNIFFING = "*"; protected NameClass getNameClass( String maybeQName, boolean handleAsAttribute ) { String[] s = splitQName(maybeQName); if(s[0].length()==0 && handleAsAttribute ) // if this is an attribute and unprefixed, it is local to the element. return new SimpleNameClass(s[0],s[1]); Set vec = (Set)namespaces.get(s[0]/*uri*/); if(vec==null) { if(s[0].equals("")) // this DTD does not attempt to use namespace. // this is OK and we assume anonymous namespace. return new SimpleNameClass("",s[1]); // we found element name like "html:p" but // we haven't see any "xmlns:html" attribute declaration. // this is considered as an error for MSV. controller.error( new Locator[]{locator}, Localizer.localize( ERR_UNDECLARED_PREFIX, s[0] ), null ); // recover by returning something return new LocalNameClass( s[1]/*local*/ ); } if( vec.contains(ABANDON_URI_SNIFFING) ) { // System.out.println("sniffing abandoned for "+s[0]); // possibly multiple URI can be assigned. // so fall back to use LocalNameClass to at least check local part. return new LocalNameClass( s[1] ); } // create choice of all possible namespace, and // return it. String[] candidates = (String[])vec.toArray(new String[vec.size()]); NameClass nc = new SimpleNameClass( candidates[0], s[1] ); // System.out.println("candidate for "+s[0]+" is "+ candidates[0] ); for( int i=1; i * Its defeinition will be later filled by the choice of all elements. */ protected final ReferenceExp getAnyExp() { return grammar.namedPatterns.getOrCreate("$ all $"); } public void endContentModel( String elementName, short type ) { if( contentModel==null ) // assertion failed. // this must be a bug of DTDScanner. throw new Error(); switch(type) { case CONTENT_MODEL_CHILDREN: case CONTENT_MODEL_ANY: break; // do nothing. case CONTENT_MODEL_EMPTY: contentModel = Expression.epsilon; break; case CONTENT_MODEL_MIXED: if( contentModel != Expression.nullSet ) contentModel = grammar.pool.createMixed( grammar.pool.createZeroOrMore(contentModel)); else // this happens when mixed content model is #PCDATA only. contentModel = Expression.anyString; break; } // memorize the location setDeclaredLocationOf( grammar.namedPatterns.getOrCreate(elementName) ); // memorize parsed content model. elementDecls.put( elementName, contentModel ); contentModel = null; } /** * processes occurence (?,+,*) of the given expression */ protected Expression processOccurs( Expression item, short occurence ) { switch( occurence ) { case OCCURENCE_ONCE: return item; case OCCURENCE_ONE_OR_MORE: return grammar.pool.createOneOrMore(item); case OCCURENCE_ZERO_OR_MORE: return grammar.pool.createZeroOrMore(item); case OCCURENCE_ZERO_OR_ONE: return grammar.pool.createOptional(item); default: // assertion failed. this must be a bug of DTDScanner. throw new Error(); } } protected class Context { final Expression exp; final short connectorType; final Context previous; Context( Context prev, Expression exp, short connector ) { this.exp = exp; this.connectorType = connector; this.previous = prev; } } protected Context contextStack; protected Expression contentModel; protected short connectorType; protected final short CONNECTOR_UNKNOWN = -999; public void childElement( String elementName, short occurence ) { Expression exp = processOccurs( grammar.namedPatterns.getOrCreate(elementName), occurence); if( connectorType == CONNECTOR_UNKNOWN ) { // this must be the first child element within this model group. if( contentModel!=null ) throw new Error(); contentModel = exp; } else { combineToContentModel(exp); } } protected void combineToContentModel( Expression exp ) { switch( connectorType ) { case CHOICE: contentModel = grammar.pool.createChoice( contentModel, exp ); break; case SEQUENCE: contentModel = grammar.pool.createSequence( contentModel, exp ); break; default: // assertion failed. no such connector. throw new Error(); } } public void mixedElement( String elementName ) { if( contentModel==null ) // assertion failed. contentModel must be prepared by startContentModel method. throw new Error(); contentModel = grammar.pool.createChoice( contentModel, grammar.namedPatterns.getOrCreate(elementName) ); } public void startModelGroup() { // push context contextStack = new Context( contextStack, contentModel, connectorType ); contentModel = null; connectorType = CONNECTOR_UNKNOWN; } public void endModelGroup( short occurence ) { Expression exp = processOccurs( contentModel, occurence ); // pop context contentModel = contextStack.exp; connectorType = contextStack.connectorType; contextStack = contextStack.previous; if( contentModel==null ) // this model group is the first item in the parent model group. contentModel = exp; else combineToContentModel(exp); } public void connector( short type ) throws SAXException { if( this.connectorType==CONNECTOR_UNKNOWN ) this.connectorType = type; else if( this.connectorType!=type ) // assertion failed. // within a model group, operator must be the same. throw new Error(); } private Set getPossibleNamespaces( String prefix ) { Set s = (Set)namespaces.get(prefix); if(s!=null) return s; s = new java.util.HashSet(); namespaces.put(prefix,s); return s; } /** * this flag is set to true after reporting WRN_ATTEMPT_TO_USE_NAMESPACE. * this is used to prevent issuing the same warning more than once. */ private boolean reportedXmlnsWarning = false; public void attributeDecl( String elementName, String attributeName, String attributeType, String[] enums, short attributeUse, String defaultValue ) throws SAXException { if( attributeName.startsWith("xmlns") ) { // this is namespace declaration if( !reportedXmlnsWarning ) controller.warning( new Locator[]{locator}, Localizer.localize( WRN_ATTEMPT_TO_USE_NAMESPACE ) ); reportedXmlnsWarning = true; if( defaultValue==null ) // we don't have a default value, so no way to determine URI. defaultValue = ABANDON_URI_SNIFFING; Set s; if( attributeName.equals("xmlns") ) s = getPossibleNamespaces(""); else s = getPossibleNamespaces( attributeName.substring(6) ); s.add( defaultValue ); // System.out.println("add " + defaultValue + " for att name " + attributeName ); // xmlns:* cannot be added to attr constraint expression. return; } Map attList = (Map)attributeDecls.get(elementName); if( attList==null ) { // the first attribute for this element. attList = new java.util.HashMap(); attributeDecls.put(elementName,attList); } Expression body = createAttributeBody( elementName,attributeName,attributeType,enums, attributeUse,defaultValue); AttModel am = new AttModel( body, attributeUse==USE_REQUIRED ); setDeclaredLocationOf(am); // add it to the list. attList.put( attributeName, am ); } /** * Creates an attribute body from the declaration * found in the DTD. */ protected Expression createAttributeBody( String elementName, String attributeName, String attributeType, String[] enums, short attributeUse, String defaultValue ) throws SAXException { // create Datatype that validates attribute value. Datatype dt = createDatatype(attributeType); StringPair str = new StringPair("",attributeType); if(enums!=null) { Expression exp = Expression.nullSet; for( int i=0; iKohsuke KAWAGUCHI */ public interface ExpressionOwner { void onEndChild( Expression exp ); } msv-2009.1/msv/src/com/sun/msv/reader/ChildlessState.java0000644000175000017500000000113607671170035023433 0ustar giovannigiovanni/* * @(#)$Id: ChildlessState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader; import com.sun.msv.util.StartTagInfo; /** * state that has no children. * * @author Kohsuke KAWAGUCHI */ public class ChildlessState extends SimpleState { protected final State createChildState( StartTagInfo tag ) { return null; } } msv-2009.1/msv/src/com/sun/msv/grammar/0000755000175000017500000000000011622453067020040 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/grammar/ConcurExp.java0000644000175000017500000000253207766432346022626 0ustar giovannigiovanni/* * @(#)$Id: ConcurExp.java 1620 2003-12-12 21:36:38Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; /** * <concur> pattern of TREX. * * None of the other language needs this expression. * So application can deny processing this expression if neceesary, * without hampering the multi-schema-ness. * * @author Kohsuke KAWAGUCHI */ public final class ConcurExp extends BinaryExp { ConcurExp( Expression left, Expression right ) { super(left,right); } public Object visit( ExpressionVisitor visitor ) { return visitor.onConcur(this); } public Expression visit( ExpressionVisitorExpression visitor ) { return visitor.onConcur(this); } public boolean visit( ExpressionVisitorBoolean visitor ) { return visitor.onConcur(this); } public void visit( ExpressionVisitorVoid visitor ) { visitor.onConcur(this); } protected boolean calcEpsilonReducibility() { return exp1.isEpsilonReducible() && exp2.isEpsilonReducible(); } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/ReferenceExp.java0000644000175000017500000000576707766432346023310 0ustar giovannigiovanni/* * @(#)$Id: ReferenceExp.java 1620 2003-12-12 21:36:38Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; /** * Reference to the other expression. * *

      * In RELAX grammar, this class is used as a base class of elementRule reference * and hedgeRule reference. * TREX uses this class directly. * *

      * This object is created and controlled by TREXGrammar/RELAXModule object, * rather than ExpressionPool. Therefore, this object is not a subject to unification. * *

      * This class can be derived. In fact, many classes derive this class. * * @author Kohsuke KAWAGUCHI */ public class ReferenceExp extends Expression { /** child expression. Due to the possible forward reference, * this variable is not available when the object is instanciated. * * Actual expression will be set once if the definition is parsed. */ public Expression exp = null; /** name of the referenced expression. * * can be null for anonymously referenced expression. */ public final String name; public ReferenceExp( String name ) { this.name = name; } public ReferenceExp( String name, Expression exp ) { this(name); this.exp = exp; } protected final int calcHashCode() { return System.identityHashCode(this); } /** * checks if this ReferenceExp is properly defined. * this method is used to detect undeclared definitions. * Derived classes can override this method. */ public boolean isDefined() { return exp!=null; } public boolean equals( Object o ) { return this==o; } protected boolean calcEpsilonReducibility() { if(exp==null) // // actual expression is not supplied yet. // // actual definition of the referenced expression must be supplied // // before any computation over the grammar. // throw new Error(); // assertion failed. return false; // this method can be called while parsing a grammar. // in that case, epsilon reducibility is just used for approximation. // therefore we can safely return false. return exp.isEpsilonReducible(); } // derived class must be able to behave as a ReferenceExp public final Object visit( ExpressionVisitor visitor ) { return visitor.onRef(this); } public final Expression visit( ExpressionVisitorExpression visitor ){ return visitor.onRef(this); } public final boolean visit( ExpressionVisitorBoolean visitor ) { return visitor.onRef(this); } public final void visit( ExpressionVisitorVoid visitor ) { visitor.onRef(this); } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/DataExp.java0000644000175000017500000000552511156747174022247 0ustar giovannigiovanni/* * @(#)$Id: DataExp.java 1744 2009-03-14 15:34:20Z bimargulies $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; import org.relaxng.datatype.Datatype; import com.sun.msv.datatype.xsd.XSDatatype; import com.sun.msv.util.StringPair; /** * Expression that matchs characters of the particular {@link Datatype}. * * @author Kohsuke KAWAGUCHI */ public final class DataExp extends Expression implements DataOrValueExp { /** datatype object that actually validates text. */ public final Datatype dt; public Datatype getType() { return dt; } /** * name of this datatype. * * The value of this field is not considered as significant. * When two TypedStringExps share the same Datatype object, * then they are unified even if they have different names. */ public final StringPair name; public StringPair getName() { return name; } /** * 'except' clause of RELAX NG. * If a token matches this pattern, then it should be rejected. */ public final Expression except; protected DataExp( Datatype dt, StringPair typeName, Expression except ) { super(dt.hashCode()+except.hashCode()); this.dt=dt; this.name = typeName; this.except = except; } protected final int calcHashCode() { return dt.hashCode()+except.hashCode(); } public boolean equals( Object o ) { // Note that equals method of this class *can* be sloppy, // since this class does not have a pattern as its child. // Therefore datatype vocaburary does not necessarily provide // strict equals method. if(o.getClass()!=this.getClass()) return false; DataExp rhs = (DataExp)o; if( this.except != rhs.except ) return false; return rhs.dt.equals(dt); } public Object visit( ExpressionVisitor visitor ) { return visitor.onData(this); } public Expression visit( ExpressionVisitorExpression visitor ) { return visitor.onData(this); } public boolean visit( ExpressionVisitorBoolean visitor ) { return visitor.onData(this); } public void visit( ExpressionVisitorVoid visitor ) { visitor.onData(this); } protected boolean calcEpsilonReducibility() { XSDatatype xdt = (XSDatatype)dt; if(except==Expression.nullSet && xdt.isAlwaysValid()) // because for such datatype we return STRING_IGNORE from StringCareLevelCalculator return true; return false; } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/ExpressionVisitorExpression.java0000644000175000017500000000216707671170035026510 0ustar giovannigiovanni/* * @(#)$Id: ExpressionVisitorExpression.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; /** * ExpressionVisitor that returns Expression object. * * @author Kohsuke KAWAGUCHI */ public interface ExpressionVisitorExpression { Expression onAttribute( AttributeExp exp ); Expression onChoice( ChoiceExp exp ); Expression onElement( ElementExp exp ); Expression onOneOrMore( OneOrMoreExp exp ); Expression onMixed( MixedExp exp ); Expression onList( ListExp exp ); Expression onRef( ReferenceExp exp ); Expression onOther( OtherExp exp ); Expression onEpsilon(); Expression onNullSet(); Expression onAnyString(); Expression onSequence( SequenceExp exp ); Expression onData( DataExp exp ); Expression onValue( ValueExp exp ); Expression onConcur( ConcurExp p ); Expression onInterleave( InterleaveExp p ); } msv-2009.1/msv/src/com/sun/msv/grammar/ReferenceContainer.java0000644000175000017500000000567010034315204024436 0ustar giovannigiovanni/* * @(#)$Id: ReferenceContainer.java 1634 2004-04-05 17:42:28Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; import java.util.Iterator; import java.util.Map; /** * Container of ReferenceExp. a map from name to ReferenceExp. * * @author Kohsuke KAWAGUCHI */ public abstract class ReferenceContainer implements java.io.Serializable { protected final Map impl = new java.util.HashMap(); /** * gets or creates ReferenceExp object. * * Derived class should provide type-safe accesser methods. * * Usually, this method is only necessary for some kind of grammar loader. * If you are programming an application over MSV, * {@link #_get(String)} method is probably what you need. */ public final ReferenceExp _getOrCreate( String name ) { Object o = impl.get(name); if(o!=null) return (ReferenceExp)o; // this is the first time this name is used. // so create a ReferenceExp here. ReferenceExp exp = createReference(name); impl.put(name,exp); return exp; } /** creates a new reference object with given name */ protected abstract ReferenceExp createReference( String name ); /** * replaces the current ReferenceExp by newly specified reference exp. */ public void redefine( String name, ReferenceExp newExp ) { if( impl.put(name,newExp)==null ) // no object is associated with this name. throw new IllegalArgumentException(); } /** gets a referenced expression * * Derived class should provide type-safe accesser methods. * * @return null * if no expression is defined with the given name. */ public final ReferenceExp _get( String name ) { Object o = impl.get(name); if(o!=null) return (ReferenceExp)o; else return null; // not found } /** iterates all ReferenceExp in this container */ public final Iterator iterator() { return impl.values().iterator(); } /** obtains all items in this container. */ public final ReferenceExp[] getAll() { ReferenceExp[] r = new ReferenceExp[size()]; impl.values().toArray(r); return r; } /** removes an object from this container. * * @return * removed object. Null if no such name is found. */ public final ReferenceExp remove( String name ) { return (ReferenceExp)impl.remove(name); } /** gets the number of ReferenceExps in this container. */ public final int size() { return impl.size(); } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/IDContextProvider.java0000644000175000017500000000164707671167271024277 0ustar giovannigiovanni/* * @(#)$Id: IDContextProvider.java 1565 2003-06-09 20:31:53Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; import org.relaxng.datatype.Datatype; import org.relaxng.datatype.ValidationContext; /** * ValidationContextProvider that supports limited ID/IDREF implementation. * * @deprecated * use {@link IDContextProvider2}. * * @author Kohsuke KAWAGUCHI */ public interface IDContextProvider extends ValidationContext { /** * this method is called when a type with ID semantics is matched. * * It is the callee's responsibility that stores * ID and checks doubly defined ID, if it is necessary. */ void onID(Datatype datatype, String literal); } msv-2009.1/msv/src/com/sun/msv/grammar/NameClassAndExpression.java0000644000175000017500000000104707671170035025256 0ustar giovannigiovanni/* * @(#)$Id: NameClassAndExpression.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; /** * common interface of AttributeExp and ElementExp. * * @author Kohsuke KAWAGUCHI */ public interface NameClassAndExpression { NameClass getNameClass(); Expression getContentModel(); } msv-2009.1/msv/src/com/sun/msv/grammar/OtherExp.java0000644000175000017500000000647207766432346022465 0ustar giovannigiovanni/* * @(#)$Id: OtherExp.java 1620 2003-12-12 21:36:38Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; /** * Base class for application-specific AGM annotation. * *

      * This primitive has no meaning to MSV. For example, the following expression *

       * Expression exp = new OtherExp( pool.createSequence(a,b) );
       * 
      * is treated as if MSV sees the following, OtherExp-less expression: *
       * Expression exp = pool.createSequence(a,b);
       * 
      * *

      * By using this "transparency", application can implement derived classes * of OtherExp and add application-specific information to AGM. * *

      * For example, you can implement AnnotationInfoExp class that derives * OtherExp and introduces "documentation" field. * Then you'll write a customized XMLSchemaReader that * parses <annotation> tag and mix AnnotationInfoExp into an AGM. * Your application can then examine it and do some useful things. * *

      * Those application-specific information added through OtherExp are completely * ignored by MSV. So the annotated AGM can still be used just like anormal AGM. * * * @author Kohsuke KAWAGUCHI */ public class OtherExp extends Expression { /** * returns the string which will be used by ExpressionPrinter * to print this expression. */ public String printName() { String className = this.getClass().getName(); int idx = className.lastIndexOf('.'); if(idx>=0) className = className.substring(idx+1); return className; } /** * child expression. */ public Expression exp; public OtherExp() { } protected final int calcHashCode() { return System.identityHashCode(this); } public OtherExp( Expression exp ) { this(); this.exp = exp; } public boolean equals( Object o ) { return this==o; } protected boolean calcEpsilonReducibility() { if(exp==null) // // actual expression is not supplied yet. // // actual definition of the referenced expression must be supplied // // before any computation over the grammar. // throw new Error(); // assertion failed. return false; // this method can be called while parsing a grammar. // in that case, epsilon reducibility is just used for approximation. // therefore we can safely return false. return exp.isEpsilonReducible(); } // derived class must be able to behave as a ReferenceExp public final Object visit( ExpressionVisitor visitor ) { return visitor.onOther(this); } public final Expression visit( ExpressionVisitorExpression visitor ){ return visitor.onOther(this); } public final boolean visit( ExpressionVisitorBoolean visitor ) { return visitor.onOther(this); } public final void visit( ExpressionVisitorVoid visitor ) { visitor.onOther(this); } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/package.html0000644000175000017500000000304307260744467022333 0ustar giovannigiovanni

      abstract grammar model(AGM): common part.

      ID/IDREF support

      Support for 'ID' and 'IDREF' types are implemented in this package, due to the restriction of the implementation.

      The implementation in this package works as follows:

      • When verify method of IDType is called, it only checks the conformance as a NMTOKEN and uniqueness, then stores it as ID.
      • When verify method of IDREFType is called, it only checks the conformance as a NMTOKEN and stores it as IDREF.
      • When the entire document is parsed, ID list and IDREF list are cross-checked. IDREF without the corresponding ID is detected in this stage.

      This implementation implies very severe limitations. For example, consider the following TREX pattern.

      <element name="foo">
      <choice>
      <attribute name="bar" type="ID" />
      <attribute name="bar" type="string" />
      </choice>
      <element name="child">
      <attribute name="id" type="ID" />
      </element>
      </element>

      And the following XML fragment.

      <foo bar="xyz"> <child id="xyz" /> </foo>

      This implementation cannot validate the above fragment, because "xyz" is registered as an ID when "bar" attribute is tested against "ID" type. IDREF type also has similar problems.

      Note that RELAX prohibits these "abuse" of ID/IDREF in the way that this implementation works.

      msv-2009.1/msv/src/com/sun/msv/grammar/ChoiceExp.java0000644000175000017500000000220307766432346022562 0ustar giovannigiovanni/* * @(#)$Id: ChoiceExp.java 1620 2003-12-12 21:36:38Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; /** * A|B. * * @author Kohsuke KAWAGUCHI */ public final class ChoiceExp extends BinaryExp { ChoiceExp( Expression left, Expression right ) { super(left,right); } public Object visit( ExpressionVisitor visitor ) { return visitor.onChoice(this); } public Expression visit( ExpressionVisitorExpression visitor ) { return visitor.onChoice(this); } public boolean visit( ExpressionVisitorBoolean visitor ) { return visitor.onChoice(this); } public void visit( ExpressionVisitorVoid visitor ) { visitor.onChoice(this); } protected boolean calcEpsilonReducibility() { return exp1.isEpsilonReducible() || exp2.isEpsilonReducible(); } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/ExpressionVisitorBoolean.java0000644000175000017500000000206707671170035025727 0ustar giovannigiovanni/* * @(#)$Id: ExpressionVisitorBoolean.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; /** * ExpressionVisitor that returns boolean. * * @author Kohsuke KAWAGUCHI */ public interface ExpressionVisitorBoolean { boolean onAttribute( AttributeExp exp ); boolean onChoice( ChoiceExp exp ); boolean onElement( ElementExp exp ); boolean onOneOrMore( OneOrMoreExp exp ); boolean onMixed( MixedExp exp ); boolean onList( ListExp exp ); boolean onRef( ReferenceExp exp ); boolean onOther( OtherExp exp ); boolean onEpsilon(); boolean onNullSet(); boolean onAnyString(); boolean onSequence( SequenceExp exp ); boolean onData( DataExp exp ); boolean onValue( ValueExp exp ); boolean onConcur( ConcurExp p ); boolean onInterleave( InterleaveExp p ); } msv-2009.1/msv/src/com/sun/msv/grammar/relax/0000755000175000017500000000000011622453066021152 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/grammar/relax/RELAXExpressionVisitorBoolean.java0000644000175000017500000000146507671170035027637 0ustar giovannigiovanni/* * @(#)$Id: RELAXExpressionVisitorBoolean.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.relax; import com.sun.msv.grammar.ExpressionVisitorBoolean; /** * RELAX version of {@link ExpressionVisitorBoolean}. * * @author Kohsuke KAWAGUCHI */ public interface RELAXExpressionVisitorBoolean extends ExpressionVisitorBoolean { // RELAX visitor can ignore onRef callback. boolean onAttPool( AttPoolClause exp ); boolean onTag( TagClause exp ); boolean onElementRules( ElementRules exp ); boolean onHedgeRules( HedgeRules exp ); } msv-2009.1/msv/src/com/sun/msv/grammar/relax/EmptyStringType.java0000644000175000017500000000340307671170035025145 0ustar giovannigiovanni/* * @(#)$Id: EmptyStringType.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.relax; import org.relaxng.datatype.ValidationContext; import com.sun.msv.datatype.SerializationContext; import com.sun.msv.datatype.xsd.BuiltinAtomicType; import com.sun.msv.datatype.xsd.SimpleURType; import com.sun.msv.datatype.xsd.XSDatatype; /** * 'emptyString' type of RELAX. * * this type accepts nothing but "". * * @author Kohsuke KAWAGUCHI */ public class EmptyStringType extends BuiltinAtomicType { public static final EmptyStringType theInstance = new EmptyStringType(); private EmptyStringType() { super("emptyString"); } final public XSDatatype getBaseType() { return SimpleURType.theInstance; } public int isFacetApplicable( String facetName ) { return NOT_ALLOWED; } public boolean checkFormat( String literal, ValidationContext context ) { return literal.equals(""); } public Object _createValue( String lexicalValue, ValidationContext context ) { if( lexicalValue.equals("") ) return lexicalValue; else return null; } public String convertToLexicalValue( Object o, SerializationContext context ) { if( o.equals("") ) return ""; else throw new IllegalArgumentException(); } public Class getJavaObjectType() { return String.class; } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/relax/ElementRule.java0000644000175000017500000000303607671170035024241 0ustar giovannigiovanni/* * @(#)$Id: ElementRule.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.relax; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.NameClass; /** * ElementRule declaration of RELAX. * * @author Kohsuke KAWAGUCHI */ public class ElementRule extends ElementExp { /** constraints over start tag of the element */ public final TagClause clause; /** Attribute-free content model */ public final Expression attributeFreeContentModel; protected ElementRules parent; /** gets the parent ElementRules object. * * when this object is used as a named, no-inline elementRule, * this variable holds a reference to the parent ElementRules object. * otherwise, null */ public ElementRules getParent() { return parent; } public final NameClass getNameClass() { return clause.nameClass; } public ElementRule( ExpressionPool pool, TagClause clause, Expression contentModel ) { super( pool.createSequence(clause,contentModel), true ); this.clause = clause; this.attributeFreeContentModel = contentModel; } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/relax/package.html0000644000175000017500000000011107260744467023437 0ustar giovannigiovanni abstract grammar model(AGM): RELAX stub. msv-2009.1/msv/src/com/sun/msv/grammar/relax/RELAXExpressionVisitorVoid.java0000644000175000017500000000143107671170035027152 0ustar giovannigiovanni/* * @(#)$Id: RELAXExpressionVisitorVoid.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.relax; import com.sun.msv.grammar.ExpressionVisitorVoid; /** * RELAX Version of {@link ExpressionVisitorVoid} * * @author Kohsuke KAWAGUCHI */ public interface RELAXExpressionVisitorVoid extends ExpressionVisitorVoid { // RELAX visitor can ignore onRef callback. void onAttPool( AttPoolClause exp ); void onTag( TagClause exp ); void onElementRules( ElementRules exp ); void onHedgeRules( HedgeRules exp ); } msv-2009.1/msv/src/com/sun/msv/grammar/relax/AttPoolClause.java0000644000175000017500000000266707671170035024550 0ustar giovannigiovanni/* * @(#)$Id: AttPoolClause.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.relax; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ReferenceExp; /** * 'attPool' of RELAX module. * * ReferenceExp.exp contains a sequence of AttributeExp. * * @author Kohsuke KAWAGUCHI */ public class AttPoolClause extends ReferenceExp implements Exportable { protected AttPoolClause( String role ) { super(role); } /** * a flag that indicates this elementRule is exported and * therefore accessible from other modules. */ public boolean exported = false; public boolean isExported() { return exported; } public Object visit( RELAXExpressionVisitor visitor ) { return visitor.onAttPool(this); } public Expression visit( RELAXExpressionVisitorExpression visitor ) { return visitor.onAttPool(this); } public boolean visit( RELAXExpressionVisitorBoolean visitor ) { return visitor.onAttPool(this); } public void visit( RELAXExpressionVisitorVoid visitor ) { visitor.onAttPool(this); } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/relax/RELAXExpressionVisitor.java0000644000175000017500000000170207671170035026331 0ustar giovannigiovanni/* * @(#)$Id: RELAXExpressionVisitor.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.relax; import com.sun.msv.grammar.ExpressionVisitor; /** * Visitor interface for RELAX expressions. * * By implementing this interface, your visitor can distinguish * four subclass of ReferenceExp introduced as RELAX stub. * *

      * Note that onRef method may still be called if you visit AGM created from * TREX pattern. * * @author Kohsuke KAWAGUCHI */ public interface RELAXExpressionVisitor extends ExpressionVisitor { Object onAttPool( AttPoolClause exp ); Object onTag( TagClause exp ); Object onElementRules( ElementRules exp ); Object onHedgeRules( HedgeRules exp ); } msv-2009.1/msv/src/com/sun/msv/grammar/relax/HedgeRules.java0000644000175000017500000000370307671170035024050 0ustar giovannigiovanni/* * @(#)$Id: HedgeRules.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.relax; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.ReferenceExp; /** * hedgeRule of RELAX module. * * ReferenceExp.exp holds a choice of the content models of all hedgeRules that * share the same label name. * * @author Kohsuke KAWAGUCHI */ public class HedgeRules extends ReferenceExp implements Exportable { protected HedgeRules( String label, RELAXModule ownerModule ) { super(label); this.ownerModule = ownerModule; } public void addHedge( Expression exp, ExpressionPool pool ) { if( this.exp==null ) this.exp=exp; // first time else this.exp=pool.createChoice(this.exp,exp); } public boolean equals( Object o ) { return this==o; } public Object visit( RELAXExpressionVisitor visitor ) { return visitor.onHedgeRules(this); } public Expression visit( RELAXExpressionVisitorExpression visitor ) { return visitor.onHedgeRules(this); } public boolean visit( RELAXExpressionVisitorBoolean visitor ) { return visitor.onHedgeRules(this); } public void visit( RELAXExpressionVisitorVoid visitor ) { visitor.onHedgeRules(this); } /** a flag that indicates this hedgeRule is exported and * therefore accessible from other modules. */ public boolean exported = false; public boolean isExported() { return exported; } /** RELAXModule object to which this object belongs */ public final RELAXModule ownerModule; // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/relax/NoneType.java0000644000175000017500000000316407671170035023563 0ustar giovannigiovanni/* * @(#)$Id: NoneType.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.relax; import org.relaxng.datatype.ValidationContext; import com.sun.msv.datatype.SerializationContext; import com.sun.msv.datatype.xsd.BuiltinAtomicType; import com.sun.msv.datatype.xsd.SimpleURType; import com.sun.msv.datatype.xsd.XSDatatype; /** * 'none' datatype of RELAX. * * this type accepts nothing. * * @author Kohsuke KAWAGUCHI */ public class NoneType extends BuiltinAtomicType { public static final NoneType theInstance = new NoneType(); private NoneType() { super("none"); } final public XSDatatype getBaseType() { return SimpleURType.theInstance; } public int isFacetApplicable( String facetName ) { return NOT_ALLOWED; } public boolean checkFormat( String literal, ValidationContext context ) { return false; } public Object _createValue( String lexicalValue, ValidationContext context ) { return null; } public String convertToLexicalValue( Object o, SerializationContext context ) { throw new IllegalArgumentException(); } public Class getJavaObjectType() { return Object.class; // actually, it never returns a value. } // TODO: implement _checkValid // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/relax/TagClause.java0000644000175000017500000000302207671170035023663 0ustar giovannigiovanni/* * @(#)$Id: TagClause.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.relax; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.ReferenceExp; /** * 'tag' of RELAX module. * * exp field contains a sequence of AttributeExp. * * @author Kohsuke KAWAGUCHI */ public class TagClause extends ReferenceExp { /** * tag name constraint. * This should be SimpleNameClass. The only exception is for stub module. */ public NameClass nameClass; /** RefContainer-controlled creation. should be created via RefContainer.getOrCreate */ protected TagClause( String role ) { super(role); } /** constructor for inline tag. creatable directly from outside */ public TagClause() { super(null); } public Object visit( RELAXExpressionVisitor visitor ) { return visitor.onTag(this); } public Expression visit( RELAXExpressionVisitorExpression visitor ) { return visitor.onTag(this); } public boolean visit( RELAXExpressionVisitorBoolean visitor ) { return visitor.onTag(this); } public void visit( RELAXExpressionVisitorVoid visitor ) { visitor.onTag(this); } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/relax/RELAXModule.java0000644000175000017500000001263307671170035024044 0ustar giovannigiovanni/* * @(#)$Id: RELAXModule.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ /* * @(#)$Id: RELAXModule.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.relax; import java.util.Map; import com.sun.msv.datatype.xsd.XSDatatype; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.Grammar; import com.sun.msv.grammar.ReferenceContainer; import com.sun.msv.grammar.ReferenceExp; /** * "Module" of RELAX Core. * * @author Kohsuke KAWAGUCHI */ public class RELAXModule implements Grammar { final public class ElementRulesContainer extends ReferenceContainer { public ElementRules getOrCreate( String name ) { return (ElementRules)super._getOrCreate(name); } public ElementRules get( String name ) { return (ElementRules)super._get(name); } protected ReferenceExp createReference( String name ) { return new ElementRules(name,RELAXModule.this); } } /** map from label name to ElementRules object */ public final ElementRulesContainer elementRules = new ElementRulesContainer(); final public class HedgeRulesContainer extends ReferenceContainer { public HedgeRules getOrCreate( String name ) { return (HedgeRules)super._getOrCreate(name); } public HedgeRules get( String name ) { return (HedgeRules)super._get(name); } protected ReferenceExp createReference( String name ) { return new HedgeRules(name,RELAXModule.this); } } /** map from label name to HedgeRules object */ public final HedgeRulesContainer hedgeRules = new HedgeRulesContainer(); final public class TagContainer extends ReferenceContainer { public TagClause getOrCreate( String name ) { return (TagClause)super._getOrCreate(name); } public TagClause get( String name ) { return (TagClause)super._get(name); } protected ReferenceExp createReference( String name ) { return new TagClause(name); } } /** map from role name to TagClause object */ public final TagContainer tags = new TagContainer(); final public class AttPoolContainer extends ReferenceContainer { public AttPoolClause getOrCreate( String name ) { return (AttPoolClause)super._getOrCreate(name); } public AttPoolClause get( String name ) { return (AttPoolClause)super._get(name); } protected ReferenceExp createReference( String name ) { return new AttPoolClause(name); } } /** map from role name to AttPoolClause object */ public final AttPoolContainer attPools = new AttPoolContainer(); // /** map from role name to exported AttPoolClause object */ // public final AttPoolContainer exportedAttPools = new AttPoolContainer(); /* exported AttPool objects are treated differently because they have difference in validation semantics. Namely, when attPool is used from the same module, its attribute declarations validate themselves against default namespace(""), whereas when used from the external modules, they validate themselves against target namespace of the module. The difficult part is that we have to achieve this semantics even when we use the RELAX schema with com.sun.msv.verifier.trex. To do this, this class has separate difinition for all exported attPools. */ /** target namespace URI */ public final String targetNamespace; /** Datatypes. */ public class DatatypeContainer { private final Map m = new java.util.HashMap(); public XSDatatype get( String name ) { return (XSDatatype)m.get(name); } public void add( XSDatatype dt ) { if(dt.getName()==null) throw new IllegalArgumentException(); m.put(dt.getName(),dt); } }; public final DatatypeContainer datatypes = new DatatypeContainer(); /** * chioce of all exported elementRules and hedgeRules. * * This can be used as the top-level expression when a module is used * to validate documents by itself. */ public Expression topLevel; public Expression getTopLevel() { return topLevel; } /** * ExpressionPool object which was used to create this module. */ public final ExpressionPool pool; public ExpressionPool getPool() { return pool; } public RELAXModule( ExpressionPool pool, String targetNamespace ) { // if you don't want to namespace, specify "" if( targetNamespace==null ) throw new NullPointerException(); this.pool = pool; this.targetNamespace = targetNamespace; datatypes.add( EmptyStringType.theInstance ); datatypes.add( NoneType.theInstance ); } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/relax/RELAXExpressionVisitorExpression.java0000644000175000017500000000156607671170035030421 0ustar giovannigiovanni/* * @(#)$Id: RELAXExpressionVisitorExpression.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.relax; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionVisitorExpression; /** * RELAX version of {@link ExpressionVisitorExpression} * * @author Kohsuke KAWAGUCHI */ public interface RELAXExpressionVisitorExpression extends ExpressionVisitorExpression { // RELAX visitor can ignore onRef callback. Expression onAttPool( AttPoolClause exp ); Expression onTag( TagClause exp ); Expression onElementRules( ElementRules exp ); Expression onHedgeRules( HedgeRules exp ); } msv-2009.1/msv/src/com/sun/msv/grammar/relax/Exportable.java0000644000175000017500000000072507671170035024127 0ustar giovannigiovanni/* * @(#)$Id: Exportable.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.relax; /** * exportable Expression. * * @author Kohsuke KAWAGUCHI */ public interface Exportable { boolean isExported(); } msv-2009.1/msv/src/com/sun/msv/grammar/relax/ElementRules.java0000644000175000017500000000417707671170035024433 0ustar giovannigiovanni/* * @(#)$Id: ElementRules.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.relax; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.ReferenceExp; /** * Set of ElementRule objects that share the label name. * * ReferenceExp.exp contains choice of ElementRule objects. * * @author Kohsuke KAWAGUCHI */ public class ElementRules extends ReferenceExp implements Exportable { protected ElementRules( String label, RELAXModule ownerModule ) { super(label); this.ownerModule = ownerModule; } public boolean equals( Object o ) { return this==o; } protected boolean calcEpsilonReducibility() { // elementRules are always not epsilon-reducible. return false; } public void addElementRule( ExpressionPool pool, ElementRule newRule ) { newRule.parent = this; if( exp==null ) // the first element exp = newRule; else exp = pool.createChoice(exp,newRule); } public Object visit( RELAXExpressionVisitor visitor ) { return visitor.onElementRules(this); } public Expression visit( RELAXExpressionVisitorExpression visitor ) { return visitor.onElementRules(this); } public boolean visit( RELAXExpressionVisitorBoolean visitor ) { return visitor.onElementRules(this); } public void visit( RELAXExpressionVisitorVoid visitor ) { visitor.onElementRules(this); } /** * a flag that indicates this elementRule is exported and * therefore accessible from other modules. */ public boolean exported = false; public boolean isExported() { return exported; } /** RELAXModule object to which this object belongs */ public final RELAXModule ownerModule; // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/NameClass.java0000644000175000017500000000761110005261245022543 0ustar giovannigiovanni/* * @(#)$Id: NameClass.java 1628 2004-01-26 18:55:33Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; import com.sun.msv.grammar.util.NameClassCollisionChecker; import com.sun.msv.grammar.util.NameClassComparator; import com.sun.msv.grammar.util.NameClassSimplifier; import com.sun.msv.util.StringPair; /** * validator of (namespaceURI,localPart) pair. * * This is equivalent to RELAX NG's "name class". * * @author Kohsuke KAWAGUCHI */ public abstract class NameClass implements java.io.Serializable { /** * checks if this name class accepts given namespace:localName pair. * * @param namespaceURI * namespace URI to be tested. If this value equals to * NAMESPACE_WILDCARD, implementation must assume that * valid namespace is specified. this twist will be used for * error diagnosis. * * @param localName * local part to be tested. As with namespaceURI, LOCALNAME_WILDCARD * will acts as a wild card. * * @return * true if the pair is accepted, * false otherwise. */ public abstract boolean accepts( String namespaceURI, String localName ); public final boolean accepts( StringPair name ) { return accepts( name.namespaceURI, name.localName ); } /** Returns true if this name class is a superset of another name class. */ public final boolean includes( NameClass rhs ) { boolean r = new NameClassComparator() { protected void probe(String uri, String local) { if( !nc1.accepts(uri,local) && nc2.accepts(uri,local) ) throw eureka; // this is not a super-set! } }.check(this,rhs); return !r; } /** Returns true if this name class doesn't accept anything. */ public boolean isNull() { return !new NameClassCollisionChecker().check(this,NameClass.ALL); } /** * Returns true if this name class represents the same set as the given name class. */ public final boolean isEqualTo( NameClass rhs ) { boolean r = new NameClassComparator() { protected void probe(String uri, String local) { boolean a = nc1.accepts(uri,local); boolean b = nc2.accepts(uri,local); if( (a&&!b) || (!a&&b) ) throw eureka; } }.check(this,rhs); return !r; } /** * Computes the equivalent but simple name class. */ public NameClass simplify() { return NameClassSimplifier.simplify(this); } /** * visitor pattern support */ public abstract Object visit( NameClassVisitor visitor ); /** wildcard should be accepted by any name class. */ public static final String NAMESPACE_WILDCARD = "*"; public static final String LOCALNAME_WILDCARD = "*"; /** Computes the intersection of two name classes. */ public static NameClass intersection( NameClass lhs, NameClass rhs ) { return NameClassSimplifier.simplify( new DifferenceNameClass( lhs, new NotNameClass(rhs) ) ); } /** Computes the union of two name classes. */ public static NameClass union( NameClass lhs, NameClass rhs ) { return NameClassSimplifier.simplify( new ChoiceNameClass(lhs,rhs) ); } /** name class that accepts everything. */ public static final NameClass ALL = new AnyNameClass(); /** Name class that accepts nothing. */ public static final NameClass NONE = new NotNameClass(ALL); // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/NotNameClass.java0000644000175000017500000000220507671170035023231 0ustar giovannigiovanni/* * @(#)$Id: NotNameClass.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; /** * NameClass that acts a not operator. * * Actually, A NotNameClass can be represented by using a DifferenceNameClass * and AnyNameClass. * * @author Kohsuke KAWAGUCHI */ public final class NotNameClass extends NameClass { public final NameClass child; /** * accepts a name if it is not accepted by the child name class. */ public boolean accepts( String namespaceURI, String localName ) { return !child.accepts(namespaceURI,localName); } public Object visit( NameClassVisitor visitor ) { return visitor.onNot(this); } public NotNameClass( NameClass child ) { this.child = child; } public String toString() { return "~"+child.toString(); } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/Grammar.java0000644000175000017500000000154307671170035022274 0ustar giovannigiovanni/* * @(#)$Id: Grammar.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; /** * base interface of the "grammar". * * This interface characterizes very basic part of grammar. * * @author Kohsuke KAWAGUCHI */ public interface Grammar extends java.io.Serializable { /** * gets top-level expression. * This expression shall be the constraint over the document element. * Never return null. */ Expression getTopLevel(); /** * gets ExpressionPool object which was used to construct this grammar. * Never return null. */ ExpressionPool getPool(); } msv-2009.1/msv/src/com/sun/msv/grammar/NamespaceNameClass.java0000644000175000017500000000226607671170035024374 0ustar giovannigiovanni/* * @(#)$Id: NamespaceNameClass.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; /** * NameClass that matchs any names in a particular namespace. * * @author Kohsuke KAWAGUCHI */ public class NamespaceNameClass extends NameClass { public final String namespaceURI; /** * accepts a name if its namespace URI matches to the namespaceURI field. */ public boolean accepts( String namespaceURI, String localName ) { if( NAMESPACE_WILDCARD==namespaceURI ) return true; return this.namespaceURI.equals(namespaceURI); } public Object visit( NameClassVisitor visitor ) { return visitor.onNsName(this); } public NamespaceNameClass( String namespaceURI ) { this.namespaceURI = namespaceURI; } public String toString() { return namespaceURI+":*"; } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/ElementExp.java0000644000175000017500000000545007766432346022770 0ustar giovannigiovanni/* * @(#)$Id: ElementExp.java 1620 2003-12-12 21:36:38Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; /** * Element declaration. * * For RELAX, this is a base implementation of 'elementRule' declaration. * For TREX, this is a base implementation of 'element' pattern. * * Each grammar must/can provide only one concrete implementation. * Therefore, they cannot override visit method. * *

      * This class can be extended. * * @author Kohsuke KAWAGUCHI */ public abstract class ElementExp extends Expression implements NameClassAndExpression { /** content model of this element declaration. */ public Expression contentModel; public final Expression getContentModel() { return contentModel; } /** a flag that indicates undeclared attributes should be ignored. */ public boolean ignoreUndeclaredAttributes; /** obtains a constraint over tag name. * * ElementExp is cannot be shared because NameClass has to be mutable * to absorb the difference of RELAX and TREX. * * In case of TREX, name class will be determined when parsing ElementExp itself. * Thus effectively it's immutable. * * In case of RELAX, name class will be determined when its corresponding Clause * object is parsed. */ abstract public NameClass getNameClass(); public ElementExp( Expression contentModel, boolean ignoreUndeclaredAttributes ) { // since ElementExp is not unified, no two ElementExp objects are considered equal. // therefore essentially any value can be used as hash code. // that's why this code works even when content model may be changed later. super( contentModel.hashCode() ); this.contentModel = contentModel; this.ignoreUndeclaredAttributes = ignoreUndeclaredAttributes; } protected final int calcHashCode() { return contentModel.hashCode(); } public final boolean equals( Object o ) { return this==o; } public final Object visit( ExpressionVisitor visitor ) { return visitor.onElement(this); } public final Expression visit( ExpressionVisitorExpression visitor ) { return visitor.onElement(this); } public final boolean visit( ExpressionVisitorBoolean visitor ) { return visitor.onElement(this); } public final void visit( ExpressionVisitorVoid visitor ) { visitor.onElement(this); } protected final boolean calcEpsilonReducibility() { return false; } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/ExpressionCloner.java0000644000175000017500000000561207671170035024211 0ustar giovannigiovanni/* * @(#)$Id: ExpressionCloner.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; /** * clones an expression. * *

      * By visiting an expression, returns a cloned expression. * *

      * This class is useless by itself since expressions are shared and unified. * It should be used as a base class for various AGM-related tasks to modify * AGM. * *

      * Note that this class doesn't provide default implementations for * onAttribute, onElement, and onRef methods. * Typically, the derived class needs to do something to prevent infinite recursion. * * @author Kohsuke KAWAGUCHI */ public abstract class ExpressionCloner implements ExpressionVisitorExpression { protected final ExpressionPool pool; protected ExpressionCloner( ExpressionPool pool ) { this.pool = pool; } public Expression onChoice( ChoiceExp exp ) { Expression np1 = exp.exp1.visit(this); Expression np2 = exp.exp2.visit(this); if(exp.exp1==np1 && exp.exp2==np2) return exp; else return pool.createChoice(np1,np2); } public Expression onOneOrMore( OneOrMoreExp exp ) { Expression np = exp.exp.visit(this); if(exp.exp==np) return exp; else return pool.createOneOrMore(np); } public Expression onMixed( MixedExp exp ) { Expression body = exp.exp.visit(this); if(exp.exp==body) return exp; else return pool.createMixed( body ); } public Expression onList( ListExp exp ) { Expression body = exp.exp.visit(this); if(exp.exp==body) return exp; else return pool.createList( body ); } public Expression onSequence( SequenceExp exp ) { Expression np1 = exp.exp1.visit(this); Expression np2 = exp.exp2.visit(this); if(exp.exp1==np1 && exp.exp2==np2) return exp; else return pool.createSequence(np1,np2); } public Expression onConcur( ConcurExp exp ) { return pool.createConcur( exp.exp1.visit(this), exp.exp2.visit(this)); } public Expression onInterleave( InterleaveExp exp ) { return pool.createInterleave( exp.exp1.visit(this), exp.exp2.visit(this)); } public Expression onEpsilon() { return Expression.epsilon; } public Expression onNullSet() { return Expression.nullSet; } public Expression onAnyString() { return Expression.anyString; } public Expression onData( DataExp exp ) { return exp; } public Expression onValue( ValueExp exp ) { return exp; } } msv-2009.1/msv/src/com/sun/msv/grammar/UnaryExp.java0000644000175000017500000000216607766432346022476 0ustar giovannigiovanni/* * @(#)$Id: UnaryExp.java 1620 2003-12-12 21:36:38Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; /** * Base implementation for those expression who has one child expresison. * * @author Kohsuke KAWAGUCHI */ public abstract class UnaryExp extends Expression { /** child expression. */ public final Expression exp; protected UnaryExp( Expression exp) { super(exp.hashCode()); this.exp = exp; } protected final int calcHashCode() { return exp.hashCode(); } public boolean equals( Object o ) { if( !this.getClass().equals(o.getClass()) ) return false; // every existing children are already unified. // therefore, == is enough. (don't need to call equals) return ((UnaryExp)o).exp == exp; } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/AttributeExp.java0000644000175000017500000000405507766432346023342 0ustar giovannigiovanni/* * @(#)$Id: AttributeExp.java 1620 2003-12-12 21:36:38Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; /** * Attribute declaration. * *

      * Attribute declaration consists of a NameClass that verifies attribute name * and an Expression that verifies the value of the attribute. * * @author Kohsuke KAWAGUCHI */ public class AttributeExp extends Expression implements NameClassAndExpression { /** constraint over attribute name */ public final NameClass nameClass; public final NameClass getNameClass() { return nameClass; } /** child expression */ public final Expression exp; public final Expression getContentModel() { return exp; } public AttributeExp( NameClass nameClass, Expression exp ) { super( nameClass.hashCode()+exp.hashCode() ); this.nameClass = nameClass; this.exp = exp; } protected final int calcHashCode() { return nameClass.hashCode()+exp.hashCode(); } public boolean equals( Object o ) { // reject derived classes if(o.getClass()!=AttributeExp.class) return false; AttributeExp rhs = (AttributeExp)o; return rhs.nameClass.equals(nameClass) && rhs.exp.equals(exp); } public Object visit( ExpressionVisitor visitor ) { return visitor.onAttribute(this); } public Expression visit( ExpressionVisitorExpression visitor ) { return visitor.onAttribute(this); } public boolean visit( ExpressionVisitorBoolean visitor ) { return visitor.onAttribute(this); } public void visit( ExpressionVisitorVoid visitor ) { visitor.onAttribute(this); } protected boolean calcEpsilonReducibility() { return false; } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/util/0000755000175000017500000000000011622453067021015 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/grammar/util/NameClassComparator.java0000644000175000017500000000542110005261245025545 0ustar giovannigiovanni/* * @(#)$Id: NameClassComparator.java 1628 2004-01-26 18:55:33Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.util; import com.sun.msv.grammar.AnyNameClass; import com.sun.msv.grammar.ChoiceNameClass; import com.sun.msv.grammar.DifferenceNameClass; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.NameClassVisitor; import com.sun.msv.grammar.NamespaceNameClass; import com.sun.msv.grammar.NotNameClass; import com.sun.msv.grammar.SimpleNameClass; /** * Abstract implementation of a function *

       *   NameClass x NameClass ->  boolean
       * 
      * * Override the probe method to define the actual function. * * *

      * To compute, create an instance and call the check method. This class is not * reentrant, so the caller is responsible not to reuse the same object by multiple * threads. * * @author Kohsuke KAWAGUCHI */ public abstract class NameClassComparator implements NameClassVisitor { /** Two name classes to be tested. */ protected NameClass nc1,nc2; /** * This exception will be thrown when a collision is found. */ protected final RuntimeException eureka = new RuntimeException(); /** * Returns true if two name classes collide. */ public boolean check( NameClass _new, NameClass _old ) { try { nc1 = _new; nc2 = _old; _old.visit(this); _new.visit(this); return false; } catch( RuntimeException e ) { if(e==eureka) return true; // the collision was found. throw e; } } /** * Throw eureka to return true from the probe method. */ protected abstract void probe( String uri, String local ); private /*static*/ final String MAGIC = "\u0000"; public Object onAnyName( AnyNameClass nc ) { probe(MAGIC,MAGIC); return null; } public Object onNsName( NamespaceNameClass nc ) { probe(nc.namespaceURI,MAGIC); return null; } public Object onSimple( SimpleNameClass nc ) { probe(nc.namespaceURI,nc.localName); return null; } public Object onNot( NotNameClass nc ) { nc.child.visit(this); return null; } public Object onDifference( DifferenceNameClass nc ) { nc.nc1.visit(this); nc.nc2.visit(this); return null; } public Object onChoice( ChoiceNameClass nc ) { nc.nc1.visit(this); nc.nc2.visit(this); return null; } }msv-2009.1/msv/src/com/sun/msv/grammar/util/package.html0000644000175000017500000000010207260744467023301 0ustar giovannigiovanni

      Miscellaneous utility classes.

      msv-2009.1/msv/src/com/sun/msv/grammar/util/RefExpRemover.java0000644000175000017500000000534607671170035024421 0ustar giovannigiovanni/* * @(#)$Id: RefExpRemover.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.util; import java.util.Set; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionCloner; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.OtherExp; import com.sun.msv.grammar.ReferenceExp; /** * removes all ReferenceExp from AGM. * * when named expression is nullSet, it cannot be used. * by replacing ReferenceExp by its definition, those unavailable expressions * will be properly removed from AGM. * * @author Kohsuke KAWAGUCHI */ public class RefExpRemover extends ExpressionCloner { /** set of visited ElementExps */ private final Set visitedElements = new java.util.HashSet(); private final boolean recursive; /** * @param _recursive *

      * If true, this object behaves destructively. It recursively * visits all the reachable expressions and removes ReferenceExps. * In this process, this object changes the content model of * ElementExps. * *

      * If false, this object doesn't visit the content models of child * elements, therefore, it behaves non-destructively. Nothing in the * original expression will be touched. */ public RefExpRemover(ExpressionPool pool, boolean _recursive) { super(pool); this.recursive = _recursive; } public Expression onElement(ElementExp exp) { if (!recursive) // do not touch child elements. return exp; if (!visitedElements.contains(exp)) { // remove refs from this content model visitedElements.add(exp); exp.contentModel = exp.contentModel.visit(this); } if (exp.contentModel == Expression.nullSet) return Expression.nullSet; // this element is not allowed else return exp; } public Expression onAttribute(AttributeExp exp) { Expression content = exp.exp.visit(this); if (content == Expression.nullSet) return Expression.nullSet; // this attribute is not allowed else return pool.createAttribute(exp.nameClass, content); } public Expression onRef(ReferenceExp exp) { return exp.exp.visit(this); } public Expression onOther(OtherExp exp) { return exp.exp.visit(this); } } msv-2009.1/msv/src/com/sun/msv/grammar/util/NameClassSimplifier.java0000644000175000017500000000725707730143103025555 0ustar giovannigiovanni/* * @(#)$Id: NameClassSimplifier.java 1601 2003-09-11 19:00:19Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.util; import java.util.Iterator; import java.util.Set; import com.sun.msv.grammar.AnyNameClass; import com.sun.msv.grammar.ChoiceNameClass; import com.sun.msv.grammar.DifferenceNameClass; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.NamespaceNameClass; import com.sun.msv.grammar.NotNameClass; import com.sun.msv.grammar.SimpleNameClass; import com.sun.msv.util.StringPair; /** * Minimizes a name class. * * Sometimes, a name class could become unnecessarily big. For example, * *

      
       * <choice>
       *   <anyName/>
       *   <anyName/>
       *   <anyName/>
       * </choice>
       * 
      * * This procedure converts those name classes to the equivalent small name class. * * @author Kohsuke KAWAGUCHI */ public class NameClassSimplifier { public static NameClass simplify( NameClass nc ) { final Set possibleNames = PossibleNamesCollector.calc(nc); final String MAGIC = PossibleNamesCollector.MAGIC; Set uris = new java.util.HashSet(); Iterator itr = possibleNames.iterator(); while( itr.hasNext() ) { StringPair name = (StringPair)itr.next(); if( name.localName!=MAGIC ) { // a simple name. if( nc.accepts(name)==nc.accepts( name.namespaceURI, MAGIC ) ) { itr.remove(); continue; } } else if( name.namespaceURI!=MAGIC ) { // a ns name if( nc.accepts(name)==nc.accepts(MAGIC,MAGIC) ) { itr.remove(); continue; } } // collect the remainig namespace URIs. if( name.namespaceURI!=MAGIC ) uris.add(name.namespaceURI); } if( !nc.accepts(MAGIC,MAGIC) ) possibleNames.remove( new StringPair(MAGIC,MAGIC) ); NameClass result = null; Iterator jtr = uris.iterator(); while( jtr.hasNext() ) { final String uri = (String)jtr.next(); NameClass local = null; itr = possibleNames.iterator(); while( itr.hasNext() ) { final StringPair name = (StringPair)itr.next(); if(!name.namespaceURI.equals(uri)) continue; if(name.localName==MAGIC) continue; if(local==null) local = new SimpleNameClass(name); else local = new ChoiceNameClass(local,new SimpleNameClass(name)); } if(possibleNames.contains(new StringPair(uri,MAGIC))) { if(local==null) local = new NamespaceNameClass(uri); else local = new DifferenceNameClass(new NamespaceNameClass(uri),local); } if(local!=null) { if(result==null) result = local; else result = new ChoiceNameClass(result,local); } } if( nc.accepts(MAGIC,MAGIC) ) { if(result==null) result = NameClass.ALL; else result = new NotNameClass(result); } if( result==null ) result = AnyNameClass.NONE; return result; } } msv-2009.1/msv/src/com/sun/msv/grammar/util/ExpressionWalker.java0000644000175000017500000000466407671170035025177 0ustar giovannigiovanni/* * @(#)$Id: ExpressionWalker.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.util; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.BinaryExp; import com.sun.msv.grammar.ChoiceExp; import com.sun.msv.grammar.ConcurExp; import com.sun.msv.grammar.DataExp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.ExpressionVisitorVoid; import com.sun.msv.grammar.InterleaveExp; import com.sun.msv.grammar.ListExp; import com.sun.msv.grammar.MixedExp; import com.sun.msv.grammar.OneOrMoreExp; import com.sun.msv.grammar.OtherExp; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.SequenceExp; import com.sun.msv.grammar.ValueExp; /** * Visits all reachable expressions but do nothing. * * Note that unless the derived class do something, this implementation * will recurse infinitely. * * @author Kohsuke KAWAGUCHI */ public abstract class ExpressionWalker implements ExpressionVisitorVoid { public void onRef( ReferenceExp exp ) { exp.exp.visit(this); } public void onOther( OtherExp exp ) { exp.exp.visit(this); } public void onElement( ElementExp exp ) { exp.contentModel.visit(this); } public void onEpsilon() {} public void onNullSet() {} public void onAnyString() {} public void onData( DataExp exp ) {} public void onValue( ValueExp exp ) {} public void onInterleave( InterleaveExp exp ) { onBinExp(exp); } public void onConcur( ConcurExp exp ) { onBinExp(exp); } public void onChoice( ChoiceExp exp ) { onBinExp(exp); } public void onSequence( SequenceExp exp ) { onBinExp(exp); } public void onBinExp( BinaryExp exp ) { exp.exp1.visit(this); exp.exp2.visit(this); } public void onMixed( MixedExp exp ) { exp.exp.visit(this); } public void onList( ListExp exp ) { exp.exp.visit(this); } public void onOneOrMore( OneOrMoreExp exp ) { exp.exp.visit(this); } public void onAttribute( AttributeExp exp ) { exp.exp.visit(this); } } msv-2009.1/msv/src/com/sun/msv/grammar/util/NameClassCollisionChecker.java0000644000175000017500000000201011156747174026667 0ustar giovannigiovanni/* * @(#)$Id: NameClassCollisionChecker.java 1744 2009-03-14 15:34:20Z bimargulies $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.util; import com.sun.msv.grammar.NameClass; /** * Computes if two name classes collide or not. * *

      * This comparator returns true if the intersection of two name classes * is non empty. * *

      * The same thing can be computed by using the * {@link com.sun.msv.grammar.NameClass#intersection(NameClass, NameClass)} method, * but generally this method is faster. * * @author Kohsuke KAWAGUCHI */ public class NameClassCollisionChecker extends NameClassComparator { protected void probe( String uri, String local ) { if(nc1.accepts(uri,local) && nc2.accepts(uri,local)) // conflict is found. throw eureka; } }msv-2009.1/msv/src/com/sun/msv/grammar/util/ExpressionFinder.java0000644000175000017500000000551007671170035025150 0ustar giovannigiovanni/* * @(#)$Id: ExpressionFinder.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.util; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.ChoiceExp; import com.sun.msv.grammar.ConcurExp; import com.sun.msv.grammar.DataExp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.ExpressionVisitorBoolean; import com.sun.msv.grammar.InterleaveExp; import com.sun.msv.grammar.ListExp; import com.sun.msv.grammar.MixedExp; import com.sun.msv.grammar.OneOrMoreExp; import com.sun.msv.grammar.OtherExp; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.SequenceExp; import com.sun.msv.grammar.ValueExp; /** * Base class for "finding" something from an expression. * * This class visits all reachable expressions and returns boolean. * * In any binary expression, if one branch returns true, then the binary * expression itself returns true. Thus it can be used to find something * from an expression. * * Note that unless the derived class do something, this implementation * will recurse infinitely. * * @author Kohsuke KAWAGUCHI */ public abstract class ExpressionFinder implements ExpressionVisitorBoolean { public boolean onSequence( SequenceExp exp ) { return exp.exp1.visit(this)||exp.exp2.visit(this); } public boolean onInterleave( InterleaveExp exp ) { return exp.exp1.visit(this)||exp.exp2.visit(this); } public boolean onConcur( ConcurExp exp ) { return exp.exp1.visit(this)||exp.exp2.visit(this); } public boolean onChoice( ChoiceExp exp ) { return exp.exp1.visit(this)||exp.exp2.visit(this); } public boolean onAttribute( AttributeExp exp ) { return exp.exp.visit(this); } public boolean onElement( ElementExp exp ) { return exp.contentModel.visit(this); } public boolean onOneOrMore( OneOrMoreExp exp ) { return exp.exp.visit(this); } public boolean onMixed( MixedExp exp ) { return exp.exp.visit(this); } public boolean onList( ListExp exp ) { return exp.exp.visit(this); } public boolean onRef( ReferenceExp exp ) { return exp.exp.visit(this); } public boolean onOther( OtherExp exp ) { return exp.exp.visit(this); } public boolean onEpsilon() { return false; } public boolean onNullSet() { return false; } public boolean onAnyString() { return false; } public boolean onData( DataExp exp ) { return false; } public boolean onValue( ValueExp exp ) { return false; } } msv-2009.1/msv/src/com/sun/msv/grammar/util/IDContextProviderWrapper.java0000644000175000017500000000305007671167271026603 0ustar giovannigiovanni/* * @(#)$Id: IDContextProviderWrapper.java 1565 2003-06-09 20:31:53Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.util; import org.relaxng.datatype.Datatype; import com.sun.msv.grammar.IDContextProvider; import com.sun.msv.grammar.IDContextProvider2; import com.sun.msv.verifier.regexp.StringToken; /** * Wraps {@link IDContextProvider} so that it can be used * where {@link IDContextProvider2} is expected. * * @author * Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) */ public final class IDContextProviderWrapper implements IDContextProvider2 { private final IDContextProvider core; public static IDContextProvider2 create( IDContextProvider core ) { if(core==null) return null; else return new IDContextProviderWrapper(core); } private IDContextProviderWrapper( IDContextProvider _core ) { this.core = _core; } public String getBaseUri() { return core.getBaseUri(); } public boolean isNotation(String arg0) { return core.isNotation(arg0); } public boolean isUnparsedEntity(String arg0) { return core.isUnparsedEntity(arg0); } public void onID(Datatype datatype, StringToken token) { core.onID(datatype, token.literal); } public String resolveNamespacePrefix(String arg0) { return core.resolveNamespacePrefix(arg0); } } msv-2009.1/msv/src/com/sun/msv/grammar/util/ExpressionPrinter.java0000644000175000017500000001405507671170035025370 0ustar giovannigiovanni/* * @(#)$Id: ExpressionPrinter.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.util; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.BinaryExp; import com.sun.msv.grammar.ChoiceExp; import com.sun.msv.grammar.ConcurExp; import com.sun.msv.grammar.DataExp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionVisitor; import com.sun.msv.grammar.InterleaveExp; import com.sun.msv.grammar.ListExp; import com.sun.msv.grammar.MixedExp; import com.sun.msv.grammar.OneOrMoreExp; import com.sun.msv.grammar.OtherExp; import com.sun.msv.grammar.ReferenceContainer; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.SequenceExp; import com.sun.msv.grammar.ValueExp; /** * creates a string representation of the expression. * * useful for debug and dump. * * @author Kohsuke KAWAGUCHI */ public class ExpressionPrinter implements ExpressionVisitor { /** in this mode, reference to other expression is * one of the terminal symbol of stringnization. * * Suitable to dump the entire grammar */ public final static int FRAGMENT = 0x001; /** in this mode, element declaration is * one of the terminal symbol of stringnization. * * Suitable to dump the content model of element declarations. */ public final static int CONTENTMODEL = 0x002; // singleton access public static ExpressionPrinter fragmentInstance = new ExpressionPrinter(FRAGMENT); public static ExpressionPrinter contentModelInstance = new ExpressionPrinter(CONTENTMODEL); public static ExpressionPrinter smallestInstance = new ExpressionPrinter(CONTENTMODEL|FRAGMENT); public static String printFragment(Expression exp) { return (String)exp.visit(fragmentInstance); } public static String printContentModel(Expression exp) { return (String)exp.visit(contentModelInstance); } public static String printSmallest(Expression exp) { return (String)exp.visit(smallestInstance); } /** this flag controls how expression will be stringnized */ protected final int mode; protected ExpressionPrinter( int mode ) { this.mode = mode; } /** dumps all the contents of ReferenceContainer. * * this method is a useful piece to dump the entire grammar. */ public String printRefContainer( ReferenceContainer cont ) { String r=""; java.util.Iterator itr = cont.iterator(); while( itr.hasNext() ) { ReferenceExp exp = (ReferenceExp)itr.next(); r += exp.name + " : " + exp.exp.visit(this) + "\n"; } return r; } /** determines whether brackets should be used to represent the pattern */ protected static boolean isComplex( Expression exp ) { return exp instanceof BinaryExp; } protected String printBinary( BinaryExp exp, String op ) { String r; if( exp.exp1.getClass()==exp.getClass() || !isComplex(exp.exp1) ) r = (String)exp.exp1.visit(this); else r = "("+exp.exp1.visit(this)+")"; r+=op; if( !isComplex(exp.exp2) ) r+=exp.exp2.visit(this); else r+="("+exp.exp2.visit(this)+")"; return r; } public Object onAttribute( AttributeExp exp ) { return "@"+exp.nameClass.toString()+"<"+exp.exp.visit(this)+">"; } private Object optional( Expression exp ) { if( exp instanceof OneOrMoreExp ) { OneOrMoreExp ome = (OneOrMoreExp)exp; if( isComplex(ome.exp) ) return "("+ome.exp.visit(this)+")*"; else return ome.exp.visit(this)+"*"; } else { if( isComplex(exp) ) return "("+exp.visit(this)+")?"; else return exp.visit(this)+"?"; } } public Object onChoice( ChoiceExp exp ) { if( exp.exp1==Expression.epsilon ) return optional(exp.exp2); if( exp.exp2==Expression.epsilon ) return optional(exp.exp1); return printBinary(exp,"|"); } public Object onConcur( ConcurExp exp ) { return printBinary(exp,"&"); } public Object onInterleave( InterleaveExp exp ){ return printBinary(exp,"^"); } public Object onElement( ElementExp exp ) { if( (mode&CONTENTMODEL)!=0 ) return exp.getNameClass().toString(); else return exp.getNameClass().toString()+"<"+exp.contentModel.visit(this)+">"; } public Object onOneOrMore( OneOrMoreExp exp ) { if( isComplex(exp.exp) ) return "("+exp.exp.visit(this)+")+"; else return exp.exp.visit(this)+"+"; } public Object onMixed( MixedExp exp ) { return "mixed["+exp.exp.visit(this)+"]"; } public Object onList( ListExp exp ) { return "list["+exp.exp.visit(this)+"]"; } public Object onEpsilon() { return "#epsilon"; } public Object onNullSet() { return "#nullSet"; } public Object onAnyString() { return ""; } public Object onSequence( SequenceExp exp ) { return printBinary(exp,","); } public Object onData( DataExp exp ) { return "$"+exp.name.localName; } public Object onValue( ValueExp exp ) { return "$$"+exp.value; } public Object onOther( OtherExp exp ) { return exp.printName()+"["+exp.exp.visit(this)+"]"; } public Object onRef( ReferenceExp exp ) { if( (mode&FRAGMENT)!=0 ) return "{%"+exp.name+"}"; else return "("+exp.exp.visit(this)+")"; } } msv-2009.1/msv/src/com/sun/msv/grammar/util/PossibleNamesCollector.java0000644000175000017500000000461407671170035026300 0ustar giovannigiovanni/* * @(#)$Id: PossibleNamesCollector.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.util; import java.util.Set; import com.sun.msv.grammar.AnyNameClass; import com.sun.msv.grammar.ChoiceNameClass; import com.sun.msv.grammar.DifferenceNameClass; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.NameClassVisitor; import com.sun.msv.grammar.NamespaceNameClass; import com.sun.msv.grammar.NotNameClass; import com.sun.msv.grammar.SimpleNameClass; import com.sun.msv.util.StringPair; /** * computes the possible names. * *

      * See * the description. * * @author Kohsuke KAWAGUCHI */ public class PossibleNamesCollector implements NameClassVisitor { /** * computes all possibile names for this name class, and returns * the set of {@link StringPair}. */ public static Set calc( NameClass nc ) { PossibleNamesCollector col = new PossibleNamesCollector(); nc.visit(col); return col.names; } public static final String MAGIC = "\u0000"; private static final StringPair pairForAny = new StringPair( MAGIC, MAGIC ); /** this set will receive all possible names. */ private Set names = new java.util.HashSet(); public Object onChoice( ChoiceNameClass nc ) { nc.nc1.visit(this); nc.nc2.visit(this); return null; } public Object onAnyName( AnyNameClass nc ) { names.add( pairForAny ); return null; } public Object onSimple( SimpleNameClass nc ) { names.add( new StringPair( nc.namespaceURI, nc.localName ) ); return null; } public Object onNsName( NamespaceNameClass nc ) { names.add( new StringPair( nc.namespaceURI, MAGIC ) ); return null; } public Object onNot( NotNameClass nc ) { names.add( pairForAny ); nc.child.visit(this); return null; } public Object onDifference( DifferenceNameClass nc ) { nc.nc1.visit(this); nc.nc2.visit(this); return null; } }; msv-2009.1/msv/src/com/sun/msv/grammar/ChoiceNameClass.java0000644000175000017500000000222507671170035023665 0ustar giovannigiovanni/* * @(#)$Id: ChoiceNameClass.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; /** * Union of two NameClasses. * * @author Kohsuke KAWAGUCHI */ public class ChoiceNameClass extends NameClass { public final NameClass nc1; public final NameClass nc2; /** accepts a name if it is accepted by nc1 or nc2. */ public boolean accepts( String namespaceURI, String localPart ) { return nc1.accepts(namespaceURI,localPart) || nc2.accepts(namespaceURI,localPart); } public Object visit( NameClassVisitor visitor ) { return visitor.onChoice(this); } public ChoiceNameClass( NameClass nc1, NameClass nc2 ) { this.nc1 = nc1; this.nc2 = nc2; } public String toString() { return '('+nc1.toString()+'|'+nc2.toString()+')'; } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/NameClassVisitor.java0000644000175000017500000000132507671170035024132 0ustar giovannigiovanni/* * @(#)$Id: NameClassVisitor.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; /** * Visitor interface for NameClass. * * @author Kohsuke KAWAGUCHI */ public interface NameClassVisitor { Object onChoice( ChoiceNameClass nc ); Object onAnyName( AnyNameClass nc ); Object onSimple( SimpleNameClass nc ); Object onNsName( NamespaceNameClass nc ); Object onNot( NotNameClass nc ); Object onDifference( DifferenceNameClass nc ); } msv-2009.1/msv/src/com/sun/msv/grammar/SequenceExp.java0000644000175000017500000000227607766432346023152 0ustar giovannigiovanni/* * @(#)$Id: SequenceExp.java 1620 2003-12-12 21:36:38Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; /** * A,B. concatenation operator of the regular expression. * * @author Kohsuke KAWAGUCHI */ public final class SequenceExp extends BinaryExp { SequenceExp( Expression left, Expression right ) { super(left,right); } public Object visit( ExpressionVisitor visitor ) { return visitor.onSequence(this); } public Expression visit( ExpressionVisitorExpression visitor ) { return visitor.onSequence(this); } public boolean visit( ExpressionVisitorBoolean visitor ) { return visitor.onSequence(this); } public void visit( ExpressionVisitorVoid visitor ) { visitor.onSequence(this); } protected boolean calcEpsilonReducibility() { return exp1.isEpsilonReducible() && exp2.isEpsilonReducible(); } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/SimpleNameClass.java0000644000175000017500000000321607671170035023725 0ustar giovannigiovanni/* * @(#)$Id: SimpleNameClass.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; import com.sun.msv.util.StringPair; /** * a NameClass that accepts only one fixed name. * * @author Kohsuke KAWAGUCHI */ public final class SimpleNameClass extends NameClass { public final String namespaceURI; public final String localName; public boolean accepts( String namespaceURI, String localName ) { // wild cards are treated as symbols, rather than strings. return ( this.namespaceURI.equals(namespaceURI) || NAMESPACE_WILDCARD==namespaceURI ) && ( this.localName.equals(localName) || LOCALNAME_WILDCARD==localName ); } public Object visit( NameClassVisitor visitor ) { return visitor.onSimple(this); } public SimpleNameClass( StringPair name ) { this( name.namespaceURI, name.localName ); } public SimpleNameClass( String namespaceURI, String localName ) { this.namespaceURI = namespaceURI; this.localName = localName; } public StringPair toStringPair() { return new StringPair(namespaceURI,localName); } public String toString() { if( namespaceURI.length()==0 ) return localName; else return /*namespaceURI+":"+*/localName; } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/InterleaveExp.java0000644000175000017500000000175007766432346023474 0ustar giovannigiovannipackage com.sun.msv.grammar; /** * <interleave> pattern of TREX, or <all> particle of XML Schema. * * @author Kohsuke KAWAGUCHI */ public final class InterleaveExp extends BinaryExp { InterleaveExp( Expression left, Expression right ) { super(left,right); } public Object visit( ExpressionVisitor visitor ) { return visitor.onInterleave(this); } public Expression visit( ExpressionVisitorExpression visitor ) { return visitor.onInterleave(this); } public boolean visit( ExpressionVisitorBoolean visitor ) { return visitor.onInterleave(this); } public void visit( ExpressionVisitorVoid visitor ) { visitor.onInterleave(this); } protected boolean calcEpsilonReducibility() { return exp1.isEpsilonReducible() && exp2.isEpsilonReducible(); } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/BinaryExp.java0000644000175000017500000000540607766432346022624 0ustar giovannigiovanni/* * @(#)$Id: BinaryExp.java 1620 2003-12-12 21:36:38Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; import java.util.Iterator; /** * Base implementation for those expression which has two child expressions. * * @author Kohsuke KAWAGUCHI */ public abstract class BinaryExp extends Expression { public final Expression exp1; public final Expression exp2; public BinaryExp( Expression left, Expression right ) { super( left.hashCode()+right.hashCode() ); this.exp1 = left; this.exp2 = right; } protected final int calcHashCode() { return exp1.hashCode()+exp2.hashCode(); } public boolean equals( Object o ) { if( this.getClass()!=o.getClass() ) return false; // every existing children are already unified. // therefore, == is enough. (don't need to call equals) BinaryExp rhs = (BinaryExp)o; return rhs.exp1 == exp1 && rhs.exp2 == exp2; } /** * returns all child expressions in one array. * * This method is similar to the children method but it returns an array * that contains all children instead of an iterator object. */ public Expression[] getChildren() { // count the number of children int cnt=1; Expression exp = this; while( exp.getClass()==this.getClass() ) { cnt++; exp = ((BinaryExp)exp).exp1; } Expression[] r = new Expression[cnt]; exp=this; while( exp.getClass()==this.getClass() ) { r[--cnt] = ((BinaryExp)exp).exp2; exp = ((BinaryExp)exp).exp1; } r[0] = exp; return r; } /** * iterates all child expressions. * * Since expressions are binarized, expressions like A|B|C is modeled as * A|(B|C). This is may not be preferable for some applications. * *

      * This method returns an iterator that iterates all children * (A,B, and C in this example) */ public Iterator children() { final Expression[] items = getChildren(); return new Iterator() { private int idx =0; public Object next() { return items[idx++]; } public boolean hasNext() { return idx!=items.length; } public void remove() { throw new UnsupportedOperationException(); } }; } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/ExpressionVisitor.java0000644000175000017500000000276607671170035024435 0ustar giovannigiovanni/* * @(#)$Id: ExpressionVisitor.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; /** * Visitor interface for Expression and its derived types. * *

      * You may want to use ExpressionVisitorXXXX class if you want to * return boolean, void, or {@link Expression}. * *

      * It is the callee's responsibility to traverse child expression. * Expression and its derived classes do not provide any traversal. * See {@link ExpressionCloner} for example. * *

      * onRef method is called for all subclass of ReferenceExp. So you can safely use this * interface to visit AGMs from RELAX grammar. * * @author Kohsuke KAWAGUCHI */ public interface ExpressionVisitor { Object onAttribute( AttributeExp exp ); Object onChoice( ChoiceExp exp ); Object onElement( ElementExp exp ); Object onOneOrMore( OneOrMoreExp exp ); Object onMixed( MixedExp exp ); Object onList( ListExp exp ); Object onRef( ReferenceExp exp ); Object onOther( OtherExp exp ); Object onEpsilon(); Object onNullSet(); Object onAnyString(); Object onSequence( SequenceExp exp ); Object onData( DataExp exp ); Object onValue( ValueExp exp ); Object onConcur( ConcurExp p ); Object onInterleave( InterleaveExp p ); } msv-2009.1/msv/src/com/sun/msv/grammar/DifferenceNameClass.java0000644000175000017500000000230307671170035024522 0ustar giovannigiovanni/* * @(#)$Id: DifferenceNameClass.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; /** * <difference> name class. * * @author Kohsuke KAWAGUCHI */ public class DifferenceNameClass extends NameClass { public final NameClass nc1; public final NameClass nc2; /** * accepts a name if it is accepted by nc1 and not by nc2. */ public boolean accepts( String namespaceURI, String localPart ) { return nc1.accepts(namespaceURI,localPart) && !nc2.accepts(namespaceURI,localPart); } public Object visit( NameClassVisitor visitor ) { return visitor.onDifference(this); } public DifferenceNameClass( NameClass nc1, NameClass nc2 ) { this.nc1 = nc1; this.nc2 = nc2; } public String toString() { return nc1.toString()+"-"+nc2.toString(); } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/trex/0000755000175000017500000000000011622453066021021 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/grammar/trex/typed/0000755000175000017500000000000011622453066022146 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/grammar/trex/typed/TypedElementPattern.java0000644000175000017500000000176607671170035026761 0ustar giovannigiovanni/* * @(#)$Id: TypedElementPattern.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.trex.typed; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.trex.ElementPattern; /** * ElementPattern with type. * * Proprietary extension by MSV to support type-assignment in TREX. * * @author Kohsuke KAWAGUCHI */ public class TypedElementPattern extends ElementPattern { /** label of this element. */ public final String label; public TypedElementPattern( NameClass nameClass, Expression contentModel, String label ) { super(nameClass,contentModel); this.label = label; } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/trex/typed/package.html0000644000175000017500000000013407260744467024440 0ustar giovannigiovanni

      Abstract grammar model (AGM): TREX label-annotated stub.

      msv-2009.1/msv/src/com/sun/msv/grammar/trex/package.html0000644000175000017500000000060607260744445023313 0ustar giovannigiovanni

      abstract grammar model (AGM): TREX extension and TREX stub.

      This model acts as the in-memory representation of TREX grammar. This grammar is then used to validate documents, as well as any other application-dependent purpose.

      msv-2009.1/msv/src/com/sun/msv/grammar/trex/Localizer.java0000644000175000017500000000162607671170035023616 0ustar giovannigiovanni/* * @(#)$Id: Localizer.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.trex; /** * formats messages by using a resource file. * * @author Kohsuke KAWAGUCHI */ class Localizer { public static String localize( String prop, Object[] args ) { return java.text.MessageFormat.format( java.util.ResourceBundle.getBundle("com.sun.msv.grammar.trex.Messages").getString(prop), args ); } public static String localize( String prop ) { return localize( prop, null ); } public static String localize( String prop, Object arg1 ) { return localize( prop, new Object[]{arg1} ); } } msv-2009.1/msv/src/com/sun/msv/grammar/trex/ElementPattern.java0000644000175000017500000000165607671170035024624 0ustar giovannigiovanni/* * @(#)$Id: ElementPattern.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.trex; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.NameClass; /** * <element> pattern of TREX. * * @author Kohsuke KAWAGUCHI */ public class ElementPattern extends ElementExp { public final NameClass nameClass; public final NameClass getNameClass() { return nameClass; } public ElementPattern( NameClass nameClass, Expression contentModel ) { super(contentModel,false); this.nameClass = nameClass; } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/trex/Messages.properties0000644000175000017500000000005607255777334024725 0ustar giovannigiovanniTypedString.Diagnosis =\ value must be "{0}" msv-2009.1/msv/src/com/sun/msv/grammar/trex/TREXGrammar.java0000644000175000017500000000552007671170035023760 0ustar giovannigiovanni/* * @(#)$Id: TREXGrammar.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.trex; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.Grammar; import com.sun.msv.grammar.ReferenceContainer; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.reader.datatype.DataTypeVocabularyMap; /** * TREX grammar, which is expressed as <grammar> element. * *

      * The exp field keeps the start pattern. * * @author Kohsuke KAWAGUCHI */ public class TREXGrammar extends ReferenceExp implements Grammar{ static final public class RefContainer extends ReferenceContainer { public ReferenceExp getOrCreate( String name ) { return super._getOrCreate(name); } protected ReferenceExp createReference( String name ) { return new ReferenceExp(name); } } /** named patterns which are defined by using <define> element. * * this is a map from pattern name to RefPattern object */ public final RefContainer namedPatterns = new RefContainer(); /** gets the start pattern. * * The pattern defined under <start> element. * This pattern will be used to verify document element. */ public Expression getTopLevel() { return this.exp; } /** ExpressionPool that is associated with this grammar */ public final ExpressionPool pool; public ExpressionPool getPool() { return pool; } /** in case of nested grammar, this variable points to the parent grammar. * Otherwise null. */ protected final TREXGrammar parentGrammar; /** * gets a parent TREXGrammar. * * In case of nested grammar, the parent grammar will be returned. * Otherwise, it returns null. */ public final TREXGrammar getParentGrammar() { return parentGrammar; } /** * data type vocabularies used and defined by this grammar. */ public final DataTypeVocabularyMap dataTypes = new DataTypeVocabularyMap(); /** * * @param parentGrammar * this object is used to resolve <ref> element with parent * attribute. */ public TREXGrammar( ExpressionPool pool, TREXGrammar parentGrammar ) { super(null); this.pool = pool; this.parentGrammar = parentGrammar; } public TREXGrammar( ExpressionPool pool ) { this(pool,null); } public TREXGrammar() { this(new ExpressionPool(),null); } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/ExpressionPool.java0000644000175000017500000004256510005261216023673 0ustar giovannigiovanni/* * @(#)$Id: ExpressionPool.java 1627 2004-01-26 18:55:10Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import org.relaxng.datatype.Datatype; import com.sun.msv.datatype.xsd.XSDatatype; import com.sun.msv.util.StringPair; /** * Creates a new Expression by combining existing expressions. * * all expressions are memorized and unified so that every subexpression * will be shared and reused. Optimization will be also done transparently. * For example, createChoice(P,P) will result in P. createSequence(P,nullSet) * will result in nullSet. * * Furthermore, associative operators are grouped to the left. * createChoice( (P|Q), (R|S) ) will be ((P|Q)|R)|S. * *

      * Although this unification is essential, this is also the performance * bottle neck. In particular, createChoice and createSequence are two most * commonly called methods. * *

      * For example, when validating a DocBook XML (150KB) twice against * DocBook.trex(237KB), createChoice is called 63000 times and createSequence * called 23000 times. (the third is the createOptional method and only 1560 times.) * And they took more than 10% of validation time, which is the worst * time-consuming method. * *

      * Therefore, please beware that this class includes several ugly code optimization. * * @author Kohsuke KAWAGUCHI */ public class ExpressionPool implements java.io.Serializable { public final Expression createAttribute( NameClass nameClass ) { return unify(new AttributeExp(nameClass,Expression.anyString)); } public final Expression createAttribute( NameClass nameClass, Expression content ) { if(content==Expression.nullSet) return content; return unify(new AttributeExp(nameClass,content)); } public final Expression createEpsilon() { return Expression.epsilon; } public final Expression createNullSet() { return Expression.nullSet; } public final Expression createAnyString() { return Expression.anyString; } public final Expression createChoice( Expression left, Expression right ) { if( left==Expression.nullSet ) return right; if( right==Expression.nullSet ) return left; if( left==Expression.epsilon && right.isEpsilonReducible() ) return right; if( right==Expression.epsilon && left.isEpsilonReducible() ) return left; // TODO: should we re-order choice in a consistent manner? // associative operators are grouped to the left if( right instanceof ChoiceExp ) { final ChoiceExp c = (ChoiceExp)right; return createChoice( createChoice(left,c.exp1), c.exp2 ); } // eliminate duplicate choice items by checking that the right // is already included in the left. Expression next = left; while( true ) { if( next==right ) return left; // left is already in the choice if(!(next instanceof ChoiceExp)) break; ChoiceExp cp = (ChoiceExp)next; if( cp.exp2==right ) return left; next = cp.exp1; } // special (optimized) unification. // this will prevent unnecessary ChoiceExp instanciation. Expression o = expTable.getBinExp( left, right, ChoiceExp.class ); if(o==null) // different thread may possibly be doing the same thing at the same time. // so we have to call unify method, too synchronize update. return unify( new ChoiceExp(left,right) ); else return o; } public final Expression createOneOrMore( Expression child ) { if( child == Expression.epsilon || child == Expression.anyString || child == Expression.nullSet || child instanceof OneOrMoreExp ) return child; return unify(new OneOrMoreExp(child)); } public final Expression createZeroOrMore( Expression child ) { return createOptional(createOneOrMore(child)); } public final Expression createOptional( Expression child ) { // optimization will be done in createChoice method. return createChoice(child,Expression.epsilon); } public final Expression createData( XSDatatype dt ) { String ns = dt.getNamespaceUri(); if(ns==null) ns="\u0000"; // use something that doesn't collide with others. return createData( dt, new StringPair(ns,dt.displayName()) ); } public final Expression createData( Datatype dt, StringPair typeName ) { return createData( dt, typeName, Expression.nullSet ); } public final Expression createData( Datatype dt, StringPair typeName, Expression except ) { return unify( new DataExp(dt,typeName,except) ); } public final Expression createValue( XSDatatype dt, Object value ) { return createValue( dt, new StringPair("",dt.displayName()), value ); } public final Expression createValue( Datatype dt, StringPair typeName, Object value ) { return unify( new ValueExp(dt,typeName,value) ); } public final Expression createList( Expression exp ) { if(exp==Expression.nullSet) return exp; return unify( new ListExp(exp) ); } public final Expression createMixed( Expression body ) { if( body==Expression.nullSet ) return Expression.nullSet; if( body==Expression.epsilon ) return Expression.anyString; return unify( new MixedExp(body) ); } public final Expression createSequence( Expression left, Expression right ) { if( left ==Expression.nullSet || right==Expression.nullSet ) return Expression.nullSet; if( left ==Expression.epsilon ) return right; if( right==Expression.epsilon ) return left; // associative operators are grouped to the left if( right instanceof SequenceExp ) { final SequenceExp s = (SequenceExp)right; return createSequence( createSequence(left,s.exp1), s.exp2 ); } // special (optimized) unification. Expression o = expTable.getBinExp( left, right, SequenceExp.class ); if(o==null) return unify( new SequenceExp(left,right) ); else return o; } public final Expression createConcur( Expression left, Expression right ) { if( left==Expression.nullSet || right==Expression.nullSet ) return Expression.nullSet; if( left==Expression.epsilon ) { if( right.isEpsilonReducible() ) return Expression.epsilon; else return Expression.nullSet; } if( right==Expression.epsilon ) { if( left.isEpsilonReducible() ) return Expression.epsilon; else return Expression.nullSet; } // associative operators are grouped to the left if( right instanceof ConcurExp ) { final ConcurExp c = (ConcurExp)right; return createConcur( createConcur(left, c.exp1), c.exp2 ); } return unify(new ConcurExp(left,right)); } public final Expression createInterleave( Expression left, Expression right ) { if( left == Expression.epsilon ) return right; if( right== Expression.epsilon ) return left; if( left == Expression.nullSet || right== Expression.nullSet ) return Expression.nullSet; // associative operators are grouped to the left if( right instanceof InterleaveExp ) { final InterleaveExp i = (InterleaveExp)right; return createInterleave( createInterleave(left, i.exp1), i.exp2 ); } return unify(new InterleaveExp(left,right)); } /** hash table that contains all expressions currently known to this table. */ private final ClosedHash expTable; /** * creates new expression pool as a child pool of the given parent pool. * *

      * Every expression memorized in the parent pool can be retrieved, but update * operations are only performed upon the child pool. * In this way, the parent pool can be shared among the multiple threads without * interfering performance. * *

      * Furthermore, you can throw away a child pool after a certain time period to * prevent it from eating up memory. */ public ExpressionPool( ExpressionPool parent ) { expTable = new ClosedHash(parent.expTable); } public ExpressionPool() { expTable = new ClosedHash(); } /** * unifies expressions. * * If the equivalent expression is already registered in the table, * destroy newly created one (so that no two objects represents * same expression structure). * * If it's not registered, then register it and return it. */ protected final Expression unify( Expression exp ) { // call of get method need not be synchronized. // the implementation guarantee that simulatenous calls to get & put // will work correctly. Object o = expTable.get(exp); if(o==null) { // expression may not be registered. So try it again with lock synchronized(expTable) { o = expTable.get(exp); if(o==null) { // this check prevents two same expressions to be added simultaneously. // expression is not registered. expTable.put( exp ); return exp; } } } // expression is already registered. return (Expression)o; } /** * expression cache by closed hash. * * Special care has to be taken wrt threading. * This implementation allows get and put method to be called simulatenously. */ public final static class ClosedHash implements java.io.Serializable { /** The hash table data. */ private Expression table[]; /** The total number of mappings in the hash table. */ private int count; /** * The table is rehashed when its size exceeds this threshold. (The * value of this field is (int)(capacity * loadFactor).) */ private int threshold; /** The load factor for the hashtable. */ private static final float loadFactor = 0.3f; private static final int initialCapacity = 191; /** * The parent hash table. * can be null. items in the parent hash table will be returned by * get method. * *

      * The field is essentially final but because of the serialization * support we cannot mark it as such. */ private ClosedHash parent; public ClosedHash() { this(null); } public ClosedHash(ClosedHash parent) { table = new Expression[initialCapacity]; threshold = (int) (initialCapacity * loadFactor); this.parent = parent; } public Expression getBinExp(Expression left, Expression right, Class type) { int hash = (left.hashCode()+right.hashCode())^type.hashCode(); return getBinExp( hash, left, right, type ); } private Expression getBinExp(int hash, Expression left, Expression right, Class type) { if (parent != null) { Expression e = parent.getBinExp(hash, left, right, type); if (e != null) return e; } Expression tab[] = table; int index = (hash & 0x7FFFFFFF) % tab.length; while (true) { final Expression e = tab[index]; if (e == null) return null; if (e.hashCode() == hash && e.getClass() == type) { BinaryExp be = (BinaryExp)e; if (be.exp1 == left && be.exp2 == right) return be; } index = (index + 1) % tab.length; } } public Expression get(int hash, Expression child, Class type) { if (parent != null) { Expression e = parent.get(hash, child, type); if (e != null) return e; } Expression tab[] = table; int index = (hash & 0x7FFFFFFF) % tab.length; while (true) { final Expression e = tab[index]; if (e == null) return null; if (e.hashCode() == hash && e.getClass() == type) { UnaryExp ue = (UnaryExp)e; if (ue.exp == child) return ue; } index = (index + 1) % tab.length; } } public Expression get(Expression key) { if (parent != null) { Expression e = parent.get(key); if (e != null) return e; } Expression tab[] = table; int index = (key.hashCode() & 0x7FFFFFFF) % tab.length; while (true) { final Expression e = tab[index]; if (e == null) return null; if (e.equals(key)) return e; index = (index + 1) % tab.length; } } /** * rehash. * * It is possible for one thread to call get method * while another thread is performing rehash. * Keep this in mind. */ private void rehash() { // create a new table first. // meanwhile, other threads can safely access get method. int oldCapacity = table.length; Expression oldMap[] = table; int newCapacity = oldCapacity * 2 + 1; Expression newMap[] = new Expression[newCapacity]; for (int i = oldCapacity; i-- > 0;) if (oldMap[i] != null) { int index = (oldMap[i].hashCode() & 0x7FFFFFFF) % newMap.length; while (newMap[index] != null) index = (index + 1) % newMap.length; newMap[index] = oldMap[i]; } // threshold is not accessed by get method. threshold = (int) (newCapacity * loadFactor); // switch! table = newMap; } /** * put method. No two threads can call this method simulatenously, * and it's the caller's responsibility to enforce it. */ public void put(Expression newExp) { if (count >= threshold) rehash(); Expression tab[] = table; int index = (newExp.hashCode() & 0x7FFFFFFF) % tab.length; while (tab[index] != null) index = (index + 1) % tab.length; tab[index] = newExp; count++; } // serialization support private static final long serialVersionUID = -2924295970572669668L; private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField("count", Integer.TYPE), new ObjectStreamField("streamVersion", Byte.TYPE), new ObjectStreamField("parent", ExpressionPool.class) }; private void writeObject(ObjectOutputStream s) throws IOException { ObjectOutputStream.PutField fields = s.putFields(); fields.put("count",count); fields.put("parent",parent); fields.put("streamVersion",(byte)1); s.writeFields(); for( int i=0; iKohsuke KAWAGUCHI */ public interface DataOrValueExp { StringPair getName(); Datatype getType(); } msv-2009.1/msv/src/com/sun/msv/grammar/ValueExp.java0000644000175000017500000000502507766432346022451 0ustar giovannigiovanni/* * @(#)$Id: ValueExp.java 1620 2003-12-12 21:36:38Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; import org.relaxng.datatype.Datatype; import com.sun.msv.util.StringPair; /** * Expression that matchs a particular value of a {@link Datatype}. * * @author Kohsuke KAWAGUCHI */ public final class ValueExp extends Expression implements DataOrValueExp { /** Datatype object that is used to test the equality. */ public final Datatype dt; public Datatype getType() { return dt; } /** This expression matches this value only. */ public final Object value; /** * name of this datatype. * * The value of this field is not considered as significant. * When two TypedStringExps share the same Datatype object, * then they are unified even if they have different names. */ public final StringPair name; public StringPair getName() { return name; } protected ValueExp( Datatype dt, StringPair typeName, Object value ) { super(dt.hashCode()+dt.valueHashCode(value)); this.dt=dt; this.name = typeName; this.value = value; } protected final int calcHashCode() { return dt.hashCode()+dt.valueHashCode(value); } public boolean equals( Object o ) { // Note that equals method of this class *can* be sloppy, // since this class does not have a pattern as its child. // Therefore datatype vocaburary does not necessarily provide // strict equals method. if(o.getClass()!=this.getClass()) return false; ValueExp rhs = (ValueExp)o; if(!rhs.dt.equals(dt)) return false; return dt.sameValue(value,rhs.value); } public Object visit( ExpressionVisitor visitor ) { return visitor.onValue(this); } public Expression visit( ExpressionVisitorExpression visitor ) { return visitor.onValue(this); } public boolean visit( ExpressionVisitorBoolean visitor ) { return visitor.onValue(this); } public void visit( ExpressionVisitorVoid visitor ) { visitor.onValue(this); } protected boolean calcEpsilonReducibility() { return false; } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/ListExp.java0000644000175000017500000000223507766432346022310 0ustar giovannigiovanni/* * @(#)$Id: ListExp.java 1620 2003-12-12 21:36:38Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; /** * <list> of RELAX NG. * * This primitive is not used by RELAX Core,TREX,DTD, and W3C XML Schema. * * @author Kohsuke KAWAGUCHI */ public final class ListExp extends UnaryExp { ListExp( Expression exp ) { super(exp); } public Object visit( ExpressionVisitor visitor ) { return visitor.onList(this); } public Expression visit( ExpressionVisitorExpression visitor ) { return visitor.onList(this); } public boolean visit( ExpressionVisitorBoolean visitor ) { return visitor.onList(this); } public void visit( ExpressionVisitorVoid visitor ) { visitor.onList(this); } protected boolean calcEpsilonReducibility() { return exp.isEpsilonReducible(); } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/MixedExp.java0000644000175000017500000000260207766432346022441 0ustar giovannigiovanni/* * @(#)$Id: MixedExp.java 1620 2003-12-12 21:36:38Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; /** * <mixed> of RELAX. * * For TREX, this operator is not an essential one. You can use *

      * <interleave> * <anyString /> * ... * </interleave> * * * However, by introducing "mixed" as a primitive, * RELAX module can be expressed without using interleave. * * Also, mixed makes validation faster. * * @author Kohsuke KAWAGUCHI */ public final class MixedExp extends UnaryExp { MixedExp(Expression exp) { super(exp); } public Object visit(ExpressionVisitor visitor) { return visitor.onMixed(this); } public Expression visit(ExpressionVisitorExpression visitor) { return visitor.onMixed(this); } public boolean visit(ExpressionVisitorBoolean visitor) { return visitor.onMixed(this); } public void visit(ExpressionVisitorVoid visitor) { visitor.onMixed(this); } protected boolean calcEpsilonReducibility() { return exp.isEpsilonReducible(); } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/AnyNameClass.java0000644000175000017500000000217407730143103023215 0ustar giovannigiovanni/* * @(#)$Id: AnyNameClass.java 1601 2003-09-11 19:00:19Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; /** * a NameClass that matches any name. * * @author Kohsuke KAWAGUCHI */ public final class AnyNameClass extends NameClass { /** AnyNameClass accpets any name, as its name suggests. */ public boolean accepts( String namespaceURI, String localName ) { return true; } public Object visit( NameClassVisitor visitor ) { return visitor.onAnyName(this); } /** * Singleton instance. * * @deprecated Use {@link NameClass#ALL} instead. */ public static final NameClass theInstance = new AnyNameClass(); protected AnyNameClass() {} public String toString() { return "*:*"; } // serialization support private static final long serialVersionUID = 1; private Object readResolve() { return theInstance; } } msv-2009.1/msv/src/com/sun/msv/grammar/OneOrMoreExp.java0000644000175000017500000000212607766432346023241 0ustar giovannigiovanni/* * @(#)$Id: OneOrMoreExp.java 1620 2003-12-12 21:36:38Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; /** * A+. * * @author Kohsuke KAWAGUCHI */ public final class OneOrMoreExp extends UnaryExp { OneOrMoreExp( Expression exp ) { super(exp); } public Object visit( ExpressionVisitor visitor ) { return visitor.onOneOrMore(this); } public Expression visit( ExpressionVisitorExpression visitor ) { return visitor.onOneOrMore(this); } public boolean visit( ExpressionVisitorBoolean visitor ) { return visitor.onOneOrMore(this); } public void visit( ExpressionVisitorVoid visitor ) { visitor.onOneOrMore(this); } protected boolean calcEpsilonReducibility() { return exp.isEpsilonReducible(); } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/xmlschema/0000755000175000017500000000000011622453066022020 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/grammar/xmlschema/LaxDefaultNameClass.java0000644000175000017500000000726110034315204026474 0ustar giovannigiovanni/* * @(#)$Id: LaxDefaultNameClass.java 1634 2004-04-05 17:42:28Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.xmlschema; import java.util.Set; import com.sun.msv.grammar.DifferenceNameClass; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.NameClassVisitor; import com.sun.msv.grammar.SimpleNameClass; import com.sun.msv.util.StringPair; /** * Special name class implementation used for the wild card of the "lax" mode. * *

      * In "lax" mode, we need a name class that matches all undefined names. * Although it is possible to use DifferenceNameClass for this purpose, * it is not a cost-efficient way because typically it becomes very large. * (If there are twenty element declarations, we'll need twenty DifferenceNameClass * to exclude all defined names). * *

      * This name class uses a {@link Set} to hold multiple names. If a name * is contained in that set, it'll be rejected. If a name is not contained, * it'll be accepted. * *

      * Special care is taken to make this NC as seamless as possible. * When the visit method is called, the equivalent name class is constructed * internally and the visitor will visit that name class. In this way, the visitors * won't notice the existance of this "special" name class. * * @author Kohsuke KAWAGUCHI */ public class LaxDefaultNameClass extends NameClass { /** * @param _base * this name class accepts a name if *

        *
      1. it's in the 'base" name class and *
      2. it's not one of those excluded names */ public LaxDefaultNameClass( NameClass _base ) { this.base = _base; names.add( new StringPair(NAMESPACE_WILDCARD,LOCALNAME_WILDCARD) ); } private NameClass base; public Object visit( NameClassVisitor visitor ) { // create equivalent name class and let visitor visit it. if( equivalentNameClass==null ) { NameClass nc = base; StringPair[] items = (StringPair[])names.toArray(new StringPair[0]); for( int i=0; iKohsuke KAWAGUCHI */ public interface AttWildcardExp { /** * Gets the attribute wildcard property of this schema component. * * @return * If the value is absent, null is returned. */ AttributeWildcard getAttributeWildcard(); } msv-2009.1/msv/src/com/sun/msv/grammar/xmlschema/KeyRefConstraint.java0000644000175000017500000000154407671170035026122 0ustar giovannigiovanni/* * @(#)$Id: KeyRefConstraint.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.xmlschema; /** * keyref constraint. * * @author Kohsuke KAWAGUCHI */ public class KeyRefConstraint extends IdentityConstraint { public KeyRefConstraint( String namespaceURI, String localName, XPath[] selector, Field[] fields ) { super(namespaceURI,localName,selector,fields); } /** * corresponding key constraint. * this field is intentionally non-final. */ public KeyConstraint key; // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/xmlschema/XPath.java0000644000175000017500000000210007671170035023701 0ustar giovannigiovanni/* * @(#)$Id: XPath.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.xmlschema; import com.sun.msv.grammar.NameClass; /** * internal representation of XPath ('aaa/bbb/ccc/ ... /eee'). * Note that 'A|B' is repsented by using two Path instances. * * @author Kohsuke KAWAGUCHI */ public class XPath implements java.io.Serializable { /** * this field is true if the XPath starts with '//' operator. */ public boolean isAnyDescendant; /** * each name class represents each step. */ public NameClass[] steps; /** * optional attribute step that can only appear as the last child. * Null if not present. */ public NameClass attributeStep; // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/xmlschema/ElementDeclExp.java0000644000175000017500000002427210034315204025513 0ustar giovannigiovanni/* * @(#)$Id: ElementDeclExp.java 1634 2004-04-05 17:42:28Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.xmlschema; import java.util.Vector; import com.sun.msv.grammar.ChoiceExp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.SimpleNameClass; import com.sun.msv.grammar.util.ExpressionWalker; /** * Element declaration. * *

        * the inherited exp field holds an expression that * also matches to substituted element declarations. * *

        * The body field contains an expression that matches * only to this element declaration without no substituted element decls. * * *

        Element Declaration Schema Component Properties

        *

        * This table shows the mapping between * * "element declaration schema component properties" * (which is defined in the spec) and corresponding method/field of this class. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
        Property of the specmethod/field of this class
        * name * * The {@link #name} field. *
        * target namespace * * the {@link #getTargetNamespace()} method. *
        * type definition * * {@link #getTypeDefinition()} method. *
        * scope * * To be implemented *
        * value constraint * * To be implemented. Accessible through the {@link #body} field. *
        * nillable * * the {@link #isNillable} field. *
        * identity constraints * * The identityConstraints field of the {@link XSElementExp}, * which in turn can be obtained throught the {@link #body} field. *
        * substitution group affiliation * * The {@link #substitutionAffiliation} field. *
        * substitution group exclusion * * The {@link #finalValue} field. *
        * disallowed substitution * * The {@link #block} field. *
        * abstract * * the {@link #isAbstract()} method. *
        * annotation * * Unaccessible. This information is removed during the parsing phase. *
        * * * *

        Abstractness

        * *

        * The exp field and the self field are very similar. * In fact, the only difference is that the former is affected by the abstract * property, while the latter isn't. * *

        * So if it has to be affected by the * abstract property (like referencing a complex type as the element body), * you should use the exp field. * If you don't want to be affected by the abstract property * (like referencing a complex type as the base type of another complex type), * then you should refer to the body field. * * * @author Kohsuke KAWAGUCHI */ public class ElementDeclExp extends ReferenceExp { public ElementDeclExp( XMLSchemaSchema schema, String typeLocalName ) { super(typeLocalName); this.parent = schema; this.substitutions = new ReferenceExp( typeLocalName+":substitutions" ); this.substitutions.exp = Expression.nullSet; } /** * * The substitution group affiliation property * of this component, if any. * Otherwise null. */ public ElementDeclExp substitutionAffiliation; /** * The expression that represents the "body" of this expression. * Usually, this refers to XSElementExp, but not necessarily. */ public final ReferenceExp body = new ReferenceExp(null); private XSElementExp element; public void setElementExp( XSElementExp exp ) { this.element = exp; body.exp = exp; } public XSElementExp getElementExp() { return element; } /** * choices of all elements that can validly substitute this element. */ public final ReferenceExp substitutions; /** * gets the pattern that represents the content model of * this element declaration. * * This method is just a short cut for self.contentModel. */ public Expression getContentModel() { return element.contentModel; } /** parent XMLSchemaSchema object to which this object belongs. */ public final XMLSchemaSchema parent; /** * XML Schema version of {@link ElementExp}. * * @author Kohsuke KAWAGUCHI */ public class XSElementExp extends ElementExp { public final SimpleNameClass elementName; public final NameClass getNameClass() { return elementName; } public XSElementExp( SimpleNameClass elementName, Expression contentModel ) { super(contentModel,false); this.elementName = elementName; parent = ElementDeclExp.this; } /** * identity constraints associated to this declaration. * When no constraint exists, this field may be null (or empty vector). * Items are of derived types of {@link IdentityConstraint} class. * *

        * These identity constraints are not enforced by the default Verifier * implementation. */ public final Vector identityConstraints = new Vector(); public final ElementDeclExp parent; } // // Schema component properties //====================================== // /** * gets the nillable property of this component as * * specified in the spec. */ public boolean isNillable; /** * gets the scope property of this component as * * specified in the spec. * * @return * true if this component is global. * false if this component is local. */ public boolean isGlobal() { return parent.elementDecls.get(name)==this; } /** * gets the target namespace property of this component as * * specified in the spec. * *

        * If the property is * absent, then this method returns the empty string. * *

        * This method is just a shortcut for parent.targetNamespace. */ public final String getTargetNamespace() { return parent.targetNamespace; } /** * checks if this element declaration is abstract. * * @return * true if this method is abstract. */ public boolean isAbstract() { if( exp instanceof ChoiceExp ) { ChoiceExp cexp = (ChoiceExp)exp; if(cexp.exp1!=body && cexp.exp2!=body) throw new Error(); // assertion failed return true; } if(exp!=substitutions) throw new Error(); // assertion failed return false; } public void setAbstract( boolean isAbstract ) { if(isAbstract) exp = substitutions; else exp = parent.pool.createChoice( substitutions, body ); } public static final int RESTRICTION = 0x1; public static final int EXTENSION = 0x2; public static final int SUBSTITUTION = 0x4; public static final int ALL = 0x7; /** * The * substitution group exclusions property of this schema component, * implemented as a bit field. * *

        * a bit-wise OR of RESTRICTION and EXTENSION. */ public int finalValue =0; /** * The * disallowed substitution property of this schema component, * implemented as a bit field. * *

        * a bit-wise OR of RESTRICTION, EXTENSION, and SUBSTITUTION. */ public int block =0; public boolean isSubstitutionBlocked() { return (block&SUBSTITUTION)!=0; } public boolean isRestrictionBlocked() { return (block&RESTRICTION)!=0; } /** * gets the * type definition property of this schema component. */ public XMLSchemaTypeExp getTypeDefinition() { final RuntimeException eureka = new RuntimeException(); final XMLSchemaTypeExp[] result = new XMLSchemaTypeExp[1]; try { getContentModel().visit( new ExpressionWalker(){ public void onElement( ElementExp exp ) {} public void onRef( ReferenceExp exp ) { if(exp instanceof XMLSchemaTypeExp) { result[0] = (XMLSchemaTypeExp)exp; throw eureka; } super.onRef(exp); } }); // assertion failed. It couldn't be found. throw new Error(); } catch( RuntimeException e ) { if(e==eureka) return result[0]; throw e; } } // // Implementation details //========================================= public boolean isDefined() { return super.isDefined() && element!=null; } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/xmlschema/SimpleTypeExp.java0000644000175000017500000000457707671170035025451 0ustar giovannigiovanni/* * @(#)$Id: SimpleTypeExp.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.xmlschema; import com.sun.msv.datatype.xsd.XSDatatype; import com.sun.msv.reader.datatype.xsd.XSDatatypeExp; /** * Simple type declaration. * *

        * Most of the properties of the simple type declaration component * is defined in the {@link XSDatatype} object, which is obtained by the * {@link #getType()} method. * *

        * Note: XML Schema allows forward reference to simple types. * Therefore it must be indirectionalized by ReferenceExp. * And this is the only reason this class exists. * * @author Kohsuke KAWAGUCHI */ public class SimpleTypeExp extends XMLSchemaTypeExp { SimpleTypeExp( String typeName ) { super(typeName); } public void set( XSDatatypeExp exp ) { this.exp = this.type = exp; } protected XSDatatypeExp type; /** gets the XSDatatypeExp object that represents this simple type. */ public XSDatatypeExp getType() { return type; } /** * Gets the encapsulated Datatype object. *

        * This method can be called only after the parsing is finished. */ public XSDatatype getDatatype() { return type.getCreatedType(); } /** * gets the value of the block constraint. * SimpleTypeExp always returns 0 because it doesn't * have the block constraint. */ public int getBlock() { return 0; } /** clone this object. */ public RedefinableExp getClone() { SimpleTypeExp exp = new SimpleTypeExp(this.name); exp.redefine(this); return exp; } public void redefine( RedefinableExp _rhs ) { super.redefine(_rhs); SimpleTypeExp rhs = (SimpleTypeExp)_rhs; if(type==null) type = rhs.getType().getClone(); else { // because redefinition only happens by a defined declaration if(rhs.getType()==null) throw new InternalError(); type.redefine(rhs.getType()); } } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/xmlschema/package.html0000644000175000017500000000017207331671737024312 0ustar giovannigiovanni W3C XML Schema grammar model.

        These classes serve as the object model of W3C XML Schema. msv-2009.1/msv/src/com/sun/msv/grammar/xmlschema/XMLSchemaGrammar.java0000644000175000017500000000354107671170035025757 0ustar giovannigiovanni/* * @(#)$Id: XMLSchemaGrammar.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.xmlschema; import java.util.Iterator; import java.util.Map; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.Grammar; /** * set of XML Schema. This set can be used to validate a document. * * @author Kohsuke KAWAGUCHI */ public class XMLSchemaGrammar implements Grammar { public XMLSchemaGrammar() { this( new ExpressionPool() ); } public XMLSchemaGrammar( ExpressionPool pool ) { this.pool = pool; } /** pool object which was used to construct this grammar. */ protected final ExpressionPool pool; public final ExpressionPool getPool() { return pool; } public Expression topLevel; public final Expression getTopLevel() { return topLevel; } /** map from namespace URI to loaded XMLSchemaSchema object. */ protected final Map schemata = new java.util.HashMap(); /** gets XMLSchemaSchema object that has the given target namespace. * * @return null if no schema is associated with that namespace. */ public XMLSchemaSchema getByNamespace( String targetNamesapce ) { return (XMLSchemaSchema)schemata.get(targetNamesapce); } /** * returns an Iterator that enumerates XMLSchemaSchema objects * that are defined in this grammar. */ public Iterator iterateSchemas() { return schemata.values().iterator(); } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/xmlschema/GroupDeclExp.java0000644000175000017500000000151007671170035025222 0ustar giovannigiovanni/* * @(#)$Id: GroupDeclExp.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.xmlschema; /** * model group declaration. * * @author Kohsuke KAWAGUCHI */ public class GroupDeclExp extends RedefinableExp { public GroupDeclExp( String typeLocalName ) { super(typeLocalName); } /** clone this object. */ public RedefinableExp getClone() { RedefinableExp exp = new GroupDeclExp(super.name); exp.redefine(this); return exp; } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/xmlschema/KeyConstraint.java0000644000175000017500000000132207671170035025457 0ustar giovannigiovanni/* * @(#)$Id: KeyConstraint.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.xmlschema; /** * key constraint. * * @author Kohsuke KAWAGUCHI */ public class KeyConstraint extends IdentityConstraint { public KeyConstraint( String namespaceURI, String localName, XPath[] selector, Field[] fields ) { super(namespaceURI,localName,selector,fields); } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/xmlschema/AttributeGroupExp.java0000644000175000017500000000453707671170035026332 0ustar giovannigiovanni/* * @(#)$Id: AttributeGroupExp.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.xmlschema; /** * attribute group declaration. * * the inherited exp field contains the attributes defined in this declaration. * * @author Kohsuke KAWAGUCHI */ public class AttributeGroupExp extends RedefinableExp implements AttWildcardExp { /** * Attribute wild card constraint. * *

        * Due to the nasty definition of the interaction between attribute wildcards, * we cannot add the expression for validating wildcard until the very last moment. * *

        * In any way, AttribtueGroupExp will NOT contain the expression * corresponding to the wildcard. Only ComplexTypeExp will get * that expression. * *

        * Until the wrap-up phase of the schema parsing, this field will contain * the "local wildcard definition." In the wrap-up phase, this field is replaced * by the "complete wildcard definition." */ public AttributeWildcard wildcard; public AttributeWildcard getAttributeWildcard() { return wildcard; } public void setAttributeWildcard( AttributeWildcard local ) { wildcard=local; } /** * name of this attribute group declaration. * According to the spec, the name must be unique within one schema * (in our object model, one XMLSchemaSchema object). */ public AttributeGroupExp( String typeLocalName ) { super(typeLocalName); } /** clone this object. */ public RedefinableExp getClone() { RedefinableExp exp = new AttributeGroupExp(super.name); exp.redefine(this); return exp; } // this class does not have its own member, so no need to override this method. public void redefine( RedefinableExp _rhs ) { super.redefine(_rhs); AttributeGroupExp rhs = (AttributeGroupExp)_rhs; if(rhs.wildcard==null) wildcard = null; else wildcard = rhs.wildcard.copy(); } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/xmlschema/XMLSchemaSchema.java0000644000175000017500000001270607671170035025574 0ustar giovannigiovanni/* * @(#)$Id: XMLSchemaSchema.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.xmlschema; import java.util.Map; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.ReferenceContainer; import com.sun.msv.grammar.ReferenceExp; /** * XML Schema object. * *

        * A set of "schema components" that share the same target namespace. * It contains all global declarations. * * @author Kohsuke KAWAGUCHI */ public class XMLSchemaSchema implements java.io.Serializable { public static final String XMLSchemaInstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance"; public XMLSchemaSchema( String targetNamespace, XMLSchemaGrammar parent ) { this.pool = parent.pool; this.targetNamespace = targetNamespace; parent.schemata.put( targetNamespace, this ); } /** target namespace URI of this schema. */ public final String targetNamespace; /** pool object which was used to construct this grammar. */ public final ExpressionPool pool; /** choice of all global element declarations. */ public Expression topLevel; final public class SimpleTypeContainer extends ReferenceContainer { public SimpleTypeExp getOrCreate( String name ) { return (SimpleTypeExp)super._getOrCreate(name); } public SimpleTypeExp get( String name ) { return (SimpleTypeExp)super._get(name); } protected ReferenceExp createReference( String name ) { return new SimpleTypeExp(name); } } /** map from simple type name to SimpleTypeExp object */ public final SimpleTypeContainer simpleTypes = new SimpleTypeContainer(); final public class ComplexTypeContainer extends ReferenceContainer { public ComplexTypeExp getOrCreate( String name ) { return (ComplexTypeExp)super._getOrCreate(name); } public ComplexTypeExp get( String name ) { return (ComplexTypeExp)super._get(name); } protected ReferenceExp createReference( String name ) { return new ComplexTypeExp(XMLSchemaSchema.this,name); } } /** map from simple type name to SimpleTypeExp object */ public final ComplexTypeContainer complexTypes = new ComplexTypeContainer(); final public class AttributeGroupContainer extends ReferenceContainer { public AttributeGroupExp getOrCreate( String name ) { return (AttributeGroupExp)super._getOrCreate(name); } public AttributeGroupExp get( String name ) { return (AttributeGroupExp)super._get(name); } protected ReferenceExp createReference( String name ) { return new AttributeGroupExp(name); } } /** map from attribute group name to AttributeGroupExp object */ public final AttributeGroupContainer attributeGroups = new AttributeGroupContainer(); final public class AttributeDeclContainer extends ReferenceContainer { public AttributeDeclExp getOrCreate( String name ) { return (AttributeDeclExp)super._getOrCreate(name); } public AttributeDeclExp get( String name ) { return (AttributeDeclExp)super._get(name); } protected ReferenceExp createReference( String name ) { return new AttributeDeclExp(name); } } /** map from attribute declaration name to AttributeDeclExp object */ public final AttributeDeclContainer attributeDecls = new AttributeDeclContainer(); final public class ElementDeclContainer extends ReferenceContainer { public ElementDeclExp getOrCreate( String name ) { return (ElementDeclExp)super._getOrCreate(name); } public ElementDeclExp get( String name ) { return (ElementDeclExp)super._get(name); } protected ReferenceExp createReference( String name ) { return new ElementDeclExp(XMLSchemaSchema.this,name); } } /** map from attribute declaration name to AttributeDeclExp object */ public final ElementDeclContainer elementDecls = new ElementDeclContainer(); final public class GroupDeclContainer extends ReferenceContainer { public GroupDeclExp getOrCreate( String name ) { return (GroupDeclExp)super._getOrCreate(name); } public GroupDeclExp get( String name ) { return (GroupDeclExp)super._get(name); } protected ReferenceExp createReference( String name ) { return new GroupDeclExp(name); } } /** map from attribute declaration name to AttributeDeclExp object */ public final GroupDeclContainer groupDecls = new GroupDeclContainer(); final public class IdentityConstraintContainer implements java.io.Serializable { private final Map storage = new java.util.HashMap(); public IdentityConstraint get( String name ) { return (IdentityConstraint)storage.get(name); } public void add( String name, IdentityConstraint idc ) { storage.put(name,idc); } } /** map from identity constraint name to IdentityConstraint object. */ public final IdentityConstraintContainer identityConstraints = new IdentityConstraintContainer(); // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/xmlschema/UniqueConstraint.java0000644000175000017500000000133607671170035026202 0ustar giovannigiovanni/* * @(#)$Id: UniqueConstraint.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.xmlschema; /** * unique constraint. * * @author Kohsuke KAWAGUCHI */ public class UniqueConstraint extends IdentityConstraint { public UniqueConstraint( String namespaceURI, String localName, XPath[] selector, Field[] fields ) { super(namespaceURI,localName,selector,fields); } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/xmlschema/XMLSchemaTypeExp.java0000644000175000017500000000207407671170035025767 0ustar giovannigiovanni/* * @(#)$Id: XMLSchemaTypeExp.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.xmlschema; /** * Base class of {@link ComplexTypeExp} and {@link SimpleTypeExp}. * * This class represents "type" of W3C XML Schema. * * @author Kohsuke KAWAGUCHI */ public abstract class XMLSchemaTypeExp extends RedefinableExp { XMLSchemaTypeExp( String typeLocalName ) { super(typeLocalName); } /** * gets the value of the block constraint. */ public abstract int getBlock(); // actual values for these constants must keep in line with those values // defined in the ElementDeclExp. public static final int RESTRICTION = 0x1; public static final int EXTENSION = 0x2; // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/xmlschema/ComplexTypeExp.java0000644000175000017500000003062710034315204025604 0ustar giovannigiovanni/* * @(#)$Id: ComplexTypeExp.java 1634 2004-04-05 17:42:28Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.xmlschema; import com.sun.msv.datatype.xsd.XSDatatype; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.reader.datatype.xsd.XSDatatypeExp; /** * ComplexType definition. * * ComplexTypeExp holds an expression (as a ReferenceExp) that matches to * this type itself. * *

        * the {@link #body} field contains the expression that exactly matches * to the declared content model (without any substitutable types). * *

        * the exp field contains the reference to the body field, * if this complex type is not abstract. If abstract, then nullSet is set. * You shouldn't directly manipulate the exp field. Instead, you should use * the {@link #setAbstract(boolean)} method to do it. * *

        * Note: The runtime type substitution * (the use of xsi:type attribute) * is implemented at the VGM layer. Therefore, AGMs of XML Schema does NOT * precisely represent what are actually allowed and what are not. * * *

        Complex Type Definition Schema Component Properties

        *

        * This table shows the mapping between * * "complex type definition schema component properties" * (which is defined in the spec) and corresponding method/field of this class. * * * * * * * * * * * * * * * * * * * * * * * * * *
        Property of the specmethod/field of this class
        * name * * The {@link #name} field. *
        * target namespace * * the {@link #getTargetNamespace()} method. *
        * abstract * * the {@link #isAbstract()} method. *
        * base type definition * * {@link #simpleBaseType} or {@link #complexBaseType} field, * depending on whether the base type is a simple type or a complex type. *
        * derivation method * * the {@link #derivationMethod} field. *
        * final * * the {@link #finalValue} field. *
        * prohibited substitutions * * the {@link #block} field. *
        * attribtue uses
        attribute wildcard
        content type *
        * Not directly accessible. Can be found by walking * the children of the {@link #body} field. *
        * annotation * * Unaccessible. This information is removed during the parsing phase. *
        * * * * * *

        Abstractness

        * *

        * The exp field and the self field are very similar. * In fact, the only difference is that the former is affected by the abstract * property, while the latter isn't. * *

        * So if it has to be affected by the * abstract property (like referencing a complex type as the element body), * you should use the exp field. * If you don't want to be affected by the abstract property * (like referencing a complex type as the base type of another complex type), * then you should refer to the body field. * * * * * @see ElementDeclExp * * @author Kohsuke KAWAGUCHI */ public class ComplexTypeExp extends XMLSchemaTypeExp { public ComplexTypeExp( XMLSchemaSchema schema, String localName ) { super(localName); this.parent = schema; setAbstract(false); } /** actual content model definition + attribute uses. */ public final ReferenceExp body = new ReferenceExp(null); /** attribute wildcard as an expression. */ public final ReferenceExp attWildcard = new ReferenceExp(null,Expression.epsilon); /** parent XMLSchemaSchema object to which this object belongs. */ public final XMLSchemaSchema parent; /** * Attribute wild card constraint. * *

        * Due to the nasty definition of the interaction between attribute wildcards, * we cannot add the expression for validating wildcard until the very last moment. * *

        * Until the wrap-up phase of the schema parsing, this field will contain * the "local wildcard definition." In the wrap-up phase, this field is replaced * by the "complete wildcard definition." */ public AttributeWildcard wildcard; public AttributeWildcard getAttributeWildcard() { return wildcard; } public void setAttributeWildcard( AttributeWildcard local ) { wildcard=local; } // // Schema component properties //====================================== // /** * gets the target namespace property of this component as * * specified in the spec. * *

        * If the property is * absent, then this method returns the empty string. * *

        * This method is just a shortcut for parent.targetNamespace. */ public final String getTargetNamespace() { return parent.targetNamespace; } /** * base type of this complex type. * * Either baseComplexType field or baseSimpleType field is set. * If the base type is * * ur-type, both fields are set to null. * * @see #simpleBaseType */ public ComplexTypeExp complexBaseType; /** * base type of this complex type. * * @see #complexBaseType */ public XSDatatypeExp simpleBaseType; /** * the derivation method used to derive this complex type from the base type. * Either RESTRICTION or EXTENSION. * * @see #complexBaseType * #simpleBaseType */ public int derivationMethod = -1; /** * checks if this complex type is abstract. * *

        * This method corresponds to the abstract property of * the complex type declaration schema component. * * @return * true if this method is abstract. Flase if not. */ public boolean isAbstract() { return exp==Expression.nullSet; } public void setAbstract( boolean isAbstract ) { if( isAbstract ) exp=Expression.nullSet; else exp=parent.pool.createSequence(body,attWildcard); } /** * Checks if this type is a derived type of the specified type. * *

        * This method is an implementation of * * "Type Derivation OK (Complex)" test * of the spec. * *

        * If you are not familiar with the abovementioned part of the spec, * don't use this method. This method probably won't give you * what you expected. * * @param constraint * A bit field that represents the restricted derivation. This field * must consists of bitwise and of {@link #EXTENSION} or {@link #RESTRICTION}. * * @return * true if the specified type is "validly derived" from this type. * false if not. */ public boolean isDerivedTypeOf( ComplexTypeExp baseType, int constraint ) { ComplexTypeExp derived = this; while( derived!=null ) { if( derived==baseType ) return true; if( (derived.derivationMethod&constraint)!=0 ) return false; // this type of derivation is prohibited. derived = derived.complexBaseType; } return false; } /** * @see #isDerivedTypeOf(ComplexTypeExp,int) */ public boolean isDerivedTypeOf( XSDatatype baseType, int constraint ) { ComplexTypeExp derived = this; while(true) { if( derived.complexBaseType==null ) { if( derived.simpleBaseType!=null ) return derived.simpleBaseType.getCreatedType().isDerivedTypeOf( baseType, (constraint&RESTRICTION)==0 ); else return false; } if( (derived.derivationMethod&constraint)!=0 ) return false; // this type of derivation is prohibited. derived = derived.complexBaseType; } } public boolean isDerivedTypeOf( XMLSchemaTypeExp exp, int constraint ) { if( exp instanceof ComplexTypeExp ) return isDerivedTypeOf( (ComplexTypeExp)exp, constraint ); else return isDerivedTypeOf( ((SimpleTypeExp)exp).getDatatype(), constraint ); } /** * The * final property of this schema component, implemented as a bit field. * *

        * 0, RESTRICTION, EXTENSION, or (RESTRICTION|EXTENSION). */ public int finalValue =0; /** * The * block property of this schema component, implemented as a bit field. * *

        * 0, RESTRICTION, EXTENSION, or (RESTRICTION|EXTENSION). */ public int block =0; /** * Gets the value of the block constraint. * SimpleTypeExp always returns 0 because it doesn't have the block constraint. */ public int getBlock() { return block; } // // Other implementation details //====================================== // /** clone this object. */ public RedefinableExp getClone() { ComplexTypeExp exp = new ComplexTypeExp(parent,super.name); exp.redefine(this); return exp; } public void redefine( RedefinableExp _rhs ) { super.redefine(_rhs); ComplexTypeExp rhs = (ComplexTypeExp)_rhs; body.exp = rhs.body.exp; attWildcard.exp = rhs.attWildcard.exp; complexBaseType = rhs.complexBaseType; simpleBaseType = rhs.simpleBaseType; derivationMethod = rhs.derivationMethod; finalValue = rhs.finalValue; block = rhs.block; if(rhs.wildcard==null) wildcard = null; else wildcard = rhs.wildcard.copy(); if( this.parent != rhs.parent ) // those two must share the parent. throw new IllegalArgumentException(); } // /** derives a QName type that only accepts this type name. */ /* private static XSDatatype getQNameType( final String namespaceURI, final String localName ) { try { TypeIncubator ti = new TypeIncubator( QnameType.theInstance ); ti.addFacet( "enumeration", "foo:"+localName, true, new ValidationContext() { public String resolveNamespacePrefix( String prefix ) { if( "foo".equals(prefix) ) return namespaceURI; return null; } public boolean isUnparsedEntity( String entityName ) { throw new Error(); // shall never be called. } public boolean isNotation( String notationName ) { throw new Error(); // shall never be called. } public String getBaseUri() { return null; } } ); return ti.derive(null); } catch( DatatypeException e ) { // assertion failed. this can't happen. throw new Error(); } } */ /** * implementation detail. * * A ComplexTypeDecl is properly defined if its self is defined. * Note that the default implementation of the isDefined method doesn't * work for this class because the exp field is set by the constructor. */ public boolean isDefined() { return body.isDefined(); } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/xmlschema/Field.java0000644000175000017500000000133707671170035023713 0ustar giovannigiovanni/* * @(#)$Id: Field.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.xmlschema; /** * represents one field of an identity constraint. * * @author Kohsuke KAWAGUCHI */ public class Field implements java.io.Serializable { /** * XPath that characterizes this field. * 'A|B' is represented by using two FieldPath objects. */ public XPath[] paths; // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/xmlschema/AttributeWildcard.java0000644000175000017500000000665107671170035026311 0ustar giovannigiovanni/* * @(#)$Id: AttributeWildcard.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.xmlschema; import java.util.Iterator; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.ReferenceExp; /** * Attribute wildcard property of the schema component. * *

        * This object is used during the parsing process to keep the intermediate information. * Once the parsing is finished, attribute wildcard is kept as an expression. * * @author Kohsuke KAWAGUCHI */ public class AttributeWildcard { public AttributeWildcard( NameClass name, int processMode ) { this.name = name; this.processMode = processMode; } private NameClass name; /** Gets the target of the name class. */ public NameClass getName() { return name; } private int processMode; /** Gets the processing model of the wildcard. */ public int getProcessMode() { return processMode; } public static final int SKIP = 0; public static final int LAX = 1; public static final int STRICT = 2; public AttributeWildcard copy() { return new AttributeWildcard(name,processMode); } /** * Creates the expression that corresponds to * the current attribute wildcard specification. */ public Expression createExpression( XMLSchemaGrammar grammar ) { final ExpressionPool pool = grammar.pool; switch(processMode) { case SKIP: return pool.createZeroOrMore(pool.createAttribute(name)); case STRICT: case LAX: Expression exp = Expression.epsilon; LaxDefaultNameClass laxNc = new LaxDefaultNameClass(name); Iterator itr = grammar.iterateSchemas(); while( itr.hasNext() ) { XMLSchemaSchema schema = (XMLSchemaSchema)itr.next(); // nc is built by using NamespaceNameClass. // "strict" allows global element declarations of // specified namespaces. if(name.accepts( schema.targetNamespace, NameClass.LOCALNAME_WILDCARD )) { // gather global attributes. ReferenceExp[] atts = schema.attributeDecls.getAll(); for( int i=0; i * This expression is just a marker, and the exp field * of this instance still contains the precise expression * of the occurrence constraint. * *

        * For example, if A is maxOccurs=5 and minOccurs=3, * then the exp field of this instance will be: * A,A,A,(A,A?)?, the maxOccurs field * will be 5, the minOccurs field will be 3, and * the itemExp field will hold a reference to A. * *

        * Note that MSV doesn't using this marker by itself. * It is intended to help other applications that use * the AGM of MSV. * *

        * Also note that this expression will not * be used in the following cases to avoid excessive allocation * of this expression: * *

          *
        • when maxOccurs=unbounded and minOccurs is 1 or 0 *
        • when maxOccurs=1 *
        * *

        * Those cases can be expressed quite nicely with existing primitives * So the client shouldn't find it difficuult to process them. * I appreciate any feedback on this issue. * * @author * Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) */ public class OccurrenceExp extends OtherExp { public OccurrenceExp( Expression preciseExp, int maxOccurs, int minOccurs, Expression itemExp ) { super(preciseExp); this.maxOccurs = maxOccurs; this.minOccurs = minOccurs; this.itemExp = itemExp; } /** Maximum occurence. -1 to indicate "unbounded" */ public final int maxOccurs; /** Minimum occurence. */ public final int minOccurs; /** The unit of repetition. */ public final Expression itemExp; /** Obtains a string representation suitable for quick debugging. */ public String toString() { return itemExp.toString()+"["+minOccurs+","+ (maxOccurs==-1?"inf":String.valueOf(maxOccurs))+"]"; } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/xmlschema/IdentityConstraint.java0000644000175000017500000000240107671170035026517 0ustar giovannigiovanni/* * @(#)$Id: IdentityConstraint.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.xmlschema; /** * represents an identity constraint. * * @author Kohsuke KAWAGUCHI */ public class IdentityConstraint implements java.io.Serializable { /** * selectors of the identity constraint. * each XPath separated by '|' will be treated as one entity. */ public final XPath[] selectors; /** namespace URI of the identity constraint. */ public final String namespaceURI; /** local name of the identity constraint. */ public final String localName; /** fields of this constraint. */ public final Field[] fields; public IdentityConstraint( String namespaceURI, String localName, XPath[] selectors, Field[] fields ) { this.namespaceURI = namespaceURI; this.localName = localName; this.selectors = selectors; this.fields = fields; } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/xmlschema/AttributeDeclExp.java0000644000175000017500000000230407671170035026073 0ustar giovannigiovanni/* * @(#)$Id: AttributeDeclExp.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.xmlschema; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.ReferenceExp; /** * global attribute declaration. * * The exp field of this object is not much useful. * * @author Kohsuke KAWAGUCHI */ public class AttributeDeclExp extends ReferenceExp { /** * name of this attribute declaration. * According to the spec, the name must be unique within one schema * (in our object model, one XMLSchemaSchema object). */ public AttributeDeclExp( String typeLocalName ) { super(typeLocalName); } /** * actual definition. This expression contains meaningful information. */ public AttributeExp self; public void set( AttributeExp exp ) { self = exp; this.exp = self; } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/xmlschema/SkipElementExp.java0000644000175000017500000000170507671170035025564 0ustar giovannigiovanni/* * @(#)$Id: SkipElementExp.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.xmlschema; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.NameClass; /** * ElementExp that is used for <any processContents="skip"/>. * * This is kept in the separate class so that the wildcard element * can be easily distinguished by the application program. * * @author Kohsuke KAWAGUCHI */ public class SkipElementExp extends com.sun.msv.grammar.trex.ElementPattern { public SkipElementExp( NameClass nameClass, Expression contentModel ) { super(nameClass,contentModel); } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/xmlschema/RedefinableExp.java0000644000175000017500000000266107671170035025546 0ustar giovannigiovanni/* * @(#)$Id: RedefinableExp.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.xmlschema; import com.sun.msv.grammar.ReferenceExp; /** * declaration that can be redefined by using <redefine> element. * * @author Kohsuke KAWAGUCHI */ public abstract class RedefinableExp extends ReferenceExp { public RedefinableExp( String typeLocalName ) { super(typeLocalName); } /** clones this object. */ public abstract RedefinableExp getClone(); /** * assigns contents of rhs to this object. * * rhs and this object must be the same runtime type, and * they must have the same name. * this method redefines this object by the given component. * * derived class should override this method and copy * necessary fields, should it necessary. */ public void redefine( RedefinableExp rhs ) { if( this.getClass()!=rhs.getClass() || !this.name.equals(rhs.name) ) // two must be the same class. throw new IllegalArgumentException(); this.exp = rhs.exp; } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/ExpressionVisitorVoid.java0000644000175000017500000000200207671170035025236 0ustar giovannigiovanni/* * @(#)$Id: ExpressionVisitorVoid.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; /** * ExpressionVisitor that returns void. * * @author Kohsuke KAWAGUCHI */ public interface ExpressionVisitorVoid { void onAttribute( AttributeExp exp ); void onChoice( ChoiceExp exp ); void onElement( ElementExp exp ); void onOneOrMore( OneOrMoreExp exp ); void onMixed( MixedExp exp ); void onList( ListExp exp ); void onRef( ReferenceExp exp ); void onOther( OtherExp exp ); void onEpsilon(); void onNullSet(); void onAnyString(); void onSequence( SequenceExp exp ); void onData( DataExp exp ); void onValue( ValueExp exp ); void onConcur( ConcurExp exp ); void onInterleave( InterleaveExp exp ); } msv-2009.1/msv/src/com/sun/msv/grammar/Expression.java0000644000175000017500000003015110005261216023025 0ustar giovannigiovanni/* * @(#)$Id: Expression.java 1627 2004-01-26 18:55:10Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; import com.sun.msv.grammar.util.RefExpRemover; /** * Primitive of the tree regular expression. * * most of the derived class is immutable (except ReferenceExp, ElementExp and OtherExp). * *

        * By making it immutable, it becomes possible to share subexpressions among expressions. * This is very important for regular-expression-derivation based validation algorithm, * as well as for smaller memory footprint. * This sharing is automatically achieved by ExpressionPool. * *

        * ReferebceExp, ElementExp, and OtherExp are also placed in the pool, * but these are not unified. Since they are not unified, * application can derive classes from these expressions * and mix them into AGM. This technique is heavily used to introduce schema language * specific primitives into AGM. See various sub-packages of this package for examples. * *

        * The equals method must be implemented by the derived type. equals method will be * used to unify the expressions. equals method can safely assume that its children * are already unified (therefore == can be used to test the equality, rather than * equals method). * *

        * To achieve unification, we overload the equals method so that * o1.equals(o2) is true if o1 and o2 are identical. * There, those two objects must return the same hash code. For this purpose, * the hash code is calculated statically and cached internally. * * * @author Kohsuke KAWAGUCHI */ public abstract class Expression implements java.io.Serializable { /** cached value of epsilon reducibility. * * Epsilon reducibility can only be calculated after parsing the entire expression, * because of forward reference to other pattern. */ private Boolean epsilonReducibility; /** returns true if this expression accepts empty sequence. * *

        * If this method is called while creating Expressions, then this method * may return approximated value. When this method is used while validation, * this method is guaranteed to return the correct value. */ public boolean isEpsilonReducible() { // epsilon reducibility is cached internally. if (epsilonReducibility == null) epsilonReducibility = calcEpsilonReducibility() ? Boolean.TRUE : Boolean.FALSE; return epsilonReducibility.booleanValue(); } /** computes epsilon reducibility */ protected abstract boolean calcEpsilonReducibility(); /** * Cached value of the expression after ReferenceExps are removed. * This value is computed on demand. */ private Expression expandedExp = null; /** * Gets the expression after removing all ReferenceExps, until child * AttributeExp or ElementExp. */ public Expression getExpandedExp(ExpressionPool pool) { if (expandedExp == null) { // this part of the code may be called by the multiple threads // even if that happens, there is no consistency problem // because two thread will compute the same value. expandedExp = this.visit(new RefExpRemover(pool, false)); } return expandedExp; } /** * Peels the occurence expressions from this expression. *

        * In AGM, 'X?','X+' and 'X*' are represented by using * other primitives. This method returns the 'X' part by * removing occurence related expressions. */ public final Expression peelOccurence() { // 'X?' is represented as 'choice(X,epsilon)'. if (this instanceof ChoiceExp) { ChoiceExp cexp = (ChoiceExp)this; if (cexp.exp1 == Expression.epsilon) return cexp.exp2.peelOccurence(); if (cexp.exp2 == Expression.epsilon) return cexp.exp1.peelOccurence(); // note that epsilon may be in some branch deep under the tree. // for example, when the expression is ((A|epsilon)|B) // the above code won't be able to peel the epsilon in it. // but this is OK, since this method still returns ChoiceExp, // and the type of the expression is what matters. } // 'X+' is represented as 'oneOrMore(X)' if (this instanceof OneOrMoreExp) return ((OneOrMoreExp)this).exp.peelOccurence(); // 'X*' is represented as '(X+)?' // therefore it is important to recursively process it. // otherwise we've finished. return this; } protected Expression(int hashCode) { setHashCode(hashCode); } /** * this constructor can be used for the ununified expressions. * the only reason there are two parameters is to prevent unintentional * use of the default constructor. */ protected Expression() { this.cachedHashCode = System.identityHashCode(this); } /** * this field can be used by Verifier implementation to speed up * validation. Due to its nature, this field is not serialized. * * TODO: revisit this decision of not to serialize this field. */ public transient Object verifierTag = null; public abstract Object visit(ExpressionVisitor visitor); public abstract Expression visit(ExpressionVisitorExpression visitor); public abstract boolean visit(ExpressionVisitorBoolean visitor); public abstract void visit(ExpressionVisitorVoid visitor); // if you don't need RELAX capability at all, cut these lines public Object visit(com.sun.msv.grammar.relax.RELAXExpressionVisitor visitor) { return visit((ExpressionVisitor)visitor); } public Expression visit(com.sun.msv.grammar.relax.RELAXExpressionVisitorExpression visitor) { return visit((ExpressionVisitorExpression)visitor); } public boolean visit(com.sun.msv.grammar.relax.RELAXExpressionVisitorBoolean visitor) { return visit((ExpressionVisitorBoolean)visitor); } public void visit(com.sun.msv.grammar.relax.RELAXExpressionVisitorVoid visitor) { visit((ExpressionVisitorVoid)visitor); } // until here /** * Hash code of this object. * *

        * To memorize every sub expression, hash code is frequently used. * And computation of the hash code requires full-traversal of * the expression. Therefore, hash code is computed when the object * is constructed, and kept cached thereafter. * *

        * This field is essentially final, but because of the serialization * support, we cannot declare it as such. */ private transient int cachedHashCode; public final int hashCode() { return cachedHashCode; } private final void setHashCode(int hashCode) { this.cachedHashCode = hashCode^getClass().hashCode(); } /** * Computes the hashCode again. *

        * This method and the parameter to the constructor has to be * the same. This method is used when the object is being read * from the stream. */ protected abstract int calcHashCode(); public abstract boolean equals(Object o); static protected int hashCode(Object o1, Object o2, int hashKey) { // TODO: more efficient hashing algorithm return o1.hashCode() + o2.hashCode() + hashKey; } static protected int hashCode(Object o, int hashKey) { // TODO: more efficient hashing algorithm return o.hashCode() + hashKey; } private static class EpsilonExpression extends Expression { EpsilonExpression() { } protected final int calcHashCode() { return System.identityHashCode(this); } public Object visit(ExpressionVisitor visitor) { return visitor.onEpsilon(); } public Expression visit(ExpressionVisitorExpression visitor) { return visitor.onEpsilon(); } public boolean visit(ExpressionVisitorBoolean visitor) { return visitor.onEpsilon(); } public void visit(ExpressionVisitorVoid visitor) { visitor.onEpsilon(); } protected boolean calcEpsilonReducibility() { return true; } public boolean equals(Object o) { return this == o; } // this class is used as singleton. // serialization support private static final long serialVersionUID = 1; protected Object readResolve() { return Expression.epsilon; } }; /** * Special expression object that represents epsilon (ε). * This expression matches to "empty". * Epsilon can be thought as an empty sequence. */ public static final Expression epsilon = new EpsilonExpression(); private static class NullSetExpression extends Expression { NullSetExpression() { } protected final int calcHashCode() { return System.identityHashCode(this); } public Object visit(ExpressionVisitor visitor) { return visitor.onNullSet(); } public Expression visit(ExpressionVisitorExpression visitor) { return visitor.onNullSet(); } public boolean visit(ExpressionVisitorBoolean visitor) { return visitor.onNullSet(); } public void visit(ExpressionVisitorVoid visitor) { visitor.onNullSet(); } protected boolean calcEpsilonReducibility() { return false; } public boolean equals(Object o) { return this == o; } // this class is used as singleton. // serialization support private static final long serialVersionUID = 1; protected Object readResolve() { return Expression.nullSet; } }; /** * special expression object that represents the empty set (Φ). * This expression doesn't match to anything. * NullSet can be thought as an empty choice. */ public static final Expression nullSet = new NullSetExpression(); private static class AnyStringExpression extends Expression { AnyStringExpression() { } protected final int calcHashCode() { return System.identityHashCode(this); } public Object visit(ExpressionVisitor visitor) { return visitor.onAnyString(); } public Expression visit(ExpressionVisitorExpression visitor) { return visitor.onAnyString(); } public boolean visit(ExpressionVisitorBoolean visitor) { return visitor.onAnyString(); } public void visit(ExpressionVisitorVoid visitor) { visitor.onAnyString(); } // anyString is consider to be epsilon reducible. // In other words, one can always ignore anyString. // // Instead, anyString will remain in the expression even after // consuming some StringToken. // That is, residual of anyString by StringToken is not the epsilon but an anyString. protected boolean calcEpsilonReducibility() { return true; } public boolean equals(Object o) { return this == o; } // this class is used as singleton. // serialization support private static final long serialVersionUID = 1; protected Object readResolve() { return Expression.anyString; } }; /** * special expression object that represents "any string". * It is close to xsd:string datatype, but they have different semantics * in several things. * *

        * This object is used as <anyString/> pattern of TREX and * <text/> pattern of RELAX NG. */ public static final Expression anyString = new AnyStringExpression(); protected Object readResolve() { setHashCode(calcHashCode()); return this; } private static final long serialVersionUID = -569561418606215601L; } msv-2009.1/msv/src/com/sun/msv/grammar/dtd/0000755000175000017500000000000011622453067020613 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/grammar/dtd/LocalNameClass.java0000644000175000017500000000243107767410006024300 0ustar giovannigiovanni/* * @(#)$Id: LocalNameClass.java 1622 2003-12-15 19:48:22Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.dtd; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.NameClassVisitor; import com.sun.msv.grammar.SimpleNameClass; /** * a NameClass that accepts any tag name as long as its local part is specified name. * * @author Kohsuke KAWAGUCHI */ public final class LocalNameClass extends NameClass { public final String localName; public boolean accepts( String namespaceURI, String localName ) { return this.localName.equals(localName) || LOCALNAME_WILDCARD.equals(localName); } public Object visit( NameClassVisitor visitor ) { // use the approximation. // FIXME return new SimpleNameClass("",localName).visit(visitor); } public LocalNameClass( String localName ) { this.localName = localName; } public String toString() { return localName; } // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/IDContextProvider2.java0000644000175000017500000000164607671167271024360 0ustar giovannigiovanni/* * @(#)$Id: IDContextProvider2.java 1565 2003-06-09 20:31:53Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar; import org.relaxng.datatype.Datatype; import org.relaxng.datatype.ValidationContext; import com.sun.msv.verifier.regexp.StringToken; /** * ValidationContextProvider that supports limited ID/IDREF implementation. * * @author Kohsuke KAWAGUCHI */ public interface IDContextProvider2 extends ValidationContext { /** * this method is called when a type with ID semantics is matched. * * It is the callee's responsibility that stores * ID and checks doubly defined ID, if it is necessary. */ void onID( Datatype datatype, StringToken literal ); } msv-2009.1/msv/src/com/sun/msv/grammar/relaxng/0000755000175000017500000000000011622453066021477 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/grammar/relaxng/RELAXNGGrammar.java0000644000175000017500000000736207671170035024762 0ustar giovannigiovanni/* * @(#)$Id: RELAXNGGrammar.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.relaxng; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.trex.TREXGrammar; /** * Grammar for RELAX NG (with DTD compatibility annotation). * * @author Kohsuke KAWAGUCHI */ public class RELAXNGGrammar extends TREXGrammar { public RELAXNGGrammar( ExpressionPool pool, TREXGrammar parentGrammar ) { super(pool,parentGrammar); } public RELAXNGGrammar( ExpressionPool pool ) { super(pool); } public RELAXNGGrammar() { super(); } /** * the compatibility property of the ID/IDREF feature. * * This flag is set to true if this schema is compatible in terms of * ID/IDREF, as defined in the spec. */ public boolean isIDcompatible = true; /** * the compatibility property of the default attribute feature. * * This flag is set to true if this schema is compatible in terms of * the default attribute value feature, as defined in the spec. * *

        * Note that the currently we don't support infoset augmentation. */ public boolean isDefaultAttributeValueCompatible = true; /** * the compatibility property of the annotation feature. * * This flag is set to true if this schema is compatible in terms of * the annotation feature, as defined in the spec. */ public boolean isAnnotationCompatible = true; /* /** * add an entry to the default value table. * * @return * false if the default attribute value for this element and attribute * was already specified. true if this is the first time. */ /* public final boolean addDefaultValue( String elementNamespaceURI, String elementLocalName, String attributeNamespaceURI, String attributeLocalName, String value ) { if(defaultValues==null) defaultValues = new HashMap(); return defaultValues.put( new ElemAttrNamePair(elementNamespaceURI,elementLocalName,attributeNamespaceURI,attributeLocalName), value )==null; } /** * checks if this grammar has any attribute default value. */ /* public final boolean hasDefaultValue() { return defaultValues!=null && defaultValues.size()!=0; } /** * gets the list of defaultable attributes of the given element. * * @param (namespaceURI,localName) * this pair designates the name of the element. * * @return * if there is no defaultable attribute, it returns empty array. * this method never returns null. */ /* public final String[] getDefaultableAttributes( String namespaceURI, String localName ) { } // TODO: this can be implemented much efficiently, I guess. // map from NamePair (element name) to // (a map from NamePair (attribute name) to attribute value) private Map defaultValues; */ /* public static final int KEYTYPE_NONE =0; public static final int KEYTYPE_ID =1; public static final int KEYTYPE_IDREF =2; public final int getAttributeKeyType( String elementNamespaceURI, String elementLocalName, String attributeNamespaceURI, String attributeLocalName, String value ) { } */ // serialization support private static final long serialVersionUID = 1; } msv-2009.1/msv/src/com/sun/msv/grammar/relaxng/Messages_ja.properties0000644000175000017500000000045007305564235026041 0ustar giovannigiovanni ValueType.BadValue = \ \u5024\u306F\u300C{0}\u300D\u3067\u306A\u304F\u3066\u306F\u306A\u308A\u307E\u305B\u3093 DataTypeBuilderImpl.ParameterUnsupported = \ RELAX NG\u306E\u7D44\u307F\u8FBC\u307F\u578B\u306B\u4F7F\u3048\u308B\u30D1\u30E9\u30E1\u30FC\u30BF\u306F\u3042\u308A\u307E\u305B\u3093 msv-2009.1/msv/src/com/sun/msv/grammar/relaxng/datatype/0000755000175000017500000000000011622453066023312 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/grammar/relaxng/datatype/DatatypeBuilderImpl.java0000644000175000017500000000307007671170035030062 0ustar giovannigiovanni/* * @(#)$Id: DatatypeBuilderImpl.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.relaxng.datatype; import org.relaxng.datatype.Datatype; import org.relaxng.datatype.DatatypeBuilder; import org.relaxng.datatype.DatatypeException; import org.relaxng.datatype.ValidationContext; /** * DataTypeBuilder implementation. * * There is no paramater for any built-in and compatibility types. * * @author Kohsuke KAWAGUCHI */ class DatatypeBuilderImpl implements DatatypeBuilder { private final Datatype baseType; DatatypeBuilderImpl( Datatype baseType ) { this.baseType = baseType; } public Datatype createDatatype() { return baseType; } public void addParameter( String name, String value, ValidationContext context ) throws DatatypeException { throw new DatatypeException( localize(ERR_PARAMETER_UNSUPPORTED,null)); } protected String localize( String propertyName, Object[] args ) { String format = java.util.ResourceBundle.getBundle( "com.sun.msv.grammar.relaxng.Messages").getString(propertyName); return java.text.MessageFormat.format(format, args ); } protected final static String ERR_PARAMETER_UNSUPPORTED = // arg:0 "DataTypeBuilderImpl.ParameterUnsupported"; } msv-2009.1/msv/src/com/sun/msv/grammar/relaxng/datatype/BuiltinDatatypeLibrary.java0000644000175000017500000000271107671170035030606 0ustar giovannigiovanni/* * @(#)$Id: BuiltinDatatypeLibrary.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.relaxng.datatype; import org.relaxng.datatype.Datatype; import org.relaxng.datatype.DatatypeBuilder; import org.relaxng.datatype.DatatypeException; import org.relaxng.datatype.DatatypeLibrary; /** * RELAX NG built-in datatypes. * * This implementation relies on Sun XML Datatypes Library. * * @author Kohsuke KAWAGUCHI */ public class BuiltinDatatypeLibrary implements DatatypeLibrary { /** * the sole instance of this class. */ public static final BuiltinDatatypeLibrary theInstance = new BuiltinDatatypeLibrary(); protected BuiltinDatatypeLibrary() {} public Datatype createDatatype( String name ) throws DatatypeException { if( name.equals("string") ) return com.sun.msv.datatype.xsd.StringType.theInstance; if( name.equals("token") ) return com.sun.msv.datatype.xsd.TokenType.theInstance; throw new DatatypeException("undefined built-in type:"+name); } public DatatypeBuilder createDatatypeBuilder( String name ) throws DatatypeException { return new DatatypeBuilderImpl( createDatatype(name) ); } } msv-2009.1/msv/src/com/sun/msv/grammar/relaxng/datatype/package.html0000644000175000017500000000011707305564006025572 0ustar giovannigiovanni

        RELAX NG built-in datatype implementation.

        msv-2009.1/msv/src/com/sun/msv/grammar/relaxng/datatype/CompatibilityDatatypeLibrary.java0000644000175000017500000000335607671170035032017 0ustar giovannigiovanni/* * @(#)$Id: CompatibilityDatatypeLibrary.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.grammar.relaxng.datatype; import org.relaxng.datatype.Datatype; import org.relaxng.datatype.DatatypeBuilder; import org.relaxng.datatype.DatatypeException; import org.relaxng.datatype.DatatypeLibrary; import com.sun.msv.datatype.xsd.DatatypeFactory; import com.sun.msv.datatype.xsd.IDREFType; import com.sun.msv.datatype.xsd.IDType; /** * RELAX NG DTD compatibility datatype library. * * This implementation relies on Sun XML Datatypes Library. * Compatibility datatypes library available through * http://relaxng.org/ns/compatibility/datatypes/1.0. * * @author Kohsuke KAWAGUCHI */ public class CompatibilityDatatypeLibrary implements DatatypeLibrary { /** namespace URI of the compatibility datatypes library. */ public static final String namespaceURI = "http://relaxng.org/ns/compatibility/datatypes/1.0"; public Datatype createDatatype( String name ) throws DatatypeException { if( name.equals("ID") ) return IDType.theInstance; if( name.equals("IDREF") ) return IDREFType.theInstance; if( name.equals("IDREFS") ) return DatatypeFactory.getTypeByName("IDREFS"); throw new DatatypeException("undefined built-in type:"+name); } public DatatypeBuilder createDatatypeBuilder( String name ) throws DatatypeException { return new DatatypeBuilderImpl( createDatatype(name) ); } } msv-2009.1/msv/src/com/sun/msv/grammar/relaxng/Messages.properties0000644000175000017500000000022407305564006025362 0ustar giovannigiovanni ValueType.BadValue = \ the value must be {0} DataTypeBuilderImpl.ParameterUnsupported = \ no parameter is available for RELAX NG built-in types.msv-2009.1/msv/src/com/sun/msv/verifier/0000755000175000017500000000000011622453067020225 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/verifier/IVerifier.java0000644000175000017500000000561307671170035022761 0ustar giovannigiovanni/* * @(#)$Id: IVerifier.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier; import org.iso_relax.verifier.VerifierHandler; import org.relaxng.datatype.Datatype; import org.xml.sax.ErrorHandler; import org.xml.sax.Locator; /** * Interface of verifier. * * @author Kohsuke KAWAGUCHI */ public interface IVerifier extends VerifierHandler { /** * checks if the document was valid. * This method may not be called before verification was completed. */ boolean isValid(); /** * returns current element type. * * Actual java type depends on the implementation. * This method works correctly only when called immediately * after handling startElement event. * * @return null * this method returns null when it doesn't support * type-assignment feature, or type-assignment is impossible * for the current element (for example due to the ambiguous grammar). */ Object getCurrentElementType(); /** * gets DataType that validated the last characters. * *

        * This method works correctly only when called immediately * after startElement and endElement method. When called, this method * returns DataType object that validated the last character literals. * *

        * For RELAX NG grammar, this method can return an array of length 2 or more. * This happens when the last character matches <list> pattern. * In that case, each type corresponds to each token (where tokens are the * white-space separation of the last characters). * *

        * For any other grammar, this method always returns an array of length 1 * (or null, if the type assignment failed). * *

        * So when you are using VerifierFilter, you can call this method only * in your startElement and endElement method. * * @return null * if type-assignment was not possible. */ Datatype[] getLastCharacterType(); /** * Turns on/off the panic mode. * Panic mode is on by default. Turning it on is good * for general use. It prevents false error messages to appear. *

        * However, turning it off is sometimes useful, when * you are sure that the structure of the document is * almost valid (e.g., validating a document generated by an * application or when you are sure about the validity of the * structure and only interested in validating datatypes,) */ void setPanicMode( boolean usePanicMode ); Locator getLocator(); ErrorHandler getErrorHandler(); void setErrorHandler( ErrorHandler handler ); } msv-2009.1/msv/src/com/sun/msv/verifier/DocumentDeclaration.java0000644000175000017500000000201607671170035025013 0ustar giovannigiovanni/* * @(#)$Id: DocumentDeclaration.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier; /** * Represents a kind of "constraint" over XML document. * * Usually, this is what people call a schema. * *

        * Call the {@link #createAcceptor()} method to start validation. * * @see Acceptor * * @author Kohsuke KAWAGUCHI */ public interface DocumentDeclaration { /** * creates a new Acceptor that will validate the document element. * * In RELAX, this concept is equivalent to <topLevel> * In TREX, this concept is equivalent to <start> * * @return * The implementation cannot return null. * Apparently, it is impossible to fail in this early stage. */ Acceptor createAcceptor(); } msv-2009.1/msv/src/com/sun/msv/verifier/package.html0000644000175000017500000000155007253566564022523 0ustar giovannigiovanni

        Contains abstract model for grammar-based schema and concrete verifier implementation for the abstract schema.

        The model of the schema consists of two interfaces:

        1. DocumentDeclaration, which corresponds to constraints over XML documents
        2. ElementDeclaration, which corresponds to constraints over an XML element
        3. Acceptor, which verifies XML content against the content model

        Note that these definitions capture schema from verifier's point of view. ŒŸØ‚ɑ΂µ‚Ä’†—§‚ȃXƒL[ƒ}‚̃IƒuƒWƒFƒNƒgƒ‚ƒfƒ‹‚ÆAŒŸØ‚̃Aƒ‹ƒSƒŠƒYƒ€‚É“Á‰»‚µ‚½ƒAƒ_ƒvƒ^‚Ƃ͕ʂɗpˆÓ‚·‚é‚Ì‚ª–]‚Ü‚µ‚¢BThese definitions are for the latter, not for the former.

         

        msv-2009.1/msv/src/com/sun/msv/verifier/psvi/0000755000175000017500000000000011622453067021206 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/verifier/psvi/TypedContentHandler.java0000644000175000017500000000750607671170035025777 0ustar giovannigiovanni/* * @(#)$Id: TypedContentHandler.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.psvi; import org.relaxng.datatype.Datatype; import org.relaxng.datatype.ValidationContext; import org.xml.sax.SAXException; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.ElementExp; /** * Receives notification of the typed content of the document. * *

        * This interface can be considered as the SAX ContentHandler plus type-information. * It is intended to help applications to interpret the incoming document. * *

        * Consider a following RELAX NG pattern and instance: * *

        
         * <element name="root">
         *   <optional>
         *     <attribute name="foo">
         *       <choice>
         *         <data type="boolean"/>
         *         <data type="date"/>
         *       </choice>
         *     </attribute>
         *   </optional>
         *   <element name="child">
         *     <list><zeroOrMore>
         *       <data type="NMTOKEN"/>
         *     </zeroOrMore></list>
         *   </element>
         * </element>
         * 
         * <root foo="true">
         *   <child> A B </child>
         * </root>
         * 
        * * Events are reported in the following order: *
         * startDocument()
         *  startElement(root)
         *   startAttribute(foo)
         *    characterChunk("true", com.sun.msv.datatype.xsd.BooleanType)
         *   endAttribute(foo)
         *   endAttributePart()
         *   startElement(child)
         *    characterChunk("A", com.sun.msv.datatype.xsd.NMTOKENType)
         *    characterChunk("B", com.sun.msv.datatype.xsd.NMTOKENType)
         *   endElement(child, MSV's internal object that represents the child element)
         *  endElement(root, MSV's internal object that represents the root element)
         * endDocument()
         * 
        * * @see * TypeDetector * * @author Kohsuke KAWAGUCHI */ public interface TypedContentHandler { /** * receives notification of the start of a document. * * @param context * This ValidationContext object is effective through the entire document. */ void startDocument( ValidationContext context ) throws SAXException; /** * receives notification of the end of a document. */ void endDocument() throws SAXException; /** * receives notification of a string. * * @param literal * the contents. * @param type * assigned type. The validator assigns this type for this literal. */ void characterChunk( String literal, Datatype type ) throws SAXException; /** * receives notification of the start of an element. * * If this element has attributes, the start/endAttribute methods are * called after this method. */ void startElement( String namespaceURI, String localName, String qName ) throws SAXException; /** * receives notification of the end of an element. * * @param type * the type of this element. */ void endElement( String namespaceURI, String localName, String qName, ElementExp type ) throws SAXException; /** * receives notification of the start of an attribute. * * the value of the attribute is reported through the characterChunk method. */ void startAttribute( String namespaceURI, String localName, String qName ) throws SAXException; /** * receives notification of the end of an attribute. * * @param type * assigned type. */ void endAttribute( String namespaceURI, String localName, String qName, AttributeExp type ) throws SAXException; /** * this method is called after the start/endAttribute method are called * for all attributes. */ void endAttributePart() throws SAXException; } msv-2009.1/msv/src/com/sun/msv/verifier/psvi/package.html0000644000175000017500000000051607330377004023466 0ustar giovannigiovanni

        Type-assignment engine that can be used by application programs.

        Classes in this package provides the functionality equivalent to post-schema-validation-infoset (PSVI) of W3C XML Schema.

        msv-2009.1/msv/src/com/sun/msv/verifier/psvi/TypeDetector.java0000644000175000017500000001674607671170035024502 0ustar giovannigiovanni/* * @(#)$Id: TypeDetector.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.psvi; import java.util.StringTokenizer; import org.relaxng.datatype.Datatype; import org.xml.sax.Attributes; import org.xml.sax.ErrorHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import com.sun.msv.grammar.ElementExp; import com.sun.msv.util.DatatypeRef; import com.sun.msv.util.StartTagInfo; import com.sun.msv.util.StringRef; import com.sun.msv.verifier.Acceptor; import com.sun.msv.verifier.DocumentDeclaration; import com.sun.msv.verifier.ErrorInfo; import com.sun.msv.verifier.ValidityViolation; import com.sun.msv.verifier.Verifier; import com.sun.msv.verifier.regexp.ComplexAcceptor; import com.sun.msv.verifier.regexp.REDocumentDeclaration; import com.sun.msv.verifier.regexp.SimpleAcceptor; /** * assign types to the incoming SAX2 events and reports them to * the application handler through TypedContentHandler. * * This class "augment" infoset by adding type information. The application can * receive augmented infoset by implementing TypedContentHandler. * * @author Kohsuke KAWAGUCHI */ public class TypeDetector extends Verifier { /** characters that were read (but not processed) */ private StringBuffer text = new StringBuffer(); protected TypedContentHandler handler; public TypeDetector( DocumentDeclaration documentDecl, ErrorHandler errorHandler ) { super(documentDecl,errorHandler); } public TypeDetector( DocumentDeclaration documentDecl, TypedContentHandler handler, ErrorHandler errorHandler ) { this(documentDecl,errorHandler); setContentHandler(handler); } /** * sets the TypedContentHandler which will received the type-augmented * infoset. */ public void setContentHandler( TypedContentHandler handler ) { this.handler = handler; } private final DatatypeRef characterType = new DatatypeRef(); protected void verifyText() throws SAXException { if(text.length()!=0) { final String txt = new String(text); if(!current.onText2( txt, this, null, characterType )) { // error // diagnose error, if possible StringRef err = new StringRef(); current.onText2( txt, this, err, null ); // report an error errorHandler.error( new ValidityViolation(locator, localizeMessage( ERR_UNEXPECTED_TEXT, null ), new ErrorInfo.BadText(txt) ) ); } // characters are validated. report to the handler. reportCharacterChunks( txt, characterType.types ); text = new StringBuffer(); } } private void reportCharacterChunks( String text, Datatype[] types ) throws SAXException { if( types==null ) // unable to assign type. throw new AmbiguousDocumentException(); switch( types.length ) { case 0: return; // this text is ignored. case 1: handler.characterChunk( text, types[0] ); return; default: StringTokenizer tokens = new StringTokenizer(text); for( int i=0; i for the patch. // the startAttribute method should be called before the feedAttribute. // // this makes the error report consistent with the startAttribute event. handler.startAttribute( uri, localName, qName ); Datatype[] result = super.feedAttribute(child,uri,localName,qName,value); reportCharacterChunks( value, result ); handler.endAttribute( uri, localName, qName, ((REDocumentDeclaration)docDecl).attToken.matchedExp ); return result; } public void startElement( String namespaceUri, String localName, String qName, Attributes atts ) throws SAXException { super.startElement( namespaceUri, localName, qName, atts ); handler.endAttributePart(); } protected void onNextAcceptorReady( StartTagInfo sti, Acceptor nextAcceptor ) throws SAXException { /* You cannot call handler.startElement before super.startElement invocation because unconsumed text maybe processed here. */ handler.startElement( sti.namespaceURI, sti.localName, sti.qName ); } public void endElement( String namespaceUri, String localName, String qName ) throws SAXException { Acceptor child = current; super.endElement(namespaceUri,localName,qName); {// report to the handler ElementExp type; if( child instanceof SimpleAcceptor ) { type = ((SimpleAcceptor)child).owner; } else if( child instanceof ComplexAcceptor ) { ElementExp[] exps = ((ComplexAcceptor)child).getSatisfiedOwners(); if(exps.length!=1) throw new AmbiguousDocumentException(); type = exps[0]; } else throw new Error(); // assertion failed. not supported. handler.endElement( namespaceUri, localName, qName, type ); } } public void characters( char[] buf, int start, int len ) throws SAXException { text.append(buf,start,len); } public void ignorableWhitespace( char[] buf, int start, int len ) throws SAXException { text.append(buf,start,len); } public void startDocument() throws SAXException { super.startDocument(); handler.startDocument(this); } public void endDocument() throws SAXException { super.endDocument(); handler.endDocument(); } /** * signals that the document is ambiguous. * This exception is thrown when *
          *
        1. we cannot uniquely assign the type for given characters. *
        2. or we cannot uniquely determine the type for the element * when we reached the end element. *
        * * The formar case happens for patterns like: *
        
             * <choice>
             *   <data type="xsd:string"/>
             *   <data type="xsd:token"/>
             * </choice>
             * 
        * * The latter case happens for patterns like: *
        
             * <choice>
             *   <element name="foo">
             *     <text/>
             *   </element>
             *   <element>
             *     <anyName/>
             *     <text/>
             *   </element>
             * </choice>
             * 
        */ public class AmbiguousDocumentException extends SAXException { public AmbiguousDocumentException() { super(""); } /** returns the source of the error. */ Locator getLocation() { return TypeDetector.this.getLocator(); } }; } msv-2009.1/msv/src/com/sun/msv/verifier/Acceptor.java0000644000175000017500000003270707671170035022641 0ustar giovannigiovanni/* * @(#)$Id: Acceptor.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier; import com.sun.msv.grammar.IDContextProvider; import com.sun.msv.grammar.IDContextProvider2; import com.sun.msv.util.DatatypeRef; import com.sun.msv.util.StartTagInfo; import com.sun.msv.util.StringRef; /** * exposes the low-level validation engine interface. * *

        * represents a pseudo-automaton acceptor. * this interface is used to validate content models. * * * *

        Perform Validation

        *

        * To perform validation, call the createAcceptor method of the DocumentDeclaration * interface to obtain an Acceptor for validating the document element. * *

         * Acceptor a = vgm.createAcceptor();
         * 
        * *

        * One acceptor is responsible for validating one element. So you also need * some form of stack. If you are using a "push" interface like SAX, you need * an explicit stack. If you are validating in "pull" fashion (like DOM), then * you can use a recursion instead of an explicit stack. * The following explanation assumes SAX-like interface. * *

        * Now, get back to the story. Whenever you encounter a start tag, create a new * acceptor, which validates the children of newly encountered element. * *

         * stack.push(a);
         * a = a.createChildAcceptor( sti, null );
         * 
        * *

        * If this tag name was unexpected, then this method returns null. See javadoc * for more details. * *

        * Then, for every attributes, call the {@link #onAttribute} method. * After that you call the {@link #onEndAttributes} method. * *

        
         * for( int i=0; i<atts.getLength(); i++ )
         *   a.onAttribute( atts.getURI(i), .... );
         * a.onEndAttributes();
         * 
        * *

        * An error can occur at any method. See the method documentations for details. * *

        * If you find an end tag, make sure that the acceptor is satisfied. An acceptor * is said to be unsatisfied when it needs more elements/text to complete the content * model. For example, if the content model is (A,B,C) and it only sees (A,B), then * the acceptor is not satisfied because it needs to see C. * *

         * if(!a.isAcceptState(null))
         *   ; // error because the acceptor is unsatisfied.
         * Acceptor child = a;
         * a = stack.pop();
         * a.stepForward(child,null);
         * 
        * *

        * Then, call the stepForward method of the parent acceptor and pass * the child acceptor to it. * *

        * Finally, whenever you see a text, call the onText method. * If the text was unexpected or not allowed, then this method returns null. * See the documentation for details. * *

         * a.onText("text",context,null,null);
         * 
        * * *

        * In this way, you can better control the validation process. * *

        * If you need even finer control of the validation process * (e.g., you need to know the list of allowed elements/attributes), * you may want to rely on the regexp implementation of VGM. * see {@link com.sun.msv.verifier.regexp.REDocumentDeclaration} for detail. * * * *

        Downcasting

        * *

        * It is often useful to downcast the Acceptor interface to appropriate * derived class. For example, if you are using * {@link com.sun.msv.verifier.regexp.REDocumentDeclaration}, then you can always * downcast an Acceptor to * {@link com.sun.msv.verifier.regexp.ExpressionAcceptor}, which provides * more predictable behaviors and some useful methods. * * * @see DocumentDeclaration * @author Kohsuke KAWAGUCHI */ public interface Acceptor { /** * creates an Acceptor that will accept * the content model of the children of this moment. * * *

        * Once you create an acceptor, you need to call the * {@link #onAttribute} method for each present attribute, * and then you need to call the {@link #onEndAttributes} method. * *

        * If an error occurs at this method, the bottom line is that the user cannot * write this element here. * * @param refErr * if this parameter is non-null, the implementation should * try to detect the reason of error and recover from it. * and this object should have the error message as its str field. * * @param sti * this parameter provides the information about the start tag to the * acceptor object. Usually attribute information is ignored, but * sometimes they are used as hints. * * @return null * If refErr is null, return null if the given start tag is not accepted. * If refErr is non-null, return null only when the recovery is impossible. */ Acceptor createChildAcceptor( StartTagInfo sti, StringRef refErr ); /** * processes an attribute. * *

        * For every attribute present in the document, you need to call this method. * *

        * An error at this method typically indicates that *

          *
        1. this attribute is not allowed to appear here *
        2. the attribute name was OK, but the value was incorrect. *
        * * @param refErr * In case of an error, this object will receive the localized error * message. Null is a valid value for this parameter. * The implementation must provide some kind of message. * * @param refType * If this parameter is non-null, this object will receive the datatype * assigned to the attribute value. * *

        * This feature is optional and therefore the implementation is * not necessarily provide this information. * * @return * false if an error happens and refErr parameter * was not provided. Otherwise true. */ boolean onAttribute2( String namespaceURI, String localName, String qName, String value, IDContextProvider2 context, StringRef refErr, DatatypeRef refType ); /** * @deprecated */ boolean onAttribute( String namespaceURI, String localName, String qName, String value, IDContextProvider context, StringRef refErr, DatatypeRef refType ); /** * notifies the end of attributes. * *

        * This method needs to be called after the {@link #onAttribute} * method is called for each present attribute. * *

        * An error at this method typically indicates that some required * attributes are missing. * * @param sti * This information is used to produce the error message if that is * necessary. * * @param refErr * In case of an error, this object will receive the localized error * message. Null is a valid value for this parameter. * The implementation must provide some kind of message. * * @return * false if an error happens and refErr parameter * was not provided. Otherwise true. */ boolean onEndAttributes( StartTagInfo sti, StringRef refErr ); /** * processes a string literal. * * @param context * an object that provides context information necessary to validate * some datatypes. * @param refErr * if this parameter is non-null, the implementation should * try to detect the reason of error and recover from it. * and this object should have the error message as its str field. * @param refType * if this parameter is non-null and the callee supports * type-assignment, the callee will assign the DataType object * to this variable. * Caller must initialize refType.type to null before calling this method. * If the callee doesn't support type-assignment or type-assignment * is impossible for this literal (possibly by ambiguous grammar), * this variable must kept null. * * @return false * if the literal at this position is not allowed. */ boolean onText2( String literal, IDContextProvider2 context, StringRef refErr, DatatypeRef refType ); /** * @deprecated */ boolean onText( String literal, IDContextProvider context, StringRef refErr, DatatypeRef refType ); /** * eats a child element * *

        * A child acceptor created by the {@link createChildAcceptor} method * will be ultimately consumed by the parent through this method. * *

        * It is the caller's responsibility to make sure that child acceptor * is in the accept state. If it's not, that indicates that some required * elements are missing (in other words, contents are not allowed to end here). * *

        * It is the callee's responsibility to recover from error of * unsatisified child acceptor. That is, even if the caller finds that * there are missing elements, it is possible to call this method * as if there was no such error. * * @return false * if an error happens. For example, if the implementation passes * an acceptor which is NOT a child of this acceptor, then * the callee can return false. */ boolean stepForward( Acceptor child, StringRef errRef ); /** * checks if this Acceptor is satisifed. * *

        * Acceptor is said to be satisfied when given sequence of elements/strings * is accepted by the content model. This method should be called before * calling the stepForward method to make sure that the children * is written properly. * * @param errRef * If this value is non-null, implementation can diagnose the error * and sets the message to the object. */ boolean isAcceptState( StringRef errRef ); /** * gets the "type" object for which this acceptor is working. * * This method is used for type assignment. Actual Java type of * return value depends on the implementation. * * @return null * the callee should return null when it doesn't support * type-assignment feature, or type-assignment is impossible * for this acceptor (for example by ambiguous grammar). */ Object getOwnerType(); /** * clones this acceptor. * *

        * You can keep a "bookmark" of the acceptor by cloning it. * This is useful when you are trying to perform "partial validation". * *

        * Cloned acceptor will behave in exactly the same way as the original one. */ Acceptor createClone(); /** * gets how this acceptor handles characters. * *

        * This method makes it possible to optimize character handling. * For many elements of data-oriented schemas, characters are completely prohibited. * For example, In SVG, only handful elements are allowed to have #PCDATA and * all other elements have element-only content model. Also, for many elements of * document-oriented schemas, #PCDATA is allowed just about anywhere. * *

        * In the former case, this method returns {@link #STRING_PROHIBITED}. * In other words, this declares that any onText(String) method with * non-whitespace characters will always result in a failure. * The caller can then exploit this property of the content model and * can immediately signal an error when it finds characters, or discard any * whitespace characters without keeping them in memory. * *

        * In the latter case, this method returns {@link #STRING_IGNORE}. * This declares that any onText(String) call does not change anything at all. * The caller can then exploit this property and discard any characeters it found. * *

        * If non of the above applies, or the implementation is simply not capable of * providing this information, then this method returns {@link #STRING_STRICT}. * In this case, the caller has to faithfully call the onText(String) method * for all characeters it found. * *

        * Although this method can be called anytime, it is intended to be called * only once when the acceptor is first created. * * @return * one of the three constant values shown below. */ int getStringCareLevel(); /** * only whitespaces are allowed. Acceptor will reject any string * if it's not whitespaces. * * for example, <elementRule> of RELAX doesn't allow * characters (except whitespaces) at all. */ static final int STRING_PROHIBITED = 0x00; /** * character literals are allowed, but Acceptor doesn't care * its contents and where it is appeared. * * The caller doesn't need to call onText for literal. * This mode is used for mixed contents. */ static final int STRING_IGNORE = 0x01; /** * attentive handling of characters is required. * * Verifier has to keep track of exact contents of string and * it must call onText for string accordingly. */ static final int STRING_STRICT = 0x02; // TODO: possible 4th class, STRING_SLOPPY, // which requires stepForward invocation but don't care about its content. } msv-2009.1/msv/src/com/sun/msv/verifier/Messages_ja.properties0000644000175000017500000000205507350477355024577 0ustar giovannigiovanniVerifier.Error.UnexpectedText = \ \u30AD\u30E3\u30E9\u30AF\u30BF\u30C7\u30FC\u30BF\u306F\u3053\u3053\u306B\u306F\u8A31\u3055\u308C\u307E\u305B\u3093 Verifier.Error.UnexpectedAttribute = \ \u5C5E\u6027"{0}"\u306F\u9593\u9055\u3063\u3066\u3044\u307E\u3059 Verifier.Error.UnexpectedStartTag = \ \u8981\u7D20"{0}"\u306F\u3053\u3053\u306B\u306F\u8A31\u3055\u308C\u307E\u305B\u3093 Verifier.Error.MissingAttribute = \ \u8981\u7D20"{0}"\u306B\u5FC5\u8981\u306A\u5C5E\u6027\u304C\u8DB3\u308A\u307E\u305B\u3093 Verifier.Error.UncompletedContent = \ \u8981\u7D20"{0}"\u306E\u5185\u5BB9\u304C\u4E0D\u5B8C\u5168\u3067\u3059 Verifier.Error.UnsoldIDREF = \ "{0}"\u306FIDREF\u306B\u3088\u3063\u3066\u53C2\u7167\u3055\u308C\u3066\u3044\u307E\u3059\u304C\u3001\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u305B\u3093 Verifier.Error.DuplicateId = \ "{0}"\u306FID\u306E\u5024\u3068\u3057\u3066\u8907\u6570\u56DE\u4F7F\u308F\u308C\u3066\u3044\u307E\u3059 Verifier.Error.UnexpectedElement =\ \u8981\u7D20"{0}"\u306F\u3053\u3053\u306B\u306F\u8A31\u3055\u308C\u307E\u305B\u3093 msv-2009.1/msv/src/com/sun/msv/verifier/VerifierFilter.java0000644000175000017500000001000207671170035024002 0ustar giovannigiovanni/* * @(#)$Id: VerifierFilter.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier; import org.relaxng.datatype.Datatype; import org.xml.sax.Attributes; import org.xml.sax.ErrorHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.helpers.XMLFilterImpl; /** * SAX XMLFilter that verifies incoming SAX event stream. * * This object can be reused to validate multiple documents. * Just be careful NOT to use the same object to validate more than one * documents at the same time. * * @author Kohsuke KAWAGUCHI */ public class VerifierFilter extends XMLFilterImpl implements IVerifier { private final IVerifier verifier; /** * @param verifier * Verifier object that performs actual validation. */ public VerifierFilter( IVerifier verifier ) { this.verifier = verifier; } public VerifierFilter( DocumentDeclaration documentDecl, ErrorHandler errorHandler ) { this( new Verifier(documentDecl,errorHandler) ); } public boolean isValid() { return verifier.isValid(); } public Object getCurrentElementType() { return verifier.getCurrentElementType(); } public Datatype[] getLastCharacterType() { return verifier.getLastCharacterType(); } public final Locator getLocator() { return verifier.getLocator(); } public final ErrorHandler getErrorHandler() { return verifier.getErrorHandler(); } public final void setErrorHandler( ErrorHandler handler ) { super.setErrorHandler(handler); verifier.setErrorHandler(handler); } public final void setPanicMode( boolean usePanicMode ) { verifier.setPanicMode(usePanicMode); } public IVerifier getVerifier() { return verifier; } public void setDocumentLocator(Locator locator) { verifier.setDocumentLocator(locator); super.setDocumentLocator(locator); } public void startDocument() throws SAXException { verifier.startDocument(); super.startDocument(); } public void endDocument() throws SAXException { verifier.endDocument(); super.endDocument(); } public void startPrefixMapping( String prefix, String uri ) throws SAXException { verifier.startPrefixMapping(prefix, uri); super.startPrefixMapping(prefix, uri); } public void endPrefixMapping(String prefix) throws SAXException { verifier.endPrefixMapping(prefix); super.endPrefixMapping(prefix); } public void startElement( String namespaceURI, String localName, String qName, Attributes atts ) throws SAXException { verifier.startElement(namespaceURI, localName, qName, atts); super.startElement(namespaceURI, localName, qName, atts); } public void endElement( String namespaceURI, String localName, String qName ) throws SAXException { verifier.endElement(namespaceURI, localName, qName); super.endElement(namespaceURI, localName, qName); } public void characters( char ch[], int start, int length ) throws SAXException { verifier.characters(ch, start, length); super.characters(ch, start, length); } public void ignorableWhitespace( char ch[], int start, int length ) throws SAXException { verifier.ignorableWhitespace(ch, start, length); super.ignorableWhitespace(ch, start, length); } public void processingInstruction(String target, String data) throws SAXException { verifier.processingInstruction(target, data); super.processingInstruction(target, data); } public void skippedEntity(String name) throws SAXException { verifier.skippedEntity(name); super.skippedEntity(name); } } msv-2009.1/msv/src/com/sun/msv/verifier/util/0000755000175000017500000000000011622453067021202 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/verifier/util/package.html0000644000175000017500000000007307273576330023471 0ustar giovannigiovanni

        Miscellaneous utilities

        msv-2009.1/msv/src/com/sun/msv/verifier/util/ErrorHandlerImpl.java0000644000175000017500000000227307671170035025262 0ustar giovannigiovanni/* * @(#)$Id: ErrorHandlerImpl.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.util; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXParseException; /** * default implementation of ErrorHandler. * * If an error is found, this implementation will throw it * as an exception so that no further processing of the document will be performed. * *

        * All warnings are ignored. * * @author Kohsuke KAWAGUCHI */ public class ErrorHandlerImpl implements ErrorHandler { /** * the singleton instance of this object. This class doesn't have any * internal state so */ public static final ErrorHandler theInstance = new ErrorHandlerImpl(); public void fatalError( SAXParseException error ) throws SAXParseException { throw error; } public void error( SAXParseException error ) throws SAXParseException { throw error; } public void warning( SAXParseException warning ) {} } msv-2009.1/msv/src/com/sun/msv/verifier/util/IgnoreErrorHandler.java0000644000175000017500000000137707671170035025610 0ustar giovannigiovanni/* * @(#)$Id: IgnoreErrorHandler.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.util; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXParseException; /** * do-nothing implementation of ErrorHandler. * * @author Kohsuke KAWAGUCHI */ public class IgnoreErrorHandler implements ErrorHandler { public void fatalError( SAXParseException e ) throws SAXParseException { throw e; } public void error( SAXParseException error ) {} public void warning( SAXParseException warning ) {} } msv-2009.1/msv/src/com/sun/msv/verifier/jaxp/0000755000175000017500000000000011622453067021167 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/verifier/jaxp/Const.java0000644000175000017500000000045607671170035023125 0ustar giovannigiovannipackage com.sun.msv.verifier.jaxp; public class Const { /** * The property/attribute name which is used to set a schema. * * @see DocumentBuilderFactoryImpl * SAXParserImpl */ public static final String SCHEMA_PROPNAME = "http://www.sun.com/xml/msv/schema"; } msv-2009.1/msv/src/com/sun/msv/verifier/jaxp/DocumentBuilderFactoryImpl.java0000644000175000017500000001330610123571127027265 0ustar giovannigiovanni/* * @(#)$Id: DocumentBuilderFactoryImpl.java 1647 2004-09-20 15:08:07Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.jaxp; import java.io.File; import java.io.InputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.iso_relax.verifier.Schema; import org.iso_relax.verifier.VerifierFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import com.sun.msv.verifier.jarv.TheFactoryImpl; /** * DocumentBuilderFactory implementation that supports validation. * *

        * This class uses another DocumentBuilderFactory implementation and * adds the validation capability to it. * * @author Kohsuke KAWAGUCHI */ public class DocumentBuilderFactoryImpl extends DocumentBuilderFactory { /** * Wrapped DocumentBuilderFactory that does everything else. */ private final DocumentBuilderFactory core; /** * JARV VerifierFactory implementation, which will be used to parse schemas. */ private final VerifierFactory jarvFactory; /** * The validation will be performed against this schema object. */ private Schema schema; /** * Creates a new instance by using the default DocumentBuilderFactory implementation * as the underlying parser. This constructor does not set any schema. */ public DocumentBuilderFactoryImpl() { this( DocumentBuilderFactory.newInstance() ); } /** * Creates a new instance by specifying the underlying SAXParserFactory * implementation. This constructor does not set any schema. */ public DocumentBuilderFactoryImpl( DocumentBuilderFactory _factory ) { this(_factory,null); } public DocumentBuilderFactoryImpl( DocumentBuilderFactory _factory, Schema _schema ) { this.core = _factory; this.jarvFactory = new TheFactoryImpl(); this.schema = _schema; } public Object getAttribute( String name ) { if( name.equals(com.sun.msv.verifier.jarv.Const.PANIC_MODE_FEATURE) ) try { return jarvFactory.isFeature(name)?Boolean.TRUE:Boolean.FALSE; } catch( SAXException e ) { throw new IllegalArgumentException(e.getMessage()); } return core.getAttribute(name); } public void setAttribute( String name, Object value ) { if( name.equals(com.sun.msv.verifier.jarv.Const.PANIC_MODE_FEATURE) ) try { jarvFactory.setFeature(name,((Boolean)value).booleanValue()); } catch( SAXException e ) { throw new IllegalArgumentException(e.getMessage()); } if(Const.SCHEMA_PROPNAME.equals(name)) { try { if(value instanceof String) { schema = jarvFactory.compileSchema( (String)value ); return; } if(value instanceof File) { schema = jarvFactory.compileSchema( (File)value ); return; } if(value instanceof InputSource) { schema = jarvFactory.compileSchema( (InputSource)value ); return; } if(value instanceof InputStream) { schema = jarvFactory.compileSchema( (InputStream)value ); return; } if(value instanceof Schema) { schema = (Schema)value; return; } throw new IllegalArgumentException("unrecognized value type: "+value.getClass().getName() ); } catch( Exception e ) { throw new IllegalArgumentException(e.toString()); } } core.setAttribute(name,value); } public boolean isCoalescing() { return core.isCoalescing(); } public boolean isExpandEntityReference() { return core.isExpandEntityReferences(); } public boolean isIgnoringComments() { return core.isIgnoringComments(); } public boolean isIgnoringElementContentWhitespace() { return core.isIgnoringElementContentWhitespace(); } public boolean isNamespaceAware() { return core.isNamespaceAware(); } public boolean isValidating() { return core.isValidating(); } public DocumentBuilder newDocumentBuilder() throws ParserConfigurationException { if(schema==null) return core.newDocumentBuilder(); return new DocumentBuilderImpl(core.newDocumentBuilder(),schema); } public void setCoalescing( boolean newVal ) { core.setCoalescing(newVal); } public void setExpandEntityReference( boolean newVal ) { core.setExpandEntityReferences(newVal); } public void setIgnoringComments( boolean newVal ) { core.setIgnoringComments(newVal); } public void setIgnoringElementContentWhitespace( boolean newVal ) { core.setIgnoringElementContentWhitespace(newVal); } public void setNamespaceAware( boolean newVal ) { core.setNamespaceAware(newVal); } public void setValidating( boolean newVal ) { core.setValidating(newVal); } public boolean getFeature(String name) { throw new UnsupportedOperationException(); } public void setFeature(String name,boolean value) { throw new UnsupportedOperationException(); } } msv-2009.1/msv/src/com/sun/msv/verifier/jaxp/SAXParserFactoryImpl.java0000644000175000017500000001171007671170035026014 0ustar giovannigiovanni/* * @(#)$Id: SAXParserFactoryImpl.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.jaxp; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.iso_relax.verifier.Schema; import org.iso_relax.verifier.VerifierConfigurationException; import org.iso_relax.verifier.VerifierFactory; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import com.sun.msv.verifier.jarv.TheFactoryImpl; /** * SAXParserFactory implementation that supports validation. * *

        * This class uses another SAXParserFactory implementation and * adds the validation capability to it. * * @author Kohsuke KAWAGUCHI */ public class SAXParserFactoryImpl extends SAXParserFactory { /** Actual SAXParserFactory implementation. */ private final SAXParserFactory core; /** JARV VerifierFactory implementation, which will be used to parse schemas. */ private final VerifierFactory jarvFactory; /** * JARV Schema object which is associated with this factory, or null. */ private Schema schema; /** * Creates a new instance by using the default SAXParserFactory implementation * as the underlying parser. This constructor does not set any schema. */ public SAXParserFactoryImpl() { this( SAXParserFactory.newInstance() ); } /** * Creates a new instance by specifying the underlying SAXParserFactory * implementation. This constructor does not set any schema. */ public SAXParserFactoryImpl( SAXParserFactory _factory ) { this(_factory,null); } /** * Creates a new instance by using a default SAXParserFactory implementation * and the specified schema object. */ public SAXParserFactoryImpl( Schema schema ) { this( SAXParserFactory.newInstance(), schema ); } /** * Creates a new instance that validates documents against the specified schema. */ public SAXParserFactoryImpl( java.io.File schemaAsFile ) throws VerifierConfigurationException, SAXException, IOException { this(); schema = jarvFactory.compileSchema(schemaAsFile); } /** * Creates a new instance that validates documents against the specified schema. */ public SAXParserFactoryImpl( org.xml.sax.InputSource _schema ) throws VerifierConfigurationException, SAXException, IOException { this(); schema = jarvFactory.compileSchema(_schema); } /** * Creates a new instance that validates documents against the specified schema. */ public SAXParserFactoryImpl( String schemaUrl ) throws VerifierConfigurationException, SAXException, IOException { this(); schema = jarvFactory.compileSchema(schemaUrl); } public SAXParserFactoryImpl( SAXParserFactory _factory, Schema _schema ) { this.core = _factory; // to make this factory work with JARV, configure it to namespace aware. core.setNamespaceAware(true); jarvFactory = new TheFactoryImpl(core); this.schema = _schema; } public boolean getFeature( String name ) throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException { if( name.equals(com.sun.msv.verifier.jarv.Const.PANIC_MODE_FEATURE) ) return jarvFactory.isFeature(name); return core.getFeature(name); } public void setFeature( String name, boolean value ) throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException { if( name.equals(com.sun.msv.verifier.jarv.Const.PANIC_MODE_FEATURE) ) jarvFactory.setFeature(name,value); core.setFeature(name,value); } public SAXParser newSAXParser() throws ParserConfigurationException, SAXException { try { return new SAXParserImpl(core.newSAXParser(),jarvFactory, (schema==null)?null:schema.newVerifier() ); } catch( VerifierConfigurationException e ) { throw new SAXException(e); } } public void setNamespaceAware( boolean awareness ) { core.setNamespaceAware(awareness); } public boolean isNamespaceAware() { return core.isNamespaceAware(); } public void setValidating( boolean validating ) { core.setValidating(validating); } public boolean isValidating() { return core.isValidating(); } } msv-2009.1/msv/src/com/sun/msv/verifier/jaxp/SAXParserImpl.java0000644000175000017500000000755107671170035024474 0ustar giovannigiovanni/* * @(#)$Id: SAXParserImpl.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.jaxp; import java.io.File; import java.io.InputStream; import javax.xml.parsers.SAXParser; import org.iso_relax.verifier.Schema; import org.iso_relax.verifier.Verifier; import org.iso_relax.verifier.VerifierFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLFilter; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderAdapter; /** * SAXParser implementation that supports validation. * *

        * This class uses another SAXParser implementation and * adds the validation capability to it. * * @author Kohsuke KAWAGUCHI */ class SAXParserImpl extends SAXParser { /** The underlying SAX parser. */ private final SAXParser core; /** * JARV verifier object that performs the validation for this SAXParserImpl. * This field is null when no schema is set. */ private Verifier verifier; /** A reference to VerifierFactory that can be used to parse a schema. */ private final VerifierFactory factory; SAXParserImpl( SAXParser core, VerifierFactory _jarvFactory, Verifier _verifier ) { this.core = core; this.factory = _jarvFactory; this.verifier = _verifier; } /** @deprecated */ public org.xml.sax.Parser getParser() throws SAXException { // maybe we should throw an UnsupportedOperationException, // rather than doing a trick like this. return new XMLReaderAdapter(getXMLReader()); } public Object getProperty( String name ) throws SAXNotRecognizedException, SAXNotSupportedException { return core.getProperty(name); } public void setProperty( String name, Object value ) throws SAXNotRecognizedException, SAXNotSupportedException { if( Const.SCHEMA_PROPNAME.equals(name) ) { try { if(value instanceof String) { verifier = factory.newVerifier( (String)value ); return; } if(value instanceof File) { verifier = factory.newVerifier( (File)value ); return; } if(value instanceof InputSource) { verifier = factory.newVerifier( (InputSource)value ); return; } if(value instanceof InputStream) { verifier = factory.newVerifier( (InputStream)value ); return; } if(value instanceof Schema) { verifier = ((Schema)value).newVerifier(); return; } throw new SAXNotSupportedException("unrecognized value type: "+value.getClass().getName() ); } catch( Exception e ) { // TODO: what is the correct exception type? throw new SAXNotRecognizedException(e.toString()); } } core.setProperty(name,value); } public XMLReader getXMLReader() throws SAXException { XMLReader reader = core.getXMLReader(); if(verifier==null) return reader; // no validation is necessary. XMLFilter filter = verifier.getVerifierFilter(); filter.setParent(reader); return filter; } public boolean isNamespaceAware() { return core.isNamespaceAware(); } public boolean isValidating() { return core.isValidating(); } } msv-2009.1/msv/src/com/sun/msv/verifier/jaxp/DocumentBuilderImpl.java0000644000175000017500000000710007671170035025737 0ustar giovannigiovanni/* * @(#)$Id: DocumentBuilderImpl.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.jaxp; import java.io.File; import java.io.IOException; import java.io.InputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; import org.iso_relax.verifier.Schema; import org.iso_relax.verifier.Verifier; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * DocumentBuilder implementation that supports validation. * *

        * This class uses another DocumentBuilder implementation and * adds the validation capability to it. * * @author Kohsuke KAWAGUCHI */ class DocumentBuilderImpl extends DocumentBuilder { /** * Wrapped DocumentBuilder that does everything else. */ private final DocumentBuilder core; /** * The validation will be performed using this verifier. */ private final Verifier verifier; DocumentBuilderImpl( DocumentBuilder _core, Schema _schema ) throws ParserConfigurationException { this.core = _core; try { verifier = _schema.newVerifier(); } catch( Exception e ) { // this will not happen with our implementation of JARV. throw new ParserConfigurationException(e.toString()); } // set an error handler to throw an exception in case of error. verifier.setErrorHandler( com.sun.msv.verifier.util.ErrorHandlerImpl.theInstance ); } public DOMImplementation getDOMImplementation() { return core.getDOMImplementation(); } public boolean isNamespaceAware() { return core.isNamespaceAware(); } public boolean isValidating() { return true; } public Document newDocument() { return core.newDocument(); } public Document parse( InputSource is ) throws SAXException, IOException { return verify(core.parse(is)); } public Document parse( File f ) throws SAXException, IOException { return verify(core.parse(f)); } public Document parse( InputStream is ) throws SAXException, IOException { return verify(core.parse(is)); } public Document parse( InputStream is, String systemId ) throws SAXException, IOException { return verify(core.parse(is,systemId)); } public Document parse( String url ) throws SAXException, IOException { return verify(core.parse(url)); } public void setEntityResolver( EntityResolver resolver ) { verifier.setEntityResolver(resolver); core.setEntityResolver(resolver); } public void setErrorHandler( ErrorHandler handler ) { verifier.setErrorHandler(handler); core.setErrorHandler(handler); } /** * Validates a given DOM and returns it if it is valid. Otherwise throw an exception. */ private Document verify( Document dom ) throws SAXException, IOException { if(verifier.verify(dom)) return dom; // the document is valid // this is strange because if any error happens, the error handler // will throw an exception. throw new SAXException("the document is invalid"); } } msv-2009.1/msv/src/com/sun/msv/verifier/ErrorInfo.java0000644000175000017500000001630007671170035022775 0ustar giovannigiovanni/* * @(#)$Id: ErrorInfo.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier; import com.sun.msv.util.StartTagInfo; /** * Instances of this class is attached to {@link ValidityViolation} to * provide detailed information about the error. * *

        * WARNING: error information is highly sensitive to the internal * change of MSV. A new subclass of ErrorInfo may be added, or * existing subclasses may be removed. * So your code that uses this information may be affected by * future changes of MSV. * * @author Kohsuke KAWAGUCHI */ public abstract class ErrorInfo { /** Base class for element related errors. */ public static abstract class ElementErrorInfo extends ErrorInfo { /** tag name information. */ public final String qName; public final String namespaceURI; public final String localName; public ElementErrorInfo( String qn, String ns, String loc ) { qName = qn; namespaceURI = ns; localName = loc; } public ElementErrorInfo( StartTagInfo sti ) { this( sti.qName, sti.namespaceURI, sti.localName ); } } /** * Bad text. * *

        * This type of errors indicate that the document contains PCDATA but it * is not good. Here are typical examples of this error. * *

        1. * PCDATA appears where no text is allowed at all. For example: * *
          
               * <html>
               *   <head> ... </head>
               *   ** invalid text **
               *   <body> ... </body>
               * </html>
               * 
          * *
        2. * text was not a correct value for the given datatype. For example, * *
          
               * <!-- when "integer" is expected -->
               * <length> five </length>
               * 
          * *
        * *

        * Usually, the user can fix this error by removing or chaning the text. * *

        * MSV validates text after it collects the whole string. That means * MSV does not validate text in the SAX's characters callback. * As a result, this error is reported after * the next start tag or end tag is found. * *

        * For example, in the above example, the error is reported when MSV * reads <body>(start tag) and * </length> (end tag) respectively. */ public static class BadText extends ErrorInfo { /** The actual text that caused the error. */ public final String literal; public BadText( String _literal ) { literal = _literal; } public BadText( StringBuffer _literal ) { literal = _literal.toString(); } } /** * Bad tag name. * *

        * This type of error occurs when MSV finds an unexpected tag name. * For example: * *

        1. * When a tag name appears where it is not valid to appear. *
          
               * <html>
               *   <head> ... </head>
               *   <head> ... </head> <!-- head cannot appear here -->
               *   <body> ... </body>
               * </html>
               * </pre>
               * 
               * 
        2. * When there is a typo in the tag name. *
          
               * <html>
               *   <heed> ... </heed> <!-- typo -->
               *   <body> ... </body>
               * </pre>
               * 
               * 
        3. * When an element appears where no element is allowed at all. *
          
               * <html>
               *   <head>
               *     <meta ...>
               *       <junk/>   <!-- meta cannot have any children -->
               * 
          * *
        * *

        * This error is reported when the startElement callback is called. */ public static class BadTagName extends ElementErrorInfo { public BadTagName( String qn, String ns, String loc ) { super(qn,ns,loc); } public BadTagName( StartTagInfo sti ) { super(sti); } } /** * Bad attribute. * *

        * This is an error when the attribute name is wrong, or the attribute value * is wrong. For example: * *

        1. * When MSV sees an unexpected attribute name: *
          
               * <img hreeef="logo.gif"/>
               * 
               * 
               * 
        2. * When an attribute value does not match the specified datatype. * For example, the following document causes this error if the "width" * attribute is specified as the int type. * *
          
               * <img href="logo.gif" width="twenty four pixels" />
               * 
          * *
        * *

        * This error is reported in the startElement callback. * *

        * Currently, the application cannot easily distinguish whether * this error is caused by an invalid attribute value, or invalid * attribute name. It is also non-trivial for MSV to detect this difference * correctly. But there maybe applications to which this difference is * important. * I welcome any comments on this issue. * */ public static class BadAttribute extends ElementErrorInfo { /** information about the attribute that caused the error. */ public final String attQName; public final String attNamespaceURI; public final String attLocalName; public final String attValue; protected BadAttribute( StartTagInfo sti, String qn, String ns, String loc, String v ) { super(sti); attQName = qn; attNamespaceURI = ns; attLocalName = loc; attValue = v; } } /** * Missing attribute. * *

        * This type of error occurs only when required attributes are missing. * Note that the fields of this class provide information about the element, * not the attribute which is missing. * *

        
             * <img/>  <!-- where is the href attribute? -->
             * 
        */ public static class MissingAttribute extends ElementErrorInfo { public MissingAttribute( String qn, String ns, String loc ) { super(qn,ns,loc); } public MissingAttribute( StartTagInfo sti ) { super(sti); } } /** * This error occurs when MSV sees an end tag unexpectedly. For example: * *
        
             * <html>
             *   <head> ... </head>
             * </html>  <!-- where is the body element? -->
             * 
        * *

        * Usually, this means that additional elements and/or PCDATA are necessary * to make the document valid. * *

        * Fields of the class provide information about enclosing tag. (In case of * the above example, it is html.) */ public static class IncompleteContentModel extends ElementErrorInfo { public IncompleteContentModel( String qn, String ns, String loc ) { super(qn,ns,loc); } public IncompleteContentModel( StartTagInfo sti ) { super(sti); } } } msv-2009.1/msv/src/com/sun/msv/verifier/identity/0000755000175000017500000000000011622453067022056 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/verifier/identity/PathMatcher.java0000644000175000017500000002236407671170035025130 0ustar giovannigiovanni/* * @(#)$Id: PathMatcher.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.identity; import org.relaxng.datatype.Datatype; import org.xml.sax.SAXException; import com.sun.msv.grammar.xmlschema.XPath; /** * Base implementation of XPath matching engine. * * It only supports the subset defined in XML Schema Part 1. Extra care * must be taken to call the testInitialMatch method after the creation of an object. * * Match to an attribute is not supported. It is implemented in FieldPathMatcher * class. * * The onMatched method is called when the specified XPath matches the current element. * Derived classes should implement this method to do something useful. * * @author Kohsuke KAWAGUCHI */ public abstract class PathMatcher extends MatcherBundle { protected PathMatcher( IDConstraintChecker owner, XPath[] paths ) { super(owner); children = new Matcher[paths.length]; for( int i=0; i * This class implements the matching engine for single * * "Path". * *

        * The outer PathMatcher uses multiple instances of this class * and thereby implements the matching engine for the whole "Selector". * *

        * This class only supports the subset defined in XML Schema Part 1. Extra care * must be taken to call the testInitialMatch method * after the creation of an object. * *

        * When a match is found, this class notifies the parent object by using a flag. * * */ private class SinglePathMatcher extends Matcher { /** * stores matched steps. * first dimension is expanded as the depth goes deep. * second dimension is always equal to the size of steps. */ private boolean[][] activeSteps; // private short currentDepth=0; protected final XPath path; /** * this flag is set to true when the path contains an attribute step * and the current element matches the element part of the path. * * When this flag is true, we need to honor the onAttribute event * and check if the path really matches to the attribute. */ private boolean elementMatched = false; protected SinglePathMatcher( XPath path ) { super(PathMatcher.this.owner); this.path = path; activeSteps = new boolean[4][]; /* activeSteps[i][0] is used to represent an implicit "root". For example, when XPath is "//A/B", [0]:root [1]:A [2]:B (initial state) 1 0 0 (1 indicates "active") [0] is initialized to 1. (startElement(X)) (step:1 shift to right) 1(*1) 1 0 *1 [0] will be populated by isAnyDescendant field. In this case, since isAnyDescendant ("//") is true, [0] is set to true after shift. This indicates that new element X can possibly be used as the implicit root. (step:2 perform name test) 1 0 0 root is excluded from the test. Since A doesn't match X, the corresponding field is set to false. (startElement(A)) (step:1 shift to right) 1 1 0 (step:2 perform name test) 1 1 0 (startElement(B)) (step:1 shift to right) 1 1 1 (step:2 perform name test) 1 0 1 (*2) *2 Now that the right most slot is true, this element B matches XPath. */ activeSteps[0] = new boolean[path.steps.length+1]; activeSteps[0][0] = true; // initialization // we only need an empty buffer for activeStep[0]. // other slots are filled on demand. if(path.steps.length==0) { // if the step is length 0, (that is, ".") // it is an immediate match. if( path.attributeStep==null ) // report to the parent PathMatcher that a match was found matchFound = true; else elementMatched = true; } } protected void startElement( String namespaceURI, String localName ) throws SAXException { elementMatched = false; // reset the flag. final int depth = getDepth(); if(depth==activeSteps.length-1) { // if the buffer is used up, expand buffer boolean[][] newBuf = new boolean[depth*2][]; System.arraycopy( activeSteps, 0, newBuf, 0, activeSteps.length ); activeSteps = newBuf; } // currentDepth++; int len = path.steps.length; boolean[] prvBuf = activeSteps[depth-1]; boolean[] curBuf = activeSteps[depth]; if(curBuf==null) activeSteps[depth]=curBuf=new boolean[len+1/*implicit root*/]; // shift to right if(len!=0) { System.arraycopy( prvBuf, 0, curBuf, 1, len ); curBuf[0] = path.isAnyDescendant; } // perform name test and deactivate unmatched steps for( int i=1; i<=len; i++ ) // exclude root from test. if( curBuf[i] && !path.steps[i-1].accepts(namespaceURI,localName) ) curBuf[i] = false; if( curBuf[len] ) { // this element matched this path if( path.attributeStep==null ) // report to the parent PathMatcher that a match was found matchFound = true; else elementMatched = true; } } protected void onAttribute( String namespaceURI, String localName, String value, Datatype type ) throws SAXException { // attribute step is not tested when the parent element doesn't match // the parent XPath expression. if( !elementMatched ) return; if( path.attributeStep.accepts(namespaceURI,localName) ) // report to the parent PathMatcher that a match was found matchFound = true; // keep the elementMatched flag as-is. } protected void endElement( Datatype dt ) { elementMatched = false; // reset the flag. // currentDepth--; } } } msv-2009.1/msv/src/com/sun/msv/verifier/identity/package.html0000644000175000017500000000013407300557307024335 0ustar giovannigiovanni

        Verifier with XML Schema's identity constraint check.

        msv-2009.1/msv/src/com/sun/msv/verifier/identity/FieldsMatcher.java0000644000175000017500000001022207671170035025430 0ustar giovannigiovanni/* * @(#)$Id: FieldsMatcher.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.identity; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.helpers.LocatorImpl; import com.sun.msv.grammar.xmlschema.KeyConstraint; import com.sun.msv.grammar.xmlschema.KeyRefConstraint; /** * Coordinator of FieldMatcher. * * This object is created when SelectorMatcher finds a match. * This object then creates FieldMatcher for each field, and * let them find their field matchs. * When leaving the element that matched the selector, it collects * field values and registers a key value to IDConstraintChecker. * *

        * Depending on the type of the constraint, it works differently. * * @author Kohsuke KAWAGUCHI */ public class FieldsMatcher extends MatcherBundle { /** * location of the start tag. * It is usually preferable as a source of error. */ protected final Locator startTag; /** * the parent SelectorMatcher. */ protected final SelectorMatcher selector; protected FieldsMatcher( SelectorMatcher selector, String namespaceURI, String localName ) throws SAXException { super(selector.owner); this.selector = selector; if(owner.getLocator()==null) this.startTag = null; else this.startTag = new LocatorImpl(owner.getLocator()); children = new Matcher[selector.idConst.fields.length]; for( int i=0; iKohsuke KAWAGUCHI */ public abstract class Matcher { protected final IDConstraintChecker owner; Matcher( IDConstraintChecker owner ) { this.owner = owner; } protected abstract void startElement( String namespaceURI, String localName ) throws SAXException; protected abstract void onAttribute( String namespaceURI, String localName, String value, Datatype type ) throws SAXException; protected abstract void endElement( Datatype type ) throws SAXException; protected void characters( char[] buf, int start, int len ) throws SAXException { // do nothing by default. } } msv-2009.1/msv/src/com/sun/msv/verifier/identity/KeyValue.java0000644000175000017500000000265307671170035024454 0ustar giovannigiovannipackage com.sun.msv.verifier.identity; /* * @(#)$Id: KeyValue.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ import org.xml.sax.Locator; import org.xml.sax.helpers.LocatorImpl; /** * represents multi-field keys. * * this class implements equality test and hash code based on * the equalities of each item. * * @author Kohsuke KAWAGUCHI */ class KeyValue { public final Object[] values; /** source location that this value is found. */ public final Locator locator; KeyValue( Object[] values, Locator loc ) { this.values = values; if(loc==null) this.locator = null; else this.locator = new LocatorImpl(loc); } public int hashCode() { int code = 0; for( int i=0; iKohsuke KAWAGUCHI */ public class FieldMatcher extends PathMatcher { protected Field field; /** * the matched value. If this field is null, then it means * nothing is matched yet. */ protected Object value; /** parent FieldsMatcher object. */ protected final FieldsMatcher parent; /** * this field is set to non-null if it's found that an element * is matched to this XPath. This field is then used to collect * the contents of the matched element until it encounters * the endElement method. */ protected StringBuffer elementText = null; FieldMatcher( FieldsMatcher parent, Field field, String namespaceURI, String localName ) throws SAXException { super( parent.owner, field.paths ); this.parent = parent; // test the initial match super.start(namespaceURI,localName); } /** * this method is called when the element matches the XPath. */ protected void onElementMatched( String namespaceURI, String localName ) throws SAXException { if( com.sun.msv.driver.textui.Debug.debug ) System.out.println("field match for "+ parent.selector.idConst.localName ); // this field matches this element. // wait for the corresponding endElement call and // obtain text. elementText = new StringBuffer(); } /** * this method is called when the attribute matches the XPath. */ protected void onAttributeMatched( String namespaceURI, String localName, String value, Datatype type ) throws SAXException { if( com.sun.msv.driver.textui.Debug.debug ) System.out.println("field match for "+ parent.selector.idConst.localName ); setValue( value, type ); } protected void startElement( String namespaceURI, String localName, Attributes attributes ) throws SAXException { if( elementText!=null ) { // this situation is an error because a matched element // cannot contain any child element. // But what I don't know is how to treat this situation. // 1. to make the document invalid? // 2. cancel the match? // the current implementation choose the 2nd. elementText = null; } super.startElement(namespaceURI,localName); } protected void endElement( Datatype type ) throws SAXException { super.endElement(type); // double match error is already checked in the corresponding // startElement method. if( elementText!=null ) { setValue( elementText.toString(), type ); elementText = null; } } protected void characters( char[] buf, int start, int len ) throws SAXException { super.characters(buf,start,len); if( elementText!=null ) // collect text elementText.append(buf,start,len); } /** sets the value field. */ private void setValue( String lexical, Datatype type ) throws SAXException { if(value!=null) { // not the first match. doubleMatchError(); return; } if(type==null) { // this is possible only when we are recovering from errors. value = lexical; if(com.sun.msv.driver.textui.Debug.debug) System.out.println("no type info available"); } else value = type.createValue(lexical,owner); } /** this field matches more than once. */ private void doubleMatchError() throws SAXException { int i; // compute the index number of this field. for( i=0; i * This class can be used in the same way as {@link Verifier}. * This class also checks XML Schema's identity constraint. * * @author Kohsuke KAWAGUCHI */ public class IDConstraintChecker extends Verifier { public IDConstraintChecker( XMLSchemaGrammar grammar, ErrorHandler errorHandler ) { super(new XSREDocDecl(grammar),errorHandler); this.grammar = grammar; } /** the grammar object against which we are validating. */ protected final XMLSchemaGrammar grammar; /** active mathcers. */ protected final Vector matchers = new Vector(); protected void add( Matcher matcher ) { matchers.add(matcher); } protected void remove( Matcher matcher ) { matchers.remove(matcher); } /** * a map from SelectorMatcher to set of KeyValues. * * One SelectorMatcher correponds to one scope of the identity constraint. */ private final Map keyValues = new java.util.HashMap(); /** * a map from keyref SelectorMatcher to key/unique * SelectorMatcher. * * Given a keyref scope, this map stores which key scope should it refer to. */ private final Map referenceScope = new java.util.HashMap(); /** * a map from IdentityConstraint to a LightStack of * SelectorMatcher. * * Each stack top keeps the currently active scope for the given IdentityConstraint. */ private final Map activeScopes = new java.util.HashMap(); protected SelectorMatcher getActiveScope( IdentityConstraint c ) { LightStack s = (LightStack)activeScopes.get(c); if(s==null) return null; if(s.size()==0) return null; return (SelectorMatcher)s.top(); } protected void pushActiveScope( IdentityConstraint c, SelectorMatcher matcher ) { LightStack s = (LightStack)activeScopes.get(c); if(s==null) activeScopes.put(c,s=new LightStack()); s.push(matcher); } protected void popActiveScope( IdentityConstraint c, SelectorMatcher matcher ) { LightStack s = (LightStack)activeScopes.get(c); if(s==null) // since it's trying to pop, there must be a non-empty stack. throw new Error(); if(s.pop()!=matcher) // trying to pop a non-active scope. throw new Error(); } /** * adds a new KeyValue to the value set. * @return true if this is a new value. */ protected boolean addKeyValue( SelectorMatcher scope, KeyValue value ) { Set keys = (Set)keyValues.get(scope); if(keys==null) keyValues.put(scope, keys = new java.util.HashSet()); return keys.add(value); } /** * gets the all KeyValues that were added within the specified scope. */ protected KeyValue[] getKeyValues( SelectorMatcher scope ) { Set keys = (Set)keyValues.get(scope); if(keys==null) return new KeyValue[0]; return (KeyValue[])keys.toArray(new KeyValue[keys.size()]); } public void startDocument() throws SAXException { super.startDocument(); keyValues.clear(); } public void endDocument() throws SAXException { super.endDocument(); // keyref check Map.Entry[] scopes = (Map.Entry[]) keyValues.entrySet().toArray(new Map.Entry[keyValues.size()]); if(com.sun.msv.driver.textui.Debug.debug) System.out.println("key/keyref check: there are "+keyValues.size()+" scope(s)"); for( int i=0; i=0; i-- ) { // Matcher may remove itself from the vector. // Therefore, to make it work correctly, we have to // enumerate Matcher in reverse direction. ((Matcher)matchers.get(i)).endElement( dt ); } } /** reports an error. */ protected void reportError( ErrorInfo ei, String propKey, Object[] args ) throws SAXException { // use the current location. reportError( getLocator(), ei, propKey, args ); } protected void reportError( Locator loc, ErrorInfo ei, String propKey, Object[] args ) throws SAXException { hadError = true; errorHandler.error( new ValidityViolation( loc, localizeMessage(propKey,args), ei ) ); } public static String localizeMessage( String propertyName, Object arg ) { return localizeMessage( propertyName, new Object[]{arg} ); } public static String localizeMessage( String propertyName, Object[] args ) { String format = java.util.ResourceBundle.getBundle( "com.sun.msv.verifier.identity.Messages").getString(propertyName); return java.text.MessageFormat.format(format, args ); } public static final String ERR_UNMATCHED_KEY_FIELD = "IdentityConstraint.UnmatchedKeyField"; // arg :3 public static final String ERR_NOT_UNIQUE = "IdentityConstraint.NotUnique"; // arg:2 public static final String ERR_NOT_UNIQUE_DIAG = "IdentityConstraint.NotUnique.Diag"; // arg:2 public static final String ERR_DOUBLE_MATCH = "IdentityConstraint.DoubleMatch"; // arg:3 public static final String ERR_UNDEFINED_KEY = "IdentityConstraint.UndefinedKey"; // arg:2 } msv-2009.1/msv/src/com/sun/msv/verifier/identity/SelectorMatcher.java0000644000175000017500000000460407671170035026011 0ustar giovannigiovanni/* * @(#)$Id: SelectorMatcher.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.identity; import org.relaxng.datatype.Datatype; import org.xml.sax.SAXException; import com.sun.msv.grammar.xmlschema.IdentityConstraint; /** * XPath matcher that tests the selector of an identity constraint. * * This object is created whenever an element with identity constraints is found. * XML Schema guarantees that we can see if an element has id constraints at the * startElement method. * * This mathcer then monitor startElement/endElement and find matches to the * specified XPath. Every time it finds a match ("target node" in XML Schema * terminology), it creates a FieldsMatcher. * * @author Kohsuke KAWAGUCHI */ public class SelectorMatcher extends PathMatcher { protected IdentityConstraint idConst; SelectorMatcher( IDConstraintChecker owner, IdentityConstraint idConst, String namespaceURI, String localName ) throws SAXException { super(owner, idConst.selectors ); this.idConst = idConst; // register this scope as active. owner.pushActiveScope(idConst,this); if(com.sun.msv.driver.textui.Debug.debug) { System.out.println("new id scope is available for {"+idConst.localName+"}"); } super.start(namespaceURI,localName); } protected void onRemoved() throws SAXException { super.onRemoved(); // this scope is no longer active. owner.popActiveScope(idConst,this); } protected void onElementMatched( String namespaceURI, String localName ) throws SAXException { if( com.sun.msv.driver.textui.Debug.debug ) System.out.println("find a match for a selector: "+idConst.localName); // this element matches the path. owner.add( new FieldsMatcher(this, namespaceURI,localName) ); } protected void onAttributeMatched( String namespaceURI, String localName, String value, Datatype type ) { // assertion failed: // selectors cannot contain attribute steps. throw new Error(); } } msv-2009.1/msv/src/com/sun/msv/verifier/identity/MatcherBundle.java0000644000175000017500000000455307671170035025445 0ustar giovannigiovanni/* * @(#)$Id: MatcherBundle.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.identity; import org.relaxng.datatype.Datatype; import org.xml.sax.SAXException; /** * Base implementation of Matcher coordinator. * * This class behaves as a parent of several other matchers, or as a composite * XPath matcher. * Those child matchers are not directly registered to IDConstraintChecker. * Instead, they receive notifications through this object. * * @author Kohsuke KAWAGUCHI */ class MatcherBundle extends Matcher { /** child matchers. */ protected Matcher[] children; /** depth. */ private int depth = 0; protected final int getDepth() { return depth; } /** * the derived class must initialize the children field appropriately. */ protected MatcherBundle( IDConstraintChecker owner ) { super(owner); } protected void startElement( String namespaceURI, String localName ) throws SAXException { depth++; for( int i=0; i *

      3. collecting ID/IDREFs. *
      4. storing Locator. * *

        * By setting performIDcheck variable, the ID/IDREF checking * can be either turned on or turned off. * * @author Kohsuke KAWAGUCHI */ public abstract class AbstractVerifier implements ContentHandler, DTDHandler, IDContextProvider2 { /** * Document Locator that is given by XML reader. * Sometimes it doesn't set the locator, so start with a dummy instance. */ protected Locator locator = dummyLocator; public final Locator getLocator() { return locator; } protected static final Locator dummyLocator = new LocatorImpl(); /** * set this flag to true to perform ID/IDREF validation. * this value cannot be modified in the middle of the validation. */ protected boolean performIDcheck = true; /** this map remembers every ID token encountered in this document */ protected final Map ids = new HashMap(); /** this map remembers every IDREF token encountered in this document */ protected final Set idrefs = new java.util.HashSet(); public void setDocumentLocator( Locator loc ) { this.locator = loc; } public void skippedEntity(String p) {} public void processingInstruction(String name,String data) {} private boolean contextPushed = false; public void startPrefixMapping( String prefix, String uri ) { if( !contextPushed ) { namespaceSupport.pushContext(); contextPushed = true; } namespaceSupport.declarePrefix( prefix, uri ); } public void endPrefixMapping( String prefix ) {} public void startElement( String namespaceUri, String localName, String qName, Attributes atts ) throws SAXException { if( !contextPushed ) namespaceSupport.pushContext(); contextPushed = false; } public void endElement( String namespaceUri, String localName, String qName ) throws SAXException { namespaceSupport.popContext(); } protected void init() { ids.clear(); idrefs.clear(); } public void notationDecl( String name, String publicId, String systemId ) { notations.add(name); } public void unparsedEntityDecl( String name, String publicId, String systemId, String notationName ) { // store name of unparsed entities to implement ValidationContextProvider unparsedEntities.add(name); } /** * namespace prefix to namespace URI resolver. * * this object memorizes mapping information. */ protected final NamespaceSupport namespaceSupport = new NamespaceSupport(); /** unparsed entities found in the document. */ private final Set unparsedEntities = new java.util.HashSet(); /** declared notations. */ private final Set notations = new java.util.HashSet(); // methods of ValidationContextProvider public String resolveNamespacePrefix(String prefix) { String uri = namespaceSupport.getURI(prefix); if(uri==null && prefix.length()==0) return ""; else return uri; } public boolean isUnparsedEntity(String entityName) { return unparsedEntities.contains(entityName); } public boolean isNotation(String notationName) { return notations.contains(notationName); } public String getBaseUri() { // TODO: Verifier should implement the base URI return null; } /** this method is called when a duplicate id value is found. */ protected abstract void onDuplicateId( String id ); public void onID(Datatype dt, StringToken token) { if (!performIDcheck) return; int idType = dt.getIdType(); if (idType == Datatype.ID_TYPE_ID) { String literal = token.literal.trim(); StringToken existing = (StringToken)ids.get(literal); if( existing==null ) { // the first tiem this ID is used ids.put(literal,token); } else if( existing!=token ) { // duplicate id value onDuplicateId(literal); } return; } if (idType == Datatype.ID_TYPE_IDREF) { idrefs.add(token.literal.trim()); return; } if (idType == Datatype.ID_TYPE_IDREFS) { StringTokenizer tokens = new StringTokenizer(token.literal); while (tokens.hasMoreTokens()) idrefs.add(tokens.nextToken()); return; } throw new Error(); // assertion failed. unknown Id type. } } msv-2009.1/msv/src/com/sun/msv/verifier/jarv/0000755000175000017500000000000011622453067021167 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/verifier/jarv/FactoryImpl.java0000644000175000017500000001211707671170035024265 0ustar giovannigiovanni/* * @(#)$Id: FactoryImpl.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.jarv; import java.io.IOException; import javax.xml.parsers.SAXParserFactory; import org.iso_relax.verifier.Schema; import org.iso_relax.verifier.VerifierConfigurationException; import org.iso_relax.verifier.VerifierFactory; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.SAXParseException; import com.sun.msv.grammar.Grammar; import com.sun.msv.grammar.xmlschema.XMLSchemaGrammar; import com.sun.msv.reader.GrammarReaderController; import com.sun.msv.verifier.IVerifier; import com.sun.msv.verifier.identity.IDConstraintChecker; import com.sun.msv.verifier.regexp.REDocumentDeclaration; import com.sun.msv.verifier.util.ErrorHandlerImpl; /** * base implementation of RELAXFactoryImpl and TREXFactoryImpl * * @author Kohsuke KAWAGUCHI */ public abstract class FactoryImpl extends VerifierFactory { protected final SAXParserFactory factory; protected FactoryImpl( SAXParserFactory factory ) { this.factory = factory; } protected FactoryImpl() { factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); } private boolean usePanicMode = true; public void setFeature( String feature, boolean v ) throws SAXNotRecognizedException,SAXNotSupportedException { if(feature.equals(Const.PANIC_MODE_FEATURE)) usePanicMode = v; else super.setFeature(feature,v); } public boolean isFeature( String feature ) throws SAXNotRecognizedException,SAXNotSupportedException { if(feature.equals(Const.PANIC_MODE_FEATURE)) return usePanicMode; else return super.isFeature(feature); } /** * To be used to resolve files included/imported by the schema. Can be null. */ private EntityResolver resolver; public void setEntityResolver( EntityResolver _resolver ) { this.resolver = _resolver; } public EntityResolver getEntityResolver() { return resolver; } /** * parses a Grammar from the specified source. * return null if an error happens. */ protected abstract Grammar parse( InputSource source, GrammarReaderController controller ) throws SAXException,VerifierConfigurationException; public Schema compileSchema( InputSource source ) throws VerifierConfigurationException, SAXException { try { Grammar g = parse(source,new ThrowController()); if(g==null) // theoretically this isn't possible because we throw an exception // if an error happens. throw new VerifierConfigurationException("unable to parse the schema"); return new SchemaImpl(g,factory,usePanicMode); } catch( WrapperException we ) { throw we.e; } catch( Exception pce ) { throw new VerifierConfigurationException(pce); } } /** * gets the VGM by sniffing its type. * *

        * To validate XML Schema correctly, we need to use the specialized VGM. */ static IVerifier createVerifier( Grammar g ) { if( g instanceof XMLSchemaGrammar ) return new IDConstraintChecker( (XMLSchemaGrammar)g, new ErrorHandlerImpl() ); else return new com.sun.msv.verifier.Verifier( new REDocumentDeclaration(g), new ErrorHandlerImpl() ); } /** wrapper exception so that we can throw it from the GrammarReaderController. */ private static class WrapperException extends RuntimeException { WrapperException( SAXException e ) { super(e.getMessage()); this.e = e; } public final SAXException e; } private class ThrowController implements GrammarReaderController { public void warning( Locator[] locs, String errorMessage ) {} public void error( Locator[] locs, String errorMessage, Exception nestedException ) { for( int i=0; iKohsuke KAWAGUCHI */ public class SchemaImpl implements Schema { protected final Grammar grammar; protected final SAXParserFactory factory; protected SchemaImpl( Grammar grammar, SAXParserFactory factory, boolean _usePanicMode ) { this.grammar = grammar; this.factory = factory; this.usePanicMode = _usePanicMode; } public SchemaImpl( Grammar grammar ) { this.grammar = grammar; this.factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); this.usePanicMode = false; } public Verifier newVerifier() throws VerifierConfigurationException { IVerifier core = FactoryImpl.createVerifier(grammar); core.setPanicMode(usePanicMode); return new VerifierImpl( core, createXMLReader() ); } private synchronized XMLReader createXMLReader() throws VerifierConfigurationException { // SAXParserFactory is not thread-safe. Thus we need to // synchronize this method. try { return factory.newSAXParser().getXMLReader(); } catch( SAXException e ) { throw new VerifierConfigurationException(e); } catch( ParserConfigurationException e ) { throw new VerifierConfigurationException(e); } } private boolean usePanicMode; } msv-2009.1/msv/src/com/sun/msv/verifier/jarv/Const.java0000644000175000017500000000204307376262066023127 0ustar giovannigiovanni/* * @(#)$Id: Const.java 1316 2001-11-19 19:57:42Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.jarv; /** * Constant values related to JARV. * * @author Kohsuke KAWAGUCHI */ public class Const { /** * Turns on/off the panic mode. *

        * Panic mode is on by default. Turning it on is good * for general use. It prevents false error messages to appear. *

        * However, turning it off is sometimes useful, when * you are sure that the structure of the document is * almost valid (e.g., validating a document generated by an * application or when you are sure about the validity of the * structure and only interested in validating datatypes,) */ public static final String PANIC_MODE_FEATURE = "http://www.sun.com/xmlns/msv/features/panicMode"; } msv-2009.1/msv/src/com/sun/msv/verifier/jarv/XSFactoryImpl.java0000644000175000017500000000145707671170035024545 0ustar giovannigiovanni/* * @(#)$Id: XSFactoryImpl.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.jarv; import org.xml.sax.InputSource; import com.sun.msv.grammar.Grammar; import com.sun.msv.reader.GrammarReaderController; import com.sun.msv.reader.xmlschema.XMLSchemaReader; /** * VerifierFactory implementation for XML Schema. * * @author Kohsuke KAWAGUCHI */ public class XSFactoryImpl extends FactoryImpl { protected Grammar parse( InputSource is, GrammarReaderController controller ) { return XMLSchemaReader.parse(is,factory,controller); } } msv-2009.1/msv/src/com/sun/msv/verifier/jarv/package.html0000644000175000017500000000027207254037330023446 0ustar giovannigiovanni

        Implementation of JARV (Java API for RELAX Verifier).

        msv-2009.1/msv/src/com/sun/msv/verifier/jarv/TREXFactoryImpl.java0000644000175000017500000000146307671170035024772 0ustar giovannigiovanni/* * @(#)$Id: TREXFactoryImpl.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.jarv; import org.xml.sax.InputSource; import com.sun.msv.grammar.Grammar; import com.sun.msv.reader.GrammarReaderController; import com.sun.msv.reader.trex.classic.TREXGrammarReader; /** * VerifierFactory implementation for TREX. * * @author Kohsuke KAWAGUCHI */ public class TREXFactoryImpl extends FactoryImpl { protected Grammar parse( InputSource is, GrammarReaderController controller ) { return TREXGrammarReader.parse(is,factory,controller); } } msv-2009.1/msv/src/com/sun/msv/verifier/jarv/VerifierImpl.java0000644000175000017500000000234707671170035024435 0ustar giovannigiovanni/* * @(#)$Id: VerifierImpl.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.jarv; import org.iso_relax.verifier.VerifierConfigurationException; import org.iso_relax.verifier.VerifierHandler; import org.xml.sax.ErrorHandler; import org.xml.sax.XMLReader; import com.sun.msv.verifier.IVerifier; /** * Verifier implementation. * * @author Kohsuke KAWAGUCHI */ class VerifierImpl extends org.iso_relax.verifier.impl.VerifierImpl { private final IVerifier verifier; VerifierImpl( IVerifier verifier, XMLReader reader ) throws VerifierConfigurationException { this.verifier = verifier; super.reader = reader; } // we obtain XMLReader through the constructor. protected void prepareXMLReader() {} public void setErrorHandler( ErrorHandler handler ) { super.setErrorHandler(handler); verifier.setErrorHandler(handler); } public VerifierHandler getVerifierHandler() { return verifier; } } msv-2009.1/msv/src/com/sun/msv/verifier/jarv/FactoryLoaderImpl.java0000644000175000017500000000303007671170035025406 0ustar giovannigiovannipackage com.sun.msv.verifier.jarv; import org.iso_relax.verifier.VerifierFactory; import org.iso_relax.verifier.VerifierFactoryLoader; import com.sun.msv.reader.relax.core.RELAXCoreReader; import com.sun.msv.reader.trex.classic.TREXGrammarReader; import com.sun.msv.reader.trex.ng.RELAXNGReader; import com.sun.msv.reader.xmlschema.XMLSchemaReader; import com.sun.msv.relaxns.reader.RELAXNSReader; public class FactoryLoaderImpl implements VerifierFactoryLoader { public FactoryLoaderImpl() { } public VerifierFactory createFactory(String language) { // supported language if (language.equals(RELAXNGReader.RELAXNGNamespace)) return new RELAXNGFactoryImpl(); if (language.equals(RELAXCoreReader.RELAXCoreNamespace)) return new RELAXCoreFactoryImpl(); if (language.equals(TREXGrammarReader.TREXNamespace)) return new TREXFactoryImpl(); if (language.equals(XMLSchemaReader.XMLSchemaNamespace) || language.equals(XMLSchemaReader.XMLSchemaNamespace_old)) return new XSFactoryImpl(); if(language.equals(RELAXNSReader.RELAXNamespaceNamespace)) return new TheFactoryImpl(); if(language.equals("http://www.w3.org/XML/1998/namespace")) return new DTDFactoryImpl(); // backward compatibility if (language.equals("relax")) return new TheFactoryImpl(); if (language.toUpperCase().equals("DTD")) return new DTDFactoryImpl(); return null; } } msv-2009.1/msv/src/com/sun/msv/verifier/jarv/RELAXCoreFactoryImpl.java0000644000175000017500000000157407671170035025677 0ustar giovannigiovanni/* * @(#)$Id: RELAXCoreFactoryImpl.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.jarv; import org.xml.sax.InputSource; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.Grammar; import com.sun.msv.reader.GrammarReaderController; import com.sun.msv.reader.relax.core.RELAXCoreReader; /** * VerifierFactory implementation of RELAX Core. * * @author Kohsuke KAWAGUCHI */ public class RELAXCoreFactoryImpl extends FactoryImpl { protected Grammar parse( InputSource is, GrammarReaderController controller ) { return RELAXCoreReader.parse(is,factory,controller,new ExpressionPool()); } } msv-2009.1/msv/src/com/sun/msv/verifier/jarv/RELAXNGFactoryImpl.java0000644000175000017500000000367607671170035025320 0ustar giovannigiovanni/* * @(#)$Id: RELAXNGFactoryImpl.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.jarv; import org.relaxng.datatype.DatatypeLibraryFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import com.sun.msv.grammar.Grammar; import com.sun.msv.reader.GrammarReaderController; import com.sun.msv.reader.trex.ng.RELAXNGReader; /** * VerifierFactory implementation of RELAX NG. * * This implementation supports the "datatypeLibraryFactory" property * which configures RELAX NG parser with a datatype library factory. * * @author Kohsuke KAWAGUCHI */ public class RELAXNGFactoryImpl extends FactoryImpl { private DatatypeLibraryFactory datatypeLibraryFactory = null; private static final String PROP_NAME = "datatypeLibraryFactory"; protected Grammar parse( InputSource is, GrammarReaderController controller ) { RELAXNGReader reader = new RELAXNGReader(controller,factory); if( datatypeLibraryFactory!=null ) reader.setDatatypeLibraryFactory(datatypeLibraryFactory); reader.parse(is); return reader.getResult(); } public Object getProperty(String name) throws SAXNotRecognizedException, SAXNotSupportedException { if( name.equals(PROP_NAME) ) return datatypeLibraryFactory; return super.getProperty(name); } public void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException { if( name.equals(PROP_NAME) ) { datatypeLibraryFactory = (DatatypeLibraryFactory)value; return; } super.setProperty(name, value); } } msv-2009.1/msv/src/com/sun/msv/verifier/jarv/TheFactoryImpl.java0000644000175000017500000000314607671167271024740 0ustar giovannigiovanni/* * @(#)$Id: TheFactoryImpl.java 1565 2003-06-09 20:31:53Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.jarv; import javax.xml.parsers.SAXParserFactory; import org.iso_relax.verifier.VerifierConfigurationException; import org.xml.sax.InputSource; import com.sun.msv.grammar.Grammar; import com.sun.msv.reader.GrammarReaderController; import com.sun.msv.reader.util.GrammarLoader; /** * VerifierFactory implementation that automatically detects the schema language. * * To use this class, see * * @author Kohsuke KAWAGUCHI */ public class TheFactoryImpl extends FactoryImpl { public TheFactoryImpl(SAXParserFactory factory) { super(factory); } /** * use the default SAXParser. */ public TheFactoryImpl() { super(); } protected Grammar parse(InputSource is, GrammarReaderController controller) throws VerifierConfigurationException { try { return GrammarLoader.loadSchema(is, controller, factory); } catch (Exception e) { throw new VerifierConfigurationException(e); } } protected Grammar parse(String source, GrammarReaderController controller) throws VerifierConfigurationException { try { return GrammarLoader.loadSchema(source, controller, factory); } catch (Exception e) { throw new VerifierConfigurationException(e); } } } msv-2009.1/msv/src/com/sun/msv/verifier/Verifier.java0000644000175000017500000004230510012547060022634 0ustar giovannigiovanni/* * @(#)$Id: Verifier.java 1631 2004-02-12 00:52:00Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier; import java.util.Iterator; import java.util.Set; import org.relaxng.datatype.Datatype; import org.xml.sax.Attributes; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import com.sun.msv.datatype.xsd.StringType; import com.sun.msv.grammar.IDContextProvider2; import com.sun.msv.util.DatatypeRef; import com.sun.msv.util.StartTagInfo; import com.sun.msv.util.StringRef; /** * SAX ContentHandler that verifies incoming SAX event stream. * * This object can be reused to validate multiple documents. * Just be careful NOT to use the same object to validate more than one * documents at the same time. * * @author Kohsuke KAWAGUCHI */ public class Verifier extends AbstractVerifier implements IVerifier { protected Acceptor current; private static final class Context { final Context previous; final Acceptor acceptor; final int stringCareLevel; int panicLevel; Context(Context prev, Acceptor acc, int scl, int plv) { previous = prev; acceptor = acc; stringCareLevel = scl; panicLevel = plv; } }; /** context stack */ Context stack = null; /** current string care level. See Acceptor.getStringCareLevel */ private int stringCareLevel = Acceptor.STRING_STRICT; /** characters that were read (but not processed) */ private StringBuffer text = new StringBuffer(); /** Error handler */ protected ErrorHandler errorHandler; public final ErrorHandler getErrorHandler() { return errorHandler; } public final void setErrorHandler(ErrorHandler handler) { this.errorHandler = handler; } /** This flag will be set to true if an error is found */ protected boolean hadError; /** This flag will be set to true after endDocument method is called. */ private boolean isFinished; /** An object used to store start tag information. * the same object is reused. */ private final StartTagInfo sti = new StartTagInfo(null, null, null, null, (IDContextProvider2)null); public final boolean isValid() { return !hadError && isFinished; } /** Schema object against which the validation will be done */ protected final DocumentDeclaration docDecl; /** * Panic level. * * If the level is non-zero, createChildAcceptors will silently recover * from error. This effectively suppresses spurious error messages. * * This value is set to INITIAL_PANIC_LEVEL when first an error is encountered, * and is decreased by successful stepForward and createChildAcceptor. * This value is also propagated to child acceptors. */ protected int panicLevel = 0; /** * Initial panic level when an error is found. * If this value is bigger, MSV will take more time to recover from errors, * Setting this value to 0 means turning the panic mode off entirely. */ private int initialPanicLevel = DEFAULT_PANIC_LEVEL; private static final int DEFAULT_PANIC_LEVEL = 3; public final void setPanicMode( boolean usePanicMode ) { initialPanicLevel = usePanicMode?DEFAULT_PANIC_LEVEL:0; } public Verifier(DocumentDeclaration documentDecl, ErrorHandler errorHandler) { this.docDecl = documentDecl; this.errorHandler = errorHandler; } /** this field is used to receive type information of character literals. */ private final DatatypeRef characterType = new DatatypeRef(); public Datatype[] getLastCharacterType() { return characterType.types; } protected void verifyText() throws SAXException { characterType.types = null; switch (stringCareLevel) { case Acceptor.STRING_PROHIBITED : // only whitespace is allowed. final int len = text.length(); for (int i = 0; i < len; i++) { final char ch = text.charAt(i); if (ch != ' ' && ch != '\t' && ch != '\r' && ch != '\n') { // error onError(null, localizeMessage(ERR_UNEXPECTED_TEXT, null), new ErrorInfo.BadText(text)); break; // recover by ignoring this token } } break; case Acceptor.STRING_STRICT : final String txt = new String(text); if (!current.onText2(txt, this, null, characterType)) { // error // diagnose error, if possible StringRef err = new StringRef(); characterType.types = null; current.onText2(txt, this, err, characterType); // report an error onError(err, localizeMessage(ERR_UNEXPECTED_TEXT, null), new ErrorInfo.BadText(text)); } break; case Acceptor.STRING_IGNORE : // if STRING_IGNORE, no text should be appended. if (text.length() != 0) throw new Error(); return; default : throw new Error(); //assertion failed } if (text.length() != 0) text = new StringBuffer(); } public void startElement(String namespaceUri, String localName, String qName, Attributes atts) throws SAXException { // work gracefully with misconfigured parsers that don't support namespaces, // or other sources that produce broken SAX events. if( namespaceUri==null ) namespaceUri=""; if( localName==null || localName.length()==0 ) localName=qName; if( qName==null || qName.length()==0 ) qName=localName; super.startElement(namespaceUri, localName, qName, atts); if (com.sun.msv.driver.textui.Debug.debug) System.out.println( "\n-- startElement(" + qName + ")" + locator.getLineNumber() + ":" + locator.getColumnNumber()); verifyText(); // verify PCDATA first. // push context stack = new Context(stack, current, stringCareLevel, panicLevel); sti.reinit(namespaceUri, localName, qName, atts, this); // get Acceptor that will be used to validate the contents of this element. Acceptor next = current.createChildAcceptor(sti, null); panicLevel = Math.max(panicLevel - 1, 0); if (next == null) { // no child element matchs this one if (com.sun.msv.driver.textui.Debug.debug) System.out.println("-- no children accepted: error recovery"); // let acceptor recover from this error. StringRef ref = new StringRef(); next = current.createChildAcceptor(sti, ref); ValidityViolation vv = onError( ref, localizeMessage(ERR_UNEXPECTED_STARTTAG, new Object[] { qName }), new ErrorInfo.BadTagName(sti)); if (next == null) { if (com.sun.msv.driver.textui.Debug.debug) System.out.println("-- unable to recover"); throw new ValidationUnrecoverableException(vv); } } onNextAcceptorReady(sti, next); // feed attributes final int len = atts.getLength(); for (int i = 0; i < len; i++) feedAttribute(next, atts.getURI(i), atts.getLocalName(i), atts.getQName(i), atts.getValue(i)); // call the endAttributes if (!next.onEndAttributes(sti, null)) { // error. if (com.sun.msv.driver.textui.Debug.debug) System.out.println("-- required attributes missing: error recovery"); // let the acceptor recover from the error. StringRef ref = new StringRef(); next.onEndAttributes(sti, ref); onError( ref, localizeMessage(ERR_MISSING_ATTRIBUTE, new Object[] { qName }), new ErrorInfo.MissingAttribute(sti)); } stack.panicLevel = panicLevel; // back-patching. stringCareLevel = next.getStringCareLevel(); if (stringCareLevel == Acceptor.STRING_IGNORE) characterType.types = new Datatype[] { StringType.theInstance }; current = next; } /** * this method is called from the startElement method * after the tag name is processed and the child acceptor is created. * *

        * This method is called before the attributes are consumed. * *

        * derived class can use this method to do something useful. */ protected void onNextAcceptorReady(StartTagInfo sti, Acceptor nextAcceptor) throws SAXException { } /** * the same instance is reused by the feedAttribute method to reduce * the number of the object creation. */ private final DatatypeRef attributeType = new DatatypeRef(); protected Datatype[] feedAttribute(Acceptor child, String uri, String localName, String qName, String value) throws SAXException { // work gracefully with misconfigured parsers that don't support namespaces, // or other sources that produce broken SAX events. if( uri==null ) uri=""; if( localName==null || localName.length()==0 ) localName=qName; if( qName==null || qName.length()==0 ) qName=localName; // ignore xmlns:* attributes, which could be a part of Attributes // in some SAX events. if( qName.startsWith("xmlns:") || qName.equals("xmlns") ) return new Datatype[0]; if (com.sun.msv.driver.textui.Debug.debug) System.out.println("-- processing attribute: @" + qName); attributeType.types = null; if (!child.onAttribute2(uri, localName, qName, value, this, null, attributeType)) { // error if (com.sun.msv.driver.textui.Debug.debug) System.out.println("-- bad attribute: error recovery"); // let the acceptor recover from the error. StringRef ref = new StringRef(); child.onAttribute2(uri, localName, qName, value, this, ref, null); onError( ref, localizeMessage(ERR_UNEXPECTED_ATTRIBUTE, new Object[] { qName }), new ErrorInfo.BadAttribute(sti, qName, uri, localName, value)); } return attributeType.types; } public void endElement(String namespaceUri, String localName, String qName) throws SAXException { // work gracefully with misconfigured parsers that don't support namespaces, // or other sources that produce broken SAX events. if( namespaceUri==null ) namespaceUri=""; if( localName==null || localName.length()==0 ) localName=qName; if( qName==null || qName.length()==0 ) qName=localName; if (com.sun.msv.driver.textui.Debug.debug) System.out.println( "\n-- endElement(" + qName + ")" + locator.getLineNumber() + ":" + locator.getColumnNumber()); verifyText(); if (!current.isAcceptState(null) && panicLevel == 0) { // error diagnosis StringRef errRef = new StringRef(); current.isAcceptState(errRef); onError( errRef, localizeMessage(ERR_UNCOMPLETED_CONTENT, new Object[] { qName }), new ErrorInfo.IncompleteContentModel(qName, namespaceUri, localName)); // error recovery: pretend as if this state is satisfied // fall through is enough } Acceptor child = current; // pop context current = stack.acceptor; stringCareLevel = stack.stringCareLevel; panicLevel = Math.max(panicLevel, stack.panicLevel); stack = stack.previous; if (!current.stepForward(child, null)) { // error StringRef ref = new StringRef(); current.stepForward(child, ref); // force recovery onError(ref, localizeMessage(ERR_UNEXPECTED_ELEMENT, new Object[] { qName }), null); } else panicLevel = Math.max(panicLevel - 1, 0); super.endElement(namespaceUri, localName, qName); } /** * signals an error. * * This method can be overrided by the derived class to provide different behavior. */ protected ValidityViolation onError(StringRef ref, String defaultMsg, ErrorInfo ei) throws SAXException { if (ref == null) return onError(defaultMsg, ei); if (ref.str == null) return onError(defaultMsg, ei); else return onError(ref.str, ei); } protected ValidityViolation onError(String msg, ErrorInfo ei) throws SAXException { ValidityViolation vv = new ValidityViolation(locator, msg, ei); hadError = true; if (errorHandler != null && panicLevel == 0) errorHandler.error(vv); panicLevel = initialPanicLevel; return vv; } public Object getCurrentElementType() { return current.getOwnerType(); } public void characters(char[] buf, int start, int len) throws SAXException { if (stringCareLevel != Acceptor.STRING_IGNORE) text.append(buf, start, len); } public void ignorableWhitespace(char[] buf, int start, int len) throws SAXException { if (stringCareLevel != Acceptor.STRING_IGNORE && stringCareLevel != Acceptor.STRING_PROHIBITED) // white space is allowed even if the current mode is STRING_PROHIBITED. text.append(buf, start, len); } protected void init() { super.init(); hadError = false; isFinished = false; text = new StringBuffer(); stack = null; if (duplicateIds != null) duplicateIds.clear(); } public void startDocument() throws SAXException { // reset everything. // since Verifier maybe reused, initialization is better done here // rather than constructor. init(); // if Verifier is used without "divide&validate", // this method is called and the initial acceptor // is set by this method. // When Verifier is used in IslandVerifierImpl, // then initial acceptor is set at the constructor // and this method is not called. current = docDecl.createAcceptor(); } public void endDocument() throws SAXException { // ID/IDREF check if (performIDcheck) { if (!ids.keySet().containsAll(idrefs)) { hadError = true; Iterator itr = idrefs.iterator(); while (itr.hasNext()) { Object idref = itr.next(); if (!ids.keySet().contains(idref)) onError(localizeMessage(ERR_UNSOLD_IDREF, new Object[] { idref }), null); } } if (duplicateIds != null) { Iterator itr = duplicateIds.iterator(); while (itr.hasNext()) { Object id = itr.next(); onError(localizeMessage(ERR_DUPLICATE_ID, new Object[] { id }), null); } } } isFinished = true; } /** * Stores all duplicate id values. * Errors are reported at the endDocument method because * the onDuplicateId method cannot throw an exception. */ private Set duplicateIds; public void onDuplicateId(String id) { if (duplicateIds == null) duplicateIds = new java.util.HashSet(); duplicateIds.add(id); } public static String localizeMessage(String propertyName, Object[] args) { String format = java.util.ResourceBundle.getBundle("com.sun.msv.verifier.Messages").getString(propertyName); return java.text.MessageFormat.format(format, args); } public static final String ERR_UNEXPECTED_TEXT = // arg:0 "Verifier.Error.UnexpectedText"; public static final String ERR_UNEXPECTED_ATTRIBUTE = // arg:1 "Verifier.Error.UnexpectedAttribute"; public static final String ERR_MISSING_ATTRIBUTE = // arg:1 "Verifier.Error.MissingAttribute"; public static final String ERR_UNEXPECTED_STARTTAG = // arg:1 "Verifier.Error.UnexpectedStartTag"; public static final String ERR_UNCOMPLETED_CONTENT = // arg:1 "Verifier.Error.UncompletedContent"; public static final String ERR_UNEXPECTED_ELEMENT = // arg:1 "Verifier.Error.UnexpectedElement"; public static final String ERR_UNSOLD_IDREF = // arg:1 "Verifier.Error.UnsoldIDREF"; public static final String ERR_DUPLICATE_ID = // arg:1 "Verifier.Error.DuplicateId"; } msv-2009.1/msv/src/com/sun/msv/verifier/ValidityViolation.java0000644000175000017500000000220707671170035024543 0ustar giovannigiovanni/* * @(#)$Id: ValidityViolation.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier; import org.xml.sax.Locator; import org.xml.sax.SAXParseException; /** * Contains information about where and how validity violation was happened. * * @author Kohsuke KAWAGUCHI */ public class ValidityViolation extends SAXParseException { private ErrorInfo errorInfo; /** * Gets the detailed error information, if any. * * If there is no detailed information available, it returns null. * Otherwise one of the derived classes of ErrorInfo will be returned. */ public ErrorInfo getErrorInfo() { return errorInfo; } public ValidityViolation( Locator loc, String msg, ErrorInfo ei ) { super( msg, loc ); this.errorInfo = ei; } /* public ValidityViolation( Locator loc, String msg ) { this( msg, loc, null ); } */ } msv-2009.1/msv/src/com/sun/msv/verifier/regexp/0000755000175000017500000000000011622453067021517 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/verifier/regexp/AttributePicker.java0000644000175000017500000001057107671170035025467 0ustar giovannigiovanni/* * @(#)$Id: AttributePicker.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.regexp; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.ChoiceExp; import com.sun.msv.grammar.ConcurExp; import com.sun.msv.grammar.DataExp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.ExpressionVisitorExpression; import com.sun.msv.grammar.InterleaveExp; import com.sun.msv.grammar.ListExp; import com.sun.msv.grammar.MixedExp; import com.sun.msv.grammar.OneOrMoreExp; import com.sun.msv.grammar.OtherExp; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.SequenceExp; import com.sun.msv.grammar.ValueExp; /** * removes all unnecessary expressions and * creates an expression that consists of required attributes and choices only. * *

        * For example, * * <choice> * <element /> * <attribute /> * </choice> * * will be converted to * * <empty /> * * because no attribute is required. But * * <choice> * <attribute /> * <attribute /> * </choice> * * will remain the same because one or the other is required. * * this method also removes SequenceExp. * * <sequence> * <attribute name="A" /> * <attribute name="B" /> * </sequence> * * will be converted to * * <attribute name="A" /> * * This function object is used only for error recovery. * Resulting expressions always consist only of <choice>s and <attribute>s. * * * @author Kohsuke KAWAGUCHI */ public class AttributePicker implements ExpressionVisitorExpression { private final ExpressionPool pool; public AttributePicker( ExpressionPool pool ) { this.pool = pool; } public Expression onElement( ElementExp exp ) { return AttributeExp.epsilon; } public Expression onMixed( MixedExp exp ) { return exp.exp.visit(this); } public Expression onAnyString() { return Expression.epsilon; } public Expression onEpsilon() { return Expression.epsilon; } public Expression onNullSet() { return Expression.nullSet; } public Expression onRef( ReferenceExp exp ) { return exp.exp.visit(this); } public Expression onOther( OtherExp exp ) { return exp.exp.visit(this); } public Expression onData( DataExp exp ) { return Expression.epsilon; } public Expression onValue( ValueExp exp ) { return Expression.epsilon; } public Expression onList( ListExp exp ) { return Expression.epsilon; } public Expression onAttribute( AttributeExp exp ) { return exp; } public Expression onOneOrMore( OneOrMoreExp exp ) { // reduce A+ -> A return exp.exp.visit(this); } public Expression onSequence( SequenceExp exp ) { Expression ex1 = exp.exp1.visit(this); Expression ex2 = exp.exp2.visit(this); if(ex1.isEpsilonReducible()) { if(ex2.isEpsilonReducible()) return Expression.epsilon; else return ex2; } else return ex1; } public Expression onInterleave( InterleaveExp exp ) { Expression ex1 = exp.exp1.visit(this); Expression ex2 = exp.exp2.visit(this); if(ex1.isEpsilonReducible()) { if(ex2.isEpsilonReducible()) return Expression.epsilon; else return ex2; } else return ex1; } public Expression onConcur( ConcurExp exp ) { // abandon concur. return Expression.epsilon; } public Expression onChoice( ChoiceExp exp ) { Expression ex1 = exp.exp1.visit(this); Expression ex2 = exp.exp2.visit(this); // if one of choice is epsilon-reducible, // the entire choice becomes optional. // optional attributes have to be removed from the result. if( ex1.isEpsilonReducible() || ex2.isEpsilonReducible() ) return Expression.epsilon; return pool.createChoice(ex1,ex2); } } msv-2009.1/msv/src/com/sun/msv/verifier/regexp/OptimizationTag.java0000644000175000017500000000402107671170035025501 0ustar giovannigiovanni/* * @(#)$Id: OptimizationTag.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.regexp; import java.util.Map; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; /** * this object will be added to Expression.verifierTag * to speed up typical validation. * * @author Kohsuke KAWAGUCHI */ final class OptimizationTag { /** cached value of string care level. * See Acceptor.getStringCareLevel for meanings of value. */ int stringCareLevel = STRING_NOTCOMPUTED; /** a value indicates that stringCareLevel has not computed yet. */ public static final int STRING_NOTCOMPUTED = -1; /** * map from element to residual(exp,ElementToken(element)) * * this map is not applicable when the ElementToken represents * more than one element. Because of 'concur' operator. * * In RELAX, * residual(exp,elem1|elem2) = residual(exp,elem1) | residual(exp,elem2) * * Since it is possible for multiple threads to access the same OptimizationTag * concurrently, it has to be serialized. */ final Map simpleElementTokenResidual = new java.util.Hashtable(); protected static final class OwnerAndCont { final ElementExp owner; final Expression continuation; public OwnerAndCont( ElementExp owner, Expression cont ) { this.owner=owner; this.continuation=cont; } }; /** map from (namespaceURI,tagName) pair to OwnerAndContinuation. */ final Map transitions = new java.util.Hashtable(); /** AttributePruner.prune(exp) */ Expression attributePrunedExpression; // /** a flag that indicates this expression doesn't have any attribute node. // * // * null means unknown. // */ // Boolean isAttributeFree; } msv-2009.1/msv/src/com/sun/msv/verifier/regexp/Token.java0000644000175000017500000000266007671170035023446 0ustar giovannigiovanni/* * @(#)$Id: Token.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.regexp; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.DataExp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.ListExp; import com.sun.msv.grammar.ValueExp; /** * primitive unit of XML instance. * * this object is fed to expression. * * @author Kohsuke KAWAGUCHI */ public abstract class Token { /** returns true if the given ElementExp can consume this token */ public boolean match( ElementExp p ) { return false; } public boolean match( AttributeExp p ) { return false; } /** returns true if the given DataExp can consume this token */ public boolean match( DataExp p ) { return false; } public boolean match( ValueExp p ) { return false; } /** returns true if the given ListExp can consume this token */ public boolean match( ListExp p ) { return false; } /** returns true if anyString pattern can consume this token */ public boolean matchAnyString() { return false; } /** checks if this token is ignorable. */ boolean isIgnorable() { return false; } } msv-2009.1/msv/src/com/sun/msv/verifier/regexp/AttributeFeeder.java0000644000175000017500000001222007671170035025435 0ustar giovannigiovanni/* * @(#)$Id: AttributeFeeder.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.regexp; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.ChoiceExp; import com.sun.msv.grammar.ConcurExp; import com.sun.msv.grammar.DataExp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.ExpressionVisitorExpression; import com.sun.msv.grammar.InterleaveExp; import com.sun.msv.grammar.ListExp; import com.sun.msv.grammar.MixedExp; import com.sun.msv.grammar.OneOrMoreExp; import com.sun.msv.grammar.OtherExp; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.SequenceExp; import com.sun.msv.grammar.ValueExp; /** * Feeds AttributeToken to the expression and obtains the residual (content model). * * AttributeTokens are fed in order-less fashion. * * @author Kohsuke KAWAGUCHI */ public class AttributeFeeder implements ExpressionVisitorExpression { protected final REDocumentDeclaration docDecl; protected final ExpressionPool pool; private Token token; public AttributeFeeder( REDocumentDeclaration docDecl ) { this.docDecl = docDecl; this.pool = docDecl.pool; } public final Expression feed( Expression exp, AttributeToken token, boolean ignoreUndeclaredAttribute ) { this.token = token; Expression r = exp.visit(this); if(r!=Expression.nullSet || !ignoreUndeclaredAttribute) return r; // if ignoreUndeclaredAttribute==true and expression is nullSet, // we have to check which of the following is the case. // (1) attribute is undefined // (2) value of the attribute was rejected. this.token = token.createRecoveryAttToken(); r = exp.visit(this); // if wild card token is rejected, then it must be the absence of declaration. if(r==Expression.nullSet) return exp; // otherwise the value was wrong. return Expression.nullSet; // if( com.sun.msv.driver.textui.Debug.debug ) // System.out.println("after feeding "+atts.getQName(i)+" attribute"); // System.out.println(com.sun.msv.grammar.trex.util.TREXPatternPrinter.printContentModel(exp)); } public Expression onAttribute( AttributeExp exp ) { if( token.match(exp) ) return Expression.epsilon; else return Expression.nullSet; } // /** // * checks if the given expression is attribute-free. // * // * if a expression is attribute free, then the residual must be nullSet. // */ // protected final boolean isAttributeFree( Expression exp ) { // Object o = exp.verifierTag; // return o!=null && ((OptimizationTag)o).isAttributeFree==Boolean.TRUE; // } public Expression onChoice( ChoiceExp exp ) { // if( isAttributeFree(exp) ) return Expression.nullSet; return pool.createChoice( exp.exp1.visit(this), exp.exp2.visit(this) ); } public Expression onElement( ElementExp exp ) { return Expression.nullSet; } public Expression onOneOrMore( OneOrMoreExp exp ) { // if( isAttributeFree(exp) ) return Expression.nullSet; return pool.createSequence( exp.exp.visit(this), pool.createZeroOrMore(exp.exp) ); } public Expression onMixed( MixedExp exp ) { return pool.createMixed( exp.exp.visit(this) ); } public Expression onList( ListExp exp ) { return Expression.nullSet; } public Expression onEpsilon() { return Expression.nullSet; } public Expression onNullSet() { return Expression.nullSet; } public Expression onAnyString() { return Expression.nullSet; } public Expression onRef( ReferenceExp exp ) { return exp.exp.visit(this); } public Expression onOther( OtherExp exp ) { return exp.exp.visit(this); } public Expression onSequence( SequenceExp exp ) { // if( isAttributeFree(exp) ) return Expression.nullSet; // for attributes only, sequence acts as orderless return pool.createChoice( pool.createSequence( exp.exp1.visit(this), exp.exp2 ), pool.createSequence( exp.exp1, exp.exp2.visit(this) ) ); } public Expression onData( DataExp exp ) { return Expression.nullSet; } public Expression onValue( ValueExp exp ) { return Expression.nullSet; } public Expression onConcur( ConcurExp exp ) { return pool.createConcur( exp.exp1.visit(this), exp.exp2.visit(this) ); } public Expression onInterleave( InterleaveExp exp ) { return pool.createChoice( pool.createInterleave( exp.exp1.visit(this), exp.exp2 ), pool.createInterleave( exp.exp1, exp.exp2.visit(this) ) ); } } msv-2009.1/msv/src/com/sun/msv/verifier/regexp/package.html0000644000175000017500000000256607333627054024014 0ustar giovannigiovanni

        VGM implementation by using regular expression derivation algorithm.

        This implementation bridges a gap between neutral grammar model (com.sun.msv.grammar) and Verifier grammar model (com.sun.msv.verifier).

        Performance Analysis

        This bridge is tuned for client-side use, where MSV is repeatedly invoked from command line. Particularly,

        1. No preprocessing of grammar is necessary. Abstract grammar model can be directly used. This results in faster schema loading, at the expense of slower validation.
        2. Extensive error recovery and detailed error diagnosis is provided.

        Also, this bridge covers full expressiveness of RELAX and TREX.

        Algorithm

        Those who are interested in the algorithm of this package may want to see the following resources.

        regexp.tar.gz
        regular expression matching algorithm by Mark Hopkins.
        How to validate XML
        A brief introduction of the above algorithm by Joe English
        TREX implementation
        This implementation by James Clark employs the algorithm of Mark Hopkins.
        msv-2009.1/msv/src/com/sun/msv/verifier/regexp/ExpressionAcceptor.java0000644000175000017500000010765011156747174026222 0ustar giovannigiovanni/* * @(#)$Id: ExpressionAcceptor.java 1744 2009-03-14 15:34:20Z bimargulies $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.regexp; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Vector; import org.relaxng.datatype.DatatypeException; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.ChoiceExp; import com.sun.msv.grammar.DataOrValueExp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.IDContextProvider; import com.sun.msv.grammar.IDContextProvider2; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.NamespaceNameClass; import com.sun.msv.grammar.NotNameClass; import com.sun.msv.grammar.SimpleNameClass; import com.sun.msv.grammar.ValueExp; import com.sun.msv.grammar.util.IDContextProviderWrapper; import com.sun.msv.util.DatatypeRef; import com.sun.msv.util.StartTagInfo; import com.sun.msv.util.StringRef; import com.sun.msv.verifier.Acceptor; /** * {@link Acceptor} implementation. * *

        * When you are using REDocumentDeclaration, then the acceptor * is always guaranteed to be a subclass of this class. * * Therefore, by using this regexp implementation of VGM, you can always downcast * {@link Acceptor} to this class and access its contents to get more information. * *

        * If you consider VGM as an automaton, * this class can be thought as a lazy automaton acceptor. * * * @author Kohsuke KAWAGUCHI */ public abstract class ExpressionAcceptor implements Acceptor { private Expression expression; /** * gets the residual content model. * *

        * This method returns the expression that represents the expected content model * it will read. * For example, if the original content model is (A,(B|C)) and this acceptor * has already read A, then this method returns (B|C). * *

        * The returned residual is useful to find out what elements can appear next. * *

        * If you consider VGM as an automaton, the residual content model * can be thought as the current state. Also, * At the same time, right language (a regular expression that represents * the language it can accept from now on). */ public Expression getExpression() { return expression; } /** this object provides various function objects */ protected final REDocumentDeclaration docDecl; /** * If true, this acceptor will ignore all undeclared attributes. * If false, this acceptor will signal an error for an undeclared attribute. * *

        * This flag is used to implement the semantics of RELAX Core, where * undeclared attributes are allowed. */ protected final boolean ignoreUndeclaredAttributes; public ExpressionAcceptor( REDocumentDeclaration docDecl, Expression exp, boolean ignoreUndeclaredAttributes ) { this.docDecl = docDecl; this.expression = exp; this.ignoreUndeclaredAttributes = ignoreUndeclaredAttributes; } /** * creates combined child acceptor and primitive child acceptors (if necessary). * * be careful not to keep returned object too long because * it is reused whenever the method is called. * * @return null * if errRef is null and this expression cannot accept given start tag. * if errRef is non-null and error recovery is not possible. */ public Acceptor createChildAcceptor( StartTagInfo tag, StringRef errRef ) { final CombinedChildContentExpCreator cccc = docDecl.cccec; // obtains fully combined child content pattern CombinedChildContentExpCreator.ExpressionPair e = cccc.get(expression,tag); if( e.content!=Expression.nullSet ) { // successful. if( com.sun.msv.driver.textui.Debug.debug ) { System.out.println("accept start tag <"+ tag.qName+">. combined content pattern is"); System.out.println(com.sun.msv.grammar.util.ExpressionPrinter.printContentModel(e.content)); if( e.continuation!=null ) System.out.println("continuation is:\n"+ com.sun.msv.grammar.util.ExpressionPrinter.printContentModel(e.continuation) ); else System.out.println("no continuation"); } return createAcceptor( e.content, e.continuation, cccc.getMatchedElements(), cccc.numMatchedElements() ); } // no element declaration is satisfied by this start tag. // this must be an error of input document. if( errRef==null ) // bail out now to notify the caller that an error was found. return null; // no ElementExp accepts this tag name // (actually, some ElementExp may have possibly accepted this tag name, // but as a result of , no expression left ). errRef.str = diagnoseBadTagName(tag); if( errRef.str==null ) // no detailed error message was prepared. // use some generic one. errRef.str = docDecl.localizeMessage( REDocumentDeclaration.DIAG_BAD_TAGNAME_GENERIC, tag.qName ); // prepare child acceptor. return createRecoveryAcceptors(); } protected abstract Acceptor createAcceptor( Expression contentModel, Expression continuation/*can be null*/, ElementExp[] primitives, int numPrimitives ); /** * @deprecated */ public final boolean onAttribute( String namespaceURI, String localName, String qName, String value, IDContextProvider context, StringRef refErr, DatatypeRef refType ) { return onAttribute2( namespaceURI, localName, qName, value, IDContextProviderWrapper.create(context), refErr, refType ); } public final boolean onAttribute2( String namespaceURI, String localName, String qName, String value, IDContextProvider2 context, StringRef refErr, DatatypeRef refType ) { // instead of creating a new object each time, // use a cached copy. docDecl.attToken.reinit( namespaceURI,localName,qName, new StringToken(docDecl,value,context,refType) ); return onAttribute( docDecl.attToken, refErr ); } protected boolean onAttribute( AttributeToken token, StringRef refErr ) { Expression r = docDecl.attFeeder.feed( this.expression, token, ignoreUndeclaredAttributes ); if( r!=Expression.nullSet ) { // this attribute is properly consumed. expression = r; if(com.sun.msv.driver.textui.Debug.debug) System.out.println("-- residual after :" + com.sun.msv.grammar.util.ExpressionPrinter.printContentModel(r)); return true; } if( refErr==null ) { // refErr was not provided. bail out now. return false; } // // diagnose the error // // this attribute was not accepted. // its value may be wrong. // try feeding wild card and see if it's accepted. AttributeRecoveryToken rtoken = token.createRecoveryAttToken(); r = docDecl.attFeeder.feed( this.expression, rtoken, ignoreUndeclaredAttributes ); if( r==Expression.nullSet ) { // even the wild card was rejected. // now there are two possibilities. // the first is that this attribute name is not allowed to appear, // which is the most typical case. (e.g., type miss of the attribute name, etc). // the second is that the content model of the element is equal to the // nullSet, thus nothing can be accepted. This is usually // a problem of the schema. if( this.expression==Expression.nullSet ) { // the content model is equal to the nullSet. refErr.str = docDecl.localizeMessage( REDocumentDeclaration.DIAG_CONTENT_MODEL_IS_NULLSET, null ); } else { // the content model is not equal to the nullSet. // this means that this attribute // is not specified by the grammar. refErr.str = docDecl.localizeMessage( REDocumentDeclaration.DIAG_UNDECLARED_ATTRIBUTE, token.qName ); } // recover by using the current expression. // TODO: possibly we can make all attributes optional or something. // (because this might be a caused by the typo.) return true; } else { // wild card was accepted, so the value must be wrong. refErr.str = diagnoseBadAttributeValue( rtoken ); if( refErr.str==null ) { // no detailed error message can be provided // so use generic one. refErr.str = docDecl.localizeMessage( REDocumentDeclaration.DIAG_BAD_ATTRIBUTE_VALUE_GENERIC, token.qName ); } // now we know the reason. // recover by assuming that the valid value was specified for this attribute. this.expression = r; return true; } } public boolean onEndAttributes( StartTagInfo sti, StringRef refErr ) { Expression r = docDecl.attPruner.prune( this.expression ); if( r!=Expression.nullSet ) { // there was no error. this.expression = r; return true; } // there was an error. // specifically, some required attributes are missing. if( refErr==null ) return false; // refErr was not provided. bail out. if( this.expression==Expression.nullSet ) { // the content model is equal to the nullSet. refErr.str = docDecl.localizeMessage( REDocumentDeclaration.DIAG_CONTENT_MODEL_IS_NULLSET, null ); } else { refErr.str = diagnoseMissingAttribute(sti); if( refErr.str==null ) // no detailed error message can be provided // so use generic one. refErr.str = docDecl.localizeMessage( REDocumentDeclaration.DIAG_MISSING_ATTRIBUTE_GENERIC, sti.qName ); } // remove unconsumed attributes this.expression = this.expression.visit( docDecl.attRemover ); return true; } protected boolean stepForward( Token token, StringRef errRef ) { Expression residual = docDecl.resCalc.calcResidual( expression, token ); if( com.sun.msv.driver.textui.Debug.debug ) { System.out.println("residual of stepForward("+token+")"); System.out.print(com.sun.msv.grammar.util.ExpressionPrinter.printContentModel(expression)); System.out.print(" -> "); System.out.println(com.sun.msv.grammar.util.ExpressionPrinter.printContentModel(residual)); } if( residual==Expression.nullSet ) { // error: we can't accept this token if( errRef!=null ) { // diagnose error. if( token instanceof StringToken ) errRef.str = diagnoseUnexpectedLiteral( (StringToken)token ); // docDecl.localizeMessage( docDecl.DIAG_BAD_LITERAL_VALUE_WRAPUP, // TODO: diagnosis for ElementToken // recovery by ignoring this token. // TODO: should we modify this to choice(expression,EoCR)? // we need some measures to prevent redundant choice } else { // do not mutate any member variables. // caller may call stepForward again with error recovery. } return false; } expression = residual; return true; } /** * @deprecated */ public final boolean onText( String literal, IDContextProvider context, StringRef refErr, DatatypeRef refType ) { return onText2( literal, IDContextProviderWrapper.create(context), refErr, refType ); } public boolean onText2( String literal, IDContextProvider2 provider, StringRef refErr, DatatypeRef refType ) { return stepForward( new StringToken(docDecl,literal,provider,refType), refErr ); } public final boolean stepForwardByContinuation( Expression continuation, StringRef errRef ) { if( continuation!=Expression.nullSet ) { // successful transition if( com.sun.msv.driver.textui.Debug.debug ) System.out.println("stepForwardByCont. : " + com.sun.msv.grammar.util.ExpressionPrinter.printContentModel(continuation)); expression = continuation; return true; } if( errRef==null ) return false; // fail immediately. // TODO: diagnose uncompleted content model. return false; } /** checks if this Acceptor is satisifed */ public boolean isAcceptState( StringRef errRef ) { if( errRef==null ) return expression.isEpsilonReducible(); else { if(expression.isEpsilonReducible()) return true; // error. provide diagnosis errRef.str = diagnoseUncompletedContent(); return false; } } public int getStringCareLevel() { // if the value is cached, return cached value. // otherwise, calculate it now. OptimizationTag ot = (OptimizationTag)expression.verifierTag; if(ot==null) expression.verifierTag = ot = new OptimizationTag(); if(ot.stringCareLevel==OptimizationTag.STRING_NOTCOMPUTED) ot.stringCareLevel = StringCareLevelCalculator.calc(expression); return ot.stringCareLevel; } // error recovery //================================================== private final Expression mergeContinuation( Expression exp1, Expression exp2 ) { if(exp1==null && exp2==null) return null; if(exp1==null || exp1==Expression.nullSet) return exp2; if(exp2==null || exp2==Expression.nullSet) return exp1; return docDecl.pool.createChoice(exp1,exp2); } /** * creates Acceptor that recovers from errors. * * This method also modifies the current expression in preparation to * accept newly created child acceptor. * * Recovery will be done by preparing to accept two possibilities. * *

          *
        1. We may get back to sync by ignoring the newly found illegal element. * ( this is for mistake like "abcXdefg") *
        2. We may get back to sync by replacing newly found illegal element * by one of the valid elements. * ( this is for mistake like "abcXefg") *
        */ private final Acceptor createRecoveryAcceptors() { final CombinedChildContentExpCreator cccc = docDecl.cccec; CombinedChildContentExpCreator.ExpressionPair combinedEoC = cccc.get( expression, null, false ); // get residual of EoC. Expression eocr = docDecl.resCalc.calcResidual( expression, AnyElementToken.theInstance ); Expression continuation = docDecl.pool.createChoice( expression, eocr ); Expression contentModel = combinedEoC.content; if( com.sun.msv.driver.textui.Debug.debug ) { System.out.println("content model of recovery acceptor:"+ com.sun.msv.grammar.util.ExpressionPrinter.printContentModel(contentModel) ); System.out.println("continuation of recovery acceptor:"+ com.sun.msv.grammar.util.ExpressionPrinter.printSmallest(continuation) ); } // by passing null as elements of concern and // using continuation, we are effectively "generating" // the content model for error recovery. return createAcceptor( contentModel, continuation, null, 0 ); } /** * format list of candidates to one string. * * this method * (1) inserts separator into appropriate positions * (2) appends "more" message when items are only a portion of candidates. */ private String concatenateMessages( List items, boolean more, String separatorStr, String moreStr ) { String r=""; String sep = docDecl.localizeMessage(separatorStr,null); Collections.sort(items, new Comparator(){ public int compare( Object o1, Object o2 ) { return ((String)o1).compareTo((String)o2); } }); // sort candidates. for( int i=0; i is used. // there is no easy way to tell which what tag name is expected. // TODO: we can reduce strength by treating concur as choice. // do it. return null; } // we are now sure that combined child content expression will be // the choice of all elements of concern. // so if tag name satisfies one of those elements, // it can be accepted. // therefore we can provide candidates for users. Set s = new java.util.HashSet(); boolean more = false; // if there is a SimpleNameClass with the same localName // but with a different namespace URI, // this variable will receive that URI. String wrongNamespace = null; final ElementExp[] eocs = cccc.getMatchedElements(); final int len = cccc.numMatchedElements(); for( int i=0; is. // // this is also a frequently used pattern by TREX. // an expression like // // // // yesno // // // // falls into this pattern. final Set items = new java.util.HashSet(); boolean more = false; ChoiceExp ch = (ChoiceExp)constraint; Expression[] children = ch.getChildren(); for( int i=0; iKohsuke KAWAGUCHI */ public class AttributeRemover extends ExpressionCloner { public AttributeRemover( ExpressionPool pool ) { super(pool); } public Expression onAttribute( AttributeExp exp ) { return Expression.epsilon; } public Expression onRef( ReferenceExp exp ) { return exp.exp.visit(this); } public Expression onOther( OtherExp exp ) { return exp.exp.visit(this); } public Expression onElement( ElementExp exp ) { return exp; } } msv-2009.1/msv/src/com/sun/msv/verifier/regexp/Messages_ja.properties0000644000175000017500000001022510555773111026055 0ustar giovannigiovanniDiagnosis.ElementNotAllowed = \ \u8981\u7D20"{0}"\u304C\u898B\u3064\u304B\u308A\u307E\u3057\u305F\u304C\u3001\u3053\u3053\u306B\u306F\u4F55\u306E\u8981\u7D20\u3082\u66F8\u3051\u307E\u305B\u3093 Diagnosis.ContentModelIsNullset = \ \u3053\u306E\u8981\u7D20\u306E\u30B3\u30F3\u30C6\u30F3\u30C8\u30E2\u30C7\u30EB\u306F\u6C7A\u3057\u3066\u6E80\u305F\u3059\u3053\u3068\u304C\u51FA\u6765\u307E\u305B\u3093\u3002\ \u30B9\u30AD\u30FC\u30DE\u306E\u66F8\u304D\u640D\u3058\u3067\u3042\u308B\u53EF\u80FD\u6027\u3082\u3042\u308A\u307E\u3059 Diagnosis.BadTagName.Generic = \ \u8981\u7D20"{0}"\u306F\u3053\u3053\u306B\u306F\u66F8\u3051\u307E\u305B\u3093 Diagnosis.BadTagName.WrapUp = \ \u8981\u7D20"{0}"\u306F\u3053\u3053\u306B\u306F\u66F8\u3051\u307E\u305B\u3093\u3002\u66F8\u3051\u308B\u306E\u306F\uFF1A {1} Diagnosis.BadTagName.Separator = \ , Diagnosis.BadTagName.More = \ \u306A\u3069\u3067\u3059 Diagnosis.BadTagName.WrongNamespace = \ \u8981\u7D20"{0}"\u306E\u540D\u524D\u7A7A\u9593\u304C\u9593\u9055\u3063\u3066\u3044\u307E\u3059\u3002"{1}"\u3067\u306A\u304F\u3066\u306F\u3044\u3051\u307E\u305B\u3093 Diagnosis.BadTagName.ProbablyWrongNamespace = \ \u6050\u3089\u304F\u8981\u7D20"{0}"\u306E\u540D\u524D\u7A7A\u9593\u304C\u9593\u9055\u3063\u3066\u3044\u307E\u3059\u3002"{1}"\u3067\u306F\u306A\u3044\u304B\u3068\u601D\u308F\u308C\u307E\u3059 Diagnosis.UndeclaredAttribute = \ \u5C5E\u6027"{0}"\u306F\u3053\u3053\u306B\u306F\u66F8\u3051\u307E\u305B\u3093 Diagnosis.BadAttributeValue.Generic = \ \u5C5E\u6027"{0}"\u306E\u5024\u304C\u9593\u9055\u3063\u3066\u3044\u307E\u3059 Diagnosis.BadAttributeValue.DataType = \ \u5C5E\u6027"{0}"\u306E\u5024\u304C\u9593\u9055\u3063\u3066\u3044\u307E\u3059\uFF1A{1} Diagnosis.BadAttributeValue.WrapUp = \ \u5C5E\u6027"{0}"\u306E\u5024\u306F\u6B21\u306E\u3069\u308C\u304B\u3067\u306A\u304F\u3066\u306F\u306A\u308A\u307E\u305B\u3093\uFF1A{1} Diagnosis.BadAttributeValue.Separator = \ , Diagnosis.BadAttributeValue.More = \ \u306A\u3069 Diagnosis.MissingAttribute.Simple = \ \u8981\u7D20"{0}"\u306B\u306F\u5C5E\u6027"{1}"\u304C\u5FC5\u9808\u3067\u3059 Diagnosis.MissingAttribute.Generic = \ \u5FC5\u9808\u5C5E\u6027\u304C\u5E7E\u3064\u304B\u6B20\u3051\u3066\u3044\u307E\u3059 Diagnosis.MissingAttribute.WrapUp = \ \u8981\u7D20"{0}"\u306B\u306F\u5C11\u306A\u304F\u3068\u3082\u6B21\u306E\u3069\u308C\u304B\u306E\u5C5E\u6027\u304C\u5FC5\u8981\u3067\u3059: {1} Diagnosis.MissingAttribute.Separator = \ , Diagnosis.MissingAttribute.More = \ \u306A\u3069 Diagnosis.UncompletedContent.WrapUp = \ \u3053\u3053\u3067\u8981\u7D20\u3092\u9589\u3058\u308B\u3053\u3068\u306F\u51FA\u6765\u307E\u305B\u3093\u3002\u6B21\u306E\u3069\u308C\u304B\u304C\u5FC5\u8981\u3067\u3059\uFF1A {1} Diagnosis.UncompletedContent.Separator = \ , Diagnosis.UncompletedContent.More = \ , etc. Diagnosis.BadLiteral.WrapUp =\ \u9593\u9055\u3063\u305F\u6587\u5B57\u5217\u3067\u3059\u3002\u6B21\u306E\u3069\u308C\u304B\u304C\u5FC5\u8981\u3067\u3059\uFF1A {0} Diagnosis.BadLiteral.Separator =\ , Diagnosis.BadLiteral.More =\ , etc. Diagnosis.BadLiteral.Generic = \ \u30C6\u30AD\u30B9\u30C8\u304C\u6B63\u3057\u304F\u3042\u308A\u307E\u305B\u3093: {0} Diagnosis.BadLiteral.IncorrectValue = \ \u30C6\u30AD\u30B9\u30C8\u306F"{0}"\u3067\u306A\u304F\u3066\u306F\u3044\u3051\u307E\u305B\u3093\u304C\u3001"{1}"\u304C\u898B\u3064\u304B\u308A\u307E\u3057\u305F Diagnosis.SimpleNameClass = \ <{0}> Diagnosis.NamespaceNameClass = \ \u540D\u524D\u7A7A\u9593"{0}"\u306E\u8981\u7D20 Diagnosis.NotNamespaceNameClass = \ \u540D\u524D\u7A7A\u9593"{0}"\u4EE5\u5916\u306E\u8981\u7D20 Diagnosis.StringNotAllowed = \ \u30AD\u30E3\u30E9\u30AF\u30BF\u30C7\u30FC\u30BF\u306F\u3053\u3053\u306B\u306F\u66F8\u3051\u307E\u305B\u3093\u304C\u3001"{0}"\u304C\u898B\u3064\u304B\u308A\u307E\u3057\u305F Diagnosis.BadKeyValue = \ ID "{0}"\u306F\u65E2\u306B\u4F7F\u308F\u308C\u3066\u3044\u307E\u3059 Diagnosis.BadKeyValue2 = \ \u30AD\u30FC"{0}"\u306F\u30B7\u30F3\u30DC\u30EB\u30B9\u30DA\u30FC\u30B9"{1}"\u3067\u65E2\u306B\u4F7F\u308F\u308C\u3066\u3044\u307E\u3059 Diagnosis.BadLiteralValue.WrapUp =\ "{0}"\u306F\u6307\u5B9A\u3055\u308C\u305F\u30C7\u30FC\u30BF\u578B\u306E\u5024\u3067\u306F\u3042\u308A\u307E\u305B\u3093 msv-2009.1/msv/src/com/sun/msv/verifier/regexp/AttributeToken.java0000644000175000017500000001002507671170035025324 0ustar giovannigiovanni/* * @(#)$Id: AttributeToken.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.regexp; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.IDContextProvider2; import com.sun.msv.util.DatatypeRef; /** * represents attribute and its value. * * @author Kohsuke KAWAGUCHI */ public class AttributeToken extends Token { public String namespaceURI; public String localName; public String qName; public StringToken value; protected REDocumentDeclaration docDecl; /** * holds a reference to the assigned type. * * If this AttributeToken is successfully consumed, then this field * contains the AttributeExp which consumed this token. * * If this token is not consumed or several different AttributeExps * consumed this token, then null. */ public AttributeExp matchedExp = null; /** * If this value is false, the "matched" field must always null. This indicates * that no AttributeExp has consumed this token yet. * If this value is true and the "matched" field is non-null, then it means * that AttributeExp has consumed this token. * If this value is true and the "matched" field is null, then more than * one AttributeExps have consumed this token. */ private boolean saturated = false; AttributeToken( REDocumentDeclaration docDecl ) { this.docDecl = docDecl; } protected AttributeToken( REDocumentDeclaration docDecl, String namespaceURI, String localName, String qName, String value, IDContextProvider2 context ) { this( docDecl, namespaceURI, localName, qName, new StringToken(docDecl,value,context,new DatatypeRef()) ); } protected AttributeToken( REDocumentDeclaration docDecl, String namespaceURI, String localName, String qName, StringToken value ) { this(docDecl); reinit( namespaceURI, localName, qName, value ); } void reinit( String namespaceURI, String localName, String qName, StringToken value ) { this.namespaceURI = namespaceURI; this.localName = localName; this.qName = qName; this.value = value; matchedExp = null; saturated = false; } /** * creates a special AttributeToken which matchs any content restrictions. * * This token acts like a wild card for the attribute. This method is * used for error recovery. */ final AttributeRecoveryToken createRecoveryAttToken() { return new AttributeRecoveryToken( docDecl, namespaceURI, localName, qName, value ); } public boolean match( AttributeExp exp ) { // Attribute name must meet the constraint of NameClass if(!exp.nameClass.accepts(namespaceURI,localName)) return false; // content model of the attribute must consume the value boolean satisfied = false; if(value.literal.trim().length()==0 && exp.exp.isEpsilonReducible()) satisfied = true; else if(docDecl.resCalc.calcResidual(exp.exp, value).isEpsilonReducible()) satisfied = true; if(satisfied) { // store the expression who consumed this token. if( !saturated || exp==matchedExp ) matchedExp=exp; else matchedExp=null; /* the above is the shortened form of: if( !saturated ) matchedExp = exp; else if( exp!=matchedExp ) matchedExp = null; */ saturated = true; return true; } return false; } } msv-2009.1/msv/src/com/sun/msv/verifier/regexp/ResidualCalculator.java0000644000175000017500000001305007745023667026155 0ustar giovannigiovanni/* * @(#)$Id: ResidualCalculator.java 1605 2003-10-20 18:21:43Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.regexp; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.ChoiceExp; import com.sun.msv.grammar.ConcurExp; import com.sun.msv.grammar.DataExp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.ExpressionVisitorExpression; import com.sun.msv.grammar.InterleaveExp; import com.sun.msv.grammar.ListExp; import com.sun.msv.grammar.MixedExp; import com.sun.msv.grammar.OneOrMoreExp; import com.sun.msv.grammar.OtherExp; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.SequenceExp; import com.sun.msv.grammar.ValueExp; /** * computes regular expression derivative. * * this class receives a regexp and computes the right language after eating * given token. * * @author Kohsuke KAWAGUCHI */ public class ResidualCalculator implements ExpressionVisitorExpression { protected Token token; protected final ExpressionPool pool; public ResidualCalculator( ExpressionPool pool ) { this.pool=pool; } /** compute the residual */ final Expression calcResidual( Expression exp, ElementToken token ) { if( token.acceptedPatterns!=null && token.acceptedPatterns.length==1 ) { // we can use optimization table OptimizationTag ot; if(exp.verifierTag==null) exp.verifierTag = ot = new OptimizationTag(); else { ot = (OptimizationTag)exp.verifierTag; Expression residual = (Expression)ot.simpleElementTokenResidual.get(token.acceptedPatterns[0]); if(residual!=null) return residual; // cache hit. } this.token = token; Expression residual = exp.visit(this); // cache this residual ot.simpleElementTokenResidual.put(token.acceptedPatterns[0],residual); return residual; } // no chance of using cache. this.token = token; return exp.visit(this); } /** compute the residual */ public final Expression calcResidual( Expression exp, Token token ) { if( token instanceof ElementToken ) return calcResidual(exp,(ElementToken)token); this.token=token; Expression r = exp.visit(this); // if token is ignorable, make expression as so. if( token.isIgnorable() ) r = pool.createChoice(r,exp); return r; } public Expression onAttribute( AttributeExp exp ) { if(token.match(exp)) return Expression.epsilon; else return Expression.nullSet; } public Expression onChoice( ChoiceExp exp ) { return pool.createChoice( exp.exp1.visit(this), exp.exp2.visit(this) ); } public Expression onElement( ElementExp exp ) { if(token.match(exp)) return Expression.epsilon; else return Expression.nullSet; } public Expression onOneOrMore( OneOrMoreExp exp ) { return pool.createSequence( exp.exp.visit(this), pool.createZeroOrMore(exp.exp) ); } public Expression onMixed( MixedExp exp ) { // if token can be interpreted as anyString, eat it. if( token.matchAnyString() ) return exp; // otherwise, it must be consumed by the children. return pool.createMixed( exp.exp.visit(this) ); } public Expression onEpsilon() { return Expression.nullSet; } public Expression onNullSet() { return Expression.nullSet; } public Expression onAnyString() { // anyString is not reduced to epsilon. // it remains there even after consuming StringToken. if(token.matchAnyString()) return Expression.anyString; else return Expression.nullSet; } public Expression onRef( ReferenceExp exp ) { return exp.exp.visit(this); } public Expression onOther( OtherExp exp ) { return exp.exp.visit(this); } public Expression onSequence( SequenceExp exp ) { Expression r = pool.createSequence( exp.exp1.visit(this), exp.exp2 ); if( exp.exp1.isEpsilonReducible() ) return pool.createChoice( r, exp.exp2.visit(this) ); else return r; } public Expression onData( DataExp exp ) { if(token.match(exp)) return Expression.epsilon; else return Expression.nullSet; } public Expression onValue( ValueExp exp ) { if(token.match(exp)) return Expression.epsilon; else return Expression.nullSet; } public Expression onList( ListExp exp ) { if(token.match(exp)) return Expression.epsilon; else return Expression.nullSet; } public Expression onConcur( ConcurExp exp ) { return pool.createConcur( exp.exp1.visit(this), exp.exp2.visit(this) ); } public Expression onInterleave( InterleaveExp exp ) { return pool.createChoice( pool.createInterleave( exp.exp1.visit(this), exp.exp2 ), pool.createInterleave( exp.exp1, exp.exp2.visit(this) ) ); } } msv-2009.1/msv/src/com/sun/msv/verifier/regexp/ElementsOfConcernCollector.java0000644000175000017500000000621307671170035027604 0ustar giovannigiovanni/* * @(#)$Id: ElementsOfConcernCollector.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.regexp; import java.util.Collection; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.ChoiceExp; import com.sun.msv.grammar.ConcurExp; import com.sun.msv.grammar.DataExp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionVisitor; import com.sun.msv.grammar.InterleaveExp; import com.sun.msv.grammar.ListExp; import com.sun.msv.grammar.MixedExp; import com.sun.msv.grammar.OneOrMoreExp; import com.sun.msv.grammar.OtherExp; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.SequenceExp; import com.sun.msv.grammar.ValueExp; /** * Collects "elements of concern". * * "Elements of concern" are ElementExps that are possibly applicable to * the next element. These gathered element declarations are then tested against * next XML element. * * @author Kohsuke KAWAGUCHI */ public class ElementsOfConcernCollector implements ExpressionVisitor { private Collection result; public ElementsOfConcernCollector() {} public final void collect( Expression exp, Collection result ) { this.result = result; exp.visit(this); } public final Object onAttribute( AttributeExp exp ) { return null; } public final Object onChoice( ChoiceExp exp ) { exp.exp1.visit(this); exp.exp2.visit(this); return null; } public final Object onElement( ElementExp exp ) { // found. result.add( exp ); return null; } public final Object onOneOrMore( OneOrMoreExp exp ) { exp.exp.visit(this); return null; } public final Object onMixed( MixedExp exp ) { exp.exp.visit(this); return null; } public final Object onEpsilon() { return null; } public final Object onNullSet() { return null; } public final Object onAnyString() { return null; } public final Object onData( DataExp exp ) { return null; } public final Object onValue( ValueExp exp ) { return null; } public final Object onList( ListExp exp ) { return null; } public final Object onRef( ReferenceExp exp ) { return exp.exp.visit(this); } public final Object onOther( OtherExp exp ) { return exp.exp.visit(this); } public final Object onSequence( SequenceExp exp ) { exp.exp1.visit(this); if(exp.exp1.isEpsilonReducible()) exp.exp2.visit(this); return null; } public final Object onConcur( ConcurExp exp ) { exp.exp1.visit(this); exp.exp2.visit(this); return null; } public final Object onInterleave( InterleaveExp exp ) { exp.exp1.visit(this); exp.exp2.visit(this); return null; } } msv-2009.1/msv/src/com/sun/msv/verifier/regexp/ContentModelAcceptor.java0000644000175000017500000000656307671170035026450 0ustar giovannigiovanni/* * @(#)$Id: ContentModelAcceptor.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.regexp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.util.StringRef; import com.sun.msv.verifier.Acceptor; /** * base implementation for SimpleAcceptor and ComplexAcceptor * * @author Kohsuke KAWAGUCHI */ public abstract class ContentModelAcceptor extends ExpressionAcceptor { protected ContentModelAcceptor( REDocumentDeclaration docDecl, Expression exp, boolean ignoreUndeclaredAttributes ) { super(docDecl,exp,ignoreUndeclaredAttributes); } public boolean stepForward( Acceptor child, StringRef errRef ) { // TODO: explicitly mention that where the error recovery should be done. if( child instanceof SimpleAcceptor ) { SimpleAcceptor sa = (SimpleAcceptor)child; if(sa.continuation!=null) // if the continuation is available, // the stepForward will be very fast. return stepForwardByContinuation( sa.continuation, errRef ); else // otherwise we have to compute the residual. return stepForward( new ElementToken(new ElementExp[]{sa.owner}), errRef ); } if( child instanceof ComplexAcceptor ) { ComplexAcceptor ca = (ComplexAcceptor)child; return stepForward( new ElementToken( (errRef!=null)? ca.owners: // in error recovery mode, pretend that every owner is happy. ca.getSatisfiedOwners() ), errRef); } throw new Error(); // child must be either Simple or Complex. } /** * creates actual Acceptor object from the computed result. */ protected Acceptor createAcceptor( Expression combined, Expression continuation, ElementExp[] primitives, int numPrimitives ) { if( primitives==null || numPrimitives<=1 ) { // primitives==null is possible when recovering from error. // in this special case, combined child pattern and primitive patterns are the same. // therefore we don't need to keep track of primitive patterns. return new SimpleAcceptor( docDecl, combined, (primitives==null)?null:primitives[0], continuation ); } // TODO: implements MultipleAcceptor for cases that // combined expression is unnecessary but there are more than one primitive. if( com.sun.msv.driver.textui.Debug.debug ) System.out.println("ComplexAcceptor is used"); // we need a fresh array. ElementExp[] owners = new ElementExp[numPrimitives]; System.arraycopy( primitives, 0, owners, 0, numPrimitives ); return new ComplexAcceptor( docDecl, combined, owners ); } // ContentModelAcceptor does not support type-assignment. // This will be supported by SimpleAcceptor only. public Object getOwnerType() { return null; } } msv-2009.1/msv/src/com/sun/msv/verifier/regexp/REDocumentDeclaration.java0000644000175000017500000001645210403116315026531 0ustar giovannigiovanni/* * @(#)$Id: REDocumentDeclaration.java 1702 2006-03-06 20:34:21Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.regexp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.Grammar; import com.sun.msv.verifier.Acceptor; import com.sun.msv.verifier.DocumentDeclaration; /** * {@link DocumentDeclaration} implementation * * Grammar object can be shared among multiple threads, but this object * cannot be shared. * *

        * REDocumentDeclaration always returns subclasses of {@link ExpressionAcceptor} * as the Acceptor implementation. * * @author Kohsuke KAWAGUCHI */ public class REDocumentDeclaration implements DocumentDeclaration { /** start validation from this expression. */ protected final Expression topLevel; /** ExpressionPool object that this VGM uses. */ public final ExpressionPool pool; public REDocumentDeclaration( Grammar grammar ) { this( grammar.getTopLevel(), grammar.getPool() ); } /** * creates an object that validates the specified expression. */ public REDocumentDeclaration( Expression topLevel, ExpressionPool pool ) { this.topLevel = topLevel; this.pool = pool; resCalc = new ResidualCalculator(pool); attFeeder = new AttributeFeeder(this); attPicker = new AttributePicker(pool); attPruner = new AttributePruner(pool); attRemover = new AttributeRemover(pool); cccec = new CombinedChildContentExpCreator(pool); ecc = new ElementsOfConcernCollector(); attToken = new AttributeToken(this,null,null,null,null); } // thread local objects. // for these function objects, one per a thread is enough. protected final ResidualCalculator resCalc; protected final CombinedChildContentExpCreator cccec; protected final AttributeFeeder attFeeder; protected final AttributePruner attPruner; protected final AttributePicker attPicker; protected final AttributeRemover attRemover; protected final ElementsOfConcernCollector ecc; /** * the AttributeToken object which is re-used * *

        * Only one AttributeToken object is used during the * {@link Acceptor#onAttribute} method. * So instead of creating new object every time the method is called, we can * kept using one copy. * *

        * Note: other parts of the code may never rely on the fact that * the attribute token is cached and reused. * *

        * Note: this field should be accessed ONLY by the * {@link ExpressionAcceptor#onAttribute} method. */ public final AttributeToken attToken; public Acceptor createAcceptor() { // top-level Acceptor cannot have continuation. return new SimpleAcceptor(this, topLevel, null, Expression.epsilon); } public String localizeMessage( String propertyName, Object[] args ) { String format = java.util.ResourceBundle.getBundle( "com.sun.msv.verifier.regexp.Messages").getString(propertyName); return java.text.MessageFormat.format(format, args ); } public final String localizeMessage( String propName, Object arg1 ) { return localizeMessage(propName, new Object[]{arg1} ); } public final String localizeMessage( String propName, Object arg1, Object arg2 ) { return localizeMessage(propName, new Object[]{arg1,arg2} ); } public static final String DIAG_ELEMENT_NOT_ALLOWED = "Diagnosis.ElementNotAllowed"; public static final String DIAG_CONTENT_MODEL_IS_NULLSET = "Diagnosis.ContentModelIsNullset"; public static final String DIAG_BAD_TAGNAME_GENERIC = "Diagnosis.BadTagName.Generic"; public static final String DIAG_BAD_TAGNAME_WRAPUP = "Diagnosis.BadTagName.WrapUp"; public static final String DIAG_BAD_TAGNAME_SEPARATOR = "Diagnosis.BadTagName.Separator"; public static final String DIAG_BAD_TAGNAME_MORE = "Diagnosis.BadTagName.More"; public static final String DIAG_BAD_TAGNAME_WRONG_NAMESPACE = "Diagnosis.BadTagName.WrongNamespace"; public static final String DIAG_BAD_TAGNAME_PROBABLY_WRONG_NAMESPACE = "Diagnosis.BadTagName.ProbablyWrongNamespace"; public static final String DIAG_UNDECLARED_ATTRIBUTE = "Diagnosis.UndeclaredAttribute"; public static final String DIAG_BAD_ATTRIBUTE_VALUE_GENERIC = "Diagnosis.BadAttributeValue.Generic"; public static final String DIAG_BAD_ATTRIBUTE_VALUE_DATATYPE = "Diagnosis.BadAttributeValue.DataType"; public static final String DIAG_BAD_ATTRIBUTE_VALUE_WRAPUP = "Diagnosis.BadAttributeValue.WrapUp"; public static final String DIAG_BAD_ATTRIBUTE_VALUE_SEPARATOR = "Diagnosis.BadAttributeValue.Separator"; public static final String DIAG_BAD_ATTRIBUTE_VALUE_MORE = "Diagnosis.BadAttributeValue.More"; public static final String DIAG_MISSING_ATTRIBUTE_SIMPLE = "Diagnosis.MissingAttribute.Simple"; public static final String DIAG_MISSING_ATTRIBUTE_GENERIC = "Diagnosis.MissingAttribute.Generic"; public static final String DIAG_MISSING_ATTRIBUTE_WRAPUP = "Diagnosis.MissingAttribute.WrapUp"; public static final String DIAG_MISSING_ATTRIBUTE_SEPARATOR = "Diagnosis.MissingAttribute.Separator"; public static final String DIAG_MISSING_ATTRIBUTE_MORE = "Diagnosis.MissingAttribute.More"; public static final String DIAG_UNCOMPLETED_CONTENT_WRAPUP = "Diagnosis.UncompletedContent.WrapUp"; public static final String DIAG_UNCOMPLETED_CONTENT_SEPARATOR = "Diagnosis.UncompletedContent.Separator"; public static final String DIAG_UNCOMPLETED_CONTENT_MORE = "Diagnosis.UncompletedContent.More"; public static final String DIAG_BAD_LITERAL_WRAPUP = // arg:2 "Diagnosis.BadLiteral.WrapUp"; public static final String DIAG_BAD_LITERAL_SEPARATOR = "Diagnosis.BadLiteral.Separator"; public static final String DIAG_BAD_LITERAL_MORE = "Diagnosis.BadLiteral.More"; public static final String DIAG_BAD_LITERAL_GENERIC = // arg:1 "Diagnosis.BadLiteral.Generic"; public static final String DIAG_BAD_LITERAL_INCORRECT_VALUE = // arg:2 "Diagnosis.BadLiteral.IncorrectValue"; public static final String DIAG_SIMPLE_NAMECLASS = "Diagnosis.SimpleNameClass"; public static final String DIAG_NAMESPACE_NAMECLASS = "Diagnosis.NamespaceNameClass"; public static final String DIAG_NOT_NAMESPACE_NAMECLASS = "Diagnosis.NotNamespaceNameClass"; public static final String DIAG_STRING_NOT_ALLOWED = // arg:1 "Diagnosis.StringNotAllowed"; public static final String DIAG_BAD_KEY_VALUE = // arg:1 "Diagnosis.BadKeyValue"; public static final String DIAG_BAD_KEY_VALUE2 = // arg:2 "Diagnosis.BadKeyValue2"; } msv-2009.1/msv/src/com/sun/msv/verifier/regexp/AttributePruner.java0000644000175000017500000000346007671170035025524 0ustar giovannigiovanni/* * @(#)$Id: AttributePruner.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.regexp; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionCloner; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.OtherExp; import com.sun.msv.grammar.ReferenceExp; /** * Creates an expression whose AttributeExp is completely replaced by nullSet. * * This step is used to remove all unconsumed AttributeExp from the expression. * * @author Kohsuke KAWAGUCHI */ public class AttributePruner extends ExpressionCloner { public AttributePruner( ExpressionPool pool ) { super(pool); } public Expression onAttribute( AttributeExp exp ) { return Expression.nullSet; } public Expression onRef( ReferenceExp exp ) { return exp.exp.visit(this); } public Expression onOther( OtherExp exp ) { return exp.exp.visit(this); } public Expression onElement( ElementExp exp ) { return exp; } public final Expression prune( Expression exp ) { // check the cache first. OptimizationTag ot = (OptimizationTag)exp.verifierTag; if(ot==null) exp.verifierTag = ot = new OptimizationTag(); else if( ot.attributePrunedExpression!=null ) return ot.attributePrunedExpression; // cache miss. compute it. Expression r = exp.visit(this); ot.attributePrunedExpression = r; // cache this result return r; } } msv-2009.1/msv/src/com/sun/msv/verifier/regexp/SimpleAcceptor.java0000644000175000017500000000365607671170035025306 0ustar giovannigiovanni/* * @(#)$Id: SimpleAcceptor.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.regexp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.verifier.Acceptor; /** * Acceptor that will be used when only one ElementExp matches * the start tag. * * @author Kohsuke KAWAGUCHI */ public class SimpleAcceptor extends ContentModelAcceptor { /** * the expression that should be used by the parent acceptor * once if this acceptor is satisfied. * * This field can be null. In that case, the continuation has to be computed. */ public final Expression continuation; /** * ElementExp that accepted the start tag. * * This acceptor is verifying the content model of this ElementExp. * This value is usually non-null, but can be null when Verifier is * recovering from eariler errors. * null owner means this acceptor is "synthesized" just for proper error recovery, * therefor there is no owner element expression. */ public final ElementExp owner; public final Object getOwnerType() { return owner; } public SimpleAcceptor( REDocumentDeclaration docDecl, Expression combined, ElementExp owner, Expression continuation ) { super(docDecl,combined, // ignore undeclared attributes if we are recovering from errors. (owner==null)?true:owner.ignoreUndeclaredAttributes); this.continuation = continuation; this.owner = owner; } public Acceptor createClone() { return new SimpleAcceptor( docDecl, getExpression(), owner, continuation ); } } msv-2009.1/msv/src/com/sun/msv/verifier/regexp/CombinedChildContentExpCreator.java0000644000175000017500000003607607671170035030412 0ustar giovannigiovanni/* * @(#)$Id: CombinedChildContentExpCreator.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.regexp; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.ChoiceExp; import com.sun.msv.grammar.ConcurExp; import com.sun.msv.grammar.DataExp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.ExpressionVisitorVoid; import com.sun.msv.grammar.InterleaveExp; import com.sun.msv.grammar.ListExp; import com.sun.msv.grammar.MixedExp; import com.sun.msv.grammar.OneOrMoreExp; import com.sun.msv.grammar.OtherExp; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.SequenceExp; import com.sun.msv.grammar.ValueExp; import com.sun.msv.util.StartTagInfo; import com.sun.msv.util.StringPair; /** * creates "combined child content expression" and gathers "elements of concern" * and its "attribute-pruned" content model. * * Intuitively, "combined child content expression" is a set of * content models of "elements of concern", * which is appropriately combined to express dependency between elements. * * "Elements of concern" are ElementExps that are possibly applicable to * the next element. These gathered element declarations are then tested against * next XML element. * * "Attribute-pruned" content model is a content model after consuming * AttributeTokens and removing unused AttributeExp nodes. * *

        * For example, when the current expression is *

            <!-- javadoc escape -->
         *   <choice>
         *     <concur>
         *       <element> ..(A).. </element>
         *       <group>
         *         <element> ..(B).. </element>
         *         ...
         *       </group>
         *     </concur>
         *     <group>
         *       <element> ..(C).. </element>
         *       ....
         *     </group>
         *   </choice>
         * 
        * * then the combined child expression is * *
        
         *   <choice>
         *     <concur>
         *       ..(A').. 
         *       ..(B').. 
         *     </concur>
         *     ..(C').. 
         *   </choice>
         * 
        * * and elements of concern and its attribute-pruned content models are * * * <element> ..(A).. </element> -> ..(A').. * <element> ..(B).. </element> -> ..(B').. * <element> ..(C).. </element> -> ..(C').. * * * (A'),(B'), and (C') are attribute-pruned content models of (A),(B), and (C) * respectively. * * Note that combined child pattern contains only <choice> and <concur> as * its grue (of course, except ..(A').. , ..(B').. , and ..(C').. ). * * * This function object also calculates "continuation", which is the residual * expression after eating elements of concern. * * For example, say the expression is "(A|(B,C))?,D". * * When EoC is B, then the continuation will be C,D. * When EoC is A, then the continuation will be D. * When EoC is D, then the continuation will be epsilon. * * When there are multiple EoC, (say A and B), then * the continuation will be meaningless (because it depends on which EoC will * be accepted), and thus won't be used. * * However, the implementator must be aware that it is possible for a * binary operator to have EoC on both branch and EoC is still unique. * The following expression is an example. * * (A|B)*,C?,(A|B)* * * when A is EoC, SequenceExp of (A|B)* and C?,(A|B)* has EoC on both branch. * * @author Kohsuke KAWAGUCHI */ public class CombinedChildContentExpCreator implements ExpressionVisitorVoid { protected final ExpressionPool pool; // these variables are set each time 'get' method is called private StartTagInfo tagInfo; /** * matched elements. the buffer is usually bigger than {@link #numElements}, * but only first {@link #numElements} items are valid result. */ private ElementExp[] result = new ElementExp[4]; private int numElements; private boolean checkTagName; // TODO: do we gain some performance if we stop creating combined child content expression // (for RELAX, c.c.c.e is unnecessary) // TODO: how many object instanciation can we avoid // if we keep one local reusable copy of OwnerAndContent? public static class ExpressionPair { public final Expression content; public final Expression continuation; public ExpressionPair(Expression content, Expression continuation) { this.content = content; this.continuation = continuation; } } /* Ideally, these two fields should be return values from onXXX methods. In fact, this class was once made in that way. However, to return two values, we need to create an object to wrap them, and it takes memory and time. An experiment shows that ExpressionPairs used for that purpose occupies 1/4 (in number) of object instanciation of the entire obejcts created in Verifier.startElement method. So now it is rewritten to use this instance fields instead of return values. */ private Expression content; private Expression continuation; protected CombinedChildContentExpCreator(ExpressionPool pool) { this.pool = pool; } /** * computes a combined child content pattern and its continuation, with error recovery. * * After calling this method, caller can call getElementsOfConcern to obtain * each EoC. * If both feedAttributes and checkTagName are false, then StartTagInfo is * also unnecessary. * * @param feedAttributes * if this flag is false, Attribute feeding & pruning are skipped and * AttributeExps are fully remained in the resulting expression. * @param checkTagName * if this flag is false, tag name check is skipped. */ public ExpressionPair get(Expression combinedPattern, StartTagInfo info, boolean checkTagName) { if (com.sun.msv.driver.textui.Debug.debug) // clear the buffer to make it easier to find a bug. for (int i = 0; i < result.length; i++) result[i] = null; numElements = 0; return continueGet(combinedPattern, info, checkTagName); } public final ExpressionPair continueGet(Expression combinedPattern, StartTagInfo info, boolean checkTagName) { foundConcur = false; this.tagInfo = info; this.checkTagName = checkTagName; combinedPattern.visit(this); // when more than one element of concern is found, // continuation cannot be used. if (numElements != 1) continuation = null; return new ExpressionPair(content, continuation); } /** computes a combined child content pattern and (,if possible,) its continuation. */ public ExpressionPair get(Expression combinedPattern, StartTagInfo info) { StringPair sp = null; // check the cache if (combinedPattern.verifierTag != null) { OptimizationTag ot = (OptimizationTag)combinedPattern.verifierTag; sp = new StringPair(info.namespaceURI, info.localName); OptimizationTag.OwnerAndCont cache = (OptimizationTag.OwnerAndCont)ot.transitions.get(sp); if (cache != null) { // cache hit numElements = 1; result[0] = cache.owner; return new ExpressionPair(cache.owner.contentModel.getExpandedExp(pool), cache.continuation); } } ExpressionPair r = (ExpressionPair)get(combinedPattern, info, true); if (numElements == 1) { // only one element matchs this tag name. cache this result OptimizationTag ot = (OptimizationTag)combinedPattern.verifierTag; if (ot == null) combinedPattern.verifierTag = ot = new OptimizationTag(); if (sp == null) sp = new StringPair(info.namespaceURI, info.localName); ot.transitions.put(sp, new OptimizationTag.OwnerAndCont(result[0], r.continuation)); } return r; } /** * obtains matched elements. * * This method should be called after calling the get method. The result is * in effect until the next invocation of get method. * *

        * The extra care should be taken not to hold reference to the result * longer than necessary. * The contents of the result is valid only until the next invocation. * Because OwnerAndContent objects are reused. * *

        * Apparently this is a bad design, but this design gives us better performance. */ public final ElementExp[] getMatchedElements() { return result; } /** gets the number of matched elements. * * This method should be called after calling get method. The result is * in effect until next invocation of get method. * Apparently this is a bad design, but this design gives us better performance. */ public final int numMatchedElements() { return numElements; } /** * a flag that indicates that we have 'concur' element to combine * elements of concern. * * If 'concur' is used, we have to keep track of combined child content * expression to detect errors. If 'concur' is not used, then * keeping track of all primitive child content expressions are enough * to detect errors. */ private boolean foundConcur; public void onConcur(ConcurExp exp) { foundConcur = true; exp.exp1.visit(this); Expression content1 = content; Expression continuation1 = continuation; exp.exp2.visit(this); content = pool.createConcur(content, content1); continuation = pool.createConcur(continuation, continuation1); } public void onInterleave(InterleaveExp exp) { exp.exp1.visit(this); if (content == Expression.nullSet) { exp.exp2.visit(this); continuation = pool.createInterleave(continuation, exp.exp1); return; } Expression content1 = content; Expression continuation1 = continuation; exp.exp2.visit(this); if (content == Expression.nullSet) { content = content1; continuation = pool.createInterleave(continuation1, exp.exp2); return; } // now the situation is something like (A,X)^(A,Y). // both accepts this token. So continuation will be X^(A,Y). content = pool.createChoice(content, content1); continuation = pool.createInterleave(continuation1, exp.exp2); } /** * checks if the result of 'get' method is not the union of all * elements of concern. * * Within this class, combined child content expression is * always the union of all elements of concern. However, some derived * class does not guarantee this property. * * @return * true if the combined child content expression is not * the union of all elements of concern. * false if otherwise. */ public final boolean isComplex() { return foundConcur; } public void onElement(ElementExp exp) { // TODO: may check result and remove duplicate result // if tag name is invalid, then remove this element from candidate. if (checkTagName && !exp.getNameClass().accepts(tagInfo.namespaceURI, tagInfo.localName)) { content = continuation = Expression.nullSet; return; } // check result and see if the same element is already registered. // this will reduce the complexity of the result. // some RELAX grammar may contain something like // (A|B)* C? (A|B)* to implement interleaving of (A|B)* and C. // this check becomes important for cases like this. for (int i = 0; i < numElements; i++) if (result[i] == exp) { // the same element is found. content = exp.contentModel.getExpandedExp(pool); continuation = Expression.epsilon; return; } // also, feeding and pruning attributes are relatively expensive operation. // so this is the good place to check other redundancy. // create a new result object if (numElements == result.length) { // expand the buffer if it's full. ElementExp[] buf = new ElementExp[result.length * 2]; System.arraycopy(result, 0, buf, 0, result.length); result = buf; } result[numElements++] = exp; content = exp.contentModel.getExpandedExp(pool); continuation = Expression.epsilon; } public void onOneOrMore(OneOrMoreExp exp) { exp.exp.visit(this); continuation = pool.createSequence(continuation, pool.createZeroOrMore(exp.exp)); } public void onMixed(MixedExp exp) { exp.exp.visit(this); continuation = pool.createMixed(continuation); } public void onAttribute( AttributeExp exp ) { content = continuation = Expression.nullSet; } public void onEpsilon() { content = continuation = Expression.nullSet; } public void onNullSet() { content = continuation = Expression.nullSet; } public void onAnyString() { content = continuation = Expression.nullSet; } public void onData( DataExp exp ) { content = continuation = Expression.nullSet; } public void onValue( ValueExp exp ) { content = continuation = Expression.nullSet; } public void onList( ListExp exp ) { content = continuation = Expression.nullSet; } public void onRef(ReferenceExp exp) { exp.exp.visit(this); } public void onOther(OtherExp exp) { exp.exp.visit(this); } public void onChoice(ChoiceExp exp) { exp.exp1.visit(this); Expression content1 = content; Expression continuation1 = continuation; exp.exp2.visit(this); content = pool.createChoice(content, content1); continuation = pool.createChoice(continuation, continuation1); } public void onSequence(SequenceExp exp) { exp.exp1.visit(this); continuation = pool.createSequence(continuation, exp.exp2); if (!exp.exp1.isEpsilonReducible()) return; Expression content1 = content; Expression continuation1 = continuation; exp.exp2.visit(this); if (content == Expression.nullSet) { content = content1; continuation = continuation1; return; } if (content1 == Expression.nullSet) { // exp1 is epsilon reducible but didn't accept this token. // so continuation will be that of exp2. return; } // now, we have candidates in both left and right. // say, // exp = (A,X)?,(A,Y) content = pool.createChoice(content, content1); continuation = pool.createChoice(continuation1, continuation); } } msv-2009.1/msv/src/com/sun/msv/verifier/regexp/ComplexAcceptor.java0000644000175000017500000000545507671170035025463 0ustar giovannigiovanni/* * @(#)$Id: ComplexAcceptor.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.regexp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.verifier.Acceptor; /** * Accept that is used when more than one pattern can be applicable to the current context. * * @author Kohsuke KAWAGUCHI */ public final class ComplexAcceptor extends ComplexAcceptorBaseImpl { /** * each item of this array should be considered as read-only. */ public final ElementExp[] owners; private static Expression[] createDefaultContentModels( ElementExp[] owners, ExpressionPool pool ) { Expression[] r = new Expression[owners.length]; for( int i=0; iKohsuke KAWAGUCHI */ public class ElementToken extends Token { final ElementExp[] acceptedPatterns; public ElementToken( ElementExp[] acceptedPatterns ) { this.acceptedPatterns = acceptedPatterns; } public boolean match( ElementExp exp ) { // since every subpatterns are reused, object identity is enough // to judge the equality of patterns for( int i=0; iKohsuke KAWAGUCHI */ public class StringCareLevelCalculator implements ExpressionVisitor { protected StringCareLevelCalculator(){} /** singleton instance. */ protected static final StringCareLevelCalculator theInstance = new StringCareLevelCalculator(); // those expressions which are sensitive about string must return true public Object onAttribute( AttributeExp exp ) { return NO_STRING; } public Object onElement( ElementExp exp ) { return NO_STRING; } public Object onMixed( MixedExp exp ) { return ANY_STRING; } public Object onList( ListExp exp ) { return SOME_STRING; } public Object onAnyString() { return ANY_STRING; } public Object onData( DataExp exp ) { if(exp.except==Expression.nullSet && exp.dt instanceof XSDatatype) { XSDatatype xdt = (XSDatatype)exp.dt; if(xdt.isAlwaysValid()) return ANY_STRING; } return SOME_STRING; } public Object onValue( ValueExp exp ) { return SOME_STRING; } public Object onChoice(ChoiceExp exp) { return doChoice(exp); } private Object doChoice(BinaryExp exp) { Object lhs = exp.exp1.visit(this); Object rhs = exp.exp2.visit(this); if(lhs==ANY_STRING && rhs==ANY_STRING) return ANY_STRING; if(lhs==NO_STRING && rhs==NO_STRING) return NO_STRING; return SOME_STRING; } public Object onOneOrMore(OneOrMoreExp exp) { return exp.exp.visit(this); } public Object onRef(ReferenceExp exp) { return exp.exp.visit(this); } public Object onOther(OtherExp exp) { return exp.exp.visit(this); } public Object onEpsilon() { return NO_STRING; } public Object onNullSet() { return NO_STRING; } public Object onSequence(SequenceExp exp) { if(!exp.exp1.isEpsilonReducible()) return exp.exp1.visit(this); else return doChoice(exp); } public Object onConcur(ConcurExp exp) { Object lhs = exp.exp1.visit(this); Object rhs = exp.exp2.visit(this); if(lhs==ANY_STRING && rhs==ANY_STRING) return ANY_STRING; if(lhs==NO_STRING || rhs==NO_STRING) return NO_STRING; return SOME_STRING; } public Object onInterleave(InterleaveExp p) { return doChoice(p); } public static int calc( Expression exp ) { Object r = exp.visit(theInstance); if(r==ANY_STRING) return Acceptor.STRING_IGNORE; if(r==NO_STRING) return Acceptor.STRING_PROHIBITED; return Acceptor.STRING_STRICT; } private static final String ANY_STRING = "anyString"; private static final String NO_STRING = "noString"; private static final String SOME_STRING = "someString"; } msv-2009.1/msv/src/com/sun/msv/verifier/regexp/StringToken.java0000644000175000017500000001515610326274571024642 0ustar giovannigiovanni/* * @(#)$Id: StringToken.java 1700 2005-10-21 23:27:53Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.regexp; import java.util.StringTokenizer; import org.relaxng.datatype.Datatype; import com.sun.msv.datatype.xsd.StringType; import com.sun.msv.grammar.DataExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.IDContextProvider2; import com.sun.msv.grammar.ListExp; import com.sun.msv.grammar.ValueExp; import com.sun.msv.util.DatatypeRef; /** * chunk of string. * * ID validation depends on the immutability of this object. * * @author Kohsuke KAWAGUCHI */ public class StringToken extends Token { public final String literal; public final IDContextProvider2 context; protected final ResidualCalculator resCalc; protected final boolean ignorable; /** * if this field is non-null, * this field will receive assigned DataType object. */ public DatatypeRef refType; protected boolean saturated = false; private static final Datatype[] ignoredType = new Datatype[0]; public StringToken(REDocumentDeclaration docDecl, String literal, IDContextProvider2 context) { this(docDecl.resCalc, literal, context, null); } public StringToken(REDocumentDeclaration docDecl, String literal, IDContextProvider2 context, DatatypeRef refType) { this(docDecl.resCalc, literal, context, refType); } public StringToken(ResidualCalculator resCalc, String literal, IDContextProvider2 context, DatatypeRef refType) { this.resCalc = resCalc; this.literal = literal; this.context = context; this.refType = refType; this.ignorable = literal.trim().length() == 0; if (ignorable && refType != null) refType.types = ignoredType; } /** DataExp can consume this token if its datatype can accept this string */ public boolean match(DataExp exp) { if (!exp.dt.isValid(literal, context)) return false; // not accepted. if (exp.except != Expression.nullSet) { if (resCalc.calcResidual(exp.except, this).isEpsilonReducible()) // handling whitespace correcly requires isEpsilonReducible() // with the following test case // // with "". return false; // this token is accepted by its 'except' clause } // this type accepts me. if (refType != null) assignType(exp.dt); // if the type has ID semantics, report it. if (exp.dt.getIdType() != Datatype.ID_TYPE_NULL && context != null) // context can be legally null when this datatype is not context dependent. context.onID(exp.dt, this); return true; } public boolean match(ValueExp exp) { Object thisValue = exp.dt.createValue(literal, context); if (!exp.dt.sameValue(thisValue, exp.value)) return false; // this type accepts me. if (refType != null) assignType(exp.dt); // if the type has ID semantics, report it. if (exp.dt.getIdType() != Datatype.ID_TYPE_NULL && context != null) // context can be legally null when this datatype is not context dependent. context.onID(exp.dt, this); return true; } /** ListExp can consume this token if its pattern accepts this string */ public boolean match(ListExp exp) { StringTokenizer tokens = new StringTokenizer(literal); Expression residual = exp.exp; // if the application needs type information, // collect them from children. DatatypeRef dtRef = null; Datatype[] childTypes = null; int cnt = 0; if (this.refType != null) { dtRef = new DatatypeRef(); childTypes = new Datatype[tokens.countTokens()]; } while (tokens.hasMoreTokens()) { StringToken child = createChildStringToken(tokens.nextToken(), dtRef); residual = resCalc.calcResidual(residual, child); if (residual == Expression.nullSet) // the expression is failed to accept this item. return false; if (dtRef != null) { if (dtRef.types == null) { // failed to assign type. bail out. saturated = true; refType.types = null; dtRef = null; } else { // type is successfully assigned for this child. if (dtRef.types.length != 1) // the current RELAX NG prohibits to nest patterns. // Thus it's not possible for this child to return more than one type. throw new Error(); childTypes[cnt++] = dtRef.types[0]; } } } if (!residual.isEpsilonReducible()) // some expressions are still left. failed to accept this string. return false; // this accepts this string. if (childTypes != null) { // assign datatype if (saturated) // a type is already assigned. That means this string has more than one type. // so bail out. refType.types = null; else refType.types = childTypes; saturated = true; } return true; } protected StringToken createChildStringToken(String literal, DatatypeRef dtRef) { return new StringToken(resCalc, literal, context, dtRef); } // anyString can match any string public boolean matchAnyString() { if (refType != null) assignType(StringType.theInstance); return true; } private void assignType(Datatype dt) { if (saturated) { if (refType.types != null && (refType.types[0] != dt || refType.types.length != 1)) // different types are assigned. roll back to null refType.types = null; } else { // this is the first assignment. remember this value. refType.types = new Datatype[] { dt }; saturated = true; } } /** checks if this token is ignorable. * * StringToken is ignorable when it matches [ \t\r\n]* */ boolean isIgnorable() { return ignorable; } } msv-2009.1/msv/src/com/sun/msv/verifier/regexp/StringRecoveryToken.java0000644000175000017500000000370107671170035026351 0ustar giovannigiovanni/* * @(#)$Id: StringRecoveryToken.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.regexp; import java.util.Set; import com.sun.msv.grammar.DataExp; import com.sun.msv.grammar.ListExp; import com.sun.msv.grammar.ValueExp; import com.sun.msv.util.DatatypeRef; /** * special StringToken that acts as a wild card. * * This object is used for error recovery. It collects all TypedStringExps * that ate the token. * * @author Kohsuke KAWAGUCHI */ class StringRecoveryToken extends StringToken { StringRecoveryToken( StringToken base ) { this( base, new java.util.HashSet() ); } StringRecoveryToken( StringToken base, Set failedExps ) { super( base.resCalc, base.literal, base.context, null ); this.failedExps = failedExps; } /** * TypedStringExps and ListExps that * rejected this token are collected into this set. */ final Set failedExps; public boolean match( DataExp exp ) { if( super.match(exp) ) return true; // this datatype didn't accept me. so record it for diagnosis. failedExps.add( exp ); return true; } public boolean match( ValueExp exp ) { if( super.match(exp) ) return true; // this datatype didn't accept me. so record it for diagnosis. failedExps.add( exp ); return true; } public boolean match( ListExp exp ) { super.match(exp); return true; } protected StringToken createChildStringToken( String literal, DatatypeRef dtRef ) { return new StringRecoveryToken( new StringToken( resCalc, literal, context, dtRef ) ); } } msv-2009.1/msv/src/com/sun/msv/verifier/regexp/ContentModelRefExpRemover.java0000644000175000017500000000330607671170035027431 0ustar giovannigiovanni/* * @(#)$Id: ContentModelRefExpRemover.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.regexp; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionCloner; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.OtherExp; import com.sun.msv.grammar.ReferenceExp; /** * Non-recursive ReferenceExpRemover with a cache. * * @author Kohsuke KAWAGUCHI */ public class ContentModelRefExpRemover { // public static Expression remove( Expression exp, ExpressionPool pool ) { // return exp.getExpandedExp(pool); // } // the class that does the actual job. private static class Remover extends ExpressionCloner { public Remover(ExpressionPool pool) { super(pool); } public Expression onElement(ElementExp exp) { return exp; } public Expression onAttribute(AttributeExp exp) { Expression content = exp.exp.visit(this); if (content == Expression.nullSet) return Expression.nullSet; // this attribute is not allowed else return pool.createAttribute(exp.nameClass, content); } public Expression onRef(ReferenceExp exp) { return exp.exp.visit(this); } public Expression onOther(OtherExp exp) { return exp.exp.visit(this); } } } msv-2009.1/msv/src/com/sun/msv/verifier/regexp/xmlschema/0000755000175000017500000000000011622453067023500 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/verifier/regexp/xmlschema/XSAcceptor.java0000644000175000017500000002174107671170035026363 0ustar giovannigiovanni/* * @(#)$Id: XSAcceptor.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.regexp.xmlschema; import org.relaxng.datatype.DatatypeException; import com.sun.msv.datatype.xsd.DatatypeFactory; import com.sun.msv.datatype.xsd.QnameType; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.xmlschema.ComplexTypeExp; import com.sun.msv.grammar.xmlschema.ElementDeclExp; import com.sun.msv.grammar.xmlschema.SimpleTypeExp; import com.sun.msv.grammar.xmlschema.XMLSchemaSchema; import com.sun.msv.grammar.xmlschema.XMLSchemaTypeExp; import com.sun.msv.util.StartTagInfo; import com.sun.msv.util.StringRef; import com.sun.msv.verifier.Acceptor; import com.sun.msv.verifier.regexp.AttributeToken; import com.sun.msv.verifier.regexp.SimpleAcceptor; /** * Acceptor implementation for XSREDocDecl. * *

        * This class should be considered as a "quick-hack" to * better accomodate W3C XML Schema. */ public class XSAcceptor extends SimpleAcceptor { public static final String XSINamespace = "http://www.w3.org/2001/XMLSchema-instance"; public static final String XMLSchemaNamespace = "http://www.w3.org/2001/XMLSchema"; public XSAcceptor( XSREDocDecl docDecl, Expression combined, ElementExp owner, Expression continuation ) { super(docDecl,combined,owner,continuation); this._docDecl = docDecl; } public Acceptor createClone() { return new XSAcceptor( _docDecl, getExpression(), owner, continuation ); } /** * holds the same value as the docDecl field, but this one has * already down casted to XSREDocDecl. */ private final XSREDocDecl _docDecl; /** * creates an XSAcceptor instead of default acceptor implementations. */ protected Acceptor createAcceptor( Expression combined, Expression continuation, ElementExp[] primitives, int numPrimitives ) { if( primitives==null || numPrimitives<=1 ) { // primitives==null is possible when recovering from error. // in this special case, combined child pattern and primitive patterns are the same. // therefore we don't need to keep track of primitive patterns. return new XSAcceptor( (XSREDocDecl)docDecl, combined, (primitives==null)?null:primitives[0], continuation ); } // we don't want to use complex acceptor because it doesn't implement // XML Schema semantics. // And in XML Schema, content model can never be ambiguous. // so complex acceptor is used only for error recovery. // // So, as a workaround, create a simple acceptor from the first possible choice, // and throw other options away. return new XSAcceptor( (XSREDocDecl)docDecl, primitives[0].contentModel.getExpandedExp(docDecl.pool), primitives[0], null ); } protected boolean onAttribute( AttributeToken token, StringRef refErr ) { // xsi:*** attribute is ignored. // TODO: maybe we should issue an error for unrecognized xsi:*** attributes. if( token.namespaceURI.equals(XSINamespace) ) { token.match(_docDecl.xsiAttExp); return true; } return super.onAttribute( token, refErr ); } public Acceptor createChildAcceptor( StartTagInfo sti, StringRef refErr ) { final String type = sti.getAttribute(XSINamespace,"type"); final String nil = sti.getAttribute(XSINamespace,"nil"); if( type==null && nil==null ) // no need for the special handling. return super.createChildAcceptor(sti,refErr); // // craetes combined child content model. // it should be uniquely computed. // /*CombinedChildContentExpCreator.ExpressionPair result =*/ _docDecl.getCCCEC().get( getExpression(), sti, true ); switch( _docDecl.getCCCEC().numMatchedElements() ) { case 0: // no element matches. The default implementation would properly // handle this situation and recover from this error. return super.createChildAcceptor(sti,refErr); case 1: break; default: // ambiguous. Generally, this is not possible for XML Schema, // but this maybe because of the error recovery. // abandon XML Schema specific processing and delegate to the // default implementation. return super.createChildAcceptor(sti,refErr); } // obtain the ElementExp that mathced this start tag. final ElementExp element = _docDecl.getCCCEC().getMatchedElements()[0]; if(!(element instanceof ElementDeclExp.XSElementExp)) { // it's not an element of XML Schema. // we don't need to handle xsi:*** for this element. return super.createChildAcceptor(sti,refErr); } final ElementDeclExp.XSElementExp xe = (ElementDeclExp.XSElementExp)element; // see if there is a nil attribute if(nil!=null) { if( !xe.parent.isNillable ) { // error if( refErr==null ) return null; refErr.str = _docDecl.localizeMessage( XSREDocDecl.ERR_NON_NILLABLE_ELEMENT, sti.qName ); return new XSAcceptor( _docDecl, Expression.epsilon, xe, null ); } if( nil.trim().equals("true") ) { if( com.sun.msv.driver.textui.Debug.debug ) System.out.println("xsi:nil is found"); // it should only accept empty tag without any attribute. return new XSAcceptor( _docDecl, Expression.epsilon, xe, null ); } // TODO: should we issue an error if the value is something strange? } if(type==null) // there was no xsi:type. Use the default implementation. return super.createChildAcceptor(sti,refErr); String[] typeName = (String[])QnameType.theInstance.createJavaObject(type,sti.context); if(typeName==null) return onTypeResolutionFailure(sti,type,refErr); Expression contentModel; if( typeName[0].equals(XMLSchemaNamespace) ) { // special handling is required for built-in datatypes. try { contentModel = _docDecl.grammar.getPool().createData( DatatypeFactory.getTypeByName(typeName[1]) ); } catch( DatatypeException e ) { return onTypeResolutionFailure(sti,type,refErr); } } else { XMLSchemaSchema schema = _docDecl.grammar.getByNamespace(typeName[0]); if(schema==null) return onTypeResolutionFailure(sti,type,refErr); final XMLSchemaTypeExp currentType = xe.parent.getTypeDefinition(); ComplexTypeExp cexp = schema.complexTypes.get(typeName[1]); if(cexp!=null) { if(cexp.isDerivedTypeOf( currentType, xe.parent.block|currentType.getBlock() )) // this type can substitute the current type. contentModel = cexp; else return onNotSubstitutableType(sti,type,refErr); } else { SimpleTypeExp sexp = schema.simpleTypes.get(typeName[1]); if(sexp==null) return onTypeResolutionFailure(sti,type,refErr); if(!(currentType instanceof SimpleTypeExp)) return onNotSubstitutableType(sti,type,refErr); SimpleTypeExp curT = (SimpleTypeExp)currentType; if(sexp.getDatatype().isDerivedTypeOf( curT.getDatatype(), !xe.parent.isRestrictionBlocked() )) contentModel = sexp; else return onNotSubstitutableType(sti,type,refErr); } } return new XSAcceptor( _docDecl, contentModel, xe, null ); } private Acceptor onNotSubstitutableType( StartTagInfo sti, String type, StringRef refErr ) { if(refErr==null) return null; refErr.str = _docDecl.localizeMessage( XSREDocDecl.ERR_NOT_SUBSTITUTABLE_TYPE, type ); return super.createChildAcceptor(sti,refErr); } private Acceptor onTypeResolutionFailure( StartTagInfo sti, String type, StringRef refErr ) { if(refErr==null) return null; refErr.str = _docDecl.localizeMessage( XSREDocDecl.ERR_UNDEFINED_TYPE, type ); return super.createChildAcceptor(sti,refErr); } } msv-2009.1/msv/src/com/sun/msv/verifier/regexp/xmlschema/package.html0000644000175000017500000000026407333627054025766 0ustar giovannigiovanni

        RegExp VGM implementation that supports special semantics of XML Schema

        This package should be considered as a dity ugly quick-hack.

        msv-2009.1/msv/src/com/sun/msv/verifier/regexp/xmlschema/Messages_ja.properties0000644000175000017500000000067607333627054030053 0ustar giovannigiovanniXMLSchemaVerifier.NonNillableElement = \ \u8981\u7D20"{0}"\u306Fnillable\u3067\u306F\u3042\u308A\u307E\u305B\u3093 XMLSchemaVerifier.NotSubstitutableType = \ \u6307\u5B9A\u3055\u308C\u305F\u578B"{0}"\u3067\u73FE\u5728\u306E\u578B\u3092\u7F6E\u304D\u63DB\u3048\u308B\u3053\u3068\u306F\u51FA\u6765\u307E\u305B\u3093 XMLSchemaVerifier.UndefinedType = \ "{0}"\u306F\u578B\u3068\u3057\u3066\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u305B\u3093 msv-2009.1/msv/src/com/sun/msv/verifier/regexp/xmlschema/XSREDocDecl.java0000644000175000017500000000562511156747174026361 0ustar giovannigiovanni/* * @(#)$Id: XSREDocDecl.java 1744 2009-03-14 15:34:20Z bimargulies $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.regexp.xmlschema; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.NamespaceNameClass; import com.sun.msv.grammar.xmlschema.XMLSchemaGrammar; import com.sun.msv.verifier.Acceptor; import com.sun.msv.verifier.identity.IDConstraintChecker; import com.sun.msv.verifier.regexp.AttributeFeeder; import com.sun.msv.verifier.regexp.CombinedChildContentExpCreator; import com.sun.msv.verifier.regexp.REDocumentDeclaration; /** * {@link REDocumentDeclaration} that supports several W3C XML Schema * specific semantics. * *

        * If you do validation by using W3C XML Schema, then you should use * this VGM instead of plain REDocumentDeclaration. * You should also use {@link IDConstraintChecker} instead of Verifier class. * *

        * This package implements the following things: *

          *
        1. the xsi:nil attribute support. *
        2. the runtime type substitution by the xsi:type attribute *
        */ public class XSREDocDecl extends REDocumentDeclaration { public XSREDocDecl( XMLSchemaGrammar grammar ) { super(grammar); this.grammar = grammar; } public Acceptor createAcceptor() { // use XSAcceptor instead return new XSAcceptor(this, topLevel, null, Expression.epsilon); } CombinedChildContentExpCreator getCCCEC() { return super.cccec; } AttributeFeeder getAttFeeder() { return super.attFeeder; } /** * the grammar which this VGM is using. * * For one, this object is used to find the complex type definition * by its name. */ final protected XMLSchemaGrammar grammar; /** * AttributeExp that matches to "xsi:***" attributes. */ final protected AttributeExp xsiAttExp = new AttributeExp( new NamespaceNameClass(XSAcceptor.XSINamespace), Expression.anyString); public String localizeMessage( String propertyName, Object[] args ) { try { String format = java.util.ResourceBundle.getBundle( "com.sun.msv.verifier.regexp.xmlschema.Messages").getString(propertyName); return java.text.MessageFormat.format(format, args ); } catch( Exception e ) { return super.localizeMessage(propertyName,args); } } public static final String ERR_NON_NILLABLE_ELEMENT = // arg:1 "XMLSchemaVerifier.NonNillableElement"; public static final String ERR_NOT_SUBSTITUTABLE_TYPE = // arg:1 "XMLSchemaVerifier.NotSubstitutableType"; public static final String ERR_UNDEFINED_TYPE = // arg:1 "XMLSchemaVerifier.UndefinedType"; } msv-2009.1/msv/src/com/sun/msv/verifier/regexp/xmlschema/Messages.properties0000644000175000017500000000035107333627054027367 0ustar giovannigiovanni XMLSchemaVerifier.NonNillableElement = \ element "{0}" is not nillable XMLSchemaVerifier.NotSubstitutableType = \ specified type "{0}" cannot substitute the current type XMLSchemaVerifier.UndefinedType = \ undefined type "{0}" msv-2009.1/msv/src/com/sun/msv/verifier/regexp/ComplexAcceptorBaseImpl.java0000644000175000017500000000733007671170035027072 0ustar giovannigiovanni/* * @(#)$Id: ComplexAcceptorBaseImpl.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.regexp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.IDContextProvider2; import com.sun.msv.util.DatatypeRef; import com.sun.msv.util.StartTagInfo; import com.sun.msv.util.StringRef; import com.sun.msv.verifier.Acceptor; /** * base implementation of ComplexAcceptor. * * @author Kohsuke KAWAGUCHI */ public abstract class ComplexAcceptorBaseImpl extends ContentModelAcceptor { protected final Expression[] contents; public ComplexAcceptorBaseImpl( REDocumentDeclaration docDecl, Expression combined, Expression[] contents, boolean ignoreUndeclaredAttributes ) { super( docDecl, combined, ignoreUndeclaredAttributes ); this.contents = contents; } /** eats string literal */ public final boolean onText2( String literal, IDContextProvider2 context, StringRef refErr, DatatypeRef refType ) { if(!super.onText2(literal,context,refErr,refType)) return false; final StringToken token = new StringToken(docDecl,literal,context); final ResidualCalculator res = docDecl.resCalc; // some may become invalid, but at least one always remain valid for( int i=0; i Diagnosis.NamespaceNameClass = \ elements of "{0}" namespace Diagnosis.NotNamespaceNameClass = \ elements of any namespace other than "{0}" Diagnosis.StringNotAllowed = \ No character data is allowed here, but found "{0}" Diagnosis.BadKeyValue = \ ID "{0}" is already defined. Diagnosis.BadKeyValue2 = \ duplicate key value "{0}" for the symbol space "{1}" Diagnosis.BadLiteralValue.WrapUp =\ "{0}" does not satisfy the required data type msv-2009.1/msv/src/com/sun/msv/verifier/regexp/AnyElementToken.java0000644000175000017500000000207707671170035025432 0ustar giovannigiovanni/* * @(#)$Id: AnyElementToken.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.regexp; import com.sun.msv.grammar.ElementExp; /** * special Token that matchs any element. * * this token is used only for error recovery, to compute * "residual of elements of concern"(EoCR). * * EoCR is defined as follows * *
         * EoCR(exp) := exp/e1 | exp/e2 | ... | exp/en
         * 
         * {ei} = elements of concern
         * exp/ei = residual(exp,ei)
         * '|' represents choice
         * 
        * * @author Kohsuke KAWAGUCHI */ public final class AnyElementToken extends ElementToken { /** * use this singleton instance instead of creating an object. */ public static final Token theInstance = new AnyElementToken(); private AnyElementToken(){ super(null); } public boolean match( ElementExp exp ) { return true; } } msv-2009.1/msv/src/com/sun/msv/verifier/regexp/AttributeRecoveryToken.java0000644000175000017500000000274107671170035027051 0ustar giovannigiovanni/* * @(#)$Id: AttributeRecoveryToken.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier.regexp; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.Expression; /** * special AttributeToken that memorizes {@link AttributeExp} that fails to * validate itself. * * @author Kohsuke KAWAGUCHI */ final class AttributeRecoveryToken extends AttributeToken { AttributeRecoveryToken( REDocumentDeclaration docDecl, String namespaceURI, String localName, String qName, StringToken value ) { super( docDecl, namespaceURI, localName, qName, value ); } private Expression failedExp = Expression.nullSet; public boolean match( AttributeExp exp ) { // Attribute name must meet the constraint of NameClass if(!exp.nameClass.accepts(namespaceURI,localName)) return false; // content model of the attribute must consume the value if(!docDecl.resCalc.calcResidual(exp.exp, value).isEpsilonReducible()) failedExp = docDecl.pool.createChoice( failedExp, exp.exp ); // accept AttributeExp regardless of its content restriction return true; } Expression getFailedExp() { return failedExp; } } msv-2009.1/msv/src/com/sun/msv/verifier/Messages.properties0000644000175000017500000000112107350477355024116 0ustar giovannigiovanniVerifier.Error.UnexpectedText = \ unexpected character literal Verifier.Error.UnexpectedAttribute = \ unexpected attribute "{0}" Verifier.Error.UnexpectedStartTag = \ unexpected start tag "{0}". Verifier.Error.MissingAttribute = \ some attributes are missing for the element "{0}". Verifier.Error.UncompletedContent = \ Content of element "{0}" is incomplete Verifier.Error.UnsoldIDREF = \ "{0}" is referenced by an IDREF, but not defined. Verifier.Error.DuplicateId = \ "{0}" is used as an ID value more than once. Verifier.Error.UnexpectedElement =\ unexpected element "{0}" msv-2009.1/msv/src/com/sun/msv/verifier/ValidationUnrecoverableException.java0000644000175000017500000000144607671170035027563 0ustar giovannigiovanni/* * @(#)$Id: ValidationUnrecoverableException.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier; import org.xml.sax.SAXParseException; /** * Exception that signals error was fatal and recovery was not possible. * * @author Kohsuke KAWAGUCHI */ public class ValidationUnrecoverableException extends SAXParseException { public ValidationUnrecoverableException( SAXParseException vv ) { super( vv.getMessage(), vv.getPublicId(), vv.getSystemId(), vv.getLineNumber(), vv.getColumnNumber(), vv ); } } msv-2009.1/msv/src/com/sun/msv/util/0000755000175000017500000000000011622453067017367 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/util/xml/0000755000175000017500000000000011622453067020167 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/util/xml/DOMVisitor.java0000644000175000017500000000212707671170035023033 0ustar giovannigiovanni/* * @(#)$Id: DOMVisitor.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.util.xml; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * visits all DOM elements in the depth-first order (in-order). * * @author * Kohsuke KAWAGUCHI */ public abstract class DOMVisitor { public void visit( Document dom ) { visit( dom.getDocumentElement() ); } public void visit( Element e ) { NodeList lst = e.getChildNodes(); int len = lst.getLength(); for( int i=0; iKohsuke KAWAGUCHI */ public class DocumentFilter implements DocumentHandler { public DocumentHandler next; public DocumentFilter( DocumentHandler next ) { this.next = next; } public void startDocument() throws SAXException { next.startDocument(); } public void endDocument() throws SAXException { next.endDocument(); } public void startElement( String name, AttributeList atts ) throws SAXException { next.startElement(name,atts); } public void endElement( String name ) throws SAXException { next.endElement(name); } public void characters( char[] buf, int start, int len ) throws SAXException { next.characters(buf,start,len); } public void ignorableWhitespace( char[] buf, int start, int len ) throws SAXException { next.ignorableWhitespace(buf,start,len); } public void processingInstruction( String target, String data ) throws SAXException { next.processingInstruction(target,data); } public void setDocumentLocator( Locator loc ) { next.setDocumentLocator(loc); } } msv-2009.1/msv/src/com/sun/msv/util/xml/SAXEventGenerator.java0000644000175000017500000000640307671170035024341 0ustar giovannigiovanni/* * @(#)$Id: SAXEventGenerator.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.util.xml; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; import org.xml.sax.helpers.LocatorImpl; /** * produces SAX2 event from a DOM tree. * * @author * Kohsuke KAWAGUCHI */ public class SAXEventGenerator { /** * scans the specified DOM and sends SAX2 events to the handler. */ public static void parse( Document dom, final ContentHandler handler ) throws SAXException { DOMVisitor visitor = new DOMVisitor(){ public void visit( Element e ) { int attLen = e.getAttributes().getLength(); AttributesImpl atts = new AttributesImpl(); for( int i=0; iKohsuke KAWAGUCHI */ public class DOMBuilder extends DefaultHandler { private final Document dom; private Node parent; public DOMBuilder( Document document ) { this.dom = document; parent = dom; } public DOMBuilder() throws ParserConfigurationException { this( DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() ); } /** * returns DOM. This method should be called after the parsing was completed. */ public Document getDocument() { return dom; } public void startElement( String ns, String local, String qname, Attributes atts ) { Element e = dom.createElementNS( ns, qname ); parent.appendChild(e); parent = e; for( int i=0; i done) { buf.append(s.substring(done, i)); done = i; } if (i == len) break; for (i++; i < len && isExcluded(s.charAt(i)); i++) ; String tem = s.substring(done, i); byte[] bytes; try { bytes = tem.getBytes(utf8); } catch (UnsupportedEncodingException e) { utf8 = "UTF8"; try { bytes = tem.getBytes(utf8); } catch (UnsupportedEncodingException e2) { // Give up return s; } } for (int j = 0; j < bytes.length; j++) { buf.append('%'); buf.append(HEX_DIGITS.charAt((bytes[j] & 0xFF) >> 4)); buf.append(HEX_DIGITS.charAt(bytes[j] & 0xF)); } done = i; } return buf.toString(); } private static String excluded = "<>\"{}|\\^`"; private static boolean isExcluded(char c) { return c <= 0x20 || c >= 0x7F || excluded.indexOf(c) >= 0; } private static boolean isAlpha(char c) { return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'); } private static boolean isHexDigit(char c) { return ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F') || isDigit(c); } private static boolean isDigit(char c) { return '0' <= c && c <= '9'; } private static boolean isSchemeChar(char c) { return isAlpha(c) || isDigit(c) || c == '+' || c == '-' || c =='.'; } private static boolean isValidPercent(String s) { int len = s.length(); for (int i = 0; i < len; i++) if (s.charAt(i) == '%') { if (i + 2 >= len) return false; else if (!isHexDigit(s.charAt(i + 1)) || !isHexDigit(s.charAt(i + 2))) return false; } return true; } private static boolean isValidFragment(String s) { int i = s.indexOf('#'); return i < 0 || s.indexOf('#', i + 1) < 0; } private static boolean isValidScheme(String s) { if (!isAbsolute(s)) return true; int i = s.indexOf(':'); if (i == 0 || i + 1 == s.length() || !isAlpha(s.charAt(0))) return false; while (--i > 0) if (!isSchemeChar(s.charAt(i))) return false; return true; } public static String resolve(String baseUri, String uriReference) { if (!isAbsolute(uriReference) && baseUri != null && isAbsolute(baseUri)) { try { return new URL(new URL(baseUri), uriReference).toString(); } catch (MalformedURLException e) { } } return uriReference; } public static boolean hasFragmentId(String uri) { return uri.indexOf('#') >= 0; } public static boolean isAbsolute(String uri) { int i = uri.indexOf(':'); if (i < 0) return false; while (--i >= 0) { switch (uri.charAt(i)) { case '#': case '/': case '?': return false; } } return true; } } msv-2009.1/msv/src/com/sun/msv/util/StringRef.java0000644000175000017500000000070107671170035022133 0ustar giovannigiovanni/* * @(#)$Id: StringRef.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.util; /** * reference to String. * * @author Kohsuke KAWAGUCHI */ public class StringRef { public String str; } msv-2009.1/msv/src/com/sun/msv/util/package.html0000644000175000017500000000007307273576330021656 0ustar giovannigiovanni

        Miscellaneous utilities

        msv-2009.1/msv/src/com/sun/msv/util/StartTagInfo.java0000644000175000017500000000721111156747174022607 0ustar giovannigiovanni/* * @(#)$Id: StartTagInfo.java 1744 2009-03-14 15:34:20Z bimargulies $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.util; import org.xml.sax.Attributes; import com.sun.msv.datatype.xsd.WhiteSpaceProcessor; import com.sun.msv.grammar.IDContextProvider; import com.sun.msv.grammar.IDContextProvider2; import com.sun.msv.grammar.util.IDContextProviderWrapper; /** * immutable start tag information * * @author Kohsuke KAWAGUCHI */ public class StartTagInfo { public String namespaceURI; public String localName; public String qName; public Attributes attributes; /** * object that provides additional information which is necessary * for validating some datatypes */ public IDContextProvider2 context; protected StartTagInfo() {} /** @deprecated */ public StartTagInfo( String namespaceURI, String localName, String qName, Attributes attributes, IDContextProvider context ) { reinit(namespaceURI,localName,qName,attributes,context); } public StartTagInfo( String namespaceURI, String localName, String qName, Attributes attributes, IDContextProvider2 context ) { reinit(namespaceURI,localName,qName,attributes,context); } public StartTagInfo( String namespaceURI, String localName, String qName, Attributes attributes ) { reinit(namespaceURI,localName,qName,attributes,(IDContextProvider2)null); } /** @deprecated */ public void reinit( String namespaceURI, String localName, String qName, Attributes attributes, IDContextProvider context ) { reinit( namespaceURI, localName, qName, attributes, IDContextProviderWrapper.create(context) ); } /** re-initialize the object with brand new parameters. */ public void reinit( String namespaceURI, String localName, String qName, Attributes attributes, IDContextProvider2 context ) { this.namespaceURI = namespaceURI; this.localName = localName; this.qName = qName; this.attributes = attributes; this.context = context; } public final boolean containsAttribute( String attrName ) { return containsAttribute("",attrName); } public final boolean containsAttribute( String namespaceURI, String attrName ) { return attributes.getIndex(namespaceURI,attrName)!=-1; } /** * gets value of the specified attribute. * * @return null attribute does not exist. */ public final String getAttribute( String attrName ) { return getAttribute("",attrName); } public final String getAttribute( String namespaceURI, String attrName ) { return attributes.getValue(namespaceURI,attrName); } public final String getCollapsedAttribute( String attrName ) { String s = getAttribute(attrName); if(s==null) return null; return WhiteSpaceProcessor.collapse(s); } public final String getDefaultedAttribute( String attrName, String defaultValue ) { return getDefaultedAttribute("",attrName,defaultValue); } public final String getDefaultedAttribute( String namespaceURI, String attrName, String defaultValue ) { String v = getAttribute(namespaceURI,attrName); if(v!=null) return v; else return defaultValue; } } msv-2009.1/msv/src/com/sun/msv/util/DatatypeRef.java0000644000175000017500000000114507671170035022443 0ustar giovannigiovanni/* * @(#)$Id: DatatypeRef.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.util; /** * reference to {@link org.relaxng.datatype.Datatype} * * @author Kohsuke KAWAGUCHI */ public class DatatypeRef { /** * if the size of the array is zero, then that means this token is ignored. */ public org.relaxng.datatype.Datatype[] types = null; } msv-2009.1/msv/src/com/sun/msv/util/StringPair.java0000644000175000017500000000256107671170035022320 0ustar giovannigiovanni/* * @(#)$Id: StringPair.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.util; import com.sun.msv.grammar.SimpleNameClass; /** * pair of Strings. * * @author Kohsuke KAWAGUCHI */ public final class StringPair implements java.io.Serializable { public final String namespaceURI; public final String localName; public StringPair( SimpleNameClass name ) { this(name.namespaceURI, name.localName); } public StringPair( String ns, String ln ) { // assertion check if(ns==null) throw new InternalError("namespace URI is null"); if(ln==null) throw new InternalError("local name is null"); namespaceURI=ns; localName=ln; } public boolean equals( Object o ) { if(!(o instanceof StringPair)) return false; return namespaceURI.equals(((StringPair)o).namespaceURI) && localName.equals(((StringPair)o).localName); } public int hashCode() { return namespaceURI.hashCode()^localName.hashCode(); } public String toString() { return "{"+namespaceURI+"}"+localName; } } msv-2009.1/msv/src/com/sun/msv/util/Util.java0000644000175000017500000000620607746272513021162 0ustar giovannigiovanni/* * @(#)$Id: Util.java 1606 2003-10-24 18:54:03Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.util; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import org.xml.sax.InputSource; /** * Collection of utility methods. * * @author Kohsuke KAWAGUCHI */ public class Util { /** * Gets an InputSource from a string, which contains either * a file name or an URL. */ public static InputSource getInputSource( String fileOrURL ) { try { // try it as an URL new URL(fileOrURL); return new InputSource(fileOrURL); } catch( MalformedURLException e ) { // try it as a file String path = new File(fileOrURL).getAbsolutePath(); if (File.separatorChar != '/') path = path.replace(File.separatorChar, '/'); if (!path.startsWith("/")) path = "/" + path; // if (!path.endsWith("/") && isDirectory()) // path = path + "/"; return new InputSource("file://"+path); } } /** * Checks if a given string is an absolute URI if it is an URI. * *

        * This method does not check whether it is an URI. * *

        * This implementation is based on * * this post. */ public static boolean isAbsoluteURI( String uri ) { int len = uri.length(); if(len==0) return true; // an empty string is OK. if(len<2) return false; char ch = uri.charAt(0); if(('a'<=ch && ch<='z') || ('A'<=ch && ch<='Z')) { for( int i=1; iKohsuke KAWAGUCHI */ public final class LightStack { private Object[] buf = new Object[8]; private int len = 0; public void push( Object o ) { try { buf[len] = o; len++; } catch( ArrayIndexOutOfBoundsException e ) { Object[] nbuf = new Object[buf.length*2]; System.arraycopy( buf, 0, nbuf, 0, buf.length ); buf = nbuf; buf[len++] = o; } } public Object pop() { return buf[--len]; } public Object top() { return buf[len-1]; } public int size() { return len; } public boolean contains( Object o ) { for( int i=0; iKohsuke KAWAGUCHI */ public class TopLevelState extends HedgeRuleBaseState { protected void endSelf( Expression contentModel ) { ((RELAXNSReader)reader).grammar.topLevel = contentModel; } protected State createChildState( StartTagInfo tag ) { // user tends to forget to specify RELAX Core namespace for // topLevel elements. see if this is the case if( tag.namespaceURI.equals(RELAXNSReader.RELAXNamespaceNamespace)) {// bingo. reader.reportError( RELAXNSReader.ERR_TOPLEVEL_PARTICLE_MUST_BE_RELAX_CORE ); // return null so that user will also receive "malplaced element" error. return null; } return super.createChildState(tag); } protected boolean isGrammarElement( StartTagInfo tag ) { // children of must be RELAXCore. if( tag.namespaceURI.equals(RELAXCoreReader.RELAXCoreNamespace) ) return true; // for better error message, allow RELAX Namespace elements. // this error is handled at createChildState method. if( tag.namespaceURI.equals(RELAXNSReader.RELAXNamespaceNamespace) ) return true; return false; } } msv-2009.1/msv/src/com/sun/msv/relaxns/reader/RootGrammarState.java0000644000175000017500000000444307671170035025433 0ustar giovannigiovanni/* * @(#)$Id: RootGrammarState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.relaxns.reader; import com.sun.msv.grammar.Expression; import com.sun.msv.reader.ExpressionOwner; import com.sun.msv.reader.SimpleState; import com.sun.msv.reader.State; import com.sun.msv.relaxns.verifier.IslandSchemaImpl; import com.sun.msv.relaxns.verifier.SchemaProviderImpl; import com.sun.msv.util.StartTagInfo; /** * invokes State object that parses the document element. * * this state is used only one when starting parsing a RELAX schema. * For included module/grammar, different states are used. * * @author Kohsuke KAWAGUCHI */ public class RootGrammarState extends SimpleState implements ExpressionOwner { protected State createChildState( StartTagInfo tag ) { if(tag.localName.equals("grammar") ) // it is a grammar. return new GrammarState(); return null; } protected void endSelf() {// wrap-up. final RELAXNSReader reader = (RELAXNSReader)this.reader; SchemaProviderImpl schemaProvider = new SchemaProviderImpl(reader.grammar); reader.schemaProvider = schemaProvider; if(!reader.controller.hadError()) { // abort further wrap up if there was an error. // then bind it as the final wrap-up. if( !schemaProvider.bind(reader.controller) ) reader.controller.setErrorFlag(); // also bind top-level expression if( reader.grammar.topLevel!=null ) // this 'if' clause is necessary when // is not specified (which is an error, and already reported.) reader.grammar.topLevel = reader.grammar.topLevel.visit( new IslandSchemaImpl.Binder(schemaProvider, reader.controller, reader.pool ) ); } } // GrammarState implements ExpressionState, // so RootState has to implement ExpressionOwner. public final void onEndChild(Expression exp) {} } msv-2009.1/msv/src/com/sun/msv/relaxns/reader/package.html0000644000175000017500000000013407266637361023621 0ustar giovannigiovanni

        parses XML representation of RELAX Namespace.

        msv-2009.1/msv/src/com/sun/msv/relaxns/reader/NamespaceState.java0000644000175000017500000001752211156747174025106 0ustar giovannigiovanni/* * @(#)$Id: NamespaceState.java 1744 2009-03-14 15:34:20Z bimargulies $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.relaxns.reader; import java.util.Vector; import org.iso_relax.dispatcher.IslandSchema; import org.iso_relax.dispatcher.IslandSchemaReader; import org.iso_relax.dispatcher.impl.IgnoredSchema; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLFilterImpl; import com.sun.msv.reader.AbortException; import com.sun.msv.reader.GrammarReader; import com.sun.msv.reader.IgnoreState; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * parses <namespace> element of RELAX Namespace. * * @author Kohsuke KAWAGUCHI */ public class NamespaceState extends State { /** this flag indicates this object expects a module element to * appear as the child. */ private boolean inlineModuleExpected = false; /** this flag indicates we are in bail-out mode. * any contents of <namespace> element will be ignored. * * this flag is used for error recovery. */ private boolean bailOut = false; /** inline module should have this primary namespace */ private String namespace; /** this object will parse inlined grammar. */ IslandSchemaReader moduleReader; protected void startSelf() { super.startSelf(); namespace = startTag.getAttribute("name"); if(namespace==null) { reader.reportError( RELAXNSReader.ERR_MISSING_ATTRIBUTE, "namespace","name" ); // recover by ignoring this element. return; } if(getReader().grammar.moduleMap.containsKey(namespace)) { reader.reportError( RELAXNSReader.ERR_NAMESPACE_COLLISION, namespace ); return; // recovery by ignoring this element. } // TODO: prevent duplicate definitions final String validation = startTag.getAttribute("validation"); if( "false".equals(validation) ) {// this module will not be validated. // create stub module. getReader().grammar.moduleMap.put( namespace, new IgnoredSchema() ); return; // done. } String language = startTag.getAttribute("language"); if(language==null) language = RELAXNSReader.RELAXCoreNamespace; // assume RELAX Core if none is specified moduleReader = getReader().getIslandSchemaReader(language,namespace); if( moduleReader==null ) { // unrecognized language reader.reportError( RELAXNSReader.ERR_UNKNOWN_LANGUAGE, language ); bailOut = true; return; // ignore this element. } final String moduleLocation = startTag.getAttribute("moduleLocation"); if(moduleLocation!=null) {// parse a module from external resource. try { InputSource is = reader.resolveLocation(this,moduleLocation); XMLReader parser = reader.parserFactory.newSAXParser().getXMLReader(); parser.setContentHandler(moduleReader); parser.parse(is); } catch( javax.xml.parsers.ParserConfigurationException e ) { reader.controller.error( e, getLocation() ); } catch( java.io.IOException e ) { reader.controller.error( e, getLocation() ); } catch( SAXException e ) { reader.controller.error( e, getLocation() ); } catch( AbortException e ) { } getSchema(moduleReader); return; // done. } // moduleLocation is not specified, and validation="false" is not specified. // module element should be appeared inline. inlineModuleExpected = true; } private void getSchema( IslandSchemaReader moduleReader ) { IslandSchema schema = moduleReader.getSchema(); if( schema==null ) { // failed to load a module. reader.controller.setErrorFlag(); schema = new IgnoredSchema(); // use a dummy schema } getReader().grammar.moduleMap.put( namespace, schema ); } public void startElement( String namespace, String localName, String qName, Attributes atts ) throws SAXException { if(bailOut) { // in bail-out mode, ignore all children. reader.pushState( new IgnoreState(), this, new StartTagInfo(namespace,localName,qName,atts,reader) ); return; } if(!inlineModuleExpected) { // expecets nothing reader.reportError(RELAXNSReader.ERR_MALPLACED_ELEMENT, qName ); bailOut=true; // so that we don't issue errors for every child. return; } // feed moduleReader. //---------------------- moduleReader.startDocument(); // simulate SAX events moduleReader.setDocumentLocator(reader.getLocator()); // simulate prefix mappings GrammarReader.PrefixResolver resolver = reader.prefixResolver; Vector prefixes = new Vector(); while( resolver instanceof GrammarReader.ChainPrefixResolver ) { GrammarReader.ChainPrefixResolver ch = (GrammarReader.ChainPrefixResolver)resolver; prefixes.add( ch.prefix ); resolver = ch.previous; } for( int i=0; i

        parses XML representation of RELAXNS-extended RELAX Core.

        msv-2009.1/msv/src/com/sun/msv/relaxns/reader/relax/AnyOtherElementState.java0000644000175000017500000000336607671170035027362 0ustar giovannigiovanni/* * @(#)$Id: AnyOtherElementState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.relaxns.reader.relax; import org.xml.sax.Locator; import com.sun.msv.grammar.Expression; import com.sun.msv.reader.ExpressionWithoutChildState; import com.sun.msv.relaxns.grammar.relax.AnyOtherElementExp; /** * parses <anyOtherElement> state. * * To create an expression that implements the semantics of anyOtherElement, * the entire grammar must be parsed first. * * @author Kohsuke KAWAGUCHI */ public class AnyOtherElementState extends ExpressionWithoutChildState { protected Expression makeExpression() { // when makeExpression is called, return only a skelton. // later, after the entire grammar is parsed, we'll provide // actual expression. String in = startTag.getAttribute("includeNamespace"); String ex = startTag.getAttribute("excludeNamespace"); if( in!=null && ex!=null ) { reader.reportError( new Locator[]{this.location}, RELAXCoreIslandSchemaReader.ERR_CONFLICTING_ATTRIBUTES, new Object[]{"includeNamespace", "excludeNamespace"} ); ex=null; } if( in==null && ex==null ) ex=""; // this will correctly implement the semantics. final AnyOtherElementExp exp = new AnyOtherElementExp( this.location, in, ex ); ((RELAXCoreIslandSchemaReader)reader).pendingAnyOtherElements.add(exp); return exp; } } msv-2009.1/msv/src/com/sun/msv/relaxns/reader/relax/RELAXCoreIslandSchemaReader.java0000644000175000017500000001055611156747174030407 0ustar giovannigiovanni/* * @(#)$Id: RELAXCoreIslandSchemaReader.java 1744 2009-03-14 15:34:20Z bimargulies $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.relaxns.reader.relax; import java.util.Map; import java.util.Set; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; import org.iso_relax.dispatcher.IslandSchema; import org.iso_relax.dispatcher.IslandSchemaReader; import org.xml.sax.SAXException; import org.xml.sax.helpers.LocatorImpl; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.relax.RELAXModule; import com.sun.msv.reader.ExpressionState; import com.sun.msv.reader.GrammarReaderController; import com.sun.msv.reader.State; import com.sun.msv.reader.relax.core.RELAXCoreReader; import com.sun.msv.relaxns.grammar.ExternalAttributeExp; import com.sun.msv.relaxns.grammar.ExternalElementExp; import com.sun.msv.relaxns.grammar.relax.RELAXIslandSchema; import com.sun.msv.util.StartTagInfo; import com.sun.msv.util.StringPair; /** * reads RELAX-Namespace-extended RELAX Core. * * @author Kohsuke KAWAGUCHI */ public class RELAXCoreIslandSchemaReader extends RELAXCoreReader implements IslandSchemaReader { public RELAXCoreIslandSchemaReader( GrammarReaderController controller, SAXParserFactory parserFactory, ExpressionPool pool, String expectedTargetnamespace ) throws SAXException,ParserConfigurationException { super(controller,parserFactory,new StateFactory(),pool,expectedTargetnamespace); } private static class StateFactory extends RELAXCoreReader.StateFactory { public State interface_(State parent,StartTagInfo tag) { return new InterfaceStateEx(); } } // to allow access within this package. protected RELAXModule getModule() { return super.module; } /** returns true if the given state can have "occurs" attribute. */ protected boolean canHaveOccurs( ExpressionState state ) { return super.canHaveOccurs(state) || state instanceof AnyOtherElementState; } public final IslandSchema getSchema() { RELAXModule m = getResult(); if(m==null) return null; else return new RELAXIslandSchema( m, pendingAnyOtherElements ); } public State createExpressionChildState( State parent,StartTagInfo tag ) { if(! RELAXCoreNamespace.equals(tag.namespaceURI) ) return null; if(tag.localName.equals("anyOtherElement")) return new AnyOtherElementState(); return super.createExpressionChildState(parent,tag); } /** map from StringPair(namespace,label) to ExternalElementExp. */ private final Map externalElementExps = new java.util.HashMap(); private ExternalElementExp getExtElementExp( String namespace, String label ) { StringPair name = new StringPair(namespace,label); ExternalElementExp exp = (ExternalElementExp)externalElementExps.get(name); if( exp!=null ) return exp; exp = new ExternalElementExp( pool, namespace, label, new LocatorImpl(getLocator()) ); externalElementExps.put( name, exp ); return exp; } protected Expression resolveElementRef( String namespace, String label ) { if( namespace!=null ) return getExtElementExp( namespace, label ); else return super.resolveElementRef(namespace,label); } protected Expression resolveHedgeRef( String namespace, String label ) { if( namespace!=null ) return getExtElementExp( namespace, label ); else return super.resolveHedgeRef(namespace,label); } protected Expression resolveAttPoolRef( String namespace, String label ) { if( namespace!=null ) return new ExternalAttributeExp(pool,namespace,label,new LocatorImpl(getLocator())); else return super.resolveAttPoolRef(namespace,label); } /** * set of AnyOtherElementExp object. * * each object will be invoked to do a wrap up by bind method of IslandSchema. */ protected final Set pendingAnyOtherElements = new java.util.HashSet(); } msv-2009.1/msv/src/com/sun/msv/relaxns/reader/relax/InterfaceStateEx.java0000644000175000017500000000373707671170035026516 0ustar giovannigiovanni/* * @(#)$Id: InterfaceStateEx.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.relaxns.reader.relax; import com.sun.msv.grammar.relax.RELAXModule; import com.sun.msv.reader.ChildlessState; import com.sun.msv.reader.State; import com.sun.msv.reader.relax.core.InterfaceState; import com.sun.msv.util.StartTagInfo; /** * parses <interface> element and <div> in interface. * * @author Kohsuke KAWAGUCHI */ class InterfaceStateEx extends InterfaceState { protected State createChildState( StartTagInfo tag ) { RELAXCoreIslandSchemaReader reader = (RELAXCoreIslandSchemaReader)this.reader; if(!tag.namespaceURI.equals(RELAXCoreIslandSchemaReader.RELAXCoreNamespace)) return null; if(tag.localName.equals("div")) return new InterfaceStateEx(); RELAXModule module = reader.getModule(); if(tag.localName.equals("export")) { final String role = tag.getAttribute("role"); if(role!=null) { module.attPools.getOrCreate(role).exported = true; return new ChildlessState(); } // base class may process this element. } if(tag.localName.equals("hedgeExport")) { final String label = tag.getAttribute("label"); if(label==null) reader.reportError(RELAXCoreIslandSchemaReader.ERR_MISSING_ATTRIBUTE,"hedgeExport","label"); // recover by ignoring this hedgeExport else module.hedgeRules.getOrCreate(label).exported = true; return new ChildlessState(); } return super.createChildState(tag); } } msv-2009.1/msv/src/com/sun/msv/relaxns/reader/GrammarState.java0000644000175000017500000000303507671170035024563 0ustar giovannigiovanni/* * @(#)$Id: GrammarState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.relaxns.reader; import com.sun.msv.reader.SimpleState; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * parses <grammar> element. * * @author Kohsuke KAWAGUCHI */ public class GrammarState extends SimpleState { /** gets reader in type-safe fashion */ protected RELAXNSReader getReader() { return (RELAXNSReader)reader; } protected State createChildState( StartTagInfo tag ) { if(tag.localName.equals("namespace")) return new NamespaceState(); if(tag.localName.equals("topLevel")) return new TopLevelState(); if(tag.localName.equals("include")) return new IncludeGrammarState(); return null; } protected void startSelf() { super.startSelf(); {// check relaxNamespaceVersion final String nsVersion = startTag.getAttribute("relaxNamespaceVersion"); if( nsVersion==null ) reader.reportWarning( RELAXNSReader.ERR_MISSING_ATTRIBUTE, "module", "relaxNamespaceVersion" ); else if(!"1.0".equals(nsVersion)) reader.reportWarning( RELAXNSReader.WRN_ILLEGAL_RELAXNAMESPACE_VERSION, nsVersion ); } } } msv-2009.1/msv/src/com/sun/msv/relaxns/reader/trex/0000755000175000017500000000000011622453067022312 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/relaxns/reader/trex/package.html0000644000175000017500000000015007266637361024601 0ustar giovannigiovanni

        parses XML representation of RELAXNS-extended TREX.

        msv-2009.1/msv/src/com/sun/msv/relaxns/reader/trex/TREXIslandSchemaReader.java0000644000175000017500000000244007671170035027336 0ustar giovannigiovanni/* * @(#)$Id: TREXIslandSchemaReader.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.relaxns.reader.trex; import org.iso_relax.dispatcher.IslandSchema; import org.iso_relax.dispatcher.IslandSchemaReader; import org.xml.sax.helpers.XMLFilterImpl; import com.sun.msv.grammar.trex.TREXGrammar; import com.sun.msv.reader.trex.classic.TREXGrammarReader; import com.sun.msv.relaxns.grammar.trex.TREXIslandSchema; /** * reads extended-TREX grammar (extended by RELAX Namespace) * and constructs IslandSchema. * * @author Kohsuke KAWAGUCHI */ public class TREXIslandSchemaReader extends XMLFilterImpl implements IslandSchemaReader { private final TREXGrammarReader baseReader; public TREXIslandSchemaReader( TREXGrammarReader baseReader ) { this.baseReader = baseReader; this.setContentHandler(baseReader); } public final IslandSchema getSchema() { TREXGrammar g = baseReader.getResult(); if(g==null) return null; else return new TREXIslandSchema(g); } } msv-2009.1/msv/src/com/sun/msv/relaxns/reader/IncludeGrammarState.java0000644000175000017500000000226407671170035026072 0ustar giovannigiovanni/* * @(#)$Id: IncludeGrammarState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.relaxns.reader; import com.sun.msv.reader.AbortException; import com.sun.msv.reader.ChildlessState; /** * parses <include> element of RELAX Namespace. * * @author Kohsuke KAWAGUCHI */ public class IncludeGrammarState extends ChildlessState { protected void startSelf() { super.startSelf(); final String href = startTag.getAttribute("grammarLocation"); if(href==null) { // name attribute is required. reader.reportError( RELAXNSReader.ERR_MISSING_ATTRIBUTE, "include","grammarLocation"); // recover by ignoring this include element } else try { reader.switchSource(this,href,new RootGrammarMergeState()); } catch( AbortException e ) { // recover by ignoring this include element } } } msv-2009.1/msv/src/com/sun/msv/relaxns/reader/RootGrammarMergeState.java0000644000175000017500000000152407671170035026410 0ustar giovannigiovanni/* * @(#)$Id: RootGrammarMergeState.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.relaxns.reader; import com.sun.msv.reader.SimpleState; import com.sun.msv.reader.State; import com.sun.msv.util.StartTagInfo; /** * invokes State object that parses the document element. * * this state is used for parsing included grammar. * * @author Kohsuke KAWAGUCHI */ class RootGrammarMergeState extends SimpleState { protected State createChildState( StartTagInfo tag ) { if(tag.localName.equals("grammar")) return new GrammarState(); return null; } } msv-2009.1/msv/src/com/sun/msv/relaxns/reader/RELAXNSReader.java0000644000175000017500000001456711156747174024456 0ustar giovannigiovanni/* * @(#)$Id: RELAXNSReader.java 1744 2009-03-14 15:34:20Z bimargulies $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.relaxns.reader; import javax.xml.parsers.SAXParserFactory; import org.iso_relax.dispatcher.IslandSchemaReader; import org.iso_relax.dispatcher.SchemaProvider; import org.relaxng.datatype.Datatype; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.LocatorImpl; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.Grammar; import com.sun.msv.reader.GrammarReaderController; import com.sun.msv.reader.relax.RELAXReader; import com.sun.msv.reader.trex.classic.TREXGrammarReader; import com.sun.msv.relaxns.grammar.ExternalElementExp; import com.sun.msv.relaxns.grammar.RELAXGrammar; import com.sun.msv.util.StartTagInfo; /** * parses RELAX Namespace XML and constructs a SchemaProvider. * * @author Kohsuke KAWAGUCHI */ public class RELAXNSReader extends RELAXReader { /** namespace URI of RELAX Namespace. */ public static final String RELAXNamespaceNamespace = "http://www.xml.gr.jp/xmlns/relaxNamespace"; /** loads RELAX grammar */ public static RELAXGrammar parse( String moduleURL, SAXParserFactory factory, GrammarReaderController controller, ExpressionPool pool ) { RELAXNSReader reader = new RELAXNSReader(controller,factory,pool); reader.parse(moduleURL); return reader.getResult(); } /** loads RELAX grammar */ public static RELAXGrammar parse( InputSource module, SAXParserFactory factory, GrammarReaderController controller, ExpressionPool pool ) { RELAXNSReader reader = new RELAXNSReader(controller,factory,pool); reader.parse(module); return reader.getResult(); } public RELAXNSReader( GrammarReaderController controller, SAXParserFactory parserFactory, ExpressionPool pool ) { super(controller,parserFactory,new StateFactory(),pool,new RootGrammarState()); grammar = new RELAXGrammar(pool); } /** RELAX grammar that is currentlt being loaded */ public final RELAXGrammar grammar; /** obtains parsed grammar object only if parsing was successful. */ public final RELAXGrammar getResult() { if(controller.hadError()) return null; else return grammar; } public Grammar getResultAsGrammar() { return getResult(); } protected SchemaProvider schemaProvider; /** obtains parsed grammar object as SchemaProvider * only if parsing was successful. */ public final SchemaProvider getSchemaProvider() { if(controller.hadError()) return null; else return schemaProvider; } /** * creates an {@link IslandSchemaReader} that can parse the specified language. * * This method can be overrided by the derived class to incorporate other * language implementations. * * @return * return null if the given language is unrecognized. * error will be handled by the caller. So this method should not attempt * to report nor recover from error. */ public IslandSchemaReader getIslandSchemaReader( String language, String expectedTargetNamespace ) { try { if( language.equals( RELAXCoreNamespace ) ) // RELAX Core return new com.sun.msv.relaxns.reader.relax.RELAXCoreIslandSchemaReader( controller,parserFactory,(ExpressionPool)pool,expectedTargetNamespace); if( language.equals( TREXGrammarReader.TREXNamespace ) ) // TREX return new com.sun.msv.relaxns.reader.trex.TREXIslandSchemaReader( new TREXGrammarReader( controller,parserFactory, new com.sun.msv.reader.trex.classic.TREXGrammarReader.StateFactory(), pool) ); } catch( javax.xml.parsers.ParserConfigurationException e ) { controller.error(e, null ); } catch( SAXException e ) { controller.error(e, null ); } return null; } public Datatype resolveDataType( String typeName ) { // should never be called. // because in top-level content model, datatype reference can never occur. throw new Error(); } protected boolean isGrammarElement( StartTagInfo tag ) { if( !RELAXNamespaceNamespace.equals(tag.namespaceURI) ) return false; // annotation is ignored at this level. // by returning false, the entire subtree will be simply ignored. if(tag.localName.equals("annotation")) return false; return true; } protected Expression resolveElementRef( String namespace, String label ) { return resolveRef(namespace,label,"ref"); } protected Expression resolveHedgeRef( String namespace, String label ) { return resolveRef(namespace,label,"hedgeRef"); } private Expression resolveRef( String namespace, String label, String tagName ) { if( namespace==null ) { reportError( ERR_MISSING_ATTRIBUTE, tagName, "namespace" ); return Expression.nullSet; } return new ExternalElementExp( pool, namespace, label, new LocatorImpl(getLocator()) ); } protected String localizeMessage( String propertyName, Object[] args ) { return super.localizeMessage(propertyName,args); } public static final String WRN_ILLEGAL_RELAXNAMESPACE_VERSION // arg:1 = "RELAXNSReader.Warning.IllegalRelaxNamespaceVersion"; public static final String ERR_TOPLEVEL_PARTICLE_MUST_BE_RELAX_CORE // arg:0 = "RELAXNSReader.TopLevelParticleMustBeRelaxCore"; public static final String ERR_INLINEMODULE_NOT_FOUND // arg:0 = "RELAXNSReader.InlineModuleNotFound"; public static final String ERR_UNKNOWN_LANGUAGE = "RELAXNSReader.UnknownLanguage"; // arg:1 public static final String ERR_NAMESPACE_COLLISION // arg:1 = "RELAXNSReader.NamespaceCollision"; } msv-2009.1/msv/src/com/sun/msv/relaxns/grammar/0000755000175000017500000000000011622453067021514 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/relaxns/grammar/ExternalElementExp.java0000644000175000017500000000555307671170035026140 0ustar giovannigiovanni/* * @(#)$Id: ExternalElementExp.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.relaxns.grammar; import org.iso_relax.dispatcher.ElementDecl; import org.xml.sax.Locator; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.NamespaceNameClass; /** * place holder for imported element declaration. * * This class derives ElementExp because "elementDecl" is a constraint over one element. * This class also provides stub methods so that programs who are not aware to * divide&validate can gracefully degrade. * * @author Kohsuke KAWAGUCHI */ public class ExternalElementExp extends ElementExp { public NameClass getNameClass() { return nameClass; } /** NamespaceNameClass object that matchs this namespace. */ private final NamespaceNameClass nameClass; /** namespace URI that this ExternalElementExp belongs to. */ public final String namespaceURI; /** name of the imported Rule */ public final String ruleName; /** where did this reference is written in the source file. * * can be set to null (to reduce memory usage) at anytime. */ public transient Locator source; /** * imported ElementDecl object that actually validates this element. * this variable is set during binding phase. */ public ElementDecl rule; public ExternalElementExp( ExpressionPool pool, String namespaceURI, String ruleName, Locator loc ) { // set content model to nullSet // to make this elementExp accept absolutely nothing. // "ignoreUndeclaredAttributes" flag is also meaningless here // because actual validation of this element will be done by a different // IslandVerifier. super(Expression.nullSet,false); this.ruleName = ruleName; this.namespaceURI = namespaceURI; this.nameClass = new NamespaceNameClass(namespaceURI); this.source = loc; /* provide dummy content model <<<< this >>>> */ this.contentModel = pool.createZeroOrMore( pool.createMixed( pool.createChoice( pool.createAttribute(nameClass), this ) ) ); } } msv-2009.1/msv/src/com/sun/msv/relaxns/grammar/package.html0000644000175000017500000000013407266637361024005 0ustar giovannigiovanni

        abstract grammar model(AGM) for RELAX Namespace.

        msv-2009.1/msv/src/com/sun/msv/relaxns/grammar/ExternalAttributeExp.java0000644000175000017500000000307507671170035026507 0ustar giovannigiovanni/* * @(#)$Id: ExternalAttributeExp.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.relaxns.grammar; import org.xml.sax.Locator; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.OtherExp; /** * place holder for imported attributes declaration. * * This class also provides stub methods so that programs who are not aware to * divide&validate can gracefully degrade. * *

        * In MSV, importing AttributesDecl from different implementations is * not supported. ExternalAttributeExp is always replaced by their target Expression * before validation. * * @author Kohsuke KAWAGUCHI */ public class ExternalAttributeExp extends OtherExp { public ExternalAttributeExp( ExpressionPool pool, String namespaceURI, String role, Locator loc ) { this.source = loc; this.namespaceURI = namespaceURI; this.role = role; this.exp = Expression.epsilon; } /** namespace URI that this object belongs to. */ public final String namespaceURI; /** name of the imported AttributesDecl */ public final String role; /** * where did this reference is written in the source file. * can be set to null (to reduce memory usage) at anytime. */ public transient Locator source; } msv-2009.1/msv/src/com/sun/msv/relaxns/grammar/relax/0000755000175000017500000000000011622453067022627 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/relaxns/grammar/relax/AnyOtherElementExp.java0000644000175000017500000001223207671170035027212 0ustar giovannigiovanni/* * @(#)$Id: AnyOtherElementExp.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.relaxns.grammar.relax; import java.util.Iterator; import java.util.StringTokenizer; import org.iso_relax.dispatcher.ElementDecl; import org.iso_relax.dispatcher.SchemaProvider; import org.xml.sax.ErrorHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXParseException; import com.sun.msv.grammar.ChoiceNameClass; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.Grammar; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.NamespaceNameClass; import com.sun.msv.grammar.NotNameClass; /** * place holder for <anyOtherElement> of RELAX. * * @author Kohsuke KAWAGUCHI */ public class AnyOtherElementExp extends ElementExp implements ElementDecl { public NameClass getNameClass() { return nameClass; } public String getName() { return "anyOtherElement:"+nameClass; } /** * this name class matches all the namespaces that are accepted by this anyOtherElement. * this field is set by bind method. */ public NameClass nameClass; /** * where did this reference is written in the source file. * can be set to null (to reduce memory usage) at anytime. */ public transient Locator source; public final String includeNamespace; public final String excludeNamespace; /** * creates "skelton" of AnyOtherElement. * * pseudo content model and name class must be supplied separately. */ public AnyOtherElementExp( Locator loc, String includeNamespace, String excludeNamespace ) { // set content model to nullSet // to make this elementExp accept absolutely nothing. // "ignoreUndeclaredAttributes" parameter is meaningless here // because validation of this element is performed by // AnyOtherElementVerifier and it doesn't care about this flag. super(Expression.nullSet,true); this.source = loc; this.includeNamespace = includeNamespace; this.excludeNamespace = excludeNamespace; if( includeNamespace==null && excludeNamespace==null ) throw new IllegalArgumentException(); if( includeNamespace!=null && excludeNamespace!=null ) throw new IllegalArgumentException(); } /** creates pseudo content model and name class. * * This function is called by RELAXIslandSchema object. * Therefore, line information is not automatically available * when reporting error. * Implementator should keep this in mind and manually pass Locator to reportError method. */ protected void wrapUp( Grammar owner, Expression pseudoContentModel, SchemaProvider provider, ErrorHandler errorHandler ) throws SAXException { StringTokenizer st; if( includeNamespace!=null ) st = new StringTokenizer(includeNamespace); else st = new StringTokenizer(excludeNamespace); NameClass nc =null; while(st.hasMoreTokens()) { String uri = st.nextToken(); if(uri.equals("##local")) uri=""; if( provider.getSchemaByNamespace(uri)!=null ) { // one cannot specify defined URI. errorHandler.warning( new SAXParseException( Localizer.localize( Localizer.WRN_ANYOTHER_NAMESPACE_IGNORED, uri ), source ) ); continue; } NamespaceNameClass nsnc = new NamespaceNameClass(uri); if( nc==null ) nc = nsnc; else nc = new ChoiceNameClass(nc,nsnc); } if( excludeNamespace!=null ) { // in case of 'excludeNamespace', // all defined namespace is also considered as illegal. Iterator itr = provider.iterateNamespace(); while( itr.hasNext() ) { NamespaceNameClass nsnc = new NamespaceNameClass( (String)itr.next() ); if( nc==null ) nc = nsnc; else nc = new ChoiceNameClass(nc,nsnc); } nc = new NotNameClass(nc); } this.nameClass = nc; // provide pseudo-content model. this.contentModel = owner.getPool().createMixed( owner.getPool().createZeroOrMore( owner.getPool().createChoice(this,pseudoContentModel) ) ); } public boolean getFeature( String feature ) throws SAXNotRecognizedException { throw new SAXNotRecognizedException(feature); } public Object getProperty( String property ) throws SAXNotRecognizedException { throw new SAXNotRecognizedException(property); } } msv-2009.1/msv/src/com/sun/msv/relaxns/grammar/relax/package.html0000644000175000017500000000015207266637361025120 0ustar giovannigiovanni

        abstract grammar model(AGM) for RELAXNS-extended RELAX Core.

        msv-2009.1/msv/src/com/sun/msv/relaxns/grammar/relax/Localizer.java0000644000175000017500000000231507671170035025417 0ustar giovannigiovanni/* * @(#)$Id: Localizer.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.relaxns.grammar.relax; /** * localizes messages * * @author Kohsuke KAWAGUCHI */ public class Localizer { public static String localize( String propertyName, Object[] args ) { String format = java.util.ResourceBundle.getBundle( "com.sun.msv.relaxns.grammar.relax.Messages").getString(propertyName); return java.text.MessageFormat.format(format, args ); } public static String localize( String prop ) { return localize( prop, null ); } public static String localize( String prop, Object arg1 ) { return localize( prop, new Object[]{arg1} ); } public static String localize( String prop, Object arg1, Object arg2 ) { return localize( prop, new Object[]{arg1,arg2} ); } public static final String WRN_ANYOTHER_NAMESPACE_IGNORED // arg:1 = "AnyOtherElementExp.Warning.AnyOtherNamespaceIgnored"; } msv-2009.1/msv/src/com/sun/msv/relaxns/grammar/relax/Messages_ja.properties0000644000175000017500000000040707307765244027177 0ustar giovannigiovanniAnyOtherElementExp.Warning.AnyOtherNamespaceIgnored =\ \u3053\u306E\u540D\u524D\u7A7A\u9593\u3092\u5B9A\u7FA9\u3059\u308B\u30B9\u30AD\u30FC\u30DE\u304C\u3042\u308B\u306E\u3067\u3001\u306BURI "{0}"\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093 msv-2009.1/msv/src/com/sun/msv/relaxns/grammar/relax/RELAXIslandSchema.java0000644000175000017500000001027207671170035026623 0ustar giovannigiovanni/* * @(#)$Id: RELAXIslandSchema.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.relaxns.grammar.relax; import java.util.Iterator; import java.util.Set; import org.iso_relax.dispatcher.ElementDecl; import org.iso_relax.dispatcher.IslandSchema; import org.iso_relax.dispatcher.SchemaProvider; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.Grammar; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.relax.AttPoolClause; import com.sun.msv.grammar.relax.ElementRules; import com.sun.msv.grammar.relax.HedgeRules; import com.sun.msv.grammar.relax.RELAXModule; import com.sun.msv.relaxns.grammar.DeclImpl; import com.sun.msv.relaxns.grammar.ExternalElementExp; import com.sun.msv.relaxns.verifier.IslandSchemaImpl; /** * IslandSchema implementation for RELXA module. * * @author Kohsuke KAWAGUCHI */ public class RELAXIslandSchema extends IslandSchemaImpl { /** underlying RELAX module which this IslandSchema is representing */ protected final RELAXModule module; protected Set pendingAnyOtherElements; public RELAXIslandSchema( RELAXModule module, Set pendingAnyOtherElements ) { this.module = module; this.pendingAnyOtherElements = pendingAnyOtherElements; // export elementRules as ElementDecl ReferenceExp[] refs= module.elementRules.getAll(); for( int i=0; iKohsuke KAWAGUCHI */ class ExportedAttPoolGenerator extends ExpressionCloner implements RELAXExpressionVisitorExpression { ExportedAttPoolGenerator( ExpressionPool pool ) { super(pool); } private String targetNamespace; public Expression create( RELAXModule module, Expression exp ) { targetNamespace = module.targetNamespace; return exp.visit(this); } public Expression onAttribute( AttributeExp exp ) { if(!(exp.nameClass instanceof SimpleNameClass )) return exp; // leave it as is. or should we consider this as a failed assertion? SimpleNameClass nc = (SimpleNameClass)exp.nameClass; if( !nc.namespaceURI.equals("") ) return exp; // externl attributes. leave it as is. return pool.createAttribute( new SimpleNameClass( targetNamespace, nc.localName ), exp.exp ); } // we are traversing attPools. thus these will never be possible. public Expression onElement( ElementExp exp ) { throw new Error(); } public Expression onTag( TagClause exp ) { throw new Error(); } public Expression onElementRules( ElementRules exp ) { throw new Error(); } public Expression onHedgeRules( HedgeRules exp ) { throw new Error(); } public Expression onRef( ReferenceExp exp ) { // this class implements RELAXExpressionVisitorExpression. // So this method should never be called throw new Error(); } public Expression onOther( OtherExp exp ) { // OtherExps are removed from the generated expression. return exp.exp.visit(this); } public Expression onAttPool( AttPoolClause exp ) {// create exported version for them, too. // note that thsi exp.exp may be a AttPool of a different module. // In that case, calling visit method is no-op. But at least // it doesn't break anything. return exp.exp.visit(this); } } msv-2009.1/msv/src/com/sun/msv/relaxns/grammar/relax/Messages.properties0000644000175000017500000000024307265752221026515 0ustar giovannigiovanniAnyOtherElementExp.Warning.AnyOtherNamespaceIgnored =\ URI "{0}" cannot be specified as a member of \ because this URI is defined by a module. msv-2009.1/msv/src/com/sun/msv/relaxns/grammar/RELAXGrammar.java0000644000175000017500000000226010034315204024523 0ustar giovannigiovanni/* * @(#)$Id: RELAXGrammar.java 1634 2004-04-05 17:42:28Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.relaxns.grammar; import java.util.Map; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.Grammar; /** * "Grammar" of RELAX Namespace. * * @author Kohsuke KAWAGUCHI */ public class RELAXGrammar implements Grammar { /** * map from namespace URI to IslandSchema. * All modules are stored in this map. * * @see org.iso_relax.dispatcher.IslandSchema */ public final Map moduleMap = new java.util.HashMap(); /** top-level expression */ public Expression topLevel; public Expression getTopLevel() { return topLevel; } /** expression pool that was used to create these objects */ public final ExpressionPool pool; public ExpressionPool getPool() { return pool; } public RELAXGrammar( ExpressionPool pool ) { this.pool = pool; } } msv-2009.1/msv/src/com/sun/msv/relaxns/grammar/DeclImpl.java0000644000175000017500000000262307671170035024053 0ustar giovannigiovanni/* * @(#)$Id: DeclImpl.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.relaxns.grammar; import org.xml.sax.SAXNotRecognizedException; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ReferenceExp; /** * Implementation of ElementDecl interface by MSV grammar model. * * @author Kohsuke KAWAGUCHI */ public class DeclImpl implements org.iso_relax.dispatcher.ElementDecl, org.iso_relax.dispatcher.AttributesDecl, java.io.Serializable { /** "meat" of this Rule. */ public final Expression exp; /** name of this rule */ protected final String name; public DeclImpl( ReferenceExp exp ) { this( exp.name, exp.exp ); } public DeclImpl( String name, Expression exp ) { this.exp=exp; this.name=name; } public String getName() { return name; } public boolean getFeature( String feature ) throws SAXNotRecognizedException { throw new SAXNotRecognizedException(feature); } public Object getProperty( String property ) throws SAXNotRecognizedException { throw new SAXNotRecognizedException(property); } } msv-2009.1/msv/src/com/sun/msv/relaxns/grammar/trex/0000755000175000017500000000000011622453067022476 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/relaxns/grammar/trex/TREXIslandSchema.java0000644000175000017500000000305707671170035026404 0ustar giovannigiovanni/* * @(#)$Id: TREXIslandSchema.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.relaxns.grammar.trex; import org.iso_relax.dispatcher.SchemaProvider; import org.xml.sax.ErrorHandler; import com.sun.msv.grammar.Grammar; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.trex.TREXGrammar; import com.sun.msv.relaxns.grammar.DeclImpl; import com.sun.msv.relaxns.verifier.IslandSchemaImpl; /** * IslandSchema implementation for TREX pattern. * * @author Kohsuke KAWAGUCHI */ public class TREXIslandSchema extends IslandSchemaImpl { /** underlying TREX pattern which this IslandSchema is representing */ protected final TREXGrammar grammar; public TREXIslandSchema( TREXGrammar grammar ) { this.grammar = grammar; // export all named patterns. // TODO: modify to export only those element declarations. ReferenceExp[] refs = grammar.namedPatterns.getAll(); for( int i=0; i

        abstract grammar model(AGM) for RELAXNS-extended TREX.

        msv-2009.1/msv/src/com/sun/msv/relaxns/verifier/0000755000175000017500000000000011622453067021701 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/relaxns/verifier/TREXIslandVerifier.java0000644000175000017500000002274310034315204026147 0ustar giovannigiovanni/* * @(#)$Id: TREXIslandVerifier.java 1634 2004-04-05 17:42:28Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.relaxns.verifier; import java.util.Map; import java.util.Set; import java.util.Vector; import org.iso_relax.dispatcher.Dispatcher; import org.iso_relax.dispatcher.ElementDecl; import org.iso_relax.dispatcher.IslandSchema; import org.iso_relax.dispatcher.IslandVerifier; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.relaxns.grammar.ExternalElementExp; import com.sun.msv.relaxns.grammar.relax.AnyOtherElementExp; import com.sun.msv.verifier.regexp.ComplexAcceptor; import com.sun.msv.verifier.regexp.REDocumentDeclaration; import com.sun.msv.verifier.regexp.SimpleAcceptor; /** * IslandVerifier for RELAX Core and TREX. * * @author Kohsuke KAWAGUCHI */ class TREXIslandVerifier extends com.sun.msv.verifier.Verifier implements org.iso_relax.dispatcher.IslandVerifier { protected Dispatcher dispatcher; public void setDispatcher( Dispatcher disp ) { this.dispatcher = disp; this.errorHandler = new ErrorHandlerAdaptor( disp ); } /** * lazily constructed map from Rule object to ExternalElementExp. * * Rule object r and ExternalElementExp whose rule field * is r are registered to this map when child island is found. * * this map is used in endChildIsland method. */ protected final Map rule2exp = new java.util.HashMap(); TREXIslandVerifier( RulesAcceptor initialAcceptor ) { super( null, null ); // quick hack. current = initialAcceptor; } public void startElement( String namespaceUri, String localName, String qName, Attributes atts ) throws SAXException { super.startElement(namespaceUri,localName,qName,atts); // check current Acceptor object to see if switching is necessary. if( current instanceof SimpleAcceptor ) { SimpleAcceptor sa = (SimpleAcceptor)current; // if sa.owner==null, we are in error recovery mode. // so don't let another IslandVerifier kick in. // just continue validation by using the current handler. if( sa.owner instanceof ExternalElementExp ) { // switch to the child island. switchToChildIsland( new ExternalElementExp[]{(ExternalElementExp)sa.owner}, namespaceUri, localName, qName, atts ); return; } if( sa.owner instanceof AnyOtherElementExp ) { // switch to anyOtherElement. switchToAnyOtherElement( new AnyOtherElementExp[]{(AnyOtherElementExp)sa.owner}, namespaceUri, localName, qName, atts ); return; } return; } if( current instanceof ComplexAcceptor ) { ComplexAcceptor ca = (ComplexAcceptor)current; Vector vec = null; for( int i=0; i // // ... // // Even if this is the case, this implementation switches to // the new child Verifier. Therefore // ... // won't be used. if( vec!=null ) { // switch to the child island. ExternalElementExp[] exps = new ExternalElementExp[vec.size()]; vec.toArray(exps); switchToChildIsland(exps, namespaceUri, localName, qName, atts ); return; } // see if there is anyOtherElementExp for( int i=0; iKohsuke KAWAGUCHI */ public class AnyOtherElementVerifier extends DefaultHandler implements IslandVerifier { /** this Verifier validates these expressions. * * during validation, failed expression is removed. */ private final AnyOtherElementExp[] exps; public AnyOtherElementVerifier( AnyOtherElementExp[] exps ) { this.exps = exps; } protected Dispatcher dispatcher; public void setDispatcher( Dispatcher disp ) { this.dispatcher = disp; } public void startElement( String namespaceURI, String localName, String qName, Attributes atts ) throws SAXException { IslandSchema is = dispatcher.getSchemaProvider().getSchemaByNamespace(namespaceURI); if( is!=null ) { // find an island that has to be validated. // switch to the new IslandVerifier. IslandVerifier iv = is.createNewVerifier( namespaceURI, is.getElementDecls() ); dispatcher.switchVerifier(iv); iv.startElement(namespaceURI,localName,qName,atts); return; } boolean atLeastOneIsValid = false; for( int i=0; i

        "divide&validate" framework implementation.

        msv-2009.1/msv/src/com/sun/msv/relaxns/verifier/Localizer.java0000644000175000017500000000162207671170035024471 0ustar giovannigiovanni/* * @(#)$Id: Localizer.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.relaxns.verifier; /** * formats messages by using a resource file. * * @author Kohsuke KAWAGUCHI */ class Localizer { public static String localize( String prop, Object[] args ) { return java.text.MessageFormat.format( java.util.ResourceBundle.getBundle("com.sun.msv.relaxns.verifier.Messages").getString(prop), args ); } public static String localize( String prop ) { return localize( prop, null ); } public static String localize( String prop, Object arg1 ) { return localize( prop, new Object[]{arg1} ); } } msv-2009.1/msv/src/com/sun/msv/relaxns/verifier/Messages_ja.properties0000644000175000017500000000177007307765244026255 0ustar giovannigiovanniIslandSchemaImpl.UndefinedNamespace =\ \u540D\u524D\u7A7A\u9593"{0}"\u304C\u53C2\u7167\u3055\u308C\u3066\u3044\u307E\u3059\u304C\u3001\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u305B\u3093 IslandSchemaImpl.UnexportedElementDecl =\ "{0}"\u306F\u30A8\u30AF\u30B9\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u307E\u305B\u3093 IslandSchemaImpl.UnexportedAttributeDecl =\ "{0}"\u306F\u30A8\u30AF\u30B9\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u307E\u305B\u3093 IslandSchemaImpl.UnsupportedAttributesImport =\ \u3053\u306E\u8A00\u8A9E\u304B\u3089\u5C5E\u6027\u3092\u30A4\u30F3\u30DD\u30FC\u30C8\u3059\u308B\u6A5F\u80FD\u306F\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u307E\u305B\u3093 AnyOtherElementVerifier.UnexpectedNamespace =\ \u540D\u524D\u7A7A\u9593"{0}"\u306B\u5C5E\u3059\u308B\u8981\u7D20\u306F\u3053\u3053\u306B\u306F\u3053\u3089\u308C\u307E\u305B\u3093 # RELAXReader.UnexportedHedgeRule =\ # hedgeRule "{0}" is not exported # # RELAXReader.UnexportedAttPool =\ # attPool "{0}" is not exported msv-2009.1/msv/src/com/sun/msv/relaxns/verifier/SchemaProviderImpl.java0000644000175000017500000000741210034315204026267 0ustar giovannigiovanni/* * @(#)$Id: SchemaProviderImpl.java 1634 2004-04-05 17:42:28Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.relaxns.verifier; import java.util.Iterator; import org.iso_relax.dispatcher.IslandSchema; import org.iso_relax.dispatcher.IslandVerifier; import org.iso_relax.dispatcher.impl.AbstractSchemaProviderImpl; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.Grammar; import com.sun.msv.relaxns.grammar.DeclImpl; import com.sun.msv.relaxns.grammar.RELAXGrammar; /** * implementation of SchemaProvider by using RELAX Grammar. * * @author Kohsuke KAWAGUCHI */ public class SchemaProviderImpl extends AbstractSchemaProviderImpl { private final DeclImpl[] topLevel; /** top-level expression as AGM. */ private final Expression topLevelExp; /** shared expression pool. */ private final ExpressionPool pool; public IslandVerifier createTopLevelVerifier() { return new TREXIslandVerifier( new RulesAcceptor( new com.sun.msv.verifier.regexp.REDocumentDeclaration(topLevelExp,pool), topLevel ) ); } /** * creates SchemaProvider from generic Grammar (including TREX/RELAX Core) */ public static SchemaProviderImpl fromGrammar( Grammar grammar ) { if( grammar instanceof RELAXGrammar ) return new SchemaProviderImpl( (RELAXGrammar)grammar ); RELAXGrammar g = new RELAXGrammar(grammar.getPool()); g.topLevel = grammar.getTopLevel(); return new SchemaProviderImpl( g ); } /** * creates SchemaProvider from existing RELAXGrammar. * * Since bind method is already called by RELAXNSReader, * the application should not call bind method. */ public SchemaProviderImpl( RELAXGrammar grammar ) { // this.grammar = grammar; this.pool = grammar.pool; this.topLevelExp = grammar.topLevel; this.topLevel = new DeclImpl[]{new DeclImpl("##start",grammar.topLevel)}; // add all parsed modules into the provider. Iterator itr = grammar.moduleMap.keySet().iterator(); while( itr.hasNext() ) { String namespaceURI = (String)itr.next(); addSchema( namespaceURI, (IslandSchema)grammar.moduleMap.get(namespaceURI) ); } } /** binds all IslandSchemata. */ public boolean bind( ErrorHandler handler ) { ErrorHandlerFilter filter = new ErrorHandlerFilter(handler); try { Iterator itr = schemata.values().iterator(); while( itr.hasNext() ) ((IslandSchema)itr.next()).bind( this, filter ); } catch( SAXException e ) { // bind method may throw SAXException. return false; } return !filter.hadError; } private static class ErrorHandlerFilter implements ErrorHandler { private final ErrorHandler core; boolean hadError = false; ErrorHandlerFilter( ErrorHandler handler ) { this.core=handler; } public void fatalError( SAXParseException spe ) throws SAXException { error(spe); } public void error( SAXParseException spe ) throws SAXException { core.error(spe); hadError = true; } public void warning( SAXParseException spe ) throws SAXException { core.warning(spe); } } } msv-2009.1/msv/src/com/sun/msv/relaxns/verifier/ErrorHandlerAdaptor.java0000644000175000017500000000225007671170035026445 0ustar giovannigiovanni/* * @(#)$Id: ErrorHandlerAdaptor.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.relaxns.verifier; import org.iso_relax.dispatcher.Dispatcher; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * wraps ISORELAX ErrorHandler by VerificationErrorHandler interface. * * @author Kohsuke KAWAGUCHI */ public class ErrorHandlerAdaptor implements ErrorHandler { private final Dispatcher core; public ErrorHandlerAdaptor( Dispatcher core ) { this.core = core; } public void fatalError( SAXParseException error ) throws SAXException { core.getErrorHandler().fatalError( error ); } public void error( SAXParseException error ) throws SAXException { core.getErrorHandler().error( error ); } public void warning( SAXParseException error ) throws SAXException { core.getErrorHandler().warning( error ); } } msv-2009.1/msv/src/com/sun/msv/relaxns/verifier/Messages.properties0000644000175000017500000000112707267141274025573 0ustar giovannigiovanniIslandSchemaImpl.UndefinedNamespace =\ referenced namespace "{0}" is not defined by declaration IslandSchemaImpl.UnexportedElementDecl =\ "{0}" is not exported IslandSchemaImpl.UnexportedAttributeDecl =\ "{0}" is not exported IslandSchemaImpl.UnsupportedAttributesImport =\ importing attributes from the specified language is not supported. AnyOtherElementVerifier.UnexpectedNamespace =\ elements from "{0}" namespace is not allowed. # RELAXReader.UnexportedHedgeRule =\ # hedgeRule "{0}" is not exported # # RELAXReader.UnexportedAttPool =\ # attPool "{0}" is not exported msv-2009.1/msv/src/com/sun/msv/relaxns/verifier/RulesAcceptor.java0000644000175000017500000000567210034315204025313 0ustar giovannigiovanni/* * @(#)$Id: RulesAcceptor.java 1634 2004-04-05 17:42:28Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.relaxns.verifier; import org.iso_relax.dispatcher.ElementDecl; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.relaxns.grammar.DeclImpl; import com.sun.msv.verifier.Acceptor; import com.sun.msv.verifier.regexp.REDocumentDeclaration; /** * Acceptor that is used to validate root node of the island. * * This object receives {@link DeclImpl}s and validates them. * * @author Kohsuke KAWAGUCHI */ public class RulesAcceptor extends com.sun.msv.verifier.regexp.ComplexAcceptorBaseImpl { protected final DeclImpl[] owners; /** helper function for constructor */ private static Expression createCombined( ExpressionPool pool, DeclImpl[] rules ) { Expression exp = Expression.nullSet; for( int i=0; i *
      5. * MSV is used by other RELAX Namespace * implementation or *
      6. * other IslandSchema implemntations are used by MSV's RELAXNSReader. *
    * * In that case, the current createNewVerifier method causes a performance problem. * * @author Kohsuke KAWAGUCHI */ public abstract class IslandSchemaImpl implements IslandSchema, java.io.Serializable { /** map from name to DeclImpl. */ protected final Map elementDecls = new java.util.HashMap(); /** map from name to DeclImpl. */ protected final Map attributesDecls = new java.util.HashMap(); public IslandVerifier createNewVerifier( String namespace, ElementDecl[] rules ) { // see the class comment. // this method is invoked only under certain limited situations. DeclImpl[] ri = new DeclImpl[rules.length]; System.arraycopy( rules,0, ri,0, rules.length ); return new TREXIslandVerifier( new RulesAcceptor( new REDocumentDeclaration( getGrammar() ), ri ) ); } /** get the grammar object that represents this island. */ protected abstract Grammar getGrammar(); public ElementDecl getElementDeclByName( String name ) { return (ElementDecl)elementDecls.get(name); } public Iterator iterateElementDecls() { return elementDecls.values().iterator(); } public ElementDecl[] getElementDecls() { ElementDecl[] r = new DeclImpl[elementDecls.size()]; elementDecls.values().toArray(r); return r; } public AttributesDecl getAttributesDeclByName( String name ) { return (AttributesDecl)attributesDecls.get(name); } public Iterator iterateAttributesDecls() { return attributesDecls.values().iterator(); } public AttributesDecl[] getAttributesDecls() { AttributesDecl[] r = new DeclImpl[attributesDecls.size()]; attributesDecls.values().toArray(r); return r; } public AttributesVerifier createNewAttributesVerifier( String namespaceURI, AttributesDecl[] decls ) { throw new Error("not implemented"); } protected void bind( ReferenceContainer con, Binder binder ) { ReferenceExp[] exps = con.getAll(); for( int i=0; iKohsuke KAWAGUCHI */ public class DebugController implements GrammarReaderController { /** if true, warnings are reported. If false, not reported. */ private boolean displayWarning; /** set to true after "there are warnings..." message is once printed. */ private boolean warningReported = false; /** entity resolution is delegated to this object. can be null. */ public EntityResolver externalEntityResolver; /** messages are sent to this object. */ protected PrintStream out; public DebugController( boolean displayWarning ) { // for backward compatibility. Can be removed later. this( displayWarning, false ); } public DebugController( boolean displayWarning, boolean quiet ) { this( displayWarning, quiet, System.out ); } public DebugController( boolean displayWarning, boolean quiet, EntityResolver externalEntityResolver ) { this( displayWarning, quiet, System.out, externalEntityResolver ); } public DebugController( boolean displayWarning, boolean quiet, PrintStream outDevice ) { this( displayWarning, quiet, outDevice, null ); } public DebugController( boolean displayWarning, boolean quiet, PrintStream outDevice, EntityResolver externalEntityResolver ) { this.out = outDevice; this.displayWarning = displayWarning; this.warningReported = quiet; this.externalEntityResolver = externalEntityResolver; } public void warning( Locator[] loc, String errorMessage ) { if(!displayWarning) { if( !warningReported ) out.println( Driver.localize(Driver.MSG_WARNING_FOUND) ); warningReported = true; return; } out.println(errorMessage); if(loc==null || loc.length==0) out.println(" location unknown"); else for( int i=0; i=0) col = ":"+loc.getColumnNumber(); out.println( " "+ loc.getLineNumber()+ col+ "@"+ loc.getSystemId() ); } public InputSource resolveEntity( String publicId, String systemId ) throws java.io.IOException, SAXException { if(externalEntityResolver!=null) { // System.out.println("using external resolver"); return externalEntityResolver.resolveEntity(publicId,systemId); } return null; } } msv-2009.1/msv/src/com/sun/msv/driver/textui/Debug.java0000644000175000017500000000111007671170035023111 0ustar giovannigiovanni/* * @(#)$Id: Debug.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.driver.textui; public class Debug { public static boolean debug; static { try { debug = System.getProperty("com.sun.msv.debug")!=null; } catch( SecurityException e ) { // a security manager might reject this call debug = false; } } } msv-2009.1/msv/src/com/sun/msv/driver/textui/package.html0000644000175000017500000000007207273576330023515 0ustar giovannigiovanni

    Command line verifier.

    msv-2009.1/msv/src/com/sun/msv/driver/textui/Messages_ja.properties0000644000175000017500000001024607730143103025561 0ustar giovannigiovanni ReportErrorHandler.TooManyErrors =\ \u30A8\u30E9\u30FC\u304C\u591A\u3059\u304E\u307E\u3059 ReportErrorHandler.Error =\ \u30A8\u30E9\u30FC {0}\u884C\u76EE{1}\u6587\u5B57\u76EE : {2}\n\ \ \ {3}\n ReportErrorHandler.Warning =\ \u8B66\u544A\u3000 {0}\u884C\u76EE{1}\u6587\u5B57\u76EE : {2}\n\ \ \ {3}\n ReportErrorHandler.Fatal =\ \u30A8\u30E9\u30FC {0}\u884C\u76EE{1}\u6587\u5B57\u76EE : {2}\n\ \ \ {3}\n # # Driver messages # Driver.DTDValidation =\ XML\u306B\u6307\u5B9A\u3055\u308C\u3066\u3044\u308BDTD\u3082\u4F7F\u3044\u307E\u3059 Driver.Parser =\ \u30D1\u30FC\u30B5:{0} Driver.Usage =\ \u4F7F\u3044\u65B9: java -jar msv.jar <\u30B9\u30AD\u30FC\u30DE> <\u6587\u66F81> [<\u6587\u66F82> ...]\n\ \n\ \u30AA\u30D7\u30B7\u30E7\u30F3:\n\ \ \ -standalone: \u30B9\u30AD\u30FC\u30DE\u3084\u6587\u66F8\u306B\u6307\u5B9A\u3055\u308C\u3066\u3044\u308Bexternal DTD\u3092\u7121\u8996\u3057\u307E\u3059\n\ \ \ -strict : \u30B9\u30AD\u30FC\u30DE\u3092\u3088\u308A\u53B3\u5BC6\u306B\u30A8\u30E9\u30FC\u30C1\u30A7\u30C3\u30AF\u3057\u307E\u3059\n\ \ \ -dump : \u691C\u8A3C\u3067\u306F\u306A\u304F\u30B9\u30AD\u30FC\u30DE\u3092\u30C0\u30F3\u30D7\u3057\u307E\u3059\n\ \ \ -verbose : \u69D8\u3005\u306A\u60C5\u5831\u3092\u8FFD\u52A0\u51FA\u529B\u3057\u307E\u3059\n\ \ \ -maxerror : \u9593\u9055\u3063\u305F\u30A8\u30E9\u30FC\u3092\u51FA\u3059\u5371\u967A\u3092\u5192\u3057\u3066\u3067\u3082\u591A\u304F\u306E\u30A8\u30E9\u30FC\u3092\u5831\u544A\u3057\u307E\u3059\n\ \ \ -warning : \u8B66\u544A\u30E1\u30C3\u30BB\u30FC\u30B8\u3082\u8868\u793A\u3057\u307E\u3059\n\ \ \ -catalog <\u30AB\u30BF\u30ED\u30B0\u30D5\u30A1\u30A4\u30EB>\n\ \ \ : \u5916\u90E8entity\u306E\u53C2\u7167\u89E3\u6C7A\u306BTR9401\u30AB\u30BF\u30ED\u30B0\u30D5\u30A1\u30A4\u30EB\u3092\u4F7F\u7528\u3057\u307E\u3059\n\ \ \ \u8A73\u7D30\u306Fhttp://www.sun.com/xml/developers/resolver/\u3092\u898B\u3066\u304F\u3060\u3055\u3044\n\ \ \ -version : \u30D0\u30FC\u30B8\u30E7\u30F3\u756A\u53F7\u3092\u8868\u793A\u3057\u307E\u3059\n\ \ \ -classpath /<\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA>\n\ \ \ : RELAX NG\u691C\u8A3C\u306E\u6642\u306B\u3001\u8FFD\u52A0\u3067\u5229\u7528\u3059\u308B\u30C7\u30FC\u30BF\u578B\u30E9\u30A4\u30D6\u30E9\u30EA\u3092\n\ \ \ \u6307\u5B9A\u3057\u307E\u3059\u3002\u8907\u6570\u56DE\u6307\u5B9A\u53EF\n\ \ \ -locale <\u30ED\u30B1\u30FC\u30EB>\n\ \ \ : \u30E1\u30C3\u30BB\u30FC\u30B8\u306E\u8A00\u8A9E\u3092\u6307\u5B9A\u3057\u307E\u3059(\u4F8B:"en","ja")\n\ \ \ -xerces : Xerces-J\u3092XML\u30D1\u30FC\u30B5\u3068\u3057\u3066\u4F7F\u3044\u307E\u3059\n\ \ \ -crimson : Crimson\u3092XML\u30D1\u30FC\u30B5\u3068\u3057\u3066\u4F7F\u3044\u307E\u3059\n\ \ \ -oraclev2 : Oracle V2\u30D1\u30FC\u30B5\u3092XML\u30D1\u30FC\u30B5\u3068\u3057\u3066\u4F7F\u3044\u307E\u3059\n Driver.UnrecognizedOption =\ \u7121\u52B9\u306A\u30AA\u30D7\u30B7\u30E7\u30F3\u3067\u3059: {0} Driver.StartParsingGrammar =\ \u30B9\u30AD\u30FC\u30DE\u3092\u8AAD\u307F\u8FBC\u3093\u3067\u3044\u307E\u3059... Driver.ParsingTime =\ \u30B9\u30AD\u30FC\u30DE\u8AAD\u307F\u8FBC\u307F\u5B8C\u4E86 ({0} ms) Driver.ValidationTime =\ \u691C\u8A3C\u5B8C\u4E86 ({0} ms) Driver.Validating =\ \u691C\u8A3C\u3057\u3066\u3044\u307E\u3059: {0} Driver.Valid =\ \u6587\u66F8\u306F\u59A5\u5F53(valid)\u3067\u3059 Driver.Invalid =\ \u6587\u66F8\u306B\u9055\u53CD\u304C\u307F\u3064\u304B\u308A\u307E\u3057\u305F Driver.ErrLoadGrammar =\ \u30B9\u30AD\u30FC\u30DE\u306E\u8AAD\u307F\u8FBC\u307F\u306B\u5931\u6557\u3057\u307E\u3057\u305F Driver.BailOut =\ \u51E6\u7406\u3092\u4E2D\u65AD\u3057\u307E\u3059 Driver.FailedToIgnoreExternalDTD =\ XML\u30D1\u30FC\u30B5\u306B\u5916\u90E8DTD\u3092\u7121\u8996\u3055\u305B\u308B\u3053\u3068\u304C\u51FA\u6765\u307E\u305B\u3093\u3067\u3057\u305F Driver.SniffSchema =\ detecting schema type. (use -relax/-trex option to skip this process) Driver.UnknownSchema =\ \u30B9\u30AD\u30FC\u30DE\u306E\u7A2E\u985E\u304C\u5224\u5225\u3067\u304D\u307E\u305B\u3093: {0} Driver.WarningFound =\ \u8B66\u544A\u304C\u898B\u3064\u304B\u308A\u307E\u3057\u305F\u3002-warning\u30AA\u30D7\u30B7\u30E7\u30F3\u3092\u4F7F\u3046\u3068\u8B66\u544A\u3082\u8868\u793A\u3067\u304D\u307E\u3059msv-2009.1/msv/src/com/sun/msv/driver/textui/Driver.java0000644000175000017500000004404310005261170023314 0ustar giovannigiovanni/* * @(#)$Id: Driver.java 1626 2004-01-26 18:54:48Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.driver.textui; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Locale; import javax.xml.parsers.SAXParserFactory; import org.apache.xml.resolver.tools.CatalogResolver; import org.iso_relax.dispatcher.Dispatcher; import org.iso_relax.dispatcher.SchemaProvider; import org.iso_relax.dispatcher.impl.DispatcherImpl; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import com.sun.msv.grammar.Grammar; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.relax.RELAXModule; import com.sun.msv.grammar.trex.TREXGrammar; import com.sun.msv.grammar.util.ExpressionPrinter; import com.sun.msv.grammar.xmlschema.ElementDeclExp; import com.sun.msv.grammar.xmlschema.XMLSchemaGrammar; import com.sun.msv.grammar.xmlschema.XMLSchemaSchema; import com.sun.msv.reader.util.GrammarLoader; import com.sun.msv.relaxns.grammar.RELAXGrammar; import com.sun.msv.relaxns.verifier.SchemaProviderImpl; import com.sun.msv.util.Util; import com.sun.msv.verifier.DocumentDeclaration; import com.sun.msv.verifier.Verifier; import com.sun.msv.verifier.identity.IDConstraintChecker; import com.sun.msv.verifier.regexp.REDocumentDeclaration; /** * command line Verifier. * * @author Kohsuke KAWAGUCHI */ public class Driver { static SAXParserFactory factory; /** Prints the usage screen. */ private static void usage() { System.out.println( localize(MSG_USAGE) ); } /** Prints the version number. */ private static void printVersion() { System.out.println("Multi Schema Validator Ver."+ java.util.ResourceBundle.getBundle("version").getString("version") ); } public static void main( String[] args ) throws Exception { System.exit(run(args)); } public static int run( String[] args ) throws Exception { final List fileNames = new ArrayList(); final List classPaths = new ArrayList(); String grammarName = null; boolean dump=false; boolean verbose = false; boolean warning = false; boolean standalone=false; boolean strict=false; boolean usePanicMode=true; EntityResolver entityResolver=null; for( int i=0; iKohsuke KAWAGUCHI */ public class ReportErrorHandler implements ErrorHandler { private int counter = 0; public boolean hadError = false; public void error( SAXParseException e ) throws SAXException { hadError = true; countCheck(e); printSAXParseException( e, MSG_ERROR ); } public void fatalError( SAXParseException e ) throws SAXException { hadError = true; printSAXParseException( e, MSG_FATAL ); throw new ValidationUnrecoverableException(e); } public void warning( SAXParseException e ) { printSAXParseException( e, MSG_WARNING ); } protected static void printSAXParseException( SAXParseException spe, String prop ) { System.out.println( Driver.localize( prop, new Object[]{ new Integer(spe.getLineNumber()), new Integer(spe.getColumnNumber()), spe.getSystemId(), spe.getLocalizedMessage()} ) ); } private void countCheck( SAXParseException e ) throws ValidationUnrecoverableException { if( counter++ < 20 ) return; System.out.println( Driver.localize(MSG_TOO_MANY_ERRORS) ); throw new ValidationUnrecoverableException(e); } public static final String MSG_TOO_MANY_ERRORS = //arg:1 "ReportErrorHandler.TooManyErrors"; public static final String MSG_ERROR = // arg:4 "ReportErrorHandler.Error"; public static final String MSG_WARNING = // arg:4 "ReportErrorHandler.Warning"; public static final String MSG_FATAL = // arg:4 "ReportErrorHandler.Fatal"; } msv-2009.1/msv/src/com/sun/msv/driver/textui/Messages.properties0000644000175000017500000000456107730143103025112 0ustar giovannigiovanni ReportErrorHandler.TooManyErrors =\ too many errors. ReportErrorHandler.Error =\ Error at line:{0}, column:{1} of {2}\n\ \ \ {3}\n ReportErrorHandler.Warning =\ Warning at line:{0}, column:{1} of {2}\n\ \ \ {3}\n ReportErrorHandler.Fatal =\ Fatal error at line:{0}, column:{1} of {2}\n\ \ \ {3}\n # # Driver messages # Driver.DTDValidation =\ DTD validation will be done. Driver.Parser =\ using {0} Driver.Usage =\ usage: java -jar msv.jar [ ...]\n\ \n\ options:\n\ \ \ -standalone: do not read external DTD specified in grammar/instances.\n\ \ \ -strict : perform extra check to schema and report error.\n\ \ \ -dump : dump grammar rather than perform validation.\n\ \ \ -debug : generate debug messages.\n\ \ \ -verbose : be verbose.\n\ \ \ -maxerror : try to report more errors even if they may be false.\n\ \ \ -warning : display all warning messages\n\ \ \ -catalog \n\ \ \ : use a catalog file (TR9401) to resolve external entities\n\ \ \ for detail, see http://www.sun.com/xml/developers/resolver/\n\ \ \ -version : display version number.\n\ \ \ -classpath /\n\ \ \ : use this option to specify additional datatype library\n\ \ \ jar files for RELAX NG validation. Can be specified multiple times\n\ \ \ -locale \n\ \ \ : set the language of messages (i.e., "en","ja")\n\ \ \ -xerces : use Xerces-J parser for parsing grammar and instances.\n\ \ \ -crimson : use Crimson parser for parsing grammar and instances.\n\ \ \ -oraclev2 : use OracleV2 parser for parsing grammar and instances.\n Driver.UnrecognizedOption =\ unrecognized option: {0} Driver.StartParsingGrammar =\ start parsing a grammar. Driver.ParsingTime =\ parsing took {0} ms. Driver.ValidationTime =\ validation took {0} ms. Driver.Validating =\ validating {0} Driver.Valid =\ the document is valid. Driver.Invalid =\ the document is NOT valid. Driver.ErrLoadGrammar =\ failed to load a grammar. Driver.BailOut =\ bailing out. Driver.FailedToIgnoreExternalDTD =\ failed to configure parser to ignore the external DTD. Driver.SniffSchema =\ detecting schema type. (use -relax/-trex option to skip this process) Driver.UnknownSchema =\ unrecognized schema "{0}". Driver.WarningFound =\ warnings are found. use -warning switch to see all warnings.msv-2009.1/msv/src/com/sun/msv/writer/0000755000175000017500000000000011622453067017726 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/writer/GrammarWriter.java0000644000175000017500000000222607671170035023356 0ustar giovannigiovanni/* * @(#)$Id: GrammarWriter.java 1566 2003-06-09 20:37:49Z kk122374 $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.writer; import org.xml.sax.DocumentHandler; import org.xml.sax.SAXException; import com.sun.msv.grammar.Grammar; /** * Converter from AGM to the XML representation. * * @author Kohsuke KAWAGUCHI */ public interface GrammarWriter { /** * Sets DocumentHandler. This handler will receive the result of conversion. */ void setDocumentHandler( DocumentHandler handler ); /** * Converts this grammar to the XML representation. * * @exception UnsupportedOperationException * if this grammar cannot be serialized. * this exception can be thrown on the half way of the conversion. * * @exception SAXException * DocumentHandler may throw a SAXException. */ void write( Grammar grammar ) throws UnsupportedOperationException, SAXException; } msv-2009.1/msv/src/com/sun/msv/writer/ContentHandlerAdaptor.java0000644000175000017500000003457207671170035025027 0ustar giovannigiovannipackage com.sun.msv.writer; import java.util.Enumeration; import org.xml.sax.AttributeList; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.DocumentHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.AttributesImpl; import org.xml.sax.helpers.NamespaceSupport; /** * Adapt SAX2 ContentHandler as a SAX1 DocumentHandler. * * This class wraps a ContentHandler and makes it act as a DocumentHandler. * * @author David Megginson, * sax@megginson.com */ public class ContentHandlerAdaptor implements DocumentHandler { private final NamespaceSupport nsSupport = new NamespaceSupport(); private final ContentHandler contentHandler; private final AttributeListAdapter attAdapter = new AttributeListAdapter(); private final AttributesImpl atts = new AttributesImpl(); private final boolean namespaces = true; private final boolean prefixes = false; private final String nameParts[] = new String[3]; public ContentHandlerAdaptor( ContentHandler handler ) { this.contentHandler = handler; } //////////////////////////////////////////////////////////////////// // Implementation of org.xml.sax.DocumentHandler. //////////////////////////////////////////////////////////////////// /** * Adapt a SAX1 document locator event. * * @param locator A document locator. * @see org.xml.sax.ContentHandler#setDocumentLocator */ public void setDocumentLocator (Locator locator) { if (contentHandler != null) { contentHandler.setDocumentLocator(locator); } } /** * Adapt a SAX1 start document event. * * @exception org.xml.sax.SAXException The client may raise a * processing exception. * @see org.xml.sax.DocumentHandler#startDocument */ public void startDocument () throws SAXException { if (contentHandler != null) { contentHandler.startDocument(); } } /** * Adapt a SAX1 end document event. * * @exception org.xml.sax.SAXException The client may raise a * processing exception. * @see org.xml.sax.DocumentHandler#endDocument */ public void endDocument () throws SAXException { if (contentHandler != null) { contentHandler.endDocument(); } } /** * Adapt a SAX1 startElement event. * *

    If necessary, perform Namespace processing.

    * * @param qName The qualified (prefixed) name. * @param qAtts The XML 1.0 attribute list (with qnames). */ public void startElement (String qName, AttributeList qAtts) throws SAXException { // If we're not doing Namespace // processing, dispatch this quickly. if (!namespaces) { if (contentHandler != null) { attAdapter.setAttributeList(qAtts); contentHandler.startElement("", "", qName.intern(), attAdapter); } return; } // OK, we're doing Namespace processing. nsSupport.pushContext(); boolean seenDecl = false; atts.clear(); // Take a first pass and copy all // attributes into the SAX2 attribute // list, noting any Namespace // declarations. int length = qAtts.getLength(); for (int i = 0; i < length; i++) { String attQName = qAtts.getName(i); String type = qAtts.getType(i); String value = qAtts.getValue(i); // Found a declaration... if (attQName.startsWith("xmlns")) { String prefix; int n = attQName.indexOf(':'); if (n == -1) { prefix = ""; } else { prefix = attQName.substring(n+1); } if (!nsSupport.declarePrefix(prefix, value)) { reportError("Illegal Namespace prefix: " + prefix); } if (contentHandler != null) { contentHandler.startPrefixMapping(prefix, value); } // We may still have to add this to // the list. if (prefixes) { atts.addAttribute("", "", attQName.intern(), type, value); } seenDecl = true; // This isn't a declaration. } else { String attName[] = processName(attQName, true); atts.addAttribute(attName[0], attName[1], attName[2], type, value); } } // If there was a Namespace declaration, // we have to make a second pass just // to be safe -- this will happen very // rarely, possibly only once for each // document. if (seenDecl) { length = atts.getLength(); for (int i = 0; i < length; i++) { String attQName = atts.getQName(i); if (!attQName.startsWith("xmlns")) { String attName[] = processName(attQName, true); atts.setURI(i, attName[0]); atts.setLocalName(i, attName[1]); } } } // OK, finally report the event. if (contentHandler != null) { String name[] = processName(qName, false); contentHandler.startElement(name[0], name[1], name[2], atts); } } /** * Adapt a SAX1 end element event. * * @param qName The qualified (prefixed) name. * @exception org.xml.sax.SAXException The client may raise a * processing exception. * @see org.xml.sax.DocumentHandler#endElement */ public void endElement (String qName) throws SAXException { // If we're not doing Namespace // processing, dispatch this quickly. if (!namespaces) { if (contentHandler != null) { contentHandler.endElement("", "", qName.intern()); } return; } // Split the name. String names[] = processName(qName, false); if (contentHandler != null) { contentHandler.endElement(names[0], names[1], names[2]); Enumeration prefixes = nsSupport.getDeclaredPrefixes(); while (prefixes.hasMoreElements()) { String prefix = (String)prefixes.nextElement(); contentHandler.endPrefixMapping(prefix); } } nsSupport.popContext(); } /** * Adapt a SAX1 characters event. * * @param ch An array of characters. * @param start The starting position in the array. * @param length The number of characters to use. * @exception org.xml.sax.SAXException The client may raise a * processing exception. * @see org.xml.sax.DocumentHandler#characters */ public void characters (char ch[], int start, int length) throws SAXException { if (contentHandler != null) { contentHandler.characters(ch, start, length); } } /** * Adapt a SAX1 ignorable whitespace event. * * @param ch An array of characters. * @param start The starting position in the array. * @param length The number of characters to use. * @exception org.xml.sax.SAXException The client may raise a * processing exception. * @see org.xml.sax.DocumentHandler#ignorableWhitespace */ public void ignorableWhitespace (char ch[], int start, int length) throws SAXException { if (contentHandler != null) { contentHandler.ignorableWhitespace(ch, start, length); } } /** * Adapt a SAX1 processing instruction event. * * @param target The processing instruction target. * @param data The remainder of the processing instruction * @exception org.xml.sax.SAXException The client may raise a * processing exception. * @see org.xml.sax.DocumentHandler#processingInstruction */ public void processingInstruction (String target, String data) throws SAXException { if (contentHandler != null) { contentHandler.processingInstruction(target, data); } } private String [] processName (String qName, boolean isAttribute) throws SAXException { String parts[] = nsSupport.processName(qName, nameParts, isAttribute); if (parts == null) { parts = new String[3]; parts[2] = qName.intern(); reportError("Undeclared prefix: " + qName); } return parts; } /** * Report a non-fatal error. * * @param message The error message. * @exception org.xml.sax.SAXException The client may throw * an exception. */ void reportError (String message) throws SAXException { throw new SAXParseException(message, null, null, -1, -1 ); } //////////////////////////////////////////////////////////////////// // Inner class to wrap an AttributeList when not doing NS proc. //////////////////////////////////////////////////////////////////// /** * Adapt a SAX1 AttributeList as a SAX2 Attributes object. * *

    This class is in the Public Domain, and comes with NO * WARRANTY of any kind.

    * *

    This wrapper class is used only when Namespace support * is disabled -- it provides pretty much a direct mapping * from SAX1 to SAX2, except that names and types are * interned whenever requested.

    */ final class AttributeListAdapter implements Attributes { /** * Construct a new adapter. */ AttributeListAdapter () { } /** * Set the embedded AttributeList. * *

    This method must be invoked before any of the others * can be used.

    * * @param The SAX1 attribute list (with qnames). */ void setAttributeList (AttributeList qAtts) { this.qAtts = qAtts; } /** * Return the length of the attribute list. * * @return The number of attributes in the list. * @see org.xml.sax.Attributes#getLength */ public int getLength () { return qAtts.getLength(); } /** * Return the Namespace URI of the specified attribute. * * @param The attribute's index. * @return Always the empty string. * @see org.xml.sax.Attributes#getURI */ public String getURI (int i) { return ""; } /** * Return the local name of the specified attribute. * * @param The attribute's index. * @return Always the empty string. * @see org.xml.sax.Attributes#getLocalName */ public String getLocalName (int i) { return ""; } /** * Return the qualified (prefixed) name of the specified attribute. * * @param The attribute's index. * @return The attribute's qualified name, internalized. */ public String getQName (int i) { return qAtts.getName(i).intern(); } /** * Return the type of the specified attribute. * * @param The attribute's index. * @return The attribute's type as an internalized string. */ public String getType (int i) { return qAtts.getType(i).intern(); } /** * Return the value of the specified attribute. * * @param The attribute's index. * @return The attribute's value. */ public String getValue (int i) { return qAtts.getValue(i); } /** * Look up an attribute index by Namespace name. * * @param uri The Namespace URI or the empty string. * @param localName The local name. * @return The attributes index, or -1 if none was found. * @see org.xml.sax.Attributes#getIndex(java.lang.String,java.lang.String) */ public int getIndex (String uri, String localName) { return -1; } /** * Look up an attribute index by qualified (prefixed) name. * * @param qName The qualified name. * @return The attributes index, or -1 if none was found. * @see org.xml.sax.Attributes#getIndex(java.lang.String) */ public int getIndex (String qName) { int max = atts.getLength(); for (int i = 0; i < max; i++) { if (qAtts.getName(i).equals(qName)) { return i; } } return -1; } /** * Look up the type of an attribute by Namespace name. * * @param uri The Namespace URI * @param localName The local name. * @return The attribute's type as an internalized string. */ public String getType (String uri, String localName) { return null; } /** * Look up the type of an attribute by qualified (prefixed) name. * * @param qName The qualified name. * @return The attribute's type as an internalized string. */ public String getType (String qName) { return qAtts.getType(qName).intern(); } /** * Look up the value of an attribute by Namespace name. * * @param uri The Namespace URI * @param localName The local name. * @return The attribute's value. */ public String getValue (String uri, String localName) { return null; } /** * Look up the value of an attribute by qualified (prefixed) name. * * @param qName The qualified name. * @return The attribute's value. */ public String getValue (String qName) { return qAtts.getValue(qName); } private AttributeList qAtts; } } msv-2009.1/msv/src/com/sun/msv/writer/XMLWriter.java0000644000175000017500000000353607671170035022435 0ustar giovannigiovannipackage com.sun.msv.writer; import org.xml.sax.DocumentHandler; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributeListImpl; /** * Helper class that wraps {@link DocumentHandler} and provides utility methods. * *

    * Note that this class uses DocumentHandler, not ContentHandler. * This generally allows the caller better control. * *

    * This class throws {@link SAXRuntimeException}, instead of SAXException. */ public class XMLWriter { protected DocumentHandler handler; /** this DocumentHandler will receive XML. */ public void setDocumentHandler( DocumentHandler handler ) { this.handler = handler; } public DocumentHandler getDocumentHandler() { return handler; } public void element( String name ) { element( name, new String[0] ); } public void element( String name, String[] attributes ) { start(name,attributes); end(name); } public void start( String name ) { start(name, new String[0] ); } public void start( String name, String[] attributes ) { // create attributes. AttributeListImpl as = new AttributeListImpl(); for( int i=0; i

    AGM to RELAX NG converter

    msv-2009.1/msv/src/com/sun/msv/writer/relaxng/PatternWriter.java0000644000175000017500000003721607671170035025054 0ustar giovannigiovannipackage com.sun.msv.writer.relaxng; import java.util.HashSet; import java.util.Set; import java.util.Vector; import org.relaxng.datatype.Datatype; import org.relaxng.datatype.ValidationContext; import com.sun.msv.datatype.SerializationContext; import com.sun.msv.datatype.xsd.ConcreteType; import com.sun.msv.datatype.xsd.DataTypeWithFacet; import com.sun.msv.datatype.xsd.EnumerationFacet; import com.sun.msv.datatype.xsd.FinalComponent; import com.sun.msv.datatype.xsd.FractionDigitsFacet; import com.sun.msv.datatype.xsd.LengthFacet; import com.sun.msv.datatype.xsd.ListType; import com.sun.msv.datatype.xsd.MaxLengthFacet; import com.sun.msv.datatype.xsd.MinLengthFacet; import com.sun.msv.datatype.xsd.PatternFacet; import com.sun.msv.datatype.xsd.RangeFacet; import com.sun.msv.datatype.xsd.TokenType; import com.sun.msv.datatype.xsd.TotalDigitsFacet; import com.sun.msv.datatype.xsd.UnionType; import com.sun.msv.datatype.xsd.WhiteSpaceFacet; import com.sun.msv.datatype.xsd.XSDatatype; import com.sun.msv.datatype.xsd.XSDatatypeImpl; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.BinaryExp; import com.sun.msv.grammar.ChoiceExp; import com.sun.msv.grammar.ConcurExp; import com.sun.msv.grammar.DataExp; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionVisitorVoid; import com.sun.msv.grammar.InterleaveExp; import com.sun.msv.grammar.ListExp; import com.sun.msv.grammar.MixedExp; import com.sun.msv.grammar.OneOrMoreExp; import com.sun.msv.grammar.OtherExp; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.SequenceExp; import com.sun.msv.grammar.ValueExp; import com.sun.msv.writer.XMLWriter; /** * Visits Expression and writes it as RELAX NG. */ public abstract class PatternWriter implements ExpressionVisitorVoid { public PatternWriter(Context ctxt) { this.writer = ctxt.getWriter(); this.context = ctxt; } protected final XMLWriter writer; protected final Context context; public abstract void onOther(OtherExp exp); public abstract void onRef(ReferenceExp exp); public void onElement(ElementExp exp) { writer.start("element"); context.writeNameClass(exp.getNameClass()); visitUnary(exp.contentModel); writer.end("element"); } public void onEpsilon() { writer.element("empty"); } public void onNullSet() { writer.element("notAllowed"); } public void onAnyString() { writer.element("text"); } public void onInterleave(InterleaveExp exp) { visitBinExp("interleave", exp, InterleaveExp.class); } public void onConcur(ConcurExp exp) { throw new IllegalArgumentException("the grammar includes concur, which is not supported"); } public void onList(ListExp exp) { writer.start("list"); visitUnary(exp.exp); writer.end("list"); } protected void onOptional(Expression exp) { if (exp instanceof OneOrMoreExp) { // (X+)? == X* onZeroOrMore((OneOrMoreExp)exp); return; } writer.start("optional"); visitUnary(exp); writer.end("optional"); } public void onChoice(ChoiceExp exp) { // use optional instead of p if (exp.exp1 == Expression.epsilon) { onOptional(exp.exp2); return; } if (exp.exp2 == Expression.epsilon) { onOptional(exp.exp1); return; } visitBinExp("choice", exp, ChoiceExp.class); } public void onSequence(SequenceExp exp) { visitBinExp("group", exp, SequenceExp.class); } public void visitBinExp(String elementName, BinaryExp exp, Class type) { // since AGM is binarized, // a b c is represented as // a b c // this method print them as a b c writer.start(elementName); Expression[] children = exp.getChildren(); for (int i = 0; i < children.length; i++) children[i].visit(this); writer.end(elementName); } public void onMixed(MixedExp exp) { writer.start("mixed"); visitUnary(exp.exp); writer.end("mixed"); } public void onOneOrMore(OneOrMoreExp exp) { writer.start("oneOrMore"); visitUnary(exp.exp); writer.end("oneOrMore"); } protected void onZeroOrMore(OneOrMoreExp exp) { // note that this method is not a member of TREXPatternVisitor. writer.start("zeroOrMore"); visitUnary(exp.exp); writer.end("zeroOrMore"); } public void onAttribute(AttributeExp exp) { writer.start("attribute"); context.writeNameClass(exp.nameClass); visitUnary(exp.exp); writer.end("attribute"); } /** * print expression but surpress unnecessary sequence. */ public void visitUnary(Expression exp) { // TREX treats p q // as p q // This method tries to exploit this property to // simplify the result. if (exp instanceof SequenceExp) { SequenceExp seq = (SequenceExp)exp; visitUnary(seq.exp1); seq.exp2.visit(this); } else exp.visit(this); } public void onValue( ValueExp exp ) { if (exp.dt instanceof XSDatatypeImpl) { XSDatatypeImpl base = (XSDatatypeImpl)exp.dt; final Vector ns = new Vector(); String lex = base.convertToLexicalValue(exp.value, new SerializationContext() { public String getNamespacePrefix(String namespaceURI) { int cnt = ns.size() / 2; ns.add("xmlns:ns" + cnt); ns.add(namespaceURI); return "ns" + cnt; } }); if (base != TokenType.theInstance) { // if the type is token, we don't need @type. ns.add("type"); ns.add(base.getName()); } writer.start("value", (String[])ns.toArray(new String[0])); writer.characters(lex); writer.end("value"); return; } throw new UnsupportedOperationException( exp.dt.getClass().getName() ); } public void onData(DataExp exp) { Datatype dt = exp.dt; if (dt instanceof XSDatatypeImpl) { XSDatatypeImpl dti = (XSDatatypeImpl)dt; if (isPredefinedType(dt)) { // it's a pre-defined types. writer.element("data", new String[] { "type", dti.getName()}); } else { serializeDataType(dti); } return; } // unknown datatype writer.element("data-unknown", new String[] { "class", dt.getClass().getName()}); } /** * serializes the given datatype. * * The caller should generate events for <simpleType> element * if necessary. */ protected void serializeDataType(XSDatatype dt) { if (dt instanceof UnionType) { serializeUnionType((UnionType)dt); return; } // store names of the applied facets into this set Set appliedFacets = new HashSet(); // store effective facets (those which are not shadowed by another facet). Vector effectiveFacets = new Vector(); XSDatatype x = dt; while (x instanceof DataTypeWithFacet || x instanceof FinalComponent) { if (x instanceof FinalComponent) { // skip FinalComponent x = x.getBaseType(); continue; } String facetName = ((DataTypeWithFacet)x).facetName; if (facetName.equals(XSDatatypeImpl.FACET_ENUMERATION)) { // if it contains enumeration, then we will serialize this // by using s. serializeEnumeration((XSDatatypeImpl)dt, (EnumerationFacet)x); return; } if (facetName.equals(XSDatatypeImpl.FACET_WHITESPACE)) { // TODO: better error handling System.err.println("warning: unsupported whiteSpace facet is ignored"); x = x.getBaseType(); continue; } // find the same facet twice. // pattern is allowed more than once. if (!appliedFacets.contains(facetName) || appliedFacets.equals(XSDatatypeImpl.FACET_PATTERN)) { appliedFacets.add(facetName); effectiveFacets.add(x); } x = ((DataTypeWithFacet)x).baseType; } if (x instanceof ListType) { // the base type is list. serializeListType((XSDatatypeImpl)dt); return; } // it cannot be the union type. Union type cannot be derived by // restriction. // so this must be one of the pre-defined types. if (!(x instanceof ConcreteType)) throw new Error(x.getClass().getName()); if (x instanceof com.sun.msv.grammar.relax.EmptyStringType) { // empty token will do. writer.element("value"); return; } if (x instanceof com.sun.msv.grammar.relax.NoneType) { // "none" is equal to writer.element("notAllowed"); return; } writer.start("data", new String[] { "type", x.getName()}); // serialize effective facets for (int i = effectiveFacets.size() - 1; i >= 0; i--) { DataTypeWithFacet dtf = (DataTypeWithFacet)effectiveFacets.get(i); if (dtf instanceof LengthFacet) { param("length", Long.toString(((LengthFacet)dtf).length)); } else if (dtf instanceof MinLengthFacet) { param("minLength", Long.toString(((MinLengthFacet)dtf).minLength)); } else if (dtf instanceof MaxLengthFacet) { param("maxLength", Long.toString(((MaxLengthFacet)dtf).maxLength)); } else if (dtf instanceof PatternFacet) { String pattern = ""; PatternFacet pf = (PatternFacet)dtf; for (int j = 0; j < pf.getRegExps().length; j++) { if (pattern.length() != 0) pattern += "|"; pattern += pf.patterns[j]; } param("pattern", pattern); } else if (dtf instanceof TotalDigitsFacet) { param("totalDigits", Long.toString(((TotalDigitsFacet)dtf).precision)); } else if (dtf instanceof FractionDigitsFacet) { param("fractionDigits", Long.toString(((FractionDigitsFacet)dtf).scale)); } else if (dtf instanceof RangeFacet) { param(dtf.facetName, dtf.convertToLexicalValue(((RangeFacet)dtf).limitValue, null)); // we don't need to pass SerializationContext because it is only // for QName. } else if (dtf instanceof WhiteSpaceFacet) { ; // do nothing. } else // undefined facet type throw new Error(); } writer.end("data"); } protected void param(String name, String value) { writer.start("param", new String[] { "name", name }); writer.characters(value); writer.end("param"); } /** * returns true if the specified type is a pre-defined XSD type * without any facet. */ protected boolean isPredefinedType(Datatype x) { return !( x instanceof DataTypeWithFacet || x instanceof UnionType || x instanceof ListType || x instanceof FinalComponent || x instanceof com.sun.msv.grammar.relax.EmptyStringType || x instanceof com.sun.msv.grammar.relax.NoneType); } /** * serializes a union type. * this method is called by serializeDataType method. */ protected void serializeUnionType(UnionType dt) { writer.start("choice"); // serialize member types. for (int i = 0; i < dt.memberTypes.length; i++) serializeDataType(dt.memberTypes[i]); writer.end("choice"); } /** * serializes a list type. * this method is called by serializeDataType method. */ protected void serializeListType(XSDatatypeImpl dt) { ListType base = (ListType)dt.getConcreteType(); if (dt.getFacetObject(XSDatatype.FACET_LENGTH) != null) { // with the length facet. int len = ((LengthFacet)dt.getFacetObject(XSDatatype.FACET_LENGTH)).length; writer.start("list"); for (int i = 0; i < len; i++) serializeDataType(base.itemType); writer.end("list"); return; } if (dt.getFacetObject(XSDatatype.FACET_MAXLENGTH) != null) throw new UnsupportedOperationException("warning: maxLength facet to list type is not properly converted."); MinLengthFacet minLength = (MinLengthFacet)dt.getFacetObject(XSDatatype.FACET_MINLENGTH); writer.start("list"); if (minLength != null) { // list n times for (int i = 0; i < minLength.minLength; i++) serializeDataType(base.itemType); } writer.start("zeroOrMore"); serializeDataType(base.itemType); writer.end("zeroOrMore"); writer.end("list"); } /** * serializes a type with enumeration. * this method is called by serializeDataType method. */ protected void serializeEnumeration(XSDatatypeImpl dt, EnumerationFacet enums) { Object[] values = enums.values.toArray(); if (values.length > 1) writer.start("choice"); for (int i = 0; i < values.length; i++) { final Vector ns = new Vector(); String lex = dt.convertToLexicalValue(values[i], new SerializationContext() { public String getNamespacePrefix(String namespaceURI) { int cnt = ns.size() / 2; ns.add("xmlns:ns" + cnt); ns.add(namespaceURI); return "ns" + cnt; } }); // make sure that the converted lexical value is allowed by this type. // sometimes, facets that are added later rejects some of // enumeration values. boolean allowed = dt.isValid(lex, new ValidationContext() { public String resolveNamespacePrefix(String prefix) { if (!prefix.startsWith("ns")) return null; int i = Integer.parseInt(prefix.substring(2)); return (String)ns.get(i * 2 + 1); } public boolean isUnparsedEntity(String name) { return true; } public boolean isNotation(String name) { return true; } public String getBaseUri() { return null; } }); ns.add("type"); ns.add(dt.getConcreteType().getName()); if (allowed) { writer.start("value", (String[])ns.toArray(new String[0])); writer.characters(lex); writer.end("value"); } } if (values.length > 1) writer.end("choice"); } } msv-2009.1/msv/src/com/sun/msv/writer/relaxng/Context.java0000644000175000017500000000036307671170035023657 0ustar giovannigiovannipackage com.sun.msv.writer.relaxng; import com.sun.msv.grammar.NameClass; import com.sun.msv.writer.XMLWriter; public interface Context { void writeNameClass( NameClass nc ); String getTargetNamespace(); XMLWriter getWriter(); } msv-2009.1/msv/src/com/sun/msv/writer/relaxng/RELAXNGWriter.java0000644000175000017500000005156207730143103024527 0ustar giovannigiovanni/* * @(#)$Id: RELAXNGWriter.java 1601 2003-09-11 19:00:19Z kohsuke $ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.writer.relaxng; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.xml.sax.DocumentHandler; import org.xml.sax.SAXException; import org.xml.sax.helpers.LocatorImpl; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.BinaryExp; import com.sun.msv.grammar.ChoiceExp; import com.sun.msv.grammar.ChoiceNameClass; import com.sun.msv.grammar.ConcurExp; import com.sun.msv.grammar.DataExp; import com.sun.msv.grammar.DifferenceNameClass; import com.sun.msv.grammar.ElementExp; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ExpressionCloner; import com.sun.msv.grammar.ExpressionVisitor; import com.sun.msv.grammar.Grammar; import com.sun.msv.grammar.InterleaveExp; import com.sun.msv.grammar.ListExp; import com.sun.msv.grammar.MixedExp; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.NameClassVisitor; import com.sun.msv.grammar.NamespaceNameClass; import com.sun.msv.grammar.OneOrMoreExp; import com.sun.msv.grammar.OtherExp; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.SequenceExp; import com.sun.msv.grammar.SimpleNameClass; import com.sun.msv.grammar.ValueExp; import com.sun.msv.grammar.util.ExpressionWalker; import com.sun.msv.grammar.util.PossibleNamesCollector; import com.sun.msv.reader.datatype.xsd.XSDVocabulary; import com.sun.msv.reader.trex.ng.RELAXNGReader; import com.sun.msv.util.StringPair; import com.sun.msv.writer.GrammarWriter; import com.sun.msv.writer.SAXRuntimeException; import com.sun.msv.writer.XMLWriter; /** * converts any Grammar into RELAX NG XML representation through SAX1 events. * *

    How it works

    * *

    * {@link Grammar} object can be thought as a (possibly) cyclic graph * made from {@link Expression}. For example, the following simple * TREX pattern will be represented as following AGM. *

    *
    
     * <grammar>
     *   <start name="X">
     *     <element name="foo">
     *       <choice>
     *         <string> abc </string>
     *         <ref name="Y" />
     *       </choice>
     *     </element>
     *   </start>
     *   <define name="Y">
     *     <element name="bar">
     *       <string> abc </string>
     *       <optional>
     *         <ref name="X" />
     *       </optional>
     *     </element>
     *   </define>
     * </grammar>
     * 
    * * *

    * Note that *

    *
      *
    • sub expressions are shared (see <string> expression). *
    • there is a cycle in the graph. *
    • several syntax elements are replaced by others * (e.g., <optional>P</optional> -> <choice><empty/>P</choice>) *
    * *

    * To write these expressions into TREX XML representation, * we have to take care of cycles, since cyclic references cannot be written into * XML without first cut it and use <ref>/<define> pair. *

    * *

    * First, this algorithm splits the grammar into "islands". * Island is a tree of expressions; it has a head expression * and most importantly it doesn't contain any cycles in it. Member of an island * can be always reached from its head. *

    * *

    * TREXWriter will make every {@link ElementExp} and * {@link ReferenceExp} a head of their own island. So each of them * has their own island. *

    * It is guaranteed that this split will always give islands without inner cycles. * Several islands can form a cycle, but one island can never have a cycle in it. * This is because there is always at least one ElementExp in any cycle. *

    * *

    * Note that since expressions are shared, one expression can be * a member of several islands (although this isn't depicted in the above figure.) *

    *

    * Then, this algorithm merges some islands. For example, island E is * referenced only once (from island D). This means that there is no need to * give a name to this pattern. Instead, island E can simply written as a * subordinate of island D. *

    * In other words, any island who is only referenced at most once is merged * into its referer. This step makes the output more compact. *

    * *

    * Next, TREXWriter assigns a name to each island. It tries to use the name of * the head expression. If a head is anonymous ReferenceExp (ReferenceExp whose * name field is null) or there is a name conflict, TREXWriter * will add some suffix to make the name unique. *

    * Finally, each island is written as one named pattern under <define> * element. All inter-island references are replaced by <ref> element. *

    * *

    Why SAX1?

    *

    * Due to the bug and insufficient supports for the serialization through SAX2, * The decision is made to use SAX1. SAX1 allows us to control namespace prefix * mappings better than SAX2. *

    * * @author Kohsuke KAWAGUCHI */ public class RELAXNGWriter implements GrammarWriter, Context { protected XMLWriter writer = new XMLWriter(); public XMLWriter getWriter() { return writer; } public void setDocumentHandler( DocumentHandler handler ) { writer.setDocumentHandler(handler); } public void write( Grammar g ) throws SAXException { // find a namespace URI that can be used as default "ns" attribute. write(g,sniffDefaultNs(g.getTopLevel())); } /** * generates SAX2 events of the specified grammar. * * @param defaultNs * if specified, this namespace URI is used as "ns" attribute * of grammar element. Can be null. * * @exception IllegalArgumentException * If the given grammar is beyond the expressive power of TREX * (e.g., some RELAX NG grammar), then this exception is thrown. */ public void write( Grammar g, String _defaultNs ) throws SAXException { this.defaultNs = _defaultNs; this.grammar = g; // collect all reachable ElementExps and ReferenceExps. final Set nodes = new HashSet(); // ElementExps and ReferenceExps who are referenced more than once. final Set heads = new HashSet(); g.getTopLevel().visit( new ExpressionWalker(){ // ExpressionWalker class traverses expressions in depth-first order. // So this invokation traverses the all reachable expressions from // the top level expression. // Whenever visiting elements and RefExps, they are memorized // to identify head of islands. public void onElement( ElementExp exp ) { if(nodes.contains(exp)) { heads.add(exp); return; // prevent infinite recursion. } nodes.add(exp); super.onElement(exp); } public void onRef( ReferenceExp exp ) { if(nodes.contains(exp)) { heads.add(exp); return; // prevent infinite recursion. } nodes.add(exp); super.onRef(exp); } }); // now heads contain all expressions that work as heads of islands. // create (name->RefExp) map while resolving name conflicts // Map name2exp = new HashMap(); { int cnt=0; // use to name anonymous RefExp. Iterator itr = heads.iterator(); while( itr.hasNext() ) { Expression exp = (Expression)itr.next(); if( exp instanceof ReferenceExp ) { ReferenceExp rexp = (ReferenceExp)exp; if( rexp.name == null ) { // generate unique name while( name2exp.containsKey("anonymous"+cnt) ) cnt++; name2exp.put( "anonymous"+cnt, exp ); } else if( name2exp.containsKey(rexp.name) ) { // name conflict. try to add suffix. int i = 2; while( name2exp.containsKey(rexp.name+i) ) i++; name2exp.put( rexp.name+i, exp ); } else { // name of this RefExp can be directly used without modification. name2exp.put( rexp.name, exp ); } } else if( exp instanceof ElementExp ) { ElementExp eexp = (ElementExp)exp; NameClass nc = eexp.getNameClass(); if( nc instanceof SimpleNameClass && !name2exp.containsKey( ((SimpleNameClass)nc).localName ) ) name2exp.put( ((SimpleNameClass)nc).localName, exp ); else { // generate unique name while( name2exp.containsKey("element"+cnt) ) cnt++; name2exp.put( "element"+cnt, exp ); } } else throw new Error(); // assertion failed. // it must be ElementExp or ReferenceExp. } } // then reverse name2ref to ref2name exp2name = new HashMap(); { Iterator itr = name2exp.keySet().iterator(); while( itr.hasNext() ) { String name = (String)itr.next(); exp2name.put( name2exp.get(name), name ); } } nameClassWriter = createNameClassWriter(); // generates SAX events try { final DocumentHandler handler = writer.getDocumentHandler(); handler.setDocumentLocator( new LocatorImpl() ); handler.startDocument(); // to work around the bug of current serializer, // report xmlns declarations as attributes. if( defaultNs!=null ) writer.start("grammar",new String[]{ "ns",defaultNs, "xmlns",RELAXNGReader.RELAXNGNamespace, "datatypeLibrary", XSDVocabulary.XMLSchemaNamespace }); else writer.start("grammar", new String[]{ "xmlns",RELAXNGReader.RELAXNGNamespace, "datatypeLibrary", XSDVocabulary.XMLSchemaNamespace }); {// write start pattern. writer.start("start"); writeIsland( g.getTopLevel() ); writer.end("start"); } // write all named expressions Iterator itr = exp2name.keySet().iterator(); while( itr.hasNext() ) { Expression exp = (Expression)itr.next(); String name = (String)exp2name.get(exp); if( exp instanceof ReferenceExp ) exp = ((ReferenceExp)exp).exp; writer.start("define",new String[]{"name",name}); writeIsland( exp ); writer.end("define"); } writer.end("grammar"); handler.endDocument(); } catch( SAXRuntimeException sw ) { throw sw.e; } } /** * writes a bunch of expression into one tree. */ protected void writeIsland( Expression exp ) { // pattern writer will traverse the island and generates XML representation. if( exp instanceof ElementExp ) patternWriter.writeElement( (ElementExp)exp ); else patternWriter.visitUnary(exp); } /** Grammar object which we are writing. */ protected Grammar grammar; /** * map from ReferenceExp/ElementExp to its unique name. * "unique name" is used to write/reference this ReferenceExp. * ReferenceExps who are not in this list can be directly written into XML. */ protected Map exp2name; /** * sniffs namespace URI that can be used as default 'ns' attribute * from expression. * * find an element or attribute, then use its namespace URI. */ protected String sniffDefaultNs( Expression exp ) { return (String)exp.visit( new ExpressionVisitor(){ public Object onElement( ElementExp exp ) { return sniff(exp.getNameClass()); } public Object onAttribute( AttributeExp exp ) { return sniff(exp.nameClass); } protected String sniff(NameClass nc) { if( nc instanceof SimpleNameClass ) return ((SimpleNameClass)nc).namespaceURI; else return null; } public Object onChoice( ChoiceExp exp ) { return onBinExp(exp); } public Object onSequence( SequenceExp exp ) { return onBinExp(exp); } public Object onInterleave( InterleaveExp exp ) { return onBinExp(exp); } public Object onConcur( ConcurExp exp ) { return onBinExp(exp); } public Object onBinExp( BinaryExp exp ) { Object o = exp.exp1.visit(this); if(o==null) o = exp.exp2.visit(this); return o; } public Object onMixed( MixedExp exp ) { return exp.exp.visit(this); } public Object onOneOrMore( OneOrMoreExp exp ) { return exp.exp.visit(this); } public Object onRef( ReferenceExp exp ) { return exp.exp.visit(this); } public Object onOther( OtherExp exp ) { return exp.exp.visit(this); } public Object onNullSet() { return null; } public Object onEpsilon() { return null; } public Object onAnyString() { return null; } public Object onData( DataExp exp ) { return null; } public Object onValue( ValueExp exp ) { return null; } public Object onList( ListExp exp ) { return null; } }); } /** * namespace URI currently implied through "ns" attribute propagation. */ protected String defaultNs; public String getTargetNamespace() { return defaultNs; } public void writeNameClass( NameClass src ) { final String MAGIC = PossibleNamesCollector.MAGIC; Set names = PossibleNamesCollector.calc(src); // convert a name class to the canonical form. StringPair[] values = (StringPair[])names.toArray(new StringPair[names.size()]); Set uriset = new HashSet(); for( int i=0; i in the attribute. visitUnary(exp.exp); this.writer.end("attribute"); } protected void writeElement( ElementExp exp ) { NameClass nc = exp.getNameClass(); if( nc instanceof SimpleNameClass && ((SimpleNameClass)nc).namespaceURI.equals(defaultNs) ) // we can use name attribute to simplify output. this.writer.start("element",new String[]{"name", ((SimpleNameClass)nc).localName} ); else { this.writer.start("element"); writeNameClass(exp.getNameClass()); } visitUnary(simplify(exp.contentModel)); this.writer.end("element"); } /** * remove unnecessary ReferenceExp from content model. * this will sometimes makes content model smaller. */ public Expression simplify( Expression exp ) { return exp.visit( new ExpressionCloner(grammar.getPool()){ public Expression onRef( ReferenceExp exp ) { if( exp2name.containsKey(exp) ) // this ReferenceExp will be written as a named pattern. return exp; else // bind contents return exp.exp.visit(this); } public Expression onOther( OtherExp exp ) { return exp.exp.visit(this); } public Expression onElement( ElementExp exp ) { return exp; } public Expression onAttribute( AttributeExp exp ) { return exp; } }); } }; } msv-2009.1/msv/src/com/sun/msv/writer/relaxng/doc-files/0000755000175000017500000000000011622453166023233 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/writer/relaxng/doc-files/Island.gif0000644000175000017500000001073407363665466025160 0ustar giovannigiovanniGIF89atw÷ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ»>ÒFèMÿUÿl"ÿ‚Dÿ™fÿ°ˆÿƪÿÝÌ3"J1`@wOŽ^¤n»}ÒŒè›ÿªÿµ"ÿÁDÿÌfÿ׈ÿãªÿîÌ33GG\\pp……™™­­ÂÂÖÖëëÿÿÿÿ)ÿÿRÿÿzÿÿ£ÿÿÌ"31J@`Ow^Žn¤}»ŒÒ›èªÿµÿ"ÁÿDÌÿf×ÿˆãÿªîÿÌ3M"f+€3™<³DÌMæUÿhÿ|ÿ:ÿW£ÿu¶ÿ’Êÿ¯ÝÿÌ3PmЍÅâÿÿ3ÿ3MÿMfÿf€ÿ€™ÿ™³ÿ³ÌÿÌ3Mf"€+™3³<ÌDæMÿUÿh:ÿ|Wÿuÿ£’ÿ¶¯ÿÊÌÿÝ3"J1`@wOŽ^¤n»}ÒŒè›ÿª"ÿµDÿÁfÿ̈ÿתÿãÌÿî33MMff€€™™³³ÌÌææÿÿÿÿ:ÿÿWÿÿuÿÿ’ÿÿ¯ÿÿÌÿÿ3(P7mEŠT¨bÅqâ€ÿŒÿ3™ÿM¦ÿf³ÿ€¿ÿ™Ìÿ³ÙÿÌæÿ3Uw™»Ýÿÿ--ÿDDÿ[[ÿqqÿˆˆÿŸŸÿµµÿÌÌÿ3&M3f@€M™Y³fÌsæ€ÿŽÿ:ÿ«WÿºuÿÈ’ÿׯÿæÌÿ33MMff€€™™³³ÌÌææÿÿÿÿÿ:ÿÿWÿÿuÿÿ’ÿÿ¯ÿÿÌÿ3M&f3€@™M³YÌfæsÿ€ÿŽÿ:ÿW«ÿuºÿ’Èÿ¯×ÿÌæ!ù,tw@þH° Áƒ*\Ȱ¡Ã‡#JœH±¢Å‹3jÜȱ£Ç CŠI²¤É“(Sª\©€Ë—0cʌɲ¦Í›8sŠ|©s¤Ëž@ƒ *ð'Ñ£E ]Ê´é̦P*êÔhH˜gjÝú”ªWŽS¿v´*V@×\Ór-Ëvl[…aßNTKW¦Ü»ãFÕ‹7iĺ€É.äÛ·0AÂ:þ¨W±ÏÅoŸ”,”òΊ–Af†Üss^¦ž=†¦wôEÓœM¢–¸º°ÑÖyi¦žÝ6CÛ`SÚe‰û°hÚ7{#N:·ñÇÇ÷%n¹Ôßɯº-y–j`­Ÿ/£tnv:òì$¹þ·L›ôzõÓªÛ2_<(û–·ÍËN˜ù=ýÔö5ͼ7aþµÉµhæ NçýU”S_Ê݇™ƒ>5ƘwÚ÷]„r¨ †ñ·ž‡QèÛ`$^ø Š ¢…YŠíÁø¡Œ*!f¢nJ `w.ÒhÑ$ZècŒC‰à‹F6—ä’ÔmG#LeVû%ˆ×”QV¸ YSýT–šÉǃY–É™˜cnÙ™™l⇦e‚Ùæœ鸘wBGçž§ÉœžGùYYƒs:GÙc†•#V<–×åk¯9ªf£|Vª –šé¦œv:Û›kyz磓ŠZ¨Ø¡X"—Цé*£*¦ÆZªVÊjë­¸æjäf‚êê+o-þ*ì™+ÖI©…¥;ì²M²Æì³Tþ$@à@‚ D˜PáB† >„QâDŠ-^ĘQãFŽ=~RäH’%MžD™RåJ‚\²œèò%Lš5mÞ¬9çM;}þJ@Ë Ec5šT)P™2—>͈*ÌžLJ-ØTëV®]±NûñkX‰cÉô*ÐëZ¶fϾÝè6¬\¸‘¶ÅËUm]¾éúüÛ—b^ÂUc F|õgࢌA2v,61ßÈ’'?ö{Y3æ“•Uzæ£Þ”¢7—415⮥ ç{°ÈÕ™G¿Æ‹Ú¶ÇÚ²£†ì}1øÀáÄu‡NØÚ÷ÔâŠ?óÞM;:ó­&qWר<9åé9—‹uŠðþºVçvK/×ný{v»ãà ÷.XyÒ´;Ó3%_ñëýßoßCý'þ”êͰ§ ÌŠ³Ø„êNÁõ¶{°,k:䜪ã[p$í¤špCõĸ O¤p¡ÈtM(5{±D†bDOFÁ ŒÆ¾t´‘G¸>¼­ ‡DÉGñ°óÍH"ãRRHùš4qI)7t/D§Är²« Ê,¿ìp=+´L3‹,1=/Ï|hMýܤ¯LóŒ`¨»ˆO¢ŒÃÊÎ=Ù´ Î¥Ô´PC=TÐ:ͪÊú­kLHýrt¾I/-´RKÛÔ3Á½úÄ4T5ERTSOE5UD TµÕ%<ÌSÕ\¥•%V9M0¼»œµÎ—­5X_›¶ØËþ p Á‚"L¨p!ÆBŒ(q"ÅŠ/b̨q#ÇŽ?‚ )r$É’&O¢L©r%Ë–._ÂŒ)s&Íš6oâÌ ÏžTúä©s(Ñ¢F =º0©Ò¦NŸNd õ¢Ô©V¯Öü‰•dÕ­^¿jÔ Öe×±f¿=‹S¬Ú¶Jƒút›³¬\”pÞ=Ú³.T¶|©Òµë/܆ÿõ:8±ÁÀk¦Ezx2eÆ`»Åüvò@Êž [>«ùêh³ŸOݶ´QÖrQÃV¹/cͰQ#t-»¨î˜½7S¼}Z¢Öß»_·{\¡ðÏËù&ý¹í–ÓŸ¼ÎQ;KÇÒ#r·þ;ÆñÁÉ7oþ<ú”ë!¾é]d|‚õá·?y?áþ­ýùï•ßXÿÙ' q”€ x`T‚HS„ ’Fßrˆ)·…sÉ·Û„Öuäà†vè[Fñ9ˆ"ƒ#RU¢b!–ô^\Ù±ÈhÁÈUŽâåÕYĹˆ•Š:jHdz=úÖÜŒ'~'äŽ)Zj~Ø™’UVÔ “QÒw%†Øy‰›YÆhÒ~CÊ$"xD¦yj @`nN™æÄ…™Cp 4çNOñùP Ì—§ ¹‘åÑ HÊâœó‘øgXÖ!9W¥`rui¤3…·hŸXZ êq".ÙâPÓygªÁAªZ Ü­þ ä¡7n”â“-z]¬åñ‰&”µÞ ìšjµº)“FNl²„y¨)·®Èem‰ê©,£ÒF ì}»r¸¡zÐҺ옦¶¶·««hº}Z;lœÞ’‰m¸ÇîÙ.¡çÚûZ®×ï§„æ0žãÛT±K¦lÁo9+¼ 7±¬í-,1oMŽjñžB&ꀘ䗢,_ÅûžŒ`©/–Lò»Bz©WË3+3›4ã–›§æÜ³ÎW"h¢ÏCçæš¡›I´Ò¼ׯKC}1½QS-³±ú®[µÃV/塺Z[Ɩǡ՗2ØA†œ5»(dª÷ò’m ÕoR›íÙò ’‹_Äqûèö³¿Ì®ØdçÝnÙzÓœøÚ5.¾·x¾xû÷¡‚(Ûú»î¿–ì)Á¥ Üï@‘Z«—{Ð% gÂpB k³ðÂÝòë1åãO =ŒE÷¶Ñ1ÓKHÄ?Zñ$ KÆid1¾ 1Ú‘ÇÌz¼GŽôn#!{3²È΀K*ÉäLÔîIkšR¥üÔ: Â+ãÊ=Ò’J0eK5øÌ|¨Í5_z3+ åDÊ/üp5=í<ÏÉ´ŠO;댳6 -³Ï𬤬ÐDMóFý}îD.#u²$H÷üS2òDâT0NEªÔK±ËÔÒU£ôqºTUþEÒ<¾@]¬ÖP‹|”Ö&iÂ4Ö3C:•¡SK¯ OÞðÆ½’IØ£]h™d^Çî³Ï}֊—që¡uÎ9}¸4,¿`Øš^[~ÏïR÷=¦ç^]ùñ÷rÿZ'2þÅí.Ùòß«§? P|ì+ª¼Ç¨ù©Ï_sùܰÞ3,öLp«yTø ˜«üQЃ„3Ình¾u0€šJa•"ô©|gad”6BÖÐ[ÉêañtþÈ@JpWÓ›k*¸Cnï‡£Ñ a¨Ä*a+ÁÚÜeÚ>Hiñn’ÃâO¦R«‰öÒycFÈŒ±UpclبÆÑnrü ?GœDŽal«÷µ5Úñ-Ø{ !-8D"?0»ã“øXE¹I‹PÏÜ¥(¹¨HÚ­sò:×&©µÑUÌŒ ´ß….ÇF–…0­óä*“=@¢J•°¼—³fÕÍ–™Q‚6“KÀìÒ'Âì%æh–§c–-™”Z&3„¸g Ç2+Ÿ1§yA5“jd˦ÍÇÍÔ-\7¯UÎpÓzê4€ÎyIwZ(žeTàȦ´jèPÉyÆ‹²ª•*V×ç¨â3z]«4ÏšVµ®µ˜t|çXKŠ?çpѬH¼*áÊV!Ú‡®z%Jëj½¼ú£ƒ%l) ;;àÖ5‰¥âb{BÇŽ“~rªe)YÉj‘~›ó)Y.«ÙÍ‚ï±Jm*S++ÚNVµ„bmkÅøZ-ØBR¶³MVmm›[Ýî–·÷ lo„ÂßwLS%nŸzÜLÙh¸Êmc«€®8`A &T˜áB‡!F”8‘bE‹1fÔ¸‘cG‚ü( $Å’#Q¦T¹’eK—/I¢<©qfÄš0qæÔ¹“gOƒ71-8aÉ“EC%(ÔgS§O¡F]:’©Ã†®Īt ׃RÁ†;¶eU‰f¿êÕk̤hÉÆ•;—,Ü…véæÕ»—ïG¼Sû<˜pP» 'V¼XîÖŸXG–<™reË—1C ;msv-2009.1/msv/src/com/sun/msv/writer/relaxng/doc-files/Island_Merged.gif0000644000175000017500000000646007363665466026444 0ustar giovannigiovanniGIF89a+L÷ÿÿÿÿÿÿÿÿÿÿÿÿÿÌÌ3J` w(Ž/¤7»>ÒFèMÿUÿl"ÿ‚Dÿ™fÿ°ˆÿƪÿÝÌ3"J1`@wOŽ^¤n»}ÒŒè›ÿªÿµ"ÿÁDÿÌfÿ׈ÿãªÿîÌ33GG\\pp……™™­­ÂÂÖÖëëÿÿÿÿ)ÿÿRÿÿzÿÿ£ÿÿÌ"31J@`Ow^Žn¤}»ŒÒ›èªÿµÿ"ÁÿDÌÿf×ÿˆãÿªîÿÌ3M"f+€3™<³DÌMæUÿhÿ|ÿ:ÿW£ÿu¶ÿ’Êÿ¯ÝÿÌ3PmЍÅâÿÿ3ÿ3MÿMfÿf€ÿ€™ÿ™³ÿ³ÌÿÌ3Mf"€+™3³<ÌDæMÿUÿh:ÿ|Wÿuÿ£’ÿ¶¯ÿÊÌÿÝ3"J1`@wOŽ^¤n»}ÒŒè›ÿª"ÿµDÿÁfÿ̈ÿתÿãÌÿî33MMff€€™™³³ÌÌææÿÿÿÿ:ÿÿWÿÿuÿÿ’ÿÿ¯ÿÿÌÿÿ3(P7mEŠT¨bÅqâ€ÿŒÿ3™ÿM¦ÿf³ÿ€¿ÿ™Ìÿ³ÙÿÌæÿ3Uw™»Ýÿÿ--ÿDDÿ[[ÿqqÿˆˆÿŸŸÿµµÿÌÌÿ3&M3f@€M™Y³fÌsæ€ÿŽÿ:ÿ«WÿºuÿÈ’ÿׯÿæÌÿ33MMff€€™™³³ÌÌææÿÿÿÿÿ:ÿÿWÿÿuÿÿ’ÿÿ¯ÿÿÌÿ3M&f3€@™M³YÌfæsÿ€ÿŽÿ:ÿW«ÿuºÿ’Èÿ¯×ÿÌæ!ù,+L@þH° Áƒ*\Ȱ¡Ã‡#JœH±¢Å‹3jÜȱ£Ç CŠI²¤É“ \ɲ¥Ë—0SÆœI³¦Í›UâÜɳ§O: J´hТH“*}yt©Ó§P3˜JujÔ«X³6lªµ«×¯«ŠM©RìX°hÓJäºu¬Y«oתK×hÝ»(Ùâ »ÔmUo©î½«×aáV ÿøpAÇ_!óäjVaÙ‰’!fVܸsâÈ•nÎ ytNŒ¦L=“µj¾§º¦;;ïk©,k×.¹;äçÛ{G¤,úñd‚')\¦a‹’›w¼ðÏ˨US÷*bw“ßkŽn9:nëðÐou‰žyõ횎–¾õ÷²g«ïI1þ–èÙ`}ÿ=”Z›%¶xÂw‘€IµŸy :'W…´U÷W[ bH˜‡ ‚Øa„žyâ‰A(U‰Ý‡â‹±‰”‹-Âh£f*xãŽ)"$„9òÈãYÓ idŠAfwä’L6©U’=:)%{P*þ 4xaB… 6tøbD‰)V´xcF9vôødH‘#I–4yr ”+Y¶tù¦•1iÖ´ygÁ™9yöôù3ãN C‰-*ÔhR¥K]ªð)S©S©V„µjV­['^õú,V®cÉŽ aØ„N˶uë1lܯoéÖµKVnÞ§wùö}¸Wæ\µjû¥©X™>SÔ›×1и‰bElð¬Eņn®\ÕóÂÐ6æ úôÅÄ&Cî9&ìÔ eo¼\ú3ÈÖkcÏ–ˆíÁÚK¡vnóxSÉuúÆÌ\¹óæÒE›¦Î:î™Ð7g·[›ðuyÌVu‹'íÜ»hÞæÙçL¿>éí˜ïÕ·Ÿn›«bëGíSj˜¾ÿ¬’‹½ì즥 ¶¹|k?¾dSðA¦(¬C lÁ +Œ°&;LÉÃ{IÄàp3ÑÄ çcF’\/ÆgéÆ¿ËQ#uüÈ [ò‘%€þH° Áƒ*\Ȱ¡Ã‡#JœH±¢Å‹3jÜȱ£Ç CŠI²¤É“(Sª\ɲ¥Ë—0cÊœIS €š8sêÜ™ñ&ÏŸ@ƒõ)´¨Ñ£,‰"]Ê´)G¥N£Jª*Õ«XZÍʵ+Э^Ê• v¬Ù³(Ë¢]ËÖ£Ú¶pãJ@·î[¹xó´KW¯ß¿ ëL¸!ßÈù^<5ñ;Žï2žLjbv1_î‹™²g•’"Öœù²ÃПSäL1²kÖªcã|íZ¶íЍµÞÞM57ïßÀEÓv¬ÚwËá‘#OZú0iç”—»”ns"õžDÁ*Þ<¡ÏëMÁ'þ5h90n“Ë|=÷+l´Vã{ß S¼MäÝOâßÏßþlòêÍCþwdÒ7`\ .RƒkAèà„x½%!… ¸ÚS]˜¡†Km¡|§}¨_ˆe täu&Wm yØ•…‘h؆5'ØŠïÝXœ[w(T=–$#|vøÐ‘9“æ…×›H;¶ø”7憥‘­9IàQ[F)U˜‰è¥’!>i™iÖ×ß›Ã}ùäzß}WUtîM–h&¦äJñ±ÙgGur N‚Z7èzTæH‰î$a¤êéS6.úS‚”6z&š\Þæ_§5Võ€:(©F²ºQ€ŒéXaTÄ&«9AgaVé"`,š¬¦)}:Ö°eFìœ +ܲ<á mpÎNk­¢½Á)íµm«œ¶ÜŽé­°o†›Õ¸{« ¹Í¦®˜ìju!jÚ¢o£Ù{/WÆé»¯XŸøž¿ÿÒä!ÁÕ Â ÕðÃG,ñÄïë-ÃϘñµoÌF{l"@þ$XÐàA„ .dØÐáCˆ%N¤XÑâEŒ5näØÑãG!EŽ$YÒäI”)U®dÙÒåK˜1eΤYÓæMœ9uîäÙÓçO A…%ZÔèQŠ.eÚ´ R§Q¥…:ÕêÕœU±nåúRkW°aK~[ÖìF²gÕ®˜–í[¸ÝÆ¥ wn]¼gïæå vo_ÀWÿ&ìtpaÄG'fLµñcÃ%#]<ÙrÍÊ—5Ã̼ÙóÊΟE›¬ ôhÔM¯NÝúäjئ]Ï&û4mÜcçævoàe'^ÛöqäÅ• @ÞÜöòâÎ:¿ }rsæJ¥[Ï-;ùoìÜEþ—{<»÷äOÅ?&ŸÐüóô «¯ ÿýsÝôÙ†¦Þâ|ýÂê:‹ ð&ÏÐ<Œ<Ð¥ö\0¾´ðB 3ÄÉÁŸ8Ôð"?ñ³ )$,D£Pô­DüF¼l·§,LŪ£Ñ+ðìc0°…+P¢5Úí»]\ˆ¬å²jÈû’d®® }T ¹n‹²"&³t¡+7‹ðÉîê2%-¡ÚΡ1!ìJƒ¾ªrºÿ²bƶvÚ’)$ÛÔSI6—š“Î8”Ñ=¾ sÏC¹T´¡4uû“µ it*$­£G!ê7 ‹ª4Ò¤Œœi±Oyk”®L5etÑ:Ë:52®þ^µLVǦ•(ZÑϧ\áô”¡^oU,Ñëxê5XvX_I*Õ&eùTS*íÐúqÙ_ÁDTÈ6‹ìsÙh!3O] ͪXã¶µt¿I1ªZB%$vÞuá…vEY%Dr¿ÖÕöîÜðÝß´õ_ie²r/UóÛ·Ækãªá‘½×Њ#–Ø+.1îÊbu^·ÜPƒ¢˜³ SõXdã@õb’;ÙNŽÅ qfzÍݯS?%ÌÌe¼Ì”’Ò•±õ7P<ôè‘[R1J¦Ñ,Z%œge¹Õ¦¦æØðúÒŽamNÖË3~™6¨ÿã³\Ã5Øä‡©¾—½¨­Ei0¡Yª;äþÑ´Õh´Ïev9K«{ï»ß"ÕLƧûºÙù6 qg}«pÕÆv­GÊ/º'7çΘ¯› s,?ÿ°s½3ÏåYŸ6#Ù%÷ü@k·]ó Ô½õÛ­‘ÇÓy÷òo›¥þ=q¡ë¬ë ›Î^µóݹdvÇÊKÇUL9çtù±«Ó[ÒÏå·¾Ûî'ß絕®õ«¼ß½ýñ/O­þ•ÇoþƒœX8@| LÊüˆ n.‚©Aàe†§TYÐnžÊ Ñ¢;•yPu ë G(¨:p ÓJM8:Ž!©„/„áÝÄ4CVìJxÃaþrø={õP_?DíÄ%D"ŽÅwmAbƒG-'ž0Š€© è¦1„}Ð|W<[åjÈEÕ„nƒ`|¦žHFã ^£ëÖ˜F^½QŽÀ© çxGÁ­ {äc¥')?2p‚ ÙyH ÚQ„UD")U@G *’“Sßp9I¡;msv-2009.1/msv/src/com/sun/msv/writer/relaxng/doc-files/Island_Before.gif0000644000175000017500000000572507363665466026446 0ustar giovannigiovanniGIF89a$÷ÿ::ÿWWÿuuÿ’’ÿ¯¯ÿÌÌ3J` w(Ž/¤7»>ÒFèMÿUÿl"ÿ‚Dÿ™fÿ°ˆÿƪÿÝÌ3"J1`@wOŽ^¤n»}ÒŒè›ÿªÿµ"ÿÁDÿÌfÿ׈ÿãªÿîÌ33GG\\pp……™™­­ÂÂÖÖëëÿÿÿÿ)ÿÿRÿÿzÿÿ£ÿÿÌ"31J@`Ow^Žn¤}»ŒÒ›èªÿµÿ"ÁÿDÌÿf×ÿˆãÿªîÿÌ3M"f+€3™<³DÌMæUÿhÿ|ÿ:ÿW£ÿu¶ÿ’Êÿ¯ÝÿÌ3PmЍÅâÿÿ3ÿ3MÿMfÿf€ÿ€™ÿ™³ÿ³ÌÿÌ3Mf"€+™3³<ÌDæMÿUÿh:ÿ|Wÿuÿ£’ÿ¶¯ÿÊÌÿÝ3"J1`@wOŽ^¤n»}ÒŒè›ÿª"ÿµDÿÁfÿ̈ÿתÿãÌÿî33MMff€€™™³³ÌÌææÿÿÿÿ:ÿÿWÿÿuÿÿ’ÿÿ¯ÿÿÌÿÿ3(P7mEŠT¨bÅqâ€ÿŒÿ3™ÿM¦ÿf³ÿ€¿ÿ™Ìÿ³ÙÿÌæÿ3Uw™»Ýÿÿ--ÿDDÿ[[ÿqqÿˆˆÿŸŸÿµµÿÌÌÿ3&M3f@€M™Y³fÌsæ€ÿŽÿ:ÿ«WÿºuÿÈ’ÿׯÿæÌÿ33MMff€€™™³³ÌÌææÿÿÿÿÿ:ÿÿWÿÿuÿÿ’ÿÿ¯ÿÿÌÿ3M&f3€@™M³YÌfæsÿ€ÿŽÿ:ÿW«ÿuºÿ’Èÿ¯×ÿÿÿ!ù,$@þÿ H° Áƒ*\Ȱ¡Ã‡#JœH±¢Å‹3jÜȱ£Ç CЉɓ(Sª\ɲdË—0cʜ钦͛8s®4©³§ÏŸ@!ò J´¨ÑœC*]Ê”äPI›JJ•!Ô«U³jݪðª×¯`Árµ¶¬Ù±UͪýZ0*Ú„kã&uû¨Üµ 鎽«6o]‘Pÿ¦Ô+¸0ǹ†=ŠMl“pPÇÏ.„ì“2㬖/WÌ<¯CΚ%‚}r4鯅ùJm4ð?צ»†m2viÕa/ÛŽüv·Jܹárõ‘øLã¬O—Ö‰|ðïÍÓ–ýútÀ‡•Ãź´:YîÚÃ`S'èZ|kÏ/îÎö¢úö ½o®Lþ=ø×šçÚ/ß’ÿ|ÌûY&Rúe^D’–àÎA‡Ð‚4y!ƒÂ5%àzÙ15!…Nõ´!‡ †(b]Î6"J´ ”â‰*ò”¢þôOà@‚ D˜PáB† >„QâDŠ-^ĘQãFŽ=~RäÈHžD™RåJ–M¶„SæLš_ÖÄ™SçN•7yþT¨CŸCEš³hR¦MvUªÔ§U­^¥¸ëV®]NVlT¯Çž[+Z¶TÕNlÛö­Ò¹+µÖÅëñåÝ·|%õ›—e`¸ ¯å¸ô°`ÆYA¦%êt±Ú© '7Æ,xoå¿8/ïü2´d™d]f6<Ú0͸l!ªÆ õÈÖh ÊŠÛqWÝ'×>ÛsÕÞ¯g÷ Zœ6qÈÇÃ"Užñùq†ÑIZ<;uî"›ÏÝnSMúoòÀ§#6kþ<åŸ~Õ¯Ïëþ=g ¦M'ý<Ÿ~Ùüúïw‡ª$°PÃn@SRN«ðèJì@?ë1Ҟ̘/eÊ‘[^žÜxóâÌ$+÷õü٠ܧ¢’.]ð4è rW+.{Z6ä×)m#î¬Û5n¦¾_ÿsxfãk‘O=üQyHçBJ\#këd©N^ý¢×í­Ù¦þfy›mdðb{“îÎ,úö ß”o¾+ÜÙ é7ªŸcŸ×-õŸ[æ¤Ýt¦5|%¸’ƒš-È`_6Ih—a^˜žzA¨”‡¿©—axÕxœˆÿ˜H^n[©¸œi(r§•‹ªUEc ‰x£J;â1¾ˆZ…ž÷#N=F”dOKvøS“–$”0ˆäMV(%Q»e—:5…Ÿ^ލåKƒ…6á}jQ)äšy•™bMÅ™x–YžE:v'çhÎõ‰væ §u:V¢Šò©OšŒ’žä¦”±IV9jšÔ¥2Îäéœ Žz¨—§¦˜*–©‚úUVôC¹º_˜«FI¢Ÿ[Öº©jÿÉŠè­ØéŠ$£˜ kìC‹*g>Y¢³ÐBªì´´RkíµÞ™ä+F n›·O'¸Øê þÐ? 4xaB… 6tøbD‰)V´xcF9vôødH‘#I–4yeJ•+Y¶tùfL™3iÖ´ygN;yöôùhP¡C‰öPiR¥ .uúiS¨S©î”ZkV™Wµvõz’ëW±c=†%{íD³iÙ¶eên܃kåÖEK×n^¯xõö­Ê×oà§€.JØpâ ˆ7¶êrÔÈ“S¶ì“ñeÍ*3oöl²ógÑ C6ͱôiÕ›p½öG׳_Ƕ‘6íÛ»/æN͸@ÝÁ‰«ý]ù@ß˙ϖÛzîä£W?>Ø:ôés³7ÞùvþƒàÃÇ%¿\¼òóèÝ®g?ýª{Ý­ÇÆ—ÿúºèûµáîçš¿0¼ü£n*÷#°¸ßÚëÀyS°¿cc Bª(”0½*dÀ›6tP±Û˰>D$‘§Ë2Ê0…s1'}C‘5áVÔ꿎øË ÆøºRÑGÕ"ÈEgÊñF½€ïGÔ˜Ò¡µ–Ä Iû2r¨£„ò®²¢+ðJ¡vÜèK1ã’¦áÐ$ KÒ<ü©M¥â\³­1³4‘Å´¤[hν ,NÐÈòî¡>#2”L›MSËC=[4Lõ MÒ²Ia²T$L¡Ò´¥>9ìS–&52T9Ù*µFT%«3F¾:TUþGm<ÃB•DñC>ƒµÎZÍô‹×»| ²`¿òÏ9?Q2¶F¥Êõ/Î6Ut¼a™mVÚ¥P5ð>±8½ÖV—ƒÖÂKWµjØ'Ï÷0Q!"Ì­î̶Ðt‰m7ÍÊxÄ7_8uôÍ“M£668¦FC:ñá”Ôô÷Ò“9vN;×eJQöx]QKnìf];=X_ârþwZ cNêç EN)ëd³·&í0‚7BBcí(Œ)‚zÈ%JXe㨳뭙V2Ù„ÂNúk¢Ê¾zì [M»W¸-67Å‹^ºÛ»©¬ÆUoÜ0ì[禹“{Ör«%œTO³dp± W®áÅw 1¬A ­ä '75ʶ93ð/Ï ·Pt ‹}hÊQoÑtÍß7õ5ú¯È€g¯Ò6ïu²ßÙc¼ )©üý×Ñq<ÑŽsßݱ×ùõûlßßÛ©©'~%§Ÿ‹´jn)æ{=£ïòÊ¢ýÙùðÕïYÑ›Ó/éý—âz~wO§væ#×ßÿ¶úí_={ÚòŸyxf8þodÞRp®·¥S½Š Ìø”€;msv-2009.1/msv/src/com/sun/msv/writer/relaxng/doc-files/simpleAGM.gif0000644000175000017500000001217207363665466025562 0ustar giovannigiovanniGIF89aò3÷ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿŽ^¤n»}ÒŒè›ÿªÿµ"ÿÁDÿÌfÿ׈ÿãªÿîÌ33GG\\pp……™™­­ÂÂÖÖëëÿÿÿÿ)ÿÿRÿÿzÿÿ£ÿÿÌ"31J@`Ow^Žn¤}»ŒÒ›èªÿµÿ"ÁÿDÌÿf×ÿˆãÿªîÿÌ3M"f+€3™<³DÌMæUÿhÿ|ÿ:ÿW£ÿu¶ÿ’Êÿ¯ÝÿÌ3PmЍÅâÿÿ3ÿ3MÿMfÿf€ÿ€™ÿ™³ÿ³ÌÿÌ3Mf"€+™3³<ÌDæMÿUÿh:ÿ|Wÿuÿ£’ÿ¶¯ÿÊÌÿÝ3"J1`@wOŽ^¤n»}ÒŒè›ÿª"ÿµDÿÁfÿ̈ÿתÿãÌÿî33MMff€€™™³³ÌÌææÿÿÿÿ:ÿÿWÿÿuÿÿ’ÿÿ¯ÿÿÌÿÿ3(P7mEŠT¨bÅqâ€ÿŒÿ3™ÿM¦ÿf³ÿ€¿ÿ™Ìÿ³ÙÿÌæÿ3Uw™»Ýÿÿ--ÿDDÿ[[ÿqqÿˆˆÿŸŸÿµµÿÌÌÿ3&M3f@€M™Y³fÌsæ€ÿŽÿ:ÿ«WÿºuÿÈ’ÿׯÿæÌÿ33MMff€€™™³³ÌÌææÿÿÿÿÿ:ÿÿWÿÿuÿÿ’ÿÿ¯ÿÿÌÿ3M&f3€@™M³YÌfæsÿ€ÿŽÿ:ÿW«ÿuºÿ’Èÿ¯×ÿÌæ!ù,ò3@þH° Áƒ*\Ȱ¡Ã‡#JœH±¢Å‹3jÜȱ£ÇˆI²¤É“(Sª\Ë—0cÊ„ ²¦Í›8sêÜÉÓâÌŸ@iºl)P$Á H“¢ìÉ´©Ó§P£êTJµªÕ«W¥jÝʵ«×¯` K¶¬Ù³hÓª8v­Û·pãÊ›±-Ý»xóêÝÛÕ.ß¿€ Ü$áÈÆÊ¸±ãÇFG„L¹²å—’‹2>jÔpç–ž‡‚éR4hÓ£;Tý¹uJÍŽ3CÜ<´çѦKÛ¶;µëÒYûF½²ìËÈ“#—Íù$låУWe®×ï\É­ÖN½»Ó¥yKþîå¾¼÷óOIgOKžºzôrÛÃÏ)?aý›÷1æŸrÿøŽ~\mxTQ®\[íÅ pX~Mù·F¨›‚ Že€Úw ‡zd!_‘ñ7Õ‰“QÄ"~/ª(QŠ2¾#sÖh¢Ž<~dR†d]?i¤O5ÞXâ‘)ÉäWN.¥†{%§-~˜e}Ù~ë.N,戮¡¼å6*„FÈÛ$¢kßnïúP»ïì£',®Ázþ@ À D˜PáB† >„Qâĉ-^ĘQãFŽ=~RäH’%MžD™RåJ•]¾„À Ì‚2i¸ Sç΃,}þTèP¢E½ÈSéR¦M›"…UêTªU­^ÅšgV®]½~VìX¤[ÉžE›VíZ¶mKšuWî\ºuí®„{Wï^¾}ývUøWð`Â… Ì{XñbÆ‚Öè0çãÀI]ÚÄÙ³fæ¥I>¶(™rCŒ/1O¦‰Y©g‚ 5Ã932gÈ­s¦ž:1m›ºÞÍúãhÚœ}ßÔ};÷ë乓"Ïq²SáÄ­_Ç~Y¸oÙ­³~þ{ßÄw:Þ^~üú¬«_ ß³{ö~ÃßÇ_1¥ü«üæ0Àóê#è¿Ò¼Ûê5³zR-ÁØ,7Ž\°;Oò/¨ Yڤݱ;%Ô ÂÓ,Ô 9ï"ªCûs±? }бÅÅj¬ GÁÒ±ºáv$ªG ‡|«2";ªíH ~S²I “<2F!œmJ*Ó²²°,ß Ò®-ûòÊ[2ñ´È̬òÁÇd¥0ŸÌ-!‹Û,´Þ"t¶;¬sÍ=7|óÊ@ÉûlPª ÝJDÇ[TLB±jÔSåÝvÞMç}2[~ÿ…àD&8½RŸKÐN=õTØ3V˜¾ÌÚôÏz+8ãù4þŒãÂþ P`€‚"L¨p!ÆBŒ(qâÄ/b̨q#ÇŽ?‚ )r$É’&O¢L©r¥JŠ._ÂŒ)sæC–6oâÌ©s'Ïž>^¤)ÔåÀ‚EXª”(ЦNŸB*uêÉ¥V0˜Õ(R­W¿2¤*v,Ù²fÏr«¶æÚ¶ÑÂ+w.Ý’nïâÍk´.ß¾~ÿ®‹40á†#Nls°âÆŽCŽ—±äÊ–/cÎ<’²æÎž?ƒ>Ì94éÒ¦OGz5ëÖ®Eª~-{6íÓ±kãέ[ñÂݾ÷›08ñâÆÉj=®|ùc½ÎŸ[Õ }:õ—¥«cÏîPºöîÞ¯G÷ºþ— åò]·&=OÞ|ú­Ýg¿>,ׯܕÂON>iû®ìë‡ÞQî‰w€Û¸x ŠG`ƒÃ%XW:èß[þXá…F—[xõiˆ„&߆ï)d"‡ŽhiÞeÇât¯µ#t2Þø¢;ΈZoóñ¤[Ì•u[aã…ÆžeFi“„ —Ù“’MÙ¤‡?6†¥cU6–•N¾…—tYYŠ_÷žge"'[˜h*Çf–‚IçXr¢‰'Agé¹™~®Ö'Fòt š~V¦z(õ)(£M9zŠ…J`H"ºR¤GâDhyòº¨‰ü…¦zŸ¦µgQ ²Ê’£›zþ+H²zÊ€«~Šª¡ÉJªF¨âJéu7ša¨« ,‰îùæF»Vª¬²"+­Χê±Éúºì¢2ùæ¤;QX¹q’ÛŸštnbB TŠ ¯½±Û&q·¹;[¿ùЉn«WKðngw«Á@"¹0m‡^«ÁÎ:\[ÃnV•¯¥Y'U?ʛǻû/¤©ýdrO*#Æ2šzk®­Î<¨|ãEª2È@¹L, ¾Ž¬ÐÍÊ”­ª°ÄoÊYÍÍÒ|´Í‰1±=Ãö½C-â€Ow­mØBÛÖ¬m.£iÃ<ÛZs<0Ʊî,2Zo §1ÞqþKÛñÈ_îÍ7ÏlÞWá.¸S.'>ÂÌ5®øSÿFW”€Kîc§¾mleå™§&èç8Þ;$• ·Ææè£›ÅzÛ¨£=ëd¯ãŠ3¯Ùrk4ÔÛõ™ë°O[å9ÛÌ5¦UËÝkÁV¿¼›T·Þ\N¿Ÿì¼k‰îM½XÚÏk} ÏBœï̽÷>Ÿ¿üou§?§õZg~û—¾O1‘ìÏÏ—ükâßdÿù¯Ë{û“å2ÀéyÈGdZê e?¤É eÏ+`õbG.l/l¢2Ù'GÁͽì‚(RÓí°·—²õ-~¼Ïøš‡›ÞmE¬ÔÿøWºçäÉKlá {h—Wq&>"úHÄ#ª«wÕ2íšÈ¬ôLSúÁ`·Tô¤:‘$0DbšÚe4èAMwbS•Ò6È*Q‘ yU›¹èÆ6Ò.{œ'qãÇ‘o›œys祗?—>úÝèÕ±g×¾ôúvïßÁìþž|yóÇŸW¿þ|zöïágwŸ~ýäóíç×ßÿ~ÿÿ¡PÀWëÀ¬ËÀl»ÙŒPB¥ œÐ ™* à 9¤IÃA 1#¾D,ÑĈÖ:QÅZÅEËMÆÔœ›ÑFÏv»QÇÆjÜÑG¹jCM ý²Œ¤¾Bkî´!‰\ÌÈ#*Ǩ㊲'U‹R­½°ì©Ç§ª<©KǤԒ1'“ ’JÆàÚR±"Ý„³H ¡|I&£T O̘[óÍ6ÿ¬3NÅðDòL4Mº3L+Ç”Ê6ÄÞïÏ‚ò4(ODI$èR(#ÝTÌFíªA-Õ’Ò·N­óCM± TOÁþ|ÔO3ÙìÔP@q¥sÎDiíTL_c½oÖAiÍÕÖK =ÖÎ^aåU/Y›ŒëU•;4Z2uƒöÚmîSnÁõRÛpÉ]‰¿”*W]=Ç]×Ý}K4ÝwéuQ³zñ·PMñuF{'ƒ×5€#F² FøÈÛ‚ö;_ÿDÀª(p8sÓßíÄ@•I6]ãÛÕæ ¾ˆ‚HkHc¶4§Mxô¡?(„œ4,Da‹¶S¾ª½c&£Î×Ã..ІÒñ}ÐþµÃÛÁ¬GÀ3aÍ„8Àž) †õ!b„öíˆVƒâT¬Hœ„¹g\¼¢ãöÀ÷€ˆýU•G33:Eƒ5B ÖȘB&î'Ž, Ùê(¾9êGiÖkâkžh@›HQ}BCQ;³ÄâÐqDËë‰8IHRrˆÄ ÜÒgÆ• e~ŒdŠ*µ'QN¯}¡”#iĺ1®läûÐßZ¹ÈÄ10±DÏ$éW?]®rzÝ{eæl©GT¦1–¼ œä67>RP<'¬å2©ˆÌøMówǤ¤ödøÇjÄ“£üä7÷D(WZr“ÜÌ`Y †3uŠSN¸ŒÝÂàɼq2˜& ÿxòþLhpÜa&#÷xH™‰EŸ;)è@ ȉ©ÌU£ç¹dGΓ14¡9¼"1ÑØ§1^´wŒ{z!†”tê!)‡üwRõ‡£˜\éÐ<¦•‚ˆp3å[cØÒ’zèK%¡N™vÁžÚ”Ÿ@%ԈꡇþÔ¨;5gÔ’ Á¦z£eéT©*¸°DUt›áª‰–jÄ6Ô«XÍ䨰R»‰Žæ«'²— ÖÈ5„fÍj ‹z@¶Q“•Õ\æßà÷Oè´Õ­øa¡ñ®iÌ^Ê“’ÙÔêÀìúFiæU¯ÝK\Ù‡Íz^²‚„]Ñì(‹ÐŽâ/² k?­ÚÙÒöï´‰#«×Vû¿”yÉ6µó¬[9‰—o®Q(ŒmP©Èˆ ÷£µýíhtÛÓWRnñž;¡èþ ‰>dîr#ˆÓéL7‚ duZ{ÝÍè»òáîΰðnW¼vsîzÁÛ^¼&—ééÙx+¥Ù×<ü«rTÛ^ÿŽ÷l¶=î€ LÛŒb¯´Nrç«`übÕÁÆî^w™aкþ p Á‚"L¨p!Æ p(q"ÅŠ/b̨‘`Ä?fì’£A‘:Bq%I“&G| s&M…)kâÌ©s§D™<RôùQ¦Ë–'ÆDªR§P N1Þ|*u*U›U¯"lJS+Ö’]¿:Œ v,Y‹Å–Ê5-еl»¢}+·ìÙºnçz¼‹wë^¼QÏö üÓn\Á#õΛx.áÅŽóÚ},y2寄WÎl³æÎž?o¼tç¤O£N½°®êÖ®_ÃÖŒ8vÕÙ´oãÞk;w[Þ¾'ÞÍW.K¯ ‹¯®|ù[áÂ*Eú|©Fä$G‡Î|;÷«Î¯ýwݺõ¤*QžI>ûR”êæO:}z÷úö'~7:>=ë¢ÑSž~íee^€YVÔ|÷1Ø Lù§à€)ù÷òÅTÞ…þx¡‡f9¢ˆÑ!Xw•RŠ#²ÈÜŠ-Z£Œ3²GãP6â(â‹9È£?dn;msv-2009.1/msv/src/com/sun/msv/scanner/0000755000175000017500000000000011622453067020043 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/scanner/dtd/0000755000175000017500000000000011622453067020616 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/scanner/dtd/DTDParser.java0000644000175000017500000022034510233224600023241 0ustar giovannigiovanni/* * @(#)XmlChars.java 1.1 00/08/05 * * Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved. */ package com.sun.msv.scanner.dtd; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.Hashtable; import java.util.Locale; import java.util.Set; import java.util.Vector; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * This implements parsing of XML 1.0 DTDs. * * This conforms to the portion of the XML 1.0 specification related * to the external DTD subset. * * For multi-language applications (such as web servers using XML * processing to create dynamic content), a method supports choosing * a locale for parser diagnostics which is both understood by the * message recipient and supported by the parser. * * This parser produces a stream of parse events. It supports some * features (exposing comments, CDATA sections, and entity references) * which are not required to be reported by conformant XML processors. * * @author David Brownell * @author Janet Koenig * @author Kohsuke KAWAGUCHI * @version $Id: DTDParser.java 1658 2005-04-25 17:31:44Z kohsuke $ */ public class DTDParser { public final static String TYPE_CDATA = "CDATA"; public final static String TYPE_ID = "ID"; public final static String TYPE_IDREF = "IDREF"; public final static String TYPE_IDREFS = "IDREFS"; public final static String TYPE_ENTITY = "ENTITY"; public final static String TYPE_ENTITIES = "ENTITIES"; public final static String TYPE_NMTOKEN = "NMTOKEN"; public final static String TYPE_NMTOKENS = "NMTOKENS"; public final static String TYPE_NOTATION = "NOTATION"; public final static String TYPE_ENUMERATION = "ENUMERATION"; // stack of input entities being merged private InputEntity in; // temporaries reused during parsing private StringBuffer strTmp; private char nameTmp []; private NameCache nameCache; private char charTmp [] = new char [2]; // temporary DTD parsing state private boolean doLexicalPE; // DTD state, used during parsing // private SimpleHashtable elements = new SimpleHashtable (47); protected final Set declaredElements = new java.util.HashSet(); private SimpleHashtable params = new SimpleHashtable (7); // exposed to package-private subclass Hashtable notations = new Hashtable (7); SimpleHashtable entities = new SimpleHashtable (17); private SimpleHashtable ids = new SimpleHashtable (); // listeners for DTD parsing events private DTDEventListener dtdHandler; private EntityResolver resolver; private Locale locale; // string constants -- use these copies so "==" works // package private static final String strANY = "ANY"; static final String strEMPTY = "EMPTY"; /** * Used by applications to request locale for diagnostics. * * @param l The locale to use, or null to use system defaults * (which may include only message IDs). */ public void setLocale (Locale l) throws SAXException { if (l != null && !messages.isLocaleSupported (l.toString ())) { throw new SAXException (messages.getMessage (locale, "P-078", new Object [] { l })); } locale = l; } /** * Returns the diagnostic locale. */ public Locale getLocale () { return locale; } /** * Chooses a client locale to use for diagnostics, using the first * language specified in the list that is supported by this parser. * That locale is then set using * setLocale(). Such a list could be provided by a variety of user * preference mechanisms, including the HTTP Accept-Language * header field. * * @see MessageCatalog * * @param languages Array of language specifiers, ordered with the most * preferable one at the front. For example, "en-ca" then "fr-ca", * followed by "zh_CN". Both RFC 1766 and Java styles are supported. * @return The chosen locale, or null. */ public Locale chooseLocale (String languages []) throws SAXException { Locale l = messages.chooseLocale (languages); if (l != null) { setLocale (l); } return l; } /** * Lets applications control entity resolution. */ public void setEntityResolver (EntityResolver r) { resolver = r; } /** * Returns the object used to resolve entities */ public EntityResolver getEntityResolver () { return resolver; } /** * Used by applications to set handling of DTD parsing events. */ public void setDtdHandler (DTDEventListener handler) { dtdHandler = handler; if( handler!=null ) handler.setDocumentLocator( new Locator(){ public String getPublicId() { return DTDParser.this.getPublicId(); } public String getSystemId() { return DTDParser.this.getSystemId(); } public int getLineNumber() { return DTDParser.this.getLineNumber(); } public int getColumnNumber() { return DTDParser.this.getColumnNumber(); } }); } /** * Returns the handler used to for DTD parsing events. */ public DTDEventListener getDtdHandler () { return dtdHandler; } /** * Parse a DTD. */ public void parse (InputSource in) throws IOException, SAXException { init (); parseInternal (in); } /** * Parse a DTD. */ public void parse (String uri) throws IOException, SAXException { InputSource in; init (); // System.out.println ("parse (\"" + uri + "\")"); in = resolver.resolveEntity (null, uri); // If custom resolver punts resolution to parser, handle it ... if (in == null) { in = Resolver.createInputSource (new java.net.URL (uri), false); // ... or if custom resolver doesn't correctly construct the // input entity, patch it up enough so relative URIs work, and // issue a warning to minimize later confusion. } else if (in.getSystemId () == null) { warning ("P-065", null); in.setSystemId (uri); } parseInternal (in); } // makes sure the parser is reset to "before a document" private void init () { in = null; // alloc temporary data used in parsing strTmp = new StringBuffer (); nameTmp = new char [20]; nameCache = new NameCache (); // reset doc info // isInAttribute = false; doLexicalPE = false; entities.clear (); notations.clear (); params.clear (); // elements.clear (); declaredElements.clear(); // initialize predefined references ... re-interpreted later builtin ("amp", "&"); builtin ("lt", "<"); builtin ("gt", ">"); builtin ("quot", "\""); builtin ("apos", "'"); if (locale == null) locale = Locale.getDefault (); if (resolver == null) resolver = new Resolver (); if (dtdHandler == null) dtdHandler = new DTDHandlerBase(); } private void builtin (String entityName, String entityValue) { InternalEntity entity; entity = new InternalEntity (entityName, entityValue.toCharArray ()); entities.put (entityName, entity); } //////////////////////////////////////////////////////////////// // // parsing is by recursive descent, code roughly // following the BNF rules except tweaked for simple // lookahead. rules are more or less in numeric order, // except where code sharing suggests other structures. // // a classic benefit of recursive descent parsers: it's // relatively easy to get diagnostics that make sense. // //////////////////////////////////////////////////////////////// private void parseInternal (InputSource input) throws IOException, SAXException { if (input == null) fatal("P-000"); try { in = InputEntity.getInputEntity(dtdHandler, locale); in.init(input, null, null, false); dtdHandler.startDTD(in); // [30] extSubset ::= TextDecl? extSubsetDecl // [31] extSubsetDecl ::= ( markupdecl | conditionalSect // | PEReference | S )* // ... same as [79] extPE, which is where the code is ExternalEntity externalSubset = new ExternalEntity(in); externalParameterEntity(externalSubset); if (!in.isEOF ()) { fatal ("P-001", new Object [] { Integer.toHexString (((int)getc ())) } ); } afterRoot(); dtdHandler.endDTD (); } catch (EndOfInputException e) { if (!in.isDocument ()) { String name = in.getName (); do { // force a relevant URI and line number in = in.pop (); } while (in.isInternal ()); fatal ("P-002", new Object [] { name }); } else { fatal ("P-003", null); } } catch (RuntimeException e) { // Don't discard location that triggered the exception // ## Should properly wrap exception System.err.print("Internal DTD parser error: "); // ## e.printStackTrace(); throw new SAXParseException ( e.getMessage () != null ? e.getMessage () : e.getClass ().getName (), getPublicId (), getSystemId (), getLineNumber (), getColumnNumber ()); } finally { // recycle temporary data used during parsing strTmp = null; nameTmp = null; nameCache = null; // ditto input sources etc if (in != null) { in.close (); in = null; } // get rid of all DTD info ... some of it would be // useful for editors etc, investigate later. params.clear(); entities.clear(); notations.clear(); declaredElements.clear(); // elements.clear(); ids.clear(); } } void afterRoot () throws SAXException { // Make sure all IDREFs match declared ID attributes. We scan // after the document element is parsed, since XML allows forward // references, and only now can we know if they're all resolved. for (Enumeration e = ids.keys (); e.hasMoreElements (); ) { String id = (String)e.nextElement (); Boolean value = (Boolean)ids.get(id); if (Boolean.FALSE == value) error ("V-024", new Object [] { id }); } } // role is for diagnostics private void whitespace (String roleId) throws IOException, SAXException { // [3] S ::= (#x20 | #x9 | #xd | #xa)+ if (!maybeWhitespace ()) { fatal ("P-004", new Object [] { messages.getMessage (locale, roleId) }); } } // S? private boolean maybeWhitespace () throws IOException, SAXException { if (!doLexicalPE) return in.maybeWhitespace (); // see getc() for the PE logic -- this lets us splice // expansions of PEs in "anywhere". getc() has smarts, // so for external PEs we don't bypass it. // XXX we can marginally speed PE handling, and certainly // be cleaner (hence potentially more correct), by using // the observations that expanded PEs only start and stop // where whitespace is allowed. getc wouldn't need any // "lexical" PE expansion logic, and no other method needs // to handle termination of PEs. (parsing of literals would // still need to pop entities, but not parsing of references // in content.) char c = getc(); boolean saw = false; while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { saw = true; // this gracefully ends things when we stop playing // with internal parameters. caller should have a // grammar rule allowing whitespace at end of entity. if (in.isEOF () && !in.isInternal ()) return saw; c = getc (); } ungetc (); return saw; } private String maybeGetName () throws IOException, SAXException { NameCacheEntry entry = maybeGetNameCacheEntry (); return (entry == null) ? null : entry.name; } private NameCacheEntry maybeGetNameCacheEntry () throws IOException, SAXException { // [5] Name ::= (Letter|'_'|':') (Namechar)* char c = getc (); if (!XmlChars.isLetter (c) && c != ':' && c != '_') { ungetc (); return null; } return nameCharString (c); } // Used when parsing enumerations private String getNmtoken () throws IOException, SAXException { // [7] Nmtoken ::= (Namechar)+ char c = getc (); if (!XmlChars.isNameChar (c)) fatal ("P-006", new Object [] { new Character (c) }); return nameCharString (c).name; } // n.b. this gets used when parsing attribute values (for // internal references) so we can't use strTmp; it's also // a hotspot for CPU and memory in the parser (called at least // once for each element) so this has been optimized a bit. private NameCacheEntry nameCharString (char c) throws IOException, SAXException { int i = 1; nameTmp [0] = c; for (;;) { if ((c = in.getNameChar ()) == 0) break; if (i >= nameTmp.length) { char tmp [] = new char [nameTmp.length + 10]; System.arraycopy (nameTmp, 0, tmp, 0, nameTmp.length); nameTmp = tmp; } nameTmp [i++] = c; } return nameCache.lookupEntry (nameTmp, i); } // // much similarity between parsing entity values in DTD // and attribute values (in DTD or content) ... both follow // literal parsing rules, newline canonicalization, etc // // leaves value in 'strTmp' ... either a "replacement text" (4.5), // or else partially normalized attribute value (the first bit // of 3.3.3's spec, without the "if not CDATA" bits). // private void parseLiteral (boolean isEntityValue) throws IOException, SAXException { // [9] EntityValue ::= // '"' ([^"&%] | Reference | PEReference)* '"' // | "'" ([^'&%] | Reference | PEReference)* "'" // [10] AttValue ::= // '"' ([^"&] | Reference )* '"' // | "'" ([^'&] | Reference )* "'" char quote = getc (); char c; InputEntity source = in; if (quote != '\'' && quote != '"') { fatal ("P-007"); } // don't report entity expansions within attributes, // they're reported "fully expanded" via SAX // isInAttribute = !isEntityValue; // get value into strTmp strTmp = new StringBuffer (); // scan, allowing entity push/pop wherever ... // expanded entities can't terminate the literal! for (;;) { if (in != source && in.isEOF ()) { // we don't report end of parsed entities // within attributes (no SAX hooks) in = in.pop (); continue; } if ((c = getc ()) == quote && in == source) { break; } // // Basically the "reference in attribute value" // row of the chart in section 4.4 of the spec // if (c == '&') { String entityName = maybeGetName (); if (entityName != null) { nextChar (';', "F-020", entityName); // 4.4 says: bypass these here ... we'll catch // forbidden refs to unparsed entities on use if (isEntityValue) { strTmp.append ('&'); strTmp.append (entityName); strTmp.append (';'); continue; } expandEntityInLiteral (entityName, entities, isEntityValue); // character references are always included immediately } else if ((c = getc ()) == '#') { int tmp = parseCharNumber (); if (tmp > 0xffff) { tmp = surrogatesToCharTmp (tmp); strTmp.append (charTmp [0]); if (tmp == 2) strTmp.append (charTmp [1]); } else strTmp.append ((char) tmp); } else fatal ("P-009"); continue; } // expand parameter entities only within entity value literals if (c == '%' && isEntityValue) { String entityName = maybeGetName (); if (entityName != null) { nextChar (';', "F-021", entityName); expandEntityInLiteral (entityName, params, isEntityValue); continue; } else fatal ("P-011"); } // For attribute values ... if (!isEntityValue) { // 3.3.3 says whitespace normalizes to space... if (c == ' ' || c == '\t' || c == '\n' || c == '\r') { strTmp.append (' '); continue; } // "<" not legal in parsed literals ... if (c == '<') fatal ("P-012"); } strTmp.append (c); } // isInAttribute = false; } // does a SINGLE expansion of the entity (often reparsed later) private void expandEntityInLiteral( String name, SimpleHashtable table, boolean isEntityValue) throws IOException, SAXException { Object entity = table.get (name); if (entity instanceof InternalEntity) { InternalEntity value = (InternalEntity) entity; pushReader (value.buf, name, !value.isPE); } else if (entity instanceof ExternalEntity) { if (!isEntityValue) // must be a PE ... fatal ("P-013", new Object [] { name }); // XXX if this returns false ... pushReader ((ExternalEntity) entity); } else if (entity == null) { // // Note: much confusion about whether spec requires such // errors to be fatal in many cases, but none about whether // it allows "normal" errors to be unrecoverable! // fatal ( (table == params) ? "V-022" : "P-014", new Object [] { name }); } } // [11] SystemLiteral ::= ('"' [^"]* '"') | ("'" [^']* "'") // for PUBLIC and SYSTEM literals, also "' // NOTE: XML spec should explicitly say that PE ref syntax is // ignored in PIs, comments, SystemLiterals, and Pubid Literal // values ... can't process the XML spec's own DTD without doing // that for comments. private String getQuotedString (String type, String extra) throws IOException, SAXException { // use in.getc to bypass PE processing char quote = in.getc (); if (quote != '\'' && quote != '"') fatal ("P-015", new Object [] { messages.getMessage (locale, type, new Object [] { extra }) }); char c; strTmp = new StringBuffer (); while ((c = in.getc ()) != quote) strTmp.append ((char)c); return strTmp.toString (); } private String parsePublicId () throws IOException, SAXException { // [12] PubidLiteral ::= ('"' PubidChar* '"') | ("'" PubidChar* "'") // [13] PubidChar ::= #x20|#xd|#xa|[a-zA-Z0-9]|[-'()+,./:=?;!*#@$_%] String retval = getQuotedString ("F-033", null); for (int i = 0; i < retval.length (); i++) { char c = retval.charAt (i); if (" \r\n-'()+,./:=?;!*#@$_%0123456789".indexOf(c) == -1 && !(c >= 'A' && c <= 'Z') && !(c >= 'a' && c <= 'z')) fatal ("P-016", new Object [] { new Character (c) }); } strTmp = new StringBuffer (); strTmp.append (retval); return normalize (false); } // [14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*) // handled by: InputEntity.parsedContent() private boolean maybeComment (boolean skipStart) throws IOException, SAXException { // [15] Comment ::= '' if (!in.peek (skipStart ? "!--" : " CP423 // EBCDIC-CP-TR --> CP905 } // returns an encoding name supported by JDK >= 1.1.6 // for some cases required by the XML spec private static String std2java (String encoding) { String temp = encoding.toUpperCase (); temp = (String) charsets.get (temp); return temp != null ? temp : encoding; } /** Returns the standard name of the encoding in use */ public String getEncoding () { return assignedEncoding; } private XmlReader (InputStream stream) throws IOException { super (stream); PushbackInputStream pb; byte buf []; int len; if (stream instanceof PushbackInputStream) pb = (PushbackInputStream) stream; else pb = new PushbackInputStream (stream, MAXPUSHBACK); // // See if we can figure out the character encoding used // in this file by peeking at the first few bytes. // buf = new byte [4]; len = pb.read (buf); if (len > 0) pb.unread (buf, 0, len); if (len == 4) switch (buf [0] & 0x0ff) { case 0: // 00 3c 00 3f == illegal UTF-16 big-endian if (buf [1] == 0x3c && buf [2] == 0x00 && buf [3] == 0x3f) { setEncoding (pb, "UnicodeBig"); return; } // else it's probably UCS-4 break; case '<': // 0x3c: the most common cases! switch (buf [1] & 0x0ff) { // First character is '<'; could be XML without // an XML directive such as "", " LF mapping // Internal ones got it already, and we can't repeat // else we break char ref handling!! if (c == '\r') { if (isInternal ()) continue; docHandler.characters (buf, first, last - first); docHandler.characters (newline, 0, 1); sawContent = true; lineNumber++; if (finish > (last + 1)) { if (buf [last + 1] == '\n') last++; } else { // CR at end of buffer // XXX case not yet handled: CRLF here will look like two lines } first = start = last + 1; continue; } // ']]>' is a WF error -- must fail if we see it if (c == ']') { switch (finish - last) { // for suspicious end-of-buffer cases, get more data // into the buffer to rule out this sequence. case 2: if (buf [last + 1] != ']') continue; // FALLTHROUGH case 1: if (reader == null || isClosed) continue; if (last == first) throw new InternalError ("fillbuf"); last--; if (last > first) { // validator.text (); docHandler.characters (buf, first, last - first); sawContent = true; start = last; } fillbuf (); first = last = start; continue; // otherwise any "]]>" would be buffered, and we can // see right away if that's what we have default: if (buf [last + 1] == ']' && buf [last + 2] == '>') fatal ("P-072", null); continue; } } // correctly paired surrogates are OK if (c >= 0xd800 && c <= 0xdfff) { if ((last + 1) >= finish) { if (last > first) { // validator.text (); docHandler.characters (buf, first, last - first); sawContent = true; start = last + 1; } if (isEOF ()) { // calls fillbuf fatal ("P-081", new Object [] { Integer.toHexString (c) }); } first = start; last = first ; continue; } if (checkSurrogatePair (last)) last++; else { last--; // also terminate on surrogate pair oddities break; } continue; } fatal ("P-071", new Object [] { Integer.toHexString (c) }); } if (last == first) return sawContent; // validator.text (); docHandler.characters (buf, first, last - first); start = last; return true; } /** * CDATA -- character data, terminated by "]]>" and optionally * including unescaped markup delimiters (ampersand and left angle * bracket). This should otherwise be exactly like character data, * modulo differences in error report details. * *

    The document handler's characters() or ignorableWhitespace() * methods are invoked on all the character data found * * @param docHandler gets callbacks for character data * @param ignorableWhitespace if true, whitespace characters will * be reported using docHandler.ignorableWhitespace(); implicitly, * non-whitespace characters will cause validation errors * @param whitespaceInvalidMessage if true, ignorable whitespace * causes a validity error report as well as a callback */ public boolean unparsedContent(DTDEventListener docHandler, /*ElementValidator validator,*/ boolean ignorableWhitespace, String whitespaceInvalidMessage) throws IOException, SAXException { // [18] CDSect ::= CDStart CData CDEnd // [19] CDStart ::= '' Char*)) // [21] CDEnd ::= ']]>' // caller peeked the leading '<' ... if (!peek ("![CDATA[", null)) return false; docHandler.startCDATA(); // only a literal ']]>' stops this ... int last; for (;;) { // until ']]>' seen boolean done = false; char c; // don't report ignorable whitespace as "text" for // validation purposes. boolean white = ignorableWhitespace; for (last = start; last < finish; last++) { c = buf [last]; // // Reject illegal characters. // if (!XmlChars.isChar (c)) { white = false; if (c >= 0xd800 && c <= 0xdfff) { if (checkSurrogatePair (last)) { last++; continue; } else { last--; break; } } fatal ("P-071", new Object [] { Integer.toHexString (buf [last]) }); } if (c == '\n') { if (!isInternal ()) lineNumber++; continue; } if (c == '\r') { // As above, we can't repeat CR/CRLF --> LF mapping if (isInternal ()) continue; if (white) { if (whitespaceInvalidMessage != null) errHandler.error (new SAXParseException( DTDParser.messages.getMessage (locale, whitespaceInvalidMessage),null) ); docHandler.ignorableWhitespace (buf, start, last - start); docHandler.ignorableWhitespace (newline, 0, 1); } else { // validator.text (); docHandler.characters (buf, start, last - start); docHandler.characters (newline, 0, 1); } lineNumber++; if (finish > (last + 1)) { if (buf [last + 1] == '\n') last++; } else { // CR at end of buffer // XXX case not yet handled ... as above } start = last + 1; continue; } if (c != ']') { if (c != ' ' && c != '\t') white = false; continue; } if ((last + 2) < finish) { if (buf [last + 1] == ']' && buf [last + 2] == '>') { done = true; break; } white = false; continue; } else { //last--; break; } } if (white) { if (whitespaceInvalidMessage != null) errHandler.error (new SAXParseException ( DTDParser.messages.getMessage (locale, whitespaceInvalidMessage),null)); docHandler.ignorableWhitespace (buf, start, last - start); } else { // validator.text (); docHandler.characters (buf, start, last - start); } if (done) { start = last + 3; break; } start = last; if (isEOF ()) fatal ("P-073", null); } docHandler.endCDATA (); return true; } // return false to backstep at end of buffer) private boolean checkSurrogatePair (int offset) throws SAXException { if ((offset + 1) >= finish) return false; char c1 = buf [offset++]; char c2 = buf [offset]; if ((c1 >= 0xd800 && c1 < 0xdc00) && (c2 >= 0xdc00 && c2 <= 0xdfff)) return true; fatal ("P-074", new Object [] { Integer.toHexString (c1 & 0x0ffff), Integer.toHexString (c2 & 0x0ffff) }); return false; } /** * whitespace in markup (flagged to app, discardable) * *

    the document handler's ignorableWhitespace() method * is called on all the whitespace found */ public boolean ignorableWhitespace (DTDEventListener handler) throws IOException, SAXException { char c; boolean isSpace = false; int first; // [3] S ::= #20 | #09 | #0D | #0A for (first = start;;) { if (finish <= start) { if (isSpace) handler.ignorableWhitespace (buf, first, start - first); fillbuf (); first = start; } if (finish <= start) return isSpace; c = buf [start++]; switch (c) { case '\n': if (!isInternal ()) lineNumber++; // XXX handles Macintosh line endings wrong // fallthrough case 0x09: case 0x20: isSpace = true; continue; case '\r': isSpace = true; if (!isInternal ()) lineNumber++; handler.ignorableWhitespace (buf, first, (start - 1) - first); handler.ignorableWhitespace (newline, 0, 1); if (start < finish && buf [start] == '\n') ++start; first = start; continue; default: ungetc (); if (isSpace) handler.ignorableWhitespace (buf, first, start - first); return isSpace; } } } /** * returns false iff 'next' string isn't as provided, * else skips that text and returns true. * *

    NOTE: two alternative string representations are * both passed in, since one is faster. */ public boolean peek (String next, char chars []) throws IOException, SAXException { int len; int i; if (chars != null) len = chars.length; else len = next.length (); // buffer should hold the whole thing ... give it a // chance for the end-of-buffer case and cope with EOF // by letting fillbuf compact and fill if (finish <= start || (finish - start) < len) fillbuf (); // can't peek past EOF if (finish <= start) return false; // compare the string; consume iff it matches if (chars != null) { for (i = 0; i < len && (start + i) < finish; i++) { if (buf [start + i] != chars [i]) return false; } } else { for (i = 0; i < len && (start + i) < finish; i++) { if (buf [start + i] != next.charAt (i)) return false; } } // if the first fillbuf didn't get enough data, give // fillbuf another chance to read if (i < len) { if (reader == null || isClosed) return false; // // This diagnostic "knows" that the only way big strings would // fail to be peeked is where it's a symbol ... e.g. for an // construct. That knowledge could also be applied // to get rid of the symbol length constraint, since having // the wrong symbol is a fatal error anyway ... // if (len > buf.length) fatal ("P-077", new Object [] { new Integer (buf.length) }); fillbuf (); return peek (next, chars); } start += len; return true; } // // Support for reporting the internal DTD subset, so // declarations can be recreated. This is collected as a single // string; such subsets are normally small, and many applications // don't even care about this. // public void startRemembering () { if (startRemember != 0) throw new InternalError (); startRemember = start; } public String rememberText () { String retval; // If the internal subset crossed a buffer boundary, we // created a temporary buffer. if (rememberedText != null) { rememberedText.append (buf, startRemember, start - startRemember); retval = rememberedText.toString (); } else retval = new String (buf, startRemember, start - startRemember); startRemember = 0; rememberedText = null; return retval; } private InputEntity getTopEntity() { InputEntity current = this; // don't report locations within internal entities! while (current != null && current.input == null) current = current.next; return current == null ? this : current; } /** Returns the public ID of this input source, if known */ public String getPublicId() { InputEntity where = getTopEntity(); if (where == this) return input.getPublicId(); return where.getPublicId(); } /** Returns the system ID of this input source, if known */ public String getSystemId() { InputEntity where = getTopEntity(); if (where == this) return input.getSystemId(); return where.getSystemId(); } /** Returns the current line number in this input source */ public int getLineNumber () { InputEntity where = getTopEntity(); if (where == this) return lineNumber; return where.getLineNumber(); } /** returns -1; maintaining column numbers hurts performance */ public int getColumnNumber () { return -1; // not maintained (speed) } // // n.b. for non-EOF end-of-buffer cases, reader should return // at least a handful of bytes so various lookaheads behave. // // two character pushback exists except at first; characters // represented by surrogate pairs can't be pushed back (they'd // only be in character data anyway). // // DTD exception thrown on char conversion problems; line number // will be low, as a rule. // private void fillbuf () throws IOException, SAXException { // don't touched fixed buffers, that'll usually // change entity values (and isn't needed anyway) // likewise, ignore closed streams if (reader == null || isClosed) return; // if remembering DTD text, copy! if (startRemember != 0) { if (rememberedText == null) rememberedText = new StringBuffer (buf.length); rememberedText.append (buf, startRemember, start - startRemember); } boolean extra = (finish > 0) && (start > 0); int len; if (extra) // extra pushback start--; len = finish - start; System.arraycopy (buf, start, buf, 0, len); start = 0; finish = len; try { len = buf.length - len; len = reader.read (buf, finish, len); } catch (UnsupportedEncodingException e) { fatal ("P-075", new Object [] { e.getMessage () }); } catch (CharConversionException e) { fatal ("P-076", new Object [] { e.getMessage () }); } if (len >= 0) finish += len; else close (); if (extra) // extra pushback start++; if (startRemember != 0) // assert extra == true startRemember = 1; } public void close () { try { if (reader != null && !isClosed) reader.close (); isClosed = true; } catch (IOException e) { /* NOTHING */ } } private void fatal (String messageId, Object params []) throws SAXException { SAXParseException x = new SAXParseException ( DTDParser.messages.getMessage (locale, messageId, params),null); // not continuable ... e.g. WF errors close (); errHandler.fatalError (x); throw x; } } msv-2009.1/msv/src/com/sun/msv/scanner/dtd/InternalEntity.java0000644000175000017500000000042610233224600024416 0ustar giovannigiovanni/* * Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved. */ package com.sun.msv.scanner.dtd; class InternalEntity extends EntityDecl { InternalEntity (String name, char value []) { this.name = name; this.buf = value; } char buf []; } msv-2009.1/msv/src/com/sun/msv/scanner/dtd/XmlChars.java0000644000175000017500000002750110233224600023171 0ustar giovannigiovanni/* * @(#)XmlChars.java 1.1 00/08/05 * * Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved. */ package com.sun.msv.scanner.dtd; /** * Methods in this class are used to determine whether characters may * appear in certain roles in XML documents. Such methods are used * both to parse and to create such documents. * * @version 1.1, 00/08/05 * @author David Brownell */ public class XmlChars { // can't construct instances private XmlChars () { } /** * Returns true if the argument, a UCS-4 character code, is valid in * XML documents. Unicode characters fit into the low sixteen * bits of a UCS-4 character, and pairs of Unicode surrogate * characters can be combined to encode UCS-4 characters in * documents containing only Unicode. (The char datatype * in the Java Programming Language represents Unicode characters, * including unpaired surrogates.) * *

    In XML, UCS-4 characters can also be encoded by the use of * character references such as &#x12345678;, which * happens to refer to a character that is disallowed in XML documents. * UCS-4 characters allowed in XML documents can be expressed with * one or two Unicode characters. * * @param ucs4char The 32-bit UCS-4 character being tested. */ static public boolean isChar (int ucs4char) { // [2] Char ::= #x0009 | #x000A | #x000D // | [#x0020-#xD7FF] // ... surrogates excluded! // | [#xE000-#xFFFD] // | [#x10000-#x10ffff] return ((ucs4char >= 0x0020 && ucs4char <= 0xD7FF) || ucs4char == 0x000A || ucs4char == 0x0009 || ucs4char == 0x000D || (ucs4char >= 0xE000 && ucs4char <= 0xFFFD) || (ucs4char >= 0x10000 && ucs4char <= 0x10ffff)); } /** * Returns true if the character is allowed to be a non-initial * character in names according to the XML recommendation. * @see #isNCNameChar(char) * @see #isLetter(char) */ public static boolean isNameChar (char c) { // [4] NameChar ::= Letter | Digit | '.' | '_' | ':' // | CombiningChar | Extender if (isLetter2 (c)) return true; else if (c == '>') return false; else if (c == '.' || c == '-' || c == '_' || c == ':' || isExtender (c)) return true; else return false; } /** * Returns true if the character is allowed to be a non-initial * character in unscoped names according to the rules of the XML * Namespaces proposed recommendation. Except for precluding * the colon (used to separate names from their scopes) these * characters are just as allowed by the XML recommendation. * @see #isNameChar(char) * @see #isLetter(char) */ public static boolean isNCNameChar (char c) { // [NC 5] NCNameChar ::= Letter | Digit | '.' | '_' // | CombiningChar | Extender return c != ':' && isNameChar (c); } /** * Returns true if the character is allowed where XML supports * whitespace characters, false otherwise. */ public static boolean isSpace (char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r'; } /* * NOTE: java.lang.Character.getType() values are: * * UNASSIGNED = 0, * * UPPERCASE_LETTER = 1, // Lu * LOWERCASE_LETTER = 2, // Ll * TITLECASE_LETTER = 3, // Lt * MODIFIER_LETTER = 4, // Lm * OTHER_LETTER = 5, // Lo * NON_SPACING_MARK = 6, // Mn * ENCLOSING_MARK = 7, // Me * COMBINING_SPACING_MARK = 8, // Mc * DECIMAL_DIGIT_NUMBER = 9, // Nd * LETTER_NUMBER = 10, // Nl * OTHER_NUMBER = 11, // No * SPACE_SEPARATOR = 12, // Zs * LINE_SEPARATOR = 13, // Zl * PARAGRAPH_SEPARATOR = 14, // Zp * CONTROL = 15, // Cc * FORMAT = 16, // Cf * // 17 reserved for proposed Ci category * PRIVATE_USE = 18, // Co * SURROGATE = 19, // Cs * DASH_PUNCTUATION = 20, // Pd * START_PUNCTUATION = 21, // Ps * END_PUNCTUATION = 22, // Pe * CONNECTOR_PUNCTUATION = 23, // Pc * OTHER_PUNCTUATION = 24, // Po * MATH_SYMBOL = 25, // Sm * CURRENCY_SYMBOL = 26, // Sc * MODIFIER_SYMBOL = 27, // Sk * OTHER_SYMBOL = 28; // So */ /** * Returns true if the character is an XML "letter". XML Names must * start with Letters or a few other characters, but other characters * in names must only satisfy the isNameChar predicate. * * @see #isNameChar(char) * @see #isNCNameChar(char) */ public static boolean isLetter (char c) { // [84] Letter ::= BaseChar | Ideographic // [85] BaseChar ::= ... too much to repeat // [86] Ideographic ::= ... too much to repeat // // Optimize the typical case. // if (c >= 'a' && c <= 'z') return true; if (c == '/') return false; if (c >= 'A' && c <= 'Z') return true; // // Since the tables are too ridiculous to use in code, // we're using the footnotes here to drive this test. // switch (Character.getType (c)) { // app. B footnote says these are 'name start' // chars' ... case Character.LOWERCASE_LETTER: // Ll case Character.UPPERCASE_LETTER: // Lu case Character.OTHER_LETTER: // Lo case Character.TITLECASE_LETTER: // Lt case Character.LETTER_NUMBER: // Nl // OK, here we just have some exceptions to check... return !isCompatibilityChar (c) // per "5.14 of Unicode", rule out some combiners && !(c >= 0x20dd && c <= 0x20e0); default: // check for some exceptions: these are "alphabetic" return ((c >= 0x02bb && c <= 0x02c1) || c == 0x0559 || c == 0x06e5 || c == 0x06e6); } } // // XML 1.0 discourages "compatibility" characters in names; these // were defined to permit passing through some information stored in // older non-Unicode character sets. These always have alternative // representations in Unicode, e.g. using combining chars. // private static boolean isCompatibilityChar (char c) { // the numerous comparisions here seem unavoidable, // but the switch can reduce the number which must // actually be executed. switch ((c >> 8) & 0x0ff) { case 0x00: // ISO Latin/1 has a few compatibility characters return c == 0x00aa || c == 0x00b5 || c == 0x00ba; case 0x01: // as do Latin Extended A and (parts of) B return (c >= 0x0132 && c <= 0x0133) || (c >= 0x013f && c <= 0x0140) || c == 0x0149 || c == 0x017f || (c >= 0x01c4 && c <= 0x01cc) || (c >= 0x01f1 && c <= 0x01f3) ; case 0x02: // some spacing modifiers return (c >= 0x02b0 && c <= 0x02b8) || (c >= 0x02e0 && c <= 0x02e4); case 0x03: return c == 0x037a; // Greek case 0x05: return c == 0x0587; // Armenian case 0x0e: return c >= 0x0edc && c <= 0x0edd; // Laotian case 0x11: // big chunks of Hangul Jamo are all "compatibility" return c == 0x1101 || c == 0x1104 || c == 0x1108 || c == 0x110a || c == 0x110d || (c >= 0x1113 && c <= 0x113b) || c == 0x113d || c == 0x113f || (c >= 0x1141 && c <= 0x114b) || c == 0x114d || c == 0x114f || (c >= 0x1151 && c <= 0x1153) || (c >= 0x1156 && c <= 0x1158) || c == 0x1162 || c == 0x1164 || c == 0x1166 || c == 0x1168 || (c >= 0x116a && c <= 0x116c) || (c >= 0x116f && c <= 0x1171) || c == 0x1174 || (c >= 0x1176 && c <= 0x119d) || (c >= 0x119f && c <= 0x11a2) || (c >= 0x11a9 && c <= 0x11aa) || (c >= 0x11ac && c <= 0x11ad) || (c >= 0x11b0 && c <= 0x11b6) || c == 0x11b9 || c == 0x11bb || (c >= 0x11c3 && c <= 0x11ea) || (c >= 0x11ec && c <= 0x11ef) || (c >= 0x11f1 && c <= 0x11f8) ; case 0x20: return c == 0x207f; // superscript case 0x21: return // various letterlike symbols c == 0x2102 || c == 0x2107 || (c >= 0x210a && c <= 0x2113) || c == 0x2115 || (c >= 0x2118 && c <= 0x211d) || c == 0x2124 || c == 0x2128 || (c >= 0x212c && c <= 0x212d) || (c >= 0x212f && c <= 0x2138) // most Roman numerals (less 1K, 5K, 10K) || (c >= 0x2160 && c <= 0x217f) ; case 0x30: // some Hiragana return c >= 0x309b && c <= 0x309c; case 0x31: // all Hangul Compatibility Jamo return c >= 0x3131 && c <= 0x318e; case 0xf9: case 0xfa: case 0xfb: case 0xfc: case 0xfd: case 0xfe: case 0xff: // the whole "compatibility" area is for that purpose! return true; default: // most of Unicode isn't flagged as being for compatibility return false; } } // guts of isNameChar/isNCNameChar private static boolean isLetter2 (char c) { // [84] Letter ::= BaseChar | Ideographic // [85] BaseChar ::= ... too much to repeat // [86] Ideographic ::= ... too much to repeat // [87] CombiningChar ::= ... too much to repeat // // Optimize the typical case. // if (c >= 'a' && c <= 'z') return true; if (c == '>') return false; if (c >= 'A' && c <= 'Z') return true; // // Since the tables are too ridiculous to use in code, // we're using the footnotes here to drive this test. // switch (Character.getType (c)) { // app. B footnote says these are 'name start' // chars' ... case Character.LOWERCASE_LETTER: // Ll case Character.UPPERCASE_LETTER: // Lu case Character.OTHER_LETTER: // Lo case Character.TITLECASE_LETTER: // Lt case Character.LETTER_NUMBER: // Nl // ... and these are name characters 'other // than name start characters' case Character.COMBINING_SPACING_MARK: // Mc case Character.ENCLOSING_MARK: // Me case Character.NON_SPACING_MARK: // Mn case Character.MODIFIER_LETTER: // Lm case Character.DECIMAL_DIGIT_NUMBER: // Nd // OK, here we just have some exceptions to check... return !isCompatibilityChar (c) // per "5.14 of Unicode", rule out some combiners && !(c >= 0x20dd && c <= 0x20e0); default: // added a character ... return c == 0x0387; } } private static boolean isDigit (char c) { // [88] Digit ::= ... // // java.lang.Character.isDigit is correct from the XML point // of view except that it allows "fullwidth" digits. // return Character.isDigit (c) && ! ( (c >= 0xff10) && (c <= 0xff19)); } private static boolean isExtender (char c) { // [89] Extender ::= ... return c == 0x00b7 || c == 0x02d0 || c == 0x02d1 || c == 0x0387 || c == 0x0640 || c == 0x0e46 || c == 0x0ec6 || c == 0x3005 || (c >= 0x3031 && c <= 0x3035) || (c >= 0x309d && c <= 0x309e) || (c >= 0x30fc && c <= 0x30fe) ; } } msv-2009.1/msv/src/com/sun/msv/scanner/dtd/EndOfInputException.java0000644000175000017500000000034310233224600025335 0ustar giovannigiovanni/* * @(#)XmlChars.java 1.1 00/08/05 * * Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved. */ package com.sun.msv.scanner.dtd; import java.io.IOException; class EndOfInputException extends IOException {} msv-2009.1/msv/src/com/sun/msv/scanner/dtd/XmlNames.java0000644000175000017500000000742310233224600023175 0ustar giovannigiovanni/* * Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved. */ package com.sun.msv.scanner.dtd; /** * This class contains static methods used to determine whether identifiers * may appear in certain roles in XML documents. Such methods are used * both to parse and to create such documents. * * @version 1.1, 00/08/05 * @author David Brownell */ public class XmlNames { private XmlNames () { } /** * Returns true if the value is a legal XML name. * * @param value the string being tested */ public static boolean isName (String value) { if (value == null) return false; char c = value.charAt (0); if (!XmlChars.isLetter (c) && c != '_' && c != ':') return false; for (int i = 1; i < value.length (); i++) if (!XmlChars.isNameChar (value.charAt (i))) return false; return true; } /** * Returns true if the value is a legal "unqualified" XML name, as * defined in the XML Namespaces proposed recommendation. * These are normal XML names, except that they may not contain * a "colon" character. * * @param value the string being tested */ public static boolean isUnqualifiedName (String value) { if (value == null || value.length() == 0) return false; char c = value.charAt (0); if (!XmlChars.isLetter (c) && c != '_') return false; for (int i = 1; i < value.length (); i++) if (!XmlChars.isNCNameChar (value.charAt (i))) return false; return true; } /** * Returns true if the value is a legal "qualified" XML name, as defined * in the XML Namespaces proposed recommendation. Qualified names are * composed of an optional prefix (an unqualified name), followed by a * colon, and a required "local part" (an unqualified name). Prefixes are * declared, and correspond to particular URIs which scope the "local * part" of the name. (This method cannot check whether the prefix of a * name has been declared.) * * @param value the string being tested */ public static boolean isQualifiedName (String value) { if (value == null) return false; // [6] QName ::= (Prefix ':')? LocalPart // [7] Prefix ::= NCName // [8] LocalPart ::= NCName int first = value.indexOf (':'); // no Prefix, only check LocalPart if (first <= 0) return isUnqualifiedName (value); // Prefix exists, check everything int last = value.lastIndexOf (':'); if (last != first) return false; return isUnqualifiedName (value.substring (0, first)) && isUnqualifiedName (value.substring (first + 1)); } /** * This method returns true if the identifier is a "name token" * as defined in the XML specification. Like names, these * may only contain "name characters"; however, they do not need * to have letters as their initial characters. Attribute values * defined to be of type NMTOKEN(S) must satisfy this predicate. * * @param token the string being tested */ public static boolean isNmtoken (String token) { int length = token.length (); for (int i = 0; i < length; i++) if (!XmlChars.isNameChar (token.charAt (i))) return false; return true; } /** * This method returns true if the identifier is a "name token" as * defined by the XML Namespaces proposed recommendation. * These are like XML "name tokens" but they may not contain the * "colon" character. * * @see #isNmtoken * * @param token the string being tested */ public static boolean isNCNmtoken (String token) { return isNmtoken (token) && token.indexOf (':') < 0; } } msv-2009.1/msv/src/com/sun/msv/scanner/dtd/DTDHandlerBase.java0000644000175000017500000000531010233224600024146 0ustar giovannigiovanni/* * @(#)XmlChars.java 1.1 00/08/05 * * Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved. */ package com.sun.msv.scanner.dtd; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * do-nothing implementation of DTDEventHandler. */ public class DTDHandlerBase implements DTDEventListener { public void processingInstruction(String target, String data) throws SAXException { } public void setDocumentLocator( Locator loc ) { } public void fatalError(SAXParseException e) throws SAXException { throw e; } public void error(SAXParseException e) throws SAXException { throw e; } public void warning(SAXParseException err) throws SAXException { } public void notationDecl(String name, String publicId, String systemId) throws SAXException { } public void unparsedEntityDecl(String name, String publicId, String systemId, String notationName) throws SAXException { } public void endDTD() throws SAXException { } public void externalGeneralEntityDecl(String n, String p, String s) throws SAXException { } public void internalGeneralEntityDecl (String n, String v) throws SAXException { } public void externalParameterEntityDecl (String n, String p, String s) throws SAXException { } public void internalParameterEntityDecl (String n, String v) throws SAXException { } public void startDTD (InputEntity in) throws SAXException { } public void comment (String n) throws SAXException { } public void characters (char ch[], int start, int length) throws SAXException { } public void ignorableWhitespace (char ch[], int start, int length) throws SAXException { } public void startCDATA () throws SAXException { } public void endCDATA () throws SAXException { } public void startContentModel( String elementName, short contentModelType ) throws SAXException { } public void endContentModel( String elementName, short contentModelType ) throws SAXException { } public void attributeDecl( String elementName, String attributeName, String attributeType, String[] enumeration, short attributeUse, String defaultValue ) throws SAXException { } public void childElement( String elementName, short occurence ) throws SAXException {} public void mixedElement( String elementName ) throws SAXException {} public void startModelGroup() throws SAXException {} public void endModelGroup( short occurence ) throws SAXException {} public void connector( short connectorType ) throws SAXException {} } msv-2009.1/msv/src/com/sun/msv/scanner/dtd/resources/0000755000175000017500000000000011622453067022630 5ustar giovannigiovannimsv-2009.1/msv/src/com/sun/msv/scanner/dtd/resources/Messages_en.properties0000644000175000017500000002335007270160030027167 0ustar giovannigiovanni# # @(#)Messages_en.properties 1.2 00/08/05 # # Copyright (c) 1998-1999 Sun Microsystems, Inc. All Rights Reserved. # # This software is the confidential and proprietary information of Sun # Microsystems, Inc. ("Confidential Information"). You shall not # disclose such Confidential Information and shall use it only in # accordance with the terms of the license agreement you entered into # with Sun. # # SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE # SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR # PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES # SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING # THIS SOFTWARE OR ITS DERIVATIVES. # # # English diagnostic messages (and fragments) for Sun's XML parser. # # P-NNN ... parser messages # F-NNN ... message fragments (sometimes associated with more # than one message, but usually just with one) # V-NNN ... validation related messages # # Most messages can be produced in only one way. # # # Generic parsing messages, not specific to validation # P-000 = No parser input source! P-001 = Illegal character at end of document, &#x{0}; P-002 = Expansion of entity "&{0};" is not well formed P-003 = Premature end of input P-004 = Missing whitespace {0} P-005 = Only whitespace allowed {0} # # unadorned "missing whitespace", with P-004 only # F-000 = after element name declaration F-001 = between attribute name and type F-002 = after NOTATION type name F-003 = between attribute type and default value F-004 = after #FIXED F-005 = after declaration F-026 = after attribute name F-027 = terminating element F-028 = starting content model for element F-029 = starting list of attribute NOTATIONS F-030 = beginning condition DTD subset F-031 = terminating declaration F-032 = terminating declaration P-009 = Illegal character or entity reference syntax P-010 = Only external parameter entities may use "%{0};" in entity values P-011 = Illegal parameter entity reference syntax P-012 = Use "<" for "<" in attribute values P-013 = Illegal reference to external entity "&{0};" in attribute P-014 = Reference to undefined entity "&{0};" P-015 = Expecting quoted value for {0} F-033 = PUBLIC identifier F-034 = SYSTEM identifier F-035 = attribute value {0} P-016 = Illegal character in PUBLIC identifier: "{0}" P-017 = End of entity while processing comment P-018 = Processing instruction target is missing P-019 = XML declaration may only begin entities P-020 = Illegal processing instruction target: "{0}" P-021 = End of input inside processing instruction P-022 = Illegal processing instruction name, or missing whitespace P-023 = Illegal character "&#x{0};" ({1}) at end of XML Declaration P-024 = Expected "{0}=..." P-025 = XML version "{0}" should be declared P-026 = Illegal XML version string "{0}" P-027 = XML version "{0}" is recognized, but not "{1}" P-028 = Internal DTD subset must not have "" to terminate element starting on line {1} P-035 = End of entity not allowed; an end tag is missing P-036 = ">" must terminate declaration, not "{1}" P-037 = Sequence content model must not contain "{0}" P-038 = Choice content model must not contain "{0}" P-039 = No content model may contain "{0}" P-040 = Need right parenthesis or "{1}" in content model, not "{0}" P-041 = Need right parenthesis, ",", or "|" in content model, not "{0}" P-042 = Illegal mixed content model for "{0}", next char = &#x{1}; P-043 = Mixed content model for "{0}" must end with ")*", not "{1}" P-044 = Either an attribute declaration or ">" is expected, not "{0}" P-045 = Illegal type (starts with "{1}") for attribute "{0}" P-046 = Need keyword in conditional DTD section P-047 = Unterminated conditional DTD section P-048 = Only INCLUDE and IGNORE are allowed, not "{0}" P-049 = Illegal decimal character reference P-050 = Illegal hexadecimal character reference P-051 = Illegal XML character &#x{0}; P-052 = Internal entity "&{0};" has characters after content P-053 = Unparsed entities such as "&{0};" must not be included P-054 = Using original entity definition for "&{0};" P-055 = Relative URI "{0}"; can not be resolved without a document URI P-056 = URI "{0}" has a fragment ID P-057 = Need "?>" to terminate XML declaration P-058 = External entity "&{0};" has characters after content P-059 = External parameter entity "%{0};" has characters after markup P-060 = Illegal character "{0}" in encoding name P-061 = Declared encoding "{0}" does not match actual one "{1}"; \ this might not be an error P-062 = Notation must be PUBLIC or SYSTEM P-063 = Using first definition of notation "{0}" P-064 = Premature end of parameter entity "%{0};" P-065 = Entity Resolver did not provide SYSTEM id; may affect relative URIs # P-066 ... ID available P-067 = Document root element is missing P-068 = Notation name is required P-069 = Expansion of entity "{0}" is recursive P-070 = Malformed second part of surrogate pair: &#x{0}; P-071 = Illegal XML character: &#x{0}; P-072 = Character data cannot have "]]>" P-073 = EOF while parsing declaration V-004 = Undeclared notation "{0}" is used by an declaration V-005 = Element type "{0}" is not declared V-006 = Root element type is "{0}", but was declared to be "{1}" V-007 = Attribute "{0}" is not declared for element "{1}" V-008 = Attribute "{0}" of element "{1}" must only have value "{2}" V-009 = Attribute value for "{0}" is #REQUIRED V-010 = This document is standalone, \ so attribute "{0}" must not be defaulted V-011 = This document is standalone, \ so element "{0}" must not have ignorable whitespace V-012 = Element "{0}" was already declared V-013 = Parameter entities must not contain partial declarations V-014 = Parameter entity nesting error in content model for "{0}" V-015 = Mixed content model repeats element "{0}" V-016 = This element already has an ID attribute, "{0}" V-017 = ID attribute "{0}" must not be #FIXED V-018 = ID attribute "{0}" must not be defaulted V-019 = This document is standalone; this attribute needs to be pre-normalized V-020 = Parameter entities must not contain partial conditional DTD sections V-021 = Parameter entities must not contain partial comments V-022 = Reference to undefined parameter entity "%{0};" V-023 = This document is standalone; this ignorable CDATA whitespace is forbidden V-024 = No element has an ID attribute with value "{0}" V-025 = ID values must be XML names; "{0}" is not a name V-026 = Another element already has an ID attribute with value "{0}" V-027 = IDREF/IDREFS values must be XML names; "{0}" is not a name V-028 = NMTOKEN/NMTOKENS values must be XML name tokens; "{0}" is not one V-029 = Value "{0}" is not one of the enumerated values for this attribute V-030 = Attribute value "{0}" does not name a notation V-031 = Attribute value "{0}" does not name an unparsed entity V-032 = NMTOKENS attributes must have at least one value V-033 = EMPTY content models must have no content V-034 = Element "{0}" does not allow "{1}" -- {2} V-035 = Element "{0}" allows no further input; "{1}" is not allowed V-036 = Element "{0}" does not allow "{1}" here V-037 = Element "{0}" does not allow text V-038 = Element "{0}" requires additional elements V-039 = IDREFS attributes must have at least one value V-040 = ENTITIES attributes must have at least one value msv-2009.1/msv/src/com/sun/msv/scanner/dtd/SimpleHashtable.java0000644000175000017500000001605110233224600024513 0ustar giovannigiovanni/* * Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved. */ package com.sun.msv.scanner.dtd; import java.util.Enumeration; // This could be replaced by Collections class unless we want // to be able to run on JDK 1.1 /** * This class implements a special purpose hashtable. It works like a * normal java.util.Hashtable except that:

      * *
    1. Keys to "get" are strings which are known to be interned, * so that "==" is used instead of "String.equals". (Interning * could be document-relative instead of global.) * *
    2. It's not synchronized, since it's to be used only by * one thread at a time. * *
    3. The keys () enumerator allocates no memory, with live * updates to the data disallowed. * *
    4. It's got fewer bells and whistles: fixed threshold and * load factor, no JDK 1.2 collection support, only keys can be * enumerated, things can't be removed, simpler inheritance; more. * *
    * *

    The overall result is that it's less expensive to use these in * performance-critical locations, in terms both of CPU and memory, * than java.util.Hashtable instances. In this package * it makes a significant difference when normalizing attributes, * which is done for each start-element construct. * * @version $Revision: 1658 $ */ final class SimpleHashtable implements Enumeration { // entries ... private Entry table[]; // currently enumerated key private Entry current = null; private int currentBucket = 0; private int count; private int threshold; private static final float loadFactor = 0.75f; /** * Constructs a new, empty hashtable with the specified initial * capacity. * * @param initialCapacity the initial capacity of the hashtable. */ public SimpleHashtable(int initialCapacity) { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); if (initialCapacity==0) initialCapacity = 1; table = new Entry[initialCapacity]; threshold = (int)(initialCapacity * loadFactor); } /** * Constructs a new, empty hashtable with a default capacity. */ public SimpleHashtable() { this(11); } /** */ public void clear () { count = 0; currentBucket = 0; current = null; for (int i = 0; i < table.length; i++) table [i] = null; } /** * Returns the number of keys in this hashtable. * * @return the number of keys in this hashtable. */ public int size() { return count; } /** * Returns an enumeration of the keys in this hashtable. * * @return an enumeration of the keys in this hashtable. * @see Enumeration */ public Enumeration keys() { currentBucket = 0; current = null; return this; } /** * Used to view this as an enumeration; returns true if there * are more keys to be enumerated. */ public boolean hasMoreElements () { if (current != null) return true; while (currentBucket < table.length) { current = table [currentBucket++]; if (current != null) return true; } return false; } /** * Used to view this as an enumeration; returns the next key * in the enumeration. */ public Object nextElement () { Object retval; if (current == null) throw new IllegalStateException (); retval = current.key; current = current.next; return retval; } /** * Returns the value to which the specified key is mapped in this hashtable. */ public Object get (String key) { Entry tab[] = table; int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry e = tab[index] ; e != null ; e = e.next) { if ((e.hash == hash) && (e.key == key)) return e.value; } return null; } /** * Returns the value to which the specified key is mapped in this * hashtable ... the key isn't necessarily interned, though. */ public Object getNonInterned (String key) { Entry tab[] = table; int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry e = tab[index] ; e != null ; e = e.next) { if ((e.hash == hash) && e.key.equals(key)) return e.value; } return null; } /** * Increases the capacity of and internally reorganizes this * hashtable, in order to accommodate and access its entries more * efficiently. This method is called automatically when the * number of keys in the hashtable exceeds this hashtable's capacity * and load factor. */ private void rehash() { int oldCapacity = table.length; Entry oldMap[] = table; int newCapacity = oldCapacity * 2 + 1; Entry newMap[] = new Entry[newCapacity]; threshold = (int)(newCapacity * loadFactor); table = newMap; /* System.out.println("rehash old=" + oldCapacity + ", new=" + newCapacity + ", thresh=" + threshold + ", count=" + count); */ for (int i = oldCapacity ; i-- > 0 ;) { for (Entry old = oldMap[i] ; old != null ; ) { Entry e = old; old = old.next; int index = (e.hash & 0x7FFFFFFF) % newCapacity; e.next = newMap[index]; newMap[index] = e; } } } /** * Maps the specified key to the specified * value in this hashtable. Neither the key nor the * value can be null. * *

    The value can be retrieved by calling the get method * with a key that is equal to the original key. */ public Object put(Object key, Object value) { // Make sure the value is not null if (value == null) { throw new NullPointerException(); } // Makes sure the key is not already in the hashtable. Entry tab[] = table; int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry e = tab[index] ; e != null ; e = e.next) { // if ((e.hash == hash) && e.key.equals(key)) { if ((e.hash == hash) && (e.key == key)) { Object old = e.value; e.value = value; return old; } } if (count >= threshold) { // Rehash the table if the threshold is exceeded rehash(); tab = table; index = (hash & 0x7FFFFFFF) % tab.length; } // Creates the new entry. Entry e = new Entry(hash, key, value, tab[index]); tab[index] = e; count++; return null; } /** * Hashtable collision list. */ private static class Entry { int hash; Object key; Object value; Entry next; protected Entry(int hash, Object key, Object value, Entry next) { this.hash = hash; this.key = key; this.value = value; this.next = next; } } } msv-2009.1/msv/src/com/sun/msv/scanner/dtd/ExternalEntity.java0000644000175000017500000000164411156747174024454 0ustar giovannigiovanni/* * @(#)XmlChars.java 1.1 00/08/05 * * Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved. */ package com.sun.msv.scanner.dtd; import java.io.IOException; import java.net.URL; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; class ExternalEntity extends EntityDecl { String systemId; // resolved URI (not relative) String publicId; // "-//xyz//....//en" String notation; public ExternalEntity (InputEntity in) { } public InputSource getInputSource (EntityResolver r) throws IOException, SAXException { InputSource retval; retval = r.resolveEntity (publicId, systemId); // SAX sez if null is returned, use the URI directly if (retval == null) retval = Resolver.createInputSource (new URL (systemId), false); return retval; } } msv-2009.1/msv/src/com/sun/msv/overview.html0000644000175000017500000000042307330406303021135 0ustar giovannigiovanni This document is for advanced developers. Everyone should first consult developer.html for a general guideline. msv-2009.1/msv/readme.txt0000644000175000017500000000206407650064511015431 0ustar giovannigiovanni directory structure ------------------- src main MSV source codes relaxng RELAX NG datatype interfaces. Intended to be in the public domain. rngconverter RELAX NG Converter source code. (has dependency on src) trexconverter TREX Converter source code. (has dependency on src) generator XML Generator (has dependency on src) test Test harnesses. (has dependency on everything else) testCases schemas and instances that are used for the batch test. testLog the result of the batch test will be stored under this directory. ref reference to the external libraries. JavaCC is necessary. doc documents that will be attached to the distribution package. grouped by the product. build binary byte codes will go into this directory. ant.xml ant script to build everything. Contains a lot of targets. Read carefully. To run tests ------------ To try individual test $ java batch.verifier.BatchVerifyTester and see the usage. To split ssuites, $ cd msv/testCases $ ant To run the entire test, $ ant test msv-2009.1/shared/0000755000175000017500000000000011622453155014072 5ustar giovannigiovannimsv-2009.1/shared/ant.config0000644000175000017500000000247307714500564016055 0ustar giovannigiovanni # # all directories are relative to the project directory # (e.g., ****/msv/xsdlib or ****/msv/relames, etc.) # # compress jar files? compress = true # # Third party libraries # # JavaCC is available at http://www.webgain.com/products/java_cc/ javaCClib = ../shared/lib # # JUnit and Ant are maintained at Apache Jakarta Project. # (http://jakarta.apache.org/) # junit.jar = ../shared/lib/junit.jar ant.jar = ../shared/lib/ant.jar # # RELAX NG Datatype interface can be obtained from # "RELAX NG SourceForge project" # (http://relaxng.sourceforge.net/) # relaxngDatatype.jar = ../shared/lib/relaxngDatatype.jar rngInterfaceSource = ../../relaxng/datatype/java/src # # ISO RELAX project is at http://iso-relax.sourceforge.net/ # isorelax.jar = ../shared/lib/isorelax.jar # # Xerces and Xalan are from Apache XML Project. # xerces.source = \ C:/Program Files/Development/Xerces/src xerces.jar = ../shared/lib/xercesImpl.jar xalan.jar = ../shared/lib/xalan.jar xmlParserAPIs.jar = ../shared/lib/xmlParserAPIs.jar # # jdom.jar taken from http://www.jdom.org # jdom.jar = ../shared/lib/jdom.jar # # resolver.jar, obtained from http://www.sun.com/software/xml/developers/resolver/ # resolver.jar=../shared/lib/resolver.jar # # SAXON. available at http://users.iclway.co.uk/mhkay/saxon/ # saxon.jar = ../shared/lib/saxon.jar msv-2009.1/shared/ExternalPackageLists/0000755000175000017500000000000011622453070020143 5ustar giovannigiovannimsv-2009.1/shared/ExternalPackageLists/Xalan/0000755000175000017500000000000011622453070021206 5ustar giovannigiovannimsv-2009.1/shared/ExternalPackageLists/Xalan/package-list0000644000175000017500000000260307635404354023510 0ustar giovannigiovannijavax.xml.parsers javax.xml.transform javax.xml.transform.dom javax.xml.transform.sax javax.xml.transform.stream org.apache.xalan org.apache.xalan.client org.apache.xalan.extensions org.apache.xalan.lib org.apache.xalan.lib.sql org.apache.xalan.processor org.apache.xalan.res org.apache.xalan.serialize org.apache.xalan.templates org.apache.xalan.trace org.apache.xalan.transformer org.apache.xalan.xslt org.apache.xalan.xsltc org.apache.xalan.xsltc.cmdline org.apache.xalan.xsltc.cmdline.getopt org.apache.xalan.xsltc.compiler org.apache.xalan.xsltc.compiler.util org.apache.xalan.xsltc.dom org.apache.xalan.xsltc.runtime org.apache.xalan.xsltc.runtime.output org.apache.xalan.xsltc.trax org.apache.xalan.xsltc.util org.apache.xml.dtm org.apache.xml.dtm.ref org.apache.xml.dtm.ref.dom2dtm org.apache.xml.dtm.ref.sax2dtm org.apache.xml.res org.apache.xml.utils org.apache.xml.utils.res org.apache.xml.utils.synthetic org.apache.xml.utils.synthetic.reflection org.apache.xmlcommons org.apache.xpath org.apache.xpath.axes org.apache.xpath.compiler org.apache.xpath.domapi org.apache.xpath.functions org.apache.xpath.objects org.apache.xpath.operations org.apache.xpath.patterns org.apache.xpath.res org.w3c.dom org.w3c.dom.css org.w3c.dom.events org.w3c.dom.html org.w3c.dom.ranges org.w3c.dom.stylesheets org.w3c.dom.traversal org.w3c.dom.views org.w3c.dom.xpath org.xml.sax org.xml.sax.ext org.xml.sax.helpers msv-2009.1/shared/ExternalPackageLists/XML/0000755000175000017500000000000011622453070020603 5ustar giovannigiovannimsv-2009.1/shared/ExternalPackageLists/XML/package-list0000644000175000017500000000100107307537113023070 0ustar giovannigiovanniorg.apache.html.dom org.apache.xerces.dom org.apache.xerces.dom.events org.apache.xerces.domx org.apache.xerces.framework org.apache.xerces.jaxp org.apache.xerces.msg org.apache.xerces.parsers org.apache.xerces.readers org.apache.xerces.utils org.apache.xerces.validators.datatype org.apache.xerces.validators.dtd org.apache.xerces.validators.schema org.apache.xml.serialize org.w3c.dom org.w3c.dom.events org.w3c.dom.html org.w3c.dom.range org.w3c.dom.traversal org.xml.sax org.xml.sax.ext org.xml.sax.helpers msv-2009.1/shared/ExternalPackageLists/ISO-RELAX/0000755000175000017500000000000011622453070021446 5ustar giovannigiovannimsv-2009.1/shared/ExternalPackageLists/ISO-RELAX/package-list0000644000175000017500000000014407307537113023742 0ustar giovannigiovanniorg.iso_relax.catalog org.iso_relax.dispatcher org.iso_relax.dispatcher.impl org.iso_relax.verifier msv-2009.1/shared/ExternalPackageLists/CoreAPI/0000755000175000017500000000000011622453070021365 5ustar giovannigiovannimsv-2009.1/shared/ExternalPackageLists/CoreAPI/package-list0000644000175000017500000000201507307537113023660 0ustar giovannigiovannijava.applet java.awt java.awt.color java.awt.datatransfer java.awt.dnd java.awt.event java.awt.font java.awt.geom java.awt.im java.awt.image java.awt.image.renderable java.awt.print java.beans java.beans.beancontext java.io java.lang java.lang.ref java.lang.reflect java.math java.net java.rmi java.rmi.activation java.rmi.dgc java.rmi.registry java.rmi.server java.security java.security.acl java.security.cert java.security.interfaces java.security.spec java.sql java.text java.util java.util.jar java.util.zip javax.accessibility javax.swing javax.swing.border javax.swing.colorchooser javax.swing.event javax.swing.filechooser javax.swing.plaf javax.swing.plaf.basic javax.swing.plaf.metal javax.swing.plaf.multi javax.swing.table javax.swing.text javax.swing.text.html javax.swing.text.html.parser javax.swing.text.rtf javax.swing.tree javax.swing.undo org.omg.CORBA org.omg.CORBA.DynAnyPackage org.omg.CORBA.ORBPackage org.omg.CORBA.portable org.omg.CORBA.TypeCodePackage org.omg.CosNaming org.omg.CosNaming.NamingContextPackage msv-2009.1/shared/ExternalPackageLists/RELAXNG/0000755000175000017500000000000011622453070021243 5ustar giovannigiovannimsv-2009.1/shared/ExternalPackageLists/RELAXNG/package-list0000644000175000017500000000006207365413411023534 0ustar giovannigiovanniorg.relaxng.datatype org.relaxng.datatype.helpers msv-2009.1/shared/lib/0000755000175000017500000000000011622453161014635 5ustar giovannigiovannimsv-2009.1/shared/readme.txt0000644000175000017500000000055007365414356016101 0ustar giovannigiovanni The "lib" directory contains third party libraries which are 1) used to build MSV and related projects 2) bundled in the release package for the user's convenience The "regexp" directory contains the regular expression library taken from Apache Xerces project. We should occasionally check the update to their repository and copy them into this directory. msv-2009.1/shared/ant.test.xml0000644000175000017500000002132210470166352016354 0ustar giovannigiovanni